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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
idea4bsd/idea4bsd | java/java-tests/testSrc/com/intellij/psi/impl/search/JavaNullMethodArgumentIndexTest.kt | 7 | 3627 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.search
import com.intellij.openapi.fileTypes.StdFileTypes
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import com.intellij.util.indexing.FileContentImpl
import com.intellij.util.indexing.IndexingDataKeys
import org.intellij.lang.annotations.Language
class JavaNullMethodArgumentIndexTest : LightPlatformCodeInsightFixtureTestCase() {
fun testIndex() {
@Language("JAVA")
val file = myFixture.configureByText(StdFileTypes.JAVA, """
package org.some;
class Main111 {
Main111(Object o) {
}
void someMethod(Object o, Object o2, Object o3) {
}
static void staticMethod(Object o, Object o2, Object o3) {
}
public static void main(String[] args) {
staticMethod(null, "", "");
org.some.Main111.staticMethod("", "", null);
new Main111(null).someMethod("", "", null);
Main111 m = new Main111(null);
m.someMethod(null, "", "");
}
static class SubClass {
SubClass(Object o) {
}
}
static class SubClass2 {
SubClass2(Object o) {
}
}
static void main() {
new org.some.Main111(null);
new org.some.Main111.SubClass(null);
new SubClass2(null);
new ParametrizedRunnable(null) {
@Override
void run() {
}};
}
abstract class ParametrizedRunnable {
Object parameter;
ParametrizedRunnable(Object parameter){
this.parameter = parameter;
}
abstract void run();
}
}
""").virtualFile
val content = FileContentImpl.createByFile(file)
content.putUserData(IndexingDataKeys.PROJECT, project)
val data = JavaNullMethodArgumentIndex().indexer.map(content).keys
assertSize(8, data)
assertContainsElements(data,
JavaNullMethodArgumentIndex.MethodCallData("staticMethod", 0),
JavaNullMethodArgumentIndex.MethodCallData("staticMethod", 2),
JavaNullMethodArgumentIndex.MethodCallData("someMethod", 0),
JavaNullMethodArgumentIndex.MethodCallData("someMethod", 2),
JavaNullMethodArgumentIndex.MethodCallData("Main111", 0),
JavaNullMethodArgumentIndex.MethodCallData("SubClass", 0),
JavaNullMethodArgumentIndex.MethodCallData("SubClass2", 0),
JavaNullMethodArgumentIndex.MethodCallData("ParametrizedRunnable", 0))
}
} | apache-2.0 | 1614a47f309053493d9302fc79a45338 | 34.223301 | 97 | 0.570168 | 5.784689 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt | 1 | 4084 | package eu.kanade.tachiyomi.data.preference
import android.content.Context
import eu.kanade.tachiyomi.R
/**
* This class stores the keys for the preferences in the application. Most of them are defined
* in the file "keys.xml". By using this class we can define preferences in one place and get them
* referenced here.
*/
class PreferenceKeys(context: Context) {
val theme = context.getString(R.string.pref_theme_key)
val rotation = context.getString(R.string.pref_rotation_type_key)
val enableTransitions = context.getString(R.string.pref_enable_transitions_key)
val showPageNumber = context.getString(R.string.pref_show_page_number_key)
val fullscreen = context.getString(R.string.pref_fullscreen_key)
val keepScreenOn = context.getString(R.string.pref_keep_screen_on_key)
val customBrightness = context.getString(R.string.pref_custom_brightness_key)
val customBrightnessValue = context.getString(R.string.pref_custom_brightness_value_key)
val colorFilter = context.getString(R.string.pref_color_filter_key)
val colorFilterValue = context.getString(R.string.pref_color_filter_value_key)
val defaultViewer = context.getString(R.string.pref_default_viewer_key)
val imageScaleType = context.getString(R.string.pref_image_scale_type_key)
val imageDecoder = context.getString(R.string.pref_image_decoder_key)
val zoomStart = context.getString(R.string.pref_zoom_start_key)
val readerTheme = context.getString(R.string.pref_reader_theme_key)
val readWithTapping = context.getString(R.string.pref_read_with_tapping_key)
val readWithVolumeKeys = context.getString(R.string.pref_read_with_volume_keys_key)
val reencodeImage = context.getString(R.string.pref_reencode_key)
val portraitColumns = context.getString(R.string.pref_library_columns_portrait_key)
val landscapeColumns = context.getString(R.string.pref_library_columns_landscape_key)
val updateOnlyNonCompleted = context.getString(R.string.pref_update_only_non_completed_key)
val autoUpdateMangaSync = context.getString(R.string.pref_auto_update_manga_sync_key)
val askUpdateMangaSync = context.getString(R.string.pref_ask_update_manga_sync_key)
val lastUsedCatalogueSource = context.getString(R.string.pref_last_catalogue_source_key)
val lastUsedCategory = context.getString(R.string.pref_last_used_category_key)
val catalogueAsList = context.getString(R.string.pref_display_catalogue_as_list)
val displayR18content = context.getString(R.string.pref_R18_content_key)
val enabledLanguages = context.getString(R.string.pref_source_languages)
val downloadsDirectory = context.getString(R.string.pref_download_directory_key)
val downloadThreads = context.getString(R.string.pref_download_slots_key)
val downloadOnlyOverWifi = context.getString(R.string.pref_download_only_over_wifi_key)
val removeAfterReadSlots = context.getString(R.string.pref_remove_after_read_slots_key)
val removeAfterMarkedAsRead = context.getString(R.string.pref_remove_after_marked_as_read_key)
val libraryUpdateInterval = context.getString(R.string.pref_library_update_interval_key)
val libraryUpdateRestriction = context.getString(R.string.pref_library_update_restriction_key)
val libraryUpdateCategories = context.getString(R.string.pref_library_update_categories_key)
val filterDownloaded = context.getString(R.string.pref_filter_downloaded_key)
val filterUnread = context.getString(R.string.pref_filter_unread_key)
val automaticUpdates = context.getString(R.string.pref_enable_automatic_updates_key)
val startScreen = context.getString(R.string.pref_start_screen_key)
fun sourceUsername(sourceId: String) = "pref_source_username_$sourceId"
fun sourcePassword(sourceId: String) = "pref_source_password_$sourceId"
fun syncUsername(syncId: Int) = "pref_mangasync_username_$syncId"
fun syncPassword(syncId: Int) = "pref_mangasync_password_$syncId"
val libraryAsList = context.getString(R.string.pref_display_library_as_list)
}
| gpl-3.0 | c2a1873cf732234297f401f80c55b660 | 38.650485 | 98 | 0.771548 | 3.746789 | false | false | false | false |
siosio/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/ui/preview/MarkdownTextEditorProvider.kt | 1 | 1924 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.ui.preview
import com.intellij.ide.scratch.ScratchUtil
import com.intellij.lang.LanguageUtil
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import org.intellij.plugins.markdown.lang.MarkdownFileType
import org.intellij.plugins.markdown.lang.MarkdownLanguage
import org.intellij.plugins.markdown.ui.floating.FloatingToolbar
import org.jetbrains.annotations.ApiStatus
/**
* This provider will create default text editor and attach [FloatingToolbar].
* Toolbar will be disposed right before parent editor disposal.
*
* This provider is not registered in plugin.xml, so it can be used only manually.
*/
@ApiStatus.Experimental
class MarkdownTextEditorProvider: PsiAwareTextEditorProvider() {
override fun accept(project: Project, file: VirtualFile): Boolean {
if (!super.accept(project, file)) {
return false
}
return file.fileType == MarkdownFileType.INSTANCE || shouldAcceptScratchFile(project, file)
}
private fun shouldAcceptScratchFile(project: Project, file: VirtualFile): Boolean {
return ScratchUtil.isScratch(file) && LanguageUtil.getLanguageForPsi(project, file, file.fileType) == MarkdownLanguage.INSTANCE
}
override fun createEditor(project: Project, file: VirtualFile): FileEditor {
val actualEditor = super.createEditor(project, file)
if (actualEditor is TextEditor) {
val toolbar = FloatingToolbar(actualEditor.editor)
Disposer.register(actualEditor, toolbar)
}
return actualEditor
}
} | apache-2.0 | 73b29f3c55742f6cdc824b107c582a3e | 41.777778 | 158 | 0.79262 | 4.453704 | false | false | false | false |
siosio/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangesViewPanel.kt | 1 | 3580 | // 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.vcs.changes
import com.intellij.ide.DataManager
import com.intellij.ide.DefaultTreeExpander
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces.CHANGES_VIEW_TOOLBAR
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.openapi.vcs.changes.ui.HoverIcon
import com.intellij.ui.IdeBorderFactory.createBorder
import com.intellij.ui.JBColor
import com.intellij.ui.ScrollPaneFactory.createScrollPane
import com.intellij.ui.SideBorder
import com.intellij.util.EditSourceOnDoubleClickHandler.isToggleEvent
import com.intellij.util.OpenSourceUtil.openSourcesFrom
import com.intellij.util.Processor
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.util.ui.tree.TreeUtil
import javax.swing.JComponent
import javax.swing.JTree
import javax.swing.SwingConstants
import kotlin.properties.Delegates.observable
class ChangesViewPanel(project: Project) : BorderLayoutPanel() {
val changesView: ChangesListView = MyChangesListView(project).apply {
treeExpander = object : DefaultTreeExpander(this) {
override fun collapseAll(tree: JTree, keepSelectionLevel: Int) {
super.collapseAll(tree, 2)
TreeUtil.expand(tree, 1)
}
}
doubleClickHandler = Processor { e ->
if (isToggleEvent(this, e)) return@Processor false
openSourcesFrom(DataManager.getInstance().getDataContext(this), true)
true
}
enterKeyHandler = Processor {
openSourcesFrom(DataManager.getInstance().getDataContext(this), false)
true
}
}
val toolbarActionGroup = DefaultActionGroup()
var isToolbarHorizontal: Boolean by observable(false) { _, oldValue, newValue ->
if (oldValue != newValue) {
addToolbar(newValue) // this also removes toolbar from previous parent
}
}
val toolbar: ActionToolbar =
ActionManager.getInstance().createActionToolbar(CHANGES_VIEW_TOOLBAR, toolbarActionGroup, isToolbarHorizontal).apply {
setTargetComponent(changesView)
}
var statusComponent by observable<JComponent?>(null) { _, oldValue, newValue ->
if (oldValue == newValue) return@observable
if (oldValue != null) centerPanel.remove(oldValue)
if (newValue != null) centerPanel.addToBottom(newValue)
}
private val centerPanel = simplePanel(createScrollPane(changesView))
init {
addToCenter(centerPanel)
addToolbar(isToolbarHorizontal)
}
private fun addToolbar(isHorizontal: Boolean) {
if (isHorizontal) {
toolbar.setOrientation(SwingConstants.HORIZONTAL)
centerPanel.border = createBorder(JBColor.border(), SideBorder.TOP)
addToTop(toolbar.component)
}
else {
toolbar.setOrientation(SwingConstants.VERTICAL)
centerPanel.border = createBorder(JBColor.border(), SideBorder.LEFT)
addToLeft(toolbar.component)
}
}
private class MyChangesListView(project: Project) : ChangesListView(project, false) {
override fun getHoverIcon(node: ChangesBrowserNode<*>): HoverIcon? {
return ChangesViewNodeAction.EP_NAME.computeSafeIfAny(project) { it.createNodeHoverIcon(node) }
}
}
}
| apache-2.0 | a619a3df3c89bab0be967a1b5c81d2c6 | 37.085106 | 140 | 0.77067 | 4.589744 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/lambdas.0.kt | 3 | 747 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter
// OPTIONS: usages
data class A(val <caret>a: Int, val b: Int)
fun takeExtFun(p: A.() -> Unit) {
}
fun takeFun1(p: (A) -> Unit) {
}
fun takeFun2(p: ((A?, Int) -> Unit)?) {
}
fun takeFun3(p: (List<A>) -> Unit) {
}
fun takeFuns(p: MutableList<(A) -> Unit>) {
p[0] = { val (x, y) = it }
}
fun <T> x(p1: T, p2: (T) -> Unit){}
fun foo(p: A) {
takeExtFun { val (x, y) = this }
takeFun1 { val (x, y) = it }
takeFun2 { a, n -> val (x, y) = a!! }
takeFun3 { val (x, y) = it[0] }
x(p) { val (x, y) = it }
x(p, fun (p) { val (x, y) = p })
}
var Any.v: (A) -> Unit
get() = TODO()
set(value) = TODO()
fun f() {
"".v = { val (x, y ) = it }
}
// FIR_IGNORE | apache-2.0 | 4cc40d52d24ddd52b97af346607d7a5e | 16.395349 | 52 | 0.481928 | 2.298462 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/openal/src/templates/kotlin/openal/templates/AL_SOFT_UHJ.kt | 4 | 5123 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package openal.templates
import org.lwjgl.generator.*
import openal.*
val AL_SOFT_UHJ = "SOFTUHJ".nativeClassAL("SOFT_UHJ") {
documentation =
"""
Native bindings to the $specLinkOpenALSoft extension.
This extension adds support for UHJ channel formats and a Super Stereo (a.k.a. Stereo Enhance) processor.
UHJ is a method of encoding surround sound from a first-order B-Format signal into a stereo-compatible signal. Such signals can be played as normal
stereo (with more stable and wider stereo imaging than pan-pot mixing) or decoded back to surround sound, which makes it a decent choice where 3+
channel surround sound isn't available or desirable. When decoded, a UHJ signal behaves like B-Format, which allows it to be rotated through
AL_EXT_BFORMAT's source orientation property as with B-Format formats.
The standard equation[1] for decoding UHJ to B-Format is:
${codeBlock("""
S = Left + Right
D = Left - Right
W = 0.981532*S + 0.197484*j(0.828331*D + 0.767820*T)
X = 0.418496*S - j(0.828331*D + 0.767820*T)
Y = 0.795968*D - 0.676392*T + j(0.186633*S)
Z = 1.023332*Q""")}
where {@code j} is a wide-band +90 degree phase shift. 2-channel UHJ excludes the T and Q input channels, and 3-channel excludes the Q input channel.
Be aware that the resulting W, X, Y, and Z signals are 3dB louder than their FuMa counterparts, and the implementation should account for that to
properly balance it against other sounds.
An alternative equation for decoding 2-channel-only UHJ is:
${codeBlock("""
S = Left + Right
D = Left - Right
W = 0.981532*S + j(0.163582*D)
X = 0.418496*S - j(0.828331*D)
Y = 0.762956*D + j(0.384230*S)""")}
Which equation to use depends on the implementation and user preferences. It's relevant to note that the standard decoding equation is reversible with
the encoding equation, meaning decoding UHJ to B-Format with the standard equation and then encoding B-Format to UHJ results in the original UHJ
signal, even for 2-channel. The alternative 2-channel decoding equation does not result in the original UHJ signal when re- encoded.
One additional note for decoding 2-channel UHJ is the resulting B-Format signal should pass through alternate shelf filters for frequency-dependent
processing. For the standard equation, suitable shelf filters are given as:
${codeBlock("""
W: LF = 0.661, HF = 1.000
X/Y: LF = 1.293, HF = 1.000""")}
And for the alternative equation, suitable shelf filters are given as:
${codeBlock("""
W: LF = 0.646, HF = 1.000
X/Y: LF = 1.263, HF = 1.000""")}
3- and 4-channel UHJ should use the normal shelf filters for B-Format.
Super Stereo (occasionally called Stereo Enhance) is a technique for processing a plain (non-UHJ) stereo signal to derive a B-Format signal. It's
backed by the same functionality as UHJ decoding, making it an easy addition on top of UHJ support. Super Stereo has a variable width control, allowing
the stereo soundfield to "wrap around" the listener while maintaining a stable center image (a more naive virtual speaker approach would cause the
center image to collapse as the soundfield widens). Since this derives a B-Format signal like UHJ, it also allows such sources to be rotated through
the source orientation property.
There are various forms of Super Stereo, with varying equations, but a good suggested option is:
${codeBlock("""
S = Left + Right
D = Left - Right
W = 0.6098637*S - j(0.6896511*w*D)
X = 0.8624776*S + j(0.7626955*w*D)
Y = 1.6822415*w*D - j(0.2156194*S)""".trimIndent())}
where {@code w} is a variable width factor, in the range {@code [0...0.7]}. As with UHJ, the resulting W, X, Y, and Z signals are 3dB louder than their
FuMa counterparts. The normal shelf filters for playing B-Format should apply.
"""
IntConstant(
"Accepted by the {@code format} parameter of #BufferData().",
"FORMAT_UHJ2CHN8_SOFT"..0x19A2,
"FORMAT_UHJ2CHN16_SOFT"..0x19A3,
"FORMAT_UHJ2CHN_FLOAT32_SOFT"..0x19A4,
"FORMAT_UHJ3CHN8_SOFT"..0x19A5,
"FORMAT_UHJ3CHN16_SOFT"..0x19A6,
"FORMAT_UHJ3CHN_FLOAT32_SOFT"..0x19A7,
"FORMAT_UHJ4CHN8_SOFT"..0x19A8,
"FORMAT_UHJ4CHN16_SOFT"..0x19A9,
"FORMAT_UHJ4CHN_FLOAT32_SOFT"..0x19AA
)
IntConstant(
"Accepted by the {@code param} parameter of #Sourcei(), #Sourceiv(), #GetSourcei(), and #GetSourceiv().",
"STEREO_MODE_SOFT"..0x19B0
)
IntConstant(
"Accepted by the {@code param} parameter of #Sourcef(), #Sourcefv(), #GetSourcef(), and #GetSourcefv().",
"SUPER_STEREO_WIDTH_SOFT"..0x19B1
)
IntConstant(
"Accepted by the {@code value} parameter of #Sourcei() and #Sourceiv() for #STEREO_MODE_SOFT.",
"NORMAL_SOFT"..0x0000,
"SUPER_STEREO_SOFT"..0x0001
)
} | bsd-3-clause | 8e670f16662a3b3e3eb9e1c31a9f8b9f | 44.345133 | 159 | 0.679289 | 3.667144 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/html/GlobalStyleSheetHolder.kt | 4 | 2454 | // 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.html
import com.intellij.diagnostic.runActivity
import com.intellij.ide.ui.LafManager
import com.intellij.ide.ui.LafManagerListener
import com.intellij.openapi.editor.colors.EditorColorsListener
import com.intellij.openapi.editor.colors.EditorColorsScheme
import org.jetbrains.annotations.ApiStatus.Internal
import javax.swing.text.html.HTMLEditorKit
import javax.swing.text.html.StyleSheet
/**
* Holds a reference to global CSS style sheet that should be used by [HTMLEditorKit] to properly render everything
* with respect to Look-and-Feel
*
* Based on a default swing stylesheet at javax/swing/text/html/default.css
*/
@Internal
object GlobalStyleSheetHolder {
private val globalStyleSheet = StyleSheet()
private var swingStyleSheetHandled = false
private var currentLafStyleSheet: StyleSheet? = null
/**
* Returns a global style sheet that is dynamically updated when LAF changes
*/
fun getGlobalStyleSheet(): StyleSheet {
val result = StyleSheet()
// return a linked sheet to avoid mutation of a global variable
result.addStyleSheet(globalStyleSheet)
return result
}
/**
* Populate global stylesheet with LAF-based overrides
*/
internal fun updateGlobalStyleSheet() {
runActivity("global styleSheet updating") {
if (!swingStyleSheetHandled) {
// get the default JRE CSS and ...
val kit = HTMLEditorKit()
val defaultSheet = kit.styleSheet
globalStyleSheet.addStyleSheet(defaultSheet)
// ... set a new default sheet
kit.styleSheet = getGlobalStyleSheet()
swingStyleSheetHandled = true
}
val currentSheet = currentLafStyleSheet
if (currentSheet != null) {
globalStyleSheet.removeStyleSheet(currentSheet)
}
val newStyle = StyleSheet()
newStyle.addRule(LafCssProvider.getCssForCurrentLaf())
newStyle.addRule(LafCssProvider.getCssForCurrentEditorScheme())
currentLafStyleSheet = newStyle
globalStyleSheet.addStyleSheet(newStyle)
}
}
internal class UpdateListener : EditorColorsListener, LafManagerListener {
override fun lookAndFeelChanged(source: LafManager) {
updateGlobalStyleSheet()
}
override fun globalSchemeChange(scheme: EditorColorsScheme?) {
updateGlobalStyleSheet()
}
}
} | apache-2.0 | 6b3a4d3b6927f701c7eadbcde3e380c7 | 32.630137 | 120 | 0.740016 | 4.765049 | false | false | false | false |
janishar/Tutorials | tinder-swipe-kotlin/app/src/main/java/tinderswipe/swipe/mindorks/demo/Utils.kt | 1 | 2278 | package tinderswipe.swipe.mindorks.demo
import android.content.Context
import android.content.res.Resources
import android.graphics.Point
import android.os.Build
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import com.google.gson.GsonBuilder
import org.json.JSONArray
import java.io.IOException
import java.nio.charset.Charset
object Utils {
private val TAG = "Utils"
fun loadProfiles(context: Context): List<Profile> {
try {
val builder = GsonBuilder()
val gson = builder.create()
val array = JSONArray(loadJSONFromAsset(context, "profiles.json"))
val profileList = ArrayList<Profile>()
for (i in 0 until array.length()) {
val profile = gson.fromJson(array.getString(i), Profile::class.java)
profileList.add(profile)
}
return profileList
} catch (e: Exception) {
e.printStackTrace()
return ArrayList()
}
}
private fun loadJSONFromAsset(context: Context, jsonFileName: String): String {
try {
val manager = context.assets
Log.d(TAG, "path $jsonFileName")
val inputStream = manager.open(jsonFileName)
val size = inputStream!!.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
return String(buffer, Charset.forName("UTF-8"))
} catch (ex: IOException) {
ex.printStackTrace()
return "{}";
}
}
fun getDisplaySize(windowManager: WindowManager): Point {
try {
if (Build.VERSION.SDK_INT > 16) {
val display = windowManager.defaultDisplay
val displayMetrics = DisplayMetrics()
display.getMetrics(displayMetrics)
return Point(displayMetrics.widthPixels, displayMetrics.heightPixels)
} else {
return Point(0, 0)
}
} catch (e: Exception) {
e.printStackTrace()
return Point(0, 0)
}
}
fun dpToPx(dp: Int): Int {
return (dp * Resources.getSystem().displayMetrics.density).toInt()
}
}
| apache-2.0 | 4ae28c4619fea164649f38c788404684 | 30.205479 | 85 | 0.595698 | 4.775681 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/util/project-model-updater/src/org/jetbrains/tools/model/updater/impl/MavenId.kt | 1 | 872 | package org.jetbrains.tools.model.updater.impl
data class MavenId(val groupId: String, val artifactId: String, val version: String = "") {
val coordinates: String = if (version == "") "$groupId:$artifactId" else "$groupId:$artifactId:$version"
companion object {
fun fromCoordinates(coordinates: String): MavenId {
val (group, artifact, version) = coordinates.split(":").also {
check(it.size == 3) {
"mavenCoordinates ($coordinates) are expected to two semicolons"
}
}
return MavenId(group, artifact, version)
}
}
}
fun MavenId.toJarPath(): String = "${groupId.replace(".", "/")}/$artifactId/$version/$artifactId-$version.jar"
fun MavenId.toSourcesJarPath(): String = "${groupId.replace(".", "/")}/$artifactId/$version/$artifactId-$version-sources.jar"
| apache-2.0 | caf4fbc9132554dc94071c8551deb95b | 44.894737 | 125 | 0.625 | 4.518135 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ui/charts/LineChart.kt | 3 | 8744 | package com.intellij.ui.charts
import java.awt.BasicStroke
import java.awt.BasicStroke.CAP_BUTT
import java.awt.BasicStroke.JOIN_ROUND
import java.awt.Graphics2D
import java.awt.Rectangle
import java.awt.geom.Area
import java.awt.geom.Path2D
import java.awt.geom.Point2D
import java.util.*
import kotlin.NoSuchElementException
import kotlin.math.hypot
import kotlin.math.min
/**
* Simple Line Chart.
*
* Has options:
* <ul>
* <li><b>stepped</b> — can be set to LineStepped.(NONE|BEFORE|AFTER)
* <li><b>stacked</b> — if <code>true</code> area under chart's line subtracts from result graphic (every next chart cannot paint on this area anymore)
* <li><b>stroke</b> — set custom stroke for the line
* </ul>
*/
abstract class LineDataset<X: Number, Y: Number>: Dataset<Coordinates<X, Y>>() {
var stepped: LineStepped = LineStepped.NONE
var stacked: Boolean = false
var stroke = BasicStroke(1.5f, CAP_BUTT, JOIN_ROUND)
var smooth: Boolean = false
var modificationFirst: Boolean = false
set(value) {
field = value
data = (if (value) LinkedList() else mutableListOf<Coordinates<X, Y>>()).apply {
data.forEach { [email protected](it) }
}
}
fun find(x: X): Y? = data.find { it.x == x }?.y
companion object {
@JvmStatic fun <T: Number> of(vararg values: T) = CategoryLineDataset<T>().apply {
addAll(values.mapIndexed(::Coordinates).toList())
}
@JvmStatic fun <X: Number, Y: Number> of(xs: Array<X>, ys: Array<Y>) = XYLineDataset<X, Y>().apply {
addAll(Array(min(xs.size, ys.size)) { i -> Coordinates(xs[i], ys[i]) }.toList())
}
@JvmStatic fun <X: Number, Y: Number> of(vararg points: Coordinates<X, Y>) = XYLineDataset<X, Y>().apply {
addAll(points.toList())
}
}
}
/**
* Type of stepped line:
*
* * NONE — line continuously connects every line
* * BEFORE — line changes value before connection to another point
* * AFTER — line changes value after connection to another point
*/
enum class LineStepped {
NONE, BEFORE, AFTER
}
/**
* Default 2-dimensional dataset for function like f(x) = y.
*/
open class XYLineDataset<X: Number, Y: Number> : LineDataset<X, Y>() {
}
/**
* Default category dataset, that is specific type of XYLineDataset, when x in range of (0..<value count>).
*/
open class CategoryLineDataset<X: Number> : LineDataset<Int, X>() {
var values: Iterable<X>
get() = data.map { it.y }
set(value) {
data = value.mapIndexed(::Coordinates)
}
}
/**
* Base chart component.
*
* For drawing uses GeneralPath from AWT library.
*
* Has options:
*
* * gridColor
* * borderPainted — if <code>true</code> draws a border around the chart and respects margins
* * ranges — grid based range, that holds all information about grid painting. Has minimal and maximum values for graphic.
*/
abstract class LineChart<X: Number, Y: Number, D: LineDataset<X, Y>>: GridChartWrapper<X, Y>() {
var datasets: List<D> = mutableListOf()
companion object {
@JvmStatic fun <T: Number, D: CategoryLineDataset<T>> of(vararg values: D) = CategoryLineChart<T>().apply {
datasets = mutableListOf(*values)
}
@JvmStatic fun <X: Number, Y: Number, D: XYLineDataset<X, Y>> of(vararg values: D) = XYLineChart<X, Y>().apply {
datasets = mutableListOf(*values)
}
@JvmStatic fun <T: Number> of(vararg values: T) = CategoryLineChart<T>().apply {
datasets = mutableListOf(LineDataset.of(*values))
}
@JvmStatic fun <X: Number, Y: Number> of(vararg points: Coordinates<X, Y>) = XYLineChart<X, Y>().apply {
datasets = mutableListOf(LineDataset.of(*points))
}
}
var borderPainted: Boolean = false
override val ranges = Grid<X, Y>()
override fun paintComponent(g: Graphics2D) {
val gridWidth = width - (margins.left + margins.right)
val gridHeight = height - (margins.top + margins.bottom)
if (borderPainted) {
g.color = gridColor
g.drawRect(margins.left, margins.top, gridWidth, gridHeight)
}
val xy = findMinMax()
if (xy.isInitialized) {
val grid = g.create(margins.left, margins.top, gridWidth, gridHeight) as Graphics2D
paintGrid(grid, g, xy)
datasets.forEach {
it.paintDataset(grid, xy)
}
grid.dispose()
}
}
override fun findMinMax() = if (ranges.isInitialized) ranges else ranges * (ranges + MinMax()).apply {
datasets.forEach { it.data.forEach(::process) }
}
private fun D.paintDataset(g: Graphics2D, xy: MinMax<X, Y>) {
val path = Path2D.Double()
lateinit var first: Point2D
val bounds = g.clipBounds
g.paint = lineColor
g.stroke = stroke
// set small array to store 4 points of values
val useSplines = smooth && stepped == LineStepped.NONE
val neighborhood = DoubleArray(8) { Double.NaN }
data.forEachIndexed { i, (x, y) ->
val px = findX(xy, x)
val py = findY(xy, y)
neighborhood.shiftLeftByTwo(px, py)
if (i == 0) {
first = Point2D.Double(px, py)
path.moveTo(px, py)
} else {
if (!useSplines) {
when (stepped) {
LineStepped.AFTER -> path.lineTo(neighborhood[4], py)
LineStepped.BEFORE -> path.lineTo(px, neighborhood[5])
}
path.lineTo(px, py)
} else if (i > 1) {
path.curveTo(neighborhood)
}
}
}
// last step to draw tail of graphic, when spline is used
if (useSplines) {
neighborhood.shiftLeftByTwo(Double.NaN, Double.NaN)
path.curveTo(neighborhood)
}
g.paint = lineColor
g.stroke = stroke
g.draw(path)
// added some points
path.currentPoint?.let { last ->
path.lineTo(last.x, bounds.height + 1.0)
path.lineTo(first.x, bounds.height + 1.0)
path.closePath()
}
fillColor?.let {
g.paint = it
g.fill(path)
}
if (stacked) {
// fix stroke cutting
val area = Area(g.clip)
area.subtract(Area(path))
g.clip = area
}
}
fun findLocation(xy: MinMax<X, Y>, coordinates: Coordinates<X, Y>) = Point2D.Double(
findX(xy, coordinates.x) + margins.left, findY(xy, coordinates.y) + margins.top
)
open fun add(x: X, y: Y) {
datasets.firstOrNull()?.add(x to y)
}
fun getDataset() = datasets.first()
@JvmName("getDataset")
operator fun get(label: String): LineDataset<X, Y> = datasets.find { it.label == label } ?: throw NoSuchElementException("Cannot find dataset with label $datasets")
fun clear() {
datasets.forEach { (it.data as MutableList).clear() }
}
}
open class CategoryLineChart<X: Number> : LineChart<Int, X, CategoryLineDataset<X>>()
open class XYLineChart<X: Number, Y: Number> : LineChart<X, Y, XYLineDataset<X, Y>>()
// HELPERS
/**
* Calculates control points for bezier function and curves line.
* Requires an array of 4 points in format (x0, y0, x1, y1, x2, y2, x3, y3),
* where (x2, y2) — is target point, x1, y1 — point, that can be acquired by Path2D.currentPoint.
* (x0, y0) — point before current and (x3, y3) —point after.
*
* @param neighbour array keeps 4 points (size 8)
*
* Using Monotone Cubic Splines: algorithm https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
*/
private fun Path2D.Double.curveTo(neighbour: DoubleArray) {
assert(neighbour.size == 8) { "Array must contain 4 points in format (x0, y0, x1, y1, x2, y2, x3, y3)" }
val x0 = neighbour[0]
val y0 = neighbour[1]
val x1 = neighbour[2]
val y1 = neighbour[3]
val x2 = neighbour[4]
val y2 = neighbour[5]
val x3 = neighbour[6]
val y3 = neighbour[7]
val slope0 = ((y1 - y0) / (x1 - x0)).orZero()
val slope1 = ((y2 - y1) / (x2 - x1)).orZero()
val slope2 = ((y3 - y2) / (x3 - x2)).orZero()
var tan1 = if (slope0 * slope1 <= 0) 0.0 else (slope0 + slope1) / 2
var tan2 = if (slope1 * slope2 <= 0) 0.0 else (slope1 + slope2) / 2
if (slope1 == 0.0) {
tan1 = 0.0
tan2 = 0.0
} else {
val a = tan1 / slope1
val b = tan2 / slope1
val h = hypot(a, b)
if (h > 3.0) {
val t = 3.0 / h
tan1 = t * a * slope1
tan2 = t * b * slope1
}
}
val delta2 = (x2 - x1) / 3
var cx0 = x1 + delta2
var cy0 = y1 + delta2 * tan1
if (x0.isNaN() || y0.isNaN()) {
cx0 = x1
cy0 = y1
}
val delta0 = (x2 - x1) / 3
var cx1 = x2 - delta0
var cy1 = y2 - delta0 * tan2
if (x3.isNaN() || y3.isNaN()) {
cx1 = x2
cy1 = y2
}
curveTo(cx0, cy0, cx1, cy1, x2, y2)
}
private fun Double.orZero() = if (this.isNaN()) 0.0 else this
private fun DoubleArray.shiftLeftByTwo(first: Double, second: Double) {
for (j in 2 until size) {
this[j - 2] = this[j]
}
this[size - 2] = first
this[size - 1] = second
}
| apache-2.0 | 34f0acf98c25139bbb1bae2086d74a25 | 27.496732 | 166 | 0.630161 | 3.315589 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/console/PyConsoleCopyHandler.kt | 1 | 3037 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vgrechka.phizdetsidea.phizdets.console
import com.intellij.execution.impl.ConsoleViewUtil
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.richcopy.settings.RichCopySettings
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import java.awt.datatransfer.StringSelection
/**
* Created by Yuli Fiterman on 9/17/2016.
*/
class PyConsoleCopyHandler(val originalHandler: EditorActionHandler) : EditorActionHandler() {
override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext) {
if (!RichCopySettings.getInstance().isEnabled) {
return originalHandler.execute(editor, null, dataContext);
}
if (true != editor.getUserData(ConsoleViewUtil.EDITOR_IS_CONSOLE_HISTORY_VIEW)) {
return originalHandler.execute(editor, null, dataContext);
}
doCopyWithoutPrompt(editor as EditorEx);
}
private fun doCopyWithoutPrompt(editor: EditorEx) {
val start = editor.selectionModel.selectionStart
val end = editor.selectionModel.selectionEnd
val document = editor.document
val beginLine = document.getLineNumber(start)
val endLine = document.getLineNumber(end)
val sb = StringBuilder()
for (i in beginLine..endLine) {
var lineStart = document.getLineStartOffset(i)
val r = Ref.create<Int>()
editor.markupModel.processRangeHighlightersOverlappingWith(lineStart, lineStart) {
val length = it.getUserData(PROMPT_LENGTH_MARKER) ?: return@processRangeHighlightersOverlappingWith true
r.set(length)
false
}
if (!r.isNull) {
lineStart += r.get()
}
val rangeStart = Math.max(lineStart, start)
val rangeEnd = Math.min(document.getLineEndOffset(i), end)
if (rangeStart < rangeEnd) {
sb.append(document.getText(TextRange(rangeStart, rangeEnd)))
sb.append("\n")
}
}
if (!sb.isEmpty()) {
CopyPasteManager.getInstance().setContents(StringSelection(sb.toString()))
}
}
companion object {
@JvmField
val PROMPT_LENGTH_MARKER: Key<Int?> = Key.create<Int>("PROMPT_LENGTH_MARKER");
}
}
| apache-2.0 | 854a6c7a092c8aa6cc379ffc1854e662 | 36.036585 | 112 | 0.735265 | 4.265449 | false | false | false | false |
frc2052/FRC-Krawler | app/src/main/kotlin/com/team2052/frckrawler/metric/types/StringIndexMetricTypeEntry.kt | 1 | 3641 | package com.team2052.frckrawler.metric.types
import android.view.View
import com.google.common.base.Joiner
import com.google.common.base.Strings
import com.google.common.collect.Maps
import com.google.gson.JsonObject
import com.team2052.frckrawler.database.metric.CompiledMetricValue
import com.team2052.frckrawler.database.metric.MetricValue
import com.team2052.frckrawler.db.Metric
import com.team2052.frckrawler.db.Robot
import com.team2052.frckrawler.metric.MetricTypeEntry
import com.team2052.frckrawler.metrics.view.MetricWidget
import com.team2052.frckrawler.tba.JSON
import com.team2052.frckrawler.util.MetricHelper
import com.team2052.frckrawler.util.Tuple2
open class StringIndexMetricTypeEntry<out W : MetricWidget>(widgetType: Class<W>) : MetricTypeEntry<W>(widgetType) {
override fun convertValueToString(value: JsonObject): String {
val names = value.get("names").asJsonArray
val values = value.get("values").asJsonArray
var value = ""
for (i in 0..names.size() - 1) {
value += String.format("%s - %s%s" + if (i == names.size() - 1) "" else "\n", names.get(i).asString, values.get(i).asDouble, '%')
}
return value
}
override fun compileValues(robot: Robot, metric: Metric, metricData: List<MetricValue>, compileWeight: Double): JsonObject {var denominator = 0.0
val compiledValue = JsonObject()
val possible_values = JSON.getAsJsonObject(metric.data).get("values").asJsonArray
val compiledVal = Maps.newTreeMap<Int, Tuple2<String, Double>>()
for (i in 0..possible_values.size() - 1) {
compiledVal.put(i, Tuple2(possible_values.get(i).asString, 0.0))
}
if (metricData.isEmpty()) {
val values = JSON.getGson().toJsonTree(Tuple2.yieldValues(compiledVal.values).toTypedArray()).asJsonArray
compiledValue.add("names", possible_values)
compiledValue.add("values", values)
return compiledValue
}
for (metricValue in metricData) {
val result = MetricHelper.getListIndexMetricValue(metricValue)
if (result.t2.isError)
continue
val weight = CompiledMetricValue.getCompileWeightForMatchNumber(metricValue, metricData, compileWeight)
result.t1
.filter { compiledVal.containsKey(it) }
.forEach { compiledVal.put(it, compiledVal[it]!!.setT2(compiledVal[it]!!.t2 + weight)) }
denominator += weight
}
for ((key, value) in compiledVal) {
compiledVal.put(key, value.setT2(Math.round(value.t2 / denominator * 100 * 100.0) / 100.0))
}
val values = JSON.getGson().toJsonTree(Tuple2.yieldValues(compiledVal.values).toTypedArray()).asJsonArray
compiledValue.add("names", possible_values)
compiledValue.add("values", values)
return compiledValue
}
override fun addInfo(metric: Metric, info: MutableMap<String, String>) {
val data = JSON.getAsJsonObject(metric.data)
val values = Joiner.on(", ").join(data.get("values").asJsonArray)
info.put("Comma Separated List", if (Strings.isNullOrEmpty(values)) "No Values" else values)
}
override fun buildMetric(name: String, min: Int?, max: Int?, inc: Int?, commaList: List<String>?): MetricHelper.MetricFactory {
val metricFactory = MetricHelper.MetricFactory(name)
metricFactory.setMetricType(this.typeId)
metricFactory.setDataListIndexValue(commaList)
return metricFactory
}
override fun commaListVisibility(): Int = View.VISIBLE
} | mit | 6caf66ffb4b02bea5241a50e0134a8a1 | 41.847059 | 149 | 0.680857 | 4.175459 | false | false | false | false |
androidx/androidx | metrics/metrics-performance/src/androidTest/java/androidx/metrics/performance/test/MyCustomView.kt | 3 | 2025 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.metrics.performance.test
import android.content.Context
import android.graphics.Canvas
import android.os.Build
import android.util.AttributeSet
import android.view.View
import androidx.annotation.RequiresApi
/**
* This custom view is used to inject an artificial, random delay during drawing, to simulate
* jank on the UI thread.
*/
public class MyCustomView : View {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : super(context, attrs, defStyleAttr, defStyleRes)
override fun onDraw(canvas: Canvas) {
/**
* Inject random delay to cause jank in the app.
* For any given item, there should be a 30% chance of jank (>32ms), and a 2% chance of
* extreme jank (>500ms).
* Regular jank will be between 32 and 82ms, extreme from 500-700ms.
*/
val probability = Math.random()
if (probability > .7) {
val delay: Long
delay = if (probability > .98) {
500 + (Math.random() * 200).toLong()
} else {
32 + (Math.random() * 50).toLong()
}
try {
Thread.sleep(delay)
} catch (e: Exception) {
}
}
super.onDraw(canvas)
}
} | apache-2.0 | e69db5c7f541efd30f3291aee9570361 | 32.213115 | 95 | 0.636543 | 4.326923 | false | false | false | false |
OpenConference/DroidconBerlin2017 | businesslogic/schedule/src/main/java/de/droidcon/berlin2018/schedule/backend/DroidconBerlinBackendScheduleAdapter2018.kt | 1 | 4628 | package de.droidcon.berlin2018.schedule.backend
import de.droidcon.berlin2018.model.Location
import de.droidcon.berlin2018.model.Session
import de.droidcon.berlin2018.model.Speaker
import de.droidcon.berlin2018.schedule.backend.data2018.SessionItem
import de.droidcon.berlin2018.schedule.backend.data2018.SessionResult
import de.droidcon.berlin2018.schedule.backend.data2018.SpeakerItem
import de.droidcon.berlin2018.schedule.backend.data2018.mapping.SimpleLocation
import de.droidcon.berlin2018.schedule.backend.data2018.mapping.SimpleSession
import de.droidcon.berlin2018.schedule.backend.data2018.mapping.SimpleSpeaker
import io.reactivex.Single
import io.reactivex.functions.BiFunction
/**
* [BackendScheduleAdapter] for droidcon Berlin backend
*
* @author Hannes Dorfmann
*/
public class DroidconBerlinBackendScheduleAdapter2018(
private val backend: DroidconBerlinBackend2018
) : BackendScheduleAdapter {
override fun getSpeakers(): Single<BackendScheduleResponse<Speaker>> =
backend.getSpeakers().map { speakerResult ->
val list: List<Speaker> = speakerResult.items.map { it.toSpeaker() }
BackendScheduleResponse.dataChanged(list)
}
override fun getLocations(): Single<BackendScheduleResponse<Location>> =
backend.getSession().map { result: SessionResult? ->
if (result == null)
BackendScheduleResponse.dataChanged(emptyList())
else {
val locations: List<Location> =
result.items.map {
SimpleLocation.create(
it.roomName,
it.roomName
)
} // TODO roomId is fucked up on backend
.distinct()
.toList()
BackendScheduleResponse.dataChanged(locations)
}
}
override fun getSessions(): Single<BackendScheduleResponse<Session>> {
val sessionsResult = backend.getSession()
val spakersMap = backend.getSpeakers().map {
it.items.map { it.toSpeaker() }.associateBy { it.id() }
}
val sessions: Single<List<Session>> =
Single.zip(sessionsResult, spakersMap, BiFunction { sessions, speakersMap ->
sessions.items.map { it.toSession(speakersMap) }
})
return sessions.map {
BackendScheduleResponse.dataChanged(it)
}
}
private fun SpeakerItem.toSpeaker(): Speaker = SimpleSpeaker.create(
id = id,
name = "$firstname $lastname",
company = company,
info = description,
jobTitle = position,
profilePic = imageUrl,
link1 = if (links != null && links.size >= 1) links[0].url else null,
link2 = if (links != null && links.size >= 2) links[1].url else null,
link3 = if (links != null && links.size >= 3) links[2].url else null
)
private fun SessionItem.toSession(speakers: Map<String, Speaker>): Session {
return SimpleSession.create(
id = id,
title = title,
description = description,
favorite = false,
locationId = roomName, // TODO roomId is fucked up on backend site.
locationName = roomName,
speakers = when (id) {
"3858" -> listOf(speakers["237"]!!, speakers["1135"]!!)// MVI
"3785" -> listOf(speakers["1144"]!!, speakers["347"]!!)// Code sharing is caring
"3949" -> listOf(
speakers["1217"]!!,
speakers["276"]!!
)// Everything is better with(out) Bluetooth
"3859" -> listOf(speakers["127"]!!, speakers["304"]!!)// The build side of an app
"5302" -> listOf(
speakers["1345"]!!,
speakers["1347"]!!,
speakers["1348"]!!,
speakers["1349"]!!
) // Manage android without an app
"5309" -> listOf(
speakers["1345"]!!,
speakers["1347"]!!,
speakers["1348"]!!,
speakers["1349"]!!
) // Manage android api hands on
"5307" -> listOf(
speakers["1354"]!!,
speakers["1355"]!!
) // Sharing a success story
else -> listOf(speakers[speakerIds]!!)
},
tags = category,
startTime = startDate,
endTime = endDate
)
}
}
| apache-2.0 | 57022ad132836639399148d70daef764 | 38.220339 | 97 | 0.566335 | 4.955032 | false | false | false | false |
GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectChangesBuilder.kt | 4 | 3156 | /*
* Copyright 2000-2009 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.idea.maven.project
class MavenProjectChangesBuilder : MavenProjectChanges() {
private var hasPackagingChanges = false
private var hasOutputChanges = false
private var hasSourceChanges = false
private var hasDependencyChanges = false
private var hasPluginsChanges = false
private var hasPropertyChanges = false
override fun hasPackagingChanges(): Boolean {
return hasPackagingChanges
}
fun setHasPackagingChanges(value: Boolean) {
hasPackagingChanges = value
packaging = value // backward compatibility
}
override fun hasOutputChanges(): Boolean {
return hasOutputChanges
}
fun setHasOutputChanges(value: Boolean) {
hasOutputChanges = value
output = value // backward compatibility
}
override fun hasSourceChanges(): Boolean {
return hasSourceChanges
}
fun setHasSourceChanges(value: Boolean) {
hasSourceChanges = value
sources = value // backward compatibility
}
override fun hasDependencyChanges(): Boolean {
return hasDependencyChanges
}
fun setHasDependencyChanges(value: Boolean) {
hasDependencyChanges = value
dependencies = value // backward compatibility
}
override fun hasPluginsChanges(): Boolean {
return hasPluginsChanges
}
fun setHasPluginChanges(value: Boolean) {
hasPluginsChanges = value
plugins = value // backward compatibility
}
override fun hasPropertyChanges(): Boolean {
return hasPropertyChanges
}
fun setHasPropertyChanges(value: Boolean) {
hasPropertyChanges = value
properties = value // backward compatibility
}
fun setAllChanges(value: Boolean) {
setHasPackagingChanges(value)
setHasOutputChanges(value)
setHasSourceChanges(value)
setHasDependencyChanges(value)
setHasPluginChanges(value)
setHasPropertyChanges(value)
}
companion object {
@JvmStatic
fun merged(a: MavenProjectChanges, b: MavenProjectChanges): MavenProjectChangesBuilder {
val result = MavenProjectChangesBuilder()
result.setHasPackagingChanges(a.hasPackagingChanges() || b.hasPackagingChanges())
result.setHasOutputChanges(a.hasOutputChanges() || b.hasOutputChanges())
result.setHasSourceChanges(a.hasSourceChanges() || b.hasSourceChanges())
result.setHasDependencyChanges(a.hasDependencyChanges() || b.hasDependencyChanges())
result.setHasPluginChanges(a.hasPluginsChanges() || b.hasPluginsChanges())
result.setHasPropertyChanges(a.hasPropertyChanges() || b.hasPropertyChanges())
return result
}
}
} | apache-2.0 | 65189baef5f02d1db25d83a8185c640d | 29.95098 | 92 | 0.74398 | 5.009524 | false | false | false | false |
Abdel-RhmanAli/Inventory-App | app/src/main/java/com/example/android/inventory/database/AppDatabase.kt | 1 | 955 | package com.example.android.inventory.database
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.TypeConverters
import android.content.Context
import com.example.android.inventory.model.Item
import com.example.android.inventory.util.Converters
@Database(entities = [(Item::class)], version = 1)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun itemsDao(): ItemsDao
companion object {
private var INSTANCE: AppDatabase? = null
private const val DATABASE_NAME = "items.db"
fun getInstance(context: Context): AppDatabase? {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME).build()
}
return INSTANCE
}
}
} | apache-2.0 | eb2526498391bb06f70ad48502353949 | 32.178571 | 104 | 0.697382 | 4.462617 | false | false | false | false |
ncoe/rosetta | Two_bullet_roulette/Kotlin/src/main/kotlin/main.kt | 1 | 1771 | import kotlin.random.Random
val cylinder = Array(6) { false }
fun rShift() {
val t = cylinder[cylinder.size - 1]
for (i in (0 until cylinder.size - 1).reversed()) {
cylinder[i + 1] = cylinder[i]
}
cylinder[0] = t
}
fun unload() {
for (i in cylinder.indices) {
cylinder[i] = false
}
}
fun load() {
while (cylinder[0]) {
rShift()
}
cylinder[0] = true
rShift()
}
fun spin() {
val lim = Random.nextInt(0, 6) + 1
for (i in 1..lim) {
rShift()
}
}
fun fire(): Boolean {
val shot = cylinder[0]
rShift()
return shot
}
fun method(s: String): Int {
unload()
for (c in s) {
when (c) {
'L' -> {
load()
}
'S' -> {
spin()
}
'F' -> {
if (fire()) {
return 1
}
}
}
}
return 0
}
fun mString(s: String): String {
val buf = StringBuilder()
fun append(txt: String) {
if (buf.isNotEmpty()) {
buf.append(", ")
}
buf.append(txt)
}
for (c in s) {
when (c) {
'L' -> {
append("load")
}
'S' -> {
append("spin")
}
'F' -> {
append("fire")
}
}
}
return buf.toString()
}
fun test(src: String) {
val tests = 100000
var sum = 0
for (t in 0..tests) {
sum += method(src)
}
val str = mString(src)
val pc = 100.0 * sum / tests
println("%-40s produces %6.3f%% deaths.".format(str, pc))
}
fun main() {
test("LSLSFSF");
test("LSLSFF");
test("LLSFSF");
test("LLSFF");
}
| mit | 523cf9ade59a43852a32ef43194e0fa7 | 16.362745 | 61 | 0.411067 | 3.465753 | false | true | false | false |
siosio/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/VirtualFileUrlBridge.kt | 1 | 1622 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlImpl
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
class VirtualFileUrlBridge(id: Int, manager: VirtualFileUrlManagerImpl, initializeVirtualFileLazily: Boolean) :
VirtualFileUrlImpl(id, manager), VirtualFilePointer {
@Volatile
private var file: VirtualFile? = null
@Volatile
private var timestampOfCachedFiles = -1L
init {
if (!initializeVirtualFileLazily) findVirtualFile()
}
override fun getFile() = findVirtualFile()
override fun isValid() = findVirtualFile() != null
override fun toString() = url
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as VirtualFileUrlBridge
if (id != other.id) return false
return true
}
override fun hashCode(): Int = id
private fun findVirtualFile(): VirtualFile? {
val fileManager = VirtualFileManager.getInstance()
val timestamp = timestampOfCachedFiles
val cachedResults = file
return if (timestamp == fileManager.modificationCount) cachedResults
else {
file = fileManager.findFileByUrl(url)
timestampOfCachedFiles = fileManager.modificationCount
file
}
}
} | apache-2.0 | dbdafce0490eefe4591fe892e27a9756 | 31.46 | 140 | 0.75709 | 4.841791 | false | false | false | false |
siosio/intellij-community | platform/lang-api/src/com/intellij/execution/target/value/TargetEnvironmentFunctions.kt | 1 | 6239 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("TargetEnvironmentFunctions")
package com.intellij.execution.target.value
import com.intellij.execution.target.HostPort
import com.intellij.execution.target.TargetEnvironment
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.TargetPlatform
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.io.FileUtil
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.util.function.Function
import kotlin.io.path.name
/**
* The function that is expected to be resolved with provided
* [TargetEnvironment].
*
* Such functions could be used during the construction of a command line and
* play the role of deferred values of, for example:
* - the path to an executable;
* - the working directory;
* - the command-line parameters;
* - the values of environment variables.
*/
typealias TargetEnvironmentFunction<R> = Function<TargetEnvironment, R>
/**
* This function is preferable to use over function literals in Kotlin
* (i.e. `TargetEnvironmentFunction { value }`) and lambdas in Java
* (i.e. `ignored -> value`) because it is has more explicit [toString] which
* results in clear variable descriptions during debugging and better logging
* abilities.
*/
fun <T> constant(value: T): TargetEnvironmentFunction<T> = TargetEnvironmentFunction { value }
fun <T> Iterable<TargetEnvironmentFunction<T>>.joinToStringFunction(separator: CharSequence): TargetEnvironmentFunction<String> =
JoinedStringTargetEnvironmentFunction(iterable = this, separator = separator)
fun TargetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(localPath: String): TargetEnvironmentFunction<String> {
val (uploadRoot, relativePath) = getUploadRootForLocalPath(localPath)
?: throw IllegalArgumentException("Local path \"$localPath\" is not registered within uploads in the request")
return TargetEnvironmentFunction { targetEnvironment ->
val volume = targetEnvironment.uploadVolumes[uploadRoot]
?: throw IllegalStateException("Upload root \"$uploadRoot\" is expected to be created in the target environment")
return@TargetEnvironmentFunction joinPaths(volume.targetRoot, relativePath, targetEnvironment.targetPlatform)
}
}
fun TargetEnvironmentRequest.getUploadRootForLocalPath(localPath: String): Pair<TargetEnvironment.UploadRoot, String>? {
val targetFileSeparator = targetPlatform.platform.fileSeparator
return uploadVolumes.mapNotNull { uploadRoot ->
getRelativePathIfAncestor(ancestor = uploadRoot.localRootPath.toString(), file = localPath)?.let { relativePath ->
uploadRoot to if (File.separatorChar != targetFileSeparator) {
relativePath.replace(File.separatorChar, targetFileSeparator)
}
else {
relativePath
}
}
}.firstOrNull()
}
private fun getRelativePathIfAncestor(ancestor: String, file: String): String? =
if (FileUtil.isAncestor(ancestor, file, false)) {
FileUtil.getRelativePath(ancestor, file, File.separatorChar)
}
else {
null
}
private fun joinPaths(basePath: String, relativePath: String, targetPlatform: TargetPlatform): String {
val fileSeparator = targetPlatform.platform.fileSeparator.toString()
return FileUtil.toSystemIndependentName("${basePath.removeSuffix(fileSeparator)}$fileSeparator$relativePath")
}
fun TargetEnvironment.UploadRoot.getTargetUploadPath(): TargetEnvironmentFunction<String> =
TargetEnvironmentFunction { targetEnvironment ->
val uploadRoot = this@getTargetUploadPath
val uploadableVolume = targetEnvironment.uploadVolumes[uploadRoot]
?: throw IllegalStateException("Upload root \"$uploadRoot\" cannot be found")
return@TargetEnvironmentFunction uploadableVolume.targetRoot
}
fun TargetEnvironmentFunction<String>.getRelativeTargetPath(targetRelativePath: String): TargetEnvironmentFunction<String> =
TargetEnvironmentFunction { targetEnvironment ->
val targetBasePath = [email protected](targetEnvironment)
return@TargetEnvironmentFunction joinPaths(targetBasePath, targetRelativePath, targetEnvironment.targetPlatform)
}
fun TargetEnvironment.DownloadRoot.getTargetDownloadPath(): TargetEnvironmentFunction<String> =
TargetEnvironmentFunction { targetEnvironment ->
val downloadRoot = this@getTargetDownloadPath
val downloadableVolume = targetEnvironment.downloadVolumes[downloadRoot]
?: throw IllegalStateException("Download root \"$downloadRoot\" cannot be found")
return@TargetEnvironmentFunction downloadableVolume.targetRoot
}
fun TargetEnvironment.LocalPortBinding.getTargetEnvironmentValue(): TargetEnvironmentFunction<HostPort> =
TargetEnvironmentFunction { targetEnvironment ->
val localPortBinding = this@getTargetEnvironmentValue
val resolvedPortBinding = (targetEnvironment.localPortBindings[localPortBinding]
?: throw IllegalStateException("Local port binding \"$localPortBinding\" cannot be found"))
return@TargetEnvironmentFunction resolvedPortBinding.targetEndpoint
}
@Throws(IOException::class)
fun TargetEnvironment.downloadFromTarget(localPath: Path, progressIndicator: ProgressIndicator) {
val localFileDir = localPath.parent
val downloadVolumes = downloadVolumes.values
val downloadVolume = downloadVolumes.find { it.localRoot == localFileDir }
?: error("Volume with local root $localFileDir not found")
downloadVolume.download(localPath.name, progressIndicator)
}
private class JoinedStringTargetEnvironmentFunction<T>(private val iterable: Iterable<TargetEnvironmentFunction<T>>,
private val separator: CharSequence) : TargetEnvironmentFunction<String> {
override fun apply(t: TargetEnvironment): String = iterable.map { it.apply(t) }.joinToString(separator = separator)
override fun toString(): String {
return "JoinedStringTargetEnvironmentValue(iterable=$iterable, separator=$separator)"
}
}
| apache-2.0 | 382eb12f360476f0c6356b7660f7937b | 48.515873 | 140 | 0.773201 | 5.560606 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/text/regex/sets/NonCapturingJointSet.kt | 4 | 1911 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.text.regex
/**
* Node representing non-capturing group
*/
open internal class NonCapturingJointSet(children: List<AbstractSet>, fSet: FSet) : JointSet(children, fSet) {
/**
* Returns startIndex+shift, the next position to match
*/
override fun matches(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int {
val start = matchResult.getConsumed(groupIndex)
matchResult.setConsumed(groupIndex, startIndex)
children.forEach {
val shift = it.matches(startIndex, testString, matchResult)
if (shift >= 0) {
return shift
}
}
matchResult.setConsumed(groupIndex, start)
return -1
}
override val name: String
get() = "NonCapturingJointSet"
override fun hasConsumed(matchResult: MatchResultImpl): Boolean {
return matchResult.getConsumed(groupIndex) != 0
}
}
| apache-2.0 | 1f87ba76d1c5a0fc57d1b2db3cb6a82d | 34.388889 | 110 | 0.695971 | 4.413395 | false | false | false | false |
googlemaps/android-maps-ktx | maps-ktx/src/main/java/com/google/maps/android/ktx/StreetViewPanoramaView.kt | 1 | 3217 | package com.google.maps.android.ktx
import com.google.android.gms.maps.StreetViewPanorama
import com.google.android.gms.maps.StreetViewPanoramaView
import com.google.android.gms.maps.model.StreetViewPanoramaCamera
import com.google.android.gms.maps.model.StreetViewPanoramaLocation
import com.google.android.gms.maps.model.StreetViewPanoramaOrientation
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* A suspending function that provides an instance of a [StreetViewPanorama] from this
* [StreetViewPanoramaView]. This is an alternative to using
* [StreetViewPanoramaView.getStreetViewPanoramaAsync] by using coroutines to obtain a
* [StreetViewPanorama].
*
* @return the [StreetViewPanorama] instance
*/
public suspend inline fun StreetViewPanoramaView.awaitStreetViewPanorama(): StreetViewPanorama =
suspendCoroutine { continuation ->
getStreetViewPanoramaAsync {
continuation.resume(it)
}
}
/**
* Returns a flow that emits when the street view panorama camera changes. Using this to
* observe panorama camera change events will override an existing listener (if any) to
* [StreetViewPanorama.setOnStreetViewPanoramaCameraChangeListener].
*/
public fun StreetViewPanorama.cameraChangeEvents(): Flow<StreetViewPanoramaCamera> =
callbackFlow {
setOnStreetViewPanoramaCameraChangeListener {
trySend(it)
}
awaitClose {
setOnStreetViewPanoramaCameraChangeListener(null)
}
}
/**
* Returns a flow that emits when the street view panorama loads a new panorama. Using this to
* observe panorama load change events will override an existing listener (if any) to
* [StreetViewPanorama.setOnStreetViewPanoramaChangeListener].
*/
public fun StreetViewPanorama.changeEvents(): Flow<StreetViewPanoramaLocation> =
callbackFlow {
setOnStreetViewPanoramaChangeListener {
trySend(it)
}
awaitClose {
setOnStreetViewPanoramaChangeListener(null)
}
}
/**
* Returns a flow that emits when the street view panorama is clicked. Using this to
* observe panorama click events will override an existing listener (if any) to
* [StreetViewPanorama.setOnStreetViewPanoramaClickListener].
*/
public fun StreetViewPanorama.clickEvents(): Flow<StreetViewPanoramaOrientation> =
callbackFlow {
setOnStreetViewPanoramaClickListener {
trySend(it)
}
awaitClose {
setOnStreetViewPanoramaClickListener(null)
}
}
/**
* Returns a flow that emits when the street view panorama is long clicked. Using this to
* observe panorama long click events will override an existing listener (if any) to
* [StreetViewPanorama.setOnStreetViewPanoramaLongClickListener].
*/
public fun StreetViewPanorama.longClickEvents(): Flow<StreetViewPanoramaOrientation> =
callbackFlow {
setOnStreetViewPanoramaLongClickListener {
trySend(it)
}
awaitClose {
setOnStreetViewPanoramaLongClickListener(null)
}
} | apache-2.0 | dd4d85cd96c4c21790e6c479bc641c2f | 35.988506 | 96 | 0.747902 | 5.4618 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/java/src/service/project/wizard/GradleSdkSettingsStep.kt | 4 | 2387 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project.wizard
import com.intellij.ide.util.projectWizard.JavaSettingsStep
import com.intellij.ide.util.projectWizard.SettingsStep
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.util.lang.JavaVersion
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.util.*
class GradleSdkSettingsStep(
private val settingsStep: SettingsStep,
private val builder: AbstractGradleModuleBuilder
) : JavaSettingsStep(settingsStep, builder, builder::isSuitableSdkType) {
private val context get() = settingsStep.context
private val jdk get() = myJdkComboBox.selectedJdk
private val javaVersion get() = JavaVersion.tryParse(jdk?.versionString)
private fun getPreferredGradleVersion(): GradleVersion {
val project = context.project ?: return GradleVersion.current()
return findGradleVersion(project) ?: GradleVersion.current()
}
private fun getGradleVersion(): GradleVersion? {
val preferredGradleVersion = getPreferredGradleVersion()
val javaVersion = javaVersion ?: return preferredGradleVersion
return when (isSupported(preferredGradleVersion, javaVersion)) {
true -> preferredGradleVersion
else -> suggestGradleVersion(javaVersion)
}
}
override fun validate(): Boolean {
return super.validate() && validateGradleVersion()
}
private fun validateGradleVersion(): Boolean {
val javaVersion = javaVersion ?: return true
if (getGradleVersion() != null) {
return true
}
val preferredGradleVersion = getPreferredGradleVersion()
return MessageDialogBuilder.yesNo(
title = GradleBundle.message(
"gradle.settings.wizard.unsupported.jdk.title",
if (context.isCreatingNewProject) 0 else 1
),
message = GradleBundle.message(
"gradle.settings.wizard.unsupported.jdk.message",
javaVersion.toFeatureString(),
MINIMUM_SUPPORTED_JAVA.toFeatureString(),
MAXIMUM_SUPPORTED_JAVA.toFeatureString(),
preferredGradleVersion.version))
.asWarning()
.ask(component)
}
override fun updateDataModel() {
super.updateDataModel()
builder.gradleVersion = getGradleVersion() ?: getPreferredGradleVersion()
}
} | apache-2.0 | 70bc5f4e9623c67a38d663ed922485fb | 36.904762 | 140 | 0.748638 | 5.025263 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinFileChooserDialog.kt | 4 | 2808 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.ui
import com.intellij.ide.util.AbstractTreeClassChooserDialog
import com.intellij.ide.util.TreeChooser
import com.intellij.ide.util.gotoByName.GotoFileModel
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.idea.projectView.KtClassOrObjectTreeNode
import org.jetbrains.kotlin.idea.projectView.KtFileTreeNode
import org.jetbrains.kotlin.idea.search.projectScope
import org.jetbrains.kotlin.idea.search.restrictToKotlinSources
import org.jetbrains.kotlin.psi.KtFile
import javax.swing.tree.DefaultMutableTreeNode
class KotlinFileChooserDialog(
@NlsContexts.DialogTitle title: String,
project: Project,
searchScope: GlobalSearchScope?,
packageName: String?
) : AbstractTreeClassChooserDialog<KtFile>(
title,
project,
searchScope ?: project.projectScope().restrictToKotlinSources(),
KtFile::class.java,
ScopeAwareClassFilter(searchScope, packageName),
null,
null,
false,
false
) {
override fun getSelectedFromTreeUserObject(node: DefaultMutableTreeNode): KtFile? = when (val userObject = node.userObject) {
is KtFileTreeNode -> userObject.ktFile
is KtClassOrObjectTreeNode -> {
val containingFile = userObject.value.containingKtFile
if (containingFile.declarations.size == 1) containingFile else null
}
else -> null
}
override fun getClassesByName(name: String, checkBoxState: Boolean, pattern: String, searchScope: GlobalSearchScope): List<KtFile> {
return FilenameIndex.getFilesByName(project, name, searchScope).filterIsInstance<KtFile>()
}
override fun createChooseByNameModel() = GotoFileModel(this.project)
/**
* Base class [AbstractTreeClassChooserDialog] unfortunately doesn't filter the file tree according to the provided "scope".
* As a workaround we use filter preventing wrong file selection.
*/
private class ScopeAwareClassFilter(val searchScope: GlobalSearchScope?, val packageName: String?) : TreeChooser.Filter<KtFile> {
override fun isAccepted(element: KtFile?): Boolean {
if (element == null) return false
if (searchScope == null && packageName == null) return true
val matchesSearchScope = searchScope?.accept(element.virtualFile) ?: true
val matchesPackage = packageName?.let { element.packageFqName.asString() == it } ?: true
return matchesSearchScope && matchesPackage
}
}
} | apache-2.0 | d84f9107a08839b51d6f1a0eeecf0299 | 42.215385 | 158 | 0.746083 | 4.866551 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownImpl.kt | 6 | 2485 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pushDown
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.refactoring.pullUp.addMemberToTarget
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.util.findCallableMemberBySignature
internal fun moveCallableMemberToClass(
member: KtCallableDeclaration,
memberDescriptor: CallableMemberDescriptor,
targetClass: KtClassOrObject,
targetClassDescriptor: ClassDescriptor,
substitutor: TypeSubstitutor,
makeAbstract: Boolean
): KtCallableDeclaration {
val targetMemberDescriptor = memberDescriptor.substitute(substitutor)?.let {
targetClassDescriptor.findCallableMemberBySignature(it as CallableMemberDescriptor)
}
val targetMember = targetMemberDescriptor?.source?.getPsi() as? KtCallableDeclaration
return targetMember?.apply {
if (memberDescriptor.modality != Modality.ABSTRACT && makeAbstract) {
addModifier(KtTokens.OVERRIDE_KEYWORD)
} else if (memberDescriptor.overriddenDescriptors.isEmpty()) {
removeModifier(KtTokens.OVERRIDE_KEYWORD)
} else {
addModifier(KtTokens.OVERRIDE_KEYWORD)
}
} ?: addMemberToTarget(member, targetClass).apply {
val sourceClassDescriptor = memberDescriptor.containingDeclaration as? ClassDescriptor
if (sourceClassDescriptor?.kind == ClassKind.INTERFACE) {
if (targetClassDescriptor.kind != ClassKind.INTERFACE && memberDescriptor.modality == Modality.ABSTRACT) {
addModifier(KtTokens.ABSTRACT_KEYWORD)
}
}
if (memberDescriptor.modality != Modality.ABSTRACT && makeAbstract) {
KtTokens.VISIBILITY_MODIFIERS.types.forEach { removeModifier(it as KtModifierKeywordToken) }
addModifier(KtTokens.OVERRIDE_KEYWORD)
}
} as KtCallableDeclaration
} | apache-2.0 | b77cf356349f7b3b44d3a46768ce01b0 | 48.72 | 158 | 0.766197 | 5.473568 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/javaStreamsApi/createStream.kt | 12 | 974 | import java.util.Arrays
import java.util.stream.Collectors
import java.util.stream.Stream
internal class Test {
fun main(lst: List<String>) {
val streamOfList = lst.stream()
.map { x: String -> x + "e" }
.collect(Collectors.toList())
val streamOfElements = Stream.of(1, 2, 3)
.map { x: Int -> x + 1 }
.collect(Collectors.toList())
val array = arrayOf(1, 2, 3)
val streamOfArray = Arrays.stream(array)
.map { x: Int -> x + 1 }
.collect(Collectors.toList())
val streamOfArray2 = Stream.of(*array)
.map { x: Int -> x + 1 }
.collect(Collectors.toList())
val streamIterate = Stream.iterate(2) { v: Int -> v * 2 }
.map { x: Int -> x + 1 }
.collect(Collectors.toList())
val streamGenerate = Stream.generate { 42 }
.map { x: Int -> x + 1 }
.collect(Collectors.toList())
}
} | apache-2.0 | 17ac3530eda6a0925226651a43e2ea33 | 35.111111 | 65 | 0.525667 | 3.789883 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/AnonymousTemplateEditingListener.kt | 6 | 3858 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.liveTemplates.macro
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.codeInsight.template.impl.TemplateState
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.overrideImplement.ImplementMembersHandler
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
internal class AnonymousTemplateEditingListener(private val psiFile: PsiFile, private val editor: Editor) : TemplateEditingAdapter() {
private var classRef: KtReferenceExpression? = null
private var classDescriptor: ClassDescriptor? = null
override fun currentVariableChanged(templateState: TemplateState, template: Template?, oldIndex: Int, newIndex: Int) {
if (templateState.template == null) return
val variableRange = templateState.getVariableRange("SUPERTYPE") ?: return
val name = psiFile.findElementAt(variableRange.startOffset)
if (name != null && name.parent is KtReferenceExpression) {
val ref = name.parent as KtReferenceExpression
val descriptor = ref.analyze(BodyResolveMode.FULL).get(BindingContext.REFERENCE_TARGET, ref)
if (descriptor is ClassDescriptor) {
classRef = ref
classDescriptor = descriptor
}
}
}
override fun templateFinished(template: Template, brokenOff: Boolean) {
editor.putUserData(LISTENER_KEY, null)
if (brokenOff) return
if (classDescriptor != null) {
if (classDescriptor!!.kind == ClassKind.CLASS) {
val placeToInsert = classRef!!.textRange.endOffset
runWriteAction {
PsiDocumentManager.getInstance(psiFile.project).getDocument(psiFile)!!.insertString(placeToInsert, "()")
}
var hasConstructorsParameters = false
for (cd in classDescriptor!!.constructors) {
// TODO check for visibility
hasConstructorsParameters = hasConstructorsParameters or (cd.valueParameters.size != 0)
}
if (hasConstructorsParameters) {
editor.caretModel.moveToOffset(placeToInsert + 1)
}
}
ImplementMembersHandler().invoke(psiFile.project, editor, psiFile, true)
}
}
companion object {
private val LISTENER_KEY = Key.create<AnonymousTemplateEditingListener>("kotlin.AnonymousTemplateEditingListener")
fun registerListener(editor: Editor, project: Project) {
if (editor.getUserData(LISTENER_KEY) != null) return
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)!!
val templateState = TemplateManagerImpl.getTemplateState(editor)
if (templateState != null) {
val listener = AnonymousTemplateEditingListener(psiFile, editor)
editor.putUserData(LISTENER_KEY, listener)
templateState.addTemplateStateListener(listener)
}
}
}
}
| apache-2.0 | bf2d64259a12f2b823957d6338e8c810 | 44.928571 | 158 | 0.703473 | 5.31405 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesOrDirectories/KotlinMoveFilesOrDirectoriesHandler.kt | 5 | 4800 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.MoveHandler
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesHandler
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.idea.refactoring.move.logFusForMoveRefactoring
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinAwareMoveFilesOrDirectoriesDialog
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinAwareMoveFilesOrDirectoriesModel
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
class KotlinMoveFilesOrDirectoriesHandler : MoveFilesOrDirectoriesHandler() {
private fun adjustElements(elements: Array<out PsiElement>): Array<PsiFileSystemItem>? {
return elements.map {
when {
it is PsiFile -> it
it is PsiDirectory -> it
it is PsiClass && it.containingClass == null -> it.containingFile
it is KtClassOrObject && it.parent is KtFile -> it.parent as KtFile
else -> return null
}
}.toTypedArray()
}
override fun canMove(elements: Array<out PsiElement>, targetContainer: PsiElement?, reference: PsiReference?): Boolean {
val adjustedElements = adjustElements(elements) ?: return false
if (adjustedElements.none { it is KtFile }) return false
return super.canMove(adjustedElements, targetContainer, reference)
}
override fun adjustForMove(
project: Project,
sourceElements: Array<out PsiElement>,
targetElement: PsiElement?
): Array<PsiFileSystemItem>? {
return adjustElements(sourceElements)
}
override fun doMove(project: Project, elements: Array<out PsiElement>, targetContainer: PsiElement?, callback: MoveCallback?) {
if (!(targetContainer == null || targetContainer is PsiDirectory || targetContainer is PsiDirectoryContainer)) return
val adjustedElementsToMove = adjustForMove(project, elements, targetContainer)?.toList() ?: return
val targetDirectory = MoveFilesOrDirectoriesUtil.resolveToDirectory(project, targetContainer)
if (targetContainer != null && targetDirectory == null) return
val initialTargetDirectory = MoveFilesOrDirectoriesUtil.getInitialTargetDirectory(targetDirectory, elements)
val isTestUnitMode = isUnitTestMode()
if (isTestUnitMode && initialTargetDirectory !== null) {
KotlinAwareMoveFilesOrDirectoriesModel(
project,
adjustedElementsToMove,
initialTargetDirectory.virtualFile.presentableUrl,
updatePackageDirective = true,
searchReferences = true,
moveCallback = callback
).run {
project.executeCommand(MoveHandler.getRefactoringName()) {
with(computeModelResult()) {
if (!isTestUnitMode) {
logFusForMoveRefactoring(
elementsCount,
entityToMove,
destination,
true,
processor
)
} else {
processor.run()
}
}
}
}
return
}
KotlinAwareMoveFilesOrDirectoriesDialog(project, initialTargetDirectory, adjustedElementsToMove, callback).show()
}
override fun tryToMove(
element: PsiElement,
project: Project,
dataContext: DataContext?,
reference: PsiReference?,
editor: Editor?
): Boolean {
if (element is KtLightClassForFacade) {
doMove(project, element.files.toTypedArray(), dataContext?.getData(LangDataKeys.TARGET_PSI_ELEMENT), null)
return true
}
return super.tryToMove(element, project, dataContext, reference, editor)
}
}
| apache-2.0 | 68529792f1b57fb4d9a11e5686e9207a | 43.859813 | 158 | 0.668125 | 5.839416 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/util/span/SpanOptions.kt | 1 | 5026 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.sinyuk.fanfou.util.span
import android.annotation.TargetApi
import android.content.Context
import android.graphics.BlurMaskFilter
import android.os.Build
import android.text.Layout
import android.text.style.*
import java.util.*
/**
* Created by james on 13/10/15.
*/
class SpanOptions {
val listSpan: MutableList<Any> = ArrayList()
/**
* 下划线
*
* @return
*/
fun addUnderlineSpan(): SpanOptions {
val span = UnderlineSpan()
listSpan.add(span)
return this
}
fun addBulletSpan(gapWidth: Int, color: Int): SpanOptions {
val span = BulletSpan(gapWidth, color)
listSpan.add(span)
return this
}
/**
* URL效果
* 需要实现textView.setMovementMethod(LinkMovementMethod.getInstance());
*
* @param url 格式为:电话:tel:18721850636,邮箱:mailto:[email protected],网站:http://www.baidu.com,短信:mms:4155551212,彩信:mmsto:18721850636,地图:geo:38.899533,-77.036476
* @return
*/
fun addURLSpan(url: String): SpanOptions {
val Urlspan = URLSpan(url)
listSpan.add(Urlspan)
return this
}
fun addQuoteSpan(color: Int): SpanOptions {
val span = QuoteSpan(color)
listSpan.add(span)
return this
}
fun addAlignmentSpan(align: Layout.Alignment): SpanOptions {
val span = AlignmentSpan.Standard(align)
listSpan.add(span)
return this
}
fun addStrikethroughSpan(): SpanOptions {
val span = StrikethroughSpan()
listSpan.add(span)
return this
}
fun addBackgroundColorSpan(color: Int): SpanOptions {
val span = BackgroundColorSpan(color)
listSpan.add(span)
return this
}
/**
* @param density
* @param style BlurMaskFilter.Blur.NORMAL
* @return
*/
fun addMaskFilterSpan(density: Float, style: BlurMaskFilter.Blur): SpanOptions {
val span = MaskFilterSpan(BlurMaskFilter(density, style))
listSpan.add(span)
return this
}
fun addSubscriptSpan(): SpanOptions {
val span = SubscriptSpan()
listSpan.add(span)
return this
}
fun addSuperscriptSpan(): SpanOptions {
val span = SuperscriptSpan()
listSpan.add(span)
return this
}
/**
* @param style Typeface.BOLD | Typeface.ITALIC
* @return
*/
fun addStyleSpan(style: Int): SpanOptions {
val span = StyleSpan(style)
listSpan.add(span)
return this
}
fun addAbsoluteSizeSpan(size: Int, dip: Boolean): SpanOptions {
val span = AbsoluteSizeSpan(size, dip)
listSpan.add(span)
return this
}
/**
* 同比放大索小
*
* @return
*/
fun addRelativeSizeSpan(proportion: Float): SpanOptions {
val span = RelativeSizeSpan(proportion)
listSpan.add(span)
return this
}
fun addTextAppearanceSpan(context: Context, appearance: Int): SpanOptions {
val span = TextAppearanceSpan(context, appearance)
listSpan.add(span)
return this
}
/**
* @param locale Locale.CHINESE
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
fun addLocaleSpan(locale: Locale): SpanOptions {
val span = LocaleSpan(locale)
listSpan.add(span)
return this
}
fun addScaleXSpan(proportion: Float): SpanOptions {
val span = ScaleXSpan(proportion)
listSpan.add(span)
return this
}
/**
* @param typeface serif
* @return
*/
fun addTypefaceSpan(typeface: String): SpanOptions {
val span = TypefaceSpan(typeface)
listSpan.add(span)
return this
}
fun addImageSpan(context: Context, imgId: Int): SpanOptions {
val span = ImageSpan(context, imgId)
listSpan.add(span)
return this
}
/**
* 文本颜色
*
* @return
*/
fun addForegroundColor(color: Int): SpanOptions {
val span = ForegroundColorSpan(color)
listSpan.add(span)
return this
}
/**
* 自定义Span
*
* @param object
* @return
*/
fun addSpan(span: Any): SpanOptions {
listSpan.add(span)
return this
}
}
| mit | dda25238daddeda51a819f88df2763cf | 23.176471 | 159 | 0.612328 | 4.116861 | false | false | false | false |
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt | 1 | 2249 | package eu.kanade.tachiyomi.network
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import rx.Producer
import rx.Subscription
import java.util.concurrent.atomic.AtomicBoolean
fun Call.asObservable(): Observable<Response> {
return Observable.unsafeCreate { subscriber ->
// Since Call is a one-shot type, clone it for each new subscriber.
val call = clone()
// Wrap the call in a helper which handles both unsubscription and backpressure.
val requestArbiter = object : AtomicBoolean(), Producer, Subscription {
override fun request(n: Long) {
if (n == 0L || !compareAndSet(false, true)) return
try {
val response = call.execute()
if (!subscriber.isUnsubscribed) {
subscriber.onNext(response)
subscriber.onCompleted()
}
} catch (error: Exception) {
if (!subscriber.isUnsubscribed) {
subscriber.onError(error)
}
}
}
override fun unsubscribe() {
call.cancel()
}
override fun isUnsubscribed(): Boolean {
return call.isCanceled
}
}
subscriber.add(requestArbiter)
subscriber.setProducer(requestArbiter)
}
}
fun Call.asObservableSuccess(): Observable<Response> {
return asObservable().doOnNext { response ->
if (!response.isSuccessful) {
response.close()
throw Exception("HTTP error ${response.code()}")
}
}
}
fun OkHttpClient.newCallWithProgress(request: Request, listener: ProgressListener): Call {
val progressClient = newBuilder()
.cache(null)
.addNetworkInterceptor { chain ->
val originalResponse = chain.proceed(chain.request())
originalResponse.newBuilder()
.body(ProgressResponseBody(originalResponse.body()!!, listener))
.build()
}
.build()
return progressClient.newCall(request)
} | apache-2.0 | e2c4d2c5e327f3f315f821ca5e5e09ac | 31.142857 | 90 | 0.571365 | 5.40625 | false | false | false | false |
sg26565/hott-transmitter-config | HoTT-Model/src/main/kotlin/de/treichels/hott/model/enums/ReceiverType.kt | 1 | 2830 | /**
* HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package de.treichels.hott.model.enums
import de.treichels.hott.util.get
import java.util.*
/**
* @author Oliver Treichel <[email protected]>
*/
enum class ReceiverType(override val productCode: Int = 0, override val orderNo: String = "", val id: Int = 0, val hasGyro: Boolean = false, val hasVario: Boolean = false, override val category: String = ReceiverType.category, override val baudRate: Int = 19200) : Registered<ReceiverType> {
falcon12(16007900, "S1035", 0x35, true),
falcon12_plus(16008700, "S1034", 0x34, true),
gr4(16005600, "33502"),
gr8(16005700, "33504"),
gr10c(0, "S1029", 0x3d, true),
gr12(16003500, "33506"),
gr12l(16003510, "S1012"),
gr12l_sumd(16003540, "S1037"),
gr12L_sumd_div_pcb(16003550, "S1045"),
gr12L_sumd_div(16003550, "S1046"),
gr12L_sumd_div_2(16003550, "S1051"),
gr12sc(0, "33566", 0x91),
gr12sh(0, "33565", 0x91),
gr12sh_3xg(16006000, "33575", 0x75, true),
gr12_3xg(16005400, "33576", 0x76, true),
gr12_3xg_vario(16005500, "33577", 0x77, true, true),
gr12s(16003400, "33505"),
gr16(16003100, "33508"),
gr16l(16003112, "S1021"),
gr18(16006100, "33579", 0x79, true, true),
gr18c(16006160, "S1019", 0x19, true),
gr24(16003200, "33512"),
gr24l(16003201, "S1022"),
gr24pro(16005800, "33583", 0x97, true, true),
gr32(16004000, "33516"),
gr32l(16004020, "S1023"),
gr18_alpha(19000710, "16520", 0x79, true, true),
gr18c_alpha(19001000, "16530", 0x19, true),
heim3d(16006900, "16100.86", 0x3d, true),
aiocopterfc(0, "S1038", 0x38, true);
override fun toString(): String = ResourceBundle.getBundle(javaClass.name)[name] + if (orderNo.isNotEmpty()) " ($orderNo)" else ""
companion object {
fun forProductCode(productCode: Int): ReceiverType? = values().firstOrNull { s -> s.productCode == productCode }
fun forId(id: Int): ReceiverType? = values().firstOrNull { s -> s.id == id }
fun forOrderNo(orderNo: String): ReceiverType? = values().firstOrNull { s -> s.orderNo == orderNo }
const val category = "HoTT_Receiver"
}
}
| lgpl-3.0 | 68eec5ab6ac1a85c18138781ad88b0ee | 45.393443 | 291 | 0.677032 | 3.066089 | false | false | false | false |
aosp-mirror/platform_frameworks_support | navigation/safe-args-generator/src/tests/kotlin/androidx/navigation/safe/args/generator/NavGeneratorTest.kt | 1 | 1841 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.safe.args.generator
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.io.File
@RunWith(JUnit4::class)
class NavGeneratorTest {
@Suppress("MemberVisibilityCanBePrivate")
@get:Rule
val workingDir = TemporaryFolder()
@Test
fun test() {
val output = generateSafeArgs("foo", "foo.flavor",
testData("naive_test.xml"), workingDir.root)
val javaNames = output.files
val expectedSet = setOf(
"androidx.navigation.testapp.MainFragmentDirections",
"foo.flavor.NextFragmentDirections",
"androidx.navigation.testapp.MainFragmentArgs",
"foo.flavor.NextFragmentArgs"
)
assertThat(output.errors.isEmpty(), `is`(true))
assertThat(javaNames.toSet(), `is`(expectedSet))
javaNames.forEach { name ->
val file = File(workingDir.root, "${name.replace('.', File.separatorChar)}.java")
assertThat(file.exists(), `is`(true))
}
}
} | apache-2.0 | c7bd2a1693a078288d48f2fc6535346d | 33.754717 | 93 | 0.685497 | 4.352246 | false | true | false | false |
BlackBoxVision/mvp-helpers | library/src/main/java/io/blackbox_vision/mvphelpers/ui/loader/PresenterLoader.kt | 1 | 1133 | package io.blackbox_vision.mvphelpers.ui.loader
import android.content.Context
import android.support.v4.content.Loader
import io.blackbox_vision.mvphelpers.logic.factory.PresenterFactory
import io.blackbox_vision.mvphelpers.logic.presenter.BasePresenter
class PresenterLoader<P : BasePresenter<*>> constructor(context: Context, private val factory: PresenterFactory<P>) : Loader<P>(context) {
private var presenter: P? = null
override fun onStartLoading() {
super.onStartLoading()
if (null != presenter) {
deliverResult(presenter)
}
forceLoad()
}
override fun onForceLoad() {
super.onForceLoad()
presenter = factory.create()
deliverResult(presenter)
}
override fun onReset() {
super.onReset()
if (null != presenter) {
presenter!!.detachView()
presenter = null
}
}
companion object {
fun <P : BasePresenter<*>> newInstance(context: Context, factory: PresenterFactory<P>): PresenterLoader<P> {
return PresenterLoader(context, factory)
}
}
}
| mit | 014e94c68a763b186796807a5d9f2cf8 | 24.177778 | 138 | 0.647838 | 4.532 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/speakers/SpeakerDao.kt | 2 | 682 | package org.fossasia.openevent.general.speakers
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy.REPLACE
import androidx.room.Query
import io.reactivex.Flowable
import io.reactivex.Single
@Dao
interface SpeakerDao {
@Insert(onConflict = REPLACE)
fun insertSpeakers(speakers: List<Speaker>)
@Insert(onConflict = REPLACE)
fun insertSpeaker(speaker: Speaker)
@Query("SELECT * from Speaker WHERE id = :id")
fun getSpeaker(id: Long): Flowable<Speaker>
@Query("SELECT * FROM speaker WHERE email = :email AND event = :eventId")
fun getSpeakerByEmailAndEvent(email: String, eventId: Long): Single<Speaker>
}
| apache-2.0 | c08157799e4e8d1ada49c87a089d60a9 | 27.416667 | 80 | 0.755132 | 4.059524 | false | false | false | false |
jdigger/gradle-defaults | src/main/kotlin/com/mooregreatsoftware/gradle/util/xml/XmlUtils.kt | 1 | 3479 | /*
* Copyright 2014-2017 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 com.mooregreatsoftware.gradle.util.xml
import groovy.util.Node
import groovy.util.NodeList
import java.util.Collections.emptyMap
fun NodeList.findByAttribute(attrName: String, attrValue: String, nodeCreator: () -> Node): Node {
@Suppress("UNCHECKED_CAST")
return (this as Iterable<Node>).find { it.attributeMatches(attrName, attrValue) } ?: nodeCreator()
}
fun Node.getOrCreate(elementName: String, nodeCreator: () -> Node): Node {
@Suppress("UNCHECKED_CAST")
return (this.children() as Iterable<Node>).find { it.name() == elementName } ?: nodeCreator()
}
private fun Node.attributeMatches(attrName: String, attrValue: String): Boolean {
val attr = this.attributes()[attrName] as String?
return attr != null && attr.equals(attrValue, ignoreCase = true)
}
private fun noNodes(): List<NodeBuilder> = listOf()
fun n(name: String, attrs: Map<String, String>) = NodeBuilder(name, attrs, null, noNodes())
fun n(name: String, textVal: String): NodeBuilder = NodeBuilder(name, mapOf(), textVal, listOf())
fun n(name: String, children: Iterable<NodeBuilder>) = NodeBuilder(name, emptyMap(), null, children)
fun n(name: String) = NodeBuilder(name, emptyMap(), null, noNodes())
fun n(name: String, attrs: Map<String, String>?, child: NodeBuilder) = NodeBuilder(name, attrs, null, listOf(child))
fun n(name: String, attrs: Map<String, String>?, children: Iterable<NodeBuilder>) = NodeBuilder(name, attrs, null, children)
fun n(name: String, child: NodeBuilder) = NodeBuilder(name, emptyMap(), null, listOf(child))
fun Node.appendChild(nodeName: String) = this.appendChildren(nodeName, null, listOf())
fun Node.appendChild(nodeName: String, attrs: Map<String, String>) = this.appendChildren(nodeName, attrs, listOf())
fun Node.appendChild(nodeName: String, child: NodeBuilder) = this.appendChild(nodeName, null, child)
fun Node.appendChild(nodeName: String, attrs: Map<String, String>?, child: NodeBuilder) = this.appendChildren(nodeName, attrs, null, child)
fun Node.appendChildren(nodeName: String, attrs: Map<String, String>?, textVal: String?, child: NodeBuilder) = this.appendChildren(nodeName, attrs, textVal, listOf(child))
fun Node.appendChildren(nodeName: String, children: Iterable<NodeBuilder>) = this.appendChildren(nodeName, null, null, children)
fun Node.appendChildren(nodeName: String, attrs: Map<String, String>?, children: Iterable<NodeBuilder>) = this.appendChildren(nodeName, attrs, null, children)
fun Node.appendChildren(nodeName: String, attrs: Map<String, String>?, textVal: String?, children: Iterable<NodeBuilder>): Node {
val node = when (textVal) {
null -> this.appendNode(nodeName, attrs as Map<*, *>?)
else -> this.appendNode(nodeName, attrs as Map<*, *>?, textVal)
}
children.forEach { node.appendChildren(it.name, it.attrs, it.textVal, it.children) }
return node
}
| apache-2.0 | 72a36c7c623460127df268e31237977e | 53.359375 | 171 | 0.734981 | 3.957907 | false | false | false | false |
rjhdby/motocitizen | Motocitizen/src/motocitizen/user/User.kt | 1 | 618 | package motocitizen.user
object User {
private var role = Role.RO
var name = ""
var id = 0
var isAuthorized = false
val roleName: String
get() = role.text
fun isReadOnly() = role == Role.RO
fun isModerator() = role in arrayOf(Role.MODERATOR, Role.DEVELOPER)
fun notIsModerator() = !isModerator()
fun logout() {
name = ""
role = Role.RO
id = 0
isAuthorized = false
}
fun authenticate(id: Int, name: String, role: Role) {
this.id = id
this.name = name
this.role = role
isAuthorized = true
}
}
| mit | 413f95ed3f46fd4e04624b2a4ca02e1b | 18.935484 | 71 | 0.559871 | 4.065789 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/format/Pbp.kt | 1 | 1929 | package com.soywiz.kpspemu.format
import com.soywiz.korio.error.*
import com.soywiz.korio.stream.*
class Pbp(val version: Int, val base: AsyncStream, val streams: List<AsyncStream>) {
val streamsByName = NAMES.zip(streams).toMap()
val PARAM_SFO get() = this[Pbp.PARAM_SFO]!!
val ICON0_PNG get() = this[Pbp.ICON0_PNG]!!
val ICON1_PMF get() = this[Pbp.ICON1_PMF]!!
val PIC0_PNG get() = this[Pbp.PIC0_PNG]!!
val PIC1_PNG get() = this[Pbp.PIC1_PNG]!!
val SND0_AT3 get() = this[Pbp.SND0_AT3]!!
val PSP_DATA get() = this[Pbp.PSP_DATA]!!
val PSAR_DATA get() = this[Pbp.PSAR_DATA]!!
companion object {
const val PBP_MAGIC = 0x50425000
const val PARAM_SFO = "param.sfo"
const val ICON0_PNG = "icon0.png"
const val ICON1_PMF = "icon1.pmf"
const val PIC0_PNG = "pic0.png"
const val PIC1_PNG = "pic1.png"
const val SND0_AT3 = "snd0.at3"
const val PSP_DATA = "psp.data"
const val PSAR_DATA = "psar.data"
val NAMES = listOf(PARAM_SFO, ICON0_PNG, ICON1_PMF, PIC0_PNG, PIC1_PNG, SND0_AT3, PSP_DATA, PSAR_DATA)
suspend fun check(s: AsyncStream): Boolean {
return s.duplicate().readS32_le() == PBP_MAGIC
}
suspend operator fun invoke(s: AsyncStream): Pbp = load(s)
suspend fun load(s: AsyncStream): Pbp {
val magic = s.readS32_le()
if (magic != PBP_MAGIC) invalidOp("Not a PBP file")
val version = s.readS32_le()
val offsets = s.readIntArray_le(8).toList() + listOf(s.size().toInt())
val streams =
(0 until (offsets.size - 1)).map { s.sliceWithBounds(offsets[it].toLong(), offsets[it + 1].toLong()) }
return Pbp(version, s, streams)
}
}
operator fun get(name: String) = streamsByName[name.toLowerCase()]?.duplicate()
operator fun get(index: Int) = streams[index]
}
| mit | 2c4eaf697b6d9efb671f397951a8e945 | 36.823529 | 118 | 0.601866 | 3.157119 | false | false | false | false |
wiryls/HomeworkCollectionOfMYLS | 2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/fragment/PersonFragment.kt | 1 | 3772 | package com.myls.odes.fragment
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.view.*
import com.myls.odes.R
import com.myls.odes.activity.MainActivity
import com.myls.odes.application.AnApplication
import com.myls.odes.data.UserList
import com.myls.odes.request.QueryUser
import com.myls.odes.service.PullJsonService
import com.myls.odes.utility.Storage
import kotlinx.android.synthetic.main.fragment_person.*
import kotlinx.android.synthetic.main.fragment_person.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class PersonFragment :
Fragment(),
SwipeRefreshLayout.OnRefreshListener
{
private lateinit var saver: Storage
private lateinit var useri: UserList.Info
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(activity.application as AnApplication).let {
saver = it.saver
useri = it.userlist.list.firstOrNull()?.info
?: return@let post(MainActivity.InvalidDataEvent("UserList is empty"))
onUpdateUserLayout()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, saved: Bundle?)
= inflater.inflate(R.layout.fragment_person, container, false)!!
.also {
it.refresh_layout.setOnRefreshListener(this)
}
override fun onRefresh() {
with(activity) {
Intent(Intent.ACTION_SYNC, null, this, PullJsonService::class.java).apply {
putExtra(PullJsonService.Contract.REQUEST.name, QueryUser.Request(useri.stid))
startService(this)
}
}
}
private fun onUpdateUserLayout() {
useri.let {
with(basic_layout) {
this.name_view.text = it.name
this.stid_view.text = it.stid
}
with(detail_layout) {
this. gender_view.text = it.gender
this. grade_view.text = it.grade
this.location_view.text = it.location
}
with(room_layout) {
this. room_view.text = it.room
this.building_view.text = it.building
if (it.room.isBlank() && it.building.isBlank())
visibility = View.GONE
}
}
}
// 关于 Fragment 的生命周期
// (https://developer.android.com/guide/components/fragments.html#Creating)
@Subscribe(threadMode = ThreadMode.MAIN)
fun onUserUpdated(event: MainActivity.UserInfoUpdatedEvent) {
if (event.done) {
useri = event.user
onUpdateUserLayout()
}
with(refresh_layout) {
isRefreshing = false
}
}
override fun onStart() {
super.onStart()
EVENT_BUS.register(this)
}
override fun onStop() {
EVENT_BUS.unregister(this)
super.onStop()
}
companion object {
private val TAG = PersonFragment::class.java.canonicalName!!
private val EVENT_BUS = EventBus.getDefault()
private fun <T> post(data: T) = EVENT_BUS.post(data)
// [Android Fragments Tutorial: An Introduction with Kotlin]
// (https://www.raywenderlich.com/169885/android-fragments-tutorial-introduction-2)
// [Best practice for instantiating a new Android Fragment]
// (https://stackoverflow.com/q/9245408)
fun create() = PersonFragment().apply {
// 由于使用了近似全局的 Application,因此这里不需要通过 arguments: Bundle 传递参数
}
}
}
| mit | a28f2210a4619c9775787cfd72759964 | 30.709402 | 94 | 0.638544 | 4.289017 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/entity/info/Recommendation.kt | 2 | 2562 | package me.proxer.library.entity.info
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import me.proxer.library.entity.ProxerIdItem
import me.proxer.library.enums.Category
import me.proxer.library.enums.FskConstraint
import me.proxer.library.enums.License
import me.proxer.library.enums.MediaState
import me.proxer.library.enums.Medium
import me.proxer.library.internal.adapter.DelimitedEnumSet
import me.proxer.library.internal.adapter.DelimitedStringSet
import me.proxer.library.internal.adapter.NumberBasedBoolean
/**
* Entity holding the data associated with a recommendation.
*
* @property name The name.
* @property genres The genres.
* @property fskConstraints The fsk ratings.
* @property description The description.
* @property medium The medium.
* @property episodeAmount The amount of episodes, this entry has. They do not necessarily have to be uploaded.
* @property state The current state.
* @property ratingSum The sum of all ratings.
* @property ratingAmount The clicks on this entry, in this season.
* @property category The category.
* @property license The type of license.
* @property positiveVotes The amount of positive votes.
* @property negativeVotes The amount of negative votes.
* @property negativeVotes The vote of the user if present when calling the respective api.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = true)
data class Recommendation(
@Json(name = "id") override val id: String,
@Json(name = "name") val name: String,
@field:DelimitedStringSet(valuesToKeep = ["Slice of Life"]) @Json(name = "genre") val genres: Set<String>,
@field:DelimitedEnumSet @Json(name = "fsk") val fskConstraints: Set<FskConstraint>,
@Json(name = "description") val description: String,
@Json(name = "medium") val medium: Medium,
@Json(name = "count") val episodeAmount: Int,
@Json(name = "state") val state: MediaState,
@Json(name = "rate_sum") val ratingSum: Int,
@Json(name = "rate_count") val ratingAmount: Int,
@Json(name = "clicks") val clicks: Int,
@Json(name = "kat") val category: Category,
@Json(name = "license") val license: License,
@Json(name = "count_positive") val positiveVotes: Int,
@Json(name = "count_negative") val negativeVotes: Int,
@field:NumberBasedBoolean @Json(name = "positive") val userVote: Boolean?
) : ProxerIdItem {
/**
* Returns the average of all ratings.
*/
val rating = when {
ratingAmount <= 0 -> 0f
else -> ratingSum.toFloat() / ratingAmount.toFloat()
}
}
| gpl-3.0 | 8801d057a5b5e3698fc1031be201a1c2 | 40.322581 | 111 | 0.725605 | 3.864253 | false | false | false | false |
kmruiz/sonata | middle-end/src/main/kotlin/io/sonatalang/snc/middleEnd/infrastructure/types/TypeResolver.kt | 1 | 1474 | package io.sonatalang.snc.middleEnd.infrastructure.types
import io.sonatalang.snc.middleEnd.domain.node.*
import io.sonatalang.snc.middleEnd.infrastructure.TreeTraverser
class TypeResolver(val entityRegistry: EntityListener) : TreeTraverser {
override fun traverse(node: Node): Node = when (node) {
is ScriptNode -> ScriptNode(node.currentNode, node.nodes.map { traverse(it) })
is LetConstantNode -> when {
node.value is TermNode && node.type == null -> LetConstantNode(node.name, node.value.type, node.value)
else -> node
}
is LetFunctionNode -> {
val body = traverse(node.body) as TypedNode
LetFunctionNode(node.name, node.parameters.map { ParameterNode(it.name, resolveType(it.type)) }, returnTypeOrBodyType(node), body)
}
is FunctionCallNode -> FunctionCallNode(node.receiver, node.parameters, "Boolean")
is TermNode -> when {
node.type == null -> TermNode(node.name, entityRegistry.resolveTypeOfConstant(node.name).qualifiedName())
else -> node
}
else -> node
}
private fun returnTypeOrBodyType(fn: LetFunctionNode): String {
if (fn.returnType != null) {
return resolveType(fn.returnType)
} else {
return fn.body.getType(entityRegistry).qualifiedName()
}
}
private fun resolveType(name: String) = entityRegistry.resolveTypeByName(name).qualifiedName()
} | gpl-2.0 | be0df6bf50829fcdec5d399395d42cdd | 42.382353 | 142 | 0.662144 | 4.309942 | false | false | false | false |
facebook/fresco | vito/core-impl/src/main/java/com/facebook/fresco/vito/core/impl/KFrescoVitoDrawable.kt | 1 | 5592 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.core.impl
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.drawable.Drawable
import com.facebook.common.closeables.AutoCleanupDelegate
import com.facebook.datasource.DataSource
import com.facebook.drawee.drawable.VisibilityCallback
import com.facebook.fresco.vito.core.FrescoDrawableInterface
import com.facebook.fresco.vito.core.VitoImagePerfListener
import com.facebook.fresco.vito.core.VitoImageRequest
import com.facebook.fresco.vito.listener.ImageListener
import com.facebook.fresco.vito.renderer.DrawableImageDataModel
import java.io.Closeable
import java.io.IOException
class KFrescoVitoDrawable(val _imagePerfListener: VitoImagePerfListener = NopImagePerfListener()) :
Drawable(), FrescoDrawableInterface {
var _imageId: Long = 0
var _isLoading: Boolean = false
override var callerContext: Any? = null
var _visibilityCallback: VisibilityCallback? = null
var _fetchSubmitted: Boolean = false
val listenerManager: CombinedImageListenerImpl = CombinedImageListenerImpl()
override var extras: Any? = null
var viewportDimensions: Rect? = null
var dataSource: DataSource<out Any>? by DataSourceCleanupDelegate()
val releaseState = ImageReleaseScheduler.createReleaseState(this)
private var hasBoundsSet = false
override var imageRequest: VitoImageRequest? = null
private val closeableCleanupFunction: (Closeable) -> Unit = {
ImageReleaseScheduler.cancelAllReleasing(this)
try {
it.close()
} catch (e: IOException) {
// swallow
}
}
var closeable: Closeable? by AutoCleanupDelegate(null, closeableCleanupFunction)
override var refetchRunnable: Runnable? = null
override val imageId: Long
get() = _imageId
override val imagePerfListener: VitoImagePerfListener
get() = _imagePerfListener
override fun setMutateDrawables(mutateDrawables: Boolean) {
// No-op since we never mutate Drawables
}
override val actualImageDrawable: Drawable?
get() {
return when (val model = actualImageLayer.getDataModel()) {
is DrawableImageDataModel -> model.drawable
else -> null
}
}
override fun hasImage(): Boolean = actualImageLayer.getDataModel() != null
fun setFetchSubmitted(fetchSubmitted: Boolean) {
_fetchSubmitted = fetchSubmitted
}
override val isFetchSubmitted: Boolean
get() = _fetchSubmitted
override fun setVisibilityCallback(visibilityCallback: VisibilityCallback?) {
_visibilityCallback = visibilityCallback
}
override var imageListener: ImageListener?
get() = listenerManager.imageListener
set(value) {
listenerManager.imageListener = value
}
override fun setOverlayDrawable(drawable: Drawable?): Drawable? {
overlayImageLayer.apply {
configure(
dataModel = if (drawable == null) null else DrawableImageDataModel(drawable),
roundingOptions = null,
borderOptions = null)
}
return drawable
}
override fun setVisible(visible: Boolean, restart: Boolean): Boolean {
_visibilityCallback?.onVisibilityChange(visible)
return super.setVisible(visible, restart)
}
fun reset() {
imageRequest?.let { listenerManager.onRelease(imageId, it, obtainExtras()) }
imagePerfListener.onImageRelease(this)
ImageReleaseScheduler.cancelAllReleasing(this)
_imageId = 0
closeable = null
dataSource = null
imageRequest = null
_isLoading = false
callerContext = null
placeholderLayer.reset()
actualImageLayer.reset()
progressLayer?.reset()
overlayImageLayer.reset()
debugOverlayImageLayer?.reset()
hasBoundsSet = false
listenerManager.onReset()
listenerManager.imageListener = null
}
private var drawableAlpha: Int = 255
private var drawableColorFilter: ColorFilter? = null
val callbackProvider: (() -> Callback?) = { callback }
val invalidateLayerCallback: (() -> Unit) = { invalidateSelf() }
val placeholderLayer = createLayer()
val actualImageLayer = createLayer()
var progressLayer: ImageLayerDataModel? = null
val overlayImageLayer = createLayer()
var debugOverlayImageLayer: ImageLayerDataModel? = null
override fun draw(canvas: Canvas) {
if (!hasBoundsSet) {
setLayerBounds(bounds)
}
placeholderLayer.draw(canvas)
actualImageLayer.draw(canvas)
progressLayer?.draw(canvas)
overlayImageLayer.draw(canvas)
debugOverlayImageLayer?.draw(canvas)
}
override fun onBoundsChange(bounds: Rect) {
super.onBoundsChange(bounds)
setLayerBounds(bounds)
}
private fun setLayerBounds(bounds: Rect?) {
if (bounds != null) {
placeholderLayer.configure(bounds = bounds)
actualImageLayer.configure(bounds = bounds)
progressLayer?.configure(bounds = bounds)
overlayImageLayer.configure(bounds = bounds)
debugOverlayImageLayer?.configure(bounds = bounds)
hasBoundsSet = true
}
}
override fun setAlpha(alpha: Int) {
drawableAlpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
drawableColorFilter = colorFilter
}
// TODO(T105148151) Calculate opacity based on layers
override fun getOpacity(): Int = PixelFormat.TRANSPARENT
internal fun createLayer() = ImageLayerDataModel(callbackProvider, invalidateLayerCallback)
}
| mit | c438f549530723a10ff32e97b976d66a | 29.725275 | 99 | 0.742132 | 4.695214 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/resolver/KotlinBuildScriptModelRepositoryTest.kt | 3 | 6484 | /*
* 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.resolver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import org.gradle.kotlin.dsl.tooling.models.EditorReport
import org.gradle.kotlin.dsl.tooling.models.KotlinBuildScriptModel
import org.hamcrest.CoreMatchers.nullValue
import org.hamcrest.CoreMatchers.sameInstance
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import java.io.File
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.TimeUnit
import kotlin.coroutines.Continuation
class KotlinBuildScriptModelRepositoryTest {
@Test
fun `cancels older requests before returning response to most recent request`() = runBlockingWithTimeout {
// given:
// Notice the project directory is never written to by the test so its path is immaterial
val projectDir = File("/project-dir")
val scriptFile = File(projectDir, "build.gradle.kts")
/**
* Request accepted into the queue.
*/
val acceptedRequest = Channel<KotlinBuildScriptModelRequest>(3)
/**
* Request taken off the queue awaiting for a response.
*/
val pendingRequest = Channel<KotlinBuildScriptModelRequest>(3)
/**
* Next response to [KotlinBuildScriptModelRepository.fetch].
*/
val nextResponse = ArrayBlockingQueue<KotlinBuildScriptModel>(3)
val subject = object : KotlinBuildScriptModelRepository() {
override fun accept(request: KotlinBuildScriptModelRequest, k: Continuation<KotlinBuildScriptModel?>) {
super.accept(request, k)
acceptedRequest.trySendBlocking(request).getOrThrow()
}
override fun fetch(request: KotlinBuildScriptModelRequest): KotlinBuildScriptModel {
pendingRequest.trySendBlocking(request).getOrThrow()
return nextResponse.poll(defaultTestTimeoutMillis, TimeUnit.MILLISECONDS)!!
}
}
fun newModelRequest() = KotlinBuildScriptModelRequest(projectDir, scriptFile)
fun asyncResponseTo(request: KotlinBuildScriptModelRequest): Deferred<KotlinBuildScriptModel?> = async {
subject.scriptModelFor(request)
}
// when:
val pendingTasks =
(0..2).map { index ->
val request = newModelRequest()
request to asyncResponseTo(request).also {
assertThat(
"Request is accepted",
acceptedRequest.receive(),
sameInstance(request)
)
if (index == 0) {
// wait for the first request to be taken off the queue
// so the remaining requests are received while the request handler is busy
assertThat(
pendingRequest.receive(),
sameInstance(request)
)
}
}
}
// submit the first response
// this response should satisfy the very first request
val resp1 = newModelResponse().also(nextResponse::put)
val (_, asyncResp1) = pendingTasks[0]
assertThat(
asyncResp1.await(),
sameInstance(resp1)
)
// now we expect to receive the most recent request since the last request that got a response,
// that's the last request in our list of pending tasks
val (reqLast, asyncRespLast) = pendingTasks.last()
assertThat(
pendingRequest.receive(),
sameInstance(reqLast)
)
// submit the second (and last) response
val respLast = newModelResponse().also(nextResponse::put)
// upon receiving this response, the request handler will first complete
// any and all outdated requests off the queue by responding with `null`
val (_, asyncResp2) = pendingTasks[1]
assertThat(
asyncResp2.await(),
nullValue()
)
// only then the most recent request will be given its response
assertThat(
asyncRespLast.await(),
sameInstance(respLast)
)
// and no other requests are left to process
assertThat(
withTimeoutOrNull(50) { pendingRequest.receive() },
nullValue()
)
}
private
fun newModelResponse(): KotlinBuildScriptModel = StandardKotlinBuildScriptModel()
data class StandardKotlinBuildScriptModel(
private val classPath: List<File> = emptyList(),
private val sourcePath: List<File> = emptyList(),
private val implicitImports: List<String> = emptyList(),
private val editorReports: List<EditorReport> = emptyList(),
private val exceptions: List<String> = emptyList(),
private val enclosingScriptProjectDir: File? = null
) : KotlinBuildScriptModel {
override fun getClassPath() = classPath
override fun getSourcePath() = sourcePath
override fun getImplicitImports() = implicitImports
override fun getEditorReports() = editorReports
override fun getExceptions() = exceptions
override fun getEnclosingScriptProjectDir() = enclosingScriptProjectDir
}
}
internal
fun runBlockingWithTimeout(timeMillis: Long = defaultTestTimeoutMillis, block: suspend CoroutineScope.() -> Unit) {
runBlocking {
withTimeout(timeMillis, block)
}
}
internal
const val defaultTestTimeoutMillis = 5000L
| apache-2.0 | 09e5ee55a718d26c86829a719700bae5 | 34.823204 | 115 | 0.653763 | 5.476351 | false | false | false | false |
FirebaseExtended/make-it-so-android | app/src/main/java/com/example/makeitso/common/composable/CardComposable.kt | 1 | 2784 | /*
Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.example.makeitso.common.composable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.example.makeitso.common.ext.dropdownSelector
@ExperimentalMaterialApi
@Composable
fun DangerousCardEditor(
@StringRes title: Int,
@DrawableRes icon: Int,
content: String,
modifier: Modifier,
onEditClick: () -> Unit
) {
CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.primary, modifier)
}
@ExperimentalMaterialApi
@Composable
fun RegularCardEditor(
@StringRes title: Int,
@DrawableRes icon: Int,
content: String,
modifier: Modifier,
onEditClick: () -> Unit
) {
CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.onSurface, modifier)
}
@ExperimentalMaterialApi
@Composable
private fun CardEditor(
@StringRes title: Int,
@DrawableRes icon: Int,
content: String,
onEditClick: () -> Unit,
highlightColor: Color,
modifier: Modifier
) {
Card(
backgroundColor = MaterialTheme.colors.onPrimary,
modifier = modifier,
onClick = onEditClick
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(16.dp)
) {
Column(modifier = Modifier.weight(1f)) { Text(stringResource(title), color = highlightColor) }
if (content.isNotBlank()) {
Text(text = content, modifier = Modifier.padding(16.dp, 0.dp))
}
Icon(painter = painterResource(icon), contentDescription = "Icon", tint = highlightColor)
}
}
}
@Composable
@ExperimentalMaterialApi
fun CardSelector(
@StringRes label: Int,
options: List<String>,
selection: String,
modifier: Modifier,
onNewValue: (String) -> Unit
) {
Card(backgroundColor = MaterialTheme.colors.onPrimary, modifier = modifier) {
DropdownSelector(label, options, selection, Modifier.dropdownSelector(), onNewValue)
}
}
| apache-2.0 | 33621366319ff4b0294a48010a00cc43 | 27.408163 | 100 | 0.753951 | 4.231003 | false | false | false | false |
AndroidX/constraintlayout | demoProjects/ExamplesComposeMotionLayout/app/src/main/java/com/example/examplescomposemotionlayout/MotionInLazyColumnDsl.kt | 2 | 4689 | package com.example.examplescomposemotionlayout
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.Dimension
import androidx.constraintlayout.compose.ExperimentalMotionApi
import androidx.constraintlayout.compose.MotionLayout
import androidx.constraintlayout.compose.MotionScene
/**
* A demo of using MotionLayout in a Lazy Column written using DSL Syntax
*/
@OptIn(ExperimentalMotionApi::class)
@Preview(group = "scroll", device = "spec:shape=Normal,width=480,height=800,unit=dp,dpi=440")
@Composable
fun MotionInLazyColumnDsl() {
var scene = MotionScene() {
val title = createRefFor("title")
val image = createRefFor("image")
val icon = createRefFor("icon")
val start1 = constraintSet {
constrain(title) {
centerVerticallyTo(icon)
start.linkTo(icon.end, 16.dp)
}
constrain(image) {
width = Dimension.value(40.dp)
height = Dimension.value(40.dp)
centerVerticallyTo(icon)
end.linkTo(parent.end, 8.dp)
}
constrain(icon) {
top.linkTo(parent.top, 16.dp)
bottom.linkTo(parent.bottom, 16.dp)
start.linkTo(parent.start, 16.dp)
}
}
val end1 = constraintSet {
constrain(title) {
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
scaleX = 0.7f
scaleY = 0.7f
}
constrain(image) {
width = Dimension.matchParent
height = Dimension.value(200.dp)
centerVerticallyTo(parent)
}
constrain(icon) {
top.linkTo(parent.top, 16.dp)
start.linkTo(parent.start, 16.dp)
}
}
transition("default", start1, end1) {}
}
val model = remember { BooleanArray(100) }
LazyColumn() {
items(100) {
// Text(text = "item $it", modifier = Modifier.padding(4.dp))
Box(modifier = Modifier.padding(3.dp)) {
var animateToEnd by remember { mutableStateOf(model[it]) }
val progress = remember { Animatable(if (model[it]) 1f else 0f) }
LaunchedEffect(animateToEnd) {
progress.animateTo(
if (animateToEnd) 1f else 0f,
animationSpec = tween(700)
)
}
MotionLayout(
modifier = Modifier
.background(Color(0xFF331B1B))
.fillMaxWidth()
.padding(1.dp),
motionScene = scene,
progress = progress.value
) {
Image(
modifier = Modifier.layoutId("image"),
painter = painterResource(R.drawable.bridge),
contentDescription = null,
contentScale = ContentScale.Crop
)
Image(
modifier = Modifier
.layoutId("icon")
.clickable {
animateToEnd = !animateToEnd
model[it] = animateToEnd;
},
painter = painterResource(R.drawable.menu),
contentDescription = null
)
Text(
modifier = Modifier.layoutId("title"),
text = "San Francisco $it",
fontSize = 30.sp,
color = Color.White
)
}
}
}
}
}
| apache-2.0 | f2e2b1a50cb8b4e807e40262dcdfbd97 | 35.632813 | 93 | 0.544039 | 5.113413 | false | false | false | false |
arcao/Geocaching4Locus | app/src/main/java/com/arcao/geocaching4locus/import_bookmarks/fragment/BookmarkListFragment.kt | 1 | 5399 | package com.arcao.geocaching4locus.import_bookmarks.fragment
import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.arcao.geocaching4locus.R
import com.arcao.geocaching4locus.base.paging.handleErrors
import com.arcao.geocaching4locus.base.util.exhaustive
import com.arcao.geocaching4locus.base.util.invoke
import com.arcao.geocaching4locus.base.util.withObserve
import com.arcao.geocaching4locus.databinding.FragmentBookmarkListBinding
import com.arcao.geocaching4locus.error.hasPositiveAction
import com.arcao.geocaching4locus.import_bookmarks.ImportBookmarkViewModel
import com.arcao.geocaching4locus.import_bookmarks.adapter.BookmarkListAdapter
import com.arcao.geocaching4locus.import_bookmarks.widget.decorator.MarginItemDecoration
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class BookmarkListFragment : BaseBookmarkFragment() {
private val viewModel by viewModel<BookmarkListViewModel>()
private val activityViewModel by sharedViewModel<ImportBookmarkViewModel>()
private val toolbar get() = (activity as? AppCompatActivity)?.supportActionBar
private val adapter = BookmarkListAdapter { bookmarkList, importAll ->
if (importAll) {
viewModel.importAll(bookmarkList)
} else {
viewModel.chooseBookmarks(bookmarkList)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
toolbar?.subtitle = null
val binding = DataBindingUtil.inflate<FragmentBookmarkListBinding>(
inflater,
R.layout.fragment_bookmark_list,
container,
false
)
binding.lifecycleOwner = viewLifecycleOwner
binding.vm = viewModel
binding.isLoading = true
binding.list.apply {
adapter = [email protected]
layoutManager = LinearLayoutManager(context)
addItemDecoration(MarginItemDecoration(context, R.dimen.cardview_space))
}
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.RESUMED) {
viewModel.pagerFlow.collectLatest { data ->
adapter.submitData(data)
}
}
}
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.RESUMED) {
adapter.loadStateFlow.collect { state ->
val isListEmpty =
state.refresh is LoadState.NotLoading && adapter.itemCount == 0
binding.isEmpty = isListEmpty
binding.isLoading = state.source.refresh is LoadState.Loading
state.handleErrors(viewModel::handleLoadError)
}
}
}
viewModel.action.withObserve(viewLifecycleOwner, ::handleAction)
viewModel.progress.withObserve(viewLifecycleOwner) { state ->
activityViewModel.progress(state)
}
return binding.root
}
@Suppress("IMPLICIT_CAST_TO_ANY")
fun handleAction(action: BookmarkListAction) {
when (action) {
is BookmarkListAction.Error -> {
startActivity(action.intent)
requireActivity().apply {
setResult(
if (action.intent.hasPositiveAction()) {
Activity.RESULT_OK
} else {
Activity.RESULT_CANCELED
}
)
finish()
}
}
is BookmarkListAction.Finish -> {
startActivity(action.intent)
requireActivity().apply {
setResult(Activity.RESULT_OK)
finish()
}
}
BookmarkListAction.Cancel -> {
requireActivity().apply {
setResult(Activity.RESULT_CANCELED)
finish()
}
}
is BookmarkListAction.ChooseBookmarks -> {
activityViewModel.chooseBookmarks(action.geocacheList)
}
is BookmarkListAction.LoadingError -> {
startActivity(action.intent)
requireActivity().apply {
if (adapter.itemCount == 0) {
setResult(Activity.RESULT_CANCELED)
finish()
}
}
}
}.exhaustive
}
override fun onProgressCancel(requestId: Int) {
viewModel.cancelProgress()
}
companion object {
fun newInstance() = BookmarkListFragment().apply {
arguments = bundleOf()
}
}
}
| gpl-3.0 | 1ba68a08e6a524dd2f4884ed8eda4493 | 35.727891 | 88 | 0.626042 | 5.618106 | false | false | false | false |
Ch3D/QuickTiles | app/src/main/java/com/ch3d/android/quicktiles/BaseTileService.kt | 1 | 1661 | package com.ch3d.android.quicktiles
import android.content.Intent
import android.graphics.drawable.Icon
import android.net.Uri
import android.provider.Settings
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
/**
* Created by Dmitry on 6/20/2016.
*/
abstract class BaseTileService constructor(defaultState: TileState) : TileService() {
companion object {
const val DEFAULT_VALUE = -1
}
private fun hasWriteSettingsPermission() = Settings.System.canWrite(this)
protected var mCurrentState: TileState = defaultState
override fun onStartListening() {
if (hasWriteSettingsPermission()) {
updateTile(qsTile)
}
}
abstract fun updateTile(tile: Tile)
protected fun updateState(tile: Tile, newState: TileState) {
mCurrentState = newState
setMode(mCurrentState)
tile.apply {
label = getString(mCurrentState.titleResId)
icon = Icon.createWithResource(this@BaseTileService, mCurrentState.drawableId)
state = newState.state
updateTile()
}
}
protected abstract fun setMode(state: TileState): Boolean
override fun onClick() {
if (!hasWriteSettingsPermission()) {
startActivity(Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
.apply {
data = Uri.parse("package:" + applicationContext.packageName)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
})
} else {
onTileClick(qsTile)
}
}
protected abstract fun onTileClick(tile: Tile)
}
| apache-2.0 | 8defd5fe76d6b4889cd4bd8310660cd2 | 28.140351 | 90 | 0.649007 | 4.914201 | false | false | false | false |
Geobert/Efficio | app/src/main/kotlin/fr/geobert/efficio/drag/DepartmentDragHelper.kt | 1 | 3259 | package fr.geobert.efficio.drag
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import com.crashlytics.android.Crashlytics
import fr.geobert.efficio.*
import fr.geobert.efficio.adapter.DepartmentViewHolder
import fr.geobert.efficio.data.*
import fr.geobert.efficio.db.StoreCompositionTable
import java.util.*
class DepartmentDragHelper(val activity: EditDepartmentsActivity,
val depManager: DepartmentManager) :
ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) {
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder): Boolean {
Collections.swap(depManager.departmentsList, viewHolder.adapterPosition,
target.adapterPosition)
depManager.depAdapter.notifyItemMoved(viewHolder.adapterPosition,
target.adapterPosition)
return true
}
private var orig: Float = 0f
private var lastDragTask: DepartmentViewHolder? = null
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
// end of drag n drop, adapter is correctly ordered but not our representation here
val vh = viewHolder as DepartmentViewHolder?
if (vh == null) {
val last = lastDragTask
if (last != null) {
last.cardView.cardElevation = orig
updateDepWeight(last)
StoreCompositionTable.updateDepWeight(activity, last.dep!!)
}
} else {
orig = vh.cardView.cardElevation
vh.cardView.cardElevation = 20.0f
}
lastDragTask = vh
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {
// nothing
}
private fun updateDepWeight(dragged: DepartmentViewHolder) {
val pos = dragged.adapterPosition
val dep = dragged.dep!!
if (depManager.nbDepartment() > 1)
if (pos == 0) { // first
val next = depManager.getDepartment(pos + 1)
if (dep.weight >= next.weight)
dep.weight = next.weight - 1.0
} else if (pos == (depManager.nbDepartment() - 1)) { // last
val prev = depManager.getDepartment(pos - 1)
if (dep.weight <= prev.weight)
dep.weight = prev.weight + 1.0
} else { // between
val next = depManager.getDepartment(pos + 1)
val prev = depManager.getDepartment(pos - 1)
if (dep.weight <= prev.weight || dep.weight >= next.weight) {
dep.weight = (prev.weight + next.weight) / 2.0
if (dep.weight <= prev.weight || dep.weight >= next.weight)
handleDoubleCollision(pos, dep, next, prev)
}
}
}
private fun handleDoubleCollision(pos: Int, dep: Department, next: Department, prev: Department) {
if (!BuildConfig.DEBUG)
Crashlytics.log("double collision occurred for Department!!! handleDoubleCollision")
}
} | gpl-2.0 | 7756585735f72daa43b5c5d59a3c7a77 | 41.337662 | 102 | 0.622584 | 4.799705 | false | false | false | false |
androidx/constraintlayout | demoProjects/ExamplesComposeMotionLayout/app/src/main/java/com/example/examplescomposemotionlayout/CollapsingToolbarDsl.kt | 2 | 4257 | package com.example.examplescomposemotionlayout
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.datasource.LoremIpsum
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.Dimension
import androidx.constraintlayout.compose.ExperimentalMotionApi
import androidx.constraintlayout.compose.MotionLayout
import androidx.constraintlayout.compose.MotionScene
import java.lang.Float.min
/**
* A demo of using MotionLayout as a collapsing Toolbar using the DSL to define the MotionScene
*/
@OptIn(ExperimentalMotionApi::class)
@Preview(group = "scroll", device = "spec:shape=Normal,width=480,height=800,unit=dp,dpi=440")
@Composable
fun ToolBarExampleDsl() {
val scroll = rememberScrollState(0)
val big = 250.dp
val small = 50.dp
var scene = MotionScene() {
val title = createRefFor("title")
val image = createRefFor("image")
val icon = createRefFor("icon")
val start1 = constraintSet {
constrain(title) {
bottom.linkTo(image.bottom)
start.linkTo(image.start)
}
constrain(image) {
width = Dimension.matchParent
height = Dimension.value(big)
top.linkTo(parent.top)
customColor("cover", Color(0x000000FF))
}
constrain(icon) {
top.linkTo(image.top, 16.dp)
start.linkTo(image.start, 16.dp)
alpha = 0f
}
}
val end1 = constraintSet {
constrain(title) {
bottom.linkTo(image.bottom)
start.linkTo(icon.end)
centerVerticallyTo(image)
scaleX = 0.7f
scaleY = 0.7f
}
constrain(image) {
width = Dimension.matchParent
height = Dimension.value(small)
top.linkTo(parent.top)
customColor("cover", Color(0xFF0000FF))
}
constrain(icon) {
top.linkTo(image.top, 16.dp)
start.linkTo(image.start, 16.dp)
}
}
transition("default", start1, end1) {}
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.verticalScroll(scroll)
) {
Spacer(Modifier.height(big))
repeat(5) {
Text(
text = LoremIpsum(222).values.first(),
modifier = Modifier
.background(Color.White)
.padding(16.dp)
)
}
}
val gap = with(LocalDensity.current){big.toPx() - small.toPx()}
val progress = min(scroll.value / gap, 1f);
MotionLayout(
modifier = Modifier.fillMaxSize(),
motionScene = scene,
progress = progress
) {
Image(
modifier = Modifier.layoutId("image"),
painter = painterResource(R.drawable.bridge),
contentDescription = null,
contentScale = ContentScale.Crop
)
Box(modifier = Modifier
.layoutId("image")
.background(motionProperties("image").value.color("cover"))) {
}
Image(
modifier = Modifier.layoutId("icon"),
painter = painterResource(R.drawable.menu),
contentDescription = null
)
Text(
modifier = Modifier.layoutId("title"),
text = "San Francisco",
fontSize = 30.sp,
color = Color.White
)
}
} | apache-2.0 | 45a67d71ae1d04226d0c40898d58873d | 33.33871 | 95 | 0.610054 | 4.683168 | false | false | false | false |
luxons/seven-wonders | sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/errors/ErrorDialog.kt | 1 | 2226 | package org.luxons.sevenwonders.ui.components.errors
import com.palantir.blueprintjs.Classes
import com.palantir.blueprintjs.Intent
import com.palantir.blueprintjs.bpButton
import com.palantir.blueprintjs.bpDialog
import kotlinx.browser.window
import org.luxons.sevenwonders.ui.redux.*
import org.luxons.sevenwonders.ui.router.Navigate
import org.luxons.sevenwonders.ui.router.Route
import react.RBuilder
import react.RComponent
import react.RProps
import react.RState
import react.dom.p
import styled.css
import styled.styledDiv
interface ErrorDialogStateProps : RProps {
var errorMessage: String?
}
interface ErrorDialogDispatchProps : RProps {
var goHome: () -> Unit
}
interface ErrorDialogProps : ErrorDialogDispatchProps, ErrorDialogStateProps
class ErrorDialogPresenter(props: ErrorDialogProps) : RComponent<ErrorDialogProps, RState>(props) {
override fun RBuilder.render() {
val errorMessage = props.errorMessage
bpDialog(
isOpen = errorMessage != null,
title = "Oops!",
icon = "error",
iconIntent = Intent.DANGER,
onClose = { goHomeAndRefresh() }
) {
styledDiv {
css {
classes.add(Classes.DIALOG_BODY)
}
p {
+(errorMessage ?: "fatal error")
}
}
styledDiv {
css {
classes.add(Classes.DIALOG_FOOTER)
}
bpButton(icon = "log-out", onClick = { goHomeAndRefresh() }) {
+"HOME"
}
}
}
}
}
private fun goHomeAndRefresh() {
// we don't use a redux action here because we actually want to redirect and refresh the page
window.location.href = Route.HOME.path
}
fun RBuilder.errorDialog() = errorDialog {}
private val errorDialog = connectStateAndDispatch<ErrorDialogStateProps, ErrorDialogDispatchProps, ErrorDialogProps>(
clazz = ErrorDialogPresenter::class,
mapStateToProps = { state, _ ->
errorMessage = state.fatalError
},
mapDispatchToProps = { dispatch, _ ->
goHome = { dispatch(Navigate(Route.HOME)) }
},
)
| mit | 3a7f850065ff55f1fc235f4574c624f9 | 29.081081 | 117 | 0.636568 | 4.686316 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/TimeUtils.kt | 1 | 6416 | package net.perfectdreams.loritta.morenitta.utils
import java.time.LocalDateTime
import java.time.ZonedDateTime
object TimeUtils {
private val TIME_PATTERN = "(([01]?\\d|2[0-3]):([0-5]\\d?)(:([0-5]\\d))?) ?(am|pm)?".toPattern()
private val DATE_PATTERN = "(0[1-9]|[12][0-9]|3[01])[-/.](0[1-9]|1[012])[-/.]([0-9]+)".toPattern()
private val YEAR_PATTERN = "([0-9]+) ?(y|a)".toPattern()
private val MONTH_PATTERN = "([0-9]+) ?(month(s)?|m(e|ê)s(es)?)".toPattern()
private val WEEK_PATTERN = "([0-9]+) ?(w)".toPattern()
private val DAY_PATTERN = "([0-9]+) ?(d)".toPattern()
private val HOUR_PATTERN = "([0-9]+) ?(h)".toPattern()
private val SHORT_MINUTE_PATTERN = "([0-9]+) ?(m)".toPattern()
private val MINUTE_PATTERN = "([0-9]+) ?(min)".toPattern()
private val SECONDS_PATTERN = "([0-9]+) ?(s)".toPattern()
// TODO: Would be better to not hardcode it
val TIME_ZONE = Constants.LORITTA_TIMEZONE
fun convertToMillisRelativeToNow(input: String) = convertToLocalDateTimeRelativeToNow(input)
.toInstant()
.toEpochMilli()
fun convertToLocalDateTimeRelativeToNow(input: String) = convertToLocalDateTimeRelativeToTime(input, ZonedDateTime.now(TIME_ZONE))
fun convertToLocalDateTimeRelativeToTime(input: String, relativeTo: ZonedDateTime): ZonedDateTime {
val content = input.toLowerCase()
var localDateTime = relativeTo
.withNano(0)
var foundViaTime = false
if (content.contains(":")) { // horário
val matcher = TIME_PATTERN.matcher(content)
if (matcher.find()) { // Se encontrar...
val hour = matcher.group(2).toIntOrNull() ?: 0
val minute = matcher.group(3).toIntOrNull() ?: 0
val seconds = try {
matcher.group(5)?.toIntOrNull() ?: 0
} catch (e: IllegalStateException) {
0
}
var meridiem = try {
matcher.group(6)
} catch (e: IllegalStateException) {
null
}
// Horários que usam o meridiem
if (meridiem != null) {
meridiem = meridiem.replace(".", "").replace(" ", "")
if (meridiem.equals("pm", true)) { // Se for PM, aumente +12
localDateTime = localDateTime.withHour((hour % 12) + 12)
} else { // Se for AM, mantenha do jeito atual
localDateTime = localDateTime.withHour(hour % 12)
}
} else {
localDateTime = localDateTime.withHour(hour)
}
localDateTime = localDateTime
.withMinute(minute)
.withSecond(seconds)
foundViaTime = true
}
}
if (content.contains("/")) { // data
val matcher = DATE_PATTERN.matcher(content)
if (matcher.find()) { // Se encontrar...
val day = matcher.group(1).toIntOrNull() ?: 1
val month = matcher.group(2).toIntOrNull() ?: 1
val year = matcher.group(3).toIntOrNull() ?: 1999
localDateTime = localDateTime
.withDayOfMonth(day)
.withMonth(month)
.withYear(year)
}
} else if (foundViaTime && localDateTime.isBefore(LocalDateTime.now().atZone(TIME_ZONE))) {
// If it was found via time but there isn't any day set, we are going to check if it is in the past and, if true, we are going to add one day
localDateTime = localDateTime
.plusDays(1)
}
val yearsMatcher = YEAR_PATTERN.matcher(content)
if (yearsMatcher.find()) {
val addYears = yearsMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusYears(addYears)
}
val monthMatcher = MONTH_PATTERN.matcher(content)
var foundMonths = false
if (monthMatcher.find()) {
foundMonths = true
val addMonths = monthMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusMonths(addMonths)
}
val weekMatcher = WEEK_PATTERN.matcher(content)
if (weekMatcher.find()) {
val addWeeks = weekMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusWeeks(addWeeks)
}
val dayMatcher = DAY_PATTERN.matcher(content)
if (dayMatcher.find()) {
val addDays = dayMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusDays(addDays)
}
val hourMatcher = HOUR_PATTERN.matcher(content)
if (hourMatcher.find()) {
val addHours = hourMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusHours(addHours)
}
// This check is needed due to the month pattern also checking for "m"
// So, if the month was not found, we will check with the short minute pattern
// If it was found, we will ignore the short minute pattern and only use the long pattern
var foundMinutes = false
if (!foundMonths) {
val minuteMatcher = SHORT_MINUTE_PATTERN.matcher(content)
if (minuteMatcher.find()) {
foundMinutes = true
val addMinutes = minuteMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusMinutes(addMinutes)
}
}
if (!foundMinutes) {
val minuteMatcher = MINUTE_PATTERN.matcher(content)
if (minuteMatcher.find()) {
val addMinutes = minuteMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusMinutes(addMinutes)
}
}
val secondsMatcher = SECONDS_PATTERN.matcher(content)
if (secondsMatcher.find()) {
val addSeconds = secondsMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusSeconds(addSeconds)
}
return localDateTime
}
} | agpl-3.0 | 055048a036e6fa3fde87b075f6d2adbb | 40.921569 | 153 | 0.543116 | 4.739837 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/administration/LockCommand.kt | 1 | 2992 | package net.perfectdreams.loritta.morenitta.commands.vanilla.administration
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.isValidSnowflake
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.extensions.getGuildMessageChannelById
class LockCommand(loritta: LorittaBot) : AbstractCommand(loritta, "lock", listOf("trancar", "fechar"), net.perfectdreams.loritta.common.commands.CommandCategory.MODERATION) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.lock.description")
override fun getDiscordPermissions(): List<Permission> {
return listOf(Permission.MANAGE_SERVER)
}
override fun canUseInPrivateChannel(): Boolean {
return false
}
override fun getBotPermissions(): List<Permission> {
return listOf(Permission.MANAGE_CHANNEL, Permission.MANAGE_PERMISSIONS)
}
override suspend fun run(context: CommandContext, locale: BaseLocale) {
val channel = getTextChannel(context, context.args.getOrNull(0)) ?: context.event.textChannel!! // Já que o comando não será executado via DM, podemos assumir que textChannel nunca será nulo
val publicRole = context.guild.publicRole
val override = channel.getPermissionOverride(publicRole)
if (override != null) {
if (Permission.MESSAGE_SEND !in override.denied) {
override.manager
.deny(Permission.MESSAGE_SEND)
.queue()
context.reply(
LorittaReply(
locale["commands.command.lock.denied", context.config.commandPrefix],
"\uD83C\uDF89"
)
)
} else {
context.reply(
LorittaReply(
locale["commands.command.lock.channelAlreadyIsLocked", context.config.commandPrefix],
Emotes.LORI_CRYING
)
)
}
} else {
channel.permissionContainer.upsertPermissionOverride(publicRole)
.deny(Permission.MESSAGE_SEND)
.queue()
context.reply(
LorittaReply(
locale["commands.command.lock.denied", context.config.commandPrefix],
"\uD83C\uDF89"
)
)
}
}
fun getTextChannel(context: CommandContext, input: String?): TextChannel? {
if (input == null)
return null
val guild = context.guild
val channels = guild.getTextChannelsByName(input, false)
if (channels.isNotEmpty()) {
return channels[0]
}
val id = input
.replace("<", "")
.replace("#", "")
.replace(">", "")
if (!id.isValidSnowflake())
return null
val channel = guild.getTextChannelById(id)
if (channel != null) {
return channel
}
return null
}
} | agpl-3.0 | 8fccd3f19a91d1bc7cece5cc3cb67f21 | 30.135417 | 192 | 0.741633 | 3.865459 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/util/globpatternmapper.kt | 1 | 1766 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.util.GlobPatternMapper
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface IGlobPatternMapperNested {
fun globmapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addGlobPatternMapper(GlobPatternMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun _addGlobPatternMapper(value: GlobPatternMapper)
}
fun IFileNameMapperNested.globmapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addFileNameMapper(GlobPatternMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun GlobPatternMapper._init(
handledirsep: Boolean?,
casesensitive: Boolean?,
from: String?,
to: String?)
{
if (handledirsep != null)
setHandleDirSep(handledirsep)
if (casesensitive != null)
setCaseSensitive(casesensitive)
if (from != null)
setFrom(from)
if (to != null)
setTo(to)
}
| apache-2.0 | 1169e9f5259ca77e547b2835b0cedab0 | 26.169231 | 79 | 0.663647 | 3.959641 | false | false | false | false |
lttng/lttng-scope | jabberwocky-core/src/main/kotlin/com/efficios/jabberwocky/views/xychart/model/provider/XYChartSeriesProvider.kt | 1 | 2763 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.views.xychart.model.provider
import com.efficios.jabberwocky.common.TimeRange
import com.efficios.jabberwocky.views.xychart.model.XYChartResolutionUtils
import com.efficios.jabberwocky.views.xychart.model.render.XYChartRender
import com.efficios.jabberwocky.views.xychart.model.render.XYChartSeries
import javafx.beans.property.BooleanProperty
import javafx.beans.property.SimpleBooleanProperty
import java.util.concurrent.FutureTask
import kotlin.math.max
abstract class XYChartSeriesProvider(val series: XYChartSeries) {
/** Indicate if this series is enabled or not. */
private val enabledProperty: BooleanProperty = SimpleBooleanProperty(true)
fun enabledProperty() = enabledProperty
var enabled
get() = enabledProperty.get()
set(value) = enabledProperty.set(value)
fun generateSeriesRender(range: TimeRange, numberOfDataPoints: Int, task: FutureTask<*>? = null): XYChartRender {
if (numberOfDataPoints < 3) throw IllegalArgumentException("XYChart render needs at least 3 data points.")
/**
* We want similar queries to "stay aligned" on a sort of grid, so that slight deviations do
* not cause aliasing. First compute the step of the grid we will use, then the start time
* to use (which will be earlier or equal to the query's time range). Then compute the actual
* timestamps.
*/
/* Determine the step */
val roughResolution = max(1.0, range.duration / (numberOfDataPoints - 1.0))
val step = XYChartResolutionUtils.GRID_RESOLUTIONS.floor(roughResolution.toLong())
?: XYChartResolutionUtils.GRID_RESOLUTIONS.first()!!
/* Determine the start time of the target range. Simply "star_time - (start_time % step). */
val renderStart = range.startTime - (range.startTime % step)
val timestamps = (renderStart..range.endTime step step).toList()
if (timestamps.size <= 1) {
/* We don't even have a range, so there should be no events returned. */
return XYChartRender.EMPTY_RENDER
}
val datapoints = fillSeriesRender(timestamps, task) ?: return XYChartRender.EMPTY_RENDER
return XYChartRender(series, range, step, datapoints)
}
protected abstract fun fillSeriesRender(timestamps: List<Long>, task: FutureTask<*>? = null): List<XYChartRender.DataPoint>?
}
| epl-1.0 | 09d75ea4641dba1fc9e038f797333684 | 45.05 | 128 | 0.720232 | 4.5 | false | false | false | false |
robinverduijn/gradle | subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/beans/BeanPropertyWriter.kt | 1 | 3872 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.serialization.beans
import groovy.lang.Closure
import org.gradle.api.internal.GeneratedSubclasses
import org.gradle.api.internal.IConventionAware
import org.gradle.api.provider.Property
import org.gradle.instantexecution.InstantExecutionException
import org.gradle.instantexecution.extensions.uncheckedCast
import org.gradle.instantexecution.serialization.Codec
import org.gradle.instantexecution.serialization.PropertyKind
import org.gradle.instantexecution.serialization.WriteContext
import org.gradle.instantexecution.serialization.logPropertyError
import org.gradle.instantexecution.serialization.logPropertyInfo
import java.io.IOException
import java.util.concurrent.Callable
import java.util.function.Supplier
class BeanPropertyWriter(
beanType: Class<*>
) : BeanStateWriter {
private
val relevantFields = relevantStateOf(beanType)
/**
* Serializes a bean by serializing the value of each of its fields.
*/
override suspend fun WriteContext.writeStateOf(bean: Any) {
for (field in relevantFields) {
val fieldName = field.name
val fieldValue = valueOrConvention(field.get(bean), bean, fieldName)
writeNextProperty(fieldName, fieldValue, PropertyKind.Field)
}
}
private
fun conventionalValueOf(bean: Any, fieldName: String): Any? = (bean as? IConventionAware)?.run {
conventionMapping.getConventionValue<Any?>(null, fieldName, false)
}
private
fun valueOrConvention(fieldValue: Any?, bean: Any, fieldName: String): Any? = when (fieldValue) {
is Property<*> -> {
if (!fieldValue.isPresent) {
// TODO - disallow using convention mapping + property types
val convention = conventionalValueOf(bean, fieldName)
if (convention != null) {
(fieldValue.uncheckedCast<Property<Any>>()).convention(convention)
}
}
fieldValue
}
is Closure<*> -> fieldValue
// TODO - do not eagerly evaluate these types
is Callable<*> -> fieldValue.call()
is Supplier<*> -> fieldValue.get()
is Function0<*> -> fieldValue.invoke()
is Lazy<*> -> fieldValue.value
else -> fieldValue ?: conventionalValueOf(bean, fieldName)
}
}
/**
* Returns whether the given property could be written. A property can only be written when there's
* a suitable [Codec] for its [value].
*/
suspend fun WriteContext.writeNextProperty(name: String, value: Any?, kind: PropertyKind): Boolean {
withPropertyTrace(kind, name) {
try {
write(value)
} catch (passThrough: IOException) {
throw passThrough
} catch (passThrough: InstantExecutionException) {
throw passThrough
} catch (e: Exception) {
logPropertyError("write", e) {
text("error writing value of type ")
reference(value?.let { unpackedTypeNameOf(it) } ?: "null")
}
return false
}
logPropertyInfo("serialize", value)
return true
}
}
private
fun unpackedTypeNameOf(value: Any) = GeneratedSubclasses.unpackType(value).name
| apache-2.0 | a4e230ad30dc8268bdf2c8feeea1b20a | 35.186916 | 101 | 0.68156 | 4.693333 | false | false | false | false |
ScreamingHawk/phone-saver | app/src/main/java/link/standen/michael/phonesaver/activity/CreditsActivity.kt | 1 | 2068 | package link.standen.michael.phonesaver.activity
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.widget.TextView
import link.standen.michael.phonesaver.R
import java.util.Locale
import android.os.Build
import android.view.View
import link.standen.michael.phonesaver.util.DebugLogger
/**
* Credits activity.
*/
class CreditsActivity : AppCompatActivity() {
private val defaultLocale = Locale("en").language
private lateinit var log: DebugLogger
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.credits_activity)
log = DebugLogger(this)
// Version
try {
val versionName = packageManager.getPackageInfo(packageName, 0).versionName
findViewById<TextView>(R.id.credits_version).text = resources.getString(R.string.credits_version, versionName)
} catch (e: PackageManager.NameNotFoundException) {
log.e("Unable to get package version", e)
}
// Linkify
findViewById<TextView>(R.id.credits_creator).movementMethod = LinkMovementMethod.getInstance()
findViewById<TextView>(R.id.credits_content1).movementMethod = LinkMovementMethod.getInstance()
findViewById<TextView>(R.id.credits_content2).movementMethod = LinkMovementMethod.getInstance()
findViewById<TextView>(R.id.credits_content3).movementMethod = LinkMovementMethod.getInstance()
if (getCurrentLocale().language == defaultLocale){
// English, hide the translator info
findViewById<TextView>(R.id.credits_content_translator).visibility = View.GONE
} else {
findViewById<TextView>(R.id.credits_content_translator).movementMethod = LinkMovementMethod.getInstance()
}
}
/**
* A version safe way to get the currently applied locale.
*/
private fun getCurrentLocale(): Locale =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
this.resources.configuration.locales.get(0)
} else {
@Suppress("DEPRECATION")
this.resources.configuration.locale
}
}
| mit | 54920bc1376a45c29b310fea6955a39d | 32.901639 | 113 | 0.776596 | 4.054902 | false | false | false | false |
h3rald/mal | kotlin/src/mal/stepA_mal.kt | 1 | 7106 | package mal
import java.util.*
fun read(input: String?): MalType = read_str(input)
fun eval(_ast: MalType, _env: Env): MalType {
var ast = _ast
var env = _env
while (true) {
ast = macroexpand(ast, env)
if (ast is MalList) {
when ((ast.first() as? MalSymbol)?.value) {
"def!" -> return env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env))
"let*" -> {
val childEnv = Env(env)
val bindings = ast.nth(1) as? ISeq ?: throw MalException("expected sequence as the first parameter to let*")
val it = bindings.seq().iterator()
while (it.hasNext()) {
val key = it.next()
if (!it.hasNext()) throw MalException("odd number of binding elements in let*")
childEnv.set(key as MalSymbol, eval(it.next(), childEnv))
}
env = childEnv
ast = ast.nth(2)
}
"fn*" -> return fn_STAR(ast, env)
"do" -> {
eval_ast(ast.slice(1, ast.count() - 1), env)
ast = ast.seq().last()
}
"if" -> {
val check = eval(ast.nth(1), env)
if (check !== NIL && check !== FALSE) {
ast = ast.nth(2)
} else if (ast.count() > 3) {
ast = ast.nth(3)
} else return NIL
}
"quote" -> return ast.nth(1)
"quasiquote" -> ast = quasiquote(ast.nth(1))
"defmacro!" -> return defmacro(ast, env)
"macroexpand" -> return macroexpand(ast.nth(1), env)
"try*" -> return try_catch(ast, env)
else -> {
val evaluated = eval_ast(ast, env) as ISeq
val firstEval = evaluated.first()
when (firstEval) {
is MalFnFunction -> {
ast = firstEval.ast
env = Env(firstEval.env, firstEval.params, evaluated.rest().seq())
}
is MalFunction -> return firstEval.apply(evaluated.rest())
else -> throw MalException("cannot execute non-function")
}
}
}
} else return eval_ast(ast, env)
}
}
fun eval_ast(ast: MalType, env: Env): MalType =
when (ast) {
is MalSymbol -> env.get(ast)
is MalList -> ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalVector -> ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalHashMap -> ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a })
else -> ast
}
private fun fn_STAR(ast: MalList, env: Env): MalType {
val binds = ast.nth(1) as? ISeq ?: throw MalException("fn* requires a binding list as first parameter")
val params = binds.seq().filterIsInstance<MalSymbol>()
val body = ast.nth(2)
return MalFnFunction(body, params, env, { s: ISeq -> eval(body, Env(env, params, s.seq())) })
}
private fun is_pair(ast: MalType): Boolean = ast is ISeq && ast.seq().any()
private fun quasiquote(ast: MalType): MalType {
if (!is_pair(ast)) {
val quoted = MalList()
quoted.conj_BANG(MalSymbol("quote"))
quoted.conj_BANG(ast)
return quoted
}
val seq = ast as ISeq
var first = seq.first()
if ((first as? MalSymbol)?.value == "unquote") {
return seq.nth(1)
}
if (is_pair(first) && ((first as ISeq).first() as? MalSymbol)?.value == "splice-unquote") {
val spliced = MalList()
spliced.conj_BANG(MalSymbol("concat"))
spliced.conj_BANG(first.nth(1))
spliced.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return spliced
}
val consed = MalList()
consed.conj_BANG(MalSymbol("cons"))
consed.conj_BANG(quasiquote(ast.first()))
consed.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return consed
}
private fun is_macro_call(ast: MalType, env: Env): Boolean {
val symbol = (ast as? MalList)?.first() as? MalSymbol ?: return false
val function = env.find(symbol) as? MalFunction ?: return false
return function.is_macro
}
private fun macroexpand(_ast: MalType, env: Env): MalType {
var ast = _ast
while (is_macro_call(ast, env)) {
val symbol = (ast as MalList).first() as MalSymbol
val function = env.find(symbol) as MalFunction
ast = function.apply(ast.rest())
}
return ast
}
private fun defmacro(ast: MalList, env: Env): MalType {
val macro = eval(ast.nth(2), env) as MalFunction
macro.is_macro = true
return env.set(ast.nth(1) as MalSymbol, macro)
}
private fun try_catch(ast: MalList, env: Env): MalType =
try {
eval(ast.nth(1), env)
} catch (e: Exception) {
val thrown = if (e is MalException) e else MalException(e.message)
val symbol = (ast.nth(2) as MalList).nth(1) as MalSymbol
val catchBody = (ast.nth(2) as MalList).nth(2)
val catchEnv = Env(env)
catchEnv.set(symbol, thrown)
eval(catchBody, catchEnv)
}
fun print(result: MalType) = pr_str(result, print_readably = true)
fun rep(input: String, env: Env): String =
print(eval(read(input), env))
fun main(args: Array<String>) {
val repl_env = Env()
ns.forEach({ it -> repl_env.set(it.key, it.value) })
repl_env.set(MalSymbol("*host-language*"), MalString("kotlin"))
repl_env.set(MalSymbol("*ARGV*"), MalList(args.drop(1).map({ it -> MalString(it) }).toCollection(LinkedList<MalType>())))
repl_env.set(MalSymbol("eval"), MalFunction({ a: ISeq -> eval(a.first(), repl_env) }))
rep("(def! not (fn* (a) (if a false true)))", repl_env)
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env)
rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", repl_env)
rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))", repl_env)
if (args.any()) {
rep("(load-file \"${args[0]}\")", repl_env)
return
}
while (true) {
val input = readline("user> ")
try {
println(rep(input, repl_env))
} catch (e: EofException) {
break
} catch (e: MalContinue) {
} catch (e: MalException) {
println("Error: " + e.message)
} catch (t: Throwable) {
println("Uncaught " + t + ": " + t.message)
t.printStackTrace()
}
}
}
| mpl-2.0 | 5fbba4b21c3b93ccea0df3159f185260 | 36.010417 | 197 | 0.527019 | 3.789867 | false | false | false | false |
moezbhatti/qksms | presentation/src/main/java/com/moez/QKSMS/common/widget/QkEditText.kt | 3 | 4113 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputConnectionWrapper
import android.widget.EditText
import androidx.core.view.inputmethod.EditorInfoCompat
import androidx.core.view.inputmethod.InputConnectionCompat
import androidx.core.view.inputmethod.InputContentInfoCompat
import com.google.android.mms.ContentType
import com.moez.QKSMS.common.util.TextViewStyler
import com.moez.QKSMS.injection.appComponent
import com.moez.QKSMS.util.tryOrNull
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
/**
* Custom implementation of EditText to allow for dynamic text colors
*
* Beware of updating to extend AppCompatTextView, as this inexplicably breaks the view in
* the contacts chip view
*/
class QkEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : EditText(context, attrs) {
@Inject lateinit var textViewStyler: TextViewStyler
val backspaces: Subject<Unit> = PublishSubject.create()
val inputContentSelected: Subject<InputContentInfoCompat> = PublishSubject.create()
var supportsInputContent: Boolean = false
init {
if (!isInEditMode) {
appComponent.inject(this)
textViewStyler.applyAttributes(this, attrs)
} else {
TextViewStyler.applyEditModeAttributes(this, attrs)
}
}
override fun onCreateInputConnection(editorInfo: EditorInfo): InputConnection {
val inputConnection = object : InputConnectionWrapper(super.onCreateInputConnection(editorInfo), true) {
override fun sendKeyEvent(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_DEL) {
backspaces.onNext(Unit)
}
return super.sendKeyEvent(event)
}
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
if (beforeLength == 1 && afterLength == 0) {
backspaces.onNext(Unit)
}
return super.deleteSurroundingText(beforeLength, afterLength)
}
}
if (supportsInputContent) {
EditorInfoCompat.setContentMimeTypes(editorInfo, arrayOf(
ContentType.IMAGE_JPEG,
ContentType.IMAGE_JPG,
ContentType.IMAGE_PNG,
ContentType.IMAGE_GIF))
}
val callback = InputConnectionCompat.OnCommitContentListener { inputContentInfo, flags, opts ->
val grantReadPermission = flags and InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION != 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && grantReadPermission) {
return@OnCommitContentListener tryOrNull {
inputContentInfo.requestPermission()
inputContentSelected.onNext(inputContentInfo)
true
} ?: false
}
true
}
return InputConnectionCompat.createWrapper(inputConnection, editorInfo, callback)
}
} | gpl-3.0 | fdb02e4185be9347da0ca32e824bcdc7 | 36.743119 | 118 | 0.691223 | 4.967391 | false | false | false | false |
tmarsteel/compiler-fiddle | src/compiler/parser/postproc/type.kt | 1 | 2424 | /*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**
*
*/
package compiler.parser.postproc
import compiler.InternalCompilerError
import compiler.ast.type.TypeModifier
import compiler.ast.type.TypeReference
import compiler.lexer.*
import compiler.parser.rule.Rule
import compiler.parser.rule.RuleMatchingResult
import compiler.transact.Position
import compiler.transact.TransactionalSequence
fun TypePostprocessor(rule: Rule<List<RuleMatchingResult<*>>>): Rule<TypeReference> {
return rule
.flatten()
.mapResult(::toAST)
}
private fun toAST(tokens: TransactionalSequence<Any, Position>): TypeReference {
val nameOrModifier = tokens.next()!!
val typeModifier: TypeModifier?
val nameToken: IdentifierToken
if (nameOrModifier is TypeModifier) {
typeModifier = nameOrModifier
nameToken = tokens.next()!! as IdentifierToken
}
else {
typeModifier = null
nameToken = nameOrModifier as IdentifierToken
}
val isNullable = tokens.hasNext() && tokens.next()!! == OperatorToken(Operator.QUESTION_MARK)
return TypeReference(nameToken, isNullable, typeModifier)
}
fun TypeModifierPostProcessor(rule: Rule<List<RuleMatchingResult<*>>>): Rule<TypeModifier> {
return rule
.flatten()
.mapResult { tokens ->
val keyword = (tokens.next() as KeywordToken?)?.keyword
when(keyword) {
Keyword.MUTABLE -> TypeModifier.MUTABLE
Keyword.READONLY -> TypeModifier.READONLY
Keyword.IMMUTABLE -> TypeModifier.IMMUTABLE
else -> throw InternalCompilerError("$keyword is not a type modifier")
}
}
} | lgpl-3.0 | 0b93851d32354e37c6f38f212f8c6749 | 32.680556 | 97 | 0.706271 | 4.67052 | false | false | false | false |
google/horologist | audio-ui/src/debug/java/com/google/android/horologist/audio/ui/VolumeScreenLocalePreview.kt | 1 | 1738 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.audio.ui
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalConfiguration
import androidx.wear.compose.material.Scaffold
import com.google.android.horologist.audio.AudioOutput
import com.google.android.horologist.audio.VolumeState
import com.google.android.horologist.audio.ui.components.toAudioOutputUi
import com.google.android.horologist.compose.tools.WearLocalePreview
@WearLocalePreview
@Composable
fun VolumeScreenLocalePreview() {
val volume = VolumeState(5, 10)
Scaffold(
positionIndicator = {
VolumePositionIndicator(
volumeState = { volume },
autoHide = false
)
}
) {
VolumeScreen(
volume = { volume },
audioOutputUi = AudioOutput.WatchSpeaker(
id = "1",
name = LocalConfiguration.current.locales.get(0).displayName
)
.toAudioOutputUi(),
increaseVolume = { },
decreaseVolume = { },
onAudioOutputClick = {}
)
}
}
| apache-2.0 | 29c45e89c52c11e8d7a43c1819598f73 | 32.423077 | 76 | 0.677215 | 4.514286 | false | false | false | false |
CarrotCodes/Warren | src/test/kotlin/chat/willow/warren/handler/ModeHandlerTests.kt | 1 | 6788 | package chat.willow.warren.handler
import chat.willow.kale.helper.CaseMapping
import chat.willow.kale.irc.message.rfc1459.ModeMessage
import chat.willow.kale.irc.prefix.Prefix
import chat.willow.kale.irc.prefix.prefix
import chat.willow.kale.irc.tag.TagStore
import chat.willow.warren.IClientMessageSending
import chat.willow.warren.WarrenChannel
import chat.willow.warren.event.ChannelModeEvent
import chat.willow.warren.event.IWarrenEvent
import chat.willow.warren.event.IWarrenEventDispatcher
import chat.willow.warren.event.UserModeEvent
import chat.willow.warren.state.*
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class ModeHandlerTests {
lateinit var handler: ModeHandler
lateinit var mockEventDispatcher: IWarrenEventDispatcher
lateinit var channelsState: ChannelsState
lateinit var mockClientMessaging: IClientMessageSending
val caseMappingState = CaseMappingState(mapping = CaseMapping.RFC1459)
@Before fun setUp() {
mockEventDispatcher = mock()
val channelTypes = ChannelTypesState(types = setOf('#'))
channelsState = emptyChannelsState(caseMappingState)
val userPrefixesState = UserPrefixesState(prefixesToModes = mapOf('+' to 'v', '@' to 'o'))
mockClientMessaging = mock()
handler = ModeHandler(mockEventDispatcher, mockClientMessaging, channelTypes, channelsState.joined, userPrefixesState, caseMappingState)
}
@Test fun test_handle_ChannelModeChange_NoPrefix_FiresEvents() {
val firstExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'x', parameter = "someone")
val secondExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'y')
val channelState = emptyChannel("#channel")
channelsState.joined += channelState
handler.handle(ModeMessage.Message(source = prefix(""), target = "#channel", modifiers = listOf(firstExpectedModifier, secondExpectedModifier)), TagStore())
val channel = WarrenChannel(state = channelState, client = mockClientMessaging)
verify(mockEventDispatcher).fire(ChannelModeEvent(user = prefix(""), channel = channel, modifier = firstExpectedModifier))
verify(mockEventDispatcher).fire(ChannelModeEvent(user = prefix(""), channel = channel, modifier = secondExpectedModifier))
}
@Test fun test_handle_ChannelModeChange_WithPrefix_FiresEvents() {
val firstExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'x', parameter = "someone")
val secondExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'y')
val channelState = emptyChannel("#channel")
channelsState.joined += channelState
handler.handle(ModeMessage.Message(source = Prefix(nick = "admin"), target = "#channel", modifiers = listOf(firstExpectedModifier, secondExpectedModifier)), TagStore())
val channel = WarrenChannel(state = channelState, client = mockClientMessaging)
verify(mockEventDispatcher).fire(ChannelModeEvent(user = Prefix(nick = "admin"), channel = channel, modifier = firstExpectedModifier))
verify(mockEventDispatcher).fire(ChannelModeEvent(user = Prefix(nick = "admin"), channel = channel, modifier = secondExpectedModifier))
}
@Test fun test_handle_ChannelModeChange_ForChannelNotIn_DoesNothing() {
val dummyModifier = ModeMessage.ModeModifier(type = '+', mode = 'x', parameter = "someone")
handler.handle(ModeMessage.Message(source = Prefix(nick = "admin"), target = "#notInChannel", modifiers = listOf(dummyModifier)), TagStore())
verify(mockEventDispatcher, never()).fire(any<IWarrenEvent>())
}
@Test fun test_handle_ChannelModeChange_UserPrefixAdded() {
channelsState.joined += ChannelState("#channel", generateUsersWithModes(("someone" to mutableSetOf()), mappingState = caseMappingState))
val addVoiceModifier = ModeMessage.ModeModifier(type = '+', mode = 'v', parameter = "someone")
handler.handle(ModeMessage.Message(target = "#channel", modifiers = listOf(addVoiceModifier), source = prefix("")), TagStore())
assertEquals(mutableSetOf('v'), channelsState.joined["#channel"]!!.users["someone"]!!.modes)
}
@Test fun test_handle_ChannelModeChange_UserPrefixRemoved() {
channelsState.joined += ChannelState("#channel", generateUsersWithModes(("someone" to mutableSetOf('o')), mappingState = caseMappingState))
val addVoiceModifier = ModeMessage.ModeModifier(type = '-', mode = 'o', parameter = "someone")
handler.handle(ModeMessage.Message(target = "#channel", modifiers = listOf(addVoiceModifier), source = prefix("")), TagStore())
assertEquals(mutableSetOf<Char>(), channelsState.joined["#channel"]!!.users["someone"]!!.modes)
}
@Test fun test_handle_ChannelModeChange_UserPrefixForNonExistentChannel_NothingHappens() {
channelsState.joined += ChannelState("#channel", generateUsersWithModes(("someone" to mutableSetOf('o')), mappingState = caseMappingState))
val addVoiceModifier = ModeMessage.ModeModifier(type = '-', mode = 'o', parameter = "someone")
handler.handle(ModeMessage.Message(target = "#anotherchannel", modifiers = listOf(addVoiceModifier), source = prefix("")), TagStore())
assertEquals(mutableSetOf('o'), channelsState.joined["#channel"]!!.users["someone"]!!.modes)
}
@Test fun test_handle_ChannelModeChange_UserPrefixForNonExistentUser_NothingHappens() {
channelsState.joined += ChannelState("#channel", generateUsersWithModes(("someone" to mutableSetOf('o')), mappingState = caseMappingState))
val addVoiceModifier = ModeMessage.ModeModifier(type = '-', mode = 'o', parameter = "someone-else")
handler.handle(ModeMessage.Message(target = "#channel", modifiers = listOf(addVoiceModifier), source = prefix("")), TagStore())
assertEquals(mutableSetOf('o'), channelsState.joined["#channel"]!!.users["someone"]!!.modes)
}
@Test fun test_handle_UserModeChange_FiresEvents() {
val firstExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'v', parameter = "someone")
val secondExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'x')
handler.handle(ModeMessage.Message(source = prefix(""), target = "someone", modifiers = listOf(firstExpectedModifier, secondExpectedModifier)), TagStore())
verify(mockEventDispatcher).fire(UserModeEvent(user = "someone", modifier = firstExpectedModifier))
verify(mockEventDispatcher).fire(UserModeEvent(user = "someone", modifier = secondExpectedModifier))
}
} | isc | b55517ba7a03df914e1e2dad0781cc3c | 52.039063 | 176 | 0.727902 | 5.031875 | false | true | false | false |
josesamuel/remoter | remoter/src/main/java/remoter/compiler/kbuilder/LongParamBuilder.kt | 1 | 3468 | package remoter.compiler.kbuilder
import com.squareup.kotlinpoet.FunSpec
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.VariableElement
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
/**
* A [ParamBuilder] for long type parameters
*/
internal class LongParamBuilder(remoterInterfaceElement: Element, bindingManager: KBindingManager) : ParamBuilder(remoterInterfaceElement, bindingManager) {
override fun writeParamsToProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) {
if (param.asType().kind == TypeKind.ARRAY) {
if (paramType == ParamType.OUT) {
writeArrayOutParamsToProxy(param, methodBuilder)
} else {
methodBuilder.addStatement("$DATA.writeLongArray(" + param.simpleName + ")")
}
} else {
methodBuilder.addStatement("$DATA.writeLong(" + param.simpleName + ")")
}
}
override fun readResultsFromStub(methodElement: ExecutableElement, resultType: TypeMirror, methodBuilder: FunSpec.Builder) {
if (resultType.kind == TypeKind.ARRAY) {
methodBuilder.addStatement("$REPLY.writeLongArray($RESULT)")
} else {
methodBuilder.addStatement("$REPLY.writeLong($RESULT)")
}
}
override fun readResultsFromProxy(methodType: ExecutableElement, methodBuilder: FunSpec.Builder) {
val resultMirror = methodType.getReturnAsTypeMirror()
val resultType = methodType.getReturnAsKotlinType()
if (resultMirror.kind == TypeKind.ARRAY) {
val suffix = if (resultType.isNullable) "" else "!!"
methodBuilder.addStatement("$RESULT = $REPLY.createLongArray()$suffix")
} else {
methodBuilder.addStatement("$RESULT = $REPLY.readLong()")
}
}
override fun readOutResultsFromStub(param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) {
if (param.asType().kind == TypeKind.ARRAY) {
methodBuilder.addStatement("$REPLY.writeLongArray($paramName)")
}
}
override fun writeParamsToStub(methodType: ExecutableElement, param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) {
super.writeParamsToStub(methodType, param, paramType, paramName, methodBuilder)
if (param.asType().kind == TypeKind.ARRAY) {
if (paramType == ParamType.OUT) {
writeOutParamsToStub(param, paramType, paramName, methodBuilder)
} else {
val suffix = if (param.isNullable()) "" else "!!"
methodBuilder.addStatement("$paramName = $DATA.createLongArray()$suffix")
}
} else {
methodBuilder.addStatement("$paramName = $DATA.readLong()")
}
}
override fun readOutParamsFromProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) {
if (param.asType().kind == TypeKind.ARRAY && paramType != ParamType.IN) {
if (param.isNullable()){
methodBuilder.beginControlFlow("if (${param.simpleName} != null)")
}
methodBuilder.addStatement("$REPLY.readLongArray(" + param.simpleName + ")")
if (param.isNullable()){
methodBuilder.endControlFlow()
}
}
}
}
| apache-2.0 | 6d69c263ceba7720edacfd14cf09fd58 | 42.898734 | 164 | 0.657439 | 5.092511 | false | false | false | false |
elifarley/kotlin-examples | src/com/github/elifarley/kotlin/path/DirectoryWatcher.kt | 2 | 5636 | package com.orgecc.util.path
import com.m4u.util.WithLogging
import com.m4u.util.logger
import java.io.File
import java.io.IOException
import java.nio.file.*
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
interface PathHandler {
fun handle(path: Path)
}
fun Path.handleAndDelete(pathHandler: (Path) -> Unit): Unit =
try {
DirectoryWatcher.LOG.warn("Will handle '$this'")
pathHandler(this)
DirectoryWatcher.LOG.debug("Done. Deleting '$this'...")
try {
Files.delete(this)
} catch(e: Exception) {
DirectoryWatcher.LOG.error("Unable to delete '$this'")
}
} catch (e: Exception) {
logger(pathHandler.javaClass).error("Unable to handle file '$this'", e)
this.parent.resolveSibling("error").let { errorPath ->
Files.createDirectories(errorPath)
var errorFile = errorPath.resolve(this.fileName)
var tries = 0
while (tries < 1000 && Files.exists(errorFile)) {
tries++
errorFile = File("$errorFile.$tries").toPath()
}
Files.move(this, errorFile)
}
}
fun Path.enqueueExistingFiles(target: MutableCollection<Path>) =
Files.newDirectoryStream(this) {
!Files.isDirectory(it) &&
!it.fileName.toString().startsWith(".")
}.use { directoryStream ->
target += directoryStream
}
// Simple class to watch directory events.
class DirectoryWatcher(rootPathArg: String, executor: ExecutorService = Executors.newSingleThreadExecutor()) {
companion object : WithLogging()
private val rootPath = Paths.get(rootPathArg)
private val queue = ConcurrentLinkedQueue<Path>()
init {
executor.execute { rootPath.enqueuePaths(this.queue) }
LOG.warn("STARTED watching dir ${rootPath.toAbsolutePath()}")
}
val next: Path?
get() = queue.poll()?.let {
rootPath.resolve(it)
}
fun waitNext(sleepInMillis: Long = 5000): Path {
var result: Path? = null
while (result == null) {
result = next
if (result == null) Thread.sleep(sleepInMillis)
}
return result
}
fun loop(pathHandler: (Path) -> Unit, sleepInMillis: Long = 5000) {
while (!Thread.currentThread().isInterrupted) {
waitNext(sleepInMillis).handleAndDelete(pathHandler)
}
}
}
fun String.watchDir(executor: ExecutorService = Executors.newSingleThreadExecutor())
= DirectoryWatcher(this, executor)
fun String.watchDirLoop(pathHandler: (Path) -> Unit, sleepInMillis: Long = 5000, executor: ExecutorService = Executors.newFixedThreadPool(2))
= executor.execute { this.watchDir(executor).loop(pathHandler, sleepInMillis) }
fun Path.enqueuePaths(eventQueue: ConcurrentLinkedQueue<Path>,
sleepInMillis: Long = 500, kind: WatchEvent.Kind<Path> = StandardWatchEventKinds.ENTRY_CREATE): Unit {
Thread.currentThread().name = "enqueuePaths[$kind:${this.toAbsolutePath()}]"
Files.createDirectories(this)
try {
this.enqueueExistingFiles(eventQueue)
val watchService = [email protected]()
[email protected](watchService, kind)
// loop forever to watch directory
while (!Thread.currentThread().isInterrupted) {
val watchKey: WatchKey
watchKey = watchService.take() // this call is blocking until events are present
watchKey.pollEvents().map { it.context() as Path }.forEach {
while (!eventQueue.offer(it)) Thread.sleep(sleepInMillis)
}
// if the watched directed gets deleted, break loop
if (!watchKey.reset()) {
DirectoryWatcher.LOG.warn("[enqueuePaths] No longer valid")
watchKey.cancel()
watchService.close()
break
}
}
} catch (ex: InterruptedException) {
DirectoryWatcher.LOG.warn("Interrupted. Goodbye")
} catch (ex: IOException) {
DirectoryWatcher.LOG.warn("", ex)
}
}
fun Path.enqueueEvents(eventQueue: ConcurrentLinkedQueue<WatchEvent<*>>,
sleepInMillis: Long = 500, vararg kinds: WatchEvent.Kind<*> = arrayOf(StandardWatchEventKinds.ENTRY_CREATE)): Unit {
Thread.currentThread().name = "enqueueEvents[$kinds:${this.toAbsolutePath()}]"
try {
val watchService = [email protected]()
[email protected](watchService, *kinds)
// loop forever to watch directory
while (!Thread.currentThread().isInterrupted) {
val watchKey: WatchKey
watchKey = watchService.take() // this call is blocking until events are present
for (event in watchKey.pollEvents()) {
while (!eventQueue.offer(event)) Thread.sleep(sleepInMillis)
}
// if the watched directed gets deleted, break loop
if (!watchKey.reset()) {
DirectoryWatcher.LOG.warn("No longer valid")
watchKey.cancel()
watchService.close()
break
}
}
} catch (ex: InterruptedException) {
DirectoryWatcher.LOG.warn("Interrupted. Goodbye")
} catch (ex: IOException) {
DirectoryWatcher.LOG.warn("", ex)
}
}
| mit | 0b31bba5c2bd7714a8d4f507961f1bea | 31.578035 | 141 | 0.613023 | 4.917976 | false | false | false | false |
petrbalat/jlib | src/main/java/cz/softdeluxe/jlib/service/EmailService.kt | 1 | 1897 | package cz.softdeluxe.jlib.service
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.io.InputStreamSource
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.scheduling.annotation.Async
import org.springframework.scheduling.annotation.AsyncResult
import org.springframework.stereotype.Service
import java.util.concurrent.Future
/**
* Created by Petr on 9. 5. 2015.
*/
@Service
open class EmailServiceImpl(val mailSender: JavaMailSender,
@Value(value = "\${spring.mail.username}") val from: String) : EmailService {
private val logger = LoggerFactory.getLogger(javaClass)
@Async
override fun send(to: Array<String>, subject: String, text: String, html: Boolean,
attachments: Iterable<EmailAttachment>): Future<Boolean> {
try {
val mimeMessage = mailSender.createMimeMessage()
val multipart: Boolean = attachments.any()
val message = MimeMessageHelper(mimeMessage, multipart)
message.setFrom(from)
attachments.forEach {
message.addAttachment(it.name, it.stream)
}
message.setTo(to)
message.setSubject(subject)
message.setText(text, html)
mailSender.send(mimeMessage)
return AsyncResult(true)
} catch (ex: Exception) {
logger.error("Chyba při odeslání emailu", ex)
return AsyncResult(false)
}
}
}
interface EmailService {
fun send(to: Array<String>, subject: String, text: String, html: Boolean = true,
attachments: Iterable<EmailAttachment> = emptyList()): Future<Boolean>
}
class EmailAttachment(val name: String, val stream: InputStreamSource) | apache-2.0 | 3aebafd77ee4d6427bb46637f91ad80a | 34.754717 | 105 | 0.68321 | 4.563855 | false | false | false | false |
trivago/reportoire | core/src/main/kotlin/com/trivago/reportoire/core/common/MemorySource.kt | 1 | 1789 | /*********************************************************************************
* Copyright 2017-present trivago GmbH
*
* 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.trivago.reportoire.core.common
import com.trivago.reportoire.core.sources.Source
import com.trivago.reportoire.core.sources.SyncSource
/**
* Source that stores a value within the memory for the given input.
*/
class MemorySource<TModel, in TInput> : SyncSource<TModel, TInput> {
// Members
private var mLatestInput: TInput? = null
private var mCachedModel: TModel? = null
// Public Api
/**
* Saves the model in relation to the given input.
*/
fun setModel(input: TInput?, model: TModel?) {
mLatestInput = input
mCachedModel = model
}
// SyncSource
override fun getResult(input: TInput?): Source.Result<TModel> {
if (mCachedModel != null && input?.equals(mLatestInput)!!) {
return Source.Result.Success(mCachedModel)
} else {
return Source.Result.Error(IllegalStateException("No model in memory found!"))
}
}
// Source
override fun reset() {
setModel(null, null)
}
}
| apache-2.0 | bcc1d7debd84d07c79f9b585c2cdc2ff | 30.385965 | 90 | 0.61934 | 4.658854 | false | true | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/browser/history/view/ViewHistoryListUi.kt | 1 | 4856 | /*
* Copyright (c) 2022 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.browser.history.view
import android.net.Uri
import androidx.activity.ComponentActivity
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.model.OptionMenu
import jp.toastkid.lib.view.list.ListActionAttachment
import jp.toastkid.ui.dialog.DestructiveChangeConfirmDialog
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.browser.history.ViewHistory
import jp.toastkid.yobidashi.libs.db.DatabaseFinder
import jp.toastkid.yobidashi.search.view.BindItemContent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
fun ViewHistoryListUi() {
val context = LocalContext.current as? ComponentActivity ?: return
val database = DatabaseFinder().invoke(context)
val viewHistoryRepository = database.viewHistoryRepository()
val fullItems = mutableListOf<ViewHistory>()
val viewHistoryItems = remember { mutableStateListOf<ViewHistory>() }
val listState = rememberLazyListState()
val clearConfirmDialogState = remember { mutableStateOf(false) }
val contentViewModel = viewModel(ContentViewModel::class.java, context)
LaunchedEffect(key1 = "first_launch", block = {
contentViewModel.optionMenus(
OptionMenu(titleId = R.string.title_clear_view_history, action = {
clearConfirmDialogState.value = true
})
)
CoroutineScope(Dispatchers.Main).launch {
val loaded = withContext(Dispatchers.IO) {
viewHistoryRepository.reversed()
}
fullItems.clear()
fullItems.addAll(loaded)
viewHistoryItems.addAll(fullItems)
}
})
val browserViewModel = viewModel(BrowserViewModel::class.java, context)
val onClick: (ViewHistory, Boolean) -> Unit = { viewHistory, isLongClick ->
when (isLongClick) {
true -> {
browserViewModel.openBackground(viewHistory.title, Uri.parse(viewHistory.url))
}
false -> {
browserViewModel.open(Uri.parse(viewHistory.url))
}
}
}
List(viewHistoryItems, listState, onClick) {
viewHistoryRepository.delete(it)
viewHistoryItems.remove(it)
}
ListActionAttachment.make(context)
.invoke(
listState,
LocalLifecycleOwner.current,
viewHistoryItems,
fullItems,
{ item, word -> item.title.contains(word) || item.url.contains(word) }
)
DestructiveChangeConfirmDialog(
clearConfirmDialogState,
R.string.title_clear_view_history
) {
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) {
viewHistoryRepository.deleteAll()
}
viewHistoryItems.clear()
contentViewModel.snackShort(R.string.done_clear)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun List(
viewHistoryItems: SnapshotStateList<ViewHistory>,
listState: LazyListState,
onClick: (ViewHistory, Boolean) -> Unit,
onDelete: (ViewHistory) -> Unit
) {
LazyColumn(state = listState) {
items(viewHistoryItems, { it._id }) { viewHistory ->
BindItemContent(
viewHistory,
onClick = {
onClick(viewHistory, false)
},
onLongClick = {
onClick(viewHistory, true)
},
onDelete = {
onDelete(viewHistory)
},
modifier = Modifier.animateItemPlacement()
)
}
}
} | epl-1.0 | 655dd4b3e42818b4f775a6e72bb3bf05 | 33.692857 | 94 | 0.688839 | 4.995885 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_gls/src/main/java/no/nordicsemi/android/gls/main/view/GLSMapper.kt | 1 | 4047 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.gls.main.view
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import no.nordicsemi.android.gls.R
import no.nordicsemi.android.gls.data.ConcentrationUnit
import no.nordicsemi.android.gls.data.RecordType
import no.nordicsemi.android.gls.data.WorkingMode
@Composable
internal fun RecordType?.toDisplayString(): String {
return when (this) {
RecordType.CAPILLARY_WHOLE_BLOOD -> stringResource(id = R.string.gls_type_capillary_whole_blood)
RecordType.CAPILLARY_PLASMA -> stringResource(id = R.string.gls_type_capillary_plasma)
RecordType.VENOUS_WHOLE_BLOOD -> stringResource(id = R.string.gls_type_venous_whole_blood)
RecordType.VENOUS_PLASMA -> stringResource(id = R.string.gls_type_venous_plasma)
RecordType.ARTERIAL_WHOLE_BLOOD -> stringResource(id = R.string.gls_type_arterial_whole_blood)
RecordType.ARTERIAL_PLASMA -> stringResource(id = R.string.gls_type_arterial_plasma)
RecordType.UNDETERMINED_WHOLE_BLOOD -> stringResource(id = R.string.gls_type_undetermined_whole_blood)
RecordType.UNDETERMINED_PLASMA -> stringResource(id = R.string.gls_type_undetermined_plasma)
RecordType.INTERSTITIAL_FLUID -> stringResource(id = R.string.gls_type_interstitial_fluid)
RecordType.CONTROL_SOLUTION -> stringResource(id = R.string.gls_type_control_solution)
null -> stringResource(id = R.string.gls_type_reserved)
}
}
@Composable
internal fun ConcentrationUnit.toDisplayString(): String {
return when (this) {
//TODO("Check unit_kgpl --> mgpdl")
ConcentrationUnit.UNIT_KGPL -> stringResource(id = R.string.gls_unit_mgpdl)
ConcentrationUnit.UNIT_MOLPL -> stringResource(id = R.string.gls_unit_mmolpl)
}
}
@Composable
internal fun WorkingMode.toDisplayString(): String {
return when (this) {
WorkingMode.ALL -> stringResource(id = R.string.gls__working_mode__all)
WorkingMode.LAST -> stringResource(id = R.string.gls__working_mode__last)
WorkingMode.FIRST -> stringResource(id = R.string.gls__working_mode__first)
}
}
@Composable
internal fun glucoseConcentrationDisplayValue(value: Float, unit: ConcentrationUnit): String {
val result = when (unit) {
ConcentrationUnit.UNIT_KGPL -> value * 100000.0f
ConcentrationUnit.UNIT_MOLPL -> value * 1000.0f
}
return String.format("%.2f %s", result, unit.toDisplayString())
}
| bsd-3-clause | 61ce6d7f73cd0a224f23d634aab7400d | 47.759036 | 110 | 0.745738 | 4.108629 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/collections/CollectionsManager.kt | 1 | 19261 | package com.openlattice.collections
import com.google.common.base.Preconditions.checkArgument
import com.google.common.base.Preconditions.checkState
import com.google.common.collect.Sets
import com.google.common.eventbus.EventBus
import com.hazelcast.aggregation.Aggregators
import com.hazelcast.core.HazelcastInstance
import com.hazelcast.query.Predicate
import com.hazelcast.query.Predicates
import com.openlattice.authorization.*
import com.openlattice.authorization.securable.SecurableObjectType
import com.openlattice.collections.aggregators.EntitySetCollectionConfigAggregator
import com.openlattice.collections.mapstores.ENTITY_SET_COLLECTION_ID_INDEX
import com.openlattice.collections.mapstores.ENTITY_TYPE_COLLECTION_ID_INDEX
import com.openlattice.collections.mapstores.ID_INDEX
import com.openlattice.collections.processors.AddPairToEntityTypeCollectionTemplateProcessor
import com.openlattice.collections.processors.RemoveKeyFromEntityTypeCollectionTemplateProcessor
import com.openlattice.collections.processors.UpdateEntitySetCollectionMetadataProcessor
import com.openlattice.collections.processors.UpdateEntityTypeCollectionMetadataProcessor
import com.openlattice.controllers.exceptions.ForbiddenException
import com.openlattice.datastore.services.EdmManager
import com.openlattice.datastore.services.EntitySetManager
import com.openlattice.edm.EntitySet
import com.openlattice.edm.events.EntitySetCollectionCreatedEvent
import com.openlattice.edm.events.EntitySetCollectionDeletedEvent
import com.openlattice.edm.events.EntityTypeCollectionCreatedEvent
import com.openlattice.edm.events.EntityTypeCollectionDeletedEvent
import com.openlattice.edm.requests.MetadataUpdate
import com.openlattice.edm.schemas.manager.HazelcastSchemaManager
import com.openlattice.edm.set.EntitySetFlag
import com.openlattice.hazelcast.HazelcastMap
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import org.springframework.stereotype.Service
import java.util.*
@Service
@SuppressFBWarnings("NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE")
class CollectionsManager(
hazelcast: HazelcastInstance,
private val edmManager: EdmManager,
private val entitySetManager: EntitySetManager,
private val aclKeyReservations: HazelcastAclKeyReservationService,
private val schemaManager: HazelcastSchemaManager,
private val authorizations: AuthorizationManager,
private val eventBus: EventBus
) {
private val entityTypeCollections = HazelcastMap.ENTITY_TYPE_COLLECTIONS.getMap(hazelcast)
private val entitySetCollections = HazelcastMap.ENTITY_SET_COLLECTIONS.getMap(hazelcast)
private val entitySetCollectionConfig = HazelcastMap.ENTITY_SET_COLLECTION_CONFIG.getMap(hazelcast)
/** READ **/
fun getAllEntityTypeCollections(): Iterable<EntityTypeCollection> {
return entityTypeCollections.values
}
fun getEntityTypeCollection(id: UUID): EntityTypeCollection {
return entityTypeCollections[id] ?: throw IllegalStateException("EntityTypeCollection $id does not exist")
}
fun getEntityTypeCollections(ids: Set<UUID>): Map<UUID, EntityTypeCollection> {
return entityTypeCollections.getAll(ids)
}
fun getEntitySetCollection(id: UUID): EntitySetCollection {
val entitySetCollection = entitySetCollections[id]
?: throw IllegalStateException("EntitySetCollection $id does not exist")
entitySetCollection.template = getTemplatesForIds(setOf(id))[id] ?: mutableMapOf()
return entitySetCollection
}
fun getEntitySetCollections(ids: Set<UUID>): Map<UUID, EntitySetCollection> {
val templates = getTemplatesForIds(ids)
val collections = entitySetCollections.getAll(ids)
collections.forEach { it.value.template = templates[it.key] ?: mutableMapOf() }
return collections
}
fun getEntitySetCollectionsOfType(ids: Set<UUID>, entityTypeCollectionId: UUID): Iterable<EntitySetCollection> {
val templates = getTemplatesForIds(ids)
val collections = entitySetCollections.values(
Predicates.and(
idsPredicate(ids),
entityTypeCollectionIdPredicate(
entityTypeCollectionId
)
)
)
collections.map { it.template = templates[it.id] ?: mutableMapOf() }
return collections
}
/** CREATE **/
fun createEntityTypeCollection(entityTypeCollection: EntityTypeCollection): UUID {
val entityTypeIds = entityTypeCollection.template.map { it.entityTypeId }.toSet()
val nonexistentEntityTypeIds = Sets.difference(
entityTypeIds,
edmManager.getEntityTypesAsMap(entityTypeIds).keys
)
if (nonexistentEntityTypeIds.isNotEmpty()) {
throw IllegalStateException("EntityTypeCollection contains entityTypeIds that do not exist: $nonexistentEntityTypeIds")
}
aclKeyReservations.reserveIdAndValidateType(entityTypeCollection)
val existingEntityTypeCollection = entityTypeCollections.putIfAbsent(
entityTypeCollection.id,
entityTypeCollection
)
if (existingEntityTypeCollection == null) {
schemaManager.upsertSchemas(entityTypeCollection.schemas)
} else {
throw IllegalStateException("EntityTypeCollection ${entityTypeCollection.type} with id ${entityTypeCollection.id} already exists")
}
eventBus.post(EntityTypeCollectionCreatedEvent(entityTypeCollection))
return entityTypeCollection.id
}
fun createEntitySetCollection(entitySetCollection: EntitySetCollection, autoCreate: Boolean): UUID {
val principal = Principals.getCurrentUser()
Principals.ensureUser(principal)
val entityTypeCollectionId = entitySetCollection.entityTypeCollectionId
val template = entityTypeCollections[entityTypeCollectionId]?.template ?: throw IllegalStateException(
"Cannot create EntitySetCollection ${entitySetCollection.id} because EntityTypeCollection $entityTypeCollectionId does not exist."
)
if (!autoCreate) {
checkArgument(
template.map { it.id }.toSet() == entitySetCollection.template.keys,
"EntitySetCollection ${entitySetCollection.name} template keys do not match its EntityTypeCollection template."
)
}
validateEntitySetCollectionTemplate(entitySetCollection.name, entitySetCollection.template, template)
aclKeyReservations.reserveIdAndValidateType(entitySetCollection, entitySetCollection::name)
checkState(
entitySetCollections.putIfAbsent(entitySetCollection.id, entitySetCollection) == null,
"EntitySetCollection ${entitySetCollection.name} already exists."
)
val templateTypesToCreate = template.filter { !entitySetCollection.template.keys.contains(it.id) }
if (templateTypesToCreate.isNotEmpty()) {
val userPrincipal = Principals.getCurrentUser()
val entitySetsCreated = templateTypesToCreate.associate {
it.id to generateEntitySet(
entitySetCollection,
it,
userPrincipal
)
}
entitySetCollection.template.putAll(entitySetsCreated)
}
entitySetCollectionConfig.putAll(entitySetCollection.template.entries.associate {
CollectionTemplateKey(
entitySetCollection.id,
it.key
) to it.value
})
authorizations.setSecurableObjectType(AclKey(entitySetCollection.id), SecurableObjectType.EntitySetCollection)
authorizations.addPermission(
AclKey(entitySetCollection.id),
principal,
EnumSet.allOf(Permission::class.java)
)
eventBus.post(EntitySetCollectionCreatedEvent(entitySetCollection))
return entitySetCollection.id
}
/** UPDATE **/
fun updateEntityTypeCollectionMetadata(id: UUID, update: MetadataUpdate) {
ensureEntityTypeCollectionExists(id)
if (update.type.isPresent) {
aclKeyReservations.renameReservation(id, update.type.get())
}
entityTypeCollections.submitToKey(id, UpdateEntityTypeCollectionMetadataProcessor(update))
signalEntityTypeCollectionUpdated(id)
}
fun addTypeToEntityTypeCollectionTemplate(id: UUID, collectionTemplateType: CollectionTemplateType) {
ensureEntityTypeCollectionExists(id)
edmManager.ensureEntityTypeExists(collectionTemplateType.entityTypeId)
val entityTypeCollection = entityTypeCollections[id]!!
if (entityTypeCollection.template.any { it.id == collectionTemplateType.id || it.name == collectionTemplateType.name }) {
throw IllegalArgumentException("Id or name of CollectionTemplateType $collectionTemplateType is already used on template of EntityTypeCollection $id.")
}
updateEntitySetCollectionsForNewType(id, collectionTemplateType)
entityTypeCollections.executeOnKey(id, AddPairToEntityTypeCollectionTemplateProcessor(collectionTemplateType))
signalEntityTypeCollectionUpdated(id)
}
private fun updateEntitySetCollectionsForNewType(
entityTypeCollectionId: UUID, collectionTemplateType: CollectionTemplateType
) {
val entitySetCollectionsToUpdate = entitySetCollections.values(
entityTypeCollectionIdPredicate(
entityTypeCollectionId
)
).associate { it.id to it }
val entitySetCollectionOwners = authorizations.getOwnersForSecurableObjects(entitySetCollectionsToUpdate.keys.map {
AclKey(
it
)
}.toSet())
val entitySetsCreated = entitySetCollectionsToUpdate.values.associate {
it.id to generateEntitySet(
it,
collectionTemplateType,
entitySetCollectionOwners.get(AclKey(it.id)).first { p -> p.type == PrincipalType.USER })
}
val propertyTypeIds = edmManager.getEntityType(collectionTemplateType.entityTypeId).properties
val ownerPermissions = EnumSet.allOf(Permission::class.java)
val permissionsToAdd = mutableMapOf<AceKey, EnumSet<Permission>>()
entitySetsCreated.forEach {
val entitySetCollectionId = it.key
val entitySetId = it.value
entitySetCollectionOwners.get(AclKey(entitySetCollectionId)).forEach { owner ->
permissionsToAdd[AceKey(AclKey(entitySetId), owner)] = ownerPermissions
propertyTypeIds.forEach { ptId ->
permissionsToAdd[AceKey(
AclKey(entitySetId, ptId),
owner
)] = ownerPermissions
}
}
entitySetCollectionsToUpdate.getValue(entitySetCollectionId).template[collectionTemplateType.id] = entitySetId
}
authorizations.setPermissions(permissionsToAdd)
entitySetCollectionConfig.putAll(entitySetCollectionsToUpdate.keys.associate {
CollectionTemplateKey(
it,
collectionTemplateType.id
) to entitySetsCreated.getValue(it)
})
entitySetCollectionsToUpdate.values.forEach { eventBus.post(EntitySetCollectionCreatedEvent(it)) }
}
fun removeKeyFromEntityTypeCollectionTemplate(id: UUID, templateTypeId: UUID) {
ensureEntityTypeCollectionExists(id)
ensureEntityTypeCollectionNotInUse(id)
entityTypeCollections.executeOnKey(id, RemoveKeyFromEntityTypeCollectionTemplateProcessor(templateTypeId))
signalEntityTypeCollectionUpdated(id)
}
fun updateEntitySetCollectionMetadata(id: UUID, update: MetadataUpdate) {
ensureEntitySetCollectionExists(id)
if (update.name.isPresent) {
aclKeyReservations.renameReservation(id, update.name.get())
}
if (update.organizationId.isPresent) {
if (!authorizations.checkIfHasPermissions(
AclKey(update.organizationId.get()),
Principals.getCurrentPrincipals(),
EnumSet.of(Permission.READ)
)) {
throw ForbiddenException("Cannot update EntitySetCollection $id with organization id ${update.organizationId.get()}")
}
}
entitySetCollections.submitToKey(id, UpdateEntitySetCollectionMetadataProcessor(update))
signalEntitySetCollectionUpdated(id)
}
fun updateEntitySetCollectionTemplate(id: UUID, templateUpdates: Map<UUID, UUID>) {
val entitySetCollection = entitySetCollections[id]
?: throw IllegalStateException("EntitySetCollection $id does not exist")
val entityTypeCollectionId = entitySetCollection.entityTypeCollectionId
val template = entityTypeCollections[entityTypeCollectionId]?.template ?: throw IllegalStateException(
"Cannot update EntitySetCollection ${entitySetCollection.id} because EntityTypeCollection $entityTypeCollectionId does not exist."
)
entitySetCollection.template.putAll(templateUpdates)
validateEntitySetCollectionTemplate(entitySetCollection.name, entitySetCollection.template, template)
entitySetCollectionConfig.putAll(templateUpdates.entries.associate {
CollectionTemplateKey(
id,
it.key
) to it.value
})
eventBus.post(EntitySetCollectionCreatedEvent(entitySetCollection))
}
/** DELETE **/
fun deleteEntityTypeCollection(id: UUID) {
ensureEntityTypeCollectionNotInUse(id)
entityTypeCollections.remove(id)
aclKeyReservations.release(id)
eventBus.post(EntityTypeCollectionDeletedEvent(id))
}
fun deleteEntitySetCollection(id: UUID) {
entitySetCollections.remove(id)
aclKeyReservations.release(id)
entitySetCollectionConfig.removeAll(Predicates.equal(ENTITY_SET_COLLECTION_ID_INDEX, id))
eventBus.post(EntitySetCollectionDeletedEvent(id))
}
/** validation **/
fun ensureEntityTypeCollectionExists(id: UUID) {
if (!entityTypeCollections.containsKey(id)) {
throw IllegalStateException("EntityTypeCollection $id does not exist.")
}
}
fun ensureEntitySetCollectionExists(id: UUID) {
if (!entitySetCollections.containsKey(id)) {
throw IllegalStateException("EntitySetCollection $id does not exist.")
}
}
private fun ensureEntityTypeCollectionNotInUse(id: UUID) {
val numEntitySetCollectionsOfType = entitySetCollections.aggregate(
Aggregators.count(),
entityTypeCollectionIdPredicate(id)
)
checkState(
numEntitySetCollectionsOfType == 0L,
"EntityTypeCollection $id cannot be deleted or modified because there exist $numEntitySetCollectionsOfType EntitySetCollections that use it"
)
}
private fun validateEntitySetCollectionTemplate(
name: String, mappings: Map<UUID, UUID>, template: LinkedHashSet<CollectionTemplateType>
) {
val entitySets = entitySetManager.getEntitySetsAsMap(mappings.values.toSet())
val templateEntityTypesById = template.map { it.id to it.entityTypeId }.toMap()
mappings.forEach {
val id = it.key
val entitySetId = it.value
val entitySet = entitySets[entitySetId]
?: throw IllegalStateException("Could not create/update EntitySetCollection $name because entity set $entitySetId does not exist.")
if (entitySet.entityTypeId != templateEntityTypesById[id]) {
throw IllegalStateException(
"Could not create/update EntitySetCollection $name because entity set" +
" $entitySetId for key $id does not match template entity type ${templateEntityTypesById[id]}."
)
}
}
}
/** predicates **/
private fun idsPredicate(ids: Collection<UUID>): Predicate<UUID, EntitySetCollection> {
return Predicates.`in`(ID_INDEX, *ids.toTypedArray())
}
private fun entityTypeCollectionIdPredicate(entityTypeCollectionId: UUID): Predicate<UUID, EntitySetCollection> {
return Predicates.equal(ENTITY_TYPE_COLLECTION_ID_INDEX, entityTypeCollectionId)
}
private fun entitySetCollectionIdsPredicate(ids: Set<UUID>): Predicate<CollectionTemplateKey, UUID> {
return Predicates.`in`(ENTITY_SET_COLLECTION_ID_INDEX, *ids.toTypedArray())
}
/** helpers **/
private fun formatEntitySetName(prefix: String, templateTypeName: String): String {
var name = prefix + "_" + templateTypeName
name = name.toLowerCase().replace("[^a-z0-9_]".toRegex(), "")
return getNextAvailableName(name)
}
private fun generateEntitySet(
entitySetCollection: EntitySetCollection,
collectionTemplateType: CollectionTemplateType,
principal: Principal
): UUID {
val name = formatEntitySetName(entitySetCollection.name, collectionTemplateType.name)
val title = collectionTemplateType.title + " (" + entitySetCollection.name + ")"
val description = "${collectionTemplateType.description}\n\nAuto-generated for EntitySetCollection ${entitySetCollection.name}"
val flags = EnumSet.noneOf(EntitySetFlag::class.java)
val entitySet = EntitySet(
entityTypeId = collectionTemplateType.entityTypeId,
name = name,
_title = title,
_description = description,
contacts = mutableSetOf(),
organizationId = entitySetCollection.organizationId,
flags = flags
)
entitySetManager.createEntitySet(principal, entitySet)
return entitySet.id
}
private fun getNextAvailableName(name: String): String {
var nameAttempt = name
var counter = 1
while (aclKeyReservations.isReserved(nameAttempt)) {
nameAttempt = name + "_" + counter.toString()
counter++
}
return nameAttempt
}
private fun getTemplatesForIds(ids: Set<UUID>): MutableMap<UUID, MutableMap<UUID, UUID>> {
return entitySetCollectionConfig.aggregate(
EntitySetCollectionConfigAggregator(CollectionTemplates()),
entitySetCollectionIdsPredicate(ids)
).templates
}
private fun signalEntityTypeCollectionUpdated(id: UUID) {
eventBus.post(EntityTypeCollectionCreatedEvent(entityTypeCollections.getValue(id)))
}
private fun signalEntitySetCollectionUpdated(id: UUID) {
eventBus.post(EntitySetCollectionCreatedEvent(getEntitySetCollection(id)))
}
} | gpl-3.0 | b2bc71c60f68556050692a884f893c61 | 39.551579 | 163 | 0.693889 | 6.002181 | false | false | false | false |
backpaper0/syobotsum | core/src/syobotsum/screen/ResultScreen.kt | 1 | 3435 | package syobotsum.screen
import syobotsum.Syobotsum
import syobotsum.actor.forResult
import syobotsum.actor.Block
import syobotsum.actor.Block.BlockType
import syobotsum.actor.BlockField
import syobotsum.actor.BlockResult
import syobotsum.actor.ExitDialog
import com.badlogic.gdx.scenes.scene2d.Action
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.ui.Dialog
import com.badlogic.gdx.scenes.scene2d.ui.Image
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.Align
/**
* 結果画面
*
*/
class ResultScreen(syobotsum: Syobotsum, val blocks: BlockField) : ScreenSkeleton(syobotsum) {
init {
Image(skin, "resultBackground").let {
it.setPosition(0f, 0f)
stage.addActor(it)
}
Image(skin, "resultTitle").let {
it.setPosition(stage.width / 2f, stage.height - 50f, Align.center or Align.top)
stage.addActor(it)
}
val max = blocks.findMax()
val centerBottom = Align.center or Align.bottom
val centerX = stage.width / 2f
BlockResult(skin, "resultHeart", max, BlockType.HEART).let {
it.setPosition(centerX, 650f, centerBottom)
stage.addActor(it)
}
BlockResult(skin, "resultRedking", max, BlockType.REDKING).let {
it.setPosition(centerX, 530f, centerBottom)
stage.addActor(it)
}
val otherResult = BlockResult(skin, "resultOther", max, BlockType.OTHER)
otherResult.setPosition(centerX, 410f, centerBottom)
stage.addActor(otherResult)
var value = 0
var b = max
while (b != null) {
value = value + b.blockType.calc(1)
b = b.under
}
val result = Label(String.format("%03d", value), skin, "score")
result.setPosition(otherResult.getX(Align.right), 250f, Align.bottomRight)
stage.addActor(result)
Image(skin, "resultJoshiryoku").let {
it.setPosition(result.x, 230f, Align.bottomRight)
stage.addActor(it)
}
val restart = Button(skin, "resultRestart")
restart.setPosition((stage.width - (restart.width * 2f)) / 3f, restart.height / 2f)
stage.addActor(restart)
val exit = Button(skin, "resultExit")
exit.setPosition(exit.width + ((stage.width - (exit.width * 2f)) * 2f / 3f), exit.height / 2f)
stage.addActor(exit)
exit.addListener(object : ClickListener() {
override fun clicked(event: InputEvent, x: Float, y: Float) {
val dialog = forResult(skin)
dialog.show(stage)
}
})
restart.addListener(object : ClickListener() {
override fun clicked(event: InputEvent, x: Float, y: Float) {
val fadeOut = Actions.fadeOut(0.5f)
val toGameScreen = Actions.run(Runnable {
syobotsum.screen = GameScreen(syobotsum)
})
stage.addAction(Actions.sequence(fadeOut, toGameScreen))
}
})
val toTransparent = Actions.alpha(0f)
val fadeIn = Actions.fadeIn(0.5f)
stage.addAction(Actions.sequence(toTransparent, fadeIn))
}
}
| apache-2.0 | 2e2643ffe9662098f8a45adab48d8134 | 33.27 | 102 | 0.632915 | 3.90764 | false | false | false | false |
Arasthel/SpannedGridLayoutManager | spannedgridlayoutmanager/src/main/java/com/arasthel/spannedgridlayoutmanager/SpannedGridLayoutManager.kt | 1 | 32122 | /*
* Copyright © 2017 Jorge Martín Espinosa
*/
package com.arasthel.spannedgridlayoutmanager
import android.graphics.PointF
import android.graphics.Rect
import android.os.Parcel
import android.os.Parcelable
import android.support.v7.widget.LinearSmoothScroller
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.util.SparseArray
import android.view.View
/**
* A [android.support.v7.widget.RecyclerView.LayoutManager] which layouts and orders its views
* based on width and height spans.
*
* @param orientation Whether the views will be layouted and scrolled in vertical or horizontal
* @param spans How many spans does the layout have per row or column
*/
open class SpannedGridLayoutManager(val orientation: Orientation,
val spans: Int) : RecyclerView.LayoutManager() {
//==============================================================================================
// ~ Orientation & Direction enums
//==============================================================================================
/**
* Orientations to layout and scroll views
* <li>VERTICAL</li>
* <li>HORIZONTAL</li>
*/
enum class Orientation {
VERTICAL, HORIZONTAL
}
/**
* Direction of scroll for layouting process
* <li>START</li>
* <li>END</li>
*/
enum class Direction {
START, END
}
//==============================================================================================
// ~ Properties
//==============================================================================================
/**
* Current scroll amount
*/
protected var scroll = 0
/**
* Helper get free rects to place views
*/
protected lateinit var rectsHelper: RectsHelper
/**
* First visible position in layout - changes with recycling
*/
open val firstVisiblePosition: Int get() {
if (childCount == 0) { return 0 }
return getPosition(getChildAt(0)!!)
}
/**
* Last visible position in layout - changes with recycling
*/
open val lastVisiblePosition: Int get() {
if (childCount == 0) { return 0 }
return getPosition(getChildAt(childCount-1)!!)
}
/**
* Start of the layout. Should be [getPaddingEndForOrientation] + first visible item top
*/
protected var layoutStart = 0
/**
* End of the layout. Should be [layoutStart] + last visible item bottom + [getPaddingEndForOrientation]
*/
protected var layoutEnd = 0
/**
* Total length of the layout depending on current orientation
*/
val size: Int get() = if (orientation == Orientation.VERTICAL) height else width
/**
* Cache of rects for layouted views
*/
protected val childFrames = mutableMapOf<Int, Rect>()
/**
* Temporary variable to store wanted scroll by [scrollToPosition]
*/
protected var pendingScrollToPosition: Int? = null
/**
* Whether item order will be kept along re-creations of this LayoutManager with different
* configurations of not. Default is false. Only set to true if this condition is met.
* Otherwise, scroll bugs will happen.
*/
var itemOrderIsStable = false
/**
* Provides SpanSize values for the LayoutManager. Otherwise they will all be (1, 1).
*/
var spanSizeLookup: SpanSizeLookup? = null
set(newValue) {
field = newValue
// If the SpanSizeLookup changes, the views need a whole re-layout
requestLayout()
}
/**
* SpanSize provider for this LayoutManager.
* SpanSizes can be cached to improve efficiency.
*/
open class SpanSizeLookup(
/** Used to provide an SpanSize for each item. */
var lookupFunction: ((Int) -> SpanSize)? = null
) {
private var cache = SparseArray<SpanSize>()
/**
* Enable SpanSize caching. Can be used to improve performance if calculating the SpanSize
* for items is a complex process.
*/
var usesCache = false
/**
* Returns an SpanSize for the provided position.
* @param position Adapter position of the item
* @return An SpanSize, either provided by the user or the default one.
*/
fun getSpanSize(position: Int): SpanSize {
if (usesCache) {
val cachedValue = cache[position]
if (cachedValue != null) return cachedValue
val value = getSpanSizeFromFunction(position)
cache.put(position, value)
return value
} else {
return getSpanSizeFromFunction(position)
}
}
private fun getSpanSizeFromFunction(position: Int): SpanSize {
return lookupFunction?.invoke(position) ?: getDefaultSpanSize()
}
protected open fun getDefaultSpanSize(): SpanSize {
return SpanSize(1, 1)
}
fun invalidateCache() {
cache.clear()
}
}
//==============================================================================================
// ~ Initializer
//==============================================================================================
init {
if (spans < 1) {
throw InvalidMaxSpansException(spans)
}
}
//==============================================================================================
// ~ Override parent
//==============================================================================================
override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
return RecyclerView.LayoutParams(
RecyclerView.LayoutParams.MATCH_PARENT,
RecyclerView.LayoutParams.WRAP_CONTENT
)
}
//==============================================================================================
// ~ View layouting methods
//==============================================================================================
override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
rectsHelper = RectsHelper(this, orientation)
layoutStart = getPaddingStartForOrientation()
layoutEnd = if (scroll != 0) {
val currentRow = (scroll - layoutStart) / rectsHelper.itemSize
currentRow * rectsHelper.itemSize
} else {
getPaddingEndForOrientation()
}
// Clear cache, since layout may change
childFrames.clear()
// If there were any views, detach them so they can be recycled
detachAndScrapAttachedViews(recycler)
val start = System.currentTimeMillis()
for (i in 0 until state.itemCount) {
val spanSize = spanSizeLookup?.getSpanSize(i) ?: SpanSize(1, 1)
val childRect = rectsHelper.findRect(i, spanSize)
rectsHelper.pushRect(i, childRect)
}
if (DEBUG) {
val elapsed = System.currentTimeMillis() - start
debugLog("Elapsed time: $elapsed ms")
}
// Restore scroll position based on first visible view
val pendingScrollToPosition = pendingScrollToPosition
if (itemCount != 0 && pendingScrollToPosition != null && pendingScrollToPosition >= spans) {
val currentRow = rectsHelper.rows.filter { (_, value) -> value.contains(pendingScrollToPosition) }.keys.firstOrNull()
if (currentRow != null) {
scroll = getPaddingStartForOrientation() + (currentRow * rectsHelper.itemSize)
}
this.pendingScrollToPosition = null
}
// Fill from start to visible end
fillGap(Direction.END, recycler, state)
recycleChildrenOutOfBounds(Direction.END, recycler)
// Check if after changes in layout we aren't out of its bounds
val overScroll = scroll + size - layoutEnd - getPaddingEndForOrientation()
val isLastItemInScreen = (0 until childCount).map { getPosition(getChildAt(it)!!) }.contains(itemCount - 1)
val allItemsInScreen = itemCount == 0 || (firstVisiblePosition == 0 && isLastItemInScreen)
if (!allItemsInScreen && overScroll > 0) {
// If we are, fix it
scrollBy(overScroll, state)
if (overScroll > 0) {
fillBefore(recycler)
} else {
fillAfter(recycler)
}
}
}
/**
* Measure child view using [RectsHelper]
*/
protected open fun measureChild(position: Int, view: View) {
val freeRectsHelper = this.rectsHelper
val itemWidth = freeRectsHelper.itemSize
val itemHeight = freeRectsHelper.itemSize
val spanSize = spanSizeLookup?.getSpanSize(position) ?: SpanSize(1, 1)
val usedSpan = if (orientation == Orientation.HORIZONTAL) spanSize.height else spanSize.width
if (usedSpan > this.spans || usedSpan < 1) {
throw InvalidSpanSizeException(errorSize = usedSpan, maxSpanSize = spans)
}
// This rect contains just the row and column number - i.e.: [0, 0, 1, 1]
val rect = freeRectsHelper.findRect(position, spanSize)
// Multiply the rect for item width and height to get positions
val left = rect.left * itemWidth
val right = rect.right * itemWidth
val top = rect.top * itemHeight
val bottom = rect.bottom * itemHeight
val insetsRect = Rect()
calculateItemDecorationsForChild(view, insetsRect)
// Measure child
val width = right - left - insetsRect.left - insetsRect.right
val height = bottom - top - insetsRect.top - insetsRect.bottom
val layoutParams = view.layoutParams
layoutParams.width = width
layoutParams.height = height
measureChildWithMargins(view, width, height)
// Cache rect
childFrames[position] = Rect(left, top, right, bottom)
}
/**
* Layout child once it's measured and its position cached
*/
protected open fun layoutChild(position: Int, view: View) {
val frame = childFrames[position]
if (frame != null) {
val scroll = this.scroll
val startPadding = getPaddingStartForOrientation()
if (orientation == Orientation.VERTICAL) {
layoutDecorated(view,
frame.left + paddingLeft,
frame.top - scroll + startPadding,
frame.right + paddingLeft,
frame.bottom - scroll + startPadding)
} else {
layoutDecorated(view,
frame.left - scroll + startPadding,
frame.top + paddingTop,
frame.right - scroll + startPadding,
frame.bottom + paddingTop)
}
}
// A new child was layouted, layout edges change
updateEdgesWithNewChild(view)
}
/**
* Ask the recycler for a view, measure and layout it and add it to the layout
*/
protected open fun makeAndAddView(position: Int, direction: Direction, recycler: RecyclerView.Recycler): View {
val view = makeView(position, direction, recycler)
if (direction == Direction.END) {
addView(view)
} else {
addView(view, 0)
}
return view
}
protected open fun makeView(position: Int, direction: Direction, recycler: RecyclerView.Recycler): View {
val view = recycler.getViewForPosition(position)
measureChild(position, view)
layoutChild(position, view)
return view
}
/**
* A new view was added, update layout edges if needed
*/
protected open fun updateEdgesWithNewChild(view: View) {
val childStart = getChildStart(view) + scroll + getPaddingStartForOrientation()
if (childStart < layoutStart) {
layoutStart = childStart
}
val newLayoutEnd = childStart + rectsHelper.itemSize
if (newLayoutEnd > layoutEnd) {
layoutEnd = newLayoutEnd
}
}
//==============================================================================================
// ~ Recycling methods
//==============================================================================================
/**
* Recycle any views that are out of bounds
*/
protected open fun recycleChildrenOutOfBounds(direction: Direction, recycler: RecyclerView.Recycler) {
if (direction == Direction.END) {
recycleChildrenFromStart(direction, recycler)
} else {
recycleChildrenFromEnd(direction, recycler)
}
}
/**
* Recycle views from start to first visible item
*/
protected open fun recycleChildrenFromStart(direction: Direction, recycler: RecyclerView.Recycler) {
val childCount = childCount
val start = getPaddingStartForOrientation()
val toDetach = mutableListOf<View>()
for (i in 0 until childCount) {
val child = getChildAt(i)!!
val childEnd = getChildEnd(child)
if (childEnd < start) {
toDetach.add(child)
}
}
for (child in toDetach) {
removeAndRecycleView(child, recycler)
updateEdgesWithRemovedChild(child, direction)
}
}
/**
* Recycle views from end to last visible item
*/
protected open fun recycleChildrenFromEnd(direction: Direction, recycler: RecyclerView.Recycler) {
val childCount = childCount
val end = size + getPaddingEndForOrientation()
val toDetach = mutableListOf<View>()
for (i in (0 until childCount).reversed()) {
val child = getChildAt(i)!!
val childStart = getChildStart(child)
if (childStart > end) {
toDetach.add(child)
}
}
for (child in toDetach) {
removeAndRecycleView(child, recycler)
updateEdgesWithRemovedChild(child, direction)
}
}
/**
* Update layout edges when views are recycled
*/
protected open fun updateEdgesWithRemovedChild(view: View, direction: Direction) {
val childStart = getChildStart(view) + scroll
val childEnd = getChildEnd(view) + scroll
if (direction == Direction.END) { // Removed from start
layoutStart = getPaddingStartForOrientation() + childEnd
} else if (direction == Direction.START) { // Removed from end
layoutEnd = getPaddingStartForOrientation() + childStart
}
}
//==============================================================================================
// ~ Scroll methods
//==============================================================================================
override fun computeVerticalScrollOffset(state: RecyclerView.State): Int {
return computeScrollOffset()
}
override fun computeHorizontalScrollOffset(state: RecyclerView.State): Int {
return computeScrollOffset()
}
private fun computeScrollOffset(): Int {
return if (childCount == 0) 0 else firstVisiblePosition
}
override fun computeVerticalScrollExtent(state: RecyclerView.State): Int {
return childCount
}
override fun computeHorizontalScrollExtent(state: RecyclerView.State): Int {
return childCount
}
override fun computeVerticalScrollRange(state: RecyclerView.State): Int {
return state.itemCount
}
override fun computeHorizontalScrollRange(state: RecyclerView.State): Int {
return state.itemCount
}
override fun canScrollVertically(): Boolean {
return orientation == Orientation.VERTICAL
}
override fun canScrollHorizontally(): Boolean {
return orientation == Orientation.HORIZONTAL
}
override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
return scrollBy(dx, recycler, state)
}
override fun scrollVerticallyBy(dy: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
return scrollBy(dy, recycler, state)
}
protected open fun scrollBy(delta: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
// If there are no view or no movement, return
if (delta == 0) {
return 0
}
val canScrollBackwards = (firstVisiblePosition) >= 0 &&
0 < scroll &&
delta < 0
val canScrollForward = (firstVisiblePosition + childCount) <= state.itemCount &&
(scroll + size) < (layoutEnd + rectsHelper.itemSize + getPaddingEndForOrientation())
delta > 0
// If can't scroll forward or backwards, return
if (!(canScrollBackwards || canScrollForward)) {
return 0
}
val correctedDistance = scrollBy(-delta, state)
val direction = if (delta > 0) Direction.END else Direction.START
recycleChildrenOutOfBounds(direction, recycler)
fillGap(direction, recycler, state)
return -correctedDistance
}
/**
* Scrolls distance based on orientation. Corrects distance if out of bounds.
*/
protected open fun scrollBy(distance: Int, state: RecyclerView.State): Int {
val paddingEndLayout = getPaddingEndForOrientation()
val start = 0
val end = layoutEnd + rectsHelper.itemSize + paddingEndLayout
scroll -= distance
var correctedDistance = distance
// Correct scroll if was out of bounds at start
if (scroll < start) {
correctedDistance += scroll
scroll = start
}
// Correct scroll if it would make the layout scroll out of bounds at the end
if (scroll + size > end && (firstVisiblePosition + childCount + spans) >= state.itemCount) {
correctedDistance -= (end - scroll - size)
scroll = end - size
}
if (orientation == Orientation.VERTICAL) {
offsetChildrenVertical(correctedDistance)
} else{
offsetChildrenHorizontal(correctedDistance)
}
return correctedDistance
}
override fun scrollToPosition(position: Int) {
pendingScrollToPosition = position
requestLayout()
}
override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {
val smoothScroller = object: LinearSmoothScroller(recyclerView.context) {
override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
if (childCount == 0) {
return null
}
val direction = if (targetPosition < firstVisiblePosition) -1 else 1
return PointF(0f, direction.toFloat())
}
override fun getVerticalSnapPreference(): Int {
return LinearSmoothScroller.SNAP_TO_START
}
}
smoothScroller.targetPosition = position
startSmoothScroll(smoothScroller)
}
/**
* Fills gaps on the layout, on directions [Direction.START] or [Direction.END]
*/
protected open fun fillGap(direction: Direction, recycler: RecyclerView.Recycler, state: RecyclerView.State) {
if (direction == Direction.END) {
fillAfter(recycler)
} else {
fillBefore(recycler)
}
}
/**
* Fill gaps before the current visible scroll position
* @param recycler Recycler
*/
protected open fun fillBefore(recycler: RecyclerView.Recycler) {
val currentRow = (scroll - getPaddingStartForOrientation()) / rectsHelper.itemSize
val lastRow = (scroll + size - getPaddingStartForOrientation()) / rectsHelper.itemSize
for (row in (currentRow until lastRow).reversed()) {
val positionsForRow = rectsHelper.findPositionsForRow(row).reversed()
for (position in positionsForRow) {
if (findViewByPosition(position) != null) continue
makeAndAddView(position, Direction.START, recycler)
}
}
}
/**
* Fill gaps after the current layouted views
* @param recycler Recycler
*/
protected open fun fillAfter(recycler: RecyclerView.Recycler) {
val visibleEnd = scroll + size
val lastAddedRow = layoutEnd / rectsHelper.itemSize
val lastVisibleRow = visibleEnd / rectsHelper.itemSize
for (rowIndex in lastAddedRow .. lastVisibleRow) {
val row = rectsHelper.rows[rowIndex] ?: continue
for (itemIndex in row) {
if (findViewByPosition(itemIndex) != null) continue
makeAndAddView(itemIndex, Direction.END, recycler)
}
}
}
//==============================================================================================
// ~ Decorated position and sizes
//==============================================================================================
override fun getDecoratedMeasuredWidth(child: View): Int {
val position = getPosition(child)
return childFrames[position]!!.width()
}
override fun getDecoratedMeasuredHeight(child: View): Int {
val position = getPosition(child)
return childFrames[position]!!.height()
}
override fun getDecoratedTop(child: View): Int {
val position = getPosition(child)
val decoration = getTopDecorationHeight(child)
var top = childFrames[position]!!.top + decoration
if (orientation == Orientation.VERTICAL) {
top -= scroll
}
return top
}
override fun getDecoratedRight(child: View): Int {
val position = getPosition(child)
val decoration = getLeftDecorationWidth(child) + getRightDecorationWidth(child)
var right = childFrames[position]!!.right + decoration
if (orientation == Orientation.HORIZONTAL) {
right -= scroll - getPaddingStartForOrientation()
}
return right
}
override fun getDecoratedLeft(child: View): Int {
val position = getPosition(child)
val decoration = getLeftDecorationWidth(child)
var left = childFrames[position]!!.left + decoration
if (orientation == Orientation.HORIZONTAL) {
left -= scroll
}
return left
}
override fun getDecoratedBottom(child: View): Int {
val position = getPosition(child)
val decoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child)
var bottom = childFrames[position]!!.bottom + decoration
if (orientation == Orientation.VERTICAL) {
bottom -= scroll - getPaddingStartForOrientation()
}
return bottom
}
//==============================================================================================
// ~ Orientation Utils
//==============================================================================================
protected open fun getPaddingStartForOrientation(): Int {
return if (orientation == Orientation.VERTICAL) {
paddingTop
} else {
paddingLeft
}
}
protected open fun getPaddingEndForOrientation(): Int {
return if (orientation == Orientation.VERTICAL) {
paddingBottom
} else {
paddingRight
}
}
protected open fun getChildStart(child: View): Int {
return if (orientation == Orientation.VERTICAL) {
getDecoratedTop(child)
} else {
getDecoratedLeft(child)
}
}
protected open fun getChildEnd(child: View): Int {
return if (orientation == Orientation.VERTICAL) {
getDecoratedBottom(child)
} else {
getDecoratedRight(child)
}
}
//==============================================================================================
// ~ Save & Restore State
//==============================================================================================
override fun onSaveInstanceState(): Parcelable? {
return if (itemOrderIsStable && childCount > 0) {
debugLog("Saving first visible position: $firstVisiblePosition")
SavedState(firstVisiblePosition)
} else {
null
}
}
override fun onRestoreInstanceState(state: Parcelable) {
debugLog("Restoring state")
val savedState = state as? SavedState
if (savedState != null) {
val firstVisibleItem = savedState.firstVisibleItem
scrollToPosition(firstVisibleItem)
}
}
companion object {
const val TAG = "SpannedGridLayoutMan"
const val DEBUG = false
fun debugLog(message: String) {
if (DEBUG) Log.d(TAG, message)
}
}
class SavedState(val firstVisibleItem: Int): Parcelable {
companion object {
@JvmField val CREATOR = object: Parcelable.Creator<SavedState> {
override fun createFromParcel(source: Parcel): SavedState {
return SavedState(source.readInt())
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(firstVisibleItem)
}
override fun describeContents(): Int {
return 0
}
}
}
/**
* A helper to find free rects in the current layout.
*/
open class RectsHelper(val layoutManager: SpannedGridLayoutManager,
val orientation: SpannedGridLayoutManager.Orientation) {
/**
* Comparator to sort free rects by position, based on orientation
*/
private val rectComparator = Comparator<Rect> { rect1, rect2 ->
when (orientation) {
SpannedGridLayoutManager.Orientation.VERTICAL -> {
if (rect1.top == rect2.top) {
if (rect1.left < rect2.left) { -1 } else { 1 }
} else {
if (rect1.top < rect2.top) { -1 } else { 1 }
}
}
SpannedGridLayoutManager.Orientation.HORIZONTAL -> {
if (rect1.left == rect2.left) {
if (rect1.top < rect2.top) { -1 } else { 1 }
} else {
if (rect1.left < rect2.left) { -1 } else { 1 }
}
}
}
}
val rows = mutableMapOf<Int, Set<Int>>()
/**
* Cache of rects that are already used
*/
private val rectsCache = mutableMapOf<Int, Rect>()
/**
* List of rects that are still free
*/
private val freeRects = mutableListOf<Rect>()
/**
* Free space to divide in spans
*/
val size: Int get() {
return if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL) {
layoutManager.width - layoutManager.paddingLeft - layoutManager.paddingRight
} else {
layoutManager.height - layoutManager.paddingTop - layoutManager.paddingBottom
}
}
/**
* Space occupied by each span
*/
val itemSize: Int get() = size / layoutManager.spans
/**
* Start row/column for free rects
*/
val start: Int get() {
return if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL) {
freeRects[0].top * itemSize
} else {
freeRects[0].left * itemSize
}
}
/**
* End row/column for free rects
*/
val end: Int get() {
return if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL) {
(freeRects.last().top + 1) * itemSize
} else {
(freeRects.last().left + 1) * itemSize
}
}
init {
// There will always be a free rect that goes to Int.MAX_VALUE
val initialFreeRect = if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL) {
Rect(0, 0, layoutManager.spans, Int.MAX_VALUE)
} else {
Rect(0, 0, Int.MAX_VALUE, layoutManager.spans)
}
freeRects.add(initialFreeRect)
}
/**
* Get a free rect for the given span and item position
*/
fun findRect(position: Int, spanSize: SpanSize): Rect {
return rectsCache[position] ?: findRectForSpanSize(spanSize)
}
/**
* Find a valid free rect for the given span size
*/
protected open fun findRectForSpanSize(spanSize: SpanSize): Rect {
val lane = freeRects.first {
val itemRect = Rect(it.left, it.top, it.left+spanSize.width, it.top + spanSize.height)
it.contains(itemRect)
}
return Rect(lane.left, lane.top, lane.left+spanSize.width, lane.top + spanSize.height)
}
/**
* Push this rect for the given position, subtract it from [freeRects]
*/
fun pushRect(position: Int, rect: Rect) {
val start = if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL)
rect.top else
rect.left
val startRow = rows[start]?.toMutableSet() ?: mutableSetOf()
startRow.add(position)
rows[start] = startRow
val end = if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL)
rect.bottom else
rect.right
val endRow = rows[end - 1]?.toMutableSet() ?: mutableSetOf()
endRow.add(position)
rows[end - 1] = endRow
rectsCache[position] = rect
subtract(rect)
}
fun findPositionsForRow(rowPosition: Int): Set<Int> {
return rows[rowPosition] ?: emptySet()
}
/**
* Remove this rect from the [freeRects], merge and reorder new free rects
*/
protected open fun subtract(subtractedRect: Rect) {
val interestingRects = freeRects.filter { it.isAdjacentTo(subtractedRect) || it.intersects(subtractedRect) }
val possibleNewRects = mutableListOf<Rect>()
val adjacentRects = mutableListOf<Rect>()
for (free in interestingRects) {
if (free.isAdjacentTo(subtractedRect) && !subtractedRect.contains(free)) {
adjacentRects.add(free)
} else {
freeRects.remove(free)
if (free.left < subtractedRect.left) { // Left
possibleNewRects.add(Rect(free.left, free.top, subtractedRect.left, free.bottom))
}
if (free.right > subtractedRect.right) { // Right
possibleNewRects.add(Rect(subtractedRect.right, free.top, free.right, free.bottom))
}
if (free.top < subtractedRect.top) { // Top
possibleNewRects.add(Rect(free.left, free.top, free.right, subtractedRect.top))
}
if (free.bottom > subtractedRect.bottom) { // Bottom
possibleNewRects.add(Rect(free.left, subtractedRect.bottom, free.right, free.bottom))
}
}
}
for (rect in possibleNewRects) {
val isAdjacent = adjacentRects.firstOrNull { it != rect && it.contains(rect) } != null
if (isAdjacent) continue
val isContained = possibleNewRects.firstOrNull { it != rect && it.contains(rect) } != null
if (isContained) continue
freeRects.add(rect)
}
freeRects.sortWith(rectComparator)
}
}
/**
* Helper to store width and height spans
*/
class SpanSize(val width: Int, val height: Int) | mit | 4e8f5b44954c29b0fcaf16bf560b78de | 31.843558 | 129 | 0.565131 | 5.437616 | false | false | false | false |
androidthings/endtoend-base | companionApp/src/main/java/com/example/androidthings/endtoend/companion/auth/FirebaseAuthProvider.kt | 1 | 2622 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androidthings.endtoend.companion.auth
import androidx.lifecycle.MutableLiveData
import com.example.androidthings.endtoend.companion.domain.UploadUserIdUseCase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.UserInfo
/** AuthProvider implementation based on FirebaseAuth. */
object FirebaseAuthProvider : AuthProvider {
private val firebaseAuth = FirebaseAuth.getInstance()
private val uploadUserIdUseCase = UploadUserIdUseCase()
private var authUiHelper: FirebaseAuthUiHelper? = null
override val userLiveData = MutableLiveData<UserInfo?>()
init {
firebaseAuth.addAuthStateListener { auth ->
// Listener is invoked immediately after registration, when a user signs in, when the
// current user signs out, and when the current user changes.
val currentUser = auth.currentUser
userLiveData.postValue(currentUser)
// Ensure the email<>uid mapping is in Firestore
if (currentUser != null) {
uploadUserIdUseCase.execute(currentUser)
}
}
}
/**
* Set the FirebaseAuthUiHelper. Intended to be used in [Activity#oncreate]
* [android.app.Activity.onCreate].
*/
fun setAuthUiHelper(uiHelper: FirebaseAuthUiHelper) {
authUiHelper = uiHelper
}
/**
* Unset the FirebaseAuthUiHelper if the argument is the current helper. Intended to be used in
* [Activity#onDestroy][android.app.Activity.onDestroy].
*/
fun unsetAuthUiHelper(uiHelper: FirebaseAuthUiHelper) {
if (authUiHelper == uiHelper) {
authUiHelper = null
}
}
override fun performSignIn() {
requireNotNull(authUiHelper).performSignIn()
}
override fun performSignOut() {
requireNotNull(authUiHelper).performSignOut()
}
}
/** Separates auth UI from FirebaseAuthProvider logic. */
interface FirebaseAuthUiHelper {
fun performSignIn()
fun performSignOut()
}
| apache-2.0 | b28bd96aec253deca23884fc2e406770 | 32.189873 | 99 | 0.702136 | 4.891791 | false | false | false | false |
TangHao1987/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/DomainGenerator.kt | 33 | 14416 | package org.jetbrains.protocolModelGenerator
import org.jetbrains.jsonProtocol.ItemDescriptor
import org.jetbrains.jsonProtocol.ProtocolMetaModel
import org.jetbrains.protocolReader.JSON_READER_PARAMETER_DEF
import org.jetbrains.protocolReader.TextOutput
import org.jetbrains.protocolReader.appendEnums
fun fixMethodName(name: String): String {
val i = name.indexOf("breakpoint")
return if (i > 0) name.substring(0, i) + 'B' + name.substring(i + 1) else name
}
interface TextOutConsumer {
fun append(out: TextOutput)
}
class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Domain) {
fun registerTypes() {
if (domain.types() != null) {
for (type in domain.types()!!) {
generator.typeMap.getTypeData(domain.domain(), type.id()).setType(type)
}
}
}
fun generateCommandsAndEvents() {
val requestsFileUpdater = generator.startJavaFile(generator.naming.params.getPackageNameVirtual(domain.domain()), "Requests.java")
val out = requestsFileUpdater.out
out.append("import org.jetbrains.annotations.NotNull;").newLine()
out.append("import org.jetbrains.jsonProtocol.Request;").newLine()
out.newLine().append("public final class ").append("Requests")
out.openBlock()
var isFirst = true
for (command in domain.commands()) {
val hasResponse = command.returns() != null
var onlyMandatoryParams = true
val params = command.parameters()
val hasParams = params != null && !params.isEmpty()
if (hasParams) {
for (parameter in params!!) {
if (parameter.optional()) {
onlyMandatoryParams = false
}
}
}
val returnType = if (hasResponse) generator.naming.commandResult.getShortName(command.name()) else "Void"
if (onlyMandatoryParams) {
if (isFirst) {
isFirst = false
}
else {
out.newLine().newLine()
}
out.append("@NotNull").newLine().append("public static Request<")
out.append(returnType)
out.append(">").space().append(fixMethodName(command.name())).append("(")
val classScope = OutputClassScope(this, generator.naming.params.getFullName(domain.domain(), command.name()))
val parameterTypes = if (hasParams) arrayOfNulls<BoxableType>(params!!.size()) else null
if (hasParams) {
classScope.writeMethodParameters<ProtocolMetaModel.Parameter>(out, params!!, parameterTypes!!)
}
out.append(')').openBlock()
val requestClassName = generator.naming.requestClassName.replace("Request", "SimpleRequest")
if (hasParams) {
out.append(requestClassName).append('<').append(returnType).append(">").append(" r =")
}
else {
out.append("return")
}
out.append(" new ").append(requestClassName).append("<").append(returnType).append(">(\"")
if (!domain.domain().isEmpty()) {
out.append(domain.domain()).append('.')
}
out.append(command.name()).append("\")").semi()
if (hasParams) {
classScope.writeWriteCalls<ProtocolMetaModel.Parameter>(out, params!!, parameterTypes!!, "r")
out.newLine().append("return r").semi()
}
out.closeBlock()
classScope.writeAdditionalMembers(out)
}
else {
generateRequest(command, returnType)
}
if (hasResponse) {
val fileUpdater = generator.startJavaFile(generator.naming.commandResult, domain, command.name())
generateJsonProtocolInterface(fileUpdater.out, generator.naming.commandResult.getShortName(command.name()), command.description(), command.returns(), null)
fileUpdater.update()
generator.jsonProtocolParserClassNames.add(generator.naming.commandResult.getFullName(domain.domain(), command.name()).getFullText())
generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), command.name(), generator.naming.commandResult))
}
}
out.closeBlock()
requestsFileUpdater.update()
if (domain.events() != null) {
for (event in domain.events()!!) {
generateEvenData(event)
generator.jsonProtocolParserClassNames.add(generator.naming.eventData.getFullName(domain.domain(), event.name()).getFullText())
generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), event.name(), generator.naming.eventData))
}
}
}
private fun generateRequest(command: ProtocolMetaModel.Command, returnType: String) {
val baseTypeBuilder = object : TextOutConsumer {
override fun append(out: TextOutput) {
out.space().append("extends ").append(generator.naming.requestClassName).append('<').append(returnType).append('>')
}
}
val memberBuilder = object : TextOutConsumer {
override fun append(out: TextOutput) {
out.append("@NotNull").newLine().append("@Override").newLine().append("public String getMethodName()").openBlock()
out.append("return \"")
if (!domain.domain().isEmpty()) {
out.append(domain.domain()).append('.')
}
out.append(command.name()).append('"').semi().closeBlock()
}
}
generateTopLevelOutputClass(generator.naming.params, command.name(), command.description(), baseTypeBuilder, memberBuilder, command.parameters())
}
fun generateCommandAdditionalParam(type: ProtocolMetaModel.StandaloneType) {
generateTopLevelOutputClass(generator.naming.additionalParam, type.id(), type.description(), null, null, type.properties())
}
private fun <P : ItemDescriptor.Named> generateTopLevelOutputClass(nameScheme: ClassNameScheme, baseName: String, description: String?, baseType: TextOutConsumer?, additionalMemberText: TextOutConsumer?, properties: List<P>?) {
val fileUpdater = generator.startJavaFile(nameScheme, domain, baseName)
if (nameScheme == generator.naming.params) {
fileUpdater.out.append("import org.jetbrains.annotations.NotNull;").newLine().newLine()
}
generateOutputClass(fileUpdater.out, nameScheme.getFullName(domain.domain(), baseName), description, baseType, additionalMemberText, properties)
fileUpdater.update()
}
private fun <P : ItemDescriptor.Named> generateOutputClass(out: TextOutput, classNamePath: NamePath, description: String?, baseType: TextOutConsumer?, additionalMemberText: TextOutConsumer?, properties: List<P>?) {
out.doc(description)
out.append("public final class ").append(classNamePath.lastComponent)
if (baseType == null) {
out.append(" extends ").append("org.jetbrains.jsonProtocol.OutMessage")
}
else {
baseType.append(out)
}
val classScope = OutputClassScope(this, classNamePath)
if (additionalMemberText != null) {
classScope.addMember(additionalMemberText)
}
out.openBlock()
classScope.generate<P>(out, properties)
classScope.writeAdditionalMembers(out)
out.closeBlock()
}
fun createStandaloneOutputTypeBinding(type: ProtocolMetaModel.StandaloneType, name: String): StandaloneTypeBinding {
return switchByType(type, MyCreateStandaloneTypeBindingVisitorBase(this, type, name))
}
fun createStandaloneInputTypeBinding(type: ProtocolMetaModel.StandaloneType): StandaloneTypeBinding {
return switchByType(type, object : CreateStandaloneTypeBindingVisitorBase(this, type) {
override fun visitObject(properties: List<ProtocolMetaModel.ObjectProperty>?): StandaloneTypeBinding {
return createStandaloneObjectInputTypeBinding(type, properties)
}
override fun visitEnum(enumConstants: List<String>): StandaloneTypeBinding {
val name = type.id()
return object : StandaloneTypeBinding {
override fun getJavaType() = StandaloneType(generator.naming.inputEnum.getFullName(domain.domain(), name), "writeEnum")
override fun generate() {
val fileUpdater = generator.startJavaFile(generator.naming.inputEnum, domain, name)
fileUpdater.out.doc(type.description())
appendEnums(enumConstants, generator.naming.inputEnum.getShortName(name), true, fileUpdater.out)
fileUpdater.update()
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
override fun visitArray(items: ProtocolMetaModel.ArrayItemType): StandaloneTypeBinding {
val resolveAndGenerateScope = object : ResolveAndGenerateScope {
// This class is responsible for generating ad hoc type.
// If we ever are to do it, we should generate into string buffer and put strings
// inside TypeDef class.
override fun getDomainName() = domain.domain()
override fun getTypeDirection() = TypeData.Direction.INPUT
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?) = throw UnsupportedOperationException()
}
val arrayType = ListType(generator.resolveType(items, resolveAndGenerateScope).type)
return createTypedefTypeBinding(type, object : Target {
override fun resolve(context: Target.ResolveContext): BoxableType {
return arrayType
}
}, generator.naming.inputTypedef, TypeData.Direction.INPUT)
}
})
}
fun createStandaloneObjectInputTypeBinding(type: ProtocolMetaModel.StandaloneType, properties: List<ProtocolMetaModel.ObjectProperty>?): StandaloneTypeBinding {
val name = type.id()
val fullTypeName = generator.naming.inputValue.getFullName(domain.domain(), name)
generator.jsonProtocolParserClassNames.add(fullTypeName.getFullText())
return object : StandaloneTypeBinding {
override fun getJavaType(): BoxableType {
return StandaloneType(fullTypeName, "writeMessage")
}
override fun generate() {
val className = generator.naming.inputValue.getFullName(domain.domain(), name)
val fileUpdater = generator.startJavaFile(generator.naming.inputValue, domain, name)
val out = fileUpdater.out
descriptionAndRequiredImport(type.description(), out)
out.append("public interface ").append(className.lastComponent).openBlock()
val classScope = InputClassScope(this@DomainGenerator, className)
if (properties != null) {
classScope.generateDeclarationBody(out, properties)
}
classScope.writeAdditionalMembers(out)
out.closeBlock()
fileUpdater.update()
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
/**
* Typedef is an empty class that just holds description and
* refers to an actual type (such as String).
*/
fun createTypedefTypeBinding(type: ProtocolMetaModel.StandaloneType, target: Target, nameScheme: ClassNameScheme, direction: TypeData.Direction?): StandaloneTypeBinding {
val name = type.id()
val typedefJavaName = nameScheme.getFullName(domain.domain(), name)
val actualJavaType = target.resolve(object : Target.ResolveContext {
override fun generateNestedObject(shortName: String, description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType {
val classNamePath = NamePath(shortName, typedefJavaName)
if (direction == null) {
throw RuntimeException("Unsupported")
}
when (direction) {
TypeData.Direction.INPUT -> throw RuntimeException("TODO")
TypeData.Direction.OUTPUT -> {
val out = TextOutput(StringBuilder())
generateOutputClass(out, classNamePath, description, null, null, properties)
}
else -> throw RuntimeException()
}
return StandaloneType(NamePath(shortName, typedefJavaName), "writeMessage")
}
})
return object : StandaloneTypeBinding {
override fun getJavaType() = actualJavaType
override fun generate() {
}
override fun getDirection() = direction
}
}
private fun generateEvenData(event: ProtocolMetaModel.Event) {
val className = generator.naming.eventData.getShortName(event.name())
val fileUpdater = generator.startJavaFile(generator.naming.eventData, domain, event.name())
val domainName = domain.domain()
val fullName = generator.naming.eventData.getFullName(domainName, event.name()).getFullText()
generateJsonProtocolInterface(fileUpdater.out, className, event.description(), event.parameters(), object : TextOutConsumer {
override fun append(out: TextOutput) {
out.append("org.jetbrains.wip.protocol.WipEventType<").append(fullName).append("> TYPE").newLine()
out.append("\t= new org.jetbrains.wip.protocol.WipEventType<").append(fullName).append(">")
out.append("(\"").append(domainName).append('.').append(event.name()).append("\", ").append(fullName).append(".class)").openBlock()
run {
out.append("@Override").newLine().append("public ").append(fullName).append(" read(")
out.append(generator.naming.inputPackage).append('.').append(READER_INTERFACE_NAME + " protocolReader, ").append(JSON_READER_PARAMETER_DEF).append(")").openBlock()
out.append("return protocolReader.").append(generator.naming.eventData.getParseMethodName(domainName, event.name())).append("(reader);").closeBlock()
}
out.closeBlock()
out.semi()
}
})
fileUpdater.update()
}
private fun generateJsonProtocolInterface(out: TextOutput, className: String, description: String?, parameters: List<ProtocolMetaModel.Parameter>?, additionalMembersText: TextOutConsumer?) {
descriptionAndRequiredImport(description, out)
out.append("public interface ").append(className).openBlock()
val classScope = InputClassScope(this, NamePath(className, NamePath(getPackageName(generator.naming.inputPackage, domain.domain()))))
if (additionalMembersText != null) {
classScope.addMember(additionalMembersText)
}
if (parameters != null) {
classScope.generateDeclarationBody(out, parameters)
}
classScope.writeAdditionalMembers(out)
out.closeBlock()
}
private fun descriptionAndRequiredImport(description: String?, out: TextOutput) {
out.append("import org.jetbrains.jsonProtocol.JsonType;").newLine().newLine()
if (description != null) {
out.doc(description)
}
out.append("@JsonType").newLine()
}
} | apache-2.0 | 5740cc3707a82e5bbbd2a46c6fc44e7f | 42.687879 | 229 | 0.694298 | 4.881815 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/defibrillator/AddIsDefibrillatorIndoor.kt | 1 | 1239 | package de.westnordost.streetcomplete.quests.defibrillator
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddIsDefibrillatorIndoor : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes with
emergency = defibrillator
and access !~ private|no
and !indoor
"""
override val commitMessage = "Add whether defibrillator is inside building"
override val wikiLink = "Key:indoor"
override val icon = R.drawable.ic_quest_defibrillator
override val questTypeAchievements = emptyList<QuestTypeAchievement>()
override fun getTitle(tags: Map<String, String>) = R.string.quest_is_defibrillator_inside_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("indoor", answer.toYesNo())
}
}
| gpl-3.0 | 82f9ffb6812e84d112108eee4dada3b1 | 38.967742 | 99 | 0.774818 | 4.995968 | false | false | false | false |
SirWellington/alchemy-http | src/test/java/tech/sirwellington/alchemy/http/AlchemyHttpBuilderTest.kt | 1 | 6429 | /*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.http
import com.google.gson.Gson
import org.hamcrest.Matchers
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.notNullValue
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import tech.sirwellington.alchemy.generator.AlchemyGenerator.Get.one
import tech.sirwellington.alchemy.generator.CollectionGenerators
import tech.sirwellington.alchemy.generator.NumberGenerators
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.integers
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.negativeIntegers
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.smallPositiveIntegers
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphabeticStrings
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.asString
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.hexadecimalString
import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.GenerateLong
import tech.sirwellington.alchemy.test.junit.runners.Repeat
import java.util.concurrent.ExecutorService
import java.util.concurrent.TimeUnit
/**
*
* @author SirWellington
*/
@Repeat(25)
@RunWith(AlchemyTestRunner::class)
class AlchemyHttpBuilderTest
{
@Mock
private lateinit var executor: ExecutorService
private lateinit var defaultHeaders: Map<String, String>
private lateinit var instance: AlchemyHttpBuilder
@GenerateLong(min = 100)
private var timeout: Long = 0L
@Before
fun setUp()
{
defaultHeaders = CollectionGenerators.mapOf(alphabeticStrings(), alphabeticStrings(), 20)
timeout = NumberGenerators.longs(100, 2000).get()
instance = AlchemyHttpBuilder()
.usingTimeout(Math.toIntExact(timeout), TimeUnit.MILLISECONDS)
.usingExecutor(executor)
.usingDefaultHeaders(defaultHeaders)
}
@Test
fun testNewInstance()
{
instance = AlchemyHttpBuilder.newInstance()
assertThat<AlchemyHttpBuilder>(instance, notNullValue())
}
@Repeat(50)
@Test
fun testUsingTimeout()
{
val socketTimeout = one(integers(15, 100))
val result = instance.usingTimeout(socketTimeout, TimeUnit.SECONDS)
assertThat(result, notNullValue())
}
@Repeat(10)
@Test
fun testUsingTimeoutWithBadArgs()
{
val negativeNumber = one(negativeIntegers())
assertThrows { instance.usingTimeout(negativeNumber, TimeUnit.SECONDS) }
.isInstanceOf(IllegalArgumentException::class.java)
}
@Test
fun testUsingGson()
{
val gson = Gson()
val result = instance.usingGson(gson)
assertThat(result, notNullValue())
}
@Repeat(100)
@Test
fun testUsingExecutorService()
{
val result = instance.usingExecutor(executor)
assertThat(result, notNullValue())
}
@Test
fun testDisableAsyncCallbacks()
{
val result = instance.disableAsyncCallbacks()
assertThat(result, notNullValue())
}
@Test
fun testEnableAsyncCallbacks()
{
val result = instance.enableAsyncCallbacks()
assertThat(result, notNullValue())
}
@Repeat(100)
@Test
fun testUsingDefaultHeaders()
{
instance = AlchemyHttpBuilder.newInstance()
val headers = CollectionGenerators.mapOf(alphabeticStrings(),
asString(smallPositiveIntegers()),
100)
val result = instance.usingDefaultHeaders(headers)
assertThat(result, notNullValue())
val http = result.build()
assertThat(http, notNullValue())
val expected = headers + Constants.DEFAULT_HEADERS
assertThat(http.defaultHeaders, equalTo(expected))
//Empty headers is ok
instance.usingDefaultHeaders(emptyMap())
}
@Repeat
@Test
fun testUsingDefaultHeader()
{
val key = one(alphabeticStrings())
val value = one(hexadecimalString(10))
val result = instance.usingDefaultHeader(key, value)
assertThat(result, notNullValue())
val http = result.build()
assertThat(http.defaultHeaders, Matchers.hasEntry(key, value))
}
@Test
fun testUsingDefaultHeaderEdgeCases()
{
val key = one(alphabeticStrings())
//should be ok
instance.usingDefaultHeader(key, "")
}
@Repeat(100)
@Test
fun testBuild()
{
val result = instance.build()
assertThat(result, notNullValue())
val expectedHeaders = this.defaultHeaders + Constants.DEFAULT_HEADERS
assertThat(result.defaultHeaders, equalTo(expectedHeaders))
}
@Test
fun testBuildEdgeCases()
{
//Nothing is set
instance = AlchemyHttpBuilder.newInstance()
instance.build()
//No Executor Service set
instance = AlchemyHttpBuilder.newInstance()
instance.build()
//No Timeout
instance = AlchemyHttpBuilder.newInstance().usingExecutor(executor)
instance.build()
}
@Test
fun testDefaultIncludesBasicRequestHeaders()
{
instance = AlchemyHttpBuilder.newInstance()
.usingExecutor(executor)
val result = instance.build()
assertThat(result, notNullValue())
val headers = result.defaultHeaders
assertThat(headers, Matchers.hasKey("Accept"))
assertThat(headers, Matchers.hasKey("Content-Type"))
}
}
| apache-2.0 | 94637db579561477e7c164135a4b6000 | 28.351598 | 97 | 0.691661 | 5.010133 | false | true | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/service/SyncCollectionUpload.kt | 1 | 14594 | package com.boardgamegeek.service
import android.content.ContentValues
import android.content.Intent
import android.content.SyncResult
import android.database.Cursor
import android.provider.BaseColumns
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import androidx.core.database.getDoubleOrNull
import androidx.core.database.getIntOrNull
import androidx.core.database.getLongOrNull
import androidx.core.database.getStringOrNull
import com.boardgamegeek.BggApplication
import com.boardgamegeek.R
import com.boardgamegeek.auth.Authenticator
import com.boardgamegeek.entities.CollectionItemForUploadEntity
import com.boardgamegeek.extensions.NotificationTags
import com.boardgamegeek.extensions.getBoolean
import com.boardgamegeek.extensions.intentFor
import com.boardgamegeek.extensions.whereNullOrBlank
import com.boardgamegeek.io.BggService
import com.boardgamegeek.provider.BggContract.Collection
import com.boardgamegeek.provider.BggContract.Companion.INVALID_ID
import com.boardgamegeek.provider.BggContract.Games
import com.boardgamegeek.repository.GameCollectionRepository
import com.boardgamegeek.ui.CollectionActivity
import com.boardgamegeek.ui.GameActivity
import com.boardgamegeek.util.HttpUtils
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import timber.log.Timber
import java.util.concurrent.TimeUnit
class SyncCollectionUpload(application: BggApplication, service: BggService, syncResult: SyncResult) :
SyncUploadTask(application, service, syncResult) {
private val okHttpClient: OkHttpClient = HttpUtils.getHttpClientWithAuth(context)
private val uploadTasks: List<CollectionUploadTask>
private var currentGameId: Int = 0
private var currentGameName: String = ""
private var currentGameHeroImageUrl: String = ""
private var currentGameThumbnailUrl: String = ""
private val repository = GameCollectionRepository(application)
override val syncType = SyncService.FLAG_SYNC_COLLECTION_UPLOAD
override val notificationTitleResId = R.string.sync_notification_title_collection_upload
override val summarySuffixResId = R.plurals.collection_items_suffix
override val notificationSummaryIntent = context.intentFor<CollectionActivity>()
override val notificationIntent: Intent?
get() = if (currentGameId != INVALID_ID) {
GameActivity.createIntent(
context,
currentGameId,
currentGameName,
currentGameThumbnailUrl,
currentGameHeroImageUrl
)
} else super.notificationIntent
override val notificationMessageTag = NotificationTags.UPLOAD_COLLECTION
override val notificationErrorTag = NotificationTags.UPLOAD_COLLECTION_ERROR
init {
uploadTasks = createUploadTasks()
}
private fun createUploadTasks(): List<CollectionUploadTask> {
val tasks = ArrayList<CollectionUploadTask>()
tasks.add(CollectionStatusUploadTask(okHttpClient))
tasks.add(CollectionRatingUploadTask(okHttpClient))
tasks.add(CollectionCommentUploadTask(okHttpClient))
tasks.add(CollectionPrivateInfoUploadTask(okHttpClient))
tasks.add(CollectionWishlistCommentUploadTask(okHttpClient))
tasks.add(CollectionTradeConditionUploadTask(okHttpClient))
tasks.add(CollectionWantPartsUploadTask(okHttpClient))
tasks.add(CollectionHasPartsUploadTask(okHttpClient))
return tasks
}
override fun execute() {
fetchList(fetchDeletedCollectionItems()).forEach {
if (isCancelled) return@forEach
if (wasSleepInterrupted(1, TimeUnit.SECONDS)) return@forEach
processDeletedCollectionItem(it)
}
fetchList(fetchNewCollectionItems()).forEach {
if (isCancelled) return@forEach
if (wasSleepInterrupted(1, TimeUnit.SECONDS)) return@forEach
processNewCollectionItem(it)
}
fetchList(fetchDirtyCollectionItems()).forEach {
if (isCancelled) return@forEach
if (wasSleepInterrupted(1, TimeUnit.SECONDS)) return@forEach
processDirtyCollectionItem(it)
}
}
private fun fetchList(cursor: Cursor?): MutableList<CollectionItemForUploadEntity> {
val list = mutableListOf<CollectionItemForUploadEntity>()
cursor?.use {
if (it.moveToFirst()) {
do {
list.add(fromCursor(it))
} while (it.moveToNext())
}
}
return list
}
private fun fromCursor(cursor: Cursor): CollectionItemForUploadEntity {
return CollectionItemForUploadEntity(
internalId = cursor.getLong(0),
collectionId = cursor.getIntOrNull(1) ?: INVALID_ID,
gameId = cursor.getIntOrNull(2) ?: INVALID_ID,
collectionName = cursor.getStringOrNull(3).orEmpty(),
imageUrl = cursor.getStringOrNull(4).orEmpty().ifEmpty { cursor.getStringOrNull(7) }.orEmpty(),
thumbnailUrl = cursor.getStringOrNull(5).orEmpty().ifEmpty { cursor.getStringOrNull(8) }.orEmpty(),
heroImageUrl = cursor.getStringOrNull(6).orEmpty().ifEmpty { cursor.getStringOrNull(9) }.orEmpty(),
rating = cursor.getDoubleOrNull(10) ?: 0.0,
ratingTimestamp = cursor.getLongOrNull(11) ?: 0L,
comment = cursor.getStringOrNull(12).orEmpty(),
commentTimestamp = cursor.getLongOrNull(13) ?: 0L,
acquiredFrom = cursor.getStringOrNull(14).orEmpty(),
acquisitionDate = cursor.getStringOrNull(15).orEmpty(),
privateComment = cursor.getStringOrNull(16).orEmpty(),
currentValue = cursor.getDoubleOrNull(17) ?: 0.0,
currentValueCurrency = cursor.getStringOrNull(18).orEmpty(),
pricePaid = cursor.getDoubleOrNull(19) ?: 0.0,
pricePaidCurrency = cursor.getStringOrNull(20).orEmpty(),
quantity = cursor.getIntOrNull(21) ?: 1,
inventoryLocation = cursor.getStringOrNull(22).orEmpty(),
privateInfoTimestamp = cursor.getLongOrNull(23) ?: 0L,
owned = cursor.getBoolean(24),
previouslyOwned = cursor.getBoolean(25),
forTrade = cursor.getBoolean(26),
wantInTrade = cursor.getBoolean(27),
wantToBuy = cursor.getBoolean(28),
wantToPlay = cursor.getBoolean(29),
preordered = cursor.getBoolean(30),
wishlist = cursor.getBoolean(31),
wishlistPriority = cursor.getIntOrNull(32) ?: 3, // Like to Have
statusTimestamp = cursor.getLongOrNull(33) ?: 0L,
wishlistComment = cursor.getString(34),
wishlistCommentDirtyTimestamp = cursor.getLongOrNull(35) ?: 0L,
tradeCondition = cursor.getStringOrNull(36),
tradeConditionDirtyTimestamp = cursor.getLongOrNull(37) ?: 0L,
wantParts = cursor.getStringOrNull(38),
wantPartsDirtyTimestamp = cursor.getLongOrNull(39) ?: 0L,
hasParts = cursor.getStringOrNull(40),
hasPartsDirtyTimestamp = cursor.getLongOrNull(41) ?: 0L,
)
}
private fun fetchDeletedCollectionItems(): Cursor? {
return getCollectionItems(
isGreaterThanZero(Collection.Columns.COLLECTION_DELETE_TIMESTAMP),
R.plurals.sync_notification_collection_deleting
)
}
private fun fetchNewCollectionItems(): Cursor? {
val selection =
"(${getDirtyColumnSelection(isGreaterThanZero(Collection.Columns.COLLECTION_DIRTY_TIMESTAMP))}) AND ${Collection.Columns.COLLECTION_ID.whereNullOrBlank()}"
return getCollectionItems(selection, R.plurals.sync_notification_collection_adding)
}
private fun fetchDirtyCollectionItems(): Cursor? {
val selection = getDirtyColumnSelection("")
return getCollectionItems(selection, R.plurals.sync_notification_collection_uploading)
}
private fun getDirtyColumnSelection(existingSelection: String): String {
val sb = StringBuilder(existingSelection)
for (task in uploadTasks) {
if (sb.isNotEmpty()) sb.append(" OR ")
sb.append(isGreaterThanZero(task.timestampColumn))
}
return sb.toString()
}
private fun isGreaterThanZero(columnName: String): String {
return "$columnName>0"
}
private fun getCollectionItems(selection: String, @PluralsRes messageResId: Int): Cursor? {
val cursor = context.contentResolver.query(
Collection.CONTENT_URI,
PROJECTION,
selection, null, null
)
val count = cursor?.count ?: 0
val detail = context.resources.getQuantityString(messageResId, count, count)
Timber.i(detail)
if (count > 0) updateProgressNotification(detail)
return cursor
}
private fun processDeletedCollectionItem(item: CollectionItemForUploadEntity) {
val deleteTask = CollectionDeleteTask(okHttpClient, item)
deleteTask.post()
if (processResponseForError(deleteTask)) {
return
}
context.contentResolver.delete(Collection.buildUri(item.internalId), null, null)
notifySuccess(item, item.collectionId, R.string.sync_notification_collection_deleted)
}
private fun processNewCollectionItem(item: CollectionItemForUploadEntity) {
val addTask = CollectionAddTask(okHttpClient, item)
addTask.post()
if (processResponseForError(addTask)) {
return
}
val contentValues = ContentValues()
addTask.appendContentValues(contentValues)
context.contentResolver.update(Collection.buildUri(item.internalId), contentValues, null, null)
runBlocking {
repository.refreshCollectionItems(item.gameId)
}
notifySuccess(item, item.gameId * -1, R.string.sync_notification_collection_added)
}
private fun processDirtyCollectionItem(item: CollectionItemForUploadEntity) {
if (item.collectionId != INVALID_ID) {
val contentValues = ContentValues()
for (task in uploadTasks) {
if (processUploadTask(task, item, contentValues)) return
}
if (contentValues.size() > 0) {
context.contentResolver.update(Collection.buildUri(item.internalId), contentValues, null, null)
notifySuccess(item, item.collectionId, R.string.sync_notification_collection_updated)
}
} else {
Timber.d("Invalid collectionItem ID for internal ID %1\$s; game ID %2\$s", item.internalId, item.gameId)
}
}
private fun processUploadTask(
task: CollectionUploadTask,
collectionItem: CollectionItemForUploadEntity,
contentValues: ContentValues
): Boolean {
task.addCollectionItem(collectionItem)
if (task.isDirty) {
task.post()
if (processResponseForError(task)) {
return true
}
task.appendContentValues(contentValues)
}
return false
}
private fun notifySuccess(item: CollectionItemForUploadEntity, id: Int, @StringRes messageResId: Int) {
syncResult.stats.numUpdates++
currentGameId = item.gameId
currentGameName = item.collectionName
currentGameHeroImageUrl = item.heroImageUrl
currentGameThumbnailUrl = item.thumbnailUrl
notifyUser(
item.collectionName,
context.getString(messageResId),
id,
item.heroImageUrl,
item.thumbnailUrl,
item.imageUrl,
)
}
private fun processResponseForError(response: CollectionTask): Boolean {
return when {
response.hasAuthError() -> {
Timber.w("Auth error; clearing password")
syncResult.stats.numAuthExceptions++
Authenticator.clearPassword(context)
true
}
!response.errorMessage.isNullOrBlank() -> {
syncResult.stats.numIoExceptions++
notifyUploadError(response.errorMessage)
true
}
else -> false
}
}
companion object {
val PROJECTION = arrayOf(
BaseColumns._ID,
Collection.Columns.COLLECTION_ID,
Games.Columns.GAME_ID,
Collection.Columns.COLLECTION_NAME,
Collection.Columns.COLLECTION_IMAGE_URL,
Collection.Columns.COLLECTION_THUMBNAIL_URL, // 5
Collection.Columns.COLLECTION_HERO_IMAGE_URL,
Games.Columns.IMAGE_URL,
Games.Columns.THUMBNAIL_URL,
Games.Columns.HERO_IMAGE_URL,
Collection.Columns.RATING, // 10
Collection.Columns.RATING_DIRTY_TIMESTAMP,
Collection.Columns.COMMENT,
Collection.Columns.COMMENT_DIRTY_TIMESTAMP,
Collection.Columns.PRIVATE_INFO_ACQUIRED_FROM,
Collection.Columns.PRIVATE_INFO_ACQUISITION_DATE, // 15
Collection.Columns.PRIVATE_INFO_COMMENT,
Collection.Columns.PRIVATE_INFO_CURRENT_VALUE,
Collection.Columns.PRIVATE_INFO_CURRENT_VALUE_CURRENCY,
Collection.Columns.PRIVATE_INFO_PRICE_PAID,
Collection.Columns.PRIVATE_INFO_PRICE_PAID_CURRENCY, // 20
Collection.Columns.PRIVATE_INFO_QUANTITY,
Collection.Columns.PRIVATE_INFO_INVENTORY_LOCATION,
Collection.Columns.PRIVATE_INFO_DIRTY_TIMESTAMP,
Collection.Columns.STATUS_OWN,
Collection.Columns.STATUS_PREVIOUSLY_OWNED, // 25
Collection.Columns.STATUS_FOR_TRADE,
Collection.Columns.STATUS_WANT,
Collection.Columns.STATUS_WANT_TO_BUY,
Collection.Columns.STATUS_WANT_TO_PLAY,
Collection.Columns.STATUS_PREORDERED, // 30
Collection.Columns.STATUS_WISHLIST,
Collection.Columns.STATUS_WISHLIST_PRIORITY,
Collection.Columns.STATUS_DIRTY_TIMESTAMP,
Collection.Columns.WISHLIST_COMMENT,
Collection.Columns.WISHLIST_COMMENT_DIRTY_TIMESTAMP, // 35
Collection.Columns.CONDITION,
Collection.Columns.TRADE_CONDITION_DIRTY_TIMESTAMP,
Collection.Columns.WANTPARTS_LIST,
Collection.Columns.WANT_PARTS_DIRTY_TIMESTAMP,
Collection.Columns.HASPARTS_LIST, // 40
Collection.Columns.HAS_PARTS_DIRTY_TIMESTAMP,
)
}
}
| gpl-3.0 | f6d34990277d66da3761da5f08c57978 | 41.923529 | 167 | 0.670687 | 5.118906 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/provider/BuddiesProvider.kt | 1 | 762 | package com.boardgamegeek.provider
import android.content.ContentValues
import android.net.Uri
import com.boardgamegeek.provider.BggContract.Buddies
import com.boardgamegeek.provider.BggContract.Companion.PATH_BUDDIES
import com.boardgamegeek.provider.BggDatabase.Tables
class BuddiesProvider : BasicProvider() {
override fun getType(uri: Uri) = Buddies.CONTENT_TYPE
override val path: String = PATH_BUDDIES
override val table = Tables.BUDDIES
override val defaultSortOrder = Buddies.DEFAULT_SORT
override fun insertedUri(values: ContentValues?, rowId: Long): Uri? {
val buddyName = values?.getAsString(Buddies.Columns.BUDDY_NAME)
return if (buddyName.isNullOrBlank()) null else Buddies.buildBuddyUri(buddyName)
}
}
| gpl-3.0 | a5527e7381155368df15cbc74385eee1 | 33.636364 | 88 | 0.776903 | 4.404624 | false | false | false | false |
mediathekview/MediathekView | src/main/java/mediathek/tool/MVInfoFile.kt | 1 | 4437 | package mediathek.tool
import mediathek.daten.DatenDownload
import mediathek.daten.DatenFilm
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.apache.commons.text.WordUtils
import org.apache.logging.log4j.LogManager
import java.io.*
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
open class MVInfoFile {
private fun formatFilmAsString(film: DatenFilm?, url: HttpUrl?): String {
if (null == film || url == null)
return ""
//calculate file size based on actual used URL
val fileSize = FileSize.getFileSizeFromUrl(url)
val formatString = String.format("%%-%ds %%s", MAX_HEADER_LENGTH)
var sb = StringBuilder()
sb = appendFormattedTableLine(sb, formatString, FILM_SENDER, film.sender)
sb = appendFormattedTableLine(sb, formatString, FILM_THEMA, film.thema).append(System.lineSeparator())
sb = appendFormattedTableLine(sb, formatString, FILM_TITEL, film.title).append(System.lineSeparator())
sb = appendFormattedTableLine(sb, formatString, FILM_DATUM, film.sendeDatum)
sb = appendFormattedTableLine(sb, formatString, FILM_ZEIT, film.sendeZeit)
sb = appendFormattedTableLine(sb, formatString, FILM_DAUER, film.dauer)
if (fileSize > FileSize.INVALID_SIZE)
sb = appendFormattedTableLine(sb, formatString, FILM_GROESSE, FileUtils.humanReadableByteCountBinary(fileSize))
else
sb.append(System.lineSeparator())
sb.append(System.lineSeparator())
sb.append("Website")
sb.append(System.lineSeparator())
sb.append(film.websiteLink)
sb.append(System.lineSeparator())
sb.append(System.lineSeparator())
sb.append(FILM_URL)
sb.append(System.lineSeparator())
sb.append(url)
sb.append(System.lineSeparator())
sb.append(System.lineSeparator())
sb.append(splitStringIntoMaxFixedLengthLines(film.description, MAX_LINE_LENGTH))
sb.append(System.lineSeparator())
sb.append(System.lineSeparator())
return sb.toString()
}
protected fun appendFormattedTableLine(sb: StringBuilder, formatString: String?, keyTitle: String?, value: String?): StringBuilder {
return sb.append(String.format(formatString!!, String.format("%s:", keyTitle), value))
.append(System.lineSeparator())
}
protected fun splitStringIntoMaxFixedLengthLines(input: String?, lineLength: Int): String {
return Optional.ofNullable(input)
.map { s: String? -> WordUtils.wrap(s, lineLength) }
.orElse("")
}
@Throws(IOException::class)
fun writeInfoFile(film: DatenFilm?, path: Path, url: HttpUrl?) {
logger.info("Infofile schreiben nach: {}", path.toAbsolutePath().toString())
path.toFile().parentFile.mkdirs()
Files.newOutputStream(path).use { os ->
DataOutputStream(os).use { dos ->
OutputStreamWriter(dos).use { osw ->
BufferedWriter(osw).use { br ->
br.write(formatFilmAsString(film, url))
br.flush()
}
}
}
}
logger.info("Infodatei geschrieben")
}
@Throws(IOException::class)
fun writeInfoFile(datenDownload: DatenDownload) {
File(datenDownload.arr[DatenDownload.DOWNLOAD_ZIEL_PFAD]).mkdirs()
val path = Paths.get(datenDownload.fileNameWithoutSuffix + ".txt")
val film = datenDownload.film
// this is the URL that will be used during download.
// write this into info file and calculate size from it
val url = datenDownload.arr[DatenDownload.DOWNLOAD_URL].toHttpUrl()
film?.let { writeInfoFile(it, path, url) }
}
private companion object {
private val logger = LogManager.getLogger(MVInfoFile::class.java)
private const val FILM_GROESSE = "Größe"
private const val FILM_SENDER = "Sender"
private const val FILM_THEMA = "Thema"
private const val FILM_TITEL = "Titel"
private const val FILM_DATUM = "Datum"
private const val FILM_ZEIT = "Zeit"
private const val FILM_DAUER = "Dauer"
private const val FILM_URL = "URL"
private const val MAX_HEADER_LENGTH = 12
private const val MAX_LINE_LENGTH = 62
}
} | gpl-3.0 | 79c0f1d22738daa139e3cc5287fd1778 | 40.849057 | 136 | 0.652311 | 4.268527 | false | false | false | false |
minjaesong/terran-basic-java-vm | src/net/torvald/terranvm/runtime/compiler/cflat/Compiler.kt | 1 | 64831 | package net.torvald.terranvm.runtime.compiler.cflat
import net.torvald.terranvm.VMOpcodesRISC
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
/**
* A compiler for C-flat language that compiles into TerranVM Terra Instruction Set.
*
* # Disclaimer
*
* 0. This compiler, BY NO MEANS, guarantees to implement standard C language; c'mon, $100+ for a standard document?
* 1. I suck at code and test. Please report bugs!
* 2. Please move along with my terrible sense of humour.
*
* # About C-flat
*
* C-flat is a stupid version of C. Everything is global and a word (or byte if it's array).
*
* ## New Features
*
* - Typeless (everything is a word), non-zero is truthy and zero is falsy
* - Infinite loop using ```forever``` block. You can still use ```for (;;)```, ```while (true)```
* - Counted simple loop (without loop counter ref) using ```repeat``` block
*
*
* ## Important Changes from C
*
* - All function definition must specify return type, even if the type is ```void```.
* - ```float``` is IEEE 754 Binary32.
* - Everything is global
* - Everything is a word (32-bit)
* - Everything is ```int```, ```float``` and ```pointer``` at the same time. You decide.
* - Unary pre- and post- increments/decrements are considered _evil_ and thus prohibited.
* - Unsigned types are also considered _evil_ and thus prohibited.
* - Everything except function's local variable is ```extern```, any usage of the keyword will throw error.
* - Function cannot have non-local variable defined inside, as ```static``` keyword is illegal.
* - And thus, following keywords will throw error:
* - auto, register, volatile (not supported)
* - signed, unsigned (prohibited)
* - static (no global inside function)
* - extern (everything is global)
* - Assignment does not return shit.
*
*
* ## Issues
* - FIXME arithmetic ops will not work with integers, need to autodetect types and slap in ADDINT instead of just ADD
*
*
* Created by minjaesong on 2017-06-04.
*/
object Cflat {
private val structOpen = '{'
private val structClose = '}'
private val parenOpen = '('
private val parenClose = ')'
private val preprocessorTokenSep = Regex("""[ \t]+""")
private val nullchar = 0.toChar()
private val infiniteLoops = arrayListOf<Regex>(
Regex("""while\(true\)"""), // whitespaces are filtered on preprocess
Regex("""for\([\s]*;[\s]*;[\s]*\)""")
) // more types of infinite loops are must be dealt with (e.g. while (0xFFFFFFFF < 0x7FFFFFFF))
private val regexRegisterLiteral = Regex("""^[Rr][0-9]+$""") // same as the assembler
private val regexBooleanWhole = Regex("""^(true|false)$""")
private val regexHexWhole = Regex("""^(0[Xx][0-9A-Fa-f_]+?)$""") // DIFFERENT FROM the assembler
private val regexOctWhole = Regex("""^(0[0-7_]+)$""")
private val regexBinWhole = Regex("""^(0[Bb][01_]+)$""") // DIFFERENT FROM the assembler
private val regexFPWhole = Regex("""^([-+]?[0-9]*[.][0-9]+[eE]*[-+0-9]*[fF]*|[-+]?[0-9]+[.eEfF][0-9+-]*[fF]?)$""") // same as the assembler
private val regexIntWhole = Regex("""^([-+]?[0-9_]+[Ll]?)$""") // DIFFERENT FROM the assembler
private fun String.matchesNumberLiteral() = this.matches(regexHexWhole) || this.matches(regexOctWhole) || this.matches(regexBinWhole) || this.matches(regexIntWhole) || this.matches(regexFPWhole)
private fun String.matchesFloatLiteral() = this.matches(regexFPWhole)
private fun String.matchesStringLiteral() = this.endsWith(0.toChar())
private fun generateTemporaryVarName(inst: String, arg1: String, arg2: String) = "$$${inst}_${arg1}_$arg2"
private fun generateSuperTemporaryVarName(lineNum: Int, inst: String, arg1: String, arg2: String) = "$$${inst}_${arg1}_${arg2}_\$l$lineNum"
private val regexVarNameWhole = Regex("""^([A-Za-z_][A-Za-z0-9_]*)$""")
private val regexWhitespaceNoSP = Regex("""[\t\r\n\v\f]""")
private val regexIndents = Regex("""^ +|^\t+|(?<=\n) +|(?<=\n)\t+""")
private val digraphs = hashMapOf(
"<:" to '[',
":>" to ']',
"<%" to '{',
"%>" to '}',
"%:" to '#'
)
private val trigraphs = hashMapOf(
"??=" to "#",
"??/" to "'",
"??'" to "^",
"??(" to "[",
"??)" to "]",
"??!" to "|",
"??<" to "{",
"??>" to "}",
"??-" to "~"
)
private val keywords = hashSetOf(
// classic C
"auto","break","case","char","const","continue","default","do","double","else","enum","extern","float",
"for","goto","if","int","long","register","return","short","signed","static","struct","switch","sizeof", // is an operator
"typedef","union","unsigned","void","volatile","while",
// C-flat code blocks
"forever","repeat"
// C-flat dropped keywords (keywords that won't do anything/behave differently than C95, etc.):
// - auto, register, signed, unsigned, volatile, static: not implemented; WILL THROW ERROR
// - float: will act same as double
// - extern: everthing is global, anyway; WILL THROW ERROR
// C-flat exclusive keywords:
// - bool, true, false: bool algebra
)
private val unsupportedKeywords = hashSetOf(
"auto","register","signed","unsigned","volatile","static",
"extern",
"long", "short", "double", "bool"
)
private val operatorsHierarchyInternal = arrayOf(
// opirator precedence in internal format (#_nameinlowercase) PUT NO PARENS HERE! TODO [ ] are allowed? pls chk
// most important
hashSetOf("++","--","[", "]",".","->"),
hashSetOf("#_preinc","#_predec","#_unaryplus","#_unaryminus","!","~","#_ptrderef","#_addressof","sizeof","(char *)","(short *)","(int *)","(long *)","(float *)","(double *)","(bool *)","(void *)", "(char)","(short)","(int)","(long)","(float)","(double)","(bool)"),
hashSetOf("*","/","%"),
hashSetOf("+","-"),
hashSetOf("<<",">>",">>>"),
hashSetOf("<","<=",">",">="),
hashSetOf("==","!="),
hashSetOf("&"),
hashSetOf("^"),
hashSetOf("|"),
hashSetOf("&&"),
hashSetOf("||"),
hashSetOf("?",":"),
hashSetOf("=","+=","-=","*=","/=","%=","<<=",">>=","&=","^=","|="),
hashSetOf(",")
// least important
).reversedArray() // this makes op with highest precedence have bigger number
// operators must return value when TREE is evaluated -- with NO EXCEPTION; '=' must return value too! (not just because of C standard, but design of #_assignvar)
private val unaryOps = hashSetOf(
"++","--",
"#_preinc","#_predec","#_unaryplus","#_unaryminus","!","~","#_ptrderef","#_addressof","sizeof","(char *)","(short *)","(int *)","(long *)","(float *)","(double *)","(bool *)","(void *)", "(char)","(short)","(int)","(long)","(float)","(double)","(bool)"
)
private val operatorsHierarchyRTL = arrayOf(
false,
true,
false,false,false,false,false,false,false,false,false,false,
true,true,
false
)
private val operatorsNoOrder = HashSet<String>()
init {
operatorsHierarchyInternal.forEach { array ->
array.forEach { word -> operatorsNoOrder.add(word) }
}
}
private val splittableTokens = arrayOf( // order is important!
"<<=",">>=","...",
"++","--","&&","||","<<",">>","->","<=",">=","==","!=","+=","-=","*=","/=","%=","&=","^=","|=",
"<",">","^","|","?",":","=",",",".","+","-","!","~","*","&","/","%","(",")",
" "
)
private val argumentDefBadTokens = splittableTokens.toMutableList().minus(",").minus("*").minus("...").toHashSet()
private val evilOperators = hashSetOf(
"++","--"
)
private val funcAnnotations = hashSetOf(
"auto", // does nothing; useless even in C (it's derived from B language, actually)
"extern" // not used in C-flat
)
private val funcTypes = hashSetOf(
"char", "short", "int", "long", "float", "double", "bool", "void"
)
private val varAnnotations = hashSetOf(
"auto", // does nothing; useless even in C (it's derived from B language, actually)
"extern", // not used in C-flat
"const",
"register" // not used in C-flat
)
private val varTypes = hashSetOf(
"struct", "char", "short", "int", "long", "float", "double", "bool", "var", "val"
)
private val validFuncPreword = (funcAnnotations + funcTypes).toHashSet()
private val validVariablePreword = (varAnnotations + varTypes).toHashSet()
private val codeBlockKeywords = hashSetOf(
"do", "else", "enum", "for", "if", "struct", "switch", "union", "while", "forever", "repeat"
)
private val functionalKeywordsWithOneArg = hashSetOf(
"goto", "return"
)
private val functionalKeywordsNoArg = hashSetOf(
"break", "continue",
"return" // return nothing
)
private val preprocessorKeywords = hashSetOf(
"#include","#ifndef","#ifdef","#define","#if","#else","#elif","#endif","#undef","#pragma"
)
private val escapeSequences = hashMapOf<String, Char>(
"""\a""" to 0x07.toChar(), // Alert (Beep, Bell)
"""\b""" to 0x08.toChar(), // Backspace
"""\f""" to 0x0C.toChar(), // Formfeed
"""\n""" to 0x0A.toChar(), // Newline (Line Feed)
"""\r""" to 0x0D.toChar(), // Carriage Return
"""\t""" to 0x09.toChar(), // Horizontal Tab
"""\v""" to 0x0B.toChar(), // Vertical Tab
"""\\""" to 0x5C.toChar(), // Backslash
"""\'""" to 0x27.toChar(), // Single quotation mark
"""\"""" to 0x22.toChar(), // Double quotation mark
"""\?""" to 0x3F.toChar() // uestion mark (used to avoid trigraphs)
)
private val builtinFunctions = hashSetOf(
"#_declarevar" // #_declarevar(SyntaxTreeNode<RawString> varname, SyntaxTreeNode<RawString> vartype)
)
private val functionWithSingleArgNoParen = hashSetOf(
"return", "goto", "comefrom"
)
private val compilerInternalFuncArgsCount = hashMapOf(
"#_declarevar" to 2,
"endfuncdef" to 1,
"=" to 2,
"endif" to 0,
"endelse" to 0
)
/* Error messages */
val errorUndeclaredVariable = "Undeclared variable"
val errorIncompatibleType = "Incompatible type(s)"
val errorRedeclaration = "Redeclaration"
fun sizeofPrimitive(type: String) = when (type) {
"char" -> 1
"short" -> 2
"int" -> 4
"long" -> 8
"float" -> 4
"double" -> 8
"bool" -> 1
"void" -> 1 // GCC feature
else -> throw IllegalArgumentException("Unknown primitive type: $type")
}
private val functionsImplicitEnd = hashSetOf(
"if", "else", "for", "while", "switch"
)
private val exprToIR = hashMapOf(
"#_declarevar" to "DECLARE",
"return" to "RETURN",
"+" to "ADD",
"-" to "SUB",
"*" to "MUL",
"/" to "DIV",
"^" to "POW",
"%" to "MOD",
"<<" to "SHL",
">>" to "SHR",
">>>" to "USHR",
"and" to "AND",
"or" to "OR",
"xor" to "XOR",
"not" to "NOT",
"=" to "ASSIGN",
"==" to "ISEQ",
"!=" to "ISNEQ",
">" to "ISGT",
"<" to "ISLS",
">=" to "ISGTEQ",
"<=" to "ISLSEQ",
"if" to "IF",
"endif" to "ENDIF",
"else" to "ELSE",
"endelse" to "ENDELSE",
"goto" to "GOTOLABEL",
"comefrom" to "DEFLABEL",
"asm" to "INLINEASM",
"funcdef" to "FUNCDEF",
"endfuncdef" to "ENDFUNCDEF",
"stackpush" to "STACKPUSH"
)
private val irCmpInst = hashSetOf(
"ISEQ_II", "ISEQ_IF", "ISEQ_FI", "ISEQ_FF",
"ISNEQ_II", "ISNEQ_IF", "ISNEQ_FI", "ISNEQ_FF",
"ISGT_II", "ISGT_IF", "ISGT_FI", "ISGT_FF",
"ISLS_II", "ISLS_IF", "ISLS_FI", "ISLS_FF",
"ISGTEQ_II", "ISGTEQ_IF", "ISGTEQ_FI", "ISGTEQ_FF",
"ISLSEQ_II", "ISLSEQ_IF", "ISLSEQ_FI", "ISLSEQ_FF"
)
private val jmpCommands = hashSetOf(
"JMP", "JZ", "JNZ", "JGT", "JLS"
)
// compiler options
var useDigraph = true
var useTrigraph = false
var errorIncompatibles = true
operator fun invoke(
program: String,
// options
useDigraph: Boolean = false,
useTrigraph: Boolean = false,
errorIncompatible: Boolean = true
) {
this.useDigraph = useDigraph
this.useTrigraph = useTrigraph
this.errorIncompatibles = errorIncompatible
//val tree = tokenise(preprocess(program))
TODO()
}
private val structDict = ArrayList<CStruct>()
private val structNameDict = ArrayList<String>()
private val funcDict = ArrayList<CFunction>()
private val funcNameDict = ArrayList<String>()
private val varDict = HashSet<CData>()
private val varNameDict = HashSet<String>()
private val includesUser = HashSet<String>()
private val includesLib = HashSet<String>()
private fun getFuncByName(name: String): CFunction? {
funcDict.forEach {
if (it.name == name) return it
}
return null
}
private fun structSearchByName(name: String): CStruct? {
structDict.forEach {
if (it.name == name) return it
}
return null
}
fun preprocess(program: String): String {
var program = program
//.replace(regexIndents, "") // must come before regexWhitespaceNoSP
//.replace(regexWhitespaceNoSP, "")
var out = StringBuilder()
if (useTrigraph) {
trigraphs.forEach { from, to ->
program = program.replace(from, to)
}
}
val rules = PreprocessorRules()
// Scan thru line by line (assuming single command per line...?)
program.lines().forEach {
if (it.startsWith('#')) {
val tokens = it.split(preprocessorTokenSep)
val cmd = tokens[0].drop(1).toLowerCase()
when (cmd) {
"include" -> TODO("Preprocessor keyword 'include'")
"define" -> rules.addDefinition(tokens[1], tokens.subList(2, tokens.size).joinToString(" "))
"undef" -> rules.removeDefinition(tokens[1])
else -> throw UndefinedStatement("Preprocessor macro '$cmd' is not supported.")
}
}
else {
// process each line according to rules
var line = it
rules.forEachKeywordForTokens { replaceRegex, replaceWord ->
line = line.replace(replaceRegex, " $replaceWord ")
}
out.append("$line\n")
}
}
println(out.toString())
return out.toString()
}
/** No preprocessor should exist at this stage! */
fun tokenise(program: String): ArrayList<LineStructure> {
fun debug1(any: Any) { if (true) println(any) }
///////////////////////////////////
// STEP 0. Divide things cleanly //
///////////////////////////////////
// a.k.a. tokenise properly e.g. {extern int foo ( int initSize , SomeStruct strut , )} or {int foo = getch ( ) * ( ( num1 + num3 % 16 ) - 1 )}
val lineStructures = ArrayList<LineStructure>()
var currentProgramLineNumber = 1
var currentLine = LineStructure(currentProgramLineNumber, 0, ArrayList<String>())
// put things to lineStructure, kill any whitespace
val sb = StringBuilder()
var charCtr = 0
var structureDepth = 0
fun splitAndMoveAlong() {
if (sb.isNotEmpty()) {
if (errorIncompatibles && unsupportedKeywords.contains(sb.toString())) {
throw IllegalTokenException("at line $currentProgramLineNumber with token '$sb'")
}
debug1("!! split: depth $structureDepth, word '$sb'")
currentLine.depth = structureDepth // !important
currentLine.tokens.add(sb.toString())
sb.setLength(0)
}
}
fun gotoNewline() {
if (currentLine.tokens.isNotEmpty()) {
lineStructures.add(currentLine)
sb.setLength(0)
currentLine = LineStructure(currentProgramLineNumber, -1337, ArrayList<String>())
}
}
var forStatementEngaged = false // to filter FOR range semicolon from statement-end semicolon
var isLiteralMode = false // "" ''
var isCharLiteral = false
var isLineComment = false
var isBlockComment = false
while (charCtr < program.length) {
var char = program[charCtr]
var lookahead4 = program.substring(charCtr, minOf(charCtr + 4, program.length)) // charOfIndex {0, 1, 2, 3}
var lookahead3 = program.substring(charCtr, minOf(charCtr + 3, program.length)) // charOfIndex {0, 1, 2}
var lookahead2 = program.substring(charCtr, minOf(charCtr + 2, program.length)) // charOfIndex {0, 1}
var lookbehind2 = program.substring(maxOf(charCtr - 1, 0), charCtr + 1) // charOfIndex {-1, 0}
// count up line num
if (char == '\n' && !isCharLiteral && !isLiteralMode) {
currentProgramLineNumber += 1
currentLine.lineNum = currentProgramLineNumber
if (isLineComment) isLineComment = false
}
else if (char == '\n' && isLiteralMode) {
//throw SyntaxError("at line $currentProgramLineNumber -- line break used inside of string literal")
// ignore \n by doing nothing
}
else if (lookahead2 == "//" && !isLineComment) {
isLineComment = true
charCtr += 1
}
else if (!isBlockComment && lookahead2 == "/*") {
isBlockComment = true
charCtr += 1
}
else if (!isBlockComment && lookahead2 == "*/") {
isBlockComment = false
charCtr += 1
}
else if (!isLiteralMode && !isCharLiteral && !isBlockComment && !isLineComment && char.toString().matches(regexWhitespaceNoSP)) {
// do nothing
}
else if (!isLiteralMode && !isCharLiteral && !isBlockComment && !isLineComment) {
// replace digraphs
if (useDigraph && digraphs.containsKey(lookahead2)) { // replace digraphs
char = digraphs[lookahead2]!!
lookahead4 = char + lookahead4.substring(0..lookahead4.lastIndex)
lookahead3 = char + lookahead3.substring(0..lookahead3.lastIndex)
lookahead2 = char + lookahead2.substring(0..lookahead2.lastIndex)
lookbehind2 = lookbehind2.substring(0..lookahead2.lastIndex - 1) + char
charCtr += 1
}
// filter shits
if (lookahead2 == "//" || lookahead2 == "/*" || lookahead2 == "*/") {
throw SyntaxError("at line $currentProgramLineNumber -- illegal token '$lookahead2'")
}
// do the real jobs
if (char == structOpen) {
debug1("!! met structOpen at line $currentProgramLineNumber")
splitAndMoveAlong()
gotoNewline()
structureDepth += 1 // must go last, because of quirks with 'codeblock{' and 'codeblock {'
}
else if (char == structClose) {
debug1("!! met structClose at line $currentProgramLineNumber")
structureDepth -= 1 // must go first
splitAndMoveAlong()
gotoNewline()
}
// double quotes
else if (char == '"' && lookbehind2[0] != '\\') {
isLiteralMode = !isLiteralMode
sb.append(char)
}
// char literal
else if (!isCharLiteral && char == '\'' && lookbehind2[0] != '\'') {
if ((lookahead4[1] == '\\' && lookahead4[3] != '\'') || (lookahead4[1] != '\\' && lookahead4[2] != '\''))
throw SyntaxError("Illegal usage of char literal")
isCharLiteral = !isCharLiteral
}
// -- TODO -- FOR statement is now a special case
else if (!forStatementEngaged && char == ';') {
splitAndMoveAlong()
gotoNewline()
}
else {
if (splittableTokens.contains(lookahead3)) { // three-char operator
splitAndMoveAlong() // split previously accumulated word
sb.append(lookahead3)
splitAndMoveAlong()
charCtr += 2
}
else if (splittableTokens.contains(lookahead2)) { // two-char operator
splitAndMoveAlong() // split previously accumulated word
if (evilOperators.contains(lookahead2)) {
throw IllegalTokenException("at line $currentProgramLineNumber -- evil operator '$lookahead2'")
}
sb.append(lookahead2)
splitAndMoveAlong()
charCtr += 1
}
else if (splittableTokens.contains(char.toString())) { // operator and ' '
if (char == '.') { // struct reference or decimal point, depending on the context
// it's decimal if:
// .[number]
// \.e[+-]?[0-9]+ (exponent)
// [number].[ fF]?
// spaces around decimal points are NOT ALLOWED
if (lookahead2.matches(Regex("""\.[0-9]""")) or
lookahead4.matches(Regex("""\.e[+-]?[0-9]+""")) or
(lookbehind2.matches(Regex("""[0-9]+\.""")) and lookahead2.matches(Regex("""\.[ Ff,)]""")))
) {
// get match length
var charHolder: Char
// we don't need travel back because 'else' clause on the far bottom have been already putting numbers into the stringBuilder
var travelForth = 0
do {
travelForth += 1
charHolder = program[charCtr + travelForth]
} while (charHolder in '0'..'9' || charHolder.toString().matches(Regex("""[-+eEfF]""")))
val numberWord = program.substring(charCtr..charCtr + travelForth - 1)
debug1("[C-flat.tokenise] decimal number token: $sb$numberWord, on line $currentProgramLineNumber")
sb.append(numberWord)
splitAndMoveAlong()
charCtr += travelForth - 1
}
else { // reference call
splitAndMoveAlong() // split previously accumulated word
debug1("[C-flat.tokenise] splittable token: $char, on line $currentProgramLineNumber")
sb.append(char)
splitAndMoveAlong()
}
}
else if (char != ' ') {
splitAndMoveAlong() // split previously accumulated word
debug1("[C-flat.tokenise] splittable token: $char, on line $currentProgramLineNumber")
sb.append(char)
splitAndMoveAlong()
}
else { // space detected, split only
splitAndMoveAlong()
}
}
else {
sb.append(char)
}
}
}
else if (isCharLiteral && !isLiteralMode) {
if (char == '\\') { // escape sequence of char literal
sb.append(escapeSequences[lookahead2]!!.toInt())
charCtr += 1
}
else {
sb.append(char.toInt())
}
}
else if (isLiteralMode && !isCharLiteral) {
if (char == '"' && lookbehind2[0] != '\\') {
isLiteralMode = !isLiteralMode
}
sb.append(char)
}
else {
// do nothing
}
charCtr += 1
}
return lineStructures
}
val rootNodeName = "cflat_node_root"
fun buildTree(lineStructures: List<LineStructure>): SyntaxTreeNode {
fun debug1(any: Any) { if (true) println(any) }
///////////////////////////
// STEP 1. Create a tree //
///////////////////////////
// In this step, we build tree from the line structures parsed by the parser. //
val ASTroot = SyntaxTreeNode(ExpressionType.FUNCTION_DEF, ReturnType.NOTHING, name = rootNodeName, isRoot = true, lineNumber = 1)
val workingNodes = Stack<SyntaxTreeNode>()
workingNodes.push(ASTroot)
fun getWorkingNode() = workingNodes.peek()
fun printStackDebug(): String {
val sb = StringBuilder()
sb.append("Node stack: [")
workingNodes.forEachIndexed { index, it ->
if (index > 0) { sb.append(", ") }
sb.append("l"); sb.append(it.lineNumber)
}
sb.append("]")
return sb.toString()
}
lineStructures.forEachIndexed { index, it -> val (lineNum, depth, tokens) = it
val nextLineDepth = if (index != lineStructures.lastIndex) lineStructures[index + 1].depth else null
debug1("buildtree!! tokens: $tokens")
debug1("call #$index from buildTree()")
val nodeBuilt = asTreeNode(lineNum, tokens)
getWorkingNode().addStatement(nodeBuilt)
debug1("end call #$index from buildTree()")
if (nextLineDepth != null) {
// has code block
if (nextLineDepth > depth) {
workingNodes.push(nodeBuilt)
}
// code block escape
else if (nextLineDepth < depth) {
repeat(depth - nextLineDepth) { workingNodes.pop() }
}
}
}
/////////////////////////////////
// STEP 1-1. Simplify the tree //
/////////////////////////////////
// In this step, we modify the tree so translating to IR2 be easier. //
// More specifically, we do: //
// 1. "If" (cond) {stmt1} "Else" {stmt2} -> "IfElse" (cond) {stmt1, stmt2} //
ASTroot.traversePreorderStatements { node, _ ->
// JOB #1
val ifNodeIndex = node.statements.findAllToIndices { it.name == "if" }
var deletionCount = 0
ifNodeIndex.forEach {
// as we do online-delete, precalculated numbers will go off
// deletionCount will compensate it.
val it = it - deletionCount
val ifNode = node.statements[it]
val elseNode = node.statements.getOrNull(it + 1)
// if filtered IF node has ELSE node appended...
if (elseNode != null && elseNode.name == "else") {
val newNode = SyntaxTreeNode(
ifNode.expressionType, ifNode.returnType,
"ifelse",
ifNode.lineNumber,
ifNode.isRoot, ifNode.isPartOfArgumentsNode
)
if (ifNode.statements.size > 1) throw InternalError("If node contains 2 or more statements!\n[NODE START]\n$node\n[NODE END]")
if (elseNode.statements.size > 1) throw InternalError("Else node contains 2 or more statements!\n[NODE START]\n$node\n[NODE END]")
ifNode.arguments.forEach { newNode.addArgument(it) } // should contain only 1 arg but oh well
newNode.addStatement(ifNode.statements[0])
newNode.addStatement(elseNode.statements[0])
node.statements[it] = newNode
node.statements.removeAt(it + 1)
deletionCount += 1
}
}
}
return ASTroot
}
/**
* @param type "variable", "literal_i", "literal_f"
* @param value string for variable name, int for integer and float literals
*/
private data class VirtualStackItem(val type: String, val value: String)
fun String.isVariable() = this.startsWith('$')
fun String.isRegister() = this.matches(regexRegisterLiteral)
fun ArrayList<String>.append(str: String) = if (str.endsWith(';'))
this.add(str)
else
throw IllegalArgumentException("You missed a semicolon for: $str")
///////////////////////////////////////////////////
// publicising things so that they can be tested //
///////////////////////////////////////////////////
fun resolveTypeString(type: String, isPointer: Boolean = false): ReturnType {
/*val isPointer = type.endsWith('*') or type.endsWith("_ptr") or isPointer
return when (type) {
"void" -> if (isPointer) ReturnType.NOTHING_PTR else ReturnType.NOTHING
"char" -> if (isPointer) ReturnType.CHAR_PTR else ReturnType.CHAR
"short" -> if (isPointer) ReturnType.SHORT_PTR else ReturnType.SHORT
"int" -> if (isPointer) ReturnType.INT_PTR else ReturnType.INT
"long" -> if (isPointer) ReturnType.LONG_PTR else ReturnType.LONG
"float" -> if (isPointer) ReturnType.FLOAT_PTR else ReturnType.FLOAT
"double" -> if (isPointer) ReturnType.DOUBLE_PTR else ReturnType.DOUBLE
"bool" -> if (isPointer) ReturnType.BOOL_PTR else ReturnType.BOOL
else -> if (isPointer) ReturnType.STRUCT_PTR else ReturnType.STRUCT
}*/
return when (type.toLowerCase()) {
"void" -> ReturnType.NOTHING
"int" -> ReturnType.INT
"float" -> ReturnType.FLOAT
else -> throw SyntaxError("Unknown type: $type")
}
}
fun asTreeNode(lineNumber: Int, tokens: List<String>): SyntaxTreeNode {
fun splitContainsValidVariablePreword(split: List<String>): Int {
var ret = -1
for (stage in 0..minOf(3, split.lastIndex)) {
if (validVariablePreword.contains(split[stage])) ret += 1
}
return ret
}
fun debug1(any: Any?) { if (true) println(any) }
// contradiction: auto AND extern
debug1("[asTreeNode] tokens: $tokens")
val firstAssignIndex = tokens.indexOf("=")
val firstLeftParenIndex = tokens.indexOf("(")
val lastRightParenIndex = tokens.lastIndexOf(")")
// special case for FOR :
// int i = 0 // i must be declared beforehand !!; think of C < 99
// for (i = 2 + (3 * 4), i <= 10, i = i + 2) { // separated by comma, parens are mandatory
// dosometing();
// }
if (tokens[0] == "for") {
// for tokens inside of firstLeftParen..lastRightParen,
// split tokens by ',' (will result in 3 tokens, may or may not empty)
// recurse call those three
// e.g. forNode.arguments[0] = asTreeNode( ... )
// forNode.arguments[1] = asTreeNode( ... )
// forNode.arguments[2] = asTreeNode( ... )
val forNode = SyntaxTreeNode(ExpressionType.FUNCTION_CALL, null, "for", lineNumber)
val subTokens = tokens.subList(firstLeftParenIndex, lastRightParenIndex)
val commas = listOf(0, subTokens.indexOf(","), subTokens.lastIndexOf(","), subTokens.size)
val forArgs = (0..2).map { subTokens.subList(1 + commas[it], commas[it + 1]) }.map { asTreeNode(lineNumber, it) }
forArgs.forEach {
forNode.addArgument(it)
}
debug1("[asTreeNode] for tree: \n$forNode")
return forNode
}
val functionCallTokens: List<String>? =
if (firstLeftParenIndex == -1)
null
else if (firstAssignIndex == -1)
tokens.subList(0, firstLeftParenIndex)
else
tokens.subList(firstAssignIndex + 1, firstLeftParenIndex)
val functionCallTokensContainsTokens = if (functionCallTokens == null) false else
(functionCallTokens.map { if (splittableTokens.contains(it)) 1 else 0 }.sum() > 0)
// if TRUE, it's not a function call/def (e.g. foobar = funccall ( arg arg arg )
debug1("!!##[asTreeNode] line $lineNumber; functionCallTokens: $functionCallTokens; contains tokens?: $functionCallTokensContainsTokens")
/////////////////////////////
// unwrap (((((parens))))) //
/////////////////////////////
// FIXME ( asrtra ) + ( feinov ) forms are errenously stripped its paren away
/*if (tokens.first() == "(" && tokens.last() == ")") {
var wrapSize = 1
while (tokens[wrapSize] == "(" && tokens[tokens.lastIndex - wrapSize] == ")") {
wrapSize++
}
return asTreeNode(lineNumber, tokens.subList(wrapSize, tokens.lastIndex - wrapSize + 1))
}*/
debug1("!!##[asTreeNode] input token: $tokens")
////////////////////////////
// as Function Definition //
////////////////////////////
if (!functionCallTokensContainsTokens && functionCallTokens != null && functionCallTokens.size >= 2 && functionCallTokens.size <= 4) { // e.g. int main , StructName fooo , extern void doSomething , extern unsigned StructName uwwse
val actualFuncType = functionCallTokens[functionCallTokens.lastIndex - 1]
val returnType = resolveTypeString(actualFuncType)
val funcName = functionCallTokens.last()
// get arguments
// int * index , bool * * isSomething , double someNumber , ...
val argumentsDef = tokens.subList(firstLeftParenIndex + 1, lastRightParenIndex)
val argTypeNamePair = ArrayList<Pair<ReturnType, String?>>()
debug1("!! func def args")
debug1("!! <- $argumentsDef")
// chew it down to more understandable format
var typeHolder: ReturnType? = null
var nameHolder: String? = null
argumentsDef.forEachIndexed { index, token ->
if (argumentDefBadTokens.contains(token)) {
throw IllegalTokenException("at line $lineNumber -- illegal token '$token' used on function argument definition")
}
if (token == ",") {
if (typeHolder == null) throw SyntaxError("at line $lineNumber -- type not specified")
argTypeNamePair.add(typeHolder!! to nameHolder)
typeHolder = null
nameHolder = null
}
else if (token == "*") {
if (typeHolder == null) throw SyntaxError("at line $lineNumber -- type not specified")
typeHolder = resolveTypeString(typeHolder.toString().toLowerCase(), true)
}
else if (typeHolder == null) {
typeHolder = resolveTypeString(token)
}
else if (typeHolder != null) {
nameHolder = token
if (index == argumentsDef.lastIndex) {
argTypeNamePair.add(typeHolder!! to nameHolder)
}
}
else {
throw InternalError("uncaught shit right there")
}
}
debug1("!! -> $argTypeNamePair")
debug1("================================")
val funcDefNode = SyntaxTreeNode(ExpressionType.FUNCTION_DEF, returnType, funcName, lineNumber)
//if (returnType == ReturnType.STRUCT || returnType == ReturnType.STRUCT_PTR) {
// funcDefNode.structName = actualFuncType
//}
argTypeNamePair.forEach { val (type, name) = it
// TODO struct and structName
val funcDefArgNode = SyntaxTreeNode(ExpressionType.FUNC_ARGUMENT_DEF, type, name, lineNumber, isPartOfArgumentsNode = true)
funcDefNode.addArgument(funcDefArgNode)
}
return funcDefNode
}
//////////////////////
// as Function Call // (also works as keyworded code block (e.g. if, for, while))
//////////////////////
else if (tokens.size >= 3 /* foo, (, ); guaranteed to be at least three */ && tokens[1] == "(" &&
!functionCallTokensContainsTokens && functionCallTokens != null && functionCallTokens.size == 1) { // e.g. if ( , while ( ,
val funcName = functionCallTokens.last()
// get arguments
// complex_statements , ( value = funccall ( arg ) ) , "string,arg" , 42f
val argumentsDef = tokens.subList(firstLeftParenIndex + 1, lastRightParenIndex)
debug1("!! func call args:")
debug1("!! <- $argumentsDef")
// split into tokens list, splitted by ','
val functionCallArguments = ArrayList<ArrayList<String>>() // double array is intended (e.g. [["tsrasrat"], ["42"], [callff, (, "wut", )]] for input ("tsrasrat", "42", callff("wut"))
var tokensHolder = ArrayList<String>()
argumentsDef.forEachIndexed { index, token ->
if (index == argumentsDef.lastIndex) {
tokensHolder.add(token)
functionCallArguments.add(tokensHolder)
tokensHolder = ArrayList<String>() // can't reuse; must make new one
}
else if (token == ",") {
if (tokensHolder.isEmpty()) {
throw SyntaxError("at line $lineNumber -- misplaced comma")
}
else {
functionCallArguments.add(tokensHolder)
tokensHolder = ArrayList<String>() // can't reuse; must make new one
}
}
else {
tokensHolder.add(token)
}
}
debug1("!! -> $functionCallArguments")
val funcCallNode = SyntaxTreeNode(ExpressionType.FUNCTION_CALL, null, funcName, lineNumber)
functionCallArguments.forEach {
debug1("!! forEach $it")
debug1("call from asTreeNode().asFunctionCall")
val argNodeLeaf = asTreeNode(lineNumber, it); argNodeLeaf.isPartOfArgumentsNode = true
funcCallNode.addArgument(argNodeLeaf)
}
debug1("================================")
return funcCallNode
}
////////////////////////
// as Var Call / etc. //
////////////////////////
else {
// filter illegal lines (absurd keyword usage)
tokens.forEach {
if (codeBlockKeywords.contains(it)) {
// code block without argumenets; give it proper parens and redirect
val newTokens = tokens.toMutableList()
if (newTokens.size != 1) {
throw SyntaxError("Number of tokens is not 1 (got size of ${newTokens.size}): ${newTokens}")
}
newTokens.add("("); newTokens.add(")")
debug1("call from asTreeNode().filterIllegalLines")
return asTreeNode(lineNumber, newTokens)
}
}
///////////////////////
// Bunch of literals //
///////////////////////
if (tokens.size == 1) {
val word = tokens[0]
debug1("!! literal, token: '$word'")
//debug1("================================")
// filtered String literals
if (word.startsWith('"') && word.endsWith('"')) {
val leafNode = SyntaxTreeNode(ExpressionType.LITERAL_LEAF, ReturnType.DATABASE, null, lineNumber)
leafNode.literalValue = tokens[0].substring(1, tokens[0].lastIndex) + nullchar
return leafNode
}
// bool literals
else if (word.matches(regexBooleanWhole)) {
val leafNode = SyntaxTreeNode(ExpressionType.LITERAL_LEAF, ReturnType.INT, null, lineNumber)
leafNode.literalValue = word == "true"
return leafNode
}
// hexadecimal literals
else if (word.matches(regexHexWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.INT,
null, lineNumber
)
try {
leafNode.literalValue =
word.replace(Regex("""[^0-9A-Fa-f]"""), "").toLong(16).and(0xFFFFFFFFL).toInt()
}
catch (e: NumberFormatException) {
throw IllegalTokenException("at line $lineNumber -- $word is too large to be represented as ${leafNode.returnType?.toString()?.toLowerCase()}")
}
return leafNode
}
// octal literals
else if (word.matches(regexOctWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.INT,
null, lineNumber
)
try {
leafNode.literalValue =
word.replace(Regex("""[^0-7]"""), "").toLong(8).and(0xFFFFFFFFL).toInt()
}
catch (e: NumberFormatException) {
throw IllegalTokenException("at line $lineNumber -- $word is too large to be represented as ${leafNode.returnType?.toString()?.toLowerCase()}")
}
return leafNode
}
// binary literals
else if (word.matches(regexBinWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.INT,
null, lineNumber
)
try {
leafNode.literalValue =
word.replace(Regex("""[^01]"""), "").toLong(2).and(0xFFFFFFFFL).toInt()
}
catch (e: NumberFormatException) {
throw IllegalTokenException("at line $lineNumber -- $word is too large to be represented as ${leafNode.returnType?.toString()?.toLowerCase()}")
}
return leafNode
}
// int literals
else if (word.matches(regexIntWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.INT,
null, lineNumber
)
try {
leafNode.literalValue =
word.replace(Regex("""[^0-9]"""), "").toLong().and(0xFFFFFFFFL).toInt()
}
catch (e: NumberFormatException) {
throw IllegalTokenException("at line $lineNumber -- $word is too large to be represented as ${leafNode.returnType?.toString()?.toLowerCase()}")
}
return leafNode
}
// floating point literals
else if (word.matches(regexFPWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.FLOAT,
null, lineNumber
)
try {
leafNode.literalValue = if (word.endsWith('F', true))
word.slice(0..word.lastIndex - 1).toDouble() // DOUBLE when C-flat; replace it with 'toFloat()' if you're standard C
else
word.toDouble()
}
catch (e: NumberFormatException) {
throw InternalError("at line $lineNumber, while parsing '$word' as Double")
}
return leafNode
}
//////////////////////////////////////
// variable literal (VARIABLE_LEAF) // usually function call arguments
//////////////////////////////////////
else if (word.matches(regexVarNameWhole)) {
val leafNode = SyntaxTreeNode(ExpressionType.VARIABLE_READ, null, word, lineNumber)
return leafNode
}
}
else {
/////////////////////////////////////////////////
// return something; goto somewhere (keywords) //
/////////////////////////////////////////////////
if (tokens[0] == "goto" || tokens[0] == "comefrom") {
val nnode = SyntaxTreeNode(
ExpressionType.FUNCTION_CALL,
null,
tokens[0],
lineNumber
)
val rawTreeNode = tokens[1].toRawTreeNode(lineNumber); rawTreeNode.isPartOfArgumentsNode = true
nnode.addArgument(rawTreeNode)
return nnode
}
else if (tokens[0] == "return") {
val returnNode = SyntaxTreeNode(
ExpressionType.FUNCTION_CALL,
null,
"return",
lineNumber
)
val node = turnInfixTokensIntoTree(lineNumber, tokens.subList(1, tokens.lastIndex + 1)); node.isPartOfArgumentsNode = true
returnNode.addArgument(node)
return returnNode
}
//////////////////////////
// variable declaration //
//////////////////////////
// extern auto struct STRUCTID foobarbaz
// extern auto int foobarlulz
else if (splitContainsValidVariablePreword(tokens) != -1) {
val prewordIndex = splitContainsValidVariablePreword(tokens)
val realType = tokens[prewordIndex]
try {
val hasAssignment: Boolean
if (realType == "struct")
hasAssignment = tokens.lastIndex > prewordIndex + 2
else
hasAssignment = tokens.lastIndex > prewordIndex + 1
// deal with assignment
if (hasAssignment) {
// TODO support type_ptr_ptr_ptr...
// use turnInfixTokensIntoTree and inject it to assignment node
val isPtrType = tokens[1] == "*"
val typeStr = tokens[0] + if (isPtrType) "_ptr" else ""
val tokensWithoutType = if (isPtrType)
tokens.subList(2, tokens.size)
else
tokens.subList(1, tokens.size)
val infixNode = turnInfixTokensIntoTree(lineNumber, tokensWithoutType)
//#_assignvar(SyntaxTreeNode<RawString> varname, SyntaxTreeNode<RawString> vartype, SyntaxTreeNode value)
val returnNode = SyntaxTreeNode(ExpressionType.FUNCTION_CALL, ReturnType.NOTHING, "#_assignvar", lineNumber)
val nameNode = tokensWithoutType.first().toRawTreeNode(lineNumber); nameNode.isPartOfArgumentsNode = true
returnNode.addArgument(nameNode)
val typeNode = typeStr.toRawTreeNode(lineNumber); typeNode.isPartOfArgumentsNode = true
returnNode.addArgument(typeNode)
infixNode.isPartOfArgumentsNode = true
returnNode.addArgument(infixNode)
return returnNode
}
else {
// #_declarevar(SyntaxTreeNode<RawString> varname, SyntaxTreeNode<RawString> vartype)
val leafNode = SyntaxTreeNode(ExpressionType.INTERNAL_FUNCTION_CALL, ReturnType.NOTHING, "#_declarevar", lineNumber)
val valueNode = tokens[1].toRawTreeNode(lineNumber); valueNode.isPartOfArgumentsNode = true
leafNode.addArgument(valueNode)
val typeNode = tokens[0].toRawTreeNode(lineNumber); typeNode.isPartOfArgumentsNode = true
leafNode.addArgument(typeNode)
return leafNode
}
}
catch (syntaxFuck: ArrayIndexOutOfBoundsException) {
throw SyntaxError("at line $lineNumber -- missing statement(s)")
}
}
else {
debug1("!! infix in: $tokens")
// infix notation
return turnInfixTokensIntoTree(lineNumber, tokens)
}
TODO()
} // end if (tokens.size == 1)
TODO()
}
}
fun turnInfixTokensIntoTree(lineNumber: Int, tokens: List<String>): SyntaxTreeNode {
// based on https://stackoverflow.com/questions/1946896/conversion-from-infix-to-prefix
// FIXME: differentiate parens for function call from grouping
fun debug(any: Any) { if (true) println(any) }
fun precedenceOf(token: String): Int {
if (token == "(" || token == ")") return -1
operatorsHierarchyInternal.forEachIndexed { index, hashSet ->
if (hashSet.contains(token)) return index
}
throw SyntaxError("[infix-to-tree] at $lineNumber -- unknown operator '$token'")
}
val tokens = tokens.reversed()
val stack = Stack<String>()
val treeArgsStack = Stack<Any>()
fun addToTree(token: String) {
debug("[infix-to-tree] adding '$token'")
fun argsCountOf(operator: String) = if (unaryOps.contains(operator)) 1 else 2
fun popAsTree(): SyntaxTreeNode {
val rawElem = treeArgsStack.pop()
if (rawElem is String) {
debug("[infix-to-tree] call from turnInfixTokensIntoTree().addToTree().popAsTree()")
return asTreeNode(lineNumber, listOf(rawElem))
}
else if (rawElem is SyntaxTreeNode)
return rawElem
else
throw InternalError("I said you to put String or SyntaxTreeNode only; what's this? ${rawElem.javaClass.simpleName}?")
}
if (!operatorsNoOrder.contains(token)) {
debug("-> not a operator; pushing to args stack")
treeArgsStack.push(token)
}
else {
debug("-> taking ${argsCountOf(token)} value(s) from stack")
val treeNode = SyntaxTreeNode(ExpressionType.FUNCTION_CALL, null, token, lineNumber)
repeat(argsCountOf(token)) {
val poppedTree = popAsTree(); poppedTree.isPartOfArgumentsNode = true
treeNode.addArgument(poppedTree)
}
treeArgsStack.push(treeNode)
}
}
debug("[infix-to-tree] reversed tokens: $tokens")
tokens.forEachIndexed { index, rawToken ->
// contextually decide what is real token
val token =
// if prev token is operator (used '+' as token list is reversed)
if (index == tokens.lastIndex || operatorsNoOrder.contains(tokens[index + 1])) {
if (rawToken == "+") "#_unaryplus"
else if (rawToken == "-") "#_unaryminus"
else if (rawToken == "&") "#_addressof"
else if (rawToken == "*") "#_ptrderef"
else if (rawToken == "++") "#_preinc"
else if (rawToken == "--") "#_predec"
else rawToken
}
else rawToken
if (token == ")") {
stack.push(token)
}
else if (token == "(") {
while (stack.isNotEmpty()) {
val t = stack.pop()
if (t == ")") break
addToTree(t)
}
}
else if (!operatorsNoOrder.contains(token)) {
addToTree(token)
}
else {
// XXX: associativity should be considered here
// https://en.wikipedia.org/wiki/Operator_associativity
while (stack.isNotEmpty() && precedenceOf(stack.peek()) > precedenceOf(token)) {
addToTree(stack.pop())
}
stack.add(token)
}
}
while (stack.isNotEmpty()) {
addToTree(stack.pop())
}
if (treeArgsStack.size != 1) {
throw InternalError("Stack size is wrong -- supposed to be 1, but it's ${treeArgsStack.size}\nstack: $treeArgsStack")
}
debug("[infix-to-tree] finalised tree:\n${treeArgsStack.peek()}")
return if (treeArgsStack.peek() is SyntaxTreeNode)
treeArgsStack.peek() as SyntaxTreeNode
else {
debug("[infix-to-tree] call from turnInfixTokensIntoTree().if (treeArgsStack.peek() is SyntaxTreeNode).else")
asTreeNode(lineNumber, listOf(treeArgsStack.peek() as String))
}
}
data class LineStructure(var lineNum: Int, var depth: Int, val tokens: MutableList<String>)
class SyntaxTreeNode(
val expressionType: ExpressionType,
val returnType: ReturnType?, // STATEMENT, LITERAL_LEAF: valid ReturnType; VAREABLE_LEAF: always null
var name: String?,
val lineNumber: Int, // used to generate error message
val isRoot: Boolean = false,
//val derefDepth: Int = 0 // how many ***s are there for pointer
var isPartOfArgumentsNode: Boolean = false
) {
var literalValue: Any? = null // for LITERALs only
var structName: String? = null // for STRUCT return type
val arguments = ArrayList<SyntaxTreeNode>() // for FUNCTION, CODE_BLOCK
val statements = ArrayList<SyntaxTreeNode>()
var depth: Int? = null
fun addArgument(node: SyntaxTreeNode) {
arguments.add(node)
}
fun addStatement(node: SyntaxTreeNode) {
statements.add(node)
}
fun updateDepth() {
if (!isRoot) throw Error("Updating depth only make sense when used as root")
this.depth = 0
arguments.forEach { it._updateDepth(1) }
statements.forEach { it._updateDepth(1) }
}
private fun _updateDepth(recursiveDepth: Int) {
this.depth = recursiveDepth
arguments.forEach { it._updateDepth(recursiveDepth + 1) }
statements.forEach { it._updateDepth(recursiveDepth + 1) }
}
fun expandImplicitEnds() {
if (!isRoot) throw Error("Expanding implicit 'end's only make sense when used as root")
// fixme no nested ifs
statements.forEach { it.statements.forEach { it._expandImplicitEnds() } } // root level if OF FUNCDEF
statements.forEach { it._expandImplicitEnds() } // root level if
}
private fun _expandImplicitEnds() {
if (this.name in functionsImplicitEnd) {
this.statements.add(SyntaxTreeNode(
ExpressionType.INTERNAL_FUNCTION_CALL, null, "end${this.name}", this.lineNumber, this.isRoot
))
}
else if (this.expressionType == ExpressionType.FUNCTION_DEF) {
val endfuncdef = SyntaxTreeNode(
ExpressionType.INTERNAL_FUNCTION_CALL, null, "endfuncdef", this.lineNumber, this.isRoot
)
endfuncdef.addArgument(SyntaxTreeNode(ExpressionType.FUNC_ARGUMENT_DEF, null, this.name!!, this.lineNumber, isPartOfArgumentsNode = true))
this.statements.add(endfuncdef)
}
}
val isLeaf: Boolean
get() = expressionType.toString().endsWith("_LEAF") ||
(arguments.isEmpty() && statements.isEmpty())
override fun toString() = toStringRepresentation(0)
private fun toStringRepresentation(depth: Int): String {
val header = "│ ".repeat(depth) + if (isRoot) "⧫AST (name: $name)" else if (isLeaf) "◊AST$depth (name: $name)" else "☐AST$depth (name: $name)"
val lines = arrayListOf(
header,
"│ ".repeat(depth+1) + "ExprType : $expressionType",
"│ ".repeat(depth+1) + "RetnType : $returnType",
"│ ".repeat(depth+1) + "LiteralV : '$literalValue'",
"│ ".repeat(depth+1) + "isArgNod : $isPartOfArgumentsNode"
)
if (!isLeaf) {
lines.add("│ ".repeat(depth+1) + "# of arguments: ${arguments.size}")
arguments.forEach { lines.add(it.toStringRepresentation(depth + 1)) }
lines.add("│ ".repeat(depth+1) + "# of statements: ${statements.size}")
statements.forEach { lines.add(it.toStringRepresentation(depth + 1)) }
}
lines.add("│ ".repeat(depth) + "╘" + "═".repeat(header.length - 1 - 2*depth))
val sb = StringBuilder()
lines.forEachIndexed { index, line ->
sb.append(line)
if (index < lines.lastIndex) { sb.append("\n") }
}
return sb.toString()
}
private fun traverseStmtOnly(node: SyntaxTreeNode, action: (SyntaxTreeNode, Int) -> Unit, depth: Int = 0) {
//if (node == null) return
action(node, depth)
node.statements.forEach { traverseStmtOnly(it, action, depth + 1) }
}
fun traversePreorderStatements(action: (SyntaxTreeNode, Int) -> Unit) {
this.traverseStmtOnly(this, action)
}
}
private fun String.toRawTreeNode(lineNumber: Int): SyntaxTreeNode {
val node = SyntaxTreeNode(ExpressionType.LITERAL_LEAF, ReturnType.DATABASE, null, lineNumber)
node.literalValue = this
return node
}
inline fun <T> Iterable<T>.findAllToIndices(predicate: (T) -> Boolean): IntArray {
val indices = ArrayList<Int>()
this.forEachIndexed { index, t ->
if (predicate(t))
indices.add(index)
}
return indices.toIntArray()
}
enum class ExpressionType {
FUNCTION_DEF, FUNC_ARGUMENT_DEF, // expect Arguments and Statements
INTERNAL_FUNCTION_CALL,
FUNCTION_CALL, // expect Arguments and Statements
// the case of OPERATOR CALL //
// returnType: variable type; name: "="; TODO add description for STRUCT
// arg0: name of the variable (String)
// arg1: (optional) assigned value, either LITERAL or FUNCTION_CALL or another OPERATOR CALL
// arg2: (if STRUCT) struct identifier (String)
LITERAL_LEAF, // literals, also act as a leaf of the tree; has returnType of null
VARIABLE_WRITE, // CodeL; loads memory address to be written onto
VARIABLE_READ // CodeR; the actual value stored in its memory address
}
enum class ReturnType {
INT, FLOAT,
NOTHING, // null
DATABASE // array of bytes, also could be String
}
class PreprocessorRules {
private val kwdRetPair = HashMap<String, String>()
fun addDefinition(keyword: String, ret: String) {
kwdRetPair[keyword] = ret
}
fun removeDefinition(keyword: String) {
kwdRetPair.remove(keyword)
}
fun forEachKeywordForTokens(action: (String, String) -> Unit) {
kwdRetPair.forEach { key, value ->
action("""[ \t\n]+""" + key + """(?=[ \t\n;]+)""", value)
}
}
}
/**
* Notation rules:
* - Variable: prepend with '$' (e.g. $duplicantsCount) // totally not a Oxygen Not Included reference
* - Register: prepend with 'r' (e.g. r3)
*/
data class IntermediateRepresentation(
var lineNum: Int,
var instruction: String = "DUMMY",
var arg1: String? = null,
var arg2: String? = null,
var arg3: String? = null,
var arg4: String? = null,
var arg5: String? = null
) {
constructor(other: IntermediateRepresentation) : this(
other.lineNum,
other.instruction,
other.arg1,
other.arg2,
other.arg3,
other.arg4,
other.arg5
)
override fun toString(): String {
val sb = StringBuilder()
sb.append(instruction)
arg1?.let { sb.append(" $it") }
arg2?.let { sb.append(", $it") }
arg3?.let { sb.append(", $it") }
arg4?.let { sb.append(", $it") }
arg5?.let { sb.append(", $it") }
sb.append("; (at line $lineNum)")
return sb.toString()
}
}
}
open class SyntaxError(msg: String? = null) : Exception(msg)
class IllegalTokenException(msg: String? = null) : SyntaxError(msg)
class UnresolvedReference(msg: String? = null) : SyntaxError(msg)
class UndefinedStatement(msg: String? = null) : SyntaxError(msg)
class DuplicateDefinition(msg: String? = null) : SyntaxError(msg)
class PreprocessorErrorMessage(msg: String) : SyntaxError(msg)
| mit | 3b4e2e814c369eb07eb54d35d8e85bd4 | 39.834909 | 276 | 0.506705 | 5.057754 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/structure/filter/LabelFilter.kt | 1 | 1384 | package nl.hannahsten.texifyidea.structure.filter
import com.intellij.ide.util.treeView.smartTree.ActionPresentation
import com.intellij.ide.util.treeView.smartTree.Filter
import com.intellij.ide.util.treeView.smartTree.TreeElement
import nl.hannahsten.texifyidea.TexifyIcons
import nl.hannahsten.texifyidea.structure.latex.LatexStructureViewCommandElement
import nl.hannahsten.texifyidea.util.labels.getLabelDefinitionCommands
import javax.swing.Icon
/**
* @author Hannah Schellekens
*/
class LabelFilter : Filter {
override fun isVisible(treeElement: TreeElement): Boolean {
if (treeElement !is LatexStructureViewCommandElement) {
return true
}
return !getLabelDefinitionCommands().contains(treeElement.commandName)
}
override fun isReverted(): Boolean = true
override fun getPresentation(): ActionPresentation = LatexLabelFilterPresentation.INSTANCE
override fun getName(): String = "latex.texify.filter.label"
/**
* @author Hannah Schellekens
*/
private class LatexLabelFilterPresentation : ActionPresentation {
override fun getText(): String = "Show Labels"
override fun getDescription(): String = "Show Labels"
override fun getIcon(): Icon = TexifyIcons.DOT_LABEL
companion object {
val INSTANCE = LatexLabelFilterPresentation()
}
}
} | mit | a2d8ed6bb745359c0b9dccd4b69b799e | 29.777778 | 94 | 0.737717 | 5.014493 | false | false | false | false |
asamm/locus-api | locus-api-android-sample/src/main/java/com/asamm/locus/api/sample/pages/PageUtilsFragment.kt | 1 | 9035 | /**
* Created by menion on 29/08/2016.
* This code is part of Locus project from Asamm Software, s. r. o.
*/
package com.asamm.locus.api.sample.pages
import android.app.AlertDialog
import android.content.Intent
import android.widget.Toast
import com.asamm.locus.api.sample.ActivityDashboard
import com.asamm.locus.api.sample.BuildConfig
import com.asamm.locus.api.sample.utils.BasicAdapterItem
import com.asamm.locus.api.sample.utils.SampleCalls
import locus.api.android.ActionBasics
import locus.api.android.ActionFiles
import locus.api.android.features.geocaching.fieldNotes.FieldNotesHelper
import locus.api.android.objects.LocusVersion
import locus.api.android.utils.LocusConst
import java.util.*
class PageUtilsFragment : ABasePageFragment() {
override val items: List<BasicAdapterItem>
get() {
val items = ArrayList<BasicAdapterItem>()
items.add(BasicAdapterItem(-1,
"Get basic info about Locus app",
"Basic checks on installed Locus apps."))
items.add(BasicAdapterItem(1,
"Send GPX file to system",
"Send existing GPX file to system. This should invoke selection of an app that will handle this request."))
items.add(BasicAdapterItem(2,
"Send GPX file directly to Locus",
"You may also send intent (with a link to a file) directly to Locus app."))
items.add(BasicAdapterItem(3,
"Pick location from Locus",
"If you need 'location' in your application, this call allows you to use Locus 'GetLocation' screen. Result is handled in MainActivity as 'LocusUtils.isIntentGetLocation()'"))
items.add(BasicAdapterItem(4,
"Pick file",
"Allows to use Locus internal file picker and choose a file from the file system. You may also specify a filter on requested file. Request is sent as 'Activity.startActivityForResult()', so you have to handle the result in your own activity."))
items.add(BasicAdapterItem(5,
"Pick directory",
"Same as previous sample, just for picking directories instead of files."))
items.add(BasicAdapterItem(6,
"Get ROOT directory",
"Allows to get current active ROOT directory of installed Locus."))
items.add(BasicAdapterItem(7,
"Add WMS map",
"Allows to add WMS map directly to the list of WMS services."))
items.add(BasicAdapterItem(11,
"Dashboard",
"Very nice example that shows how your app may create its own dashboard filled with data received by Locus 'Periodic updates'"))
items.add(BasicAdapterItem(17,
"Get fresh UpdateContainer",
"Simple method how to get fresh UpdateContainer with new data ( no need for PeriodicUpdates )"))
items.add(BasicAdapterItem(12,
"Show circles",
"Small function that allows to draw circles on Locus map. This function is called as broadcast so check result in running Locus!"))
items.add(BasicAdapterItem(13,
"Is Periodic update enabled",
"Because periodic updates are useful in many cases, not just for the dashboard, this function allows to check if 'Periodic updates' are enabled in Locus."))
items.add(BasicAdapterItem(14,
"Request available Geocaching field notes",
"Simple method of getting number of existing field notes in Locus Map application"))
items.add(BasicAdapterItem(15,
"Check item purchase state",
"This function allows to check state of purchase of a certain item (with known ID) in Locus Store"))
items.add(BasicAdapterItem(16,
"Display detail of Store item",
"Display detail of a certain Locus Store item (with known ID)"))
items.add(BasicAdapterItem(19,
"Take a 'screenshot'",
"Take a bitmap screenshot of certain place in app"))
items.add(BasicAdapterItem(20,
"New 'Action tasks' API",
"Suggest to test in split screen mode with active Locus Map"))
// TEMPORARY TEST ITEMS
if (BuildConfig.DEBUG) {
// nothing to test
}
return items
}
@Throws(Exception::class)
override fun onItemClicked(itemId: Int, activeLocus: LocusVersion) {
// handle action
when (itemId) {
-1 -> SampleCalls.callDisplayLocusMapInfo(act)
1 -> SampleCalls.callSendFileToSystem(act)
2 -> SampleCalls.callSendFileToLocus(act, activeLocus)
3 -> SampleCalls.pickLocation(act)
4 ->
// filter data so only visible will be GPX and KML files
ActionFiles.actionPickFile(act,
0, "Give me a FILE!!",
arrayOf(".gpx", ".kml"))
5 -> ActionFiles.actionPickDir(act, 1)
6 -> AlertDialog.Builder(act)
.setTitle("Locus Root directory")
.setMessage("dir:" + SampleCalls.getRootDirectory(act, activeLocus) +
"\n\n'null' means no required version installed or different problem")
.setPositiveButton("Close") { _, _ -> }
.show()
7 -> ActionBasics.callAddNewWmsMap(act,
"http://mapy.geology.cz/arcgis/services/Inspire/GM500K/MapServer/WMSServer")
11 -> startActivity(Intent(act, ActivityDashboard::class.java))
12 -> SampleCalls.showCircles(act)
13 -> AlertDialog.Builder(act).setTitle("Periodic update")
.setMessage("enabled:" + SampleCalls.isPeriodicUpdateEnabled(act, activeLocus))
.setPositiveButton("Close") { _, _ -> }
.show()
14 -> {
val count = FieldNotesHelper.getCount(act, activeLocus)
Toast.makeText(act,
"Available field notes:$count", Toast.LENGTH_LONG).show()
}
15 -> {
// We test here if user has purchased "Add-on Field Notes Pro. Unique ID is defined on our Store
// so it needs to be known for you before asking.
val purchaseId = ActionBasics.getItemPurchaseState(
act, activeLocus, 5943264947470336L)
when (purchaseId) {
LocusConst.PURCHASE_STATE_PURCHASED -> Toast.makeText(act,
"Purchase item state: purchased", Toast.LENGTH_LONG).show()
LocusConst.PURCHASE_STATE_NOT_PURCHASED -> Toast.makeText(act,
"Purchase item state: not purchased", Toast.LENGTH_LONG).show()
else -> // this usually means that user profile is not loaded. Best what to do is call
// "displayLocusStoreItemDetail" to display item detail which also loads users
// profile
Toast.makeText(act,
"Purchase item state: $purchaseId", Toast.LENGTH_LONG).show()
}
}
16 ->
// We display here Locus Store with certain item. In this case it is "Add-on Field Notes Pro.
// Unique ID is defined on our Store so it needs to be known for you before asking.
ActionBasics.displayLocusStoreItemDetail(
act, activeLocus, 5943264947470336L)
17 -> {
val uc = ActionBasics.getUpdateContainer(act, activeLocus)
if (uc != null) {
AlertDialog.Builder(act)
.setTitle("Fresh UpdateContainer")
.setMessage("UC: $uc")
.setPositiveButton("Close") { _, _ -> }
.show()
} else {
Toast.makeText(act,
"Unable to obtain UpdateContainer from $activeLocus", Toast.LENGTH_LONG).show()
}
}
19 -> {
@Suppress("ReplaceSingleLineLet")
act.supportFragmentManager
.beginTransaction()
.add(MapFragment(), "MAP_FRAGMENT")
.commit()
}
20 -> {
@Suppress("ReplaceSingleLineLet")
act.supportFragmentManager
.beginTransaction()
.add(PageBroadcastApiSamples(), "BROADCAST_API_FRAGMENT")
.commit()
}
}
}
}
| mit | b3c48c6be08a7072a1904946f00e34dc | 52.147059 | 264 | 0.560487 | 5.219526 | false | false | false | false |
Harvard2017/matchr | app/src/main/java/com/matchr/Firebase.kt | 1 | 8595 | package com.matchr
import ca.allanwang.kau.utils.postDelayed
import com.google.firebase.database.*
import com.matchr.data.*
import com.matchr.utils.L
import org.jetbrains.anko.doAsync
import java.util.*
/**
* Created by Allan Wang on 2017-10-21.
*/
object Firebase {
const val TYPE = "type"
const val DATA = "data"
const val QUESTION = "question"
const val OPTIONS = "options"
const val USER_ID = "user_id"
const val RESPONSE_ID = "response_id"
const val WEIGHT = "weight"
const val NAME = "name"
const val EMAIL = "email"
lateinit var question_pool_key: String
val database: FirebaseDatabase by lazy { FirebaseDatabase.getInstance() }
val users
get() = database.getReference("test")
fun getFirstQuestion(callback: (Int) -> Unit) {
users.genericGet("startId") { data ->
L.v(data?.key)
L.v(data?.value?.toString())
callback(data.intValueOr(-1))
}
}
fun init(callback: () -> Unit) {
users.ref.genericGet("data_pool") {
question_pool_key = it?.value?.toString() ?: QUESTION_DATA_TUTORING
callback()
}
}
private fun DataSnapshot?.intValueOr(default: Int) = this?.value?.toString()?.toIntOrNull() ?: default
private fun DataSnapshot?.floatValueOr(default: Float) = this?.value?.toString()?.toFloatOrNull() ?: default
fun getQuestion(id: Int, callback: (Question?) -> Unit) {
users.genericGet(Endpoints.QUESTIONS.pathWith("$question_pool_key/$id")) { data ->
if (data == null) return@genericGet callback(null)
val question = data.child(QUESTION).value.toString()
val options = data.child(OPTIONS).children.filterNotNull().map { d ->
d.key to d.intValueOr(-1)
}
if (options.isEmpty()) return@genericGet callback(null)
val type = data.child(TYPE).intValueOr(0)
callback(Question(id, question, options, if (type >= QuestionType.values.size) 0 else type))
}
}
fun saveQuestion(poolKey: String, question: Question) {
val data = mutableListOf<Pair<String, Any>>().apply {
add(TYPE to question.type)
add(QUESTION to question.question)
question.options.forEach { (k, v) ->
add("$OPTIONS/$k" to v)
}
}
Endpoints.QUESTIONS.saveData(poolKey, question.id, *data.toTypedArray())
}
private fun DatabaseReference.genericGet(path: String, callback: (DataSnapshot?) -> Unit) {
L.v("Getting data for path $path")
child(path).ref.orderByPriority().addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
callback(null)
}
override fun onDataChange(p0: DataSnapshot) {
callback(p0)
}
})
}
fun saveResponse(response: Response) {
Endpoints.RESPONSES.saveData("$question_pool_key/${response.userId}", response.qOrdinal,
DATA to response.data)
}
fun getResponse(id: String, qId: Int, callback: (Response?) -> Unit) {
users.genericGet(Endpoints.RESPONSES.pathWith("$question_pool_key/$id")) { data ->
if (data == null) return@genericGet callback(null)
val response = data.child(DATA).children.filterNotNull().map { d -> d.value.toString() }
if (response.isEmpty()) return@genericGet callback(null)
callback(Response(id, qId, response))
}
}
fun getResponses(id: String, callback: (List<Response>) -> Unit) {
users.genericGet(Endpoints.RESPONSES.pathWith("$question_pool_key/$id")) { data ->
if (data == null) return@genericGet callback(emptyList())
val responses = data.children.map {
Response(id, it.key.toInt(), it.child(DATA).children.filterNotNull().map { d ->
d.value.toString()
})
}
callback(responses)
}
}
fun matchData(userId: String, callback: (List<Pair<User, Float>>) -> Unit) {
doAsync {
users.genericGet(Endpoints.RESPONSES.pathWith(question_pool_key)) { data ->
if (data == null) return@genericGet callback(emptyList())
var self: Pair<User, Map<Int, List<String>>>? = null
getUsers { users ->
if (users.isEmpty()) return@getUsers callback(emptyList())
val candidates: List<Pair<User, Map<Int, List<String>>>> = data.children.mapNotNull {
L.d("K ${it.key}")
val candidate = users[it.key] ?: return@mapNotNull null
val responses = it.children.map { r ->
val response = r.child(DATA).children.filterNotNull().map { d -> d.value.toString() }
r.key.toInt() to response
}.filter { it.second.isNotEmpty() }.toMap()
if (candidate.id == userId)
self = candidate to responses
candidate to responses
}.filter { (user, responses) -> user.id != "null" && user.id != userId && responses.isNotEmpty() }
L.d("Self $self")
L.d("Match candidates $candidates")
if (candidates.isEmpty() || self == null) return@getUsers callback(emptyList())
getMatchrs { m ->
if (m.isEmpty()) return@getMatchrs callback(emptyList())
callback(match(m, self!!.second, candidates))
}
}
}
}
}
private fun match(matchrs: List<Matchr>, selfResponses: Map<Int,
List<String>>, candidates: List<Pair<User, Map<Int, List<String>>>>): List<Pair<User, Float>> {
return candidates.map { c ->
val score = matchrs.map { m ->
match(m, selfResponses, c)
}.sum()
val u = c.first to score
L.v("UUU $u")
u
}
}
private fun match(matchr: Matchr, selfResponses: Map<Int, List<String>>,
candidate: Pair<User, Map<Int, List<String>>>): Float {
val data1 = selfResponses[matchr.rId1] ?: return 0f
val data2 = candidate.second[matchr.rId2] ?: return 0f
//compute intersect, divide by average data size, multiply be weight
return data1.intersect(data2).size.toFloat() * 2 / (data1.size + data2.size) * matchr.weight
}
fun saveUser(user: User) {
val child = database.reference.child(Endpoints.USERS.pathWith(user.id))
child.child(NAME).setValue(user.name)
child.child(EMAIL).setValue(user.email)
}
fun getUsers(callback: (Map<String, User>) -> Unit) {
database.reference.genericGet(Endpoints.USERS.pathWith("")) { data ->
data ?: return@genericGet callback(emptyMap())
callback(data.children.map { it.key to User(it.key, it.child(NAME).value.toString(), it.child(EMAIL).value.toString()) }.toMap())
}
}
fun saveMatchr(poolKey: String, rId1: Int, rId2: Int, weight: Float)
= saveMatchr(poolKey, Matchr(rId1, rId2, weight))
fun saveMatchr(poolKey: String, matchr: Matchr) {
Endpoints.MATCHR.saveData(poolKey, matchr.rId1,
RESPONSE_ID to matchr.rId2, WEIGHT to matchr.weight)
}
fun getMatchrs(callback: (List<Matchr>) -> Unit) {
users.genericGet(Endpoints.MATCHR.pathWith(question_pool_key)) { data ->
data ?: return@genericGet callback(emptyList())
callback(data.children.map {
val children = it.children
Matchr(it.key.toInt(), it.child(RESPONSE_ID).intValueOr(-1),
it.child(WEIGHT).floatValueOr(0f))
}.filter { it.rId1 >= 0 && it.rId2 >= 0 && it.weight != 0f })
}
}
}
enum class Endpoints {
RESPONSES, QUESTIONS, MATCHR, USERS;
fun saveData(userId: String, childId: Int, vararg data: Pair<String, Any>)
= saveDataImpl(pathWith(userId), childId, *data)
fun pathWith(post: String) = "${name.toLowerCase(Locale.US)}/$post"
}
fun saveDataImpl(path: String, childId: Int, vararg data: Pair<String, Any>) {
val child = Firebase.users.child("$path/$childId")
data.forEachIndexed { i, (k, v) ->
child.child(k).setValue(v)
child.child(k).setPriority(i)
}
} | apache-2.0 | 12cc16c4918c7d20cc1980c15904ca69 | 39.356808 | 141 | 0.575684 | 4.202934 | false | false | false | false |
GDG-Nantes/devfest-android | app/src/main/kotlin/com/gdgnantes/devfest/android/graphics/RoundedTransformation.kt | 1 | 876 | package com.gdgnantes.devfest.android.graphics
import android.graphics.*
import com.squareup.picasso.Transformation
class RoundedTransformation : Transformation {
private val paint: Paint = Paint()
override fun transform(source: Bitmap): Bitmap {
paint.isAntiAlias = true
paint.shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
val radius = Math.min(source.width, source.height) / 2
val output = Bitmap.createBitmap(source.width, source.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(output)
canvas.drawRoundRect(0f, 0f, source.width.toFloat(), source.height.toFloat(), radius.toFloat(), radius.toFloat(), paint)
if (source != output) {
source.recycle()
}
return output
}
override fun key(): String {
return "rounded"
}
}
| apache-2.0 | d939379a6aef7d7f72ead10f31f399b8 | 27.258065 | 128 | 0.666667 | 4.358209 | false | false | false | false |
FHannes/intellij-community | platform/testFramework/src/com/intellij/testFramework/FixtureRule.kt | 2 | 10600 | /*
* 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.testFramework
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.idea.IdeaTestApplication
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.project.stateStore
import com.intellij.util.SmartList
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.io.systemIndependentPath
import org.junit.rules.ExternalResource
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import java.nio.file.Files
import java.util.concurrent.atomic.AtomicBoolean
private var sharedModule: Module? = null
open class ApplicationRule : ExternalResource() {
companion object {
init {
Logger.setFactory(TestLoggerFactory::class.java)
}
}
override public final fun before() {
IdeaTestApplication.getInstance()
TestRunnerUtil.replaceIdeEventQueueSafely()
(PersistentFS.getInstance() as PersistentFSImpl).cleanPersistedContents()
}
}
/**
* Project created on request, so, could be used as a bare (only application).
*/
class ProjectRule : ApplicationRule() {
companion object {
private var sharedProject: ProjectEx? = null
private val projectOpened = AtomicBoolean()
private fun createLightProject(): ProjectEx {
(PersistentFS.getInstance() as PersistentFSImpl).cleanPersistedContents()
val projectFile = generateTemporaryPath("light_temp_shared_project${ProjectFileType.DOT_DEFAULT_EXTENSION}")
val projectPath = projectFile.systemIndependentPath
val buffer = ByteArrayOutputStream()
Throwable(projectPath, null).printStackTrace(PrintStream(buffer))
val project = PlatformTestCase.createProject(projectPath, "Light project: $buffer") as ProjectEx
Disposer.register(ApplicationManager.getApplication(), Disposable {
try {
disposeProject()
}
finally {
Files.deleteIfExists(projectFile)
}
})
(VirtualFilePointerManager.getInstance() as VirtualFilePointerManagerImpl).storePointers()
return project
}
private fun disposeProject() {
val project = sharedProject ?: return
sharedProject = null
sharedModule = null
Disposer.dispose(project)
}
}
override public fun after() {
if (projectOpened.compareAndSet(true, false)) {
sharedProject?.let { runInEdtAndWait { (ProjectManager.getInstance() as ProjectManagerImpl).forceCloseProject(it, false) } }
}
}
val projectIfOpened: ProjectEx?
get() = if (projectOpened.get()) sharedProject else null
val project: ProjectEx
get() {
var result = sharedProject
if (result == null) {
synchronized(IdeaTestApplication.getInstance()) {
result = sharedProject
if (result == null) {
result = createLightProject()
sharedProject = result
}
}
}
if (projectOpened.compareAndSet(false, true)) {
runInEdtAndWait { ProjectManagerEx.getInstanceEx().openTestProject(project) }
}
return result!!
}
val module: Module
get() {
var result = sharedModule
if (result == null) {
runInEdtAndWait {
LightProjectDescriptor().setUpProject(project, object : LightProjectDescriptor.SetupHandler {
override fun moduleCreated(module: Module) {
result = module
sharedModule = module
}
})
}
}
return result!!
}
}
/**
* rules: outer, middle, inner
* out:
* starting outer rule
* starting middle rule
* starting inner rule
* finished inner rule
* finished middle rule
* finished outer rule
*/
class RuleChain(vararg val rules: TestRule) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
var statement = base
for (i in (rules.size - 1) downTo 0) {
statement = rules[i].apply(statement, description)
}
return statement
}
}
private fun <T : Annotation> Description.getOwnOrClassAnnotation(annotationClass: Class<T>) = getAnnotation(annotationClass) ?: testClass?.getAnnotation(annotationClass)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class RunsInEdt
class EdtRule : TestRule {
override fun apply(base: Statement, description: Description): Statement {
return if (description.getOwnOrClassAnnotation(RunsInEdt::class.java) == null) {
base
}
else {
statement { runInEdtAndWait { base.evaluate() } }
}
}
}
class InitInspectionRule : TestRule {
override fun apply(base: Statement, description: Description) = statement { runInInitMode { base.evaluate() } }
}
inline fun statement(crossinline runnable: () -> Unit) = object : Statement() {
override fun evaluate() {
runnable()
}
}
/**
* Do not optimise test load speed.
* @see IProjectStore.setOptimiseTestLoadSpeed
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class RunsInActiveStoreMode
class ActiveStoreRule(private val projectRule: ProjectRule) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
return if (description.getOwnOrClassAnnotation(RunsInActiveStoreMode::class.java) == null) {
base
}
else {
statement { projectRule.project.runInLoadComponentStateMode { base.evaluate() } }
}
}
}
/**
* In test mode component state is not loaded. Project or module store will load component state if project/module file exists.
* So must be a strong reason to explicitly use this method.
*/
inline fun <T> Project.runInLoadComponentStateMode(task: () -> T): T {
val store = stateStore
val isModeDisabled = store.isOptimiseTestLoadSpeed
if (isModeDisabled) {
store.isOptimiseTestLoadSpeed = false
}
try {
return task()
}
finally {
if (isModeDisabled) {
store.isOptimiseTestLoadSpeed = true
}
}
}
fun createHeavyProject(path: String, useDefaultProjectSettings: Boolean = false) = ProjectManagerEx.getInstanceEx().newProject(null, path, useDefaultProjectSettings, false)!!
fun Project.use(task: (Project) -> Unit) {
val projectManager = ProjectManagerEx.getInstanceEx() as ProjectManagerImpl
try {
runInEdtAndWait { projectManager.openTestProject(this) }
task(this)
}
finally {
runInEdtAndWait { projectManager.forceCloseProject(this, true) }
}
}
class DisposeNonLightProjectsRule : ExternalResource() {
override fun after() {
val projectManager = if (ApplicationManager.getApplication().isDisposed) null else ProjectManager.getInstance() as ProjectManagerImpl
projectManager?.openProjects?.forEachGuaranteed {
if (!ProjectManagerImpl.isLight(it)) {
runInEdtAndWait { projectManager.forceCloseProject(it, true) }
}
}
}
}
class DisposeModulesRule(private val projectRule: ProjectRule) : ExternalResource() {
override fun after() {
projectRule.projectIfOpened?.let {
val moduleManager = ModuleManager.getInstance(it)
runInEdtAndWait {
moduleManager.modules.forEachGuaranteed {
if (!it.isDisposed && it !== sharedModule) {
moduleManager.disposeModule(it)
}
}
}
}
}
}
/**
* Only and only if "before" logic in case of exception doesn't require "after" logic - must be no side effects if "before" finished abnormally.
* So, should be one task per rule.
*/
class WrapRule(private val before: () -> () -> Unit) : TestRule {
override fun apply(base: Statement, description: Description) = statement {
val after = before()
try {
base.evaluate()
}
finally {
after()
}
}
}
fun createProjectAndUseInLoadComponentStateMode(tempDirManager: TemporaryDirectory, directoryBased: Boolean = false, task: (Project) -> Unit) {
createOrLoadProject(tempDirManager, task, directoryBased = directoryBased)
}
fun loadAndUseProject(tempDirManager: TemporaryDirectory, projectCreator: ((VirtualFile) -> String), task: (Project) -> Unit) {
createOrLoadProject(tempDirManager, task, projectCreator, false)
}
private fun createOrLoadProject(tempDirManager: TemporaryDirectory, task: (Project) -> Unit, projectCreator: ((VirtualFile) -> String)? = null, directoryBased: Boolean) {
runInEdtAndWait {
val filePath: String
if (projectCreator == null) {
filePath = tempDirManager.newPath("test${if (directoryBased) "" else ProjectFileType.DOT_DEFAULT_EXTENSION}").systemIndependentPath
}
else {
filePath = runUndoTransparentWriteAction { projectCreator(tempDirManager.newVirtualDirectory()) }
}
val project = if (projectCreator == null) createHeavyProject(filePath, true) else ProjectManagerEx.getInstanceEx().loadProject(filePath)!!
project.runInLoadComponentStateMode {
project.use(task)
}
}
}
fun ComponentManager.saveStore() {
stateStore.save(SmartList())
} | apache-2.0 | 13097076d8a4a54ae94746c1a8ffe3a1 | 32.231975 | 174 | 0.727264 | 4.869086 | false | true | false | false |
facebook/flipper | android/src/main/java/com/facebook/flipper/plugins/uidebugger/descriptors/TextViewDescriptor.kt | 1 | 3709 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.flipper.plugins.uidebugger.descriptors
import android.os.Build
import android.widget.TextView
import com.facebook.flipper.plugins.uidebugger.model.Color
import com.facebook.flipper.plugins.uidebugger.model.Inspectable
import com.facebook.flipper.plugins.uidebugger.model.InspectableObject
import com.facebook.flipper.plugins.uidebugger.model.InspectableValue
import com.facebook.flipper.plugins.uidebugger.model.MetadataId
object TextViewDescriptor : ChainedDescriptor<TextView>() {
private const val NAMESPACE = "TextView"
private var SectionId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, NAMESPACE)
private val TextAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "text")
private val TextSizeAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "textSize")
private val TextColorAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "textColor")
private val IsBoldAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "isBold")
private val IsItalicAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "isItalic")
private val WeightAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "weight")
private val TypefaceAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "typeface")
private val MinLinesAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "minLines")
private val MaxLinesAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "maxLines")
private val MinWidthAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "minWidth")
private val MaxWidthAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "maxWidth")
override fun onGetName(node: TextView): String = node.javaClass.simpleName
override fun onGetData(
node: TextView,
attributeSections: MutableMap<MetadataId, InspectableObject>
) {
val props =
mutableMapOf<Int, Inspectable>(
TextAttributeId to InspectableValue.Text(node.text.toString()),
TextSizeAttributeId to InspectableValue.Number(node.textSize),
TextColorAttributeId to
InspectableValue.Color(Color.fromColor(node.textColors.defaultColor)))
val typeface = node.typeface
if (typeface != null) {
val typeFaceProp =
mutableMapOf<Int, InspectableValue>(
IsBoldAttributeId to InspectableValue.Boolean(typeface.isBold),
IsItalicAttributeId to InspectableValue.Boolean(typeface.isItalic),
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
typeFaceProp[WeightAttributeId] = InspectableValue.Number(typeface.weight)
}
props[TypefaceAttributeId] = InspectableObject(typeFaceProp)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
props[MinLinesAttributeId] = InspectableValue.Number(node.minLines)
props[MaxLinesAttributeId] = InspectableValue.Number(node.maxLines)
props[MinWidthAttributeId] = InspectableValue.Number(node.minWidth)
props[MaxWidthAttributeId] = InspectableValue.Number(node.maxWidth)
}
attributeSections[SectionId] = InspectableObject(props)
}
}
| mit | e728dd9b0217be5206b0c29331fe4bbb | 42.635294 | 88 | 0.7622 | 4.880263 | false | false | false | false |
EricssonResearch/scott-eu | lyo-services/lib-common/src/main/kotlin/eu/scott/warehouse/lib/MqttTopics.kt | 1 | 498 | package eu.scott.warehouse.lib
/**
* Created on 2018-07-27
*
* @author Andrew Berezovskyi ([email protected])
* @version $version-stub$
* @since 0.0.1
*/
object MqttTopics {
const val REGISTRATION_ANNOUNCE = "_scott/whc/registration/announce"
const val REGISTRATION_ACK = "_scott/whc/registration/ack"
const val WHC_PLANS = "_scott/whc/plans"
const val TWIN_SIM_REG_ANNOUNCE = "twins/registration/announce"
const val TWIN_SIM_REG_ACK = "twins/registration/handshake"
}
| apache-2.0 | fc1b8f0088d2fc4e8968747febe0cb9f | 26.666667 | 72 | 0.700803 | 3 | false | false | false | false |
andrei-heidelbacher/metanalysis | chronolens-core/src/main/kotlin/org/chronolens/core/cli/Utils.kt | 1 | 3424 | /*
* Copyright 2018 Andrei Heidelbacher <[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.
*/
@file:JvmName("Utils")
package org.chronolens.core.cli
import picocli.CommandLine
import picocli.CommandLine.ExecutionException
import picocli.CommandLine.HelpCommand
import picocli.CommandLine.RunLast
import picocli.CommandLine.defaultExceptionHandler
import java.util.ServiceLoader
import kotlin.system.exitProcess
/**
* Prints the given [message] to `stderr` and exits with status code `1`.
* code.
*
* Should be used to validate user input and initial state.
*/
public fun exit(message: String): Nothing {
System.err.println(message)
exitProcess(1)
}
/**
* Assembles all the provided subcommands, parses the given command-line [args]
* and runs the [mainCommand], exiting with status code `1` if any error occurs.
*
* A `help` subcommand is implicitly added.
*/
public fun run(mainCommand: MainCommand, vararg args: String) {
mainCommand.registerSubcommands(assembleSubcommands())
val cmd = CommandLine(mainCommand.command).apply {
addSubcommand("help", HelpCommand())
isCaseInsensitiveEnumValuesAllowed = true
}
val exceptionHandler = defaultExceptionHandler().andExit(1)
try {
cmd.parseWithHandlers(RunLast(), exceptionHandler, *args)
} catch (e: ExecutionException) {
System.err.println(e.message)
e.printStackTrace(System.err)
exitProcess(1)
}
}
/** Returns the list of provided subcommands. */
internal fun assembleSubcommands(): List<Subcommand> =
ServiceLoader.load(Subcommand::class.java)
.sortedBy(Subcommand::name)
internal fun String.paragraphs(): Array<String> {
val pars = arrayListOf<String>()
var par = StringBuilder()
var newPar = true
for (line in trimIndent().lines()) {
if (line.isBlank() && par.isNotBlank()) {
pars += par.toString()
par = StringBuilder()
newPar = true
} else if (line.isNotBlank()) {
if (!newPar) {
par.append(' ')
}
par.append(line)
newPar = false
}
}
if (par.isNotBlank()) {
pars += par.toString()
}
return pars.toTypedArray()
}
internal fun String.words(): List<String> {
val words = arrayListOf<String>()
var word = StringBuilder()
for (char in this.capitalize()) {
if (char.isUpperCase()) {
if (!word.isBlank()) {
words += word.toString()
word = StringBuilder()
}
word.append(char.toLowerCase())
} else {
word.append(char)
}
}
if (word.isNotBlank()) {
words += word.toString()
}
return words
}
internal fun getOptionName(propertyName: String): String =
propertyName.words().joinToString(separator = "-", prefix = "--")
| apache-2.0 | c5885ff2f1d02e68619695ffc1d955e8 | 29.846847 | 80 | 0.655082 | 4.301508 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/data/TagDao.kt | 1 | 1600 | package org.tasks.data
import androidx.room.*
import com.todoroo.astrid.data.Task
@Dao
abstract class TagDao {
@Query("UPDATE tags SET name = :name WHERE tag_uid = :tagUid")
abstract suspend fun rename(tagUid: String, name: String)
@Insert
abstract suspend fun insert(tag: Tag)
@Insert
abstract suspend fun insert(tags: Iterable<Tag>)
@Query("DELETE FROM tags WHERE task = :taskId AND tag_uid in (:tagUids)")
internal abstract suspend fun deleteTags(taskId: Long, tagUids: List<String>)
@Query("SELECT * FROM tags WHERE tag_uid = :tagUid")
abstract suspend fun getByTagUid(tagUid: String): List<Tag>
@Query("SELECT * FROM tags WHERE task = :taskId")
abstract suspend fun getTagsForTask(taskId: Long): List<Tag>
@Query("SELECT * FROM tags WHERE task = :taskId AND tag_uid = :tagUid")
abstract suspend fun getTagByTaskAndTagUid(taskId: Long, tagUid: String): Tag?
@Delete
abstract suspend fun delete(tags: List<Tag>)
@Transaction
open suspend fun applyTags(task: Task, tagDataDao: TagDataDao, current: List<TagData>) {
val taskId = task.id
val existing = HashSet(tagDataDao.getTagDataForTask(taskId))
val selected = HashSet<TagData>(current)
val added = selected subtract existing
val removed = existing subtract selected
deleteTags(taskId, removed.map { td -> td.remoteId!! })
insert(task, added)
}
suspend fun insert(task: Task, tags: Collection<TagData>) {
if (!tags.isEmpty()) {
insert(tags.map { Tag(task, it) })
}
}
} | gpl-3.0 | 45aafaede6464b6f6a9c0ec33cc16968 | 32.354167 | 92 | 0.67 | 4.030227 | false | false | false | false |
chibatching/Kotpref | kotpref/src/main/kotlin/com/chibatching/kotpref/pref/LongPref.kt | 1 | 1808 | package com.chibatching.kotpref.pref
import android.annotation.SuppressLint
import android.content.SharedPreferences
import com.chibatching.kotpref.KotprefModel
import com.chibatching.kotpref.execute
import kotlin.reflect.KProperty
/**
* Delegate long shared preferences property.
* @param default default long value
* @param key custom preferences key
* @param commitByDefault commit this property instead of apply
*/
public fun KotprefModel.longPref(
default: Long = 0L,
key: String? = null,
commitByDefault: Boolean = commitAllPropertiesByDefault
): AbstractPref<Long> = LongPref(default, key, commitByDefault)
/**
* Delegate long shared preferences property.
* @param default default long value
* @param key custom preferences key resource id
* @param commitByDefault commit this property instead of apply
*/
public fun KotprefModel.longPref(
default: Long = 0L,
key: Int,
commitByDefault: Boolean = commitAllPropertiesByDefault
): AbstractPref<Long> = longPref(default, context.getString(key), commitByDefault)
internal class LongPref(
val default: Long,
override val key: String?,
private val commitByDefault: Boolean
) : AbstractPref<Long>() {
override fun getFromPreference(property: KProperty<*>, preference: SharedPreferences): Long {
return preference.getLong(preferenceKey, default)
}
@SuppressLint("CommitPrefEdits")
override fun setToPreference(
property: KProperty<*>,
value: Long,
preference: SharedPreferences
) {
preference.edit().putLong(preferenceKey, value).execute(commitByDefault)
}
override fun setToEditor(
property: KProperty<*>,
value: Long,
editor: SharedPreferences.Editor
) {
editor.putLong(preferenceKey, value)
}
}
| apache-2.0 | 049c30482a4e24f8f8d06ccfd84ae0b4 | 29.644068 | 97 | 0.729535 | 4.847185 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/stats/IndicatorStatsTest.kt | 1 | 1671 | package net.nemerosa.ontrack.extension.indicators.stats
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class IndicatorStatsTest {
@Test
fun checks() {
assertFailsWith<IllegalStateException> {
stats(
total = -1,
count = 0
)
}
assertFailsWith<IllegalStateException> {
stats(
total = 0,
count = -1
)
}
assertFailsWith<IllegalStateException> {
stats(
total = 1,
count = 2
)
}
}
@Test
fun percent() {
assertEquals(
0,
stats(
total = 0,
count = 0
).percent
)
assertEquals(
0,
stats(
total = 10,
count = 0
).percent
)
assertEquals(
20,
stats(
total = 10,
count = 2
).percent
)
assertEquals(
100,
stats(
total = 10,
count = 10
).percent
)
}
private fun stats(
total: Int,
count: Int
) = IndicatorStats(
total = total,
count = count,
min = null,
avg = null,
max = null,
minCount = 0,
maxCount = 0
)
} | mit | 7e708b779e99dec9ffa117e1715cdad7 | 21 | 55 | 0.355476 | 5.967857 | false | true | false | false |
lambdasoup/watchlater | app/src/androidTest/java/com/lambdasoup/watchlater/test/CucumberTest.kt | 1 | 11168 | /*
* 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.test
import android.accounts.Account
import android.accounts.AccountManager
import android.accounts.AccountManagerFuture
import android.app.Activity
import android.app.Instrumentation
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.content.pm.verify.domain.DomainVerificationManager
import android.content.pm.verify.domain.DomainVerificationUserState
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createEmptyComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction
import androidx.test.espresso.intent.matcher.IntentMatchers.hasData
import androidx.test.espresso.intent.matcher.IntentMatchers.hasPackage
import com.lambdasoup.tea.testing.TeaIdlingResource
import com.lambdasoup.watchlater.R
import com.lambdasoup.watchlater.onNodeWithTextRes
import com.lambdasoup.watchlater.ui.add.AddActivity
import com.lambdasoup.watchlater.ui.launcher.LauncherActivity
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.cucumber.java.After
import io.cucumber.java.Before
import io.cucumber.java.en.Given
import io.cucumber.java.en.Then
import io.cucumber.java.en.When
import io.cucumber.junit.CucumberOptions
import io.cucumber.junit.WithJunitRule
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.hamcrest.Matchers.allOf
import org.junit.Rule
import java.util.concurrent.TimeUnit
@CucumberOptions(
features = ["features"],
strict = true,
name = [".*"],
)
@WithJunitRule
class CucumberTest {
@get:Rule
val rule = createEmptyComposeRule()
private var scenario: ActivityScenario<ComponentActivity>? = null
private val packageManager: PackageManager = com.lambdasoup.watchlater.packageManager
private val domainVerificationManager: DomainVerificationManager =
com.lambdasoup.watchlater.domainVerificationManager
private val accountManager = com.lambdasoup.watchlater.accountManager
private val sharedPreferences = com.lambdasoup.watchlater.sharedPreferences
private val server = MockWebServer()
private val idlingResource = TeaIdlingResource()
@Before
fun before() {
server.start(port = 8080)
server.dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest) =
when (request.path) {
"/videos?part=snippet,contentDetails&maxResults=1&id=dGFSjKuJfrI" ->
MockResponse()
.setResponseCode(200)
.setBody(VIDEO_INFO_JSON)
else -> MockResponse()
.setResponseCode(404)
.setBody("unhandled path + ${request.path}")
}
}
Intents.init()
Intents.intending(hasAction(Intent.ACTION_VIEW))
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, Intent()))
whenever(domainVerificationManager.getDomainVerificationUserState(any())).thenReturn(
mock()
)
rule.registerIdlingResource(idlingResource.composeIdlingResource)
}
@After
fun after() {
rule.unregisterIdlingResource(idlingResource.composeIdlingResource)
Intents.release()
server.shutdown()
}
@When("I open the Launcher")
fun openLauncher() {
val intent = Intent(
ApplicationProvider.getApplicationContext(),
LauncherActivity::class.java
)
scenario = ActivityScenario.launch(intent)
}
@When("click on the demo button")
fun clickDemoButton() {
rule.onNodeWithTextRes(R.string.launcher_example_button, ignoreCase = true)
.performClick()
}
@Given("Watch Later is not set as default")
fun watchLaterIsNotDefault() {
whenever(packageManager.resolveActivity(any(), eq(PackageManager.MATCH_DEFAULT_ONLY)))
.thenReturn(null)
}
@Given("Watch Later is set as default")
fun watchLaterIsDefault() {
val resolveInfo: ResolveInfo = ResolveInfo().apply {
activityInfo = ActivityInfo().apply {
name = "com.lambdasoup.watchlater.ui.add.AddActivity"
}
}
whenever(packageManager.resolveActivity(any(), eq(PackageManager.MATCH_DEFAULT_ONLY)))
.thenReturn(resolveInfo)
}
@Given("Watch Later is not missing any hostname verifications")
fun isNotMissingVerifications() {
val state: DomainVerificationUserState = mock()
whenever(state.hostToStateMap).thenReturn(
mapOf(
"test.domain.1" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
"test.domain.2" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
"test.domain.3" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
)
)
whenever(domainVerificationManager.getDomainVerificationUserState(any()))
.thenReturn(state)
}
@Given("Watch Later is missing some hostname verifications")
fun isMissingVerifications() {
val state: DomainVerificationUserState = mock()
whenever(state.hostToStateMap).thenReturn(
mapOf(
"test.domain.1" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
"test.domain.2" to DomainVerificationUserState.DOMAIN_STATE_NONE,
"test.domain.3" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
)
)
whenever(domainVerificationManager.getDomainVerificationUserState(any()))
.thenReturn(state)
}
@Then("I see the Launcher")
fun launcherIsOpen() {
rule.onNodeWithTextRes(R.string.launcher_example_title)
.assertIsDisplayed()
}
@Then("I see the setup instructions")
fun setupInstructionsVisible() {
rule.onNodeWithTextRes(R.string.launcher_action_title)
.assertIsDisplayed()
}
@Then("I do not see the setup instructions")
fun setupInstructionsNotVisible() {
rule.onNodeWithTextRes(R.string.launcher_action_title)
.assertDoesNotExist()
}
@Then("the video is opened")
fun videoIsOpened() {
Intents.intended(allOf(hasData("https://www.youtube.com/watch?v=dGFSjKuJfrI")))
}
@Given("the Google account is set")
fun googleAccountSet() {
whenever(sharedPreferences.getString("pref_key_default_account_name", null))
.thenReturn("[email protected]")
val account = Account("[email protected]", "com.google")
whenever(accountManager.getAccountsByType("com.google"))
.thenReturn(
arrayOf(account)
)
whenever(
accountManager.getAuthToken(
account,
"oauth2:https://www.googleapis.com/auth/youtube",
null,
false,
null,
null
)
)
.thenReturn(object : AccountManagerFuture<Bundle> {
override fun cancel(p0: Boolean) = throw NotImplementedError()
override fun isCancelled() = throw NotImplementedError()
override fun isDone() = throw NotImplementedError()
override fun getResult() = Bundle().apply {
putString(AccountManager.KEY_AUTHTOKEN, "test-auth-token")
}
override fun getResult(p0: Long, p1: TimeUnit?) = throw NotImplementedError()
})
}
@Given("a playlist has been selected")
fun playlistSet() {
whenever(sharedPreferences.getString("playlist-id", null))
.thenReturn("test-playlist-id")
whenever(sharedPreferences.getString("playlist-title", null))
.thenReturn("Test playlist title")
}
@When("I open Watch Later via a YouTube URL")
fun watchLaterOpensFromUrl() {
val intent = Intent(
ApplicationProvider.getApplicationContext(),
AddActivity::class.java
)
intent.action = Intent.ACTION_VIEW
intent.data = Uri.parse("https://www.youtube.com/watch?v=dGFSjKuJfrI")
scenario = ActivityScenario.launch(intent)
}
@When("the user clicks on 'Watch now'")
fun userClicksWatchNow() {
rule.onNodeWithTextRes(R.string.action_watchnow, ignoreCase = true)
.performClick()
}
@Then("the YouTube app is opened with the video URL")
fun youtubeOpened() {
Intents.intended(
allOf(
hasData("https://www.youtube.com/watch?v=dGFSjKuJfrI"),
hasAction(Intent.ACTION_VIEW),
hasPackage("com.google.android.youtube"),
)
)
}
@Then("I see the video info")
fun videoInfoDisplayed() {
rule.onNodeWithText("Test video title")
.assertIsDisplayed()
}
companion object {
const val VIDEO_INFO_JSON = """
{
"items": [
{
"id": "dGFSjKuJfrI",
"snippet": {
"title": "Test video title",
"description": "Test video description",
"thumbnails": {
"medium": {
"url": "http://localhost:8080/test-thumbnail"
}
}
},
"contentDetails": {
"duration": "1m35s"
}
}
]
}
"""
}
}
| gpl-3.0 | b5b98d72a2aed43e58da44d063c94942 | 34.909968 | 94 | 0.64461 | 4.915493 | false | true | false | false |
usbpc102/usbBot | src/main/kotlin/usbbot/config/DBMusicQueue.kt | 1 | 5645 | package usbbot.config
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.newFixedThreadPoolContext
import org.apache.commons.collections4.CollectionUtils
import org.apache.commons.collections4.queue.CircularFifoQueue
import org.apache.commons.dbutils.ResultSetHandler
import usbbot.modules.music.Music
import usbbot.modules.music.MyData
import util.getLogger
import java.sql.Timestamp
import java.util.*
import kotlin.collections.ArrayList
data class DBMusicQueueEntry(val id: Int, val forGuild: Long, val youtubeId: String, val requetedBy: Long, val addedAt: Timestamp) {
fun getAudioTrack() : AudioTrack? {
var retTrack : AudioTrack? = null
Music.playerManager.loadItem(youtubeId, object : AudioLoadResultHandler {
override fun loadFailed(exception: FriendlyException) {
DBMusicQueue.logger.warn("This is awkward... there was a video in the DB that won't load: $youtubeId")
}
override fun trackLoaded(track: AudioTrack) {
retTrack = track
}
override fun noMatches() {
DBMusicQueue.logger.warn("This is awkward... there was a video in the DB that no longer exists: $youtubeId")
}
override fun playlistLoaded(playlist: AudioPlaylist) {
throw IllegalStateException("There should never be a playlist loaded from the database backend!")
}
}).get()
retTrack?.userData = MyData(requetedBy, id, forGuild, youtubeId)
return retTrack
}
}
fun getSongsFromDB(guildID: Long, limit: Int, offset: Int = 0) : List<DBMusicQueueEntry> =
DatabaseConnection.queryRunner
.query("SELECT * FROM music_queue WHERE forGuild = ? ORDER BY addedAt ASC LIMIT ? OFFSET ?",
DBMusicQueue.songDBEntryCreator,
guildID, limit, offset)
fun getMusicQueueForGuild(guildID: Long) : DBMusicQueue {
val result = getSongsFromDB(guildID, 10)
val queue = CircularFifoQueue<AudioTrack>(10)
result.forEach {
val tmp = it.getAudioTrack()
if (tmp != null) {
queue.add(tmp)
} else {
DatabaseConnection.queryRunner.update("DELETE FROM music_queue WHERE id = ?", it.id)
}
}
val rsh = ResultSetHandler {
if (it.next()) it.getInt(1)
else 0
}
val size = DatabaseConnection.queryRunner.query("SELECT COUNT(*) FROM music_queue WHERE forGuild = ?",
rsh,
guildID)
return DBMusicQueue(guildID, queue, size)
}
class DBMusicQueue(val guildID: Long, val queue : Queue<AudioTrack>, var size: Int) {
companion object {
val logger = DBMusicQueue.getLogger()
val songDBEntryCreator = ResultSetHandler <List<DBMusicQueueEntry>> {
val output = mutableListOf<DBMusicQueueEntry>()
while (it.next()) {
output.add(DBMusicQueueEntry(
it.getInt("id"),
it.getLong("forGuild"),
it.getString("youtubeId"),
it.getLong("requestedBy"),
it.getTimestamp("addedAt")))
}
output
}
val musicQueueWorker = newFixedThreadPoolContext(2, "Music Queue Worker")
}
fun removeFromDB(track: AudioTrack) = launch(musicQueueWorker) {
DatabaseConnection.queryRunner.update("DELETE FROM music_queue WHERE id = ?", (track.userData as MyData).id)
}
fun add(track: AudioTrack) {
val data = (track.userData as MyData)
DatabaseConnection.queryRunner
.update("INSERT INTO music_queue (forGuild, youtubeId, requestedBy) VALUES (?, ?, ?)",
data.forGuild, data.youtubeId, data.requestedBy)
synchronized(size) {
if (size < 10) {
synchronized(queue) {
val musicQueueEntry = DatabaseConnection.queryRunner
.query("SELECT * FROM music_queue WHERE forGuild = ? AND youtubeId = ? AND requestedBy = ?",
DBMusicQueue.songDBEntryCreator,
data.forGuild, data.youtubeId, data.requestedBy)
(track.userData as MyData).id = musicQueueEntry.first().id
queue.add(track)
}
}
size++
}
}
fun hasNext() : Boolean = queue.isNotEmpty()
fun getNext() : AudioTrack? {
val out = synchronized(queue) {
queue.poll()
}
removeFromDB(out)
if (queue.size < 5) {
launch(musicQueueWorker) {
val size = synchronized(queue) {
queue.size
}
val songs = getSongsFromDB(guildID, 10 - size, size)
songs.forEach {
val audioTrack = it.getAudioTrack()
if (audioTrack != null) {
synchronized(queue) {
if (!queue.contains(audioTrack)) {
queue.add(audioTrack)
}
}
}
}
}
}
synchronized(size) {
size--
}
return out
}
} | mit | 33000dc1e5831d96351ebe52375fbb3d | 36.390728 | 132 | 0.583171 | 4.96482 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/language/InterfaceTypeDefinition.kt | 1 | 1039 | package graphql.language
import java.util.ArrayList
class InterfaceTypeDefinition(override val name: String) : AbstractNode(), TypeDefinition {
val fieldDefinitions: MutableList<FieldDefinition> = ArrayList()
val directives: MutableList<Directive> = ArrayList()
override val children: List<Node>
get() {
val result = ArrayList<Node>()
result.addAll(fieldDefinitions)
result.addAll(directives)
return result
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
val that = node as InterfaceTypeDefinition
if (name != that.name) {
return false
}
return true
}
override fun toString(): String {
return "InterfaceTypeDefinition{" +
"name='" + name + '\'' +
", fieldDefinitions=" + fieldDefinitions +
", directives=" + directives +
'}'
}
}
| mit | d2ef453a7020114c6d133bce16af810c | 26.342105 | 91 | 0.582291 | 5.247475 | false | false | false | false |
soywiz/korge | korge-swf/src/commonMain/kotlin/com/soywiz/korfl/as3swf/consts.kt | 1 | 5270 | package com.soywiz.korfl.as3swf
object ActionValueType {
val STRING: Int = 0
val FLOAT: Int = 1
val NIL: Int = 2
val UNDEFINED: Int = 3
val REGISTER: Int = 4
val BOOLEAN: Int = 5
val DOUBLE: Int = 6
val INTEGER: Int = 7
val CONSTANT_8: Int = 8
val CONSTANT_16: Int = 9
fun toString(bitmapFormat: Int) = when (bitmapFormat) {
STRING -> "string"
FLOAT -> "float"
NIL -> "null"
UNDEFINED -> "undefined"
REGISTER -> "register"
BOOLEAN -> "boolean"
DOUBLE -> "double"
INTEGER -> "integer"
CONSTANT_8 -> "constant8"
CONSTANT_16 -> "constant16"
else -> "unknown"
}
}
enum class BitmapFormat(val id: Int) {
BIT_8(3), BIT_15(4), BIT_24_32(5), UNKNOWN(-1);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: UNKNOWN
}
}
object BitmapType {
const val JPEG = 1
const val GIF89A = 2
const val PNG = 3
fun toString(bitmapFormat: Int): String = when (bitmapFormat) {
JPEG -> "JPEG"
GIF89A -> "GIF89a"
PNG -> "PNG"
else -> "unknown"
}
}
object BlendMode {
const val NORMAL_0 = 0
const val NORMAL_1 = 1
const val LAYER = 2
const val MULTIPLY = 3
const val SCREEN = 4
const val LIGHTEN = 5
const val DARKEN = 6
const val DIFFERENCE = 7
const val ADD = 8
const val SUBTRACT = 9
const val INVERT = 10
const val ALPHA = 11
const val ERASE = 12
const val OVERLAY = 13
const val HARDLIGHT = 14
fun toString(blendMode: Int): String = when (blendMode) {
NORMAL_0, NORMAL_1 -> "normal"
LAYER -> "layer"
MULTIPLY -> "multiply"
SCREEN -> "screen"
LIGHTEN -> "lighten"
DARKEN -> "darken"
DIFFERENCE -> "difference"
ADD -> "add"
SUBTRACT -> "subtract"
INVERT -> "invert"
ALPHA -> "alpha"
ERASE -> "erase"
OVERLAY -> "overlay"
HARDLIGHT -> "hardlight"
else -> "unknown"
}
}
object CSMTableHint {
const val THIN = 0
const val MEDIUM = 1
const val THICK = 2
fun toString(csmTableHint: Int): String = when (csmTableHint) {
THIN -> "thin"
MEDIUM -> "medium"
THICK -> "thick"
else -> "unknown"
}
}
enum class GradientInterpolationMode(val id: Int) {
NORMAL(0), LINEAR(1);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: NORMAL
}
}
enum class GradientSpreadMode(val id: Int) {
PAD(0), REFLECT(1), REPEAT(2);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: PAD
}
}
enum class ScaleMode(val id: Int) {
NONE(0), HORIZONTAL(1), VERTICAL(2), NORMAL(3);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: NORMAL
}
}
enum class LineCapsStyle(val id: Int) {
ROUND(0), NO(1), SQUARE(2);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: LineCapsStyle.ROUND
}
}
object LineJointStyle {
const val ROUND = 0
const val BEVEL = 1
const val MITER = 2
fun toString(lineJointStyle: Int) = when (lineJointStyle) {
ROUND -> "round"
BEVEL -> "bevel"
MITER -> "miter"
else -> "null"
}
}
object SoundCompression {
const val UNCOMPRESSED_NATIVE_ENDIAN = 0
const val ADPCM = 1
const val MP3 = 2
const val UNCOMPRESSED_LITTLE_ENDIAN = 3
const val NELLYMOSER_16_KHZ = 4
const val NELLYMOSER_8_KHZ = 5
const val NELLYMOSER = 6
const val SPEEX = 11
fun toString(soundCompression: Int): String {
return when (soundCompression) {
UNCOMPRESSED_NATIVE_ENDIAN -> "Uncompressed Native Endian"
ADPCM -> "ADPCM"
MP3 -> "MP3"
UNCOMPRESSED_LITTLE_ENDIAN -> "Uncompressed Little Endian"
NELLYMOSER_16_KHZ -> "Nellymoser 16kHz"
NELLYMOSER_8_KHZ -> "Nellymoser 8kHz"
NELLYMOSER -> "Nellymoser"
SPEEX -> "Speex"
else -> return "unknown"
}
}
}
object SoundRate {
const val KHZ_5 = 0
const val KHZ_11 = 1
const val KHZ_22 = 2
const val KHZ_44 = 3
fun toString(soundRate: Int): String {
return when (soundRate) {
KHZ_5 -> "5.5kHz"
KHZ_11 -> "11kHz"
KHZ_22 -> "22kHz"
KHZ_44 -> "44kHz"
else -> "unknown"
}
}
}
object SoundSize {
const val BIT_8 = 0
const val BIT_16 = 1
fun toString(soundSize: Int): String {
return when (soundSize) {
BIT_8 -> "8bit"
BIT_16 -> "16bit"
else -> "unknown"
}
}
}
object SoundType {
const val MONO = 0
const val STEREO = 1
fun toString(soundType: Int): String {
return when (soundType) {
MONO -> "mono"
STEREO -> "stereo"
else -> "unknown"
}
}
}
object VideoCodecID {
const val H263 = 2
const val SCREEN = 3
const val VP6 = 4
const val VP6ALPHA = 5
const val SCREENV2 = 6
fun toString(codecId: Int): String {
return when (codecId) {
H263 -> "H.263"
SCREEN -> "Screen Video"
VP6 -> "VP6"
VP6ALPHA -> "VP6 With Alpha"
SCREENV2 -> "Screen Video V2"
else -> "unknown"
}
}
}
object VideoDeblockingType {
const val VIDEOPACKET = 0
const val OFF = 1
const val LEVEL1 = 2
const val LEVEL2 = 3
const val LEVEL3 = 4
const val LEVEL4 = 5
fun toString(deblockingType: Int): String {
return when (deblockingType) {
VIDEOPACKET -> "videopacket"
OFF -> "off"
LEVEL1 -> "level 1"
LEVEL2 -> "level 2"
LEVEL3 -> "level 3"
LEVEL4 -> "level 4"
else -> "unknown"
}
}
}
| apache-2.0 | 208c218d7709baffb11e4caa0b751df7 | 19.585938 | 68 | 0.63833 | 2.760608 | false | false | false | false |
cashapp/sqldelight | sample/common/src/iosMain/kotlin/com/example/sqldelight/hockey/data/Db.kt | 1 | 857 | package com.example.sqldelight.hockey.data
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.native.NativeSqliteDriver
import com.example.sqldelight.hockey.HockeyDb
import kotlin.native.concurrent.AtomicReference
import kotlin.native.concurrent.freeze
object Db {
private val driverRef = AtomicReference<SqlDriver?>(null)
private val dbRef = AtomicReference<HockeyDb?>(null)
internal fun dbSetup(driver: SqlDriver) {
val db = createQueryWrapper(driver)
driverRef.value = driver.freeze()
dbRef.value = db.freeze()
}
internal fun dbClear() {
driverRef.value!!.close()
dbRef.value = null
driverRef.value = null
}
// Called from Swift
@Suppress("unused")
fun defaultDriver() {
Db.dbSetup(NativeSqliteDriver(Schema, "sampledb"))
}
val instance: HockeyDb
get() = dbRef.value!!
}
| apache-2.0 | 850a6c3fe1f3985efaa1111bd5fa2e50 | 24.969697 | 59 | 0.736289 | 3.877828 | false | false | false | false |
apixandru/intellij-community | platform/script-debugger/protocol/protocol-reader/src/ExistingSubtypeAspect.kt | 28 | 1169 | package org.jetbrains.protocolReader
private val BASE_VALUE_PREFIX = "baseMessage"
internal class ExistingSubtypeAspect(private val jsonSuperClass: TypeRef<*>) {
private var subtypeCaster: SubtypeCaster? = null
fun setSubtypeCaster(subtypeCaster: SubtypeCaster) {
this.subtypeCaster = subtypeCaster
}
fun writeGetSuperMethodJava(out: TextOutput) {
out.newLine().append("override fun getBase() = ").append(BASE_VALUE_PREFIX)
}
fun writeSuperFieldJava(out: TextOutput) {
out.append(", private val ").append(BASE_VALUE_PREFIX).append(": ").append(jsonSuperClass.type!!.typeClass.canonicalName)
}
fun writeParseMethod(scope: ClassScope, out: TextOutput) {
out.newLine().append("companion object").block {
out.append("fun parse").append('(').append(JSON_READER_PARAMETER_DEF).append(", name: String?").append(") = ")
jsonSuperClass.type!!.writeInstantiateCode(scope, out)
out.append('(').append(READER_NAME).append(", name)").append('.')
subtypeCaster!!.writeJava(out)
}
out.newLine()
}
fun writeInstantiateCode(className: String, out: TextOutput) {
out.append(className).append(".parse")
}
}
| apache-2.0 | 73b7f20878488520dc8ff6b155b0a914 | 34.424242 | 125 | 0.708298 | 4.205036 | false | false | false | false |
cashapp/sqldelight | sqldelight-idea-plugin/src/test/kotlin/app/cash/sqldelight/intellij/gotodeclaration/GoToDeclarationHandlerTest.kt | 1 | 1813 | package app.cash.sqldelight.intellij.gotodeclaration
import app.cash.sqldelight.intellij.SqlDelightGotoDeclarationHandler
import app.cash.sqldelight.intellij.SqlDelightProjectTestCase
import com.alecstrong.sql.psi.core.psi.SqlIdentifier
import com.google.common.truth.Truth.assertThat
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class GoToDeclarationHandlerTest : SqlDelightProjectTestCase() {
private val goToDeclarationHandler = SqlDelightGotoDeclarationHandler()
fun testMethodGoesToIdentifier() {
myFixture.openFileInEditor(
tempRoot.findFileByRelativePath("src/main/java/com/example/SampleClass.java")!!,
)
val sourceElement = searchForElement<PsiElement>("someQuery").single()
val elements = goToDeclarationHandler.getGotoDeclarationTargets(sourceElement, 0, editor)
myFixture.openFileInEditor(
tempRoot.findFileByRelativePath("src/main/sqldelight/com/example/Main.sq")!!,
)
val offset = file.text.indexOf("someQuery")
assertThat(elements).asList().containsExactly(
file.findElementAt(offset)!!.getStrictParentOfType<SqlIdentifier>(),
)
}
fun testMethodGoesToIdentifierFromKotlin() {
myFixture.openFileInEditor(
tempRoot.findFileByRelativePath("src/main/kotlin/com/example/KotlinClass.kt")!!,
)
val sourceElement = searchForElement<PsiElement>("someQuery").single()
val elements = goToDeclarationHandler.getGotoDeclarationTargets(sourceElement, 0, editor)
myFixture.openFileInEditor(
tempRoot.findFileByRelativePath("src/main/sqldelight/com/example/Main.sq")!!,
)
val offset = file.text.indexOf("someQuery")
assertThat(elements).asList().containsExactly(
file.findElementAt(offset)!!.getStrictParentOfType<SqlIdentifier>(),
)
}
}
| apache-2.0 | 1c0ebe6c9b65e61ff58884b1040f6d86 | 40.204545 | 93 | 0.778268 | 4.86059 | false | true | false | false |
rhdunn/marklogic-intellij-plugin | src/main/java/uk/co/reecedunn/intellij/plugin/core/xml/NodeList.kt | 1 | 1024 | /*
* Copyright (C) 2017 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.core.xml
import org.w3c.dom.Node
import org.w3c.dom.NodeList
private class NodeListIterator(val nodes: NodeList): Iterator<Node> {
private var current: Int = 0
override fun hasNext(): Boolean =
current != nodes.length
override fun next(): Node =
nodes.item(current++)
}
fun NodeList.asSequence(): Sequence<Node> =
NodeListIterator(this).asSequence()
| apache-2.0 | a270d4e243f7f7c935ca2a30216c68ab | 31 | 75 | 0.723633 | 3.984436 | false | false | false | false |
ianmcxa/vortaro | app/src/main/java/org/mcxa/vortaro/MainActivity.kt | 1 | 2400 | package org.mcxa.vortaro
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
// tag for log methods
val TAG = "Main_Activity"
var dbHelper: DatabaseHelper? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// set up the action bar
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
dbHelper = DatabaseHelper(this)
word_view.apply{
adapter = WordAdapter()
layoutManager = LinearLayoutManager(this@MainActivity)
}
search_text.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val w = word_view.adapter as WordAdapter
if (!s.isNullOrEmpty()) {
dbHelper?.search(s.toString().toLowerCase(), w)
} else {
w.words.beginBatchedUpdates()
// remove items at end, to avoid unnecessary array shifting
while (w.words.size() > 0) {
w.words.removeItemAt(w.words.size() - 1)
}
w.words.endBatchedUpdates()
}
}
override fun afterTextChanged(s: Editable?) {}
})
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.option_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.about -> {
val i = Intent(this, AboutActivity::class.java)
startActivity(i) // brings up the second activity
return true
}
}
return false
}
override fun onDestroy() {
dbHelper?.close()
super.onDestroy()
}
} | apache-2.0 | b154bf16e3722150a2c869c1e093db33 | 31.013333 | 99 | 0.605417 | 4.989605 | false | false | false | false |
slartus/4pdaClient-plus | app/src/main/java/org/softeg/slartus/forpdaplus/fragments/qms/QmsNewThreadFragment.kt | 1 | 4129 | package org.softeg.slartus.forpdaplus.fragments.qms
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import org.softeg.slartus.forpdaplus.MainActivity
import org.softeg.slartus.forpdaplus.R
import org.softeg.slartus.forpdaplus.fragments.BaseBrickContainerFragment
import org.softeg.slartus.forpdaplus.tabs.TabsManager
import org.softeg.slartus.forpdaplus.qms.impl.screens.newthread.QmsNewThreadFragment as FeatureFragment
class QmsNewThreadFragment : BaseBrickContainerFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitleByNick(null)
childFragmentManager.setFragmentResultListener(
org.softeg.slartus.forpdaplus.qms.impl.screens.newthread.QmsNewThreadFragment.ARG_CONTACT_NICK,
this
) { _, bundle ->
val nick = bundle.getString(org.softeg.slartus.forpdaplus.qms.impl.screens.newthread.QmsNewThreadFragment.ARG_CONTACT_NICK)
setTitleByNick(nick)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setArrow()
supportActionBar.setDisplayHomeAsUpEnabled(true)
supportActionBar.setHomeButtonEnabled(true)
}
private fun setTitleByNick(contactNick: String?) {
val title = if (contactNick == null) {
getString(R.string.qms_title_new_thread, "QMS")
} else {
getString(R.string.qms_title_new_thread, contactNick)
}
setTitle(title)
TabsManager.instance.getTabByTag(tag)?.title = title
mainActivity.notifyTabAdapter()
}
override fun closeTab(): Boolean {
return false
}
override fun getFragmentInstance(): Fragment {
val args = arguments
return FeatureFragment().apply {
this.arguments = args
}
}
override fun onResume() {
super.onResume()
setArrow()
// if (mPopupPanelView != null)
// mPopupPanelView.resume();
}
companion object {
// @Override
// public void hidePopupWindows() {
// super.hidePopupWindows();
// mPopupPanelView.hidePopupWindow();
// }
fun showUserNewThread(userId: String?, userNick: String?) {
val args = bundleOf(org.softeg.slartus.forpdaplus.qms.impl.screens.newthread.QmsNewThreadFragment.ARG_CONTACT_ID to userId)
val fragment = QmsNewThreadFragment().apply {
arguments = args
}
MainActivity.addTab(userNick, fragment)
}
// private val mPopupPanelView: PopupPanelView? = null
// override fun onPause() {
// super.onPause()
// mPopupPanelView?.pause()
// }
//
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// if (mPopupPanelView == null)
// mPopupPanelView = new PopupPanelView(PopupPanelView.VIEW_FLAG_EMOTICS | PopupPanelView.VIEW_FLAG_BBCODES);
// mPopupPanelView.createView(LayoutInflater.from(getContext()), (ImageButton) findViewById(R.id.advanced_button), message);
// mPopupPanelView.activityCreated(getMainActivity(), view);
// return view;
// }
//
// @Override
// public void onDestroy() {
// if (mPopupPanelView != null) {
// mPopupPanelView.destroy();
// mPopupPanelView = null;
// }
// super.onDestroy();
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home) {
// onBackPressed();
// return true;
// }
//
// return true;
// }
//
}
} | apache-2.0 | 5742301d9fe7544a177c0462a758340b | 33.416667 | 139 | 0.603294 | 4.823598 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/reflect/ImportReflectionCache.kt | 1 | 6501 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.reflect
import io.github.classgraph.ClassGraph
import org.nd4j.common.config.ND4JSystemProperties.INIT_IMPORT_REFLECTION_CACHE
import org.nd4j.samediff.frameworkimport.hooks.NodePreProcessorHook
import org.nd4j.samediff.frameworkimport.hooks.PostImportHook
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.NodePreProcessor
import org.nd4j.samediff.frameworkimport.hooks.annotations.PostHookRule
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.shade.guava.collect.Table
import org.nd4j.shade.guava.collect.TreeBasedTable
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
object ImportReflectionCache {
//all relevant node names relevant for
val preProcessRuleImplementationsByNode: Table<String,String,MutableList<PreImportHook>> = TreeBasedTable.create()
val postProcessRuleImplementationsByNode: Table<String,String,MutableList<PostImportHook>> = TreeBasedTable.create()
//all relevant op names hook should be useful for
val preProcessRuleImplementationsByOp: Table<String,String,MutableList<PreImportHook>> = TreeBasedTable.create()
val postProcessRuleImplementationsByOp: Table<String,String,MutableList<PostImportHook>> = TreeBasedTable.create()
val nodePreProcessorRuleImplementationByOp: Table<String,String,MutableList<NodePreProcessorHook<GeneratedMessageV3,
GeneratedMessageV3,GeneratedMessageV3,GeneratedMessageV3,ProtocolMessageEnum>>> = TreeBasedTable.create()
init {
if(java.lang.Boolean.parseBoolean(System.getProperty(INIT_IMPORT_REFLECTION_CACHE,"true"))) {
load()
}
}
@JvmStatic
fun load() {
val scannedClasses = ClassGraphHolder.scannedClasses
scannedClasses.getClassesImplementing(PreImportHook::class.java.name).filter { input -> input.hasAnnotation(PreHookRule::class.java.name) }.forEach {
val instance = Class.forName(it.name).getDeclaredConstructor().newInstance() as PreImportHook
val rule = it.annotationInfo.first { input -> input.name == PreHookRule::class.java.name }
val nodeNames = rule.parameterValues["nodeNames"].value as Array<String>
val frameworkName = rule.parameterValues["frameworkName"].value as String
nodeNames.forEach { nodeName ->
if(!preProcessRuleImplementationsByNode.contains(frameworkName,nodeName)) {
preProcessRuleImplementationsByNode.put(frameworkName,nodeName,ArrayList())
}
preProcessRuleImplementationsByNode.get(frameworkName,nodeName)!!.add(instance)
}
val opNames = rule.parameterValues["opNames"].value as Array<String>
opNames.forEach { opName ->
if(!preProcessRuleImplementationsByOp.contains(frameworkName,opName)) {
preProcessRuleImplementationsByOp.put(frameworkName,opName,ArrayList())
}
preProcessRuleImplementationsByOp.get(frameworkName,opName)!!.add(instance)
}
}
scannedClasses.getClassesImplementing(PostImportHook::class.java.name).filter { input -> input.hasAnnotation(PostHookRule::class.java.name) }.forEach {
val instance = Class.forName(it.name).getDeclaredConstructor().newInstance() as PostImportHook
val rule = it.annotationInfo.first { input -> input.name == PostHookRule::class.java.name }
val nodeNames = rule.parameterValues["nodeNames"].value as Array<String>
val frameworkName = rule.parameterValues["frameworkName"].value as String
nodeNames.forEach { nodeName ->
if(!postProcessRuleImplementationsByNode.contains(frameworkName,nodeName)) {
postProcessRuleImplementationsByNode.put(frameworkName,nodeName,ArrayList())
}
postProcessRuleImplementationsByNode.get(frameworkName,nodeName)!!.add(instance)
}
val opNames = rule.parameterValues["opNames"].value as Array<String>
opNames.forEach { opName ->
if(!postProcessRuleImplementationsByOp.contains(frameworkName,opName)) {
postProcessRuleImplementationsByOp.put(frameworkName,opName,ArrayList())
}
postProcessRuleImplementationsByOp.get(frameworkName,opName)!!.add(instance)
}
}
scannedClasses.getClassesImplementing(NodePreProcessorHook::class.java.name).filter { input -> input.hasAnnotation(NodePreProcessor::class.java.name) }.forEach {
val instance = Class.forName(it.name).getDeclaredConstructor().newInstance() as NodePreProcessorHook<GeneratedMessageV3,GeneratedMessageV3,GeneratedMessageV3,GeneratedMessageV3,ProtocolMessageEnum>
val rule = it.annotationInfo.first { input -> input.name == NodePreProcessor::class.java.name }
val nodeTypes = rule.parameterValues["nodeTypes"].value as Array<String>
val frameworkName = rule.parameterValues["frameworkName"].value as String
nodeTypes.forEach { nodeType ->
if(!nodePreProcessorRuleImplementationByOp.contains(frameworkName,nodeType)) {
nodePreProcessorRuleImplementationByOp.put(frameworkName,nodeType,ArrayList())
}
nodePreProcessorRuleImplementationByOp.get(frameworkName,nodeType)!!.add(instance)
}
}
}
}
| apache-2.0 | c0aebf096cdfce75d4c49e40cc2e399b | 50.188976 | 209 | 0.6982 | 5.135071 | false | false | false | false |
AndroidX/androidx | compose/animation/animation/samples/src/main/java/androidx/compose/animation/samples/AnimationModifierSample.kt | 3 | 2160 | /*
* 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.animation.samples
import androidx.annotation.Sampled
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Sampled
@Composable
fun AnimateContent() {
val shortText = "Hi"
val longText = "Very long text\nthat spans across\nmultiple lines"
var short by remember { mutableStateOf(true) }
Box(
modifier = Modifier
.background(
Color.Blue,
RoundedCornerShape(15.dp)
)
.clickable { short = !short }
.padding(20.dp)
.wrapContentSize()
.animateContentSize()
) {
Text(
if (short) {
shortText
} else {
longText
},
style = LocalTextStyle.current.copy(color = Color.White)
)
}
}
| apache-2.0 | f1805be07f3d81678150d75362560126 | 32.75 | 75 | 0.713426 | 4.585987 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/notifications/service/NotificationsService.kt | 2 | 28273 | package abi42_0_0.expo.modules.notifications.service
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.os.ResultReceiver
import android.util.Log
import androidx.core.app.RemoteInput
import expo.modules.notifications.notifications.model.Notification
import expo.modules.notifications.notifications.model.NotificationAction
import expo.modules.notifications.notifications.model.NotificationBehavior
import expo.modules.notifications.notifications.model.NotificationCategory
import expo.modules.notifications.notifications.model.NotificationRequest
import expo.modules.notifications.notifications.model.NotificationResponse
import expo.modules.notifications.notifications.model.TextInputNotificationAction
import expo.modules.notifications.notifications.model.TextInputNotificationResponse
import abi42_0_0.expo.modules.notifications.service.delegates.ExpoCategoriesDelegate
import abi42_0_0.expo.modules.notifications.service.delegates.ExpoHandlingDelegate
import abi42_0_0.expo.modules.notifications.service.delegates.ExpoPresentationDelegate
import abi42_0_0.expo.modules.notifications.service.delegates.ExpoSchedulingDelegate
import abi42_0_0.expo.modules.notifications.service.interfaces.CategoriesDelegate
import abi42_0_0.expo.modules.notifications.service.interfaces.HandlingDelegate
import abi42_0_0.expo.modules.notifications.service.interfaces.PresentationDelegate
import abi42_0_0.expo.modules.notifications.service.interfaces.SchedulingDelegate
import kotlin.concurrent.thread
/**
* Subclass of FirebaseMessagingService, central dispatcher for all the notifications-related actions.
*/
open class NotificationsService : BroadcastReceiver() {
companion object {
const val NOTIFICATION_EVENT_ACTION = "expo.modules.notifications.NOTIFICATION_EVENT"
val SETUP_ACTIONS = listOf(
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_REBOOT,
Intent.ACTION_MY_PACKAGE_REPLACED,
"android.intent.action.QUICKBOOT_POWERON",
"com.htc.intent.action.QUICKBOOT_POWERON"
)
const val USER_TEXT_RESPONSE_KEY = "userTextResponse"
// Event types
private const val GET_ALL_DISPLAYED_TYPE = "getAllDisplayed"
private const val PRESENT_TYPE = "present"
private const val DISMISS_SELECTED_TYPE = "dismissSelected"
private const val DISMISS_ALL_TYPE = "dismissAll"
private const val RECEIVE_TYPE = "receive"
private const val RECEIVE_RESPONSE_TYPE = "receiveResponse"
private const val DROPPED_TYPE = "dropped"
private const val GET_CATEGORIES_TYPE = "getCategories"
private const val SET_CATEGORY_TYPE = "setCategory"
private const val DELETE_CATEGORY_TYPE = "deleteCategory"
private const val SCHEDULE_TYPE = "schedule"
private const val TRIGGER_TYPE = "trigger"
private const val GET_ALL_SCHEDULED_TYPE = "getAllScheduled"
private const val GET_SCHEDULED_TYPE = "getScheduled"
private const val REMOVE_SELECTED_TYPE = "removeSelected"
private const val REMOVE_ALL_TYPE = "removeAll"
// Messages parts
const val SUCCESS_CODE = 0
const val ERROR_CODE = 1
const val EVENT_TYPE_KEY = "type"
const val EXCEPTION_KEY = "exception"
const val RECEIVER_KEY = "receiver"
// Specific messages parts
const val NOTIFICATION_KEY = "notification"
const val NOTIFICATION_RESPONSE_KEY = "notificationResponse"
const val TEXT_INPUT_NOTIFICATION_RESPONSE_KEY = "textInputNotificationResponse"
const val SUCCEEDED_KEY = "succeeded"
const val IDENTIFIERS_KEY = "identifiers"
const val IDENTIFIER_KEY = "identifier"
const val NOTIFICATION_BEHAVIOR_KEY = "notificationBehavior"
const val NOTIFICATIONS_KEY = "notifications"
const val NOTIFICATION_CATEGORY_KEY = "notificationCategory"
const val NOTIFICATION_CATEGORIES_KEY = "notificationCategories"
const val NOTIFICATION_REQUEST_KEY = "notificationRequest"
const val NOTIFICATION_REQUESTS_KEY = "notificationRequests"
const val NOTIFICATION_ACTION_KEY = "notificationAction"
/**
* A helper function for dispatching a "fetch all displayed notifications" command to the service.
*
* @param context Context where to start the service.
* @param receiver A receiver to which send the notifications
*/
fun getAllPresented(context: Context, receiver: ResultReceiver? = null) {
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, getUriBuilder().build()).also {
it.putExtra(EVENT_TYPE_KEY, GET_ALL_DISPLAYED_TYPE)
it.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "present notification" command to the service.
*
* @param context Context where to start the service.
* @param notification Notification to present
* @param behavior Allowed notification behavior
* @param receiver A receiver to which send the result of presenting the notification
*/
fun present(context: Context, notification: Notification, behavior: NotificationBehavior? = null, receiver: ResultReceiver? = null) {
val data = getUriBuilderForIdentifier(notification.notificationRequest.identifier).appendPath("present").build()
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, data).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, PRESENT_TYPE)
intent.putExtra(NOTIFICATION_KEY, notification)
intent.putExtra(NOTIFICATION_BEHAVIOR_KEY, behavior)
intent.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "notification received" command to the service.
*
* @param context Context where to start the service.
* @param notification Notification received
* @param receiver Result receiver
*/
fun receive(context: Context, notification: Notification, receiver: ResultReceiver? = null) {
val data = getUriBuilderForIdentifier(notification.notificationRequest.identifier).appendPath("receive").build()
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, data).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, RECEIVE_TYPE)
intent.putExtra(NOTIFICATION_KEY, notification)
intent.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "dismiss notification" command to the service.
*
* @param context Context where to start the service.
* @param identifier Notification identifier
* @param receiver A receiver to which send the result of the action
*/
fun dismiss(context: Context, identifiers: Array<String>, receiver: ResultReceiver? = null) {
val data = getUriBuilder().appendPath("dismiss").build()
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, data).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, DISMISS_SELECTED_TYPE)
intent.putExtra(IDENTIFIERS_KEY, identifiers)
intent.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "dismiss notification" command to the service.
*
* @param context Context where to start the service.
* @param receiver A receiver to which send the result of the action
*/
fun dismissAll(context: Context, receiver: ResultReceiver? = null) {
val data = getUriBuilder().appendPath("dismiss").build()
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, data).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, DISMISS_ALL_TYPE)
intent.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "notifications dropped" command to the service.
*
* @param context Context where to start the service.
*/
fun handleDropped(context: Context) {
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, DROPPED_TYPE)
}
)
}
/**
* A helper function for dispatching a "get notification categories" command to the service.
*
* @param context Context where to start the service.
*/
fun getCategories(context: Context, receiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("categories")
.build()
).also {
it.putExtra(EVENT_TYPE_KEY, GET_CATEGORIES_TYPE)
it.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "set notification category" command to the service.
*
* @param context Context where to start the service.
* @param category Notification category to be set
*/
fun setCategory(context: Context, category: NotificationCategory, receiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("categories")
.appendPath(category.identifier)
.build()
).also {
it.putExtra(EVENT_TYPE_KEY, SET_CATEGORY_TYPE)
it.putExtra(NOTIFICATION_CATEGORY_KEY, category as Parcelable)
it.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "delete notification category" command to the service.
*
* @param context Context where to start the service.
* @param identifier Category Identifier
*/
fun deleteCategory(context: Context, identifier: String, receiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("categories")
.appendPath(identifier)
.build()
).also {
it.putExtra(EVENT_TYPE_KEY, DELETE_CATEGORY_TYPE)
it.putExtra(IDENTIFIER_KEY, identifier)
it.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* Fetches all scheduled notifications asynchronously.
*
* @param context Context this is being called from
* @param resultReceiver Receiver to be called with the results
*/
fun getAllScheduledNotifications(context: Context, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, GET_ALL_SCHEDULED_TYPE)
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Fetches scheduled notification asynchronously.
*
* @param context Context this is being called from
* @param identifier Identifier of the notification to be fetched
* @param resultReceiver Receiver to be called with the results
*/
fun getScheduledNotification(context: Context, identifier: String, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("scheduled")
.appendPath(identifier)
.build()
).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, GET_SCHEDULED_TYPE)
intent.putExtra(IDENTIFIER_KEY, identifier)
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Schedule notification asynchronously.
*
* @param context Context this is being called from
* @param notificationRequest Notification request to schedule
* @param resultReceiver Receiver to be called with the result
*/
fun schedule(context: Context, notificationRequest: NotificationRequest, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("scheduled")
.appendPath(notificationRequest.identifier)
.build()
).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, SCHEDULE_TYPE)
intent.putExtra(NOTIFICATION_REQUEST_KEY, notificationRequest as Parcelable)
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Cancel selected scheduled notification and remove it from the storage asynchronously.
*
* @param context Context this is being called from
* @param identifier Identifier of the notification to be removed
* @param resultReceiver Receiver to be called with the result
*/
fun removeScheduledNotification(context: Context, identifier: String, resultReceiver: ResultReceiver? = null) =
removeScheduledNotifications(context, listOf(identifier), resultReceiver)
/**
* Cancel selected scheduled notifications and remove them from the storage asynchronously.
*
* @param context Context this is being called from
* @param identifiers Identifiers of selected notifications to be removed
* @param resultReceiver Receiver to be called with the result
*/
fun removeScheduledNotifications(context: Context, identifiers: Collection<String>, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("scheduled")
.build()
).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, REMOVE_SELECTED_TYPE)
intent.putExtra(IDENTIFIERS_KEY, identifiers.toTypedArray())
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Cancel all scheduled notifications and remove them from the storage asynchronously.
*
* @param context Context this is being called from
* @param resultReceiver Receiver to be called with the result
*/
fun removeAllScheduledNotifications(context: Context, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, REMOVE_ALL_TYPE)
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Sends the intent to the best service to handle the {@link #NOTIFICATION_EVENT_ACTION} intent
* or handles the intent immediately if the service is already up.
*
* @param context Context where to start the service
* @param intent Intent to dispatch
*/
fun doWork(context: Context, intent: Intent) {
findDesignatedBroadcastReceiver(context, intent)?.let {
intent.component = ComponentName(it.packageName, it.name)
context.sendBroadcast(intent)
return
}
Log.e("expo-notifications", "No service capable of handling notifications found (intent = ${intent.action}). Ensure that you have configured your AndroidManifest.xml properly.")
}
protected fun getUriBuilder(): Uri.Builder {
return Uri.parse("expo-notifications://notifications/").buildUpon()
}
protected fun getUriBuilderForIdentifier(identifier: String): Uri.Builder {
return getUriBuilder().appendPath(identifier)
}
fun findDesignatedBroadcastReceiver(context: Context, intent: Intent): ActivityInfo? {
val searchIntent = Intent(intent.action).setPackage(context.packageName)
return context.packageManager.queryBroadcastReceivers(searchIntent, 0).firstOrNull()?.activityInfo
}
/**
* Creates and returns a pending intent that will trigger [NotificationsService],
* which hands off the work to this class. The intent triggers notification of the given identifier.
*
* @param context Context this is being called from
* @param identifier Notification identifier
* @return [PendingIntent] triggering [NotificationsService], triggering notification of given ID.
*/
fun createNotificationTrigger(context: Context, identifier: String): PendingIntent {
val intent = Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("scheduled")
.appendPath(identifier)
.appendPath("trigger")
.build()
).also { intent ->
findDesignatedBroadcastReceiver(context, intent)?.let {
intent.component = ComponentName(it.packageName, it.name)
}
intent.putExtra(EVENT_TYPE_KEY, TRIGGER_TYPE)
intent.putExtra(IDENTIFIER_KEY, identifier)
}
return PendingIntent.getBroadcast(
context,
intent.component?.className?.hashCode() ?: NotificationsService::class.java.hashCode(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
/**
* Creates and returns a pending intent that will trigger [NotificationsService]'s "response received"
* event.
*
* @param context Context this is being called from
* @param notification Notification being responded to
* @param action Notification action being undertaken
* @return [PendingIntent] triggering [NotificationsService], triggering "response received" event
*/
fun createNotificationResponseIntent(context: Context, notification: Notification, action: NotificationAction): PendingIntent {
val intent = Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath(notification.notificationRequest.identifier)
.appendPath("actions")
.appendPath(action.identifier)
.build()
).also { intent ->
findDesignatedBroadcastReceiver(context, intent)?.let {
intent.component = ComponentName(it.packageName, it.name)
}
intent.putExtra(EVENT_TYPE_KEY, RECEIVE_RESPONSE_TYPE)
intent.putExtra(NOTIFICATION_KEY, notification)
intent.putExtra(NOTIFICATION_ACTION_KEY, action as Parcelable)
}
return PendingIntent.getBroadcast(
context,
intent.component?.className?.hashCode() ?: NotificationsService::class.java.hashCode(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
fun getNotificationResponseFromIntent(intent: Intent): NotificationResponse? {
intent.getByteArrayExtra(NOTIFICATION_RESPONSE_KEY)?.let { return unmarshalObject(NotificationResponse.CREATOR, it) }
intent.getByteArrayExtra(TEXT_INPUT_NOTIFICATION_RESPONSE_KEY)?.let { return unmarshalObject(TextInputNotificationResponse.CREATOR, it) }
return null
}
// Class loader used in BaseBundle when unmarshalling notification extras
// cannot handle abi42_0_0.expo.modules.notifications.….NotificationResponse
// so we go around it by marshalling and unmarshalling the object ourselves.
fun setNotificationResponseToIntent(intent: Intent, notificationResponse: NotificationResponse) {
try {
val keyToPutResponseUnder = if (notificationResponse is TextInputNotificationResponse) {
TEXT_INPUT_NOTIFICATION_RESPONSE_KEY
} else {
NOTIFICATION_RESPONSE_KEY
}
intent.putExtra(keyToPutResponseUnder, marshalObject(notificationResponse))
} catch (e: Exception) {
// If we couldn't marshal the request, let's not fail the whole build process.
Log.e("expo-notifications", "Could not marshal notification response: ${notificationResponse.actionIdentifier}.")
e.printStackTrace()
}
}
/**
* Marshals [Parcelable] into to a byte array.
*
* @param notificationResponse Notification response to marshall
* @return Given request marshalled to a byte array or null if the process failed.
*/
private fun marshalObject(objectToMarshal: Parcelable): ByteArray? {
val parcel: Parcel = Parcel.obtain()
objectToMarshal.writeToParcel(parcel, 0)
val bytes: ByteArray = parcel.marshall()
parcel.recycle()
return bytes
}
/**
* UNmarshals [Parcelable] object from a byte array given a [Parcelable.Creator].
* @return Object instance or null if the process failed.
*/
private fun <T> unmarshalObject(creator: Parcelable.Creator<T>, byteArray: ByteArray?): T? {
byteArray?.let {
try {
val parcel = Parcel.obtain()
parcel.unmarshall(it, 0, it.size)
parcel.setDataPosition(0)
val unmarshaledObject = creator.createFromParcel(parcel)
parcel.recycle()
return unmarshaledObject
} catch (e: Exception) {
Log.e("expo-notifications", "Could not unmarshall NotificationResponse from Intent.extra.", e)
}
}
return null
}
}
protected open fun getPresentationDelegate(context: Context): PresentationDelegate =
ExpoPresentationDelegate(context)
protected open fun getHandlingDelegate(context: Context): HandlingDelegate =
ExpoHandlingDelegate(context)
protected open fun getCategoriesDelegate(context: Context): CategoriesDelegate =
ExpoCategoriesDelegate(context)
protected open fun getSchedulingDelegate(context: Context): SchedulingDelegate =
ExpoSchedulingDelegate(context)
override fun onReceive(context: Context, intent: Intent?) {
val pendingIntent = goAsync()
thread {
try {
handleIntent(context, intent)
} finally {
pendingIntent.finish()
}
}
}
open fun handleIntent(context: Context, intent: Intent?) {
if (intent != null && SETUP_ACTIONS.contains(intent.action)) {
onSetupScheduledNotifications(context, intent)
} else if (intent?.action === NOTIFICATION_EVENT_ACTION) {
val receiver: ResultReceiver? = intent.extras?.get(RECEIVER_KEY) as? ResultReceiver
try {
var resultData: Bundle? = null
when (val eventType = intent.getStringExtra(EVENT_TYPE_KEY)) {
GET_ALL_DISPLAYED_TYPE ->
resultData = onGetAllPresentedNotifications(context, intent)
RECEIVE_TYPE -> onReceiveNotification(context, intent)
RECEIVE_RESPONSE_TYPE -> onReceiveNotificationResponse(context, intent)
DROPPED_TYPE -> onNotificationsDropped(context, intent)
PRESENT_TYPE -> onPresentNotification(context, intent)
DISMISS_SELECTED_TYPE -> onDismissNotifications(context, intent)
DISMISS_ALL_TYPE -> onDismissAllNotifications(context, intent)
GET_CATEGORIES_TYPE ->
resultData = onGetCategories(context, intent)
SET_CATEGORY_TYPE ->
resultData = onSetCategory(context, intent)
DELETE_CATEGORY_TYPE ->
resultData = onDeleteCategory(context, intent)
GET_ALL_SCHEDULED_TYPE ->
resultData = onGetAllScheduledNotifications(context, intent)
GET_SCHEDULED_TYPE ->
resultData = onGetScheduledNotification(context, intent)
SCHEDULE_TYPE -> onScheduleNotification(context, intent)
REMOVE_SELECTED_TYPE -> onRemoveScheduledNotifications(context, intent)
REMOVE_ALL_TYPE -> onRemoveAllScheduledNotifications(context, intent)
TRIGGER_TYPE -> onNotificationTriggered(context, intent)
else -> throw IllegalArgumentException("Received event of unrecognized type: $eventType. Ignoring.")
}
// If we ended up here, the callbacks must have completed successfully
receiver?.send(SUCCESS_CODE, resultData)
} catch (e: Exception) {
Log.e("expo-notifications", "Action ${intent.action} failed: ${e.message}")
e.printStackTrace()
receiver?.send(ERROR_CODE, Bundle().also { it.putSerializable(EXCEPTION_KEY, e) })
}
} else {
throw IllegalArgumentException("Received intent of unrecognized action: ${intent?.action}. Ignoring.")
}
}
//region Presenting notifications
open fun onPresentNotification(context: Context, intent: Intent) =
getPresentationDelegate(context).presentNotification(
intent.extras?.getParcelable(NOTIFICATION_KEY)!!,
intent.extras?.getParcelable(NOTIFICATION_BEHAVIOR_KEY)
)
open fun onGetAllPresentedNotifications(context: Context, intent: Intent) =
Bundle().also {
it.putParcelableArrayList(
NOTIFICATIONS_KEY,
ArrayList(
getPresentationDelegate(context).getAllPresentedNotifications()
)
)
}
open fun onDismissNotifications(context: Context, intent: Intent) =
getPresentationDelegate(context).dismissNotifications(
intent.extras?.getStringArray(IDENTIFIERS_KEY)!!.asList()
)
open fun onDismissAllNotifications(context: Context, intent: Intent) =
getPresentationDelegate(context).dismissAllNotifications()
//endregion
//region Handling notifications
open fun onReceiveNotification(context: Context, intent: Intent) =
getHandlingDelegate(context).handleNotification(
intent.getParcelableExtra(NOTIFICATION_KEY)!!
)
open fun onReceiveNotificationResponse(context: Context, intent: Intent) {
val notification = intent.getParcelableExtra<Notification>(NOTIFICATION_KEY)!!
val action = intent.getParcelableExtra<NotificationAction>(NOTIFICATION_ACTION_KEY)!!
val response = if (action is TextInputNotificationAction) {
TextInputNotificationResponse(action, notification, RemoteInput.getResultsFromIntent(intent).getString(USER_TEXT_RESPONSE_KEY))
} else {
NotificationResponse(action, notification)
}
getHandlingDelegate(context).handleNotificationResponse(response)
}
open fun onNotificationsDropped(context: Context, intent: Intent) =
getHandlingDelegate(context).handleNotificationsDropped()
//endregion
//region Category handling
open fun onGetCategories(context: Context, intent: Intent) =
Bundle().also {
it.putParcelableArrayList(
NOTIFICATION_CATEGORIES_KEY,
ArrayList(
getCategoriesDelegate(context).getCategories()
)
)
}
open fun onSetCategory(context: Context, intent: Intent) =
Bundle().also {
it.putParcelable(
NOTIFICATION_CATEGORY_KEY,
getCategoriesDelegate(context).setCategory(
intent.getParcelableExtra(NOTIFICATION_CATEGORY_KEY)!!
)
)
}
open fun onDeleteCategory(context: Context, intent: Intent) =
Bundle().also {
it.putBoolean(
SUCCEEDED_KEY,
getCategoriesDelegate(context).deleteCategory(
intent.extras?.getString(IDENTIFIER_KEY)!!
)
)
}
//endregion
//region Scheduling notifications
open fun onGetAllScheduledNotifications(context: Context, intent: Intent) =
Bundle().also {
it.putParcelableArrayList(
NOTIFICATION_REQUESTS_KEY,
ArrayList(
getSchedulingDelegate(context).getAllScheduledNotifications()
)
)
}
open fun onGetScheduledNotification(context: Context, intent: Intent) =
Bundle().also {
it.putParcelable(
NOTIFICATION_REQUEST_KEY,
getSchedulingDelegate(context).getScheduledNotification(
intent.extras?.getString(IDENTIFIER_KEY)!!
)
)
}
open fun onScheduleNotification(context: Context, intent: Intent) =
getSchedulingDelegate(context).scheduleNotification(
intent.extras?.getParcelable(NOTIFICATION_REQUEST_KEY)!!
)
open fun onNotificationTriggered(context: Context, intent: Intent) =
getSchedulingDelegate(context).triggerNotification(
intent.extras?.getString(IDENTIFIER_KEY)!!
)
open fun onRemoveScheduledNotifications(context: Context, intent: Intent) =
getSchedulingDelegate(context).removeScheduledNotifications(
intent.extras?.getStringArray(IDENTIFIERS_KEY)!!.asList()
)
open fun onRemoveAllScheduledNotifications(context: Context, intent: Intent) =
getSchedulingDelegate(context).removeAllScheduledNotifications()
open fun onSetupScheduledNotifications(context: Context, intent: Intent) =
getSchedulingDelegate(context).setupScheduledNotifications()
//endregion
}
| bsd-3-clause | 092082ebe84ccaefcaae51e3a12983c3 | 37.152497 | 183 | 0.690248 | 4.988707 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.