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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
androidx/androidx | fragment/fragment-lint/src/main/java/androidx/fragment/lint/UseRequireInsteadOfGet.kt | 3 | 13381 | /*
* 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.fragment.lint
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.LintFix
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.android.tools.lint.detector.api.isKotlin
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.ULocalVariable
import org.jetbrains.uast.UPostfixExpression
import org.jetbrains.uast.UQualifiedReferenceExpression
import org.jetbrains.uast.USimpleNameReferenceExpression
import org.jetbrains.uast.getContainingUClass
import org.jetbrains.uast.kotlin.KotlinUFunctionCallExpression
import org.jetbrains.uast.skipParenthesizedExprDown
import org.jetbrains.uast.skipParenthesizedExprUp
import org.jetbrains.uast.toUElement
import org.jetbrains.uast.tryResolve
import java.util.Locale
/**
* Androidx added new "require____()" versions of common "get___()" APIs, such as
* getContext/getActivity/getArguments/etc. Rather than wrap these in something like
* requireNotNull() or null-checking with `!!` in Kotlin, using these APIs will allow the
* underlying component to try to tell you _why_ it was null, and thus yield a better error
* message.
*/
@Suppress("UnstableApiUsage")
class UseRequireInsteadOfGet : Detector(), SourceCodeScanner {
companion object {
val ISSUE: Issue = Issue.create(
"UseRequireInsteadOfGet",
"Use the 'require_____()' API rather than 'get____()' API for more " +
"descriptive error messages when it's null.",
"""
AndroidX added new "require____()" versions of common "get___()" APIs, such as \
getContext/getActivity/getArguments/etc. Rather than wrap these in something like \
requireNotNull(), using these APIs will allow the underlying component to try \
to tell you _why_ it was null, and thus yield a better error message.
""",
Category.CORRECTNESS,
6,
Severity.ERROR,
Implementation(UseRequireInsteadOfGet::class.java, Scope.JAVA_FILE_SCOPE)
)
private const val FRAGMENT_FQCN = "androidx.fragment.app.Fragment"
internal val REQUIRABLE_METHODS = setOf(
"getArguments",
"getContext",
"getActivity",
"getFragmentManager",
"getHost",
"getParentFragment",
"getView"
)
// Convert 'getArguments' to 'arguments'
internal val REQUIRABLE_REFERENCES = REQUIRABLE_METHODS.map {
it.removePrefix("get").decapitalize(Locale.US)
}
internal val KNOWN_NULLCHECKS = setOf(
"checkNotNull",
"requireNonNull"
)
}
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
super.visitMethodCall(context, node, method)
}
override fun getApplicableUastTypes(): List<Class<out UElement>>? {
return listOf(UCallExpression::class.java, USimpleNameReferenceExpression::class.java)
}
override fun createUastHandler(context: JavaContext): UElementHandler? {
val isKotlin = isKotlin(context.psiFile)
return object : UElementHandler() {
/** This covers Kotlin accessor syntax expressions like "fragment.arguments" */
override fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression) {
val parent = skipParenthesizedExprUp(node.uastParent)
if (parent is UQualifiedReferenceExpression) {
checkReferenceExpression(parent, node.identifier) {
parent.receiver.getExpressionType()
?.let { context.evaluator.findClass(it.canonicalText) }
}
} else {
// It's a member of the enclosing class
checkReferenceExpression(node, node.identifier) {
node.getContainingUClass()
}
}
}
private fun checkReferenceExpression(
node: UExpression,
identifier: String,
resolveEnclosingClass: () -> PsiClass?
) {
if (identifier in REQUIRABLE_REFERENCES) {
// If this is a local variable do nothing
// We are doing this to avoid false positives on local variables that shadow
// Kotlin property accessors. There is probably a better way to organize
// this Lint rule.
val element = node.tryResolve()
if (element != null && element.toUElement() is ULocalVariable) {
return
}
val enclosingClass = resolveEnclosingClass() ?: return
if (context.evaluator.extendsClass(enclosingClass, FRAGMENT_FQCN, false)) {
checkForIssue(node, identifier)
}
}
}
/** This covers function/method calls like "fragment.getArguments()" */
override fun visitCallExpression(node: UCallExpression) {
val targetMethod = node.resolve() ?: return
val containingClass = targetMethod.containingClass ?: return
if (targetMethod.name in REQUIRABLE_METHODS &&
context.evaluator.extendsClass(containingClass, FRAGMENT_FQCN, false)
) {
checkForIssue(node, targetMethod.name, "${targetMethod.name}()")
}
}
/** Called only when we know we're looking at an exempted method call type. */
private fun checkForIssue(
node: UExpression,
targetMethodName: String,
targetExpression: String = targetMethodName
) {
// Note we go up potentially two parents - the first one may just be the qualified reference expression
val nearestNonQualifiedReferenceParent =
skipParenthesizedExprUp(node.nearestNonQualifiedReferenceParent) ?: return
if (isKotlin && nearestNonQualifiedReferenceParent.isNullCheckBlock()) {
// We're a double-bang expression (!!)
val parentSourceToReplace =
nearestNonQualifiedReferenceParent.asSourceString()
var correctMethod = correctMethod(
parentSourceToReplace,
"$targetExpression!!",
targetMethodName
)
if (correctMethod == parentSourceToReplace.removeSingleParentheses()) {
correctMethod = parentSourceToReplace.removeSingleParentheses().replace(
"$targetExpression?", "$targetExpression!!"
).replaceFirstOccurrenceAfter("!!", "", "$targetExpression!!")
}
report(nearestNonQualifiedReferenceParent, parentSourceToReplace, correctMethod)
} else if (nearestNonQualifiedReferenceParent is UCallExpression) {
// See if we're in a "requireNotNull(...)" or similar expression
val enclosingMethodCall =
(
skipParenthesizedExprUp(
nearestNonQualifiedReferenceParent
) as UCallExpression
).resolve() ?: return
if (enclosingMethodCall.name in KNOWN_NULLCHECKS) {
// Only match for single (specified) parameter. If existing code had a
// custom failure message, we don't want to overwrite it.
val singleParameterSpecified =
isSingleParameterSpecified(
enclosingMethodCall,
nearestNonQualifiedReferenceParent
)
if (singleParameterSpecified) {
// Grab the source of this argument as it's represented.
val source = nearestNonQualifiedReferenceParent.valueArguments[0]
.skipParenthesizedExprDown()!!.asSourceString()
val parentToReplace =
nearestNonQualifiedReferenceParent.fullyQualifiedNearestParent()
.asSourceString()
val correctMethod =
correctMethod(source, targetExpression, targetMethodName)
report(
nearestNonQualifiedReferenceParent,
parentToReplace,
correctMethod
)
}
}
}
}
private fun isSingleParameterSpecified(
enclosingMethodCall: PsiMethod,
nearestNonQualifiedRefParent: UCallExpression
) = enclosingMethodCall.parameterList.parametersCount == 1 ||
(
isKotlin &&
nearestNonQualifiedRefParent is KotlinUFunctionCallExpression &&
nearestNonQualifiedRefParent.getArgumentForParameter(1) == null
)
private fun correctMethod(
source: String,
targetExpression: String,
targetMethodName: String
): String {
return source.removeSingleParentheses().replace(
targetExpression,
"require${targetMethodName.removePrefix("get").capitalize(Locale.US)}()"
)
}
// Replaces the first occurrence of a substring after given String
private fun String.replaceFirstOccurrenceAfter(
oldValue: String,
newValue: String,
prefix: String
): String = prefix + substringAfter(prefix).replaceFirst(oldValue, newValue)
private fun report(node: UElement, targetExpression: String, correctMethod: String) {
context.report(
ISSUE,
context.getLocation(node),
"Use $correctMethod instead of $targetExpression",
LintFix.create()
.replace()
.name("Replace with $correctMethod")
.text(targetExpression)
.with(correctMethod)
.autoFix()
.build()
)
}
}
}
}
/**
* Copy of the currently experimental Kotlin stdlib version. Can be removed once the stdlib version
* comes out of experimental.
*/
internal fun String.decapitalize(locale: Locale): String {
return if (isNotEmpty() && !this[0].isLowerCase()) {
substring(0, 1).lowercase(locale) + substring(1)
} else {
this
}
}
/**
* Copy of the currently experimental Kotlin stdlib version. Can be removed once the stdlib version
* comes out of experimental.
*/
internal fun String.capitalize(locale: Locale): String {
if (isNotEmpty()) {
val firstChar = this[0]
if (firstChar.isLowerCase()) {
return buildString {
val titleChar = firstChar.titlecaseChar()
if (titleChar != firstChar.uppercaseChar()) {
append(titleChar)
} else {
append([email protected](0, 1).uppercase(locale))
}
append([email protected](1))
}
}
}
return this
}
internal fun UElement.isNullCheckBlock(): Boolean {
return this is UPostfixExpression && operator.text == "!!"
}
internal fun String.removeSingleParentheses(): String {
return this.replace("[(](?=[^)])".toRegex(), "")
.replace("(?<![(])[)]".toRegex(), "")
}
| apache-2.0 | 48ef242661346fa619c775ff18bdfe6d | 43.307947 | 119 | 0.582019 | 5.936557 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/base/enums/lifecycle/ActivityLifecycle.kt | 1 | 469 | package com.sedsoftware.yaptalker.presentation.base.enums.lifecycle
import androidx.annotation.LongDef
class ActivityLifecycle {
companion object {
const val CREATE = 0L
const val START = 1L
const val RESUME = 2L
const val PAUSE = 3L
const val STOP = 4L
const val DESTROY = 5L
}
@Retention(AnnotationRetention.SOURCE)
@LongDef(CREATE, START, RESUME, PAUSE, STOP, DESTROY)
annotation class Event
}
| apache-2.0 | 016e247a64e3b86a26bb0b9d4eaa0a4e | 23.684211 | 67 | 0.671642 | 4.263636 | false | false | false | false |
elect86/oglDevTutorials | src/main/kotlin/ogl_dev/tut05/uniform-variables.kt | 1 | 4343 | package ogl_dev.tut05
/**
* Created by elect on 23/04/2017.
*/
import glm.vec._2.Vec2i
import glm.vec._3.Vec3
import ogl_dev.GlfwWindow
import ogl_dev.common.readFile
import ogl_dev.glfw
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.*
import uno.buffer.floatBufferBig
import uno.buffer.intBufferBig
import uno.glf.semantic
import uno.gln.glBindBuffer
import uno.gln.glDrawArrays
import kotlin.properties.Delegates
import glm.Glm.sin
private var window by Delegates.notNull<GlfwWindow>()
fun main(args: Array<String>) {
with(glfw) {
// Initialize GLFW. Most GLFW functions will not work before doing this.
// It also setups an error callback. The default implementation will print the error message in System.err.
init()
windowHint { doubleBuffer = true } // Configure GLFW
}
window = GlfwWindow(300, "Tutorial 5") // Create the window
with(window) {
pos = Vec2i(100) // Set the window position
makeContextCurrent() // Make the OpenGL context current
show() // Make the window visible
}
/* This line is critical for LWJGL's interoperation with GLFW's OpenGL context, or any context that is managed
externally. LWJGL detects the context that is current in the current thread, creates the GLCapabilities instance and
makes the OpenGL bindings available for use. */
GL.createCapabilities()
println("GL version: ${glGetString(GL_VERSION)}")
glClearColor(0.0f, 0.0f, 0.0f, 0.0f)
createVertexBuffer()
compileShaders()
// Run the rendering loop until the user has attempted to close the window or has pressed the ESCAPE key.
while (!window.shouldClose) {
renderScene()
glfw.pollEvents() // Poll for window events. The key callback above will only be invoked during this call.
}
window.dispose()
glfw.terminate() // Terminate GLFW and free the error callback
}
val vbo = intBufferBig(1)
var scaleLocation = 0
val vsFileName = "tut05/shader.vert"
val fsFileName = "tut05/shader.frag"
var scale = 0.0f
fun createVertexBuffer() {
val vertices = floatBufferBig(Vec3.SIZE * 3)
Vec3(-1.0f, -1.0f, 0.0f) to vertices
Vec3(1.0f, -1.0f, 0.0f).to(vertices, Vec3.length)
Vec3(0.0f, 1.0f, 0.0f).to(vertices, Vec3.length * 2)
glGenBuffers(vbo)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)
}
fun compileShaders() {
val shaderProgram = glCreateProgram()
if (shaderProgram == 0) throw Error("Error creating shader program")
val vs = readFile(vsFileName)
val fs = readFile(fsFileName)
addShader(shaderProgram, vs, GL_VERTEX_SHADER)
addShader(shaderProgram, fs, GL_FRAGMENT_SHADER)
glLinkProgram(shaderProgram)
if (glGetProgrami(shaderProgram, GL_LINK_STATUS) == GL_FALSE) {
val errorLog = glGetProgramInfoLog(shaderProgram)
throw Error("Error linking shader program: $errorLog")
}
glValidateProgram(shaderProgram)
if (glGetProgrami(shaderProgram, GL_VALIDATE_STATUS) != GL_TRUE) {
val errorLog = glGetProgramInfoLog(shaderProgram)
throw Error("Invalid shader program: $errorLog")
}
glUseProgram(shaderProgram)
scaleLocation = glGetUniformLocation(shaderProgram, "gScale")
assert(scaleLocation != -1)
}
fun addShader(shaderProgram: Int, shaderText: String, shaderType: Int) {
val shaderObj = glCreateShader(shaderType)
if (shaderObj == 0) throw Error("Error creating shader type $shaderType")
glShaderSource(shaderObj, shaderText)
glCompileShader(shaderObj)
if (glGetShaderi(shaderObj, GL_COMPILE_STATUS) != GL_TRUE) {
val infoLog = glGetShaderInfoLog(shaderObj)
throw Error("Error compiling shader type $shaderType: $infoLog")
}
glAttachShader(shaderProgram, shaderObj)
}
fun renderScene() {
glClear(GL_COLOR_BUFFER_BIT)
scale += 0.01f
glUniform1f(scaleLocation, sin(scale))
glEnableVertexAttribArray(semantic.attr.POSITION)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glVertexAttribPointer(semantic.attr.POSITION, Vec3.length, GL_FLOAT, false, Vec3.SIZE, 0)
glDrawArrays(GL_TRIANGLES, 3)
glDisableVertexAttribArray(semantic.attr.POSITION)
window.swapBuffers()
} | mit | 7d0c886284f5b6a700aaf67405f2a9f9 | 27.96 | 120 | 0.707806 | 3.948182 | false | false | false | false |
androidx/androidx | camera/camera-camera2-pipe/src/test/java/androidx/camera/camera2/pipe/testing/FakeCameraController.kt | 3 | 1256 | /*
* 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.camera.camera2.pipe.testing
import android.view.Surface
import androidx.camera.camera2.pipe.CameraController
import androidx.camera.camera2.pipe.StreamId
internal class FakeCameraController : CameraController {
var started = false
var closed = false
var surfaceMap: Map<StreamId, Surface>? = null
override fun start() {
started = true
}
override fun stop() {
started = false
}
override fun close() {
closed = true
started = false
}
override fun updateSurfaceMap(surfaceMap: Map<StreamId, Surface>) {
this.surfaceMap = surfaceMap
}
} | apache-2.0 | e6e50c2ae2819f28fc8cb95034eb243e | 27.568182 | 75 | 0.707803 | 4.331034 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/ui/branch/GitBranchesTreePopupStep.kt | 1 | 13804 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ui.branch
import com.intellij.dvcs.DvcsUtil
import com.intellij.dvcs.diverged
import com.intellij.dvcs.ui.DvcsBundle
import com.intellij.dvcs.ui.RepositoryChangesBrowserNode
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.components.service
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.PopupStep.FINAL_CHOICE
import com.intellij.openapi.ui.popup.SpeedSearchFilter
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import com.intellij.psi.codeStyle.MinusculeMatcher
import com.intellij.psi.codeStyle.NameUtil
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.RowIcon
import com.intellij.ui.popup.ActionPopupStep
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.util.PlatformIcons
import com.intellij.util.containers.FList
import git4idea.GitBranch
import git4idea.GitLocalBranch
import git4idea.GitRemoteBranch
import git4idea.GitVcs
import git4idea.actions.branch.GitBranchActionsUtil
import git4idea.branch.GitBranchIncomingOutgoingManager
import git4idea.branch.GitBranchType
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.ui.branch.GitBranchPopupActions.EXPERIMENTAL_BRANCH_POPUP_ACTION_GROUP
import icons.DvcsImplIcons
import org.jetbrains.annotations.Nls
import javax.swing.Icon
import javax.swing.tree.TreeModel
import javax.swing.tree.TreePath
class GitBranchesTreePopupStep(private val project: Project,
internal val repositories: List<GitRepository>,
private val isFirstStep: Boolean) : PopupStep<Any> {
private var finalRunnable: Runnable? = null
override fun getFinalRunnable() = finalRunnable
private val _treeModel: GitBranchesTreeModel
val treeModel: TreeModel
get() = _treeModel
init {
val topLevelItems = mutableListOf<Any>()
if (ExperimentalUI.isNewUI() && isFirstStep) {
val experimentalUIActionsGroup = ActionManager.getInstance().getAction(EXPERIMENTAL_BRANCH_POPUP_ACTION_GROUP) as? ActionGroup
if (experimentalUIActionsGroup != null) {
topLevelItems.addAll(createActionItems(experimentalUIActionsGroup, project, repositories).addSeparators())
topLevelItems.add(GitBranchesTreePopup.createTreeSeparator())
}
}
val actionGroup = ActionManager.getInstance().getAction(TOP_LEVEL_ACTION_GROUP) as? ActionGroup
if (actionGroup != null) {
// get selected repo inside actions
topLevelItems.addAll(createActionItems(actionGroup, project, repositories).addSeparators())
topLevelItems.add(GitBranchesTreePopup.createTreeSeparator())
}
_treeModel = GitBranchesTreeModelImpl(project, repositories, topLevelItems)
}
private fun List<PopupFactoryImpl.ActionItem>.addSeparators(): List<Any> {
val actionsWithSeparators = mutableListOf<Any>()
for (action in this) {
if (action.isPrependWithSeparator) {
actionsWithSeparators.add(GitBranchesTreePopup.createTreeSeparator(action.separatorText))
}
actionsWithSeparators.add(action)
}
return actionsWithSeparators
}
fun isBranchesDiverged(): Boolean {
return repositories.size > 1
&& repositories.diverged()
&& GitBranchActionsUtil.userWantsSyncControl(project)
}
fun getPreferredSelection(): TreePath? {
return _treeModel.getPreferredSelection()
}
internal fun setPrefixGrouping(state: Boolean) {
_treeModel.isPrefixGrouping = state
}
private val LOCAL_SEARCH_PREFIX = "/l"
private val REMOTE_SEARCH_PREFIX = "/r"
fun setSearchPattern(pattern: String?) {
if (pattern == null || pattern == "/") {
_treeModel.filterBranches()
return
}
var branchType: GitBranchType? = null
var processedPattern = pattern
if (pattern.startsWith(LOCAL_SEARCH_PREFIX)) {
branchType = GitBranchType.LOCAL
processedPattern = pattern.removePrefix(LOCAL_SEARCH_PREFIX).trimStart()
}
if (pattern.startsWith(REMOTE_SEARCH_PREFIX)) {
branchType = GitBranchType.REMOTE
processedPattern = pattern.removePrefix(REMOTE_SEARCH_PREFIX).trimStart()
}
val matcher = PreferStartMatchMatcherWrapper(NameUtil.buildMatcher("*$processedPattern").build())
_treeModel.filterBranches(branchType, matcher)
}
override fun hasSubstep(selectedValue: Any?): Boolean {
val userValue = selectedValue ?: return false
return userValue is GitRepository ||
userValue is GitBranch ||
(userValue is PopupFactoryImpl.ActionItem && userValue.isEnabled && userValue.action is ActionGroup)
}
fun isSelectable(node: Any?): Boolean {
val userValue = node ?: return false
return userValue is GitRepository ||
userValue is GitBranch ||
(userValue is PopupFactoryImpl.ActionItem && userValue.isEnabled)
}
override fun onChosen(selectedValue: Any?, finalChoice: Boolean): PopupStep<out Any>? {
if (selectedValue is GitRepository) {
return GitBranchesTreePopupStep(project, listOf(selectedValue), false)
}
if (selectedValue is GitBranch) {
val actionGroup = ActionManager.getInstance().getAction(BRANCH_ACTION_GROUP) as? ActionGroup ?: DefaultActionGroup()
return createActionStep(actionGroup, project, repositories, selectedValue)
}
if (selectedValue is PopupFactoryImpl.ActionItem) {
if (!selectedValue.isEnabled) return FINAL_CHOICE
val action = selectedValue.action
if (action is ActionGroup && (!finalChoice || !selectedValue.isPerformGroup)) {
return createActionStep(action, project, repositories)
}
else {
finalRunnable = Runnable {
ActionUtil.invokeAction(action, createDataContext(project, repositories), ACTION_PLACE, null, null)
}
}
}
return FINAL_CHOICE
}
override fun getTitle(): String? =
when {
!isFirstStep -> null
repositories.size > 1 -> DvcsBundle.message("branch.popup.vcs.name.branches", GitVcs.DISPLAY_NAME.get())
else -> repositories.single().let {
DvcsBundle.message("branch.popup.vcs.name.branches.in.repo", it.vcs.displayName, DvcsUtil.getShortRepositoryName(it))
}
}
fun getIncomingOutgoingIconWithTooltip(treeNode: Any?): Pair<Icon?, @Nls(capitalization = Nls.Capitalization.Sentence) String?> {
val empty = null to null
val value = treeNode ?: return empty
return when (value) {
is GitBranch -> getIncomingOutgoingIconWithTooltip(value)
else -> empty
}
}
private fun getIncomingOutgoingIconWithTooltip(branch: GitBranch): Pair<Icon?, String?> {
val branchName = branch.name
val incomingOutgoingManager = project.service<GitBranchIncomingOutgoingManager>()
val hasIncoming =
repositories.any { incomingOutgoingManager.hasIncomingFor(it, branchName) }
val hasOutgoing =
repositories.any { incomingOutgoingManager.hasOutgoingFor(it, branchName) }
val tooltip = GitBranchPopupActions.LocalBranchActions.constructIncomingOutgoingTooltip(hasIncoming, hasOutgoing).orEmpty()
return when {
hasIncoming && hasOutgoing -> RowIcon(DvcsImplIcons.Incoming, DvcsImplIcons.Outgoing)
hasIncoming -> DvcsImplIcons.Incoming
hasOutgoing -> DvcsImplIcons.Outgoing
else -> null
} to tooltip
}
private val colorManager = RepositoryChangesBrowserNode.getColorManager(project)
fun getNodeIcon(treeNode: Any?, isSelected: Boolean): Icon? {
val value = treeNode ?: return null
return when (value) {
is PopupFactoryImpl.ActionItem -> value.getIcon(isSelected)
is GitRepository -> RepositoryChangesBrowserNode.getRepositoryIcon(value, colorManager)
else -> null
}
}
fun getIcon(treeNode: Any?, isSelected: Boolean): Icon? {
val value = treeNode ?: return null
return when (value) {
is GitBranchesTreeModel.BranchesPrefixGroup -> PlatformIcons.FOLDER_ICON
is GitBranch -> getBranchIcon(value, isSelected)
else -> null
}
}
private fun getBranchIcon(branch: GitBranch, isSelected: Boolean): Icon {
val isCurrent = repositories.all { it.currentBranch == branch }
val branchManager = project.service<GitBranchManager>()
val isFavorite = repositories.all { branchManager.isFavorite(GitBranchType.of(branch), it, branch.name) }
return when {
isSelected && isFavorite -> AllIcons.Nodes.Favorite
isSelected -> AllIcons.Nodes.NotFavoriteOnHover
isCurrent && isFavorite -> DvcsImplIcons.CurrentBranchFavoriteLabel
isCurrent -> DvcsImplIcons.CurrentBranchLabel
isFavorite -> AllIcons.Nodes.Favorite
else -> AllIcons.Vcs.BranchNode
}
}
fun getText(treeNode: Any?): @NlsSafe String? {
val value = treeNode ?: return null
return when (value) {
GitBranchType.LOCAL -> {
if (repositories.size > 1) GitBundle.message("common.local.branches") else GitBundle.message("group.Git.Local.Branch.title")
}
GitBranchType.REMOTE -> {
if (repositories.size > 1) GitBundle.message("common.remote.branches") else GitBundle.message("group.Git.Remote.Branch.title")
}
is GitBranchesTreeModel.BranchesPrefixGroup -> value.prefix.last()
is GitRepository -> DvcsUtil.getShortRepositoryName(value)
is GitBranch -> {
if (_treeModel.isPrefixGrouping) value.name.split('/').last() else value.name
}
is PopupFactoryImpl.ActionItem -> value.text
else -> value.toString()
}
}
fun getSecondaryText(treeNode: Any?): @NlsSafe String? {
return when (treeNode) {
is PopupFactoryImpl.ActionItem -> KeymapUtil.getFirstKeyboardShortcutText(treeNode.action)
is GitRepository -> treeNode.currentBranch?.name.orEmpty()
is GitLocalBranch -> {
treeNode.getCommonTrackedBranch(repositories)?.name
}
else -> null
}
}
private fun GitLocalBranch.getCommonTrackedBranch(repositories: List<GitRepository>): GitRemoteBranch? {
var commonTrackedBranch: GitRemoteBranch? = null
for (repository in repositories) {
val trackedBranch = findTrackedBranch(repository) ?: return null
if (commonTrackedBranch == null) {
commonTrackedBranch = trackedBranch
}
else if (commonTrackedBranch.name != trackedBranch.name) {
return null
}
}
return commonTrackedBranch
}
override fun canceled() {}
override fun isMnemonicsNavigationEnabled() = false
override fun getMnemonicNavigationFilter() = null
override fun isSpeedSearchEnabled() = true
override fun getSpeedSearchFilter() = SpeedSearchFilter<Any> { node ->
when (node) {
is GitBranch -> node.name
else -> node?.let(::getText) ?: ""
}
}
override fun isAutoSelectionEnabled() = false
companion object {
internal const val HEADER_SETTINGS_ACTION_GROUP = "Git.Branches.Popup.Settings"
private const val TOP_LEVEL_ACTION_GROUP = "Git.Branches.List"
internal const val SPEED_SEARCH_DEFAULT_ACTIONS_GROUP = "Git.Branches.Popup.SpeedSearch"
private const val BRANCH_ACTION_GROUP = "Git.Branch"
internal val ACTION_PLACE = ActionPlaces.getPopupPlace("GitBranchesPopup")
private fun createActionItems(actionGroup: ActionGroup,
project: Project,
repositories: List<GitRepository>): List<PopupFactoryImpl.ActionItem> {
val dataContext = createDataContext(project, repositories)
return ActionPopupStep
.createActionItems(actionGroup, dataContext, false, false, false, false, ACTION_PLACE, null)
}
private fun createActionStep(actionGroup: ActionGroup,
project: Project,
repositories: List<GitRepository>,
branch: GitBranch? = null): ListPopupStep<*> {
val dataContext = createDataContext(project, repositories, branch)
return JBPopupFactory.getInstance()
.createActionsStep(actionGroup, dataContext, ACTION_PLACE, false, true, null, null, true, 0, false)
}
internal fun createDataContext(project: Project, repositories: List<GitRepository>, branch: GitBranch? = null): DataContext =
SimpleDataContext.builder()
.add(CommonDataKeys.PROJECT, project)
.add(GitBranchActionsUtil.REPOSITORIES_KEY, repositories)
.add(GitBranchActionsUtil.BRANCHES_KEY, branch?.let(::listOf))
.build()
/**
* Adds weight to match offset. Degree of match is increased with the earlier the pattern was found in the name.
*/
private class PreferStartMatchMatcherWrapper(private val delegate: MinusculeMatcher) : MinusculeMatcher() {
override fun getPattern(): String = delegate.pattern
override fun matchingFragments(name: String): FList<TextRange>? = delegate.matchingFragments(name)
override fun matchingDegree(name: String, valueStartCaseMatch: Boolean, fragments: FList<out TextRange>?): Int {
var degree = delegate.matchingDegree(name, valueStartCaseMatch, fragments)
if (fragments.isNullOrEmpty()) return degree
degree += MATCH_OFFSET - fragments.head.startOffset
return degree
}
companion object {
private const val MATCH_OFFSET = 10000
}
}
}
}
| apache-2.0 | 484a9e5ea962410dc9a4838431703dd7 | 37.775281 | 134 | 0.720226 | 4.924724 | false | false | false | false |
GunoH/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/features/MLFeaturesUtil.kt | 2 | 1752 | // 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.completion.ml.features
import com.github.benmanes.caffeine.cache.Caffeine
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.util.Version
internal object MLFeaturesUtil {
fun getRawValue(featureValue: MLFeatureValue): Any {
return when (featureValue) {
is MLFeatureValue.BinaryValue -> if (featureValue.value) 1 else 0
is MLFeatureValue.FloatValue -> featureValue.value
is MLFeatureValue.CategoricalValue -> featureValue.value
is MLFeatureValue.ClassNameValue -> getClassNameSafe(featureValue)
is MLFeatureValue.VersionValue -> getVersionSafe(featureValue)
}
}
private data class ClassNames(val simpleName: String, val fullName: String)
private fun Class<*>.getNames(): ClassNames {
return ClassNames(simpleName, name)
}
private val THIRD_PARTY_NAME = ClassNames("third.party", "third.party")
private val CLASS_NAMES_CACHE = Caffeine.newBuilder().maximumSize(100).build<String, ClassNames>()
fun getClassNameSafe(feature: MLFeatureValue.ClassNameValue): String {
val clazz = feature.value
val names = CLASS_NAMES_CACHE.get(clazz.name) { if (getPluginInfo(clazz).isSafeToReport()) clazz.getNames() else THIRD_PARTY_NAME }!!
return if (feature.useSimpleName) names.simpleName else names.fullName
}
private const val INVALID_VERSION = "invalid.version"
private fun getVersionSafe(featureValue: MLFeatureValue.VersionValue): String =
Version.parseVersion(featureValue.value)?.toString() ?: INVALID_VERSION
}
| apache-2.0 | dfb5e37547d546f761b2a04342b3fea9 | 42.8 | 140 | 0.768265 | 4.53886 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddNamesInCommentToJavaCallArgumentsIntention.kt | 3 | 4876 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.elementType
import com.intellij.psi.util.siblings
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.descriptors.JavaClassConstructorDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.components.isVararg
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AddNamesInCommentToJavaCallArgumentsIntention : SelfTargetingIntention<KtCallElement>(
KtCallElement::class.java,
KotlinBundle.lazyMessage("add.names.in.comment.to.call.arguments")
) {
override fun isApplicableTo(element: KtCallElement, caretOffset: Int): Boolean =
resolveValueParameterDescriptors(element, anyBlockCommentsWithName = true) != null
override fun applyTo(element: KtCallElement, editor: Editor?) {
val resolvedCall = element.resolveToCall() ?: return
val psiFactory = KtPsiFactory(element)
for ((argument, parameter) in element.valueArguments.filterIsInstance<KtValueArgument>().resolve(resolvedCall)) {
val parent = argument.parent
parent.addBefore(psiFactory.createComment(parameter.toParameterNameComment()), argument)
parent.addBefore(psiFactory.createWhiteSpace(), argument)
if (parameter.isVararg) break
}
}
companion object {
fun resolveValueParameterDescriptors(
element: KtCallElement,
anyBlockCommentsWithName: Boolean
): List<Pair<KtValueArgument, ValueParameterDescriptor>>? {
val arguments = element.valueArguments.filterIsInstance<KtValueArgument>().filterNot { it is KtLambdaArgument }
if (arguments.isEmpty() || arguments.any { it.isNamed() } ||
(anyBlockCommentsWithName && arguments.any { it.hasBlockCommentWithName() }) ||
(!anyBlockCommentsWithName && arguments.none { it.hasBlockCommentWithName() })
) return null
val resolvedCall = element.resolveToCall() ?: return null
val descriptor = resolvedCall.candidateDescriptor
if (descriptor !is JavaMethodDescriptor && descriptor !is JavaClassConstructorDescriptor) return null
val resolve = arguments.resolve(resolvedCall)
if (arguments.size != resolve.size) return null
return resolve
}
fun ValueParameterDescriptor.toParameterNameComment(): String =
canonicalParameterNameComment(if (isVararg) "...$name" else name.asString())
private fun canonicalParameterNameComment(parameterName: String): String = "/* $parameterName = */"
fun PsiComment.isParameterNameComment(parameter: ValueParameterDescriptor): Boolean {
if (this.elementType != KtTokens.BLOCK_COMMENT) return false
val parameterName = text
.removePrefix("/*").removeSuffix("*/").trim()
.takeIf { it.endsWith("=") }?.removeSuffix("=")?.trim()
?: return false
return canonicalParameterNameComment(parameterName) == parameter.toParameterNameComment()
}
private fun KtValueArgument.hasBlockCommentWithName(): Boolean =
blockCommentWithName() != null
fun KtValueArgument.blockCommentWithName(): PsiComment? =
siblings(forward = false, withSelf = false)
.takeWhile { it is PsiWhiteSpace || it is PsiComment }
.filterIsInstance<PsiComment>()
.firstOrNull { it.elementType == KtTokens.BLOCK_COMMENT && it.text.removeSuffix("*/").trim().endsWith("=") }
fun List<KtValueArgument>.resolve(
resolvedCall: ResolvedCall<out CallableDescriptor>
): List<Pair<KtValueArgument, ValueParameterDescriptor>> =
mapNotNull {
if (it is KtLambdaArgument) return@mapNotNull null
val parameter = resolvedCall.getArgumentMapping(it).safeAs<ArgumentMatch>()?.valueParameter ?: return@mapNotNull null
it to parameter
}
}
}
| apache-2.0 | 930629a3dc2f72e5b28e0ec8bfc2b297 | 52.582418 | 158 | 0.710623 | 5.411765 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223JvmScriptEngine4Idea.kt | 4 | 4153 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.jsr223
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.repl.*
import org.jetbrains.kotlin.daemon.client.DaemonReportMessage
import org.jetbrains.kotlin.daemon.client.DaemonReportingTargets
import org.jetbrains.kotlin.daemon.client.KotlinCompilerClient
import org.jetbrains.kotlin.daemon.client.KotlinRemoteReplCompilerClient
import org.jetbrains.kotlin.daemon.common.*
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.utils.KotlinPaths
import org.jetbrains.kotlin.utils.KotlinPathsFromHomeDir
import java.io.File
import java.util.concurrent.locks.ReentrantReadWriteLock
import javax.script.ScriptContext
import javax.script.ScriptEngineFactory
import javax.script.ScriptException
import kotlin.io.path.exists
import kotlin.reflect.KClass
// TODO: need to manage resources here, i.e. call replCompiler.dispose when engine is collected
class KotlinJsr223JvmScriptEngine4Idea(
factory: ScriptEngineFactory,
templateClasspath: List<File>,
templateClassName: String,
private val getScriptArgs: (ScriptContext, Array<out KClass<out Any>>?) -> ScriptArgsWithTypes?,
private val scriptArgsTypes: Array<out KClass<out Any>>?
) : KotlinJsr223JvmScriptEngineBase(factory) {
private val daemon by lazy {
val libPath = KotlinPathsFromHomeDir(KotlinPluginLayout.kotlinc)
val classPath = libPath.classPath(KotlinPaths.ClassPaths.CompilerWithScripting)
assert(classPath.all { it.toPath().exists() })
val compilerId = CompilerId.makeCompilerId(classPath)
val daemonOptions = configureDaemonOptions()
val daemonJVMOptions = DaemonJVMOptions()
val daemonReportMessages = arrayListOf<DaemonReportMessage>()
KotlinCompilerClient.connectToCompileService(
compilerId, daemonJVMOptions, daemonOptions,
DaemonReportingTargets(null, daemonReportMessages),
autostart = true, checkId = true
) ?: throw ScriptException(
"Unable to connect to repl server:" + daemonReportMessages.joinToString("\n ", prefix = "\n ") {
"${it.category.name} ${it.message}"
}
)
}
private val messageCollector = MyMessageCollector()
override val replCompiler: ReplCompilerWithoutCheck by lazy {
KotlinRemoteReplCompilerClient(
daemon,
makeAutodeletingFlagFile("idea-jsr223-repl-session"),
CompileService.TargetPlatform.JVM,
emptyArray(),
messageCollector,
templateClasspath,
templateClassName
)
}
override fun overrideScriptArgs(context: ScriptContext): ScriptArgsWithTypes? =
getScriptArgs(getContext(), scriptArgsTypes)
private val localEvaluator: ReplFullEvaluator by lazy {
GenericReplCompilingEvaluator(replCompiler, templateClasspath, Thread.currentThread().contextClassLoader)
}
override val replEvaluator: ReplFullEvaluator get() = localEvaluator
override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*> = replEvaluator.createState(lock)
private class MyMessageCollector : MessageCollector {
private var hasErrors: Boolean = false
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?) {
System.err.println(message) // TODO: proper location printing
if (!hasErrors) {
hasErrors = severity == CompilerMessageSeverity.EXCEPTION || severity == CompilerMessageSeverity.ERROR
}
}
override fun clear() {}
override fun hasErrors(): Boolean = hasErrors
}
}
| apache-2.0 | a341372c1d4d8ba556546cd98af3a97d | 42.260417 | 158 | 0.742596 | 4.920616 | false | false | false | false |
ianhanniballake/muzei | main/src/main/java/com/google/android/apps/muzei/util/ScrimUtil.kt | 2 | 3515 | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.util
import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Shader
import android.graphics.drawable.Drawable
import android.graphics.drawable.PaintDrawable
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RectShape
import android.util.LruCache
import android.view.Gravity
import kotlin.math.max
import kotlin.math.pow
private val cubicGradientScrimCache = LruCache<Int, Drawable>(10)
/**
* Creates an approximated cubic gradient using a multi-stop linear gradient. See
* [this post](https://plus.google.com/+RomanNurik/posts/2QvHVFWrHZf) for more
* details.
*/
@SuppressLint("RtlHardcoded")
fun makeCubicGradientScrimDrawable(
gravity: Int,
alpha: Int = 0xFF,
red: Int = 0x0,
green: Int = 0x0,
blue: Int = 0x0,
requestedStops: Int = 8
): Drawable {
var numStops = requestedStops
// Generate a cache key by hashing together the inputs, based on the method described in the Effective Java book
var cacheKeyHash = Color.argb(alpha, red, green, blue)
cacheKeyHash = 31 * cacheKeyHash + numStops
cacheKeyHash = 31 * cacheKeyHash + gravity
val cachedGradient = cubicGradientScrimCache.get(cacheKeyHash)
if (cachedGradient != null) {
return cachedGradient
}
numStops = max(numStops, 2)
val paintDrawable = PaintDrawable().apply {
shape = RectShape()
}
val stopColors = IntArray(numStops)
for (i in 0 until numStops) {
val x = i * 1f / (numStops - 1)
val opacity = x.toDouble().pow(3.0).toFloat().constrain(0f, 1f)
stopColors[i] = Color.argb((alpha * opacity).toInt(), red, green, blue)
}
val x0: Float
val x1: Float
val y0: Float
val y1: Float
when (gravity and Gravity.HORIZONTAL_GRAVITY_MASK) {
Gravity.LEFT -> {
x0 = 1f
x1 = 0f
}
Gravity.RIGHT -> {
x0 = 0f
x1 = 1f
}
else -> {
x0 = 0f
x1 = 0f
}
}
when (gravity and Gravity.VERTICAL_GRAVITY_MASK) {
Gravity.TOP -> {
y0 = 1f
y1 = 0f
}
Gravity.BOTTOM -> {
y0 = 0f
y1 = 1f
}
else -> {
y0 = 0f
y1 = 0f
}
}
paintDrawable.shaderFactory = object : ShapeDrawable.ShaderFactory() {
override fun resize(width: Int, height: Int): Shader {
return LinearGradient(
width * x0,
height * y0,
width * x1,
height * y1,
stopColors, null,
Shader.TileMode.CLAMP)
}
}
cubicGradientScrimCache.put(cacheKeyHash, paintDrawable)
return paintDrawable
} | apache-2.0 | 6a207c715e82c7b7917b3d0f3beee425 | 28.057851 | 116 | 0.62276 | 4.106308 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/asJava/fields/FirLightFieldForPropertySymbol.kt | 2 | 4454 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.asJava
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin
import org.jetbrains.kotlin.asJava.classes.lazyPub
import org.jetbrains.kotlin.asJava.elements.FirLightIdentifier
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.idea.frontend.api.isValid
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtKotlinPropertySymbol
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtPropertySymbol
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtSimpleConstantValue
import org.jetbrains.kotlin.psi.KtDeclaration
internal class FirLightFieldForPropertySymbol(
private val propertySymbol: KtPropertySymbol,
private val fieldName: String,
containingClass: FirLightClassBase,
lightMemberOrigin: LightMemberOrigin?,
isTopLevel: Boolean,
forceStatic: Boolean,
takePropertyVisibility: Boolean
) : FirLightField(containingClass, lightMemberOrigin) {
override val kotlinOrigin: KtDeclaration? = propertySymbol.psi as? KtDeclaration
private val _returnedType: PsiType by lazyPub {
propertySymbol.annotatedType.asPsiType(
propertySymbol,
this@FirLightFieldForPropertySymbol,
FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE
)
}
private val _isDeprecated: Boolean by lazyPub {
propertySymbol.hasDeprecatedAnnotation(AnnotationUseSiteTarget.FIELD)
}
override fun isDeprecated(): Boolean = _isDeprecated
private val _identifier: PsiIdentifier by lazyPub {
FirLightIdentifier(this, propertySymbol)
}
override fun getNameIdentifier(): PsiIdentifier = _identifier
override fun getType(): PsiType = _returnedType
override fun getName(): String = fieldName
private val _modifierList: PsiModifierList by lazyPub {
val modifiers = mutableSetOf<String>()
val suppressFinal = !propertySymbol.isVal
propertySymbol.computeModalityForMethod(
isTopLevel = isTopLevel,
suppressFinal = suppressFinal,
result = modifiers
)
if (forceStatic) {
modifiers.add(PsiModifier.STATIC)
}
val visibility =
if (takePropertyVisibility) propertySymbol.toPsiVisibilityForMember(isTopLevel = false) else PsiModifier.PRIVATE
modifiers.add(visibility)
if (!suppressFinal) {
modifiers.add(PsiModifier.FINAL)
}
if (propertySymbol.hasAnnotation("kotlin/jvm/Transient", null)) {
modifiers.add(PsiModifier.TRANSIENT)
}
if (propertySymbol.hasAnnotation("kotlin/jvm/Volatile", null)) {
modifiers.add(PsiModifier.VOLATILE)
}
val nullability = if (!(propertySymbol is KtKotlinPropertySymbol && propertySymbol.isLateInit))
propertySymbol.annotatedType.type.getTypeNullability(propertySymbol, FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE)
else NullabilityType.Unknown
val annotations = propertySymbol.computeAnnotations(
parent = this,
nullability = nullability,
annotationUseSiteTarget = AnnotationUseSiteTarget.FIELD,
)
FirLightClassModifierList(this, modifiers, annotations)
}
override fun getModifierList(): PsiModifierList = _modifierList
private val _initializer by lazyPub {
if (propertySymbol !is KtKotlinPropertySymbol) return@lazyPub null
if (!propertySymbol.isConst) return@lazyPub null
if (!propertySymbol.isVal) return@lazyPub null
(propertySymbol.initializer as? KtSimpleConstantValue<*>)?.createPsiLiteral(this)
}
override fun getInitializer(): PsiExpression? = _initializer
override fun equals(other: Any?): Boolean =
this === other ||
(other is FirLightFieldForPropertySymbol &&
kotlinOrigin == other.kotlinOrigin &&
propertySymbol == other.propertySymbol)
override fun hashCode(): Int = kotlinOrigin.hashCode()
override fun isValid(): Boolean = super.isValid() && propertySymbol.isValid()
} | apache-2.0 | 066b89c4020bdec736516ebf777fedfa | 36.436975 | 125 | 0.715761 | 5.379227 | false | false | false | false |
android/sunflower | app/src/main/java/com/google/samples/apps/sunflower/PlantDetailFragment.kt | 1 | 3431 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.sunflower
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.core.app.ShareCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.google.android.material.composethemeadapter.MdcTheme
import com.google.samples.apps.sunflower.compose.plantdetail.PlantDetailsScreen
import com.google.samples.apps.sunflower.viewmodels.PlantDetailViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlin.text.Typography.dagger
/**
* A fragment representing a single Plant detail screen.
*/
@AndroidEntryPoint
class PlantDetailFragment : Fragment() {
private val plantDetailViewModel: PlantDetailViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = ComposeView(requireContext()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
// Create a Compose MaterialTheme inheriting the existing colors, typography
// and shapes of the current View system's theme
MdcTheme {
PlantDetailsScreen(
plantDetailViewModel,
onBackClick = {
findNavController().navigateUp()
},
onShareClick = {
createShareIntent()
}
)
}
}
}
private fun navigateToGallery() {
plantDetailViewModel.plant.value?.let { plant ->
val direction =
PlantDetailFragmentDirections.actionPlantDetailFragmentToGalleryFragment(plant.name)
findNavController().navigate(direction)
}
}
// Helper function for calling a share functionality.
// Should be used when user presses a share button/menu item.
@Suppress("DEPRECATION")
private fun createShareIntent() {
val shareText = plantDetailViewModel.plant.value.let { plant ->
if (plant == null) {
""
} else {
getString(R.string.share_text_plant, plant.name)
}
}
val shareIntent = ShareCompat.IntentBuilder.from(requireActivity())
.setText(shareText)
.setType("text/plain")
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
startActivity(shareIntent)
}
}
| apache-2.0 | d9d41b3e00d70e0788907a98b87a84dd | 35.892473 | 100 | 0.682891 | 5.238168 | false | false | false | false |
StuStirling/ribot-viewer | data/src/main/java/com/stustirling/ribotviewer/data/local/model/LocalRibot.kt | 1 | 718 | package com.stustirling.ribotviewer.data.local.model
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import java.util.*
/**
* Created by Stu Stirling on 23/09/2017.
*/
@Entity(tableName = "ribots")
data class LocalRibot(
@PrimaryKey var id: String,
@ColumnInfo(name = "first_name") var firstName: String,
@ColumnInfo(name = "last_name") var lastName: String,
var email: String,
@ColumnInfo(name = "dob") var dateOfBirth: Date,
var color: String,
var bio: String? = null,
var avatar: String? = null,
@ColumnInfo(name = "active") var isActive: Boolean) | apache-2.0 | d8c16f869a49c8eea6329e58afb1b95e | 33.238095 | 63 | 0.681058 | 3.798942 | false | false | false | false |
clumsy/intellij-community | platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/VariableView.kt | 2 | 19579 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.util.SmartList
import com.intellij.util.ThreeState
import com.intellij.xdebugger.XSourcePositionWrapper
import com.intellij.xdebugger.frame.*
import com.intellij.xdebugger.frame.presentation.XKeywordValuePresentation
import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation
import com.intellij.xdebugger.frame.presentation.XStringValuePresentation
import com.intellij.xdebugger.frame.presentation.XValuePresentation
import org.jetbrains.concurrency.*
import org.jetbrains.debugger.values.*
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.regex.Pattern
import javax.swing.Icon
fun VariableView(variable: Variable, context: VariableContext) = VariableView(variable.name, variable, context)
class VariableView(name: String, private val variable: Variable, private val context: VariableContext) : XNamedValue(name), VariableContext {
@Volatile private var value: Value? = null
// lazy computed
private var memberFilter: MemberFilter? = null
@Volatile private var remainingChildren: List<Variable>? = null
@Volatile private var remainingChildrenOffset: Int = 0
override fun watchableAsEvaluationExpression() = context.watchableAsEvaluationExpression()
override fun getViewSupport() = context.viewSupport
override fun getParent() = context
override fun getMemberFilter(): Promise<MemberFilter> {
return context.viewSupport.getMemberFilter(this)
}
override fun computePresentation(node: XValueNode, place: XValuePlace) {
value = variable.value
if (value != null) {
computePresentation(value!!, node)
return
}
if (variable !is ObjectProperty || variable.getter == null) {
// it is "used" expression (WEB-6779 Debugger/Variables: Automatically show used variables)
evaluateContext.evaluate(variable.name)
.done(node) {
if (it.wasThrown) {
setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(value, null), null, node)
}
else {
value = it.value
computePresentation(it.value, node)
}
}
.rejected(node) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(null, it.message), it.message, node) }
return
}
node.setPresentation(null, object : XValuePresentation() {
override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) {
renderer.renderValue("\u2026")
}
}, false)
node.setFullValueEvaluator(object : XFullValueEvaluator(" (invoke getter)") {
override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) {
val valueModifier = variable.valueModifier
assert(valueModifier != null)
valueModifier!!.evaluateGet(variable, evaluateContext)
.done(node) {
callback.evaluated("")
setEvaluatedValue(it, null, node)
}
}
}.setShowValuePopup(false))
}
private fun setEvaluatedValue(value: Value?, error: String?, node: XValueNode) {
if (value == null) {
node.setPresentation(AllIcons.Debugger.Db_primitive, null, error ?: "Internal Error", false)
}
else {
this.value = value
computePresentation(value, node)
}
}
private fun computePresentation(value: Value, node: XValueNode) {
when (value.type) {
ValueType.OBJECT, ValueType.NODE -> context.viewSupport.computeObjectPresentation((value as ObjectValue), variable, context, node, icon)
ValueType.FUNCTION -> node.setPresentation(icon, ObjectValuePresentation(trimFunctionDescription(value)), true)
ValueType.ARRAY -> context.viewSupport.computeArrayPresentation(value, variable, context, node, icon)
ValueType.BOOLEAN, ValueType.NULL, ValueType.UNDEFINED -> node.setPresentation(icon, XKeywordValuePresentation(value.valueString!!), false)
ValueType.NUMBER -> node.setPresentation(icon, createNumberPresentation(value.valueString!!), false)
ValueType.STRING -> {
node.setPresentation(icon, XStringValuePresentation(value.valueString!!), false)
// isTruncated in terms of debugger backend, not in our terms (i.e. sometimes we cannot control truncation),
// so, even in case of StringValue, we check value string length
if ((value is StringValue && value.isTruncated) || value.valueString!!.length > XValueNode.MAX_VALUE_LENGTH) {
node.setFullValueEvaluator(MyFullValueEvaluator(value))
}
}
else -> node.setPresentation(icon, null, value.valueString!!, true)
}
}
override fun computeChildren(node: XCompositeNode) {
node.setAlreadySorted(true)
if (value !is ObjectValue) {
node.addChildren(XValueChildrenList.EMPTY, true)
return
}
val list = remainingChildren
if (list != null) {
val to = Math.min(remainingChildrenOffset + XCompositeNode.MAX_CHILDREN_TO_SHOW, list.size)
val isLast = to == list.size
node.addChildren(createVariablesList(list, remainingChildrenOffset, to, this, memberFilter), isLast)
if (!isLast) {
node.tooManyChildren(list.size - to)
remainingChildrenOffset += XCompositeNode.MAX_CHILDREN_TO_SHOW
}
return
}
val objectValue = value as ObjectValue
val hasNamedProperties = objectValue.hasProperties() != ThreeState.NO
val hasIndexedProperties = objectValue.hasIndexedProperties() != ThreeState.NO
val promises = SmartList<Promise<*>>()
val additionalProperties = viewSupport.computeAdditionalObjectProperties(objectValue, variable, this, node)
if (additionalProperties != null) {
promises.add(additionalProperties)
}
// we don't support indexed properties if additional properties added - behavior is undefined if object has indexed properties and additional properties also specified
if (hasIndexedProperties) {
promises.add(computeIndexedProperties(objectValue as ArrayValue, node, !hasNamedProperties && additionalProperties == null))
}
if (hasNamedProperties) {
// named properties should be added after additional properties
if (additionalProperties == null || additionalProperties.state != Promise.State.PENDING) {
promises.add(computeNamedProperties(objectValue, node, !hasIndexedProperties && additionalProperties == null))
}
else {
promises.add(additionalProperties.thenAsync(node) { computeNamedProperties(objectValue, node, true) })
}
}
if (hasIndexedProperties == hasNamedProperties || additionalProperties != null) {
Promise.all(promises).processed(object : ObsolescentConsumer<Any?>(node) {
override fun consume(aVoid: Any?) = node.addChildren(XValueChildrenList.EMPTY, true)
})
}
}
abstract class ObsolescentIndexedVariablesConsumer(protected val node: XCompositeNode) : IndexedVariablesConsumer() {
override fun isObsolete() = node.isObsolete
}
private fun computeIndexedProperties(value: ArrayValue, node: XCompositeNode, isLastChildren: Boolean): Promise<*> {
return value.getIndexedProperties(0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, object : ObsolescentIndexedVariablesConsumer(node) {
override fun consumeRanges(ranges: IntArray?) {
if (ranges == null) {
val groupList = XValueChildrenList()
LazyVariablesGroup.addGroups(value, LazyVariablesGroup.GROUP_FACTORY, groupList, 0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, this@VariableView)
node.addChildren(groupList, isLastChildren)
}
else {
LazyVariablesGroup.addRanges(value, ranges, node, this@VariableView, isLastChildren)
}
}
override fun consumeVariables(variables: List<Variable>) {
node.addChildren(createVariablesList(variables, this@VariableView, null), isLastChildren)
}
}, null)
}
private fun computeNamedProperties(value: ObjectValue, node: XCompositeNode, isLastChildren: Boolean) = processVariables(this, value.properties, node) { memberFilter, variables ->
[email protected] = memberFilter
if (value.type == ValueType.ARRAY && value !is ArrayValue) {
computeArrayRanges(variables, node)
return@processVariables
}
var functionValue = value as? FunctionValue
if (functionValue != null && functionValue.hasScopes() == ThreeState.NO) {
functionValue = null
}
remainingChildren = processNamedObjectProperties(variables, node, this@VariableView, memberFilter, XCompositeNode.MAX_CHILDREN_TO_SHOW, isLastChildren && functionValue == null)
if (remainingChildren != null) {
remainingChildrenOffset = XCompositeNode.MAX_CHILDREN_TO_SHOW
}
if (functionValue != null) {
// we pass context as variable context instead of this variable value - we cannot watch function scopes variables, so, this variable name doesn't matter
node.addChildren(XValueChildrenList.bottomGroup(FunctionScopesValueGroup(functionValue, context)), isLastChildren)
}
}
private fun computeArrayRanges(properties: List<Variable>, node: XCompositeNode) {
val variables = filterAndSort(properties, memberFilter!!)
var count = variables.size
val bucketSize = XCompositeNode.MAX_CHILDREN_TO_SHOW
if (count <= bucketSize) {
node.addChildren(createVariablesList(variables, this, null), true)
return
}
while (count > 0) {
if (Character.isDigit(variables.get(count - 1).name[0])) {
break
}
count--
}
val groupList = XValueChildrenList()
if (count > 0) {
LazyVariablesGroup.addGroups(variables, VariablesGroup.GROUP_FACTORY, groupList, 0, count, bucketSize, this)
}
var notGroupedVariablesOffset: Int
if ((variables.size - count) > bucketSize) {
notGroupedVariablesOffset = variables.size
while (notGroupedVariablesOffset > 0) {
if (!variables.get(notGroupedVariablesOffset - 1).name.startsWith("__")) {
break
}
notGroupedVariablesOffset--
}
if (notGroupedVariablesOffset > 0) {
LazyVariablesGroup.addGroups(variables, VariablesGroup.GROUP_FACTORY, groupList, count, notGroupedVariablesOffset, bucketSize, this)
}
}
else {
notGroupedVariablesOffset = count
}
for (i in notGroupedVariablesOffset..variables.size - 1) {
val variable = variables.get(i)
groupList.add(VariableView(memberFilter!!.rawNameToSource(variable), variable, this))
}
node.addChildren(groupList, true)
}
private val icon: Icon
get() = getIcon(value!!)
override fun getModifier(): XValueModifier? {
if (!variable.isMutable) {
return null
}
return object : XValueModifier() {
override fun getInitialValueEditorText(): String? {
if (value!!.type == ValueType.STRING) {
val string = value!!.valueString!!
val builder = StringBuilder(string.length)
builder.append('"')
StringUtil.escapeStringCharacters(string.length, string, builder)
builder.append('"')
return builder.toString()
}
else {
return if (value!!.type.isObjectType) null else value!!.valueString
}
}
override fun setValue(expression: String, callback: XValueModifier.XModificationCallback) {
variable.valueModifier!!.setValue(variable, expression, evaluateContext)
.done {
value = null
callback.valueModified()
}
.rejected { callback.errorOccurred(it.message!!) }
}
}
}
override fun getEvaluateContext() = context.evaluateContext
fun getValue() = variable.value
override fun canNavigateToSource() = value is FunctionValue || viewSupport.canNavigateToSource(variable, context)
override fun computeSourcePosition(navigatable: XNavigatable) {
if (value is FunctionValue) {
(value as FunctionValue).resolve()
.done { function ->
viewSupport.vm!!.scriptManager.getScript(function)
.done {
val position = if (it == null) null else viewSupport.getSourceInfo(null, it, function.openParenLine, function.openParenColumn)
navigatable.setSourcePosition(if (position == null)
null
else
object : XSourcePositionWrapper(position) {
override fun createNavigatable(project: Project): Navigatable {
val result = PsiVisitors.visit(myPosition, project, object : PsiVisitors.Visitor<Navigatable>() {
override fun visit(element: PsiElement, positionOffset: Int, document: Document): Navigatable? {
// element will be "open paren", but we should navigate to function name,
// we cannot use specific PSI type here (like JSFunction), so, we try to find reference expression (i.e. name expression)
var referenceCandidate: PsiElement? = element
var psiReference: PsiElement? = null
while (true) {
referenceCandidate = referenceCandidate?.prevSibling ?: break
if (referenceCandidate is PsiReference) {
psiReference = referenceCandidate
break
}
}
if (psiReference == null) {
referenceCandidate = element.parent
while (true) {
referenceCandidate = referenceCandidate?.prevSibling ?: break
if (referenceCandidate is PsiReference) {
psiReference = referenceCandidate
break
}
}
}
return (if (psiReference == null) element.navigationElement else psiReference.navigationElement) as? Navigatable
}
}, null)
return result ?: super.createNavigatable(project)
}
})
}
}
}
else {
viewSupport.computeSourcePosition(name, value!!, variable, context, navigatable)
}
}
override fun computeInlineDebuggerData(callback: XInlineDebuggerDataCallback) = viewSupport.computeInlineDebuggerData(name, variable, context, callback)
override fun getEvaluationExpression(): String? {
if (!watchableAsEvaluationExpression()) {
return null
}
val list = SmartList(variable.name)
var parent: VariableContext? = context
while (parent != null && parent.name != null) {
list.add(parent.name!!)
parent = parent.parent
}
return context.viewSupport.propertyNamesToString(list, false)
}
private class MyFullValueEvaluator(private val value: Value) : XFullValueEvaluator(if (value is StringValue) value.length else value.valueString!!.length) {
override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) {
if (value !is StringValue || !value.isTruncated) {
callback.evaluated(value.valueString!!)
return
}
val evaluated = AtomicBoolean()
value.fullString
.done {
if (!callback.isObsolete && evaluated.compareAndSet(false, true)) {
callback.evaluated(value.valueString!!)
}
}
.rejected { callback.errorOccurred(it.message!!) }
}
}
override fun getScope() = context.scope
companion object {
fun setObjectPresentation(value: ObjectValue, icon: Icon, node: XValueNode) {
node.setPresentation(icon, ObjectValuePresentation(getObjectValueDescription(value)), value.hasProperties() != ThreeState.NO)
}
fun setArrayPresentation(value: Value, context: VariableContext, icon: Icon, node: XValueNode) {
assert(value.type == ValueType.ARRAY)
if (value is ArrayValue) {
val length = value.length
node.setPresentation(icon, ArrayPresentation(length, value.className), length > 0)
return
}
val valueString = value.valueString
// only WIP reports normal description
if (valueString != null && valueString.endsWith("]") && ARRAY_DESCRIPTION_PATTERN.matcher(valueString).find()) {
node.setPresentation(icon, null, valueString, true)
}
else {
context.evaluateContext.evaluate("a.length", Collections.singletonMap<String, Any>("a", value), false)
.done(node) { node.setPresentation(icon, null, "Array[${it.value.valueString}]", true) }
.rejected(node) { node.setPresentation(icon, null, "Internal error: $it", false) }
}
}
fun getIcon(value: Value): Icon {
val type = value.type
return when (type) {
ValueType.FUNCTION -> AllIcons.Nodes.Function
ValueType.ARRAY -> AllIcons.Debugger.Db_array
else -> if (type.isObjectType) AllIcons.Debugger.Value else AllIcons.Debugger.Db_primitive
}
}
}
}
fun getClassName(value: ObjectValue): String {
val className = value.className
return if (className.isNullOrEmpty()) "Object" else className!!
}
fun getObjectValueDescription(value: ObjectValue): String {
val description = value.valueString
return if (description.isNullOrEmpty()) getClassName(value) else description!!
}
internal fun trimFunctionDescription(value: Value): String {
val presentableValue = value.valueString ?: return ""
var endIndex = 0
while (endIndex < presentableValue.length && !StringUtil.isLineBreak(presentableValue[endIndex])) {
endIndex++
}
while (endIndex > 0 && Character.isWhitespace(presentableValue[endIndex - 1])) {
endIndex--
}
return presentableValue.substring(0, endIndex)
}
private fun createNumberPresentation(value: String): XValuePresentation {
return if (value == PrimitiveValue.NA_N_VALUE || value == PrimitiveValue.INFINITY_VALUE) XKeywordValuePresentation(value) else XNumericValuePresentation(value)
}
private val ARRAY_DESCRIPTION_PATTERN = Pattern.compile("^[a-zA-Z\\d]+\\[\\d+\\]$")
private class ArrayPresentation(length: Int, className: String?) : XValuePresentation() {
private val length = Integer.toString(length)
private val className = if (className.isNullOrEmpty()) "Array" else className!!
override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) {
renderer.renderSpecialSymbol(className)
renderer.renderSpecialSymbol("[")
renderer.renderSpecialSymbol(length)
renderer.renderSpecialSymbol("]")
}
}
| apache-2.0 | c1661e833e9f97f39e17fcd35232f4a5 | 39.452479 | 181 | 0.683845 | 5.133456 | false | false | false | false |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/com/COMAdventureNotesFragment.kt | 1 | 3476 | package pt.joaomneto.titancompanion.adventure.impl.fragments.com
import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView.OnItemLongClickListener
import android.widget.ArrayAdapter
import android.widget.EditText
import kotlinx.android.synthetic.main.fragment_30com_adventure_notes.*
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventure.impl.COMAdventure
import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureNotesFragment
class COMAdventureNotesFragment : AdventureNotesFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
baseLayout = R.layout.fragment_30com_adventure_notes
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adv = this.activity as COMAdventure
buttonAddCypher.setOnClickListener(
OnClickListener {
val alert = AlertDialog.Builder(adv)
alert.setTitle(R.string.note)
// Set an EditText view to get user input
val input = EditText(adv)
val imm = adv.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT)
input.requestFocus()
alert.setView(input)
alert.setPositiveButton(
R.string.ok,
{ _, _ ->
val value = input.text.toString()
if (value.isNotBlank()) {
adv.cyphers = adv.cyphers.plus(value.trim { it <= ' ' })
(cypherList!!.adapter as ArrayAdapter<String>).notifyDataSetChanged()
}
}
)
alert.setNegativeButton(
R.string.cancel
) { _, _ ->
// Canceled.
}
alert.show()
}
)
val adapter = ArrayAdapter(
adv,
android.R.layout.simple_list_item_1, android.R.id.text1, adv.cyphers
)
cypherList.adapter = adapter
cypherList.onItemLongClickListener = OnItemLongClickListener { _, _, arg2, _ ->
val builder = AlertDialog.Builder(adv)
builder.setTitle(R.string.deleteKeyword)
.setCancelable(false)
.setNegativeButton(
R.string.close
) { dialog, _ -> dialog.cancel() }
builder.setPositiveButton(R.string.ok) { _, _ ->
adv.cyphers = adv.cyphers.minus(adv.cyphers[arg2])
(cypherList!!.adapter as ArrayAdapter<String>).notifyDataSetChanged()
}
val alert = builder.create()
alert.show()
true
}
}
override fun refreshScreensFromResume() {
super.refreshScreensFromResume()
(cypherList.adapter as ArrayAdapter<String>).notifyDataSetChanged()
}
}
| lgpl-3.0 | c5b810eb5faf4d1fa4525245250d6a95 | 34.469388 | 98 | 0.604143 | 5.266667 | false | false | false | false |
glorantq/KalanyosiRamszesz | src/glorantq/ramszesz/commands/OsuCommand.kt | 1 | 7242 | package glorantq.ramszesz.commands
import com.cedarsoftware.util.io.JsonWriter
import com.overzealous.remark.Remark
import glorantq.ramszesz.osuKey
import glorantq.ramszesz.utils.BotUtils
import okhttp3.*
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import sx.blah.discord.util.EmbedBuilder
import java.io.IOException
import java.net.URLEncoder
import java.text.DecimalFormat
import java.util.*
import java.util.regex.Pattern
class OsuCommand : ICommand {
override val commandName: String
get() = "osu"
override val description: String
get() = "Check an osu! player's stats"
override val permission: Permission
get() = Permission.USER
override val usage: String
get() = "username"
override val availableInDM: Boolean
get() = true
private val httpClient: OkHttpClient by lazy { OkHttpClient.Builder().build() }
private val numberFormat: DecimalFormat = DecimalFormat("###,###")
/*
<:A_small:352910388892925953>
<:B_small:352910392210620417>
<:C_small:352910397734387713>
<:D_small:352910397529128961>
<:S_small:352910397667409931>
<:SH_small:352910397755359233>
<:XH_small:352910397897965568>
*/
override fun execute(event: MessageReceivedEvent, args: List<String>) {
if (args.isEmpty()) {
BotUtils.sendUsageEmbed("Specify a user!", "osu! statistics", event.author, event, this)
} else {
val username: String = buildString {
for(s: String in args) {
append(s)
append(" ")
}
setLength(length - 1)
}
val encodedName: String = URLEncoder.encode(username, "UTF-8").replace("+", "%20")
val requestURL: String = "https://osu.ppy.sh/api/get_user?k=$osuKey&u=$encodedName"
val request: Request = Request.Builder().url(requestURL).get().build()
httpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(p0: Call, p1: IOException) {
BotUtils.sendMessage(BotUtils.createSimpleEmbed("osu! statistics", "Failed to look up `$username`'s stats because @glorantq can't code!", event.author), event.channel)
}
override fun onResponse(p0: Call, p1: Response) {
val rawJson: String = p1.body()!!.string()
val root: Any = JSONParser().parse(rawJson)
if (root is JSONObject) {
BotUtils.sendMessage(BotUtils.createSimpleEmbed("osu! statistics", buildString {
append("Failed to look up `$username`'s stats because @glorantq can't code!")
if (root.containsKey("error")) {
append(" (${root["error"].toString()})")
}
}, event.author), event.channel)
return
}
root as JSONArray
if (root.isEmpty()) {
BotUtils.sendMessage(BotUtils.createSimpleEmbed("osu! statistics", "The user `$username` is invalid!", event.author), event.channel)
return
}
val user: JSONObject = root[0] as JSONObject
val embed: EmbedBuilder = BotUtils.embed("osu! statistics for ${user["username"]}", event.author)
embed.withAuthorUrl("https://osu.ppy.sh/u/$encodedName")
embed.withAuthorIcon("https://osu.ppy.sh/images/layout/osu-logo.png")
embed.withThumbnail("https://a.ppy.sh/${user["user_id"]}")
embed.appendField("PP", formatNumber(user["pp_raw"]), true)
embed.appendField("Global Rank", "#${user["pp_rank"]}", true)
embed.appendField("Country", ":flag_${user["country"].toString().toLowerCase()}: ${Locale("", user["country"].toString()).displayCountry}", true)
embed.appendField("Country Rank", "#${user["pp_country_rank"]}", true)
embed.appendField("Ranked Score", formatNumber(user["ranked_score"]), true)
embed.appendField("Total Score", formatNumber(user["total_score"]), true)
embed.appendField("Level", formatNumber(user["level"]), true)
embed.appendField("Accuracy", "${String.format("%.2f", user["accuracy"].toString().toDouble())}%", true)
embed.appendField("Play Count", formatNumber(user["playcount"]), true)
embed.appendField("Ranks (SS/S/A)", "${user["count_rank_ss"]}/${user["count_rank_s"]}/${user["count_rank_a"]}", true)
val events: JSONArray = user["events"] as JSONArray
if(events.isNotEmpty()) {
val eventBuilder = StringBuilder()
for(osuEvent: Any? in events) {
osuEvent as JSONObject
var title: String = osuEvent["display_html"].toString()
title = title.replace("<img src='/images/A_small.png'/>", "<:A_small:352910388892925953>")
title = title.replace("<img src='/images/B_small.png'/>", "<:B_small:352910392210620417>")
title = title.replace("<img src='/images/C_small.png'/>", "<:C_small:352910397734387713>")
title = title.replace("<img src='/images/D_small.png'/>", "<:D_small:352910397529128961>")
title = title.replace("<img src='/images/S_small.png'/>", "<:S_small:352910397667409931>")
title = title.replace("<img src='/images/SH_small.png'/>", "<:SH_small:352910397755359233>")
title = title.replace("<img src='/images/XH_small.png'/>", "<:XH_small:352910397897965568>")
title = Remark().convert(title)
title = title.replace("\\_", "_")
if(eventBuilder.length + title.length > 1024) {
break
}
eventBuilder.append(title)
eventBuilder.append("\n")
}
eventBuilder.setLength(eventBuilder.length - 1)
embed.appendField("Recent Events", eventBuilder.toString(), false)
}
BotUtils.sendMessage(embed.build(), event.channel)
}
})
}
}
private fun formatNumber(input: Any?): String {
val number: Double =
Math.round(
try {
input.toString().toDouble()
} catch (e: Exception) {
e.printStackTrace()
-1.0
}).toDouble()
return numberFormat.format(number)
}
} | gpl-3.0 | 364014dcdfe10e490ce0d6027e2ecee4 | 47.610738 | 187 | 0.538111 | 4.81516 | false | false | false | false |
nonylene/GradleExternalBuildPlugin | src/net/nonylene/gradle/external/ExternalPreferenceProvider.kt | 1 | 813 | package net.nonylene.gradle.external
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.State
import com.intellij.openapi.components.StoragePathMacros
@State(name = "ExternalPreferenceProvider", storages = arrayOf(Storage(file = "${StoragePathMacros.APP_CONFIG}/externalBuild.xml")))
class ExternalPreferenceProvider : PersistentStateComponent<ExternalPreferenceProvider.State> {
class State {
var workingDirectory: String? = null
var program: String? = null
var parameters: String? = null
}
private var state: State? = State()
override fun getState(): State? {
return state
}
override fun loadState(state: State?) {
this.state = state
}
}
| mit | f7df0b016f4e58eab93a537ed77b9def | 30.269231 | 132 | 0.733087 | 4.672414 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/gui/view/window/chatroom/roominfo/RoomInfoView.kt | 1 | 4286 | package koma.gui.view.window.chatroom.roominfo
import de.jensd.fx.glyphs.materialicons.MaterialIcon
import de.jensd.fx.glyphs.materialicons.utils.MaterialIconFactory
import javafx.beans.property.SimpleBooleanProperty
import javafx.geometry.Pos
import javafx.scene.Scene
import javafx.scene.control.Hyperlink
import javafx.scene.control.TextField
import javafx.scene.layout.Priority
import javafx.stage.Stage
import javafx.stage.Window
import koma.gui.view.window.chatroom.roominfo.about.RoomAliasForm
import koma.gui.view.window.chatroom.roominfo.about.requests.chooseUpdateRoomIcon
import koma.gui.view.window.chatroom.roominfo.about.requests.requestUpdateRoomName
import koma.matrix.UserId
import koma.matrix.event.room_message.RoomEventType
import koma.matrix.room.naming.RoomId
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import link.continuum.database.models.getChangeStateAllowed
import link.continuum.desktop.database.RoomDataStorage
import link.continuum.desktop.database.hashColor
import link.continuum.desktop.gui.*
import link.continuum.desktop.gui.icon.avatar.Avatar2L
import link.continuum.desktop.gui.view.AccountContext
import link.continuum.desktop.util.getOrNull
class RoomInfoDialog(
datas: RoomDataStorage,
context: AccountContext,
room: RoomId, user: UserId
) {
private val scope = MainScope()
val root= VBox(10.0)
private val roomicon = Avatar2L()
val stage = Stage()
fun openWindow(owner: Window) {
stage.initOwner(owner)
stage.scene = Scene(root)
stage.show()
}
init {
stage.setOnHidden {
roomicon.cancelScope()
scope.cancel()
}
datas.latestAvatarUrl.receiveUpdates(room).onEach {
roomicon.updateUrl(it?.getOrNull(), context.account.server)
}.launchIn(scope)
val color = room.hashColor()
var name: String? = null
datas.latestDisplayName(room).onEach {
name = it
roomicon.updateName(it, color)
stage.title = "$it Info"
}.launchIn(scope)
val data = datas.data
val canEditName = SimpleBooleanProperty(false)
val canEditAvatar = SimpleBooleanProperty(false)
scope.launch {
val n =data.runOp {
getChangeStateAllowed(this, room, user, RoomEventType.Name.toString())
}
canEditName.set(n)
canEditAvatar.set(data.runOp {
getChangeStateAllowed(this, room, user, RoomEventType.Avatar.toString())
})
}
stage.title = "Update Info of Room"
val aliasDialog = RoomAliasForm(room, user, datas)
with(root) {
padding = UiConstants.insets5
hbox(5.0) {
vbox {
spacing = 5.0
hbox(5.0) {
alignment = Pos.CENTER
text("Name")
val input = TextField(name)
input.editableProperty().bind(canEditName)
add(input)
button("Set") {
removeWhen(canEditName.not())
action {
requestUpdateRoomName(room, input.text)
}
}
}
}
hbox { HBox.setHgrow(this, Priority.ALWAYS) }
vbox() {
spacing = 5.0
padding = UiConstants.insets5
alignment = Pos.CENTER
add(roomicon.root)
val camera = MaterialIconFactory.get().createIcon(MaterialIcon.PHOTO_CAMERA)
add(Hyperlink().apply {
graphic = camera
removeWhen(canEditAvatar.not())
setOnAction {
chooseUpdateRoomIcon(room)
}
})
}
}
add(aliasDialog.root)
}
}
}
| gpl-3.0 | 68372b517604248531638ff35aab6f72 | 36.269565 | 96 | 0.583994 | 4.756937 | false | false | false | false |
quran/quran_android | feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/SheikhDownloadSummary.kt | 2 | 3090 | package com.quran.mobile.feature.downloadmanager.ui
import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Surface
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.quran.data.model.audio.Qari
import com.quran.labs.androidquran.common.audio.model.QariItem
import com.quran.labs.androidquran.common.ui.core.QuranTheme
import com.quran.mobile.feature.downloadmanager.R
import com.quran.mobile.feature.downloadmanager.model.DownloadedSheikhUiModel
import com.quran.mobile.feature.downloadmanager.ui.common.DownloadCommonRow
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun SheikhDownloadSummary(
downloadedSheikhUiModel: DownloadedSheikhUiModel,
onQariItemClicked: ((QariItem) -> Unit)
) {
val (color, tintColor) = if (downloadedSheikhUiModel.downloadedSuras > 0) {
Color(0xff5e8900) to MaterialTheme.colorScheme.onPrimary
} else {
MaterialTheme.colorScheme.tertiary to MaterialTheme.colorScheme.onTertiary
}
DownloadCommonRow(
title = downloadedSheikhUiModel.qariItem.name,
subtitle = pluralStringResource(
R.plurals.audio_manager_files_downloaded,
downloadedSheikhUiModel.downloadedSuras, downloadedSheikhUiModel.downloadedSuras
),
onRowPressed = { onQariItemClicked(downloadedSheikhUiModel.qariItem) }
) {
Image(
painterResource(id = R.drawable.ic_download),
contentDescription = "",
colorFilter = ColorFilter.tint(tintColor),
modifier = Modifier
.align(Alignment.CenterVertically)
.clip(CircleShape)
.background(color)
.padding(8.dp)
)
}
}
@Preview
@Preview("arabic", locale = "ar")
@Preview("dark theme", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun SheikhDownloadSummaryPreview() {
val qari = Qari(
id = 1,
nameResource = com.quran.labs.androidquran.common.audio.R.string.qari_minshawi_murattal_gapless,
url = "https://download.quranicaudio.com/quran/muhammad_siddeeq_al-minshaawee/",
path = "minshawi_murattal",
hasGaplessAlternative = false,
db = "minshawi_murattal"
)
val downloadedSheikhModel = DownloadedSheikhUiModel(
QariItem.fromQari(LocalContext.current, qari),
downloadedSuras = 1
)
QuranTheme {
Surface(color = MaterialTheme.colorScheme.surface) {
SheikhDownloadSummary(downloadedSheikhUiModel = downloadedSheikhModel) { }
}
}
}
| gpl-3.0 | b966be99c150588b8ceb25cdf3d12e0b | 34.930233 | 100 | 0.78479 | 4.081902 | false | false | false | false |
rjhdby/motocitizen | Motocitizen/src/motocitizen/utils/MapUtils.kt | 1 | 1238 | package motocitizen.utils
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import motocitizen.content.accident.Accident
import motocitizen.dictionary.Medicine
import java.util.*
const val DEFAULT_ZOOM = 16f
private const val DENSE = 1f
private const val SEMI_DENSE = 0.5f
private const val TRANSPARENT = 0.2f
fun GoogleMap.accidentMarker(accident: Accident): Marker = addMarker(makeMarker(accident))
private fun calculateAlpha(accident: Accident): Float {
val age = ((Date().time - accident.time.time) / MS_IN_HOUR).toInt()
return when {
age < 2 -> DENSE
age < 6 -> SEMI_DENSE
else -> TRANSPARENT
}
}
private fun markerTitle(accident: Accident): String {
val medicine = if (accident.medicine === Medicine.NO) "" else ", " + accident.medicine.text
val interval = accident.time.getIntervalFromNowInText()
return "${accident.type.text}$medicine, $interval назад"
}
private fun makeMarker(accident: Accident) = MarkerOptions()
.position(accident.coordinates)
.title(markerTitle(accident))
.icon(accident.type.icon)
.alpha(calculateAlpha(accident))
| mit | 35d33bcd86209a7ff954776619e13754 | 32.324324 | 95 | 0.721817 | 3.829193 | false | false | false | false |
like5188/Common | common/src/main/java/com/like/common/view/dragview/entity/DragInfo.kt | 1 | 2264 | package com.like.common.view.dragview.entity
import android.os.Parcel
import android.os.Parcelable
/**
* @param originLeft 原始imageview的left
* @param originTop 原始imageview的top
* @param originWidth 原始imageview的width
* @param originHeight 原始imageview的height
* @param thumbImageUrl 缩略图的url
* @param imageUrl 原图url
* @param videoUrl 视频url
* @param isClicked 是否当前点击的那张图片
*/
class DragInfo(val originLeft: Float,
val originTop: Float,
val originWidth: Float,
val originHeight: Float,
val thumbImageUrl: String = "",
val imageUrl: String = "",
val videoUrl: String = "",
val isClicked: Boolean = false) : Parcelable {
// 下面是根据原始尺寸计算出来的辅助尺寸
var originCenterX: Float = originLeft + originWidth / 2
var originCenterY: Float = originTop + originHeight / 2
constructor(parcel: Parcel) : this(
parcel.readFloat(),
parcel.readFloat(),
parcel.readFloat(),
parcel.readFloat(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readByte() != 0.toByte()) {
originCenterX = parcel.readFloat()
originCenterY = parcel.readFloat()
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeFloat(originLeft)
parcel.writeFloat(originTop)
parcel.writeFloat(originWidth)
parcel.writeFloat(originHeight)
parcel.writeString(thumbImageUrl)
parcel.writeString(imageUrl)
parcel.writeString(videoUrl)
parcel.writeByte(if (isClicked) 1 else 0)
parcel.writeFloat(originCenterX)
parcel.writeFloat(originCenterY)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<DragInfo> {
override fun createFromParcel(parcel: Parcel): DragInfo {
return DragInfo(parcel)
}
override fun newArray(size: Int): Array<DragInfo?> {
return arrayOfNulls(size)
}
}
}
| apache-2.0 | b5eb088a084a6e756141aca61fc0e129 | 30.852941 | 65 | 0.610803 | 4.579281 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/db/dao/BookSyncDao.kt | 1 | 539 | package com.orgzly.android.db.dao
import androidx.room.*
import com.orgzly.android.db.entity.BookSync
@Dao
interface BookSyncDao : BaseDao<BookSync> {
@Query("SELECT * FROM book_syncs WHERE book_id = :bookId")
fun get(bookId: Long): BookSync?
@Transaction
fun upsert(bookId: Long, versionedRookId: Long) {
val sync = get(bookId)
if (sync == null) {
insert(BookSync(bookId, versionedRookId))
} else {
update(sync.copy(versionedRookId = versionedRookId))
}
}
}
| gpl-3.0 | d760f2d6e20699c69d39e0a36f4d864c | 24.666667 | 64 | 0.640074 | 3.61745 | false | false | false | false |
rjhdby/motocitizen | Motocitizen/src/motocitizen/utils/AccidentUtils.kt | 1 | 763 | package motocitizen.utils
import android.location.Location
import motocitizen.content.Content
import motocitizen.content.accident.Accident
import motocitizen.dictionary.Medicine
typealias Id = Int
fun Id.name() = Content.volunteerName(this)
fun Accident.getAccidentTextToCopy(): String {
val medicineText = if (medicine == Medicine.UNKNOWN) "" else medicine.text + ". "
return "${time.dateTimeString()} ${owner.name()}: ${type.text}.$medicineText $address. $description."
}
val Accident.latitude
inline get() = coordinates.latitude
val Accident.longitude
inline get() = coordinates.longitude
fun Accident.distanceString(): String = coordinates.distanceString()
fun Accident.distanceTo(location: Location) = coordinates.distanceTo(location) | mit | 9e031f1aa23f4421c4bc9036d3ab3ea7 | 29.56 | 105 | 0.770642 | 4.124324 | false | false | false | false |
badoualy/kotlogram | api/src/main/kotlin/com/github/badoualy/telegram/api/utils/TLMessageUtils.kt | 1 | 1694 | package com.github.badoualy.telegram.api.utils
import com.github.badoualy.telegram.tl.api.*
val TLAbsMessage?.date: Int
get() = when (this) {
is TLMessage -> date
is TLMessageService -> date
else -> 0
}
val TLAbsMessage?.fromId: Int?
get() = when (this) {
is TLMessage -> fromId
is TLMessageService -> fromId
else -> null
}
fun TLAbsMessage?.getMessageOrEmpty() = when (this) {
is TLMessage -> message!!
else -> ""
}
val TLAbsMessage?.toId: TLAbsPeer?
get() = when (this) {
is TLMessage -> toId
is TLMessageService -> toId
else -> null
}
val TLAbsMessage.isReply: Boolean
get() = this is TLMessage && replyToMsgId != null
val TLAbsMessage.replyToMsgId: Int?
get() = if (this is TLMessage) replyToMsgId else null
val TLMessage.isForward: Boolean
get() = fwdFrom != null
val TLAbsMessage.isSticker: Boolean
get() {
if (this !is TLMessage) return false
if (media == null || media !is TLMessageMediaDocument) return false
val media = this.media as TLMessageMediaDocument
if (media.document.isEmpty) return false
return media.document.asDocument.attributes.any { it is TLDocumentAttributeSticker }
}
fun TLAbsMessage.getStickerAlt() = when (isSticker) {
true -> ((this as? TLMessage)?.media as? TLMessageMediaDocument)?.document?.asDocument?.attributes
?.filterIsInstance<TLDocumentAttributeSticker>()?.first()?.alt
false -> null
}
fun TLAbsMessage.getSticker(): TLDocument? = when (isSticker) {
true -> ((this as? TLMessage)?.media as? TLMessageMediaDocument)?.document?.asDocument
false -> null
} | mit | 887e6ccd963112f33797c8ae28391932 | 29.267857 | 102 | 0.657615 | 4.245614 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/ProxerException.kt | 1 | 6107 | package me.proxer.library
import me.proxer.library.ProxerException.ErrorType
/**
* Common Exception for all errors, occurring around the api.
*
* [errorType] returns the general type of error. This could for example be an [ErrorType.IO] error,
* or invalid JSON data (leading to [ErrorType.PARSING]). If the type is [ErrorType.SERVER],
* [serverErrorType] returns the type of server error. Moreover, message is set in that case.
*
* @author Ruben Gees
*/
class ProxerException : Exception {
/**
* Returns the error type of this exception.
*/
val errorType: ErrorType
/**
* Returns the server error type if, and only if, [errorType] returns [ErrorType.SERVER].
*/
val serverErrorType: ServerErrorType?
/**
* Constructs an instance from the passed [error], [serverErrorType], [message] and [cause].
*/
@JvmOverloads
constructor(
errorType: ErrorType,
serverErrorType: ServerErrorType? = null,
message: String? = null,
cause: Exception? = null
) : super(message, cause) {
this.errorType = errorType
this.serverErrorType = serverErrorType
}
/**
* Constructs an instance from the passed [error], [serverErrorCode] and [message].
*
* If a invalid number is passed for the [serverErrorCode], an error is thrown.
*/
constructor(errorType: ErrorType, serverErrorCode: Int?, message: String?) : super(message) {
this.errorType = errorType
this.serverErrorType = ServerErrorType.fromErrorCode(serverErrorCode)
}
/**
* Enum containing the available general error types.
*/
enum class ErrorType {
SERVER,
TIMEOUT,
IO,
PARSING,
CANCELLED,
UNKNOWN
}
/**
* Enum containing the server error types.
*/
enum class ServerErrorType(val code: Int) {
UNKNOWN_API(1000),
API_REMOVED(1001),
INVALID_API_CLASS(1002),
INVALID_API_FUNCTION(1003),
INSUFFICIENT_PERMISSIONS(1004),
INVALID_TOKEN(1005),
FUNCTION_BLOCKED(1006),
SERVER_MAINTENANCE(1007),
API_MAINTENANCE(1008),
IP_BLOCKED(2000),
NEWS(2001),
LOGIN_MISSING_CREDENTIALS(3000),
LOGIN_INVALID_CREDENTIALS(3001),
NOTIFICATIONS_LOGIN_REQUIRED(3002),
USERINFO_INVALID_ID(3003),
UCP_LOGIN_REQUIRED(3004),
UCP_INVALID_CATEGORY(3005),
UCP_INVALID_ID(3006),
INFO_INVALID_ID(3007),
INFO_INVALID_TYPE(3008),
INFO_LOGIN_REQUIRED(3009),
INFO_ENTRY_ALREADY_IN_LIST(3010),
INFO_EXCEEDED_MAXIMUM_ENTRIES(3011),
LOGIN_ALREADY_LOGGED_IN(3012),
LOGIN_DIFFERENT_USER_ALREADY_LOGGED_IN(3013),
USER_INSUFFICIENT_PERMISSIONS(3014),
LIST_INVALID_CATEGORY(3015),
LIST_INVALID_MEDIUM(3016),
MEDIA_INVALID_STYLE(3017),
MEDIA_INVALID_ENTRY(3018),
MANGA_INVALID_CHAPTER(3019),
ANIME_INVALID_EPISODE(3020),
ANIME_INVALID_STREAM(3021),
UCP_INVALID_EPISODE(3022),
MESSAGES_LOGIN_REQUIRED(3023),
MESSAGES_INVALID_CONFERENCE(3024),
MESSAGES_INVALID_REPORT_INPUT(3025),
MESSAGES_INVALID_MESSAGE(3026),
MESSAGES_INVALID_USER(3027),
MESSAGES_EXCEEDED_MAXIMUM_USERS(3028),
MESSAGES_INVALID_TOPIC(3029),
MESSAGES_MISSING_USER(3030),
CHAT_INVALID_ROOM(3031),
CHAT_INVALID_PERMISSIONS(3032),
CHAT_INVALID_MESSAGE(3033),
CHAT_LOGIN_REQUIRED(3034),
LIST_INVALID_LANGUAGE(3035),
LIST_INVALID_TYPE(3036),
LIST_INVALID_ID(3037),
USER_2FA_SECRET_REQUIRED(3038),
USER_ACCOUNT_EXPIRED(3039),
USER_ACCOUNT_BLOCKED(3040),
USER(3041),
ERRORLOG_INVALID_INPUT(3042),
LIST_INVALID_SUBJECT(3043),
FORUM_INVALID_ID(3044),
APPS_INVALID_ID(3045),
LIST_TOP_ACCESS_RESET(3046),
AUTH_INVALID_USER(3047),
AUTH_INVALID_CODE(3048),
AUTH_CODE_ALREADY_EXISTS(3049),
AUTH_CODE_DOES_NOT_EXIST(3050),
AUTH_CODE_REJECTED(3051),
AUTH_CODE_PENDING(3052),
AUTH_CODE_INVALID_NAME(3053),
AUTH_CODE_DUPLICATE(3054),
CHAT_SEVEN_DAY_PROTECTION(3055),
CHAT_USER_ON_BLACKLIST(3056),
CHAT_NO_PERMISSIONS(3057),
CHAT_INVALID_THANK_YOU(3058),
CHAT_INVALID_INPUT(3059),
FORUM_INVALID_PERMISSIONS(3060),
INFO_DELETE_COMMENT_INVALID_INPUT(3061),
UCP_INVALID_SETTINGS(3062),
ANIME_LOGIN_REQUIRED(3063),
IP_AUTHENTICATION_REQUIRED(3064),
MEDIA_NO_VAST_TAG(3065),
LIST_NO_ENTRIES_LEFT(3066),
COMMENT_LOGIN_REQUIRED(3067),
COMMENT_INVALID_ID(3068),
COMMENT_INVALID_COMMENT(3069),
COMMENT_INSUFFICIENT_PERMISSIONS(3070),
COMMENT_INVALID_RATING(3071),
COMMENT_INVALID_EPISODE(3072),
COMMENT_NOT_ACTIVE_YET(3073),
COMMENT_INVALID_STATUS(3074),
COMMENT_SAVE_ERROR(3075),
COMMENT_INVALID_ENTRY_ID(3076),
COMMENT_INVALID_CONTENT(3077),
COMMENT_ALREADY_EXISTS(3078),
UNKNOWN(10_000),
RATE_LIMIT(99_998),
INTERNAL(99_999);
companion object {
internal fun fromErrorCode(errorCode: Int?): ServerErrorType {
return enumValues<ServerErrorType>().find { it.code == errorCode } ?: UNKNOWN
}
}
internal val isLoginError
get() = when (this) {
INVALID_TOKEN,
NOTIFICATIONS_LOGIN_REQUIRED,
UCP_LOGIN_REQUIRED,
INFO_LOGIN_REQUIRED,
LOGIN_ALREADY_LOGGED_IN,
LOGIN_DIFFERENT_USER_ALREADY_LOGGED_IN,
MESSAGES_LOGIN_REQUIRED,
CHAT_LOGIN_REQUIRED,
USER_2FA_SECRET_REQUIRED,
ANIME_LOGIN_REQUIRED,
IP_AUTHENTICATION_REQUIRED,
COMMENT_LOGIN_REQUIRED -> true
else -> false
}
}
}
| gpl-3.0 | 9678e706a198da2ca083eb0af0b0c1cf | 31.657754 | 100 | 0.605862 | 4.047051 | false | false | false | false |
tmarsteel/kotlin-prolog | core/src/main/kotlin/com/github/prologdb/runtime/module/ModuleScopeProofSearchContext.kt | 1 | 5023 | package com.github.prologdb.runtime.module
import com.github.prologdb.async.LazySequenceBuilder
import com.github.prologdb.async.Principal
import com.github.prologdb.runtime.*
import com.github.prologdb.runtime.exception.PrologStackTraceElement
import com.github.prologdb.runtime.proofsearch.AbstractProofSearchContext
import com.github.prologdb.runtime.proofsearch.Authorization
import com.github.prologdb.runtime.proofsearch.PrologCallable
import com.github.prologdb.runtime.proofsearch.ProofSearchContext
import com.github.prologdb.runtime.query.PredicateInvocationQuery
import com.github.prologdb.runtime.term.Atom
import com.github.prologdb.runtime.term.CompoundTerm
import com.github.prologdb.runtime.term.Term
import com.github.prologdb.runtime.unification.Unification
import com.github.prologdb.runtime.unification.VariableBucket
/**
* All code declared inside a module only has access to predicates declared in the same module and
* imported into that module explicitly **but not** to predicates visible in the scope where the
* module is being imported into. This [ProofSearchContext] ensures that isolation: running code of
* module within the proper [ModuleScopeProofSearchContext] achieves that behaviour.
*/
class ModuleScopeProofSearchContext(
val module: Module,
private val runtimeEnvironment: DefaultPrologRuntimeEnvironment,
private val lookupTable: Map<ClauseIndicator, Pair<ModuleReference, PrologCallable>>,
override val principal: Principal,
override val randomVariableScope: RandomVariableScope,
override val authorization: Authorization
) : ProofSearchContext, AbstractProofSearchContext() {
override val operators = module.localOperators
override suspend fun LazySequenceBuilder<Unification>.doInvokePredicate(query: PredicateInvocationQuery, variables: VariableBucket): Unification? {
val (fqIndicator, callable, invocableGoal) = resolveHead(query.goal)
if (!authorization.mayRead(fqIndicator)) throw PrologPermissionError("Not allowed to read/invoke $fqIndicator")
return callable.fulfill(this, invocableGoal.arguments, this@ModuleScopeProofSearchContext)
}
override fun getStackTraceElementOf(query: PredicateInvocationQuery) = PrologStackTraceElement(
query.goal,
query.goal.sourceInformation.orElse(query.sourceInformation),
module
)
private fun findImport(indicator: ClauseIndicator): Pair<ModuleReference, PrologCallable>? = lookupTable[indicator]
override fun resolveModuleScopedCallable(goal: Clause): Triple<FullyQualifiedClauseIndicator, PrologCallable, Array<out Term>>? {
if (goal.functor != ":" || goal.arity != 2 || goal !is CompoundTerm) {
return null
}
val moduleNameTerm = goal.arguments[0]
val unscopedGoal = goal.arguments[1]
if (moduleNameTerm !is Atom || unscopedGoal !is CompoundTerm) {
return null
}
val simpleIndicator = ClauseIndicator.of(unscopedGoal)
if (moduleNameTerm.name == this.module.declaration.moduleName) {
val callable = module.allDeclaredPredicates[simpleIndicator]
?: throw PredicateNotDefinedException(simpleIndicator, module)
val fqIndicator = FullyQualifiedClauseIndicator(this.module.declaration.moduleName, simpleIndicator)
return Triple(fqIndicator, callable, unscopedGoal.arguments)
}
val module = runtimeEnvironment.getLoadedModule(moduleNameTerm.name)
val callable = module.exportedPredicates[simpleIndicator]
?: if (simpleIndicator in module.allDeclaredPredicates) {
throw PredicateNotExportedException(FullyQualifiedClauseIndicator(module.declaration.moduleName, simpleIndicator), this.module)
} else {
throw PredicateNotDefinedException(simpleIndicator, module)
}
return Triple(
FullyQualifiedClauseIndicator(module.declaration.moduleName, simpleIndicator),
callable,
unscopedGoal.arguments
)
}
override fun resolveCallable(simpleIndicator: ClauseIndicator): Pair<FullyQualifiedClauseIndicator, PrologCallable> {
module.allDeclaredPredicates[simpleIndicator]?.let { callable ->
val fqIndicator = FullyQualifiedClauseIndicator(module.declaration.moduleName, simpleIndicator)
return Pair(fqIndicator, callable)
}
findImport(simpleIndicator)?.let { (sourceModule, callable) ->
val fqIndicator = FullyQualifiedClauseIndicator(sourceModule.moduleName, ClauseIndicator.of(callable))
return Pair(fqIndicator, callable)
}
throw PredicateNotDefinedException(simpleIndicator, module)
}
override fun deriveForModuleContext(moduleName: String): ProofSearchContext {
return runtimeEnvironment.deriveProofSearchContextForModule(this, moduleName)
}
override fun toString() = "context of module ${module.declaration.moduleName}"
}
| mit | 476fa67f02427bc57771e35eb6c8474d | 45.943925 | 151 | 0.752737 | 5.29294 | false | false | false | false |
tingtingths/jukebot | app/src/main/java/com/jukebot/jukebot/manager/MessageManager.kt | 1 | 1299 | package com.jukebot.jukebot.manager
import com.pengrad.telegrambot.model.Message
import com.pengrad.telegrambot.request.BaseRequest
import com.pengrad.telegrambot.response.BaseResponse
import java.util.concurrent.LinkedBlockingDeque
/**
* Created by Ting.
*/
object MessageManager {
private var msgQ: LinkedBlockingDeque<Pair<BaseRequest<*, *>, ((BaseResponse?) -> Unit)?>> = LinkedBlockingDeque()
private var callback: () -> Unit = {}
private var responseExpectedRequest = HashMap<Pair<Long, Int>, (Message) -> Unit>()
fun iter(): MutableIterator<Pair<BaseRequest<*, *>, ((BaseResponse?) -> Unit)?>> =
msgQ.iterator()
fun enqueue(msg: Pair<BaseRequest<*, *>, ((BaseResponse?) -> Unit)?>) {
msgQ.offer(msg)
callback()
}
fun dequeue(): Pair<BaseRequest<*, *>, ((BaseResponse?) -> Unit)?>? = msgQ.poll()
fun onEnqueue(callback: () -> Unit) {
this.callback = callback
}
fun ignoreEnqueue() {
callback = {}
}
fun registerReplyCallback(chatId: Long, msgId: Int, callback: (Message) -> Unit) {
responseExpectedRequest[Pair(chatId, msgId)] = callback
}
fun unregisterReplyCallback(chatId: Long, msgId: Int): ((Message) -> Unit)? = responseExpectedRequest.remove(Pair(chatId, msgId))
}
| mit | 3ab9017c164ef594abb427344aaafb6c | 30.682927 | 133 | 0.659738 | 4.176849 | false | false | false | false |
tangying91/profit | src/main/java/org/profit/app/analyse/StockUpAnalyzer.kt | 1 | 1332 | package org.profit.app.analyse
import org.profit.app.StockHall
import org.profit.app.pojo.StockHistory
import org.profit.util.DateUtils
import org.profit.util.FileUtils
import org.profit.util.StockUtils
import java.lang.Exception
/**
* 【积】周期内,连续上涨天数较多
*/
class StockUpAnalyzer(code: String, private val statCount: Int, private val upPercent: Double) : StockAnalyzer(code) {
/**
* 1.周期内总天数
* 2.周期内连续上涨最大天数
* 3.周内总上涨天数
*/
override fun analyse(results: MutableList<String>) {
// 获取数据,后期可以限制天数
val list = readHistories(statCount)
// 如果没有数据
if (list.size < statCount) {
return
}
val totalDay = list.size
val riseDays = list.count { it.close > it.open }
val risePercent = (list[0].close - list[statCount - 1].open).div(list[statCount - 1].open) * 100
if (riseDays > totalDay * upPercent) {
val content = "$code${StockHall.stockName(code)} 一共$totalDay 天,累计一共上涨$riseDays 天,区间涨幅${StockUtils.twoDigits(risePercent)}% ,快速查看: http://stockpage.10jqka.com.cn/$code/"
FileUtils.writeStat(content)
}
}
} | apache-2.0 | cfa8009e8fe48dac665c5be028e3c8b9 | 29.891892 | 180 | 0.628183 | 3.245179 | false | false | false | false |
romasch/yaml-configuration-generator | src/main/kotlin/ch/romasch/gradle/yaml/config/nodes/ConfigNode.kt | 1 | 1139 | package ch.romasch.gradle.yaml.config.nodes
import org.yaml.snakeyaml.nodes.ScalarNode
sealed class ConfigNode {
class Assignment(val name: String, val value: ConfigNode) : ConfigNode()
class ConfigGroup(val members: List<ConfigNode>) : ConfigNode()
class ScalarConfigValue(val node: ScalarNode) : ConfigNode()
class ListConfigValue(val nodes: List<ScalarConfigValue>) : ConfigNode()
}
abstract class ConfigVisitor {
fun visit(config: ConfigNode):Unit = when(config) {
is ConfigNode.Assignment -> visitAssignment(config)
is ConfigNode.ConfigGroup -> visitConfigGroup(config)
is ConfigNode.ScalarConfigValue -> visitScalarConfigValue(config)
is ConfigNode.ListConfigValue -> visitListConfigValue(config)
}
open fun visitAssignment(assignment: ConfigNode.Assignment) = visit(assignment.value)
open fun visitConfigGroup(group: ConfigNode.ConfigGroup) = group.members.forEach(this::visit)
open fun visitScalarConfigValue(scalar: ConfigNode.ScalarConfigValue) = Unit
open fun visitListConfigValue( list: ConfigNode.ListConfigValue) = list.nodes.forEach(this::visit)
} | mit | 61a78bc94af7c8f822fb4f4e0ec812b2 | 44.6 | 102 | 0.761194 | 4.574297 | false | true | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/data/model/helper/CookieStore.kt | 1 | 2828 | package tech.summerly.quiet.data.model.helper
import okhttp3.Cookie
import okhttp3.HttpUrl
import org.jetbrains.anko.attempt
import java.io.*
import java.util.*
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/23
* desc : 用于持续保存Cookie
*/
abstract class CookieStore {
abstract fun add(url: HttpUrl, cookie: Cookie)
abstract fun get(url: HttpUrl): List<Cookie>
abstract fun removeAll(): Boolean
abstract fun remove(url: HttpUrl, cookie: Cookie): Boolean
abstract fun getCookies(): List<Cookie>
protected fun getCookieToken(cookie: Cookie): String {
return cookie.name() + "@" + cookie.domain()
}
/**
* cookies 序列化成 string
*
* @param cookie 要序列化的cookie
* @return 序列化之后的string
*/
protected fun encodeCookie(cookie: SerializableOkHttpCookies): String {
val os = ByteArrayOutputStream()
try {
val outputStream = ObjectOutputStream(os)
outputStream.writeObject(cookie)
} catch (e: IOException) {
error("IOException in encodeCookie")
}
return byteArrayToHexString(os.toByteArray())
}
/**
* 将字符串反序列化成cookies
*
* @param cookieString cookies string
* @return cookie object
*/
protected fun decodeCookie(cookieString: String): Cookie? {
val cookie = attempt {
val bytes = hexStringToByteArray(cookieString)
val byteArrayInputStream = ByteArrayInputStream(bytes)
val objectInputStream = ObjectInputStream(byteArrayInputStream)
(objectInputStream.readObject() as SerializableOkHttpCookies).cookies
}
return cookie.value
}
/**
* 二进制数组转十六进制字符串
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
private fun byteArrayToHexString(bytes: ByteArray): String {
val sb = StringBuilder(bytes.size * 2)
for (element in bytes) {
val v = element.toInt() and 0xff
if (v < 16) {
sb.append('0')
}
sb.append(Integer.toHexString(v))
}
return sb.toString().toUpperCase(Locale.US)
}
/**
* 十六进制字符串转二进制数组
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
private fun hexStringToByteArray(hexString: String): ByteArray {
val len = hexString.length
val data = ByteArray(len / 2)
var i = 0
while (i < len) {
data[i / 2] = ((Character.digit(hexString[i], 16) shl 4) + Character.digit(hexString[i + 1], 16)).toByte()
i += 2
}
return data
}
} | gpl-2.0 | 2eec27831822815db14c23e544a1e474 | 25.90099 | 118 | 0.607143 | 4.331738 | false | false | false | false |
Bastien7/Lux-transport-analyzer | src/main/com/bastien7/transport/analyzer/park/entityTFL/ParkTFL.kt | 1 | 1123 | package com.bastien7.transport.analyzer.park.entityTFL
import com.bastien7.transport.analyzer.park.entity.Park
data class ParkTFL(
val type: String = "",
val geometry: GeometryTFL = GeometryTFL(),
val properties: PropertiesTFL = PropertiesTFL()
) {
fun toPark(): Park {
val paymentMethods: PaymentMethodsTFL? = this.properties.meta?.payment_methods
var paid: Boolean = false
if (paymentMethods is PaymentMethodsTFL) {
paid = paymentMethods.amex ||
paymentMethods.call2park ||
paymentMethods.cash ||
paymentMethods.eurocard ||
paymentMethods.mastercard ||
paymentMethods.visa ||
paymentMethods.vpay
}
return Park(id = this.properties.id, name = this.properties.name, availablePlaces = this.properties.free ?: 0, totalPlaces = this.properties.total ?: 0,
trend = this.properties.trend, open = this.properties.meta?.open ?: false, paid = paid, address = this.properties.meta?.address?.street ?: "")
}
} | apache-2.0 | aa2ea463dca2cee8e317af3a8a5c919c | 40.62963 | 160 | 0.615316 | 4.758475 | false | false | false | false |
BracketCove/PosTrainer | app/src/main/java/com/bracketcove/postrainer/reminderlist/ReminderListLogic.kt | 1 | 3630 | package com.bracketcove.postrainer.reminderlist
import com.bracketcove.postrainer.BaseLogic
import com.bracketcove.postrainer.ERROR_GENERIC
import com.bracketcove.postrainer.REMINDER_CANCELLED
import com.bracketcove.postrainer.REMINDER_SET
import com.bracketcove.postrainer.dependencyinjection.AndroidReminderProvider
import com.wiseassblog.common.ResultWrapper
import com.wiseassblog.domain.domainmodel.Reminder
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
/**
* Retrieves a List of any Reminders which are Present in ReminderDatabase (Realm Database), and
* displays passes them to the View.
* Created by Ryan on 05/03/2017.
*/
class ReminderListLogic(
private val view: ReminderListContract.View,
//Service Locator
private val provider: AndroidReminderProvider,
dispatcher: CoroutineDispatcher
) : BaseLogic<ReminderListEvent>(dispatcher) {
//Note: these come from BaseLogic base abstract class
override val coroutineContext: CoroutineContext
get() = main + jobTracker
override fun handleEvent(eventType: ReminderListEvent) {
when (eventType) {
is ReminderListEvent.OnStart -> getAlarmList()
is ReminderListEvent.OnSettingsClick -> showSettings()
is ReminderListEvent.OnMovementsClick -> showMovements()
is ReminderListEvent.OnCreateButtonClick -> createAlarm()
is ReminderListEvent.OnReminderToggled -> onToggle(eventType.isActive, eventType.reminder)
is ReminderListEvent.OnReminderIconClick -> onIconClick(eventType.reminder)
}
}
private fun showMovements() {
view.startMovementsView()
}
private fun onIconClick(reminder: Reminder) = launch {
if (reminder.isActive) provider.cancelReminder.execute(reminder)
//since there isn't much I can do if this thing fails, not bothering
//to check the result currently
view.startReminderDetailView(reminder.reminderId!!)
}
private fun onToggle(active: Boolean, reminder: Reminder) {
if (active) setAlarm(reminder)
else cancelAlarm(reminder)
}
private fun cancelAlarm(reminder: Reminder) = launch {
val result = provider.cancelReminder.execute(reminder)
when (result) {
is ResultWrapper.Success -> alarmCancelled()
is ResultWrapper.Error -> handleError()
}
}
private fun alarmCancelled() {
view.showMessage(REMINDER_CANCELLED)
}
private fun setAlarm(reminder: Reminder) = launch {
val result = provider.setReminder.execute(reminder)
when (result) {
is ResultWrapper.Success -> alarmSet()
is ResultWrapper.Error -> handleError()
}
}
private fun alarmSet() {
view.showMessage(REMINDER_SET)
}
private fun createAlarm() {
view.startReminderDetailView("")
}
private fun showSettings() {
view.startSettingsActivity()
}
private fun getAlarmList() = launch {
val result = provider.getReminderList.execute()
when (result){
is ResultWrapper.Success -> updateView(result.value)
is ResultWrapper.Error -> {
view.setNoReminderListDataFound()
handleError()
}
}
}
private fun handleError() {
view.showMessage(ERROR_GENERIC)
}
private fun updateView(value: List<Reminder>) {
if (value.size == 0) view.setNoReminderListDataFound()
else view.setReminderListData(value)
}
}
| apache-2.0 | 46e7a71ad56a607e987d1de8c0b8974f | 30.842105 | 102 | 0.685124 | 4.952251 | false | false | false | false |
BoD/Ticker | app/src/main/kotlin/org/jraf/android/ticker/util/location/IpApiClient.kt | 1 | 2332 | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2018 Benoit 'BoD' Lubek ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jraf.android.ticker.util.location
import android.location.Location
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import org.slf4j.LoggerFactory
import java.net.HttpURLConnection
import java.net.URL
internal class IpApiClient {
companion object {
private var LOGGER = LoggerFactory.getLogger(IpApiClient::class.java)
private const val URL_API = "http://ip-api.com/json"
}
private var _currentLocation: Location? = null
val currentLocation: Location?
get() {
if (_currentLocation != null) return _currentLocation
_currentLocation = try {
callIpApi()
} catch (e: Throwable) {
LOGGER.warn("Could not call api", e)
null
}
return _currentLocation
}
private fun callIpApi(): Location {
val connection = URL(URL_API).openConnection() as HttpURLConnection
return try {
val jsonStr = connection.inputStream.bufferedReader().readText()
val rootJson: JsonObject = Parser().parse(StringBuilder(jsonStr)) as JsonObject
Location("").apply {
latitude = rootJson.float("lat")!!.toDouble()
longitude = rootJson.float("lon")!!.toDouble()
}
} finally {
connection.disconnect()
}
}
} | gpl-3.0 | 669ee16f8bc12857866ae687c8fe902e | 32.811594 | 91 | 0.600343 | 4.467433 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/ui/JournalItemActivity.kt | 1 | 24957 | package com.etesync.syncadapter.ui
import android.accounts.Account
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.provider.CalendarContract
import android.provider.ContactsContract
import android.text.format.DateFormat
import android.text.format.DateUtils
import android.view.*
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import at.bitfire.ical4android.Event
import at.bitfire.ical4android.InvalidCalendarException
import at.bitfire.ical4android.Task
import at.bitfire.ical4android.TaskProvider
import at.bitfire.vcard4android.Contact
import com.etesync.syncadapter.App
import com.etesync.syncadapter.Constants
import com.etesync.syncadapter.R
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.model.JournalEntity
import com.etesync.journalmanager.model.SyncEntry
import com.etesync.syncadapter.resource.*
import com.etesync.syncadapter.ui.journalviewer.ListEntriesFragment.Companion.setJournalEntryView
import com.etesync.syncadapter.utils.EventEmailInvitation
import com.etesync.syncadapter.utils.TaskProviderHandling
import com.google.android.material.tabs.TabLayout
import ezvcard.util.PartialDate
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.io.IOException
import java.io.StringReader
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.Future
class JournalItemActivity : BaseActivity(), Refreshable {
private var journalEntity: JournalEntity? = null
private lateinit var account: Account
protected lateinit var info: CollectionInfo
private lateinit var syncEntry: SyncEntry
private var emailInvitationEvent: Event? = null
private var emailInvitationEventString: String? = null
override fun refresh() {
val data = (applicationContext as App).data
journalEntity = JournalEntity.fetch(data, info.getServiceEntity(data), info.uid)
if (journalEntity == null || journalEntity!!.isDeleted) {
finish()
return
}
account = intent.extras!!.getParcelable(ViewCollectionActivity.EXTRA_ACCOUNT)!!
info = journalEntity!!.info
title = info.displayName
setJournalEntryView(findViewById(R.id.journal_list_item), info, syncEntry)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.journal_item_activity)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
info = intent.extras!!.getSerializable(Constants.KEY_COLLECTION_INFO) as CollectionInfo
syncEntry = intent.extras!!.getSerializable(KEY_SYNC_ENTRY) as SyncEntry
refresh()
val viewPager = findViewById<View>(R.id.viewpager) as ViewPager
viewPager.adapter = TabsAdapter(supportFragmentManager, this, info, syncEntry)
val tabLayout = findViewById<View>(R.id.tabs) as TabLayout
tabLayout.setupWithViewPager(viewPager)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_journal_item, menu)
menu.setGroupVisible(R.id.journal_item_menu_event_invite, emailInvitationEvent != null)
return true
}
fun allowSendEmail(event: Event?, icsContent: String) {
emailInvitationEvent = event
emailInvitationEventString = icsContent
invalidateOptionsMenu()
}
fun sendEventInvite(item: MenuItem) {
val intent = EventEmailInvitation(this, account).createIntent(emailInvitationEvent!!, emailInvitationEventString!!)
startActivity(intent)
}
fun restoreItem(item: MenuItem) {
// FIXME: This code makes the assumption that providers are all available. May not be true for tasks, and potentially others too.
when (info.enumType) {
CollectionInfo.Type.CALENDAR -> {
val provider = contentResolver.acquireContentProviderClient(CalendarContract.CONTENT_URI)!!
val localCalendar = LocalCalendar.findByName(account, provider, LocalCalendar.Factory, info.uid!!)!!
val event = Event.eventsFromReader(StringReader(syncEntry.content))[0]
var localEvent = localCalendar.findByUid(event.uid!!)
if (localEvent != null) {
localEvent.updateAsDirty(event)
} else {
localEvent = LocalEvent(localCalendar, event, event.uid, null)
localEvent.addAsDirty()
}
}
CollectionInfo.Type.TASKS -> {
TaskProviderHandling.getWantedTaskSyncProvider(applicationContext)?.let {
val provider = TaskProvider.acquire(this, it)!!
val localTaskList = LocalTaskList.findByName(account, provider, LocalTaskList.Factory, info.uid!!)!!
val task = Task.tasksFromReader(StringReader(syncEntry.content))[0]
var localTask = localTaskList.findByUid(task.uid!!)
if (localTask != null) {
localTask.updateAsDirty(task)
} else {
localTask = LocalTask(localTaskList, task, task.uid, null)
localTask.addAsDirty()
}
}
}
CollectionInfo.Type.ADDRESS_BOOK -> {
val provider = contentResolver.acquireContentProviderClient(ContactsContract.RawContacts.CONTENT_URI)!!
val localAddressBook = LocalAddressBook.findByUid(this, provider, account, info.uid!!)!!
val contact = Contact.fromReader(StringReader(syncEntry.content), null)[0]
if (contact.group) {
// FIXME: not currently supported
} else {
var localContact = localAddressBook.findByUid(contact.uid!!) as LocalContact?
if (localContact != null) {
localContact.updateAsDirty(contact)
} else {
localContact = LocalContact(localAddressBook, contact, contact.uid, null)
localContact.createAsDirty()
}
}
}
}
val dialog = AlertDialog.Builder(this)
.setTitle(R.string.journal_item_restore_action)
.setIcon(R.drawable.ic_restore_black)
.setMessage(R.string.journal_item_restore_dialog_body)
.setPositiveButton(android.R.string.ok) { dialog, which ->
// dismiss
}
.create()
dialog.show()
}
private class TabsAdapter(fm: FragmentManager, private val context: Context, private val info: CollectionInfo, private val syncEntry: SyncEntry) : FragmentPagerAdapter(fm) {
override fun getCount(): Int {
// FIXME: Make it depend on info enumType (only have non-raw for known types)
return 2
}
override fun getPageTitle(position: Int): CharSequence? {
return if (position == 0) {
context.getString(R.string.journal_item_tab_main)
} else {
context.getString(R.string.journal_item_tab_raw)
}
}
override fun getItem(position: Int): Fragment {
return if (position == 0) {
PrettyFragment.newInstance(info, syncEntry)
} else {
TextFragment.newInstance(syncEntry)
}
}
}
class TextFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.text_fragment, container, false)
val tv = v.findViewById<View>(R.id.content) as TextView
val syncEntry = arguments!!.getSerializable(KEY_SYNC_ENTRY) as SyncEntry
tv.text = syncEntry.content
return v
}
companion object {
fun newInstance(syncEntry: SyncEntry): TextFragment {
val frag = TextFragment()
val args = Bundle(1)
args.putSerializable(KEY_SYNC_ENTRY, syncEntry)
frag.arguments = args
return frag
}
}
}
class PrettyFragment : Fragment() {
internal lateinit var info: CollectionInfo
internal lateinit var syncEntry: SyncEntry
private var asyncTask: Future<Unit>? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var v: View? = null
info = arguments!!.getSerializable(Constants.KEY_COLLECTION_INFO) as CollectionInfo
syncEntry = arguments!!.getSerializable(KEY_SYNC_ENTRY) as SyncEntry
when (info.enumType) {
CollectionInfo.Type.ADDRESS_BOOK -> {
v = inflater.inflate(R.layout.contact_info, container, false)
asyncTask = loadContactTask(v)
}
CollectionInfo.Type.CALENDAR -> {
v = inflater.inflate(R.layout.event_info, container, false)
asyncTask = loadEventTask(v)
}
CollectionInfo.Type.TASKS -> {
v = inflater.inflate(R.layout.task_info, container, false)
asyncTask = loadTaskTask(v)
}
}
return v
}
override fun onDestroyView() {
super.onDestroyView()
if (asyncTask != null)
asyncTask!!.cancel(true)
}
private fun loadEventTask(view: View): Future<Unit> {
return doAsync {
var event: Event? = null
val inputReader = StringReader(syncEntry.content)
try {
event = Event.eventsFromReader(inputReader, null)[0]
} catch (e: InvalidCalendarException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
if (event != null) {
uiThread {
val loader = view.findViewById<View>(R.id.event_info_loading_msg)
loader.visibility = View.GONE
val contentContainer = view.findViewById<View>(R.id.event_info_scroll_view)
contentContainer.visibility = View.VISIBLE
setTextViewText(view, R.id.title, event.summary)
val dtStart = event.dtStart?.date?.time
val dtEnd = event.dtEnd?.date?.time
if ((dtStart == null) || (dtEnd == null)) {
setTextViewText(view, R.id.when_datetime, getString(R.string.loading_error_title))
} else {
setTextViewText(view, R.id.when_datetime, getDisplayedDatetime(dtStart, dtEnd, event.isAllDay(), context))
}
setTextViewText(view, R.id.where, event.location)
val organizer = event.organizer
if (organizer != null) {
val tv = view.findViewById<View>(R.id.organizer) as TextView
tv.text = organizer.calAddress.toString().replaceFirst("mailto:".toRegex(), "")
} else {
val organizerView = view.findViewById<View>(R.id.organizer_container)
organizerView.visibility = View.GONE
}
setTextViewText(view, R.id.description, event.description)
var first = true
var sb = StringBuilder()
for (attendee in event.attendees) {
if (first) {
first = false
sb.append(getString(R.string.journal_item_attendees)).append(": ")
} else {
sb.append(", ")
}
sb.append(attendee.calAddress.toString().replaceFirst("mailto:".toRegex(), ""))
}
setTextViewText(view, R.id.attendees, sb.toString())
first = true
sb = StringBuilder()
for (alarm in event.alarms) {
if (first) {
first = false
sb.append(getString(R.string.journal_item_reminders)).append(": ")
} else {
sb.append(", ")
}
sb.append(alarm.trigger.value)
}
setTextViewText(view, R.id.reminders, sb.toString())
if (event.attendees.isNotEmpty() && activity != null) {
(activity as JournalItemActivity).allowSendEmail(event, syncEntry.content)
}
}
}
}
}
private fun loadTaskTask(view: View): Future<Unit> {
return doAsync {
var task: Task? = null
val inputReader = StringReader(syncEntry.content)
try {
task = Task.tasksFromReader(inputReader)[0]
} catch (e: InvalidCalendarException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
if (task != null) {
uiThread {
val loader = view.findViewById<View>(R.id.task_info_loading_msg)
loader.visibility = View.GONE
val contentContainer = view.findViewById<View>(R.id.task_info_scroll_view)
contentContainer.visibility = View.VISIBLE
setTextViewText(view, R.id.title, task.summary)
setTextViewText(view, R.id.where, task.location)
val organizer = task.organizer
if (organizer != null) {
val tv = view.findViewById<View>(R.id.organizer) as TextView
tv.text = organizer.calAddress.toString().replaceFirst("mailto:".toRegex(), "")
} else {
val organizerView = view.findViewById<View>(R.id.organizer_container)
organizerView.visibility = View.GONE
}
setTextViewText(view, R.id.description, task.description)
}
}
}
}
private fun loadContactTask(view: View): Future<Unit> {
return doAsync {
var contact: Contact? = null
val reader = StringReader(syncEntry.content)
try {
contact = Contact.fromReader(reader, null)[0]
} catch (e: IOException) {
e.printStackTrace()
}
if (contact != null) {
uiThread {
val loader = view.findViewById<View>(R.id.loading_msg)
loader.visibility = View.GONE
val contentContainer = view.findViewById<View>(R.id.content_container)
contentContainer.visibility = View.VISIBLE
val tv = view.findViewById<View>(R.id.display_name) as TextView
tv.text = contact.displayName
if (contact.group) {
showGroup(contact)
} else {
showContact(contact)
}
}
}
}
}
private fun showGroup(contact: Contact) {
val view = this.view!!
val mainCard = view.findViewById<View>(R.id.main_card) as ViewGroup
addInfoItem(view.context, mainCard, getString(R.string.journal_item_member_count), null, contact.members.size.toString())
for (member in contact.members) {
addInfoItem(view.context, mainCard, getString(R.string.journal_item_member), null, member)
}
}
private fun showContact(contact: Contact) {
val view = this.view!!
val mainCard = view.findViewById<View>(R.id.main_card) as ViewGroup
val aboutCard = view.findViewById<View>(R.id.about_card) as ViewGroup
aboutCard.findViewById<View>(R.id.title_container).visibility = View.VISIBLE
// TEL
for (labeledPhone in contact.phoneNumbers) {
val types = labeledPhone.property.types
val type = if (types.size > 0) types[0].value else null
addInfoItem(view.context, mainCard, getString(R.string.journal_item_phone), type, labeledPhone.property.text)
}
// EMAIL
for (labeledEmail in contact.emails) {
val types = labeledEmail.property.types
val type = if (types.size > 0) types[0].value else null
addInfoItem(view.context, mainCard, getString(R.string.journal_item_email), type, labeledEmail.property.value)
}
// ORG, TITLE, ROLE
if (contact.organization != null) {
addInfoItem(view.context, aboutCard, getString(R.string.journal_item_organization), contact.jobTitle, contact.organization?.values!![0])
}
if (contact.jobDescription != null) {
addInfoItem(view.context, aboutCard, getString(R.string.journal_item_job_description), null, contact.jobTitle)
}
// IMPP
for (labeledImpp in contact.impps) {
addInfoItem(view.context, mainCard, getString(R.string.journal_item_impp), labeledImpp.property.protocol, labeledImpp.property.handle)
}
// NICKNAME
if (contact.nickName != null && !contact.nickName?.values?.isEmpty()!!) {
addInfoItem(view.context, aboutCard, getString(R.string.journal_item_nickname), null, contact.nickName?.values!![0])
}
// ADR
for (labeledAddress in contact.addresses) {
val types = labeledAddress.property.types
val type = if (types.size > 0) types[0].value else null
addInfoItem(view.context, mainCard, getString(R.string.journal_item_address), type, labeledAddress.property.label)
}
// NOTE
if (contact.note != null) {
addInfoItem(view.context, aboutCard, getString(R.string.journal_item_note), null, contact.note)
}
// URL
for (labeledUrl in contact.urls) {
addInfoItem(view.context, aboutCard, getString(R.string.journal_item_website), null, labeledUrl.property.value)
}
// ANNIVERSARY
if (contact.anniversary != null) {
addInfoItem(view.context, aboutCard, getString(R.string.journal_item_anniversary), null, getDisplayedDate(contact.anniversary?.date, contact.anniversary?.partialDate))
}
// BDAY
if (contact.birthDay != null) {
addInfoItem(view.context, aboutCard, getString(R.string.journal_item_birthday), null, getDisplayedDate(contact.birthDay?.date, contact.birthDay?.partialDate))
}
// RELATED
for (related in contact.relations) {
val types = related.types
val type = if (types.size > 0) types[0].value else null
addInfoItem(view.context, aboutCard, getString(R.string.journal_item_relation), type, related.text)
}
// PHOTO
// if (contact.photo != null)
}
private fun getDisplayedDate(date: Date?, partialDate: PartialDate?): String? {
if (date != null) {
val epochDate = date.time
return getDisplayedDatetime(epochDate, epochDate, true, context)
} else if (partialDate != null){
val formatter = SimpleDateFormat("d MMMM", Locale.getDefault())
val calendar = GregorianCalendar()
calendar.set(Calendar.DAY_OF_MONTH, partialDate.date!!)
calendar.set(Calendar.MONTH, partialDate.month!! - 1)
return formatter.format(calendar.time)
}
return null
}
companion object {
fun newInstance(info: CollectionInfo, syncEntry: SyncEntry): PrettyFragment {
val frag = PrettyFragment()
val args = Bundle(1)
args.putSerializable(Constants.KEY_COLLECTION_INFO, info)
args.putSerializable(KEY_SYNC_ENTRY, syncEntry)
frag.arguments = args
return frag
}
private fun addInfoItem(context: Context, parent: ViewGroup, type: String, label: String?, value: String?): View {
val layout = parent.findViewById<View>(R.id.container) as ViewGroup
val infoItem = LayoutInflater.from(context).inflate(R.layout.contact_info_item, layout, false)
layout.addView(infoItem)
setTextViewText(infoItem, R.id.type, type)
setTextViewText(infoItem, R.id.title, label)
setTextViewText(infoItem, R.id.content, value)
parent.visibility = View.VISIBLE
return infoItem
}
private fun setTextViewText(parent: View, id: Int, text: String?) {
val tv = parent.findViewById<View>(id) as TextView
if (text == null) {
tv.visibility = View.GONE
} else {
tv.text = text
}
}
fun getDisplayedDatetime(startMillis: Long, endMillis: Long, allDay: Boolean, context: Context?): String? {
// Configure date/time formatting.
val flagsDate = DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY
var flagsTime = DateUtils.FORMAT_SHOW_TIME
if (DateFormat.is24HourFormat(context)) {
flagsTime = flagsTime or DateUtils.FORMAT_24HOUR
}
val datetimeString: String
if (allDay) {
// For multi-day allday events or single-day all-day events that are not
// today or tomorrow, use framework formatter.
// We need to remove 24hrs because full day events are from the start of a day until the start of the next
var adjustedEnd = endMillis - 24 * 60 * 60 * 1000;
if (adjustedEnd < startMillis) {
adjustedEnd = startMillis;
}
val f = Formatter(StringBuilder(50), Locale.getDefault())
datetimeString = DateUtils.formatDateRange(context, f, startMillis,
adjustedEnd, flagsDate).toString()
} else {
// For multiday events, shorten day/month names.
// Example format: "Fri Apr 6, 5:00pm - Sun, Apr 8, 6:00pm"
val flagsDatetime = flagsDate or flagsTime or DateUtils.FORMAT_ABBREV_MONTH or
DateUtils.FORMAT_ABBREV_WEEKDAY
datetimeString = DateUtils.formatDateRange(context, startMillis, endMillis,
flagsDatetime)
}
return datetimeString
}
}
}
override fun onResume() {
super.onResume()
refresh()
}
companion object {
private val KEY_SYNC_ENTRY = "syncEntry"
fun newIntent(context: Context, account: Account, info: CollectionInfo, syncEntry: SyncEntry): Intent {
val intent = Intent(context, JournalItemActivity::class.java)
intent.putExtra(ViewCollectionActivity.EXTRA_ACCOUNT, account)
intent.putExtra(Constants.KEY_COLLECTION_INFO, info)
intent.putExtra(KEY_SYNC_ENTRY, syncEntry)
return intent
}
}
}
| gpl-3.0 | 13a1607d25f026b8494b2468a1de42c7 | 42.178201 | 183 | 0.563169 | 5.275206 | false | false | false | false |
MaibornWolff/codecharta | analysis/parser/RawTextParser/src/main/kotlin/de/maibornwolff/codecharta/parser/rawtextparser/metrics/IndentationCounter.kt | 1 | 3460 | package de.maibornwolff.codecharta.parser.rawtextparser.metrics
import de.maibornwolff.codecharta.parser.rawtextparser.model.FileMetrics
import de.maibornwolff.codecharta.parser.rawtextparser.model.toBool
import java.io.PrintStream
import java.lang.Integer.min
class IndentationCounter(
private var maxIndentation: Int = 6,
private var stderr: PrintStream = System.err,
private var verbose: Boolean = false,
private var tabWidth: Int = 0
) : Metric {
private val spaceIndentations = MutableList(maxIndentation * 8 + 1) { 0 }
private val tabIndentations = MutableList(maxIndentation + 1) { 0 }
override val name = "IndentationLevel"
override val description = "Number of lines with an indentation level of at least x"
// TODO no mixed tab/ space possible at line start?
override fun parseLine(line: String) {
var tabIndent = line.length - line.trimStart('\t').length
var spaceIndent = line.length - line.trimStart(' ').length
if (spaceIndent == line.length || tabIndent == line.length) return
if (spaceIndent > 0) {
spaceIndent = min(spaceIndent, 8 * maxIndentation)
spaceIndentations[spaceIndent] = spaceIndentations[spaceIndent] + 1
} else {
tabIndent = min(tabIndent, maxIndentation)
tabIndentations[tabIndent] = tabIndentations[tabIndent] + 1
}
}
override fun setParameters(parameters: Map<String, Int>) {
maxIndentation = parameters["maxIndentationLevel"] ?: maxIndentation
tabWidth = parameters["tabWidth"] ?: tabWidth
verbose = parameters["verbose"]?.toBool() ?: verbose
}
// TODO tabSize - (offset % tabSize) from the current position
private fun guessTabWidth(): Int {
tabWidth = 1
if (spaceIndentations.sum() == 0) return tabWidth
val candidates = 2..8
candidates.forEach { candidate ->
var mismatches = 0
for (i in spaceIndentations.indices) {
if (i % candidate != 0) {
mismatches += spaceIndentations[i]
}
}
if (mismatches == 0) {
tabWidth = candidate
}
}
if (verbose) stderr.println("INFO: Assumed tab width to be $tabWidth")
return tabWidth
}
private fun correctMismatchingIndents(tabWidth: Int) {
for (i in spaceIndentations.indices) {
if (i % tabWidth != 0 && spaceIndentations[i] > 0) {
val nextLevel: Int = i / tabWidth + 1
spaceIndentations[nextLevel * tabWidth] = spaceIndentations[nextLevel * tabWidth] + spaceIndentations[i]
stderr.println("WARN: Corrected mismatching indentations, moved ${spaceIndentations[i]} lines to indentation level $nextLevel+")
spaceIndentations[i] = 0
}
}
}
override fun getValue(): FileMetrics {
if (tabWidth == 0) {
guessTabWidth()
}
correctMismatchingIndents(tabWidth)
val fileMetrics = FileMetrics()
for (i in 0..maxIndentation) {
val tabVal = tabIndentations.subList(i, tabIndentations.size).sum()
val spaceVal = spaceIndentations.subList(i * tabWidth, spaceIndentations.size).sum()
val name = "indentation_level_$i+"
fileMetrics.addMetric(name, tabVal + spaceVal)
}
return fileMetrics
}
}
| bsd-3-clause | 57154141640e055a6c5f40e7bad09944 | 37.444444 | 144 | 0.62659 | 4.79889 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/data/cursors/ASBSessionCursor.kt | 1 | 9011 | package com.ghstudios.android.data.cursors
import android.content.Context
import android.database.Cursor
import android.database.CursorWrapper
import com.ghstudios.android.data.classes.*
import com.ghstudios.android.data.DataManager
import com.ghstudios.android.data.database.S
import com.ghstudios.android.data.util.getInt
import com.ghstudios.android.data.util.getLong
import com.ghstudios.android.data.util.getString
import com.ghstudios.android.mhgendatabase.*
import kotlin.math.min
class ASBSessionCursor(c: Cursor) : CursorWrapper(c) {
fun getASBSession(context: Context): ASBSession? {
if (isBeforeFirst || isAfterLast) {
return null
}
val session = ASBSession(
id = getLong(S.COLUMN_ASB_SET_ID),
name = getString(S.COLUMN_ASB_SET_NAME, ""),
rank = Rank.from(getInt(S.COLUMN_ASB_SET_RANK)),
hunterType = getInt(S.COLUMN_ASB_SET_HUNTER_TYPE)
)
val weaponSlots = getInt(S.COLUMN_ASB_WEAPON_SLOTS)
val weaponDecoration1 = getDecorationById(getLong(S.COLUMN_ASB_WEAPON_DECORATION_1_ID))
val weaponDecoration2 = getDecorationById(getLong(S.COLUMN_ASB_WEAPON_DECORATION_2_ID))
val weaponDecoration3 = getDecorationById(getLong(S.COLUMN_ASB_WEAPON_DECORATION_3_ID))
val headId = getLong(S.COLUMN_HEAD_ARMOR_ID)
val headArmor = getArmorById(headId)
val headDecoration1Id = getLong(S.COLUMN_HEAD_DECORATION_1_ID)
val headDecoration2Id = getLong(S.COLUMN_HEAD_DECORATION_2_ID)
val headDecoration3Id = getLong(S.COLUMN_HEAD_DECORATION_3_ID)
val headDecoration1 = getDecorationById(headDecoration1Id)
val headDecoration2 = getDecorationById(headDecoration2Id)
val headDecoration3 = getDecorationById(headDecoration3Id)
val bodyId = getLong(S.COLUMN_BODY_ARMOR_ID)
val bodyArmor = getArmorById(bodyId)
val bodyDecoration1Id = getLong(S.COLUMN_BODY_DECORATION_1_ID)
val bodyDecoration2Id = getLong(S.COLUMN_BODY_DECORATION_2_ID)
val bodyDecoration3Id = getLong(S.COLUMN_BODY_DECORATION_3_ID)
val bodyDecoration1 = getDecorationById(bodyDecoration1Id)
val bodyDecoration2 = getDecorationById(bodyDecoration2Id)
val bodyDecoration3 = getDecorationById(bodyDecoration3Id)
val armsId = getLong(S.COLUMN_ARMS_ARMOR_ID)
val armsArmor = getArmorById(armsId)
val armsDecoration1Id = getLong(S.COLUMN_ARMS_DECORATION_1_ID)
val armsDecoration2Id = getLong(S.COLUMN_ARMS_DECORATION_2_ID)
val armsDecoration3Id = getLong(S.COLUMN_ARMS_DECORATION_3_ID)
val armsDecoration1 = getDecorationById(armsDecoration1Id)
val armsDecoration2 = getDecorationById(armsDecoration2Id)
val armsDecoration3 = getDecorationById(armsDecoration3Id)
val waistId = getLong(S.COLUMN_WAIST_ARMOR_ID)
val waistArmor = getArmorById(waistId)
val waistDecoration1Id = getLong(S.COLUMN_WAIST_DECORATION_1_ID)
val waistDecoration2Id = getLong(S.COLUMN_WAIST_DECORATION_2_ID)
val waistDecoration3Id = getLong(S.COLUMN_WAIST_DECORATION_3_ID)
val waistDecoration1 = getDecorationById(waistDecoration1Id)
val waistDecoration2 = getDecorationById(waistDecoration2Id)
val waistDecoration3 = getDecorationById(waistDecoration3Id)
val legsId = getLong(S.COLUMN_LEGS_ARMOR_ID)
val legsArmor = getArmorById(legsId)
val legsDecoration1Id = getLong(S.COLUMN_LEGS_DECORATION_1_ID)
val legsDecoration2Id = getLong(S.COLUMN_LEGS_DECORATION_2_ID)
val legsDecoration3Id = getLong(S.COLUMN_LEGS_DECORATION_3_ID)
val legsDecoration1 = getDecorationById(legsDecoration1Id)
val legsDecoration2 = getDecorationById(legsDecoration2Id)
val legsDecoration3 = getDecorationById(legsDecoration3Id)
val talismanExists = getInt(S.COLUMN_TALISMAN_EXISTS)
val talismanSkill1Id = getLong(S.COLUMN_TALISMAN_SKILL_1_ID)
val talismanSkill1Points = getInt(S.COLUMN_TALISMAN_SKILL_1_POINTS)
val talismanSkill2Id = getLong(S.COLUMN_TALISMAN_SKILL_2_ID)
val talismanSkill2Points = getInt(S.COLUMN_TALISMAN_SKILL_2_POINTS)
var talismanType = getInt(S.COLUMN_TALISMAN_TYPE)
val talismanSlots = getInt(S.COLUMN_TALISMAN_SLOTS)
val talismanDecoration1Id = getLong(S.COLUMN_TALISMAN_DECORATION_1_ID)
val talismanDecoration2Id = getLong(S.COLUMN_TALISMAN_DECORATION_2_ID)
val talismanDecoration3Id = getLong(S.COLUMN_TALISMAN_DECORATION_3_ID)
val talismanDecoration1 = getDecorationById(talismanDecoration1Id)
val talismanDecoration2 = getDecorationById(talismanDecoration2Id)
val talismanDecoration3 = getDecorationById(talismanDecoration3Id)
// Set armor pieces
session.numWeaponSlots = weaponSlots
headArmor?.let { session.setEquipment(ArmorSet.HEAD, it) }
bodyArmor?.let { session.setEquipment(ArmorSet.BODY, it) }
armsArmor?.let { session.setEquipment(ArmorSet.ARMS, it) }
waistArmor?.let { session.setEquipment(ArmorSet.WAIST, it) }
legsArmor?.let { session.setEquipment(ArmorSet.LEGS, it) }
// Set Weapon decorations
weaponDecoration1?.let { session.addDecoration(ArmorSet.WEAPON, it) }
weaponDecoration2?.let { session.addDecoration(ArmorSet.WEAPON, it) }
weaponDecoration3?.let { session.addDecoration(ArmorSet.WEAPON, it) }
if (headDecoration1 != null) {
session.addDecoration(ArmorSet.HEAD, headDecoration1)
}
if (headDecoration2 != null) {
session.addDecoration(ArmorSet.HEAD, headDecoration2)
}
if (headDecoration3 != null) {
session.addDecoration(ArmorSet.HEAD, headDecoration3)
}
if (bodyDecoration1 != null) {
session.addDecoration(ArmorSet.BODY, bodyDecoration1)
}
if (bodyDecoration2 != null) {
session.addDecoration(ArmorSet.BODY, bodyDecoration2)
}
if (bodyDecoration3 != null) {
session.addDecoration(ArmorSet.BODY, bodyDecoration3)
}
if (armsDecoration1 != null) {
session.addDecoration(ArmorSet.ARMS, armsDecoration1)
}
if (armsDecoration2 != null) {
session.addDecoration(ArmorSet.ARMS, armsDecoration2)
}
if (armsDecoration3 != null) {
session.addDecoration(ArmorSet.ARMS, armsDecoration3)
}
if (waistDecoration1 != null) {
session.addDecoration(ArmorSet.WAIST, waistDecoration1)
}
if (waistDecoration2 != null) {
session.addDecoration(ArmorSet.WAIST, waistDecoration2)
}
if (waistDecoration3 != null) {
session.addDecoration(ArmorSet.WAIST, waistDecoration3)
}
if (legsDecoration1 != null) {
session.addDecoration(ArmorSet.LEGS, legsDecoration1)
}
if (legsDecoration2 != null) {
session.addDecoration(ArmorSet.LEGS, legsDecoration2)
}
if (legsDecoration3 != null) {
session.addDecoration(ArmorSet.LEGS, legsDecoration3)
}
if (talismanExists == 1) {
val talismanNames = context.resources.getStringArray(R.array.talisman_names)
talismanType = min(talismanNames.size - 1, talismanType)
val talisman = ASBTalisman(talismanType)
val typeName = talismanNames[talismanType]
talisman.name = context.getString(R.string.talisman_full_name, typeName)
talisman.numSlots = talismanSlots
talisman.setFirstSkill(getSkillTreeById(talismanSkill1Id)!!, talismanSkill1Points)
if (talismanSkill2Id != -1L) {
talisman.setSecondSkill(getSkillTreeById(talismanSkill2Id), talismanSkill2Points)
}
session.setEquipment(ArmorSet.TALISMAN, talisman)
if (talismanDecoration1 != null) {
session.addDecoration(ArmorSet.TALISMAN, talismanDecoration1)
}
if (talismanDecoration2 != null) {
session.addDecoration(ArmorSet.TALISMAN, talismanDecoration2)
}
if (talismanDecoration3 != null) {
session.addDecoration(ArmorSet.TALISMAN, talismanDecoration3)
}
}
return session
}
private fun getArmorById(id: Long): Armor? {
return if (id != 0L && id != -1L) {
DataManager.get().getArmor(id)
} else
null
}
private fun getDecorationById(id: Long): Decoration? {
return if (id != 0L && id != -1L) {
DataManager.get().getDecoration(id)
} else
null
}
private fun getSkillTreeById(id: Long): SkillTree? {
return if (id != 0L && id != -1L) {
DataManager.get().getSkillTree(id)
} else
null
}
}
| mit | 83e7a84c96d9bfe8b9160925e2df3fe0 | 42.322115 | 97 | 0.668627 | 4.414993 | false | false | false | false |
chRyNaN/GuitarChords | android/src/main/java/com/chrynan/chords/widget/ChordWidget.kt | 1 | 25196 | package com.chrynan.chords.widget
import android.content.Context
import android.graphics.*
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import com.chrynan.chords.R
import com.chrynan.chords.model.*
import com.chrynan.chords.parcel.ChordChartParceler
import com.chrynan.chords.parcel.ChordParceler
import com.chrynan.chords.util.getTypeface
import com.chrynan.chords.util.writeChord
import com.chrynan.chords.util.writeChordChart
import com.chrynan.chords.view.ChordView
import com.chrynan.chords.view.ChordView.Companion.DEFAULT_FIT_TO_HEIGHT
import com.chrynan.chords.view.ChordView.Companion.DEFAULT_MUTED_TEXT
import com.chrynan.chords.view.ChordView.Companion.DEFAULT_OPEN_TEXT
import com.chrynan.chords.view.ChordView.Companion.DEFAULT_SHOW_FINGER_NUMBERS
import com.chrynan.chords.view.ChordView.Companion.DEFAULT_SHOW_FRET_NUMBERS
import com.chrynan.chords.view.ChordView.Companion.DEFAULT_STRING_LABEL_STATE
import kotlin.math.min
import kotlin.math.round
/*
* Copyright 2020 chRyNaN
*
* 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.
*/
/**
* An Android [View] class to display guitar (or other stringed fretted instruments) chords as a
* chart. This class implements the [ChordView] interface and displays a [ChordChart] for a
* provided [Chord].
*
* @author chRyNaN
*/
class ChordWidget : View,
ChordView {
override var chord: Chord? = null
set(value) {
field = value
requestLayout()
invalidate()
}
override var chart: ChordChart = ChordChart.STANDARD_TUNING_GUITAR_CHART
set(value) {
field = value
requestLayout()
invalidate()
}
override var fitToHeight: Boolean = DEFAULT_FIT_TO_HEIGHT
set(value) {
field = value
requestLayout()
invalidate()
}
override var showFretNumbers = DEFAULT_SHOW_FRET_NUMBERS
set(value) {
field = value
requestLayout()
invalidate()
}
override var showFingerNumbers = DEFAULT_SHOW_FINGER_NUMBERS
set(value) {
field = value
invalidate()
}
override var stringLabelState: StringLabelState = DEFAULT_STRING_LABEL_STATE
set(value) {
field = value
requestLayout()
invalidate()
}
override var mutedStringText: String = DEFAULT_MUTED_TEXT
set(value) {
field = value
invalidate()
}
override var openStringText: String = DEFAULT_OPEN_TEXT
set(value) {
field = value
invalidate()
}
override var fretColor = DEFAULT_COLOR
set(value) {
field = value
fretPaint.color = value
invalidate()
}
override var fretLabelTextColor = DEFAULT_TEXT_COLOR
set(value) {
field = value
fretLabelTextPaint.color = value
invalidate()
}
override var stringColor = DEFAULT_COLOR
set(value) {
field = value
stringPaint.color = value
invalidate()
}
override var stringLabelTextColor = DEFAULT_COLOR
set(value) {
field = value
stringLabelTextPaint.color = value
invalidate()
}
override var noteColor = DEFAULT_COLOR
set(value) {
field = value
notePaint.color = value
barLinePaint.color = value
invalidate()
}
override var noteLabelTextColor = DEFAULT_TEXT_COLOR
set(value) {
field = value
noteLabelTextPaint.color = value
invalidate()
}
/**
* The [Typeface] that is used for the fret label text. This defaults to [Typeface.DEFAULT].
*
* @author chRyNaN
*/
var fretLabelTypeface: Typeface = Typeface.DEFAULT
set(value) {
field = value
fretLabelTextPaint.typeface = value
requestLayout()
invalidate()
}
/**
* The [Typeface] that is used for the note label text. This defaults to [Typeface.DEFAULT].
*
* @author chRyNaN
*/
var noteLabelTypeface: Typeface = Typeface.DEFAULT
set(value) {
field = value
noteLabelTextPaint.typeface = value
requestLayout()
invalidate()
}
/**
* The [Typeface] that is used for the string label text. This defaults to [Typeface.DEFAULT].
*
* @author chRyNaN
*/
var stringLabelTypeface: Typeface = Typeface.DEFAULT
set(value) {
field = value
stringLabelTextPaint.typeface = value
requestLayout()
invalidate()
}
private val fretPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
}
private val fretLabelTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
}
private val stringPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.BUTT
}
private val stringLabelTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
}
private val notePaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val noteLabelTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
}
private val barLinePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
}
private val drawingBounds = RectF()
private val chartBounds = RectF()
private val stringTopLabelBounds = RectF()
private val stringBottomLabelBounds = RectF()
private val fretSideLabelBounds = RectF()
private val fretCount: Int
get() = chart.fretEnd.number - chart.fretStart.number + 1
private val showBottomStringLabels: Boolean
get() = stringLabelState != StringLabelState.HIDE && chart.stringLabels.isNotEmpty()
private val fretLineRects = mutableListOf<RectF>()
private val stringLineRects = mutableListOf<RectF>()
private val fretNumberPoints = mutableListOf<PointF>()
private val notePositions = mutableListOf<NotePosition>()
private val barLinePaths = mutableListOf<BarPosition>()
private val stringBottomLabelPositions = mutableListOf<StringPosition>()
private val stringTopMarkerPositions = mutableListOf<StringPosition>()
private var fretSize = 0f //y value = 0
private var stringDistance = 0f //x value = 0f
private var fretMarkerSize = 0f
set(value) {
field = value
fretPaint.strokeWidth = value
}
private var fretLabelTextSize = 0f
set(value) {
field = value
fretLabelTextPaint.textSize = value
}
private var stringSize = 0f
set(value) {
field = value
stringPaint.strokeWidth = value
barLinePaint.strokeWidth = 2 * value
}
private var stringLabelTextSize = 0f
set(value) {
field = value
stringLabelTextPaint.textSize = value
}
private var noteSize = 0f
set(value) {
field = value
notePaint.strokeWidth = value
}
private var noteLabelTextSize = 0f
set(value) {
field = value
noteLabelTextPaint.textSize = value
}
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet? = null) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
if (!isInEditMode) {
if (attrs != null) {
val a = getContext().theme.obtainStyledAttributes(attrs, R.styleable.ChordWidget, defStyleAttr, 0)
try {
fitToHeight = a.getBoolean(R.styleable.ChordWidget_fitToHeight, DEFAULT_FIT_TO_HEIGHT)
fretColor = a.getColor(R.styleable.ChordWidget_fretColor, DEFAULT_COLOR)
stringColor = a.getColor(R.styleable.ChordWidget_stringColor, DEFAULT_COLOR)
fretLabelTextColor = a.getColor(R.styleable.ChordWidget_fretLabelTextColor, DEFAULT_COLOR)
stringLabelTextColor = a.getColor(R.styleable.ChordWidget_stringLabelTextColor, DEFAULT_COLOR)
noteColor = a.getColor(R.styleable.ChordWidget_noteColor, DEFAULT_COLOR)
noteLabelTextColor = a.getColor(R.styleable.ChordWidget_noteLabelTextColor, DEFAULT_TEXT_COLOR)
mutedStringText = a.getString(R.styleable.ChordWidget_mutedStringText)
?: DEFAULT_MUTED_TEXT
openStringText = a.getString(R.styleable.ChordWidget_openStringText)
?: DEFAULT_OPEN_TEXT
stringLabelState = when (a.getInt(R.styleable.ChordWidget_stringLabelState, 0)) {
0 -> StringLabelState.SHOW_NUMBER
1 -> StringLabelState.SHOW_LABEL
else -> StringLabelState.HIDE
}
showFingerNumbers = a.getBoolean(R.styleable.ChordWidget_showFingerNumbers, DEFAULT_SHOW_FINGER_NUMBERS)
showFretNumbers = a.getBoolean(R.styleable.ChordWidget_showFretNumbers, DEFAULT_SHOW_FRET_NUMBERS)
a.getTypeface(context, R.styleable.ChordWidget_fretLabelTypeface)?.let { fretLabelTypeface = it }
a.getTypeface(context, R.styleable.ChordWidget_noteLabelTypeface)?.let { noteLabelTypeface = it }
a.getTypeface(context, R.styleable.ChordWidget_stringLabelTypeface)?.let { stringLabelTypeface = it }
} finally {
a.recycle()
}
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
calculateSize()
calculateBarLinePositions()
calculateFretNumberPositions()
calculateFretPositions()
calculateNotePositions()
calculateStringMarkers()
calculateStringPositions()
}
override fun onDraw(canvas: Canvas) {
// First draw the strings and fret markers
fretLineRects.forEach { canvas.drawLine(it, fretPaint) }
stringLineRects.forEach { canvas.drawLine(it, stringPaint) }
// Next draw the fret numbers and string markers
drawFretNumbers(canvas)
drawStringMarkers(canvas)
// Finally, draw all the notes and the note text
drawBars(canvas)
drawNotes(canvas)
}
override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState() as Parcelable
val savedState = SavedState(superState)
savedState.chart = chart
savedState.chord = chord
return savedState
}
override fun onRestoreInstanceState(state: Parcelable) {
if (state is SavedState) {
super.onRestoreInstanceState(state.superState)
chart = state.chart
chord = state.chord
} else {
super.onRestoreInstanceState(state)
}
}
private fun calculateSize() {
val absoluteWidth = measuredWidth - (paddingLeft + paddingRight).toFloat()
val absoluteHeight = measuredHeight - (paddingTop + paddingBottom).toFloat()
val minSideSize = min(absoluteWidth, absoluteHeight)
val actualWidth = if (fitToHeight) minSideSize * (2f / 3f) else absoluteWidth
val actualHeight = if (fitToHeight) minSideSize else absoluteHeight
// Give some space for the labels
val horizontalExtraCount = if (showFretNumbers) 1 else 0
val verticalExtraCount = if (showBottomStringLabels) 2 else 1
// We add 1 to make room for two halves of notes displayed on the first and last strings. Otherwise, they'll be cut-off.
noteSize = min((actualWidth / (chart.stringCount + 1 + horizontalExtraCount)), (actualHeight / (fretCount + 1 + verticalExtraCount)))
val textSize = noteSize * .75f
fretLabelTextSize = textSize
stringLabelTextSize = textSize
noteLabelTextSize = textSize
stringDistance = noteSize
stringSize = (stringDistance / chart.stringCount).coerceAtLeast(1f)
fretMarkerSize = stringSize
fretSize = round((actualHeight - (noteSize * verticalExtraCount) - (fretCount + 1) * fretMarkerSize) / fretCount)
val drawingWidth = noteSize * (chart.stringCount + 1 + horizontalExtraCount)
val drawingHeight = (fretSize * fretCount) + (noteSize * (1 + verticalExtraCount))
// Center everything
drawingBounds.set(
(absoluteWidth - drawingWidth) / 2,
(absoluteHeight - drawingHeight) / 2,
(absoluteWidth - drawingWidth) / 2 + drawingWidth,
(absoluteHeight - drawingHeight) / 2 + drawingHeight)
// The actual chart bounds
chartBounds.set(
drawingBounds.left + (noteSize * horizontalExtraCount) + (noteSize * .5f),
drawingBounds.top + noteSize,
drawingBounds.right - (noteSize * .5f),
drawingBounds.bottom - (if (showBottomStringLabels) noteSize else 0f))
// The open/closed labels for the String above the chart
stringTopLabelBounds.set(
chartBounds.left,
drawingBounds.top,
chartBounds.right,
drawingBounds.top + noteSize)
// The number/note labels for the String below the chart
stringBottomLabelBounds.set(
chartBounds.left,
chartBounds.bottom,
chartBounds.right,
chartBounds.bottom + noteSize)
// The fret number labels on the side of the chart
fretSideLabelBounds.set(
drawingBounds.left,
chartBounds.top,
drawingBounds.left + noteSize,
drawingBounds.bottom)
}
private fun calculateFretPositions() {
fretLineRects.clear()
for (i in 0..fretCount) {
fretLineRects.add(RectF(
chartBounds.left,
chartBounds.top + i * fretSize + i * fretMarkerSize,
chartBounds.right - stringSize,
chartBounds.top + i * fretSize + i * fretMarkerSize))
}
}
private fun calculateStringPositions() {
stringLineRects.clear()
for (i in 0 until chart.stringCount) {
stringLineRects.add(RectF(
chartBounds.left + i * stringDistance + i * stringSize,
chartBounds.top,
chartBounds.left + i * stringDistance + i * stringSize,
chartBounds.top + fretCount * fretSize + fretCount * fretMarkerSize))
}
}
private fun calculateFretNumberPositions() {
fretNumberPoints.clear()
for (i in 0..(chart.fretEnd.number - chart.fretStart.number)) {
fretNumberPoints.add(PointF(
drawingBounds.left + fretSideLabelBounds.width() / 2,
getVerticalCenterTextPosition(stringTopLabelBounds.bottom + i * fretMarkerSize + i * fretSize + fretSize / 2, (i + 1).toString(), fretLabelTextPaint)))
}
}
private fun calculateBarLinePositions() {
barLinePaths.clear()
chord?.bars?.forEach { bar ->
if (bar.fret.number in chart.fretStart.number..chart.fretEnd.number && bar.endString.number < chart.stringCount + 1) {
val relativeFretNumber = bar.fret.number - (chart.fretStart.number - 1)
val left = (chartBounds.left + (chart.stringCount - bar.endString.number) * stringDistance +
(chart.stringCount - bar.endString.number) * stringSize) - noteSize / 2
val top = chartBounds.top + (relativeFretNumber * fretSize + relativeFretNumber * fretMarkerSize - fretSize / 2) - (noteSize / 2)
val right = (chartBounds.left + (chart.stringCount - bar.startString.number) * stringDistance +
(chart.stringCount - bar.startString.number) * stringSize) + (noteSize / 2)
val bottom = top + noteSize
val text = if (bar.finger === Finger.UNKNOWN) "" else bar.finger.toString()
val textX = left + (right - left) / 2
val textY = getVerticalCenterTextPosition(top + (bottom - top) / 2, text, noteLabelTextPaint)
barLinePaths.add(
BarPosition(
text = text,
textX = textX,
textY = textY,
left = left,
top = top,
right = right,
bottom = bottom))
}
}
}
private fun calculateNotePositions() {
notePositions.clear()
chord?.notes?.forEach { note ->
if (note.fret.number in chart.fretStart.number..chart.fretEnd.number && note.string.number < chart.stringCount + 1) {
val relativeFretNumber = note.fret.number - (chart.fretStart.number - 1)
val startCenterX = chartBounds.left + (chart.stringCount - note.string.number) * stringDistance + (chart.stringCount - note.string.number) * stringSize
val startCenterY = chartBounds.top + (relativeFretNumber * fretSize + relativeFretNumber * fretMarkerSize - fretSize / 2)
val text = if (note.finger === Finger.UNKNOWN) "" else note.finger.toString()
notePositions.add(
NotePosition(
text = text,
circleX = startCenterX,
circleY = startCenterY,
textX = startCenterX,
textY = getVerticalCenterTextPosition(startCenterY, text, noteLabelTextPaint)))
}
}
}
private fun calculateStringMarkers() {
stringBottomLabelPositions.clear()
stringTopMarkerPositions.clear()
// Top string mute labels
chord?.mutes?.forEach { muted ->
if (muted.string.number < chart.stringCount + 1) {
val x = chartBounds.left + (chart.stringCount - muted.string.number) * stringDistance + (chart.stringCount - muted.string.number) * stringSize
val y = getVerticalCenterTextPosition(drawingBounds.top + stringTopLabelBounds.height() / 2, mutedStringText, stringLabelTextPaint)
stringTopMarkerPositions.add(
StringPosition(
text = mutedStringText,
textX = x,
textY = y))
}
}
// Top string open labels
chord?.opens?.forEach { open ->
if (open.string.number < chart.stringCount + 1) {
val x = chartBounds.left + (chart.stringCount - open.string.number) * stringDistance + (chart.stringCount - open.string.number) * stringSize
val y = getVerticalCenterTextPosition(drawingBounds.top + stringTopLabelBounds.height() / 2, openStringText, stringLabelTextPaint)
stringTopMarkerPositions.add(
StringPosition(
text = openStringText,
textX = x,
textY = y))
}
}
if (showBottomStringLabels) {
chart.stringLabels.forEach { stringLabel ->
if (stringLabel.string.number < chart.stringCount + 1) {
val label = if (stringLabelState == StringLabelState.SHOW_NUMBER) stringLabel.string.toString() else stringLabel.label
if (label != null) {
val x = chartBounds.left + (chart.stringCount - stringLabel.string.number) * stringDistance + (chart.stringCount - stringLabel.string.number) * stringSize
val y = getVerticalCenterTextPosition(chartBounds.bottom + stringBottomLabelBounds.height() / 2, label, stringLabelTextPaint)
stringBottomLabelPositions.add(
StringPosition(
text = label,
textX = x,
textY = y))
}
}
}
}
}
private fun drawFretNumbers(canvas: Canvas) {
// Fret numbers; check if we are showing them or not
if (showFretNumbers) {
fretNumberPoints.forEachIndexed { index, point ->
canvas.drawText((chart.fretStart.number + index).toString(), point.x, point.y, fretLabelTextPaint)
}
}
}
private fun drawStringMarkers(canvas: Canvas) {
// Top String markers (open/muted)
stringTopMarkerPositions.forEach { canvas.drawText(it.text, it.textX, it.textY, stringLabelTextPaint) }
// Bottom String labels (number/note)
stringBottomLabelPositions.forEach { canvas.drawText(it.text, it.textX, it.textY, stringLabelTextPaint) }
}
private fun drawBars(canvas: Canvas) {
// Bars
barLinePaths.forEach {
// Draw Bar
canvas.drawRoundRect(it.left, it.top, it.right, it.bottom, (it.bottom - it.top), (it.bottom - it.top), barLinePaint)
// Text
if (showFingerNumbers) {
canvas.drawText(it.text, it.textX, it.textY, noteLabelTextPaint)
}
}
}
private fun drawNotes(canvas: Canvas) {
//Individual notes
notePositions.forEach {
canvas.drawCircle(it.circleX, it.circleY, noteSize / 2f, notePaint)
if (showFingerNumbers) {
canvas.drawText(it.text, it.textX, it.textY, noteLabelTextPaint)
}
}
}
private fun getVerticalCenterTextPosition(originalYPosition: Float, text: String?, textPaint: Paint): Float {
val bounds = Rect()
textPaint.getTextBounds(text, 0, text?.length ?: 0, bounds)
return originalYPosition + bounds.height() / 2
}
private fun Canvas.drawLine(rectF: RectF, paint: Paint) =
drawLine(rectF.left, rectF.top, rectF.right, rectF.bottom, paint)
companion object {
const val DEFAULT_COLOR = Color.BLACK
const val DEFAULT_TEXT_COLOR = Color.WHITE
}
private class SavedState : BaseSavedState {
companion object {
@Suppress("unused")
@JvmField
val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(source: Parcel): SavedState = SavedState(source)
override fun newArray(size: Int): Array<SavedState?> = arrayOfNulls(size)
}
}
var chart: ChordChart = ChordChart.STANDARD_TUNING_GUITAR_CHART
var chord: Chord? = null
constructor(parcelable: Parcelable) : super(parcelable)
constructor(parcel: Parcel) : super(parcel) {
chart = ChordChartParceler.create(parcel)
chord = try {
ChordParceler.create(parcel)
} catch (throwable: Throwable) {
null
}
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeChordChart(chart, flags)
chord?.let { parcel.writeChord(it, flags) }
}
}
private data class NotePosition(
val text: String,
val circleX: Float,
val circleY: Float,
val textX: Float,
val textY: Float
)
private data class StringPosition(
val text: String,
val textX: Float,
val textY: Float
)
private data class BarPosition(
val text: String,
val left: Float,
val top: Float,
val right: Float,
val bottom: Float,
val textX: Float,
val textY: Float
)
}
| apache-2.0 | 47056448952eb240e9ac6c66f61473f2 | 37.118003 | 178 | 0.59688 | 5.060454 | false | false | false | false |
kotlintest/kotlintest | kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/properties/shrinking/ShrinkTest.kt | 1 | 5126 | //package com.sksamuel.kotest.properties.shrinking
//
//import io.kotest.matchers.comparables.lte
//import io.kotest.matchers.doubles.lt
//import io.kotest.matchers.ints.shouldBeLessThan
//import io.kotest.matchers.string.shouldHaveLength
//import io.kotest.properties.Gen
//import io.kotest.properties.PropertyTesting
//import io.kotest.properties.assertAll
//import io.kotest.properties.double
//import io.kotest.properties.int
//import io.kotest.properties.negativeIntegers
//import io.kotest.properties.positiveIntegers
//import io.kotest.properties.shrinking.ChooseShrinker
//import io.kotest.properties.shrinking.Shrinker
//import io.kotest.properties.shrinking.StringShrinker
//import io.kotest.properties.string
//import io.kotest.shouldBe
//import io.kotest.shouldThrowAny
//import io.kotest.core.spec.style.StringSpec
//
//class ShrinkTest : StringSpec({
//
// beforeSpec {
// PropertyTesting.shouldPrintShrinkSteps = false
// }
//
// afterSpec {
// PropertyTesting.shouldPrintShrinkSteps = true
// }
//
// "should report shrinked values for arity 1 ints" {
// shouldThrowAny {
// assertAll(Gen.int()) {
// it.shouldBeLessThan(5)
// }
// }.message shouldBe "Property failed for\n" +
// "Arg 0: 5 (shrunk from 2147483647)\n" +
// "after 2 attempts\n" +
// "Caused by: 2147483647 should be < 5"
// }
//
// "should shrink arity 2 strings" {
// shouldThrowAny {
// assertAll(Gen.string(), Gen.string()) { a, b ->
// (a.length + b.length).shouldBeLessThan(4)
// }
// }.message shouldBe "Property failed for\n" +
// "Arg 0: <empty string>\n" +
// "Arg 1: aaaaa (shrunk from \n" +
// "abc\n" +
// "123\n" +
// ")\n" +
// "after 3 attempts\n" +
// "Caused by: 9 should be < 4"
// }
//
// "should shrink arity 3 positiveIntegers" {
// shouldThrowAny {
// assertAll(Gen.positiveIntegers(), Gen.positiveIntegers(), Gen.positiveIntegers()) { a, b, c ->
// a.toLong() + b.toLong() + c.toLong() shouldBe 4L
// }
// }.message shouldBe "Property failed for\nArg 0: 1 (shrunk from 2147483647)\nArg 1: 1 (shrunk from 2147483647)\nArg 2: 1 (shrunk from 2147483647)\nafter 1 attempts\nCaused by: expected: 4L but was: 6442450941L"
// }
//
// "should shrink arity 4 negativeIntegers" {
// shouldThrowAny {
// assertAll(Gen.negativeIntegers(),
// Gen.negativeIntegers(),
// Gen.negativeIntegers(),
// Gen.negativeIntegers()) { a, b, c, d ->
// a + b + c + d shouldBe 4
// }
// }.message shouldBe "Property failed for\nArg 0: -1 (shrunk from -2147483648)\nArg 1: -1 (shrunk from -2147483648)\nArg 2: -1 (shrunk from -2147483648)\nArg 3: -1 (shrunk from -2147483648)\nafter 1 attempts\nCaused by: expected: 4 but was: 0"
// }
//
// "should shrink arity 1 doubles" {
// shouldThrowAny {
// assertAll(Gen.double()) { a ->
// a shouldBe lt(3.0)
// }
// }.message shouldBe "Property failed for\nArg 0: 3.0 (shrunk from 1.0E300)\nafter 4 attempts\nCaused by: 1.0E300 should be < 3.0"
// }
//
// "should shrink Gen.choose" {
// shouldThrowAny {
// assertAll(object : Gen<Int> {
// override fun constants(): Iterable<Int> = emptyList()
// override fun random(seed: Long?): Sequence<Int> = generateSequence { 14 }
// override fun shrinker() = ChooseShrinker(5, 15)
// }) { a ->
// a shouldBe lte(10)
// }
// }.message shouldBe "Property failed for\nArg 0: 11 (shrunk from 14)\nafter 1 attempts\nCaused by: 14 should be <= 10"
// }
//
// "should shrink strings to empty string" {
// val gen = object : Gen<String> {
// override fun random(seed: Long?): Sequence<String> = generateSequence { "asjfiojoqiwehuoahsuidhqweqwe" }
// override fun constants(): Iterable<String> = emptyList()
// override fun shrinker(): Shrinker<String>? = StringShrinker
// }
// shouldThrowAny {
// assertAll(gen) { a ->
// a.shouldHaveLength(10)
// }
// }.message shouldBe "Property failed for\nArg 0: <empty string> (shrunk from asjfiojoqiwehuoahsuidhqweqwe)\nafter 1 attempts\nCaused by: asjfiojoqiwehuoahsuidhqweqwe should have length 10, but instead was 28"
// }
//
// "should shrink strings to min failing size" {
// val gen = object : Gen<String> {
// override fun random(seed: Long?): Sequence<String> = generateSequence { "asjfiojoqiwehuoahsuidhqweqwe" }
// override fun constants(): Iterable<String> = emptyList()
// override fun shrinker(): Shrinker<String>? = StringShrinker
// }
// shouldThrowAny {
// assertAll(gen) { a ->
// a.padEnd(10, '*').shouldHaveLength(10)
// }
// }.message shouldBe "Property failed for\nArg 0: aaaaaaaaaaaaaa (shrunk from asjfiojoqiwehuoahsuidhqweqwe)\nafter 1 attempts\nCaused by: asjfiojoqiwehuoahsuidhqweqwe should have length 10, but instead was 28"
// }
//})
| apache-2.0 | 10a8ce10dae37324c744b01b12dfc23d | 41.016393 | 249 | 0.623878 | 3.802671 | false | true | false | false |
alondero/nestlin | src/main/kotlin/com/github/alondero/nestlin/ppu/PpuAddressedMemory.kt | 1 | 9645 | package com.github.alondero.nestlin.ppu
import com.github.alondero.nestlin.*
class PpuAddressedMemory {
val controller = Control() // $2000
val mask = Mask() // $2001
val status = Status() // $2002
var oamAddress: Byte = 0 // $2003
var oamData: Byte = 0 // $2004
var scroll: Byte = 0 // $2005
var address: Byte = 0 // $2006
var data: Byte = 0 // $2007
private var writeToggle = false
val ppuInternalMemory = PpuInternalMemory()
val objectAttributeMemory = ObjectAttributeMemory()
val vRamAddress = VramAddress() // v
val tempVRamAddress = VramAddress() // t
var fineXScroll = 0 // x
var nmiOccurred = false
var nmiOutput = false
fun reset() {
controller.reset()
mask.reset()
status.reset()
oamAddress = 0
oamData = 0
scroll = 0
address = 0
data = 0
writeToggle = false
}
operator fun get(addr: Int) = when (addr) {
0 -> controller.register
1 -> mask.register
2 -> {
writeToggle = false
val value = status.register.letBit(7, nmiOccurred)
status.clearVBlank()
nmiOccurred = false
value
}
3 -> oamAddress
4 -> oamData
5 -> scroll
6 -> address
else /*7*/ -> {
vRamAddress += controller.vramAddressIncrement()
data
}
}
operator fun set(addr: Int, value: Byte) {
// println("Setting PPU Addressed data ${addr.toHexString()}, with ${value.toHexString()}")
when (addr) {
0 -> {
controller.register = value
tempVRamAddress.updateNameTable(value.toUnsignedInt() and 0x03)
}
1 -> mask.register = value
2 -> status.register = value
3 -> oamAddress = value
4 -> oamData = value
5 -> {
scroll = value
if (writeToggle) {
tempVRamAddress.coarseYScroll = (value.toUnsignedInt() shr 3) and 0x1F
tempVRamAddress.fineYScroll = value.toUnsignedInt() and 0x07
} else {
tempVRamAddress.coarseXScroll = (value.toUnsignedInt() shr 3) and 0x1F
fineXScroll = value.toUnsignedInt() and 0x07
}
writeToggle = !writeToggle
}
6 -> {
address = value
if (writeToggle) {
tempVRamAddress.setLowerByte(value)
} else {
tempVRamAddress.setUpper7Bits(value)
}
}
else /*7*/ -> {
vRamAddress += controller.vramAddressIncrement()
data = value.letBit(7, nmiOutput)
}
}
}
}
class VramAddress {
/** 15 bit register
yyy NN YYYYY XXXXX
||| || ||||| +++++-- coarse X scroll
||| || +++++-------- coarse Y scroll
||| |+-------------- horizontal nametable select
||| +--------------- vertical nametable select
+++----------------- fine Y scroll
*/
var coarseXScroll = 0
var coarseYScroll = 0 // 5 bits so maximum value is 31
var horizontalNameTable = false
var verticalNameTable = false
var fineYScroll = 0 // 3 bits so maximum value is 7 - wraps to coarseY if overflows
fun setUpper7Bits(bits: Byte) {
fineYScroll = (bits.toUnsignedInt() shr 4) and 0x03
horizontalNameTable = bits.isBitSet(2)
verticalNameTable = bits.isBitSet(3)
coarseYScroll = (coarseYScroll and 0x07) or ((bits.toUnsignedInt() and 0x03) shl 3)
}
fun setLowerByte(byte: Byte) {
coarseXScroll = byte.toUnsignedInt() and 0x1F
coarseYScroll = (coarseYScroll and 0x18) or ((byte.toUnsignedInt()) shr 5)
}
fun updateNameTable(nameTable: Int) {
nameTable.toSignedByte().let {
horizontalNameTable = it.isBitSet(0)
verticalNameTable = it.isBitSet(1)
}
}
private fun getNameTable() = (if (verticalNameTable) 2 else 0) + (if (horizontalNameTable) 1 else 0)
fun incrementVerticalPosition() {
fineYScroll++
if (fineYScroll > 7) {
coarseYScroll++
fineYScroll = 0
if (coarseYScroll > 29) {
// Y Scroll now out of bounds
if (coarseYScroll < 32) {
// Hasn't overflowed therefore switch vertical nametable
verticalNameTable = !verticalNameTable
}
coarseYScroll = 0
}
}
}
fun incrementHorizontalPosition() {
coarseXScroll++
if (coarseXScroll > 31) {
horizontalNameTable = !horizontalNameTable
coarseXScroll = 0
}
}
infix operator fun plusAssign(vramAddressIncrement: Int) {
if (vramAddressIncrement == 32) {
coarseYScroll++
} else {
coarseXScroll++
}
}
fun asAddress() = (((((fineYScroll shl 2) or getNameTable()) shl 5) or coarseYScroll) shl 5) or coarseXScroll
}
class Control {
var register: Byte = 0
fun reset() {
register = 0
}
fun baseNametableAddr() = 0x2000 + ((register.toUnsignedInt() and 0b00000011) * 0x400)
fun vramAddressIncrement() = if (register.isBitSet(2)) 32 else 1
fun spritePatternTableAddress() = if (register.isBitSet(3)) 0x1000 else 0
fun backgroundPatternTableAddress() = if (register.isBitSet(4)) 0x1000 else 0
fun spriteSize() = if (register.isBitSet(5)) SpriteSize.X_8_16 else SpriteSize.X_8_8
fun generateNmi() = register.isBitSet(7)
enum class SpriteSize {
X_8_8, X_8_16
}
}
class Mask {
var register: Byte = 0
fun reset() {
register = 0
}
/**
7 bit 0
---- ----
BGRs bMmG
|||| ||||
|||| |||+- Greyscale (0: normal color, 1: produce a greyscale display)
|||| ||+-- 1: Show background in leftmost 8 pixels of screen, 0: Hide
|||| |+--- 1: Show sprites in leftmost 8 pixels of screen, 0: Hide
|||| +---- 1: Show background
|||+------ 1: Show sprites
||+------- Emphasize red*
|+-------- Emphasize green*
+--------- Emphasize blue*
*/
fun greyscale() = register.isBitSet(0)
fun backgroundInLeftmost8px() = register.isBitSet(1)
fun spritesInLeftmost8px() = register.isBitSet(2)
fun showBackground() = register.isBitSet(3)
fun showSprites() = register.isBitSet(4)
fun emphasizeRed() = register.isBitSet(5)
fun emphasizeGreen() = register.isBitSet(6)
fun emphasizeBlue() = register.isBitSet(7)
}
class Status {
var register: Byte = 0
/**
7 bit 0
---- ----
VSO. ....
|||| ||||
|||+-++++- Least significant bits previously written into a PPU register
||| (due to register not being updated for this address)
||+------- Sprite overflow. The intent was for this flag to be set
|| whenever more than eight sprites appear on a scanline, but a
|| hardware bug causes the actual behavior to be more complicated
|| and generate false positives as well as false negatives; see
|| PPU sprite evaluation. This flag is set during sprite
|| evaluation and cleared at dot 1 (the second dot) of the
|| pre-render line.
|+-------- Sprite 0 Hit. Set when a nonzero pixel of sprite 0 overlaps
| a nonzero background pixel; cleared at dot 1 of the pre-render
| line. Used for raster timing.
+--------- Vertical blank has started (0: not in vblank; 1: in vblank).
Set at dot 1 of line 241 (the line *after* the post-render
line); cleared after reading $2002 and at dot 1 of the
pre-render line.
*/
fun spriteOverflow() = register.isBitSet(5)
fun sprite0Hit() = register.isBitSet(6)
fun vBlankStarted() = register.isBitSet(7)
fun reset() { register = 0 }
fun clearOverflow() { register = register.clearBit(5) }
fun clearVBlank() { register = register.clearBit(7) }
fun clearFlags() {reset()}
}
class PpuInternalMemory {
private val patternTable0 = ByteArray(0x1000)
private val patternTable1 = ByteArray(0x1000)
private val nameTable0 = ByteArray(0x400)
private val nameTable1 = ByteArray(0x400)
private val nameTable2 = ByteArray(0x400)
private val nameTable3 = ByteArray(0x400)
private val paletteRam = PaletteRam()
// private val backgroundNametables = Background()
// private val spriteNametables = Sprites()
operator fun get(addr: Int): Byte = when (addr) {
in 0x0000..0x0999 -> patternTable0[addr % 0x1000]
in 0x1000..0x1999 -> patternTable1[addr % 0x1000]
in 0x2000..0x23FF -> nameTable0[addr % 0x400]
in 0x2400..0x27FF -> nameTable1[addr % 0x400]
in 0x2800..0x2BFF -> nameTable2[addr % 0x400]
in 0x2C00..0x2FFF -> nameTable3[addr % 0x400]
in 0x3000..0x3EFF -> this[addr - 0x1000] // Mirror of 0x2000 - 0x2EFF
else /*in 0x3F00..0x3FFF*/ -> paletteRam[addr % 0x020]
}
}
class PaletteRam {
private val bgPalette = ByteArray(0x10)
private val spritePalette = ByteArray(0x10)
operator fun get(addr: Int): Byte = when (addr) {
in 0x00..0x0F -> bgPalette[addr]
else /*in 0x10..0x1F*/ -> spritePalette[addr]
}
} | gpl-3.0 | 68043af4ccf0c9d2f0368dc42664d5a2 | 31.26087 | 113 | 0.56309 | 4.21179 | false | false | false | false |
vania-pooh/kotlin-algorithms | src/com/freaklius/kotlin/algorithms/sort/HeapSort.kt | 1 | 2350 | package com.freaklius.kotlin.algorithms.sort
/**
* Heap sort algorithm
* AveragePerformance = O(n*lg(n))
*/
class HeapSort : SortAlgorithm {
/**
* Stores size of the heap to be used
*/
private var heapSize = 0
override fun sort(arr: Array<Long>): Array<Long> {
buildMaxHeap(arr)
var i: Int = arr.size - 1
while (i >= 1){
swap(arr, i, 0)
heapSize--
maxHeapify(arr, 0)
i--
}
return arr
}
/**
* Builds a max-heap data structure from the input array (the original array is replaced) using maxHeapify method
* @param arr
*/
private fun buildMaxHeap(arr: Array<Long>){
heapSize = arr.size
var i: Int = Math.floor(arr.size / 2.0).toInt()
while (i >= 0){
maxHeapify(arr, i)
i--
}
}
/**
* Restores MaxHeap property starting from the array's ith element and going down
* @param arr
* @param i heap index where we need to check the property; we implicitly assume that child heaps conform to the
* MaxHeap property
*/
private fun maxHeapify(arr: Array<Long>, i: Int){
val leftElementIndex = left(i)
val rightElementIndex = right(i)
var largestElementIndex : Int = i
if ( (leftElementIndex <= heapSize - 1) && (arr[leftElementIndex] > arr[i]) ){
largestElementIndex = leftElementIndex
}
if ( (rightElementIndex <= heapSize - 1) && (arr[rightElementIndex] > arr[largestElementIndex]) ){
largestElementIndex = rightElementIndex
}
if (largestElementIndex != i){
swap(arr, i, largestElementIndex)
maxHeapify(arr, largestElementIndex)
}
}
/**
* Returns the index of the array element corresponding to the left element of the ith element in the heap
* @param i an element to get the left element
*/
private fun left(i: Int) : Int{
return 2 * i + 1
}
/**
* Returns the index of the array element corresponding to the right element of the ith element in the heap
* @param i an element to get the left element
*/
private fun right(i: Int) : Int{
return 2 * i + 2
}
override fun getName(): String {
return "HeapSort"
}
} | mit | 0061761bc0cb0b40a282a7869f13d766 | 27.670732 | 117 | 0.580426 | 4.272727 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/refactoring/RsImportOptimizer.kt | 1 | 3323 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.refactoring
import com.intellij.lang.ImportOptimizer
import com.intellij.psi.PsiFile
import org.rust.ide.formatter.processors.asTrivial
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.psi.ext.childrenOfType
class RsImportOptimizer : ImportOptimizer {
override fun supports(file: PsiFile?): Boolean = file is RsFile
override fun processFile(file: PsiFile?) = Runnable {
executeForUseItem(file as RsFile)
executeForExternCrate(file)
}
private fun executeForExternCrate(file: RsFile) {
val first = file.childrenOfType<RsElement>()
.firstOrNull { it !is RsInnerAttr } ?: return
val externCrateItems = file.childrenOfType<RsExternCrateItem>()
externCrateItems
.sortedBy { it.referenceName }
.mapNotNull { it.copy() as? RsExternCrateItem }
.forEach { file.addBefore(it, first) }
externCrateItems.forEach { it.delete() }
}
private fun executeForUseItem(mod: RsMod) {
val uses = mod.childrenOfType<RsUseItem>()
if (uses.isEmpty()) {
return
}
replaceOrderOfUseItems(mod, uses)
val mods = mod.childrenOfType<RsMod>()
mods.forEach { executeForUseItem(it) }
}
companion object {
private fun optimizeUseSpeck(psiFactory: RsPsiFactory, useSpeck: RsUseSpeck) {
if (removeCurlyBraces(psiFactory, useSpeck)) return
val useSpeckList = useSpeck.useGroup?.useSpeckList ?: return
if (useSpeckList.size < 2) return
useSpeckList.forEach { optimizeUseSpeck(psiFactory, it) }
val sortedList = useSpeckList
.sortedWith(compareBy<RsUseSpeck> { it.path?.self == null }.thenBy { it.pathText })
.map { it.copy() }
useSpeckList.zip(sortedList).forEach { it.first.replace(it.second) }
}
private fun removeCurlyBraces(psiFactory: RsPsiFactory, useSpeck: RsUseSpeck): Boolean {
val name = useSpeck.useGroup?.asTrivial?.text ?: return false
val path = useSpeck.path?.text
val tempPath = "${if (path != null) "$path::" else ""}$name"
val newUseSpeck = psiFactory.createUseSpeck(tempPath)
useSpeck.replace(newUseSpeck)
return true
}
private fun replaceOrderOfUseItems(file: RsMod, uses: Collection<RsUseItem>) {
val first = file.childrenOfType<RsElement>()
.firstOrNull { it !is RsExternCrateItem && it !is RsInnerAttr } ?: return
val psiFactory = RsPsiFactory(file.project)
val sortedUses = uses
.sortedBy { it.useSpeck?.pathText }
.mapNotNull { it.copy() as? RsUseItem }
sortedUses
.mapNotNull { it.useSpeck }
.forEach { optimizeUseSpeck(psiFactory, it) }
for (importPath in sortedUses) {
file.addBefore(importPath, first)
}
uses.forEach { it.delete() }
}
}
}
private val RsUseSpeck.pathText get() = path?.text?.toLowerCase()
| mit | 22845cde958fecba9943d3c7a0b8c036 | 37.195402 | 99 | 0.628649 | 4.713475 | false | false | false | false |
icarumbas/bagel | core/src/ru/icarumbas/bagel/view/screens/LoadingScreen.kt | 1 | 3086 | package ru.icarumbas.bagel.view.screens
import com.badlogic.gdx.ScreenAdapter
import com.badlogic.gdx.graphics.g2d.Animation
import com.badlogic.gdx.graphics.g2d.Animation.PlayMode
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Image
import com.badlogic.gdx.utils.viewport.ExtendViewport
import ru.icarumbas.Bagel
import ru.icarumbas.bagel.engine.resources.ResourceManager
import ru.icarumbas.bagel.view.ui.actors.LoadingBar
class LoadingScreen(
private val assets: ResourceManager,
private val game: Bagel
) : ScreenAdapter() {
private val WIDTH = 800f
private val HEIGHT = 480f
private val loadingPack = TextureAtlas("Packs/LoadingScreen.pack")
private val stage = Stage(ExtendViewport(WIDTH, HEIGHT))
private val screenBg = Image(loadingPack.findRegion("screen-bg")).apply {
setSize(WIDTH, HEIGHT)
}
private val logo = Image(loadingPack.findRegion("IcaIcon")).apply {
x = (WIDTH - width) / 2
y = (HEIGHT - height) / 2 + 100
}
private val loadingFrame = Image(loadingPack.findRegion("loading-frame")).apply {
x = (WIDTH - width) / 2
y = (HEIGHT - height) / 2
}
private val loadingBar = LoadingBar(
Animation(0.05f, loadingPack.findRegions("loading-bar-anim"), PlayMode.LOOP_REVERSED)).apply {
x = loadingFrame.x + 15
y = loadingFrame.y + 5
}
private val loadingBarHidden = Image(
loadingPack.findRegion("loading-bar-hidden")).apply {
x = loadingBar.x + 35
y = loadingBar.y - 3
}
/* The rest of the hidden bar */
private val loadingBg = Image(loadingPack.findRegion("loading-frame-bg")).apply {
setSize(450f, 50f)
x = loadingBarHidden.x + 30
y = loadingBarHidden.y + 3
invalidate()
}
/* The start position and how far to move the hidden loading bar */
private var startX = loadingBarHidden.x
private var endX = 440f
private var percent = 0f
init {
assets.loadAssets()
with (stage) {
addActor(screenBg)
addActor(loadingBar)
addActor(loadingBg)
addActor(loadingBarHidden)
addActor(loadingFrame)
addActor(logo)
}
}
override fun render(delta: Float) {
if (assets.assetManager.update()) {
game.screen = MainMenuScreen(game)
}
// Interpolate the percentage to make it more smooth
percent = Interpolation.linear.apply(percent, assets.assetManager.progress, 0.1f)
loadingBarHidden.x = startX + endX * percent
loadingBg.x = loadingBarHidden.x + 30
loadingBg.width = 450 - 450 * percent
stage.draw()
stage.act()
}
override fun resize(width: Int, height: Int) {
stage.viewport.update(width , height, false)
}
override fun dispose() {
stage.dispose()
loadingPack.dispose()
}
} | apache-2.0 | d903f47824e46653bbb187de3bffb90b | 27.850467 | 106 | 0.64744 | 4.147849 | false | false | false | false |
semonte/intellij-community | platform/platform-api/src/com/intellij/openapi/project/ProjectUtil.kt | 1 | 8232 | /*
* 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.
*/
@file:JvmName("ProjectUtil")
package com.intellij.openapi.project
import com.intellij.ide.DataManager
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.appSystemDir
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFilePathWrapper
import com.intellij.util.PathUtilRt
import com.intellij.util.io.exists
import com.intellij.util.text.trimMiddle
import org.jetbrains.annotations.TestOnly
import java.nio.file.InvalidPathException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.function.Consumer
import javax.swing.JComponent
val Module.rootManager: ModuleRootManager
get() = ModuleRootManager.getInstance(this)
@JvmOverloads
fun calcRelativeToProjectPath(file: VirtualFile, project: Project?, includeFilePath: Boolean = true, includeUniqueFilePath: Boolean = false, keepModuleAlwaysOnTheLeft: Boolean = false): String {
if (file is VirtualFilePathWrapper && file.enforcePresentableName()) {
return if (includeFilePath) file.presentablePath else file.name
}
val url = if (includeFilePath) {
file.presentableUrl
}
else if (includeUniqueFilePath) {
UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file)
}
else {
file.name
}
if (project == null) {
return url
}
return displayUrlRelativeToProject(file, url, project, includeFilePath, keepModuleAlwaysOnTheLeft)
}
fun guessProjectForFile(file: VirtualFile?): Project? = ProjectLocator.getInstance().guessProjectForFile(file)
/***
* guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned
*/
@JvmOverloads
fun guessProjectForContentFile(file: VirtualFile, fileType: FileType = file.fileType): Project? {
if (ProjectCoreUtil.isProjectOrWorkspaceFile(file, fileType)) {
return null
}
return ProjectManager.getInstance().openProjects.firstOrNull { !it.isDefault && it.isInitialized && !it.isDisposed && ProjectRootManager.getInstance(it).fileIndex.isInContent(file) }
}
fun isProjectOrWorkspaceFile(file: VirtualFile): Boolean {
// do not use file.getFileType() to avoid autodetection by content loading for arbitrary files
return ProjectCoreUtil.isProjectOrWorkspaceFile(file, FileTypeManager.getInstance().getFileTypeByFileName(file.name))
}
fun guessCurrentProject(component: JComponent?): Project {
var project: Project? = null
if (component != null) {
project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component))
}
@Suppress("DEPRECATION")
return project
?: ProjectManager.getInstance().openProjects.firstOrNull()
?: CommonDataKeys.PROJECT.getData(DataManager.getInstance().dataContext)
?: ProjectManager.getInstance().defaultProject
}
inline fun <T> Project.modifyModules(crossinline task: ModifiableModuleModel.() -> T): T {
val model = ModuleManager.getInstance(this).modifiableModel
val result = model.task()
runWriteAction {
model.commit()
}
return result
}
fun isProjectDirectoryExistsUsingIo(parent: VirtualFile): Boolean {
try {
return Paths.get(FileUtil.toSystemDependentName(parent.path), Project.DIRECTORY_STORE_FOLDER).exists()
}
catch (e: InvalidPathException) {
return false
}
}
/**
* Tries to guess the "main project directory" of the project.
*
* There is no strict definition of what is a project directory, since a project can contain multiple modules located in different places,
* and the `.idea` directory can be located elsewhere (making the popular [Project.getBaseDir] method not applicable to get the "project
* directory"). This method should be preferred, although it can't provide perfect accuracy either.
*
* @throws IllegalStateException if called on the default project, since there is no sense in "project dir" in that case.
*/
fun Project.guessProjectDir() : VirtualFile {
if (isDefault) {
throw IllegalStateException("Not applicable for default project")
}
val modules = ModuleManager.getInstance(this).modules
val module = if (modules.size == 1) modules.first() else modules.find { it.name == this.name }
module?.rootManager?.contentRoots?.firstOrNull()?.let {
return it
}
return this.baseDir!!
}
private fun Project.getProjectCacheFileName(forceNameUse: Boolean, hashSeparator: String): String {
val presentableUrl = presentableUrl
var name = if (forceNameUse || presentableUrl == null) {
name
}
else {
// lower case here is used for cosmetic reasons (develar - discussed with jeka - leave it as it was, user projects will not have long names as in our tests)
FileUtil.sanitizeFileName(PathUtilRt.getFileName(presentableUrl).toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION), false)
}
// do not use project.locationHash to avoid prefix for IPR projects (not required in our case because name in any case is prepended).
val locationHash = Integer.toHexString((presentableUrl ?: name).hashCode())
// trim to avoid "File name too long"
name = name.trimMiddle(Math.min(name.length, 255 - hashSeparator.length - locationHash.length), useEllipsisSymbol = false)
return "$name$hashSeparator${locationHash}"
}
@JvmOverloads
fun Project.getProjectCachePath(cacheName: String, forceNameUse: Boolean = false): Path {
return getProjectCachePath(appSystemDir.resolve(cacheName), forceNameUse)
}
fun Project.getExternalConfigurationDir(): Path {
return getProjectCachePath("external_build_system")
}
@set:TestOnly
var IS_EXTERNAL_STORAGE_ENABLED = false
val isExternalStorageEnabled: Boolean
get() = Registry.`is`("store.imported.project.elements.separately", false) || IS_EXTERNAL_STORAGE_ENABLED
/**
* Use parameters only for migration purposes, once all usages will be migrated, parameters will be removed
*/
@JvmOverloads
fun Project.getProjectCachePath(baseDir: Path, forceNameUse: Boolean = false, hashSeparator: String = "."): Path {
return baseDir.resolve(getProjectCacheFileName(forceNameUse, hashSeparator))
}
/**
* Add one-time projectOpened listener.
*/
fun Project.runWhenProjectOpened(handler: Runnable) = runWhenProjectOpened(this) { handler.run() }
/**
* Add one-time first projectOpened listener.
*/
@JvmOverloads
fun runWhenProjectOpened(project: Project? = null, handler: Consumer<Project>) = runWhenProjectOpened(project) { handler.accept(it) }
/**
* Add one-time projectOpened listener.
*/
inline fun runWhenProjectOpened(project: Project? = null, crossinline handler: (project: Project) -> Unit) {
val connection = (project ?: ApplicationManager.getApplication()).messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(eventProject: Project) {
if (project == null || project === eventProject) {
connection.disconnect()
handler(eventProject)
}
}
})
} | apache-2.0 | b895871a44a64632c50d5c9ac89ad196 | 38.204762 | 194 | 0.771259 | 4.444924 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/executors/admin/CommandSQL.kt | 1 | 4101 | package me.mrkirby153.KirBot.command.executors.admin
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.AdminCommand
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.module.ModuleManager
import me.mrkirby153.KirBot.modules.Database
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.checkPermissions
import me.mrkirby153.kcutils.Time
import me.mrkirby153.kcutils.use
import me.mrkirby153.kcutils.utils.TableBuilder
import net.dv8tion.jda.api.MessageBuilder
import net.dv8tion.jda.api.Permission
import java.sql.SQLException
import java.util.concurrent.CompletableFuture
import java.util.function.Supplier
class CommandSQL {
@Command(name = "sql", arguments = ["<query:string...>"])
@AdminCommand
@CommandDescription("Execute raw SQL against the database")
fun execute(context: Context, cmdContext: CommandContext) {
val query = cmdContext.get<String>("query") ?: throw CommandException(
"Please specify a query")
context.addReaction("\uD83D\uDD04").queue()
val future = CompletableFuture.supplyAsync(Supplier {
ModuleManager[Database::class].database.getConnection().use { con ->
con.createStatement().use { statement ->
try {
val start_time = System.currentTimeMillis()
val r = statement.execute(query)
val end_time = System.currentTimeMillis()
if (r) {
val rs = statement.resultSet
val meta = rs.metaData
val columns = (1..meta.columnCount).map { meta.getColumnLabel(it) }
val builder = TableBuilder(columns.toTypedArray())
while (rs.next()) {
val data = mutableListOf<String?>()
columns.forEach {
data.add(rs.getString(it))
}
builder.addRow(data.toTypedArray())
}
val table = builder.buildTable()
if (table.length > 1900) {
if (context.channel.checkPermissions(
Permission.MESSAGE_ATTACH_FILES)) {
context.channel.sendMessage(
MessageBuilder("_Took ${Time.format(1,
end_time - start_time)}_").build()).addFile(
table.toByteArray(), "query.txt").queue()
} else {
context.send().error(
"Query is too long and files cannot be uploaded!").queue()
}
} else {
context.channel.sendMessage("```$table```_Took ${Time.format(1,
end_time - start_time)}_").queue()
}
} else {
context.channel.sendMessage(
":ballot_box_with_check: ${statement.updateCount} row(s) updated").queue()
}
} catch (ex: SQLException) {
context.channel.sendMessage(":x: Error: ```${ex.message}```").queue()
}
}
}
}, Bot.scheduler)
future.whenComplete { _, throwable ->
if (throwable != null) {
context.send().error("An error occurred: ${throwable.localizedMessage}")
}
}
}
} | mit | 7eb08170220b60ebcf7419823a97110e | 45.613636 | 110 | 0.507437 | 5.519515 | false | false | false | false |
devunt/ika | app/src/main/kotlin/org/ozinger/ika/database/models/ChannelIntegration.kt | 1 | 1029 | package org.ozinger.ika.database.models
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.javatime.datetime
object ChannelIntegrations : IntIdTable() {
val channel = reference("channel", Channels)
val type = varchar("type", 32)
val target = varchar("target", 255).uniqueIndex()
val extra = varchar("extra", 255)
val isAuthorized = bool("is_authorized")
val createdAt = datetime("created_at")
}
class ChannelIntegration(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<ChannelIntegration>(ChannelIntegrations)
var channel by Channel referencedOn ChannelIntegrations.channel
var type by ChannelFlags.type
var target by ChannelIntegrations.target
var extra by ChannelIntegrations.extra
var isAuthorized by ChannelIntegrations.isAuthorized
var createdAt by ChannelIntegrations.createdAt
}
| agpl-3.0 | e774db7da829e82fe2b8d4fb86952e08 | 37.111111 | 78 | 0.77551 | 4.454545 | false | false | false | false |
pnemonic78/RemoveDuplicates | duplicates-android/app/src/main/java/com/github/duplicates/contact/PhotoData.kt | 1 | 1944 | /*
* Copyright 2016, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.duplicates.contact
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.provider.ContactsContract.CommonDataKinds.Photo
import android.text.TextUtils
import android.util.Base64
/**
* Contact photograph data.
*
* @author moshe.w
*/
class PhotoData : ContactData() {
private var _photo: Bitmap? = null
val photo: Bitmap?
get() {
if (_photo == null) {
val data15 = data15
if (!TextUtils.isEmpty(data15)) {
val blob = Base64.decode(data15, Base64.DEFAULT)
if (blob != null) {
_photo = BitmapFactory.decodeByteArray(blob, 0, blob.size)
}
}
}
return _photo
}
val photoFileId: Long
get() = data14?.toLong() ?: 0L
override var data15: String?
get() = super.data15
set(data15) {
super.data15 = data15
_photo = null
}
override val isEmpty: Boolean
get() = data15 == null
init {
mimeType = Photo.CONTENT_ITEM_TYPE
}
override fun toString(): String {
return data15 ?: super.toString()
}
override fun containsAny(s: CharSequence, ignoreCase: Boolean): Boolean {
return false
}
}
| apache-2.0 | 33bf29abcc3f76e3ff81d87021f498e7 | 26.771429 | 82 | 0.614198 | 4.368539 | false | false | false | false |
http4k/http4k | src/docs/guide/howto/use_html_forms/example_lens.kt | 1 | 1812 | package guide.howto.use_html_forms
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.with
import org.http4k.lens.FormField
import org.http4k.lens.Header
import org.http4k.lens.LensFailure
import org.http4k.lens.Validator
import org.http4k.lens.WebForm
import org.http4k.lens.int
import org.http4k.lens.webForm
data class Name(val value: String)
fun main() {
// define fields using the standard lens syntax
val ageField = FormField.int().required("age")
val nameField = FormField.map(::Name, Name::value).optional("name")
// add fields to a form definition, along with a validator
val strictFormBody = Body.webForm(Validator.Strict, nameField, ageField).toLens()
val feedbackFormBody = Body.webForm(Validator.Feedback, nameField, ageField).toLens()
val invalidRequest = Request(GET, "/")
.with(Header.CONTENT_TYPE of ContentType.APPLICATION_FORM_URLENCODED)
// the "strict" form rejects (throws a LensFailure) because "age" is required
try {
strictFormBody(invalidRequest)
} catch (e: LensFailure) {
println(e.message)
}
// the "feedback" form doesn't throw, but collects errors to be reported later
val invalidForm = feedbackFormBody(invalidRequest)
println(invalidForm.errors)
// creating valid form using "with()" and setting it onto the request
val webForm = WebForm().with(ageField of 55, nameField of Name("rita"))
val validRequest = Request(GET, "/").with(strictFormBody of webForm)
// to extract the contents, we first extract the form and then extract the fields from it
// using the lenses
val validForm = strictFormBody(validRequest)
val age = ageField(validForm)
println(age)
}
| apache-2.0 | dfbaaa06d3a5e5cee5d1bda541135053 | 34.529412 | 93 | 0.731788 | 3.822785 | false | false | false | false |
asarkar/spring | license-report-kotlin/src/test/kotlin/org/abhijitsarkar/service/LinkVerifierTest.kt | 1 | 3239 | package org.abhijitsarkar.service
import com.github.benmanes.caffeine.cache.Cache
import io.kotlintest.properties.forAll
import io.kotlintest.properties.headers
import io.kotlintest.properties.row
import io.kotlintest.properties.table
import io.kotlintest.specs.ShouldSpec
import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyBoolean
import org.mockito.Mockito.eq
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import reactor.test.StepVerifier
import java.time.Duration
/**
* @author Abhijit Sarkar
*/
class LinkVerifierTest : ShouldSpec() {
init {
should("verify if link is valid") {
val myTable = table(
headers("link", "valid"),
row("http://www.slf4j.org/license.html", true),
row("http://www.apache.org/licenses/LICENSE-2.0.txt", true),
row("https://glassfish.dev.java.net/nonav/public/CDDL+GPL.html", true),
row("http://doesnotexist.blah.com", false),
row("http://www.opensource.org/licenses/cddl1.php", true),
row("", false)
)
val linkVerifier = LinkVerifierImpl.newInstance()
forAll(myTable) { link, valid ->
StepVerifier.create(linkVerifier.isValid(link))
.expectNext(valid)
.expectComplete()
.verify(Duration.ofSeconds(3L))
}
}
should("not make remote call if in cache") {
val path = "www.apache.org/licenses/LICENSE-2.0.txt"
@Suppress("UNCHECKED_CAST")
val cache: Cache<String, Boolean> = mock(Cache::class.java) as Cache<String, Boolean>
`when`(cache.getIfPresent(path))
.thenReturn(null, true)
val myTable = table(
headers("link", "valid"),
row("http://$path", true),
row("https://$path", true)
)
val linkVerifier = LinkVerifierImpl.newInstance(cache = cache)
forAll(myTable) { link, valid ->
StepVerifier.create(linkVerifier.isValid(link))
.expectNext(valid)
.expectComplete()
.verify(Duration.ofSeconds(3L))
}
verify(cache, times(2)).getIfPresent(path)
verify(cache).put(path, true)
}
should("not cache failed response") {
val path = "doesnotexist.blah.com"
@Suppress("UNCHECKED_CAST")
val cache: Cache<String, Boolean> = mock(Cache::class.java) as Cache<String, Boolean>
val linkVerifier = LinkVerifierImpl.newInstance(cache = cache)
for (i in 1..2) {
StepVerifier.create(linkVerifier.isValid("http://$path"))
.expectNext(false)
.expectComplete()
.verify(Duration.ofSeconds(3L))
}
verify(cache, times(2)).getIfPresent("$path")
verify(cache, never()).put(eq("$path"), anyBoolean())
}
}
} | gpl-3.0 | 8c8be00cf8a2bfa1302e80e4551128b6 | 35.818182 | 97 | 0.560667 | 4.492372 | false | true | false | false |
sai-harish/Tower | Android/src/org/droidplanner/android/utils/SpaceTime.kt | 1 | 1709 | package org.droidplanner.android.utils
import android.os.Parcel
import android.os.Parcelable
import com.o3dr.services.android.lib.coordinate.LatLongAlt
/**
* @author ne0fhyk (Fredia Huya-Kouadio)
*/
class SpaceTime(latitude: Double, longitude: Double, altitude: Double, var timeInMs: Long) :
LatLongAlt(latitude, longitude, altitude) {
constructor(space: LatLongAlt, timeInMs: Long): this(space.latitude, space.longitude, space.altitude, timeInMs)
constructor(spaceTime: SpaceTime): this(spaceTime.latitude, spaceTime.longitude, spaceTime.altitude, spaceTime.timeInMs)
fun set(reference: SpaceTime) {
super.set(reference)
timeInMs = reference.timeInMs
}
override fun equals(other: Any?): Boolean{
if (this === other) return true
if (other !is SpaceTime) return false
if (!super.equals(other)) return false
if (timeInMs != other.timeInMs) return false
return true
}
override fun hashCode(): Int{
var result = super.hashCode()
result = 31 * result + timeInMs.hashCode()
return result
}
override fun toString(): String{
val superToString = super.toString()
return "SpaceTime{$superToString, time=$timeInMs}"
}
companion object {
@JvmStatic val CREATOR = object : Parcelable.Creator<SpaceTime> {
override fun createFromParcel(source: Parcel): SpaceTime {
return source.readSerializable() as SpaceTime
}
override fun newArray(size: Int): Array<out SpaceTime?> {
return arrayOfNulls(size)
}
}
}
} | gpl-3.0 | df26b71d4a8461e0e990e3971de6431a | 28.553571 | 124 | 0.631363 | 4.606469 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryAdapter.kt | 1 | 3372 | package eu.kanade.tachiyomi.ui.library
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.RelativeLayout
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.util.inflate
import kotlinx.android.synthetic.main.fragment_library_category.*
import kotlinx.android.synthetic.main.item_catalogue_grid.view.*
import java.util.*
/**
* Adapter storing a list of manga in a certain category.
*
* @param fragment the fragment containing this adapter.
*/
class LibraryCategoryAdapter(val fragment: LibraryCategoryFragment) :
FlexibleAdapter<LibraryHolder, Manga>() {
/**
* The list of manga in this category.
*/
private var mangas: List<Manga>? = null
init {
setHasStableIds(true)
}
/**
* Sets a list of manga in the adapter.
*
* @param list the list to set.
*/
fun setItems(list: List<Manga>) {
mItems = list
// A copy of manga that it's always unfiltered
mangas = ArrayList(list)
updateDataSet(null)
}
/**
* Returns the identifier for a manga.
*
* @param position the position in the adapter.
* @return an identifier for the item.
*/
override fun getItemId(position: Int): Long {
return mItems[position].id
}
/**
* Filters the list of manga applying [filterObject] for each element.
*
* @param param the filter. Not used.
*/
override fun updateDataSet(param: String?) {
mangas?.let {
filterItems(it)
notifyDataSetChanged()
}
}
/**
* Filters a manga depending on a query.
*
* @param manga the manga to filter.
* @param query the query to apply.
* @return true if the manga should be included, false otherwise.
*/
override fun filterObject(manga: Manga, query: String): Boolean = with(manga) {
title != null && title.toLowerCase().contains(query) ||
author != null && author.toLowerCase().contains(query)
}
/**
* Creates a new view holder.
*
* @param parent the parent view.
* @param viewType the type of the holder.
* @return a new view holder for a manga.
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LibraryHolder {
val view = parent.inflate(R.layout.item_catalogue_grid)
view.image_container.layoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, coverHeight)
return LibraryHolder(view, this, fragment)
}
/**
* Binds a holder with a new position.
*
* @param holder the holder to bind.
* @param position the position to bind.
*/
override fun onBindViewHolder(holder: LibraryHolder, position: Int) {
val presenter = (fragment.parentFragment as LibraryFragment).presenter
val manga = getItem(position)
holder.onSetValues(manga, presenter)
//When user scrolls this bind the correct selection status
holder.itemView.isActivated = isSelected(position)
}
/**
* Property to return the height for the covers based on the width to keep an aspect ratio.
*/
val coverHeight: Int
get() = fragment.recycler.itemWidth / 3 * 4
}
| apache-2.0 | 1e2ff4202ec32de1e552c39b6e0b3174 | 29.107143 | 98 | 0.653025 | 4.466225 | false | false | false | false |
toxxmeister/BLEacon | library/src/main/java/de/troido/bleacon/config/advertise/BleAdData.kt | 1 | 923 | package de.troido.bleacon.config.advertise
import android.bluetooth.le.AdvertiseData
import de.troido.bleacon.ble.NORDIC_ID
import de.troido.ekstend.uuid.Uuid16
import de.troido.ekstend.uuid.bytes
import java.util.UUID
@JvmOverloads
fun bleAdData(uuid16: Uuid16? = null,
uuid128: UUID? = null,
includeTxPowerLevel: Boolean = false,
includeDeviceName: Boolean = false,
build: AdDataBuilder.() -> Unit = {}): AdvertiseData =
AdvertiseData.Builder()
.apply {
setIncludeTxPowerLevel(includeTxPowerLevel)
setIncludeDeviceName(includeDeviceName)
AdDataBuilder(this).apply {
uuid16?.let { msd[NORDIC_ID] = it.bytes }
uuid128?.let { msd[NORDIC_ID] = it.bytes }
}.apply(build)
}
.build()
| apache-2.0 | e172b9b96146bd002fba612274e1f4a2 | 34.5 | 68 | 0.574215 | 4.374408 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/process/util/Identifier.kt | 1 | 2992 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.util
import kotlinx.serialization.Serializable
import kotlinx.serialization.Serializer
import kotlinx.serialization.*
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import nl.adaptivity.serialutil.DelegatingSerializer
import nl.adaptivity.serialutil.simpleSerialClassDesc
/**
* A class representing a simple identifier. It just holds a single string.
*/
@Serializable(Identifier.Companion::class)
class Identifier(override var id: String) : Identified {
override val identifier: Identifier
get() = this
private class ChangeableIdentifier(private val idBase: String) : Identified {
private var idNo: Int = 1
override val id: String
get() = idBase + idNo.toString()
override fun compareTo(other: Identifiable): Int {
val otherId = other.id
if (otherId == null) return 1
return id.compareTo(otherId)
}
operator fun next() {
++idNo
}
}
constructor(id: CharSequence) : this(id.toString()) {}
override fun compareTo(o: Identifiable): Int {
val otherId = o.id ?: return 1
return id.compareTo(otherId)
}
override fun toString(): String = id
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as Identifier
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
companion object: DelegatingSerializer<Identifier, String>(String.serializer()) {
override fun fromDelegate(delegate: String): Identifier = Identifier(delegate)
override fun Identifier.toDelegate(): String = id
fun findIdentifier(idBase: String, exclusions: Iterable<Identifiable>): String {
val idFactory = ChangeableIdentifier(idBase)
return generateSequence({ idFactory.id }, { idFactory.next(); idFactory.id })
.filter { candidate -> exclusions.none { candidate == it.id } }
.first()
}
}
}
| lgpl-3.0 | 91e01e60e0f5e77ad7a738e4453ef877 | 31.521739 | 112 | 0.682487 | 4.697017 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/dialog/RecommendedPlayerCountFilterDialog.kt | 1 | 3063 | package com.boardgamegeek.ui.dialog
import android.content.Context
import android.view.LayoutInflater
import android.widget.ArrayAdapter
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import com.boardgamegeek.R
import com.boardgamegeek.databinding.DialogCollectionFilterRecommendedPlayerCountBinding
import com.boardgamegeek.extensions.createThemedBuilder
import com.boardgamegeek.filterer.CollectionFilterer
import com.boardgamegeek.filterer.RecommendedPlayerCountFilterer
import com.boardgamegeek.ui.viewmodel.CollectionViewViewModel
class RecommendedPlayerCountFilterDialog : CollectionFilterDialog {
private var _binding: DialogCollectionFilterRecommendedPlayerCountBinding? = null
private val binding get() = _binding!!
private val defaultPlayerCount = 4
override fun createDialog(activity: FragmentActivity, filter: CollectionFilterer?) {
val viewModel by lazy { ViewModelProvider(activity)[CollectionViewViewModel::class.java] }
_binding = DialogCollectionFilterRecommendedPlayerCountBinding.inflate(LayoutInflater.from(activity), null, false)
binding.rangeBar.addOnChangeListener { _, value, _ ->
binding.playerCountDisplay.text = value.toInt().toString()
}
val bestString = activity.getString(R.string.best)
val goodString = activity.getString(R.string.good)
binding.autocompleteView.setAdapter(ArrayAdapter(activity, R.layout.support_simple_spinner_dropdown_item, listOf(bestString, goodString)))
val recommendedPlayerCountFilterer = filter as? RecommendedPlayerCountFilterer
when (recommendedPlayerCountFilterer?.recommendation ?: RecommendedPlayerCountFilterer.RECOMMENDED) {
RecommendedPlayerCountFilterer.BEST -> binding.autocompleteView.setText(bestString, false)
else -> binding.autocompleteView.setText(goodString, false)
}
val playerCount = recommendedPlayerCountFilterer?.playerCount?.coerceIn(binding.rangeBar.valueFrom.toInt(), binding.rangeBar.valueTo.toInt())
?: defaultPlayerCount
binding.rangeBar.value = playerCount.toFloat()
activity.createThemedBuilder()
.setTitle(R.string.menu_recommended_player_count)
.setPositiveButton(R.string.set) { _, _ ->
viewModel.addFilter(RecommendedPlayerCountFilterer(activity).apply {
this.playerCount = binding.rangeBar.value.toInt()
recommendation = if (binding.autocompleteView.text.toString() == bestString)
RecommendedPlayerCountFilterer.BEST
else
RecommendedPlayerCountFilterer.RECOMMENDED
})
}
.setNegativeButton(R.string.clear) { _, _ ->
viewModel.removeFilter(getType(activity))
}
.setView(binding.root)
.create()
.show()
}
override fun getType(context: Context) = RecommendedPlayerCountFilterer(context).type
}
| gpl-3.0 | 3325343874974484883554116e5cce2c | 46.859375 | 149 | 0.721188 | 5.479428 | false | false | false | false |
Kotlin/kotlinx.serialization | benchmark/src/jmh/kotlin/kotlinx/benchmarks/json/PolymorphismOverheadBenchmark.kt | 1 | 2090 | package kotlinx.benchmarks.json
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.*
@Warmup(iterations = 7, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(1)
open class PolymorphismOverheadBenchmark {
@Serializable
@JsonClassDiscriminator("poly")
data class PolymorphicWrapper(val i: @Polymorphic Poly, val i2: Impl) // amortize the cost a bit
@Serializable
data class SimpleWrapper(val poly: @Polymorphic Poly)
@Serializable
data class BaseWrapper(val i: Impl, val i2: Impl)
@JsonClassDiscriminator("poly")
interface Poly
@Serializable
@JsonClassDiscriminator("poly")
class Impl(val a: Int, val b: String) : Poly
private val impl = Impl(239, "average_size_string")
private val module = SerializersModule {
polymorphic(Poly::class) {
subclass(Impl.serializer())
}
}
private val json = Json { serializersModule = module }
private val implString = json.encodeToString(impl)
private val polyString = json.encodeToString<Poly>(impl)
private val serializer = serializer<Poly>()
private val wrapper = SimpleWrapper(Impl(1, "abc"))
private val wrapperString = json.encodeToString(wrapper)
private val wrapperSerializer = serializer<SimpleWrapper>()
// 5000
@Benchmark
fun base() = json.decodeFromString(Impl.serializer(), implString)
// As of 1.3.x
// Baseline -- 1500
// v1, no skip -- 2000
// v2, with skip -- 3000 [withdrawn]
@Benchmark
fun poly() = json.decodeFromString(serializer, polyString)
// test for child polymorphic serializer in decoding
@Benchmark
fun polyChildDecode() = json.decodeFromString(wrapperSerializer, wrapperString)
// test for child polymorphic serializer in encoding
@Benchmark
fun polyChildEncode() = json.encodeToString(wrapperSerializer, wrapper)
}
| apache-2.0 | a2a59bccefb703180175d38a655d55c9 | 28.857143 | 100 | 0.710526 | 4.3361 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/hocon/src/main/kotlin/kotlinx/serialization/hocon/HoconExceptions.kt | 1 | 882 | /*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.hocon
import com.typesafe.config.*
import kotlinx.serialization.*
internal fun SerializerNotFoundException(type: String?) = SerializationException(
"Polymorphic serializer was not found for " +
if (type == null) "missing class discriminator ('null')" else "class discriminator '$type'"
)
internal inline fun <reified T> ConfigValueTypeCastException(valueOrigin: ConfigOrigin) = SerializationException(
"${valueOrigin.description()} required to be of type ${T::class.simpleName}."
)
internal fun InvalidKeyKindException(value: ConfigValue) = SerializationException(
"Value of type '${value.valueType()}' can't be used in HOCON as a key in the map. " +
"It should have either primitive or enum kind."
)
| apache-2.0 | de4ffe3971f033be24d15de3c5a1fbfc | 39.090909 | 113 | 0.734694 | 4.454545 | false | true | false | false |
WindSekirun/RichUtilsKt | demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/IndexActivity.kt | 1 | 4654 | package pyxis.uzuki.live.richutilskt.demo
import android.Manifest
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.activity_index.*
import kotlinx.android.synthetic.main.activity_index_item.view.*
import pyxis.uzuki.live.richutilskt.demo.item.CategoryItem
import pyxis.uzuki.live.richutilskt.demo.item.ExecuteItem
import pyxis.uzuki.live.richutilskt.demo.item.MainItem
import pyxis.uzuki.live.richutilskt.utils.RPermission
import pyxis.uzuki.live.richutilskt.utils.inflate
/**
* RichUtilsKt
* Class: IndexActivity
* Created by Pyxis on 2017-11-06.
*
* Description:
*/
class IndexActivity : AppCompatActivity() {
private val itemList = ArrayList<ExecuteItem>()
private val adapter = ListAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_index)
val item = intent.getSerializableExtra("index") as MainItem
itemList.addAll(getItemList(item.categoryItem))
itemList.sortBy { it.title }
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dy > 0 && fab.visibility == View.VISIBLE) {
fab.hide()
} else if (dy < 0 && fab.visibility != View.VISIBLE) {
fab.show()
}
}
})
supportActionBar?.title = "${item.title} :: RichUtils"
supportActionBar?.setDefaultDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
adapter.notifyDataSetChanged()
fab.setOnClickListener {
browseToFile(item.link)
}
val permissionArray = when (item.categoryItem) {
CategoryItem.DEVICEID -> arrayOf(Manifest.permission.READ_PHONE_STATE)
CategoryItem.PICKMEDIA -> arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
else -> null
}
if (permissionArray != null) {
RPermission.instance.checkPermission(this, permissionArray)
}
}
inner class ListAdapter : RecyclerView.Adapter<ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindData(itemList[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(this@IndexActivity, inflate(R.layout.activity_index_item, parent))
}
override fun getItemCount(): Int = itemList.size
}
var extendedPosition = -1
inner class ViewHolder(private val context: Context, itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindData(item: ExecuteItem) {
val isShow = extendedPosition == adapterPosition
itemView.imgExpand.isSelected = isShow
itemView.txtTitle.text = item.title
itemView.txtSummary.text = item.message
itemView.btnExecute.visibility = if (item.execute == null) View.GONE else View.VISIBLE
itemView.btnExecute.setOnClickListener {
item.execute?.invoke(context)
}
if (isShow) {
itemView.containerMore.visibility = View.VISIBLE
itemView.divider.visibility = View.VISIBLE
} else {
itemView.containerMore.visibility = View.GONE
itemView.divider.visibility = View.GONE
}
itemView.txtKotlinSample.text = item.kotlinSample
itemView.txtJavaSample.text = item.javaSample
itemView.containerTitle.setOnClickListener {
extendedPosition = if (isShow) -1 else adapterPosition
recyclerView.layoutManager.scrollToPosition(extendedPosition)
adapter.notifyDataSetChanged()
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
}
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | e1cba2c18e733b15b1faed14477a0992 | 34.265152 | 110 | 0.661367 | 4.951064 | false | false | false | false |
sabi0/intellij-community | platform/usageView/src/com/intellij/usages/UsageViewSettings.kt | 2 | 3852 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.usages
import com.intellij.openapi.components.*
import com.intellij.util.PathUtil
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Transient
/**
* Passed params will be used as default values, so, do not use constructor if instance will be used as a state (unless you want to change defaults)
*/
@State(name = "UsageViewSettings", storages = [Storage("usageView.xml")])
open class UsageViewSettings(
isGroupByFileStructure: Boolean = true,
isGroupByModule: Boolean = true,
isGroupByPackage: Boolean = true,
isGroupByUsageType: Boolean = true,
isGroupByScope: Boolean = false
) : BaseState(), PersistentStateComponent<UsageViewSettings> {
companion object {
@JvmStatic
val instance: UsageViewSettings
get() = ServiceManager.getService(UsageViewSettings::class.java)
}
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByModule")
var GROUP_BY_MODULE: Boolean = isGroupByModule
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByUsageType")
var GROUP_BY_USAGE_TYPE: Boolean = isGroupByUsageType
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByFileStructure")
var GROUP_BY_FILE_STRUCTURE: Boolean = isGroupByFileStructure
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByScope")
var GROUP_BY_SCOPE: Boolean = isGroupByScope
@Suppress("unused")
@JvmField
@Transient
@Deprecated(message = "Use isGroupByPackage")
var GROUP_BY_PACKAGE: Boolean = isGroupByPackage
@Suppress("MemberVisibilityCanPrivate")
@get:OptionTag("EXPORT_FILE_NAME")
internal var EXPORT_FILE_NAME by property("report.txt")
@get:OptionTag("IS_EXPANDED")
var isExpanded: Boolean by property(false)
@get:OptionTag("IS_AUTOSCROLL_TO_SOURCE")
var isAutoScrollToSource: Boolean by property(false)
@get:OptionTag("IS_FILTER_DUPLICATED_LINE")
var isFilterDuplicatedLine: Boolean by property(true)
@get:OptionTag("IS_SHOW_METHODS")
var isShowModules: Boolean by property(false)
@get:OptionTag("IS_PREVIEW_USAGES")
var isPreviewUsages: Boolean by property(false)
@get:OptionTag("IS_REPLACE_PREVIEW_USAGES")
var isReplacePreviewUsages: Boolean by property(true)
@get:OptionTag("IS_SORT_MEMBERS_ALPHABETICALLY")
var isSortAlphabetically: Boolean by property(false)
@get:OptionTag("PREVIEW_USAGES_SPLITTER_PROPORTIONS")
var previewUsagesSplitterProportion: Float by property(0.5f)
@get:OptionTag("GROUP_BY_USAGE_TYPE")
var isGroupByUsageType: Boolean by property(isGroupByUsageType)
@get:OptionTag("GROUP_BY_MODULE")
var isGroupByModule: Boolean by property(isGroupByModule)
@get:OptionTag("FLATTEN_MODULES")
var isFlattenModules: Boolean by property(true)
@get:OptionTag("GROUP_BY_PACKAGE")
var isGroupByPackage: Boolean by property(isGroupByPackage)
@get:OptionTag("GROUP_BY_FILE_STRUCTURE")
var isGroupByFileStructure: Boolean by property(isGroupByFileStructure)
@get:OptionTag("GROUP_BY_SCOPE")
var isGroupByScope: Boolean by property(isGroupByScope)
var exportFileName: String?
@Transient
get() = PathUtil.toSystemDependentName(EXPORT_FILE_NAME)
set(value) {
EXPORT_FILE_NAME = PathUtil.toSystemIndependentName(value)
}
override fun getState(): UsageViewSettings = this
@Suppress("DEPRECATION")
override fun loadState(state: UsageViewSettings) {
copyFrom(state)
GROUP_BY_MODULE = isGroupByModule
GROUP_BY_USAGE_TYPE = isGroupByUsageType
GROUP_BY_FILE_STRUCTURE = isGroupByFileStructure
GROUP_BY_SCOPE = isGroupByScope
GROUP_BY_PACKAGE = isGroupByPackage
}
}
| apache-2.0 | d24d286066f0ddcdb317f2ba6fe2cf6a | 31.1 | 148 | 0.75649 | 4.27525 | false | false | false | false |
zhufucdev/PCtoPE | app/src/main/java/com/zhufucdev/pctope/adapters/TutorialActivity.kt | 1 | 4582 | package com.zhufucdev.pctope.adapters
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.FrameLayout
/**
* Created by zhufu on 17-10-21.
*/
abstract class TutorialActivity(LayoutRes : Array<Int>) : AppCompatActivity(){
private val res = LayoutRes
var layouts = ArrayList<TutorialLayout>()
var showingPosition = 0
var isInAnimations = false
lateinit var animationLeftToCenter : Animation
lateinit var animationCenterToLeft : Animation
lateinit var animationRightToCenter : Animation
lateinit var animationCenterToRight : Animation
open class TutorialLayout(var view: View) {
var parmas = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.START)
}
override fun onCreate(savedInstanceState: Bundle?) {
for (i in res.indices){
layouts.add(TutorialLayout(LayoutInflater.from(this).inflate(res[i],null)))
Log.i("Tutorial","Added layout ${res[i]}.")
}
animationLeftToCenter = TranslateAnimation(-resources.displayMetrics.widthPixels.toFloat(),0f,0f,0f)
animationLeftToCenter.duration = 400
animationCenterToLeft = TranslateAnimation(0f,-resources.displayMetrics.widthPixels.toFloat(),0f,0f)
animationCenterToLeft.duration = 400
animationRightToCenter = TranslateAnimation(resources.displayMetrics.widthPixels.toFloat(),0f,0f,0f)
animationRightToCenter.duration = 400
animationCenterToRight = TranslateAnimation(0f,resources.displayMetrics.widthPixels.toFloat(),0f,0f)
animationCenterToRight.duration = 400
super.onCreate(savedInstanceState)
onPageSwitched()
}
fun show(index : Int){
if (layouts.size>index && index>=0){
if (index>showingPosition){
//Next
layouts[showingPosition].view.startAnimation(animationCenterToLeft)
addContentView(layouts[index].view,layouts[index].parmas)
layouts[index].view.startAnimation(animationRightToCenter)
animationRightToCenter.setAnimationListener(object : Animation.AnimationListener{
override fun onAnimationRepeat(animation: Animation?) {}
override fun onAnimationEnd(animation: Animation?) {
(layouts[showingPosition].view.parent as ViewGroup).removeView(layouts[showingPosition].view)
animationRightToCenter.setAnimationListener(null)
showingPosition++
isInAnimations = false
onPageSwitched()
}
override fun onAnimationStart(animation: Animation?) {
isInAnimations = true
}
})
}
else if (index<showingPosition){
//Back
layouts[showingPosition].view.startAnimation(animationCenterToRight)
addContentView(layouts[index].view,layouts[index].parmas)
layouts[index].view.startAnimation(animationLeftToCenter)
animationCenterToRight.setAnimationListener(object : Animation.AnimationListener{
override fun onAnimationRepeat(animation: Animation?) {}
override fun onAnimationEnd(animation: Animation?) {
(layouts[showingPosition].view.parent as ViewGroup).removeView(layouts[showingPosition].view)
animationCenterToRight.setAnimationListener(null)
showingPosition--
isInAnimations = false
onPageSwitched()
}
override fun onAnimationStart(animation: Animation?) {
isInAnimations = true
}
})
}
else if (index==showingPosition){
setContentView(layouts[index].view)
}
}
}
fun next(){
show(showingPosition+1)
}
fun back(){
show(showingPosition-1)
}
override fun <T : View?> findViewById(id: Int): T = layouts[showingPosition].view.findViewById<T>(id)
abstract fun onPageSwitched()
} | gpl-3.0 | a92a9a4caf3311cf1eab2c36c388042e | 34.804688 | 138 | 0.635967 | 5.72035 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/fragment/SongContentPortraitViewFragment.kt | 2 | 21813 | package org.worshipsongs.fragment
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.AdapterView
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.getbase.floatingactionbutton.FloatingActionButton
import com.getbase.floatingactionbutton.FloatingActionsMenu
import com.google.android.youtube.player.YouTubePlayer
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.WorshipSongApplication
import org.worshipsongs.activity.CustomYoutubeBoxActivity
import org.worshipsongs.adapter.PresentSongCardViewAdapter
import org.worshipsongs.domain.Setting
import org.worshipsongs.domain.Song
import org.worshipsongs.parser.LiveShareSongParser
import org.worshipsongs.service.*
import org.worshipsongs.utils.CommonUtils
import org.worshipsongs.utils.LiveShareUtils
import org.worshipsongs.utils.PermissionUtils
import java.io.File
import java.util.*
/**
* @author: Madasamy, Vignesh Palanisamy
* @since: 1.0.0
*/
class SongContentPortraitViewFragment : Fragment(), ISongContentPortraitViewFragment
{
private var title: String? = ""
private var tilteList: ArrayList<String>? = ArrayList()
private var millis: Int = 0
private val youTubePlayer: YouTubePlayer? = null
private val preferenceSettingService = UserPreferenceSettingService()
private val songDao = SongService(WorshipSongApplication.context!!)
private val authorService = AuthorService(WorshipSongApplication.context!!)
private var popupMenuService: PopupMenuService? = null
private var floatingActionMenu: FloatingActionsMenu? = null
private var song: Song? = null
private var listView: ListView? = null
private var presentSongCardViewAdapter: PresentSongCardViewAdapter? = null
private var nextButton: FloatingActionButton? = null
private var previousButton: FloatingActionButton? = null
private var presentSongFloatingButton: FloatingActionButton? = null
// @Override
// public void onAttach(Context context)
// {
// super.onAttach(context);
// Log.i(SongContentPortraitViewFragment.class.getSimpleName(), "" + context);
// if (context instanceof SongContentViewActivity) {
// activity = (SongContentViewActivity) context;
// }
// }
var presentationScreenService: PresentationScreenService? = null
private val customTagColorService = CustomTagColorService()
private val liveShareSongParser = LiveShareSongParser()
private val isPresentSong: Boolean
get()
{
return presentationScreenService != null && presentationScreenService!!.presentation != null
}
private val songBookNumber: String
get()
{
try
{
if (arguments!!.containsKey(CommonConstants.SONG_BOOK_NUMBER_KEY))
{
val songBookNumber = arguments!!.getInt(CommonConstants.SONG_BOOK_NUMBER_KEY, 0)
return if (songBookNumber > 0) "$songBookNumber. " else ""
}
} catch (ex: Exception)
{
Log.e(SongContentPortraitViewFragment::class.java.simpleName, "Error ", ex)
}
return ""
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setHasOptionsMenu(CommonUtils.isPhone(WorshipSongApplication.context!!))
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
val view = inflater.inflate(R.layout.song_content_portrait_view, container, false)
initSetUp()
setListView(view, song!!)
setFloatingActionMenu(view, song!!)
setNextButton(view)
setPreviousButton(view)
view.setOnTouchListener(SongContentPortraitViewTouchListener())
onBecameVisible(song)
return view
}
private fun initSetUp()
{
showStatusBar()
val bundle = arguments
title = bundle!!.getString(CommonConstants.TITLE_KEY)
tilteList = bundle.getStringArrayList(CommonConstants.TITLE_LIST_KEY)
if (bundle != null)
{
millis = bundle.getInt(KEY_VIDEO_TIME)
Log.i(this.javaClass.simpleName, "Video time $millis")
}
setSong()
}
private fun showStatusBar()
{
if (CommonUtils.isPhone(context!!))
{
if (Build.VERSION.SDK_INT < 16)
{
activity!!.window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
} else
{
val decorView = activity!!.window.decorView
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
}
}
val appCompatActivity = activity as AppCompatActivity?
if (appCompatActivity!!.supportActionBar != null)
{
appCompatActivity.supportActionBar!!.show()
appCompatActivity.supportActionBar!!.setDisplayHomeAsUpEnabled(CommonUtils.isPhone(WorshipSongApplication.context!!))
}
}
private fun setSong()
{
if (arguments!!.containsKey(CommonConstants.SERVICE_NAME_KEY))
{
val serviceName = arguments!!.getString(CommonConstants.SERVICE_NAME_KEY)
val serviceFilePath = LiveShareUtils.getServiceDirPath(context!!) + File.separator + serviceName
song = liveShareSongParser.parseSong(serviceFilePath, title!!)
} else
{
song = songDao.findContentsByTitle(title!!)
if (song == null)
{
song = Song(title!!)
val contents = ArrayList<String>()
contents.add(getString(R.string.message_song_not_available, "\"" + title + "\""))
song!!.contents = contents
}
song!!.authorName = authorService.findAuthorNameByTitle(title!!)
}
}
private fun setListView(view: View, song: Song)
{
listView = view.findViewById<View>(R.id.content_list) as ListView
presentSongCardViewAdapter = PresentSongCardViewAdapter(activity!!, song.contents!!)
listView!!.adapter = presentSongCardViewAdapter
listView!!.onItemClickListener = ListViewOnItemClickListener()
listView!!.onItemLongClickListener = ListViewOnItemLongClickListener()
}
private fun setFloatingActionMenu(view: View, song: Song)
{
floatingActionMenu = view.findViewById<View>(R.id.floating_action_menu) as FloatingActionsMenu
if (isPlayVideo(song.urlKey) && isPresentSong)
{
floatingActionMenu!!.visibility = View.VISIBLE
floatingActionMenu!!.setOnFloatingActionsMenuUpdateListener(object : FloatingActionsMenu.OnFloatingActionsMenuUpdateListener
{
override fun onMenuExpanded()
{
val color = R.color.gray_transparent
setListViewForegroundColor(ContextCompat.getColor(activity!!, color))
}
override fun onMenuCollapsed()
{
val color = 0x00000000
setListViewForegroundColor(color)
}
})
setPlaySongFloatingMenuButton(view, song.urlKey!!)
setPresentSongFloatingMenuButton(view)
} else
{
floatingActionMenu!!.visibility = View.GONE
if (isPresentSong)
{
setPresentSongFloatingButton(view)
}
if (isPlayVideo(song.urlKey))
{
setPlaySongFloatingButton(view, song.urlKey!!)
}
}
}
private fun setPlaySongFloatingMenuButton(view: View, urrlKey: String)
{
val playSongFloatingActionButton = view.findViewById<View>(R.id.play_song_floating_menu_button) as FloatingActionButton
if (isPlayVideo(urrlKey))
{
playSongFloatingActionButton.visibility = View.VISIBLE
playSongFloatingActionButton.setOnClickListener {
showYouTube(urrlKey)
if (floatingActionMenu!!.isExpanded)
{
floatingActionMenu!!.collapse()
}
}
}
}
private fun setPresentSongFloatingMenuButton(view: View)
{
val presentSongFloatingMenuButton = view.findViewById<View>(R.id.present_song_floating_menu_button) as FloatingActionButton
presentSongFloatingMenuButton.visibility = View.VISIBLE
presentSongFloatingMenuButton.setOnClickListener {
if (floatingActionMenu!!.isExpanded)
{
floatingActionMenu!!.collapse()
}
if (presentationScreenService!!.presentation != null)
{
presentSelectedVerse(0)
floatingActionMenu!!.visibility = View.GONE
activity!!.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
} else
{
Toast.makeText(activity, "Your device is not connected to any remote display", Toast.LENGTH_SHORT).show()
}
}
}
private fun setPresentSongFloatingButton(view: View)
{
presentSongFloatingButton = view.findViewById<View>(R.id.present_song_floating_button) as FloatingActionButton
presentSongFloatingButton!!.visibility = View.VISIBLE
presentSongFloatingButton!!.setOnClickListener {
if (presentationScreenService!!.presentation != null)
{
presentSelectedVerse(0)
presentSongFloatingButton!!.visibility = View.GONE
activity!!.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
} else
{
Toast.makeText(activity, "Your device is not connected to any remote display", Toast.LENGTH_SHORT).show()
}
}
}
private fun setPlaySongFloatingButton(view: View, urlKey: String)
{
val playSongFloatingButton = view.findViewById<View>(R.id.play_song_floating_button) as FloatingActionButton
playSongFloatingButton.visibility = View.VISIBLE
playSongFloatingButton.setOnClickListener { showYouTube(urlKey) }
}
private fun showYouTube(urlKey: String)
{
Log.i(this.javaClass.simpleName, "Url key: $urlKey")
val youTubeIntent = Intent(activity, CustomYoutubeBoxActivity::class.java)
youTubeIntent.putExtra(CustomYoutubeBoxActivity.KEY_VIDEO_ID, urlKey)
youTubeIntent.putExtra(CommonConstants.TITLE_KEY, title)
activity!!.startActivity(youTubeIntent)
}
private fun setNextButton(view: View)
{
nextButton = view.findViewById<View>(R.id.next_verse_floating_button) as FloatingActionButton
nextButton!!.visibility = View.GONE
nextButton!!.setOnClickListener(NextButtonOnClickListener())
}
private fun setPreviousButton(view: View)
{
previousButton = view.findViewById<View>(R.id.previous_verse_floating_button) as FloatingActionButton
previousButton!!.visibility = View.GONE
previousButton!!.setOnClickListener(PreviousButtonOnClickListener())
}
override fun fragmentBecameVisible()
{
onBecameVisible(song)
}
private fun onBecameVisible(song: Song?)
{
val presentingSong = Setting.instance.song
if (presentingSong != null && presentingSong == song && presentationScreenService!!.presentation != null)
{
setPresentation(song)
} else
{
hideOrShowComponents(song)
}
setActionBarTitle()
}
private fun setPresentation(song: Song)
{
val currentPosition = Setting.instance.slidePosition
presentSelectedVerse(currentPosition)
if (floatingActionMenu != null)
{
floatingActionMenu!!.visibility = View.GONE
}
if (presentSongFloatingButton != null)
{
presentSongFloatingButton!!.visibility = View.GONE
}
nextButton!!.visibility = if (song.contents!!.size - 1 == currentPosition) View.GONE else View.VISIBLE
previousButton!!.visibility = if (currentPosition == 0) View.GONE else View.VISIBLE
activity!!.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
private fun hideOrShowComponents(song: Song?)
{
if (nextButton != null)
{
nextButton!!.visibility = View.GONE
}
if (previousButton != null)
{
previousButton!!.visibility = View.GONE
}
if (isPlayVideo(song!!.urlKey) && isPresentSong && floatingActionMenu != null)
{
floatingActionMenu!!.visibility = View.VISIBLE
} else if (presentSongFloatingButton != null)
{
presentSongFloatingButton!!.visibility = View.VISIBLE
}
if (presentSongCardViewAdapter != null)
{
presentSongCardViewAdapter!!.setItemSelected(-1)
presentSongCardViewAdapter!!.notifyDataSetChanged()
}
if (listView != null)
{
listView!!.smoothScrollToPosition(0)
}
}
private inner class NextButtonOnClickListener : View.OnClickListener
{
override fun onClick(v: View)
{
val position = presentSongCardViewAdapter!!.selectedItem + 1
listView!!.smoothScrollToPositionFromTop(position, 2)
presentSelectedVerse(if (position <= song!!.contents!!.size) position else position - 1)
}
}
private inner class PreviousButtonOnClickListener : View.OnClickListener
{
override fun onClick(v: View)
{
val position = presentSongCardViewAdapter!!.selectedItem - 1
val previousPosition = if (position >= 0) position else 0
listView!!.smoothScrollToPosition(previousPosition, 2)
presentSelectedVerse(previousPosition)
}
}
private inner class ListViewOnItemClickListener : AdapterView.OnItemClickListener
{
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long)
{
if (previousButton!!.visibility == View.VISIBLE || nextButton!!.visibility == View.VISIBLE)
{
listView!!.smoothScrollToPositionFromTop(position, 2)
presentSelectedVerse(position)
}
if (floatingActionMenu != null && floatingActionMenu!!.isExpanded)
{
activity!!.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
floatingActionMenu!!.collapse()
val color = 0x00000000
setListViewForegroundColor(color)
}
}
}
private fun presentSelectedVerse(position: Int)
{
if (presentationScreenService!!.presentation != null)
{
presentationScreenService!!.showNextVerse(song, position)
presentSongCardViewAdapter!!.setItemSelected(position)
presentSongCardViewAdapter!!.notifyDataSetChanged()
previousButton!!.visibility = if (position <= 0) View.GONE else View.VISIBLE
nextButton!!.visibility = if (position >= song!!.contents!!.size - 1) View.GONE else View.VISIBLE
}
}
private inner class ListViewOnItemLongClickListener : AdapterView.OnItemLongClickListener
{
internal val isCopySelectedVerse: Boolean
get() = !isPresentSong || isPlayVideo(song!!.urlKey) && floatingActionMenu != null && floatingActionMenu!!.visibility == View.VISIBLE || presentSongFloatingButton != null && presentSongFloatingButton!!.visibility == View.VISIBLE
override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean
{
if (isCopySelectedVerse)
{
val selectedVerse = song!!.contents!![position]
presentSongCardViewAdapter!!.setItemSelected(position)
presentSongCardViewAdapter!!.notifyDataSetChanged()
shareSongInSocialMedia(selectedVerse)
}
return false
}
internal fun shareSongInSocialMedia(selectedText: String)
{
val formattedContent = song!!.title + "\n\n" + customTagColorService.getFormattedLines(selectedText) + "\n" + String.format(getString(R.string.verse_share_info), getString(R.string.app_name))
val textShareIntent = Intent(Intent.ACTION_SEND)
textShareIntent.putExtra(Intent.EXTRA_TEXT, formattedContent)
textShareIntent.type = "text/plain"
val intent = Intent.createChooser(textShareIntent, "Share verse with...")
activity!!.startActivity(intent)
}
}
private fun setListViewForegroundColor(color: Int)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
listView!!.foreground = ColorDrawable(color)
}
}
private fun isPlayVideo(urrlKey: String?): Boolean
{
val playVideoStatus = preferenceSettingService.isPlayVideo
return urrlKey != null && urrlKey.length > 0 && playVideoStatus
}
override fun onSaveInstanceState(outState: Bundle)
{
super.onSaveInstanceState(outState)
if (youTubePlayer != null)
{
outState.putInt(KEY_VIDEO_TIME, youTubePlayer.currentTimeMillis)
Log.i(this.javaClass.simpleName, "Video duration: " + youTubePlayer.currentTimeMillis)
}
}
private inner class SongContentPortraitViewTouchListener : View.OnTouchListener
{
override fun onTouch(v: View, event: MotionEvent): Boolean
{
val position = tilteList!!.indexOf(title)
Setting.instance.position = position
return true
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater)
{
menu.clear()
if (CommonUtils.isPhone(context!!))
{
inflater!!.inflate(R.menu.action_bar_options, menu)
}
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean
{
Log.i(SongContentPortraitViewFragment::class.java.simpleName, "Menu item " + item.itemId + " " + R.id.options)
when (item.itemId)
{
android.R.id.home ->
{
activity!!.finish()
return true
}
R.id.options ->
{
Log.i(SongContentPortraitViewFragment::class.java.simpleName, "On tapped options")
popupMenuService = PopupMenuService()
PermissionUtils.isStoragePermissionGranted(activity as Activity)
popupMenuService!!.showPopupmenu(activity as AppCompatActivity, activity!!.findViewById(R.id.options), title!!, false)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onPrepareOptionsMenu(menu: Menu)
{
super.onPrepareOptionsMenu(menu)
}
override fun setUserVisibleHint(isVisibleToUser: Boolean)
{
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser)
{
setActionBarTitle()
}
}
private fun setActionBarTitle()
{
val appCompatActivity = activity as AppCompatActivity?
try
{
if (preferenceSettingService != null && tilteList!!.size > 0 && CommonUtils.isPhone(context!!))
{
val title: String
if (tilteList!!.size == 1)
{
title = tilteList!![0]
} else
{
title = tilteList!![Setting.instance.position]
}
val song = songDao.findContentsByTitle(title)
appCompatActivity!!.title = getTitle(song, title)
}
} catch (ex: Exception)
{
appCompatActivity!!.title = title
}
}
private fun getTitle(song: Song?, defaultTitle: String): String
{
try
{
val title = if (preferenceSettingService.isTamil && song!!.tamilTitle!!.length > 0) song.tamilTitle
else song!!.title
return songBookNumber + title
} catch (e: Exception)
{
return songBookNumber + defaultTitle
}
}
companion object
{
val KEY_VIDEO_TIME = "KEY_VIDEO_TIME"
fun newInstance(title: String, titles: ArrayList<String>): SongContentPortraitViewFragment
{
val songContentPortraitViewFragment = SongContentPortraitViewFragment()
val bundle = Bundle()
bundle.putStringArrayList(CommonConstants.TITLE_LIST_KEY, titles)
bundle.putString(CommonConstants.TITLE_KEY, title)
songContentPortraitViewFragment.arguments = bundle
return songContentPortraitViewFragment
}
fun newInstance(bundle: Bundle): SongContentPortraitViewFragment
{
val songContentPortraitViewFragment = SongContentPortraitViewFragment()
songContentPortraitViewFragment.arguments = bundle
return songContentPortraitViewFragment
}
}
}
| gpl-3.0 | a098648a6c61ea2370a0902e97265478 | 35.846284 | 240 | 0.634576 | 5.598819 | false | false | false | false |
GeoffreyMetais/vlc-android | application/tools/src/main/java/org/videolan/tools/HttpImageLoader.kt | 1 | 3738 | /*
* ************************************************************************
* HttpImageLoader.kt
* *************************************************************************
* Copyright © 2020 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
package org.videolan.tools
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import androidx.collection.SimpleArrayMap
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import kotlin.math.floor
import kotlin.math.max
object HttpImageLoader {
private val currentJobs = SimpleArrayMap<String, CompletableDeferred<Bitmap?>>()
private val jobsLocker = Mutex()
suspend fun downloadBitmap(imageUrl: String): Bitmap? {
val icon = BitmapCache.getBitmapFromMemCache(imageUrl) ?: jobsLocker.withLock {
currentJobs[imageUrl]?.takeIf { it.isActive }
}?.await()
if (icon != null) return icon
return withContext(Dispatchers.IO) {
jobsLocker.withLock { currentJobs.put(imageUrl, CompletableDeferred()) }
var urlConnection: HttpURLConnection? = null
var inputStream: InputStream? = null
try {
val url = URL(imageUrl)
urlConnection = url.openConnection() as HttpURLConnection
inputStream = BufferedInputStream(urlConnection.inputStream)
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeStream(inputStream, null, options)
options.inJustDecodeBounds = false
//limit image to 150dp for the larger size
val ratio: Float = max(options.outHeight, options.outWidth).toFloat() / 150.dp.toFloat()
if (ratio > 1) options.inSampleSize = floor(ratio).toInt()
urlConnection = url.openConnection() as HttpURLConnection
inputStream = BufferedInputStream(urlConnection.inputStream)
BitmapFactory.decodeStream(inputStream, null, options).also {
BitmapCache.addBitmapToMemCache(imageUrl, it)
}
} catch (ignored: IOException) {
Log.e("", ignored.message, ignored)
null
} catch (ignored: IllegalArgumentException) {
Log.e("", ignored.message, ignored)
null
} finally {
CloseableUtils.close(inputStream)
urlConnection?.disconnect()
}
}.also {
jobsLocker.withLock { currentJobs[imageUrl]?.complete(it) }
}
}
}
| gpl-2.0 | a5b2e4c772e4b7796aabeff0d3f76f89 | 40.065934 | 104 | 0.629917 | 5.338571 | false | false | false | false |
NextFaze/dev-fun | devfun-compiler/src/main/java/com/nextfaze/devfun/compiler/SupportedOptions.kt | 1 | 2211 | package com.nextfaze.devfun.compiler
import javax.inject.Inject
import javax.inject.Singleton
import javax.lang.model.element.Element
import javax.lang.model.element.QualifiedNameable
import javax.lang.model.util.Elements
@Singleton
internal class Options @Inject constructor(
override val elements: Elements,
private val options: Map<String, String>
) : WithElements {
private fun String.optionOf(): String? = options[this]?.trim()?.takeIf { it.isNotBlank() }
private fun String.booleanOf(default: Boolean = false): Boolean = optionOf()?.toBoolean() ?: default
val useKotlinReflection = FLAG_USE_KOTLIN_REFLECTION.booleanOf()
private val isDebugVerbose = FLAG_DEBUG_VERBOSE.booleanOf()
val isDebugCommentsEnabled = isDebugVerbose || FLAG_DEBUG_COMMENTS.booleanOf()
val packageRoot = PACKAGE_ROOT.optionOf()
val packageSuffix = PACKAGE_SUFFIX.optionOf()
val packageOverride = PACKAGE_OVERRIDE.optionOf()
val applicationPackage = APPLICATION_PACKAGE.optionOf()
val applicationVariant = APPLICATION_VARIANT.optionOf()
val extPackageRoot = EXT_PACKAGE_ROOT.optionOf()
val extPackageSuffix = EXT_PACKAGE_SUFFIX.optionOf()
val extPackageOverride = EXT_PACKAGE_OVERRIDE.optionOf()
val generateInterfaces = GENERATE_INTERFACES.booleanOf(true)
val generateDefinitions = GENERATE_DEFINITIONS.booleanOf(true)
val noteLoggingEnabled = NOTE_LOGGING_ENABLED.booleanOf(false)
val promoteNoteMessages = PROMOTE_NOTE_LOG_MESSAGES.booleanOf(false)
private val elementFilterInclude = ELEMENTS_FILTER_INCLUDE.optionOf()?.split(",")?.map { it.trim() } ?: emptyList()
private val elementFilterExclude = ELEMENTS_FILTER_EXCLUDE.optionOf()?.split(",")?.map { it.trim() } ?: emptyList()
fun shouldProcessElement(element: Element): Boolean {
if (elementFilterInclude.isEmpty() && elementFilterExclude.isEmpty()) return true
val fqn = (element as? QualifiedNameable)?.qualifiedName?.toString() ?: "${element.packageElement}.${element.simpleName}"
return (elementFilterInclude.isEmpty() || elementFilterInclude.any { fqn.startsWith(it) }) &&
elementFilterExclude.none { fqn.startsWith(it) }
}
}
| apache-2.0 | a35ffd22c845b03b3e5b6bbd54c62650 | 45.0625 | 129 | 0.741746 | 4.512245 | false | false | false | false |
BjoernPetersen/JMusicBot | buildSrc/src/main/kotlin/Plugin.kt | 1 | 247 | object Plugin {
const val SPOTLESS = "5.7.0"
const val KTLINT = "0.39.0"
const val DETEKT = "1.14.2"
const val JACOCO = "0.8.6"
const val VERSIONS = "0.34.0"
const val KOTLIN = "1.4.10"
const val DOKKA = "1.4.10.2"
}
| mit | c9298e861a788f55c82a332ef744156a | 21.454545 | 33 | 0.566802 | 2.375 | false | false | false | false |
BjoernPetersen/JMusicBot | src/test/kotlin/net/bjoernpetersen/musicbot/spi/plugin/PluginTest.kt | 1 | 2234 | package net.bjoernpetersen.musicbot.spi.plugin
import net.bjoernpetersen.musicbot.api.config.Config
import net.bjoernpetersen.musicbot.api.player.Song
import net.bjoernpetersen.musicbot.api.plugin.IdBase
import net.bjoernpetersen.musicbot.api.plugin.bases
import net.bjoernpetersen.musicbot.api.plugin.id
import net.bjoernpetersen.musicbot.spi.loader.Resource
import net.bjoernpetersen.musicbot.spi.plugin.management.ProgressFeedback
import org.junit.jupiter.api.Assertions.assertDoesNotThrow
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class PluginTest {
@Test
fun allBases() {
val uut = TestProvider()
val bases = uut.bases.toSet()
assertEquals(setOf(Provider::class, TestProviderBase::class), bases)
}
@Test
fun idDoesNotThrow() {
val uut = TestProvider()
assertDoesNotThrow { uut.id }
}
@Test
fun idCorrect() {
val uut = TestProvider()
assertEquals(TestProviderBase::class, uut.id.type)
}
}
@IdBase("Test")
private interface TestProviderBase : Provider
private class TestProvider : TestProviderBase {
override fun createConfigEntries(config: Config): List<Config.Entry<*>> {
TODO("not implemented")
}
override fun createSecretEntries(secrets: Config): List<Config.Entry<*>> {
TODO("not implemented")
}
override fun createStateEntries(state: Config) {
TODO("not implemented")
}
override suspend fun initialize(progressFeedback: ProgressFeedback) {
TODO("not implemented")
}
override suspend fun close() {
TODO("not implemented")
}
override val subject: String = "For testing eyes only"
override val description: String = ""
override val name: String = "TestProvider"
override suspend fun loadSong(song: Song): Resource {
TODO("not implemented")
}
override suspend fun supplyPlayback(song: Song, resource: Resource): Playback {
TODO("not implemented")
}
override suspend fun lookup(id: String): Song {
TODO("not implemented")
}
override suspend fun search(query: String, offset: Int): List<Song> {
TODO("not implemented")
}
}
| mit | da65aa01f8d0388d02c421d8f2318c05 | 27.641026 | 83 | 0.695613 | 4.43254 | false | true | false | false |
goodwinnk/intellij-community | plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.kt | 2 | 18210 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.github
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.mapSmartSet
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.vcsUtil.VcsFileUtil
import git4idea.DialogManager
import git4idea.GitUtil
import git4idea.actions.BasicAction
import git4idea.actions.GitInit
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.util.GitFileUtils
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider
import org.jetbrains.plugins.github.ui.GithubShareDialog
import org.jetbrains.plugins.github.util.GithubAccountsMigrationHelper
import org.jetbrains.plugins.github.util.GithubGitHelper
import org.jetbrains.plugins.github.util.GithubNotifications
import org.jetbrains.plugins.github.util.GithubUtil
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Container
import java.awt.FlowLayout
import java.io.IOException
import java.util.*
import javax.swing.BoxLayout
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class GithubShareAction : DumbAwareAction("Share Project on GitHub", "Easily share project on GitHub", AllIcons.Vcs.Vendors.Github) {
override fun update(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT)
e.presentation.isEnabledAndVisible = project != null && !project.isDefault
}
// get gitRepository
// check for existing git repo
// check available repos and privateRepo access (net)
// Show dialog (window)
// create GitHub repo (net)
// create local git repo (if not exist)
// add GitHub as a remote host
// make first commit
// push everything (net)
override fun actionPerformed(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT)
val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
if (project == null || project.isDisposed) {
return
}
shareProjectOnGithub(project, file)
}
companion object {
private val LOG = GithubUtil.LOG
@JvmStatic
fun shareProjectOnGithub(project: Project, file: VirtualFile?) {
BasicAction.saveAll()
val gitRepository = GithubGitHelper.findGitRepository(project, file)
if (!service<GithubAccountsMigrationHelper>().migrate(project)) return
val authManager = service<GithubAuthenticationManager>()
if (!authManager.ensureHasAccounts(project)) return
val accounts = authManager.getAccounts()
val progressManager = service<ProgressManager>()
val requestExecutorManager = service<GithubApiRequestExecutorManager>()
val accountInformationProvider = service<GithubAccountInformationProvider>()
val gitHelper = service<GithubGitHelper>()
val git = service<Git>()
val possibleRemotes = gitRepository?.let(gitHelper::getAccessibleRemoteUrls).orEmpty()
if (possibleRemotes.isNotEmpty()) {
val existingRemotesDialog = GithubExistingRemotesDialog(project, possibleRemotes)
DialogManager.show(existingRemotesDialog)
if (!existingRemotesDialog.isOK) {
return
}
}
val accountInformationLoader = object : (GithubAccount, Component) -> Pair<Boolean, Set<String>> {
private val loadedInfo = mutableMapOf<GithubAccount, Pair<Boolean, Set<String>>>()
@Throws(IOException::class)
override fun invoke(account: GithubAccount, parentComponent: Component) = loadedInfo.getOrPut(account) {
val requestExecutor = requestExecutorManager.getExecutor(account, parentComponent) ?: throw ProcessCanceledException()
progressManager.runProcessWithProgressSynchronously(ThrowableComputable<Pair<Boolean, Set<String>>, IOException> {
val user = requestExecutor.execute(progressManager.progressIndicator, GithubApiRequests.CurrentUser.get(account.server))
val names = GithubApiPagesLoader
.loadAll(requestExecutor, progressManager.progressIndicator,
GithubApiRequests.CurrentUser.Repos.pages(account.server, false))
.mapSmartSet { it.name }
user.canCreatePrivateRepo() to names
}, "Loading Account Information For $account", true, project)
}
}
val shareDialog = GithubShareDialog(project,
accounts,
authManager.getDefaultAccount(project),
gitRepository?.remotes?.map { it.name }?.toSet() ?: emptySet(),
accountInformationLoader)
DialogManager.show(shareDialog)
if (!shareDialog.isOK) {
return
}
val name: String = shareDialog.getRepositoryName()
val isPrivate: Boolean = shareDialog.isPrivate()
val remoteName: String = shareDialog.getRemoteName()
val description: String = shareDialog.getDescription()
val account: GithubAccount = shareDialog.getAccount()
val requestExecutor = requestExecutorManager.getExecutor(account, project) ?: return
object : Task.Backgroundable(project, "Sharing Project on GitHub...") {
private lateinit var url: String
override fun run(indicator: ProgressIndicator) {
// create GitHub repo (network)
LOG.info("Creating GitHub repository")
indicator.text = "Creating GitHub repository..."
url = requestExecutor
.execute(indicator, GithubApiRequests.CurrentUser.Repos.create(account.server, name, description, isPrivate)).htmlUrl
LOG.info("Successfully created GitHub repository")
val root = gitRepository?.root ?: project.baseDir
// creating empty git repo if git is not initialized
LOG.info("Binding local project with GitHub")
if (gitRepository == null) {
LOG.info("No git detected, creating empty git repo")
indicator.text = "Creating empty git repo..."
if (!createEmptyGitRepository(project, root)) {
return
}
}
val repositoryManager = GitUtil.getRepositoryManager(project)
val repository = repositoryManager.getRepositoryForRoot(root)
if (repository == null) {
GithubNotifications.showError(project, "Failed to create GitHub Repository", "Can't find Git repository")
return
}
indicator.text = "Retrieving username..."
val username = accountInformationProvider.getInformation(requestExecutor, indicator, account).login
val remoteUrl = gitHelper.getRemoteUrl(account.server, username, name)
//git remote add origin [email protected]:login/name.git
LOG.info("Adding GitHub as a remote host")
indicator.text = "Adding GitHub as a remote host..."
git.addRemote(repository, remoteName, remoteUrl).throwOnError()
repository.update()
// create sample commit for binding project
if (!performFirstCommitIfRequired(project, root, repository, indicator, name, url)) {
return
}
//git push origin master
LOG.info("Pushing to github master")
indicator.text = "Pushing to github master..."
if (!pushCurrentBranch(project, repository, remoteName, remoteUrl, name, url)) {
return
}
GithubNotifications.showInfoURL(project, "Successfully shared project on GitHub", name, url)
}
private fun createEmptyGitRepository(project: Project,
root: VirtualFile): Boolean {
val result = Git.getInstance().init(project, root)
if (!result.success()) {
VcsNotifier.getInstance(project).notifyError(GitBundle.getString("initializing.title"), result.errorOutputAsHtmlString)
LOG.info("Failed to create empty git repo: " + result.errorOutputAsJoinedString)
return false
}
GitInit.refreshAndConfigureVcsMappings(project, root, root.path)
return true
}
private fun performFirstCommitIfRequired(project: Project,
root: VirtualFile,
repository: GitRepository,
indicator: ProgressIndicator,
name: String,
url: String): Boolean {
// check if there is no commits
if (!repository.isFresh) {
return true
}
LOG.info("Trying to commit")
try {
LOG.info("Adding files for commit")
indicator.text = "Adding files to git..."
// ask for files to add
val trackedFiles = ChangeListManager.getInstance(project).affectedFiles
val untrackedFiles = filterOutIgnored(project, repository.untrackedFilesHolder.retrieveUntrackedFiles())
trackedFiles.removeAll(untrackedFiles) // fix IDEA-119855
val allFiles = ArrayList<VirtualFile>()
allFiles.addAll(trackedFiles)
allFiles.addAll(untrackedFiles)
val dialog = invokeAndWaitIfNeed(indicator.modalityState) {
GithubUntrackedFilesDialog(project, allFiles).apply {
if (!trackedFiles.isEmpty()) {
selectedFiles = trackedFiles
}
DialogManager.show(this)
}
}
val files2commit = dialog.selectedFiles
if (!dialog.isOK || files2commit.isEmpty()) {
GithubNotifications.showInfoURL(project, "Successfully created empty repository on GitHub", name, url)
return false
}
val files2add = ContainerUtil.intersection(untrackedFiles, files2commit)
val files2rm = ContainerUtil.subtract(trackedFiles, files2commit)
val modified = HashSet(trackedFiles)
modified.addAll(files2commit)
GitFileUtils.addFiles(project, root, files2add)
GitFileUtils.deleteFilesFromCache(project, root, files2rm)
// commit
LOG.info("Performing commit")
indicator.text = "Performing commit..."
val handler = GitLineHandler(project, root, GitCommand.COMMIT)
handler.setStdoutSuppressed(false)
handler.addParameters("-m", dialog.commitMessage)
handler.endOptions()
Git.getInstance().runCommand(handler).throwOnError()
VcsFileUtil.markFilesDirty(project, modified)
}
catch (e: VcsException) {
LOG.warn(e)
GithubNotifications.showErrorURL(project, "Can't finish GitHub sharing process", "Successfully created project ", "'$name'",
" on GitHub, but initial commit failed:<br/>" + GithubUtil.getErrorTextFromException(e),
url)
return false
}
LOG.info("Successfully created initial commit")
return true
}
private fun filterOutIgnored(project: Project, files: Collection<VirtualFile>): Collection<VirtualFile> {
val changeListManager = ChangeListManager.getInstance(project)
val vcsManager = ProjectLevelVcsManager.getInstance(project)
return ContainerUtil.filter(files) { file -> !changeListManager.isIgnoredFile(file) && !vcsManager.isIgnored(file) }
}
private fun pushCurrentBranch(project: Project,
repository: GitRepository,
remoteName: String,
remoteUrl: String,
name: String,
url: String): Boolean {
val currentBranch = repository.currentBranch
if (currentBranch == null) {
GithubNotifications.showErrorURL(project, "Can't finish GitHub sharing process", "Successfully created project ", "'$name'",
" on GitHub, but initial push failed: no current branch", url)
return false
}
val result = git.push(repository, remoteName, remoteUrl, currentBranch.name, true)
if (!result.success()) {
GithubNotifications.showErrorURL(project, "Can't finish GitHub sharing process", "Successfully created project ", "'$name'",
" on GitHub, but initial push failed:<br/>" + result.errorOutputAsHtmlString, url)
return false
}
return true
}
override fun onThrowable(error: Throwable) {
GithubNotifications.showError(project, "Failed to create GitHub Repository", error)
}
}.queue()
}
}
@TestOnly
class GithubExistingRemotesDialog(project: Project, private val remotes: List<String>) : DialogWrapper(project) {
init {
title = "Project Is Already on GitHub"
setOKButtonText("Share Anyway")
init()
}
override fun createCenterPanel(): JComponent? {
val mainText = JBLabel(if (remotes.size == 1) "Remote is already on GitHub:"
else "Following remotes are already on GitHub:")
val remotesPanel = JPanel().apply {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
}
for (remote in remotes) {
remotesPanel.add(JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)).apply {
add(LinkLabel.create(remote, Runnable { BrowserUtil.browse(remote) }))
add(JBLabel(AllIcons.Ide.External_link_arrow))
})
}
val messagesPanel = JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP)
.addToTop(mainText)
.addToCenter(remotesPanel)
val iconContainer = Container().apply {
layout = BorderLayout()
add(JLabel(Messages.getQuestionIcon()), BorderLayout.NORTH)
}
return JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP)
.addToCenter(messagesPanel)
.addToLeft(iconContainer)
.apply { border = JBUI.Borders.emptyBottom(UIUtil.LARGE_VGAP) }
}
}
@TestOnly
class GithubUntrackedFilesDialog(private val myProject: Project, untrackedFiles: List<VirtualFile>) :
SelectFilesDialog(myProject, untrackedFiles, null, null, true, false),
DataProvider {
private var myCommitMessagePanel: CommitMessage? = null
val commitMessage: String
get() = myCommitMessagePanel!!.comment
init {
title = "Add Files For Initial Commit"
init()
}
override fun createNorthPanel(): JComponent? {
return null
}
override fun createCenterPanel(): JComponent? {
val tree = super.createCenterPanel()
myCommitMessagePanel = CommitMessage(myProject)
myCommitMessagePanel!!.setCommitMessage("Initial commit")
val splitter = Splitter(true)
splitter.setHonorComponentsMinimumSize(true)
splitter.firstComponent = tree
splitter.secondComponent = myCommitMessagePanel
splitter.proportion = 0.7f
return splitter
}
override fun getData(@NonNls dataId: String): Any? {
return if (VcsDataKeys.COMMIT_MESSAGE_CONTROL.`is`(dataId)) {
myCommitMessagePanel
}
else null
}
override fun getDimensionServiceKey(): String? {
return "Github.UntrackedFilesDialog"
}
}
} | apache-2.0 | 8305fa418b7ff4c6818e059b7bab7bb5 | 41.648712 | 140 | 0.670291 | 5.332357 | false | false | false | false |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/utils/Snackbar.kt | 1 | 1165 | package org.equeim.tremotesf.ui.utils
import androidx.annotation.StringRes
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
fun CoordinatorLayout.showSnackbar(
message: CharSequence,
length: Int,
@StringRes actionText: Int = 0,
action: (() -> Unit)? = null,
onDismissed: ((Snackbar) -> Unit)? = null
) = Snackbar.make(this, message, length).apply {
if (actionText != 0 && action != null) {
setAction(actionText) { action() }
}
if (onDismissed != null) {
addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>() {
override fun onDismissed(transientBottomBar: Snackbar, event: Int) {
onDismissed(transientBottomBar)
}
})
}
show()
}
fun CoordinatorLayout.showSnackbar(
@StringRes message: Int,
length: Int,
@StringRes actionText: Int = 0,
action: (() -> Unit)? = null,
onDismissed: ((Snackbar) -> Unit)? = null
) = showSnackbar(resources.getString(message), length, actionText, action, onDismissed)
| gpl-3.0 | fc0843e9a6ef11c301fd0b676f987c93 | 33.264706 | 87 | 0.678112 | 4.498069 | false | false | false | false |
drakeet/MultiType | sample/src/main/kotlin/com/drakeet/multitype/sample/communication/CommunicateWithBinderActivity.kt | 1 | 1627 | /*
* Copyright (c) 2016-present. Drakeet Xu
*
* 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.drakeet.multitype.sample.communication
import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.MultiTypeAdapter
import com.drakeet.multitype.sample.MenuBaseActivity
import com.drakeet.multitype.sample.R
import com.drakeet.multitype.sample.normal.TextItem
import java.util.*
/**
* @author Drakeet Xu
*/
class CommunicateWithBinderActivity : MenuBaseActivity() {
private val aFieldValue = "aFieldValue of SimpleActivity"
private var adapter: MultiTypeAdapter = MultiTypeAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
val recyclerView = findViewById<RecyclerView>(R.id.list)
val items = ArrayList<Any>()
adapter.register(TextItemWithOutsizeDataViewBinder(aFieldValue))
recyclerView.adapter = adapter
for (i in 0..19) {
items.add(TextItem(i.toString()))
}
adapter.items = items
adapter.notifyDataSetChanged()
}
}
| apache-2.0 | e01084941daf55d70027c21885b6b9aa | 31.54 | 75 | 0.757837 | 4.248042 | false | false | false | false |
mockk/mockk | modules/mockk/src/jvmTest/kotlin/io/mockk/junit5/MockKExtensionTest.kt | 1 | 2375 | @file:Suppress("UNUSED_PARAMETER")
package io.mockk.junit5
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.impl.annotations.SpyK
import io.mockk.verify
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
@ExtendWith(MockKExtension::class)
class MockKExtensionTest {
enum class Direction {
NORTH,
SOUTH,
EAST,
WEST
}
enum class Outcome {
FAILURE,
RECORDED
}
class RelaxedOutcome
class Car {
fun recordTelemetry(speed: Int, direction: Direction, lat: Double, long: Double): Outcome {
return Outcome.FAILURE
}
fun relaxedTest(): RelaxedOutcome? {
return null
}
}
@MockK
private lateinit var car2: Car
@RelaxedMockK
private lateinit var relaxedCar: Car
@SpyK
private var carSpy = Car()
@Test
fun injectsValidMockInMethods(@MockK car: Car) {
every {
car.recordTelemetry(
speed = more(50),
direction = Direction.NORTH,
lat = any(),
long = any()
)
} returns Outcome.RECORDED
val result = car.recordTelemetry(51, Direction.NORTH, 1.0, 2.0)
assertEquals(Outcome.RECORDED, result)
}
@Test
fun injectsValidMockInClass() {
every {
car2.recordTelemetry(
speed = more(50),
direction = Direction.NORTH,
lat = any(),
long = any()
)
} returns Outcome.RECORDED
val result = car2.recordTelemetry(51, Direction.NORTH, 1.0, 2.0)
assertEquals(Outcome.RECORDED, result)
}
@Test
fun injectsValidRelaxedMockInMethods(@RelaxedMockK car: Car) {
val result = car.relaxedTest()
assertTrue(result is RelaxedOutcome)
}
@Test
fun injectsValidRelaxedMockInClass() {
val result = relaxedCar.relaxedTest()
assertTrue(result is RelaxedOutcome)
}
@Test
fun testInjectsValidSpyInClass() {
val result = carSpy.relaxedTest()
assertNull(result)
verify { carSpy.relaxedTest() }
}
}
| apache-2.0 | fe36c956d69ce90db6bdb0dd216d7598 | 21.40566 | 99 | 0.605474 | 4.373849 | false | true | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/util/ArchivesManager.kt | 1 | 2956 | package com.emogoth.android.phone.mimi.util
import android.util.Log
import com.emogoth.android.phone.mimi.BuildConfig
import com.emogoth.android.phone.mimi.db.ArchiveTableConnection
import com.emogoth.android.phone.mimi.db.models.Archive
import com.emogoth.android.phone.mimi.viewmodel.ChanDataSource
import com.mimireader.chanlib.models.ChanThread
import io.reactivex.Single
import io.reactivex.SingleEmitter
import io.reactivex.schedulers.Schedulers
class ArchivesManager constructor(private val connector: ChanDataSource) {
val TAG = ArchivesManager::class.java.simpleName
private fun archives(board: String): Single<List<Archive>> {
return ArchiveTableConnection.fetchArchives(board)
}
fun thread(board: String, threadId: Long): Single<ChanThread> {
return ArchiveTableConnection.fetchArchives(board)
.observeOn(Schedulers.io())
.flatMap { archiveItems: List<Archive> ->
if (BuildConfig.DEBUG) {
if (archiveItems.isNotEmpty()) {
for (item in archiveItems) {
Log.d(TAG, "Archive: name=${item.name}, domain=${item.domain}")
}
} else {
Log.w(TAG, "No archive servers found for /$board/")
}
}
Single.create { emitter: SingleEmitter<ChanThread> ->
var success = false
var done = archiveItems.isEmpty()
var i = 0
while (!done) {
done = try {
val item = archiveItems[i]
val archivedThread = connector.fetchArchivedThread(board, threadId, item).subscribeOn(Schedulers.io()).blockingGet()
if (archivedThread.name?.isNotEmpty() == true && archivedThread.posts.size > 0) {
success = true
if (!emitter.isDisposed) {
emitter.onSuccess(archivedThread)
}
true
} else {
i++
archiveItems.size <= i
}
} catch (e: Exception) {
Log.e(TAG, "Caught exception while fetching archives", e)
i++
archiveItems.size <= i
}
}
if (!success && !emitter.isDisposed) {
emitter.onError(Exception("No Archive Found For Thread"))
}
}
}
}
} | apache-2.0 | b8a134c5786f578a0997e1929f7d3eca | 45.203125 | 148 | 0.469892 | 5.888446 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/render/Texture.kt | 1 | 4704 | package com.soywiz.korge.render
import com.soywiz.kmem.*
import com.soywiz.korag.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.format.*
import com.soywiz.korio.*
import com.soywiz.korio.file.*
import com.soywiz.korio.lang.*
import com.soywiz.korma.geom.*
/**
* A [Texture] is a region (delimited by [left], [top], [right] and [bottom]) of a [Texture.Base].
* A [Texture.Base] wraps a [AG.Texture] but adds [width] and [height] information.
*/
class Texture(
val base: Base,
/** Left position of the region of the texture in pixels */
val left: Int = 0,
/** Top position of the region of the texture in pixels */
val top: Int = 0,
/** Right position of the region of the texture in pixels */
val right: Int = base.width,
/** Bottom position of the region of the texture in pixels */
val bottom: Int = base.height
) : Closeable, BmpCoords {
/** Wether the texture is multiplied or not */
val premultiplied get() = base.premultiplied
/** Left position of the region of the texture in pixels */
val x = left
/** Top position of the region of the texture in pixels */
val y = top
/** Width of this texture region in pixels */
val width = right - left
/** Height of this texture region in pixels */
val height = bottom - top
/** Left coord of the texture region as a ratio (a value between 0 and 1) */
val x0: Float = (left).toFloat() / base.width.toFloat()
/** Right coord of the texture region as a ratio (a value between 0 and 1) */
val x1: Float = (right).toFloat() / base.width.toFloat()
/** Top coord of the texture region as a ratio (a value between 0 and 1) */
val y0: Float = (top).toFloat() / base.height.toFloat()
/** Bottom coord of the texture region as a ratio (a value between 0 and 1) */
val y1: Float = (bottom).toFloat() / base.height.toFloat()
override val tl_x get() = x0
override val tl_y get() = y0
override val tr_x get() = x1
override val tr_y get() = y0
override val bl_x get() = x0
override val bl_y get() = y1
override val br_x get() = x1
override val br_y get() = y1
/**
* Creates a slice of this texture, by [x], [y], [width] and [height].
*/
fun slice(x: Int, y: Int, width: Int, height: Int) = sliceBounds(x, y, x + width, y + height)
/**
* Createa a slice of this texture by [rect].
*/
fun slice(rect: Rectangle) = slice(rect.x.toInt(), rect.y.toInt(), rect.width.toInt(), rect.height.toInt())
/**
* Creates a slice of this texture by its bounds [left], [top], [right], [bottom].
*/
fun sliceBounds(left: Int, top: Int, right: Int, bottom: Int): Texture {
val tleft = (this.x + left).clamp(this.left, this.right)
val tright = (this.x + right).clamp(this.left, this.right)
val ttop = (this.y + top).clamp(this.top, this.bottom)
val tbottom = (this.y + bottom).clamp(this.top, this.bottom)
return Texture(base, tleft, ttop, tright, tbottom)
}
companion object {
/**
* Creates a [Texture] from a texture [agBase] and its wanted size [width], [height].
*/
operator fun invoke(agBase: AG.Texture, width: Int, height: Int): Texture =
Texture(Base(agBase, width, height), 0, 0, width, height)
}
/**
* Represents a full texture region wraping a [base] [AG.Texture] and specifying its [width] and [height]
*/
class Base(var base: AG.Texture?, var width: Int, var height: Int) : Closeable {
var version = -1
val premultiplied get() = base?.premultiplied == true
override fun close(): Unit {
base?.close()
base = null
}
fun update(bmp: Bitmap, mipmaps: Boolean = bmp.mipmaps) {
base?.upload(bmp, mipmaps)
}
}
/**
* Updates this texture from a [bmp] and optionally generates [mipmaps].
*/
fun update(bmp: Bitmap32, mipmaps: Boolean = false) {
base.update(bmp, mipmaps)
}
/**
* Closes the texture
*/
override fun close() = base.close()
override fun toString(): String = "Texture($base, (x=$x, y=$y, width=$width, height=$height))"
}
//suspend fun VfsFile.readTexture(ag: AG, imageFormats: ImageFormats, mipmaps: Boolean = true): Texture {
// //println("VfsFile.readTexture[1]")
// val tex = ag.createTexture()
// //println("VfsFile.readTexture[2]")
// val bmp = this.readBitmapOptimized(imageFormats)
// //val bmp = this.readBitmapNoNative()
// //println("VfsFile.readTexture[3]")
// val canHasMipmaps = bmp.width.isPowerOfTwo && bmp.height.isPowerOfTwo
// //println("VfsFile.readTexture[4]")
// tex.upload(bmp, mipmaps = canHasMipmaps && mipmaps)
// //println("VfsFile.readTexture[5]")
// return Texture(tex, bmp.width, bmp.height)
//}
| apache-2.0 | 20466965244dc329981770eea9c8d6e5 | 34.908397 | 109 | 0.646471 | 3.398844 | false | false | false | false |
sugnakys/UsbSerialConsole | UsbSerialConsole/app/src/main/java/jp/sugnakys/usbserialconsole/preference/SharedPreferencesExtension.kt | 1 | 5172 | package jp.sugnakys.usbserialconsole.preference
import android.annotation.SuppressLint
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Boolean Read Write Delegate
*/
fun SharedPreferences.boolean(
defaultValue: Boolean = false,
key: String? = null
): ReadWriteProperty<Any, Boolean> =
delegate(defaultValue, key, SharedPreferences::getBoolean, SharedPreferences.Editor::putBoolean)
/**
* Nullable Boolean Read Write Delegate
*/
fun SharedPreferences.nullableBoolean(key: String? = null): ReadWriteProperty<Any, Boolean?> =
nullableDelegate(
false,
key,
SharedPreferences::getBoolean,
SharedPreferences.Editor::putBoolean
)
/**
* Float Read Write Delegate
*/
fun SharedPreferences.float(
defaultValue: Float = 0f,
key: String? = null
): ReadWriteProperty<Any, Float> =
delegate(defaultValue, key, SharedPreferences::getFloat, SharedPreferences.Editor::putFloat)
/**
* Nullable Float Read Write Delegate
*/
fun SharedPreferences.nullableFloat(key: String? = null): ReadWriteProperty<Any, Float?> =
nullableDelegate(0f, key, SharedPreferences::getFloat, SharedPreferences.Editor::putFloat)
/**
* Int Read Write Delegate
*/
fun SharedPreferences.int(defaultValue: Int = 0, key: String? = null): ReadWriteProperty<Any, Int> =
delegate(defaultValue, key, SharedPreferences::getInt, SharedPreferences.Editor::putInt)
/**
* Nullable Int Read Write Delegate
*/
fun SharedPreferences.nullableInt(key: String? = null): ReadWriteProperty<Any, Int?> =
nullableDelegate(0, key, SharedPreferences::getInt, SharedPreferences.Editor::putInt)
/**
* Long Read Write Delegate
*/
fun SharedPreferences.long(
defaultValue: Long = 0,
key: String? = null
): ReadWriteProperty<Any, Long> =
delegate(defaultValue, key, SharedPreferences::getLong, SharedPreferences.Editor::putLong)
/**
* Nullable Long Read Write Delegate
*/
fun SharedPreferences.nullableLong(key: String? = null): ReadWriteProperty<Any, Long?> =
nullableDelegate(0, key, SharedPreferences::getLong, SharedPreferences.Editor::putLong)
/**
* String Read Write Delegate
*/
fun SharedPreferences.string(
defaultValue: String = "",
key: String? = null
): ReadWriteProperty<Any, String> =
delegate(defaultValue, key, SharedPreferences::getString, SharedPreferences.Editor::putString)
/**
* Nullable String Read Write Delegate
*/
fun SharedPreferences.nullableString(key: String? = null): ReadWriteProperty<Any, String?> =
nullableDelegate("", key, SharedPreferences::getString, SharedPreferences.Editor::putString)
/**
* Enum Read Write Delegate
*/
fun <T : Enum<T>> SharedPreferences.enum(
valueOf: (String) -> T,
defaultValue: Lazy<T>,
key: String? = null
) =
object : ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>): T {
return getString(key ?: property.name, null)?.let { valueOf(it) } ?: defaultValue.value
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
edit().putString(key ?: property.name, value.name).apply()
}
}
/**
* Nullable Enum Read Write Delegate
*/
fun <T : Enum<T>> SharedPreferences.nullableEnum(valueOf: (String) -> T, key: String? = null) =
object : ReadWriteProperty<Any, T?> {
override fun getValue(thisRef: Any, property: KProperty<*>): T? {
return getString(key ?: property.name, null)?.let { valueOf(it) }
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) {
edit().putString(key ?: property.name, value?.name).apply()
}
}
private inline fun <T : Any> SharedPreferences.delegate(
defaultValue: T, key: String?,
crossinline getter: SharedPreferences.(key: String, defaultValue: T) -> T?,
crossinline setter: SharedPreferences.Editor.(key: String, value: T) -> SharedPreferences.Editor
) = object : ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>) =
getter(key ?: property.name, defaultValue) ?: defaultValue
@SuppressLint("CommitPrefEdits")
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) =
edit().setter(key ?: property.name, value).apply()
}
private inline fun <T : Any> SharedPreferences.nullableDelegate(
dummy: T, key: String?,
crossinline getter: SharedPreferences.(key: String, defaultValue: T) -> T?,
crossinline setter: SharedPreferences.Editor.(key: String, value: T) -> SharedPreferences.Editor
) = object : ReadWriteProperty<Any, T?> {
override fun getValue(thisRef: Any, property: KProperty<*>): T? {
val target = key ?: property.name
return if (contains(target)) getter(target, dummy) else null
}
@SuppressLint("CommitPrefEdits")
override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) {
val target = key ?: property.name
if (value == null) {
edit().remove(target).apply()
} else {
edit().setter(target, value).apply()
}
}
} | mit | ef7314dec8f7e066952edbbf0bc25310 | 33.718121 | 100 | 0.689482 | 4.431877 | false | false | false | false |
simia-tech/epd-kotlin | src/main/kotlin/com/anyaku/epd/structure/v1/UnlockedMapper.kt | 1 | 2693 | package com.anyaku.epd.structure.v1
import com.anyaku.crypt.coder.decode
import com.anyaku.crypt.coder.encode
import com.anyaku.crypt.symmetric.Key
import com.anyaku.epd.structure.Factory as FactoryBase
import com.anyaku.epd.structure.UnlockedKeysMap
import com.anyaku.epd.structure.UnlockedSection as UnlockedSectionBase
import com.anyaku.epd.structure.UnlockedModulesMap
import com.anyaku.epd.structure.UnlockedContactsMap
import com.anyaku.epd.structure.UnlockedMapper as UnlockedMapperTrait
import com.anyaku.epd.structure.modules.Basic
import java.util.HashMap
class UnlockedMapper(private val factory: FactoryBase) : UnlockedMapperTrait {
override fun keysToMap(keys: UnlockedKeysMap): Map<String, Any?> {
val result = HashMap<String, Any?>()
for (entry in keys.entrySet())
result[ entry.key ] = encode(entry.value)
return result
}
override fun keysFromMap(map: Map<String, Any?>): UnlockedKeysMap {
val result = UnlockedKeysMap(factory)
for (entry in map.entrySet())
result[entry.key] = decode(entry.value as String) as Key
return result
}
override fun sectionToMap(unlockedSection: UnlockedSectionBase): Map<String, Any?> {
val result = HashMap<String, Any?>()
if (unlockedSection.title != null)
result["title"] = unlockedSection.title
result["modules"] = modulesToMap(unlockedSection.modules)
return result
}
[ suppress("UNCHECKED_CAST") ]
override fun sectionFromMap(
id: String, map: Map<String, Any?>,
contacts: UnlockedContactsMap?
): UnlockedSectionBase {
val result = UnlockedSectionBase(id, map["title"] as String?, contacts, factory)
result.modules.setAll(modulesFromMap(map["modules"] as Map<String, Any?>))
return result
}
[ suppress("UNCHECKED_CAST") ]
fun modulesFromMap(map: Map<String, Any?>): UnlockedModulesMap {
val result = UnlockedModulesMap(factory)
for (entry in map.entrySet()) {
val moduleMap = entry.value as Map<String, Any?>
val moduleContentMap = moduleMap["content"] as Map<String, Any?>
result[ entry.key ] = factory.buildModule(entry.key, moduleContentMap)
}
return result
}
fun modulesToMap(unlockedModulesMap: UnlockedModulesMap): Map<String, Any?> {
val result = HashMap<String, Any?>()
for (entry in unlockedModulesMap.entrySet()) {
val moduleMap = HashMap<String, Any?>()
moduleMap["content"] = entry.value.toMap()
result[ entry.key ] = moduleMap
}
return result
}
}
| lgpl-3.0 | ac2067f55b584b8afd33a161ed9924a4 | 31.445783 | 88 | 0.670628 | 4.315705 | false | false | false | false |
ejeinc/VR-MultiView-UDP | player/src/main/java/com/eje_c/player/ExoPlayerImpl.kt | 1 | 4075 | package com.eje_c.player
import android.content.Context
import android.graphics.SurfaceTexture
import android.net.Uri
import android.view.Surface
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.PlaybackParameters
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.Timeline
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.TrackGroupArray
import com.google.android.exoplayer2.trackselection.TrackSelectionArray
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import com.google.android.exoplayer2.video.VideoListener
class ExoPlayerImpl(
private val context: Context,
private val exoPlayer: SimpleExoPlayer) : Player, com.google.android.exoplayer2.Player.EventListener, VideoListener {
private val userAgent = Util.getUserAgent(context, context.applicationInfo.name)
private val dataSourceFactory = DefaultDataSourceFactory(context, userAgent)
private val mediaSourceFactory = ExtractorMediaSource.Factory(dataSourceFactory)
private var surface: Surface? = null
private var _videoWidth: Int = 0
private var _videoHeight: Int = 0
init {
// Register event listeners
exoPlayer.addVideoListener(this)
exoPlayer.addListener(this)
}
override val duration: Long
get() = exoPlayer.duration
override var currentPosition: Long
set(value) = exoPlayer.seekTo(value)
get() = exoPlayer.currentPosition
override val isPlaying: Boolean
get() = exoPlayer.playWhenReady && exoPlayer.playbackState != com.google.android.exoplayer2.Player.STATE_ENDED
override var volume: Float
get() = exoPlayer.volume
set(value) {
exoPlayer.volume = value
}
override var onRenderFirstFrame: (() -> Unit)? = null
override var onCompletion: (() -> Unit)? = null
override val videoWidth: Int
get() = _videoWidth
override val videoHeight: Int
get() = _videoHeight
override fun pause() {
exoPlayer.playWhenReady = false
}
override fun start() {
exoPlayer.playWhenReady = true
}
override fun stop() = exoPlayer.stop()
override fun load(uri: Uri) {
val mediaSource = mediaSourceFactory.createMediaSource(uri)
exoPlayer.prepare(mediaSource)
}
override fun release() {
surface?.release()
exoPlayer.release()
}
override fun setOutput(surfaceTexture: SurfaceTexture) {
surface?.release()
surface = Surface(surfaceTexture)
exoPlayer.setVideoSurface(surface)
}
override fun setOutput(surface: Surface) {
this.surface?.release()
this.surface = surface
exoPlayer.setVideoSurface(surface)
}
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
when (playbackState) {
com.google.android.exoplayer2.Player.STATE_ENDED -> onCompletion?.invoke()
}
}
override fun onRenderedFirstFrame() {
onRenderFirstFrame?.invoke()
}
override fun onVideoSizeChanged(width: Int, height: Int, unappliedRotationDegrees: Int, pixelWidthHeightRatio: Float) {
_videoWidth = width
_videoHeight = height
}
/*
* No-op events.
*/
override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters?) {}
override fun onTracksChanged(trackGroups: TrackGroupArray?, trackSelections: TrackSelectionArray?) {}
override fun onPlayerError(error: ExoPlaybackException?) {}
override fun onLoadingChanged(isLoading: Boolean) {}
override fun onPositionDiscontinuity(reason: Int) {}
override fun onRepeatModeChanged(repeatMode: Int) {}
override fun onTimelineChanged(timeline: Timeline?, manifest: Any?, reason: Int) {}
override fun onSeekProcessed() {}
override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) {}
} | apache-2.0 | ef4c2ecc1d953489f1e679ffff4ccc44 | 32.68595 | 125 | 0.715828 | 4.933414 | false | false | false | false |
Nunnery/MythicDrops | src/test/kotlin/io/pixeloutlaw/minecraft/spigot/mythicdrops/DoublesKtTest.kt | 1 | 2271 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2020 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.pixeloutlaw.minecraft.spigot.mythicdrops
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
internal class DoublesKtTest {
@Test
fun `does isZero return true for 0`() {
// given
val toTest = 0.toDouble()
// when
val result = toTest.isZero()
// then
assertThat(result).isTrue()
}
@Test
fun `does isZero return true for very very very close to 0`() {
// given
val toTest = 0.0000000007
// when
val result = toTest.isZero()
// then
assertThat(result).isTrue()
}
@Test
fun `does isZero return false for not very close to 0`() {
// given
val toTest = 0.0005
// when
val result = toTest.isZero()
// then
assertThat(result).isFalse()
}
@Test
fun `does isZero return false for 1`() {
// given
val toTest = 1.toDouble()
// when
val result = toTest.isZero()
// then
assertThat(result).isFalse()
}
}
| mit | 9f79798d6317f91e24904f4dbe072bdb | 29.28 | 105 | 0.662263 | 4.532934 | false | true | false | false |
AndroidX/androidx | compose/ui/ui-graphics/src/androidMain/kotlin/androidx/compose/ui/graphics/AndroidCanvas.android.kt | 3 | 13161 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.graphics
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.util.fastForEach
actual typealias NativeCanvas = android.graphics.Canvas
/**
* Create a new Canvas instance that targets its drawing commands
* to the provided [ImageBitmap]
*/
internal actual fun ActualCanvas(image: ImageBitmap): Canvas =
AndroidCanvas().apply {
internalCanvas = android.graphics.Canvas(image.asAndroidBitmap())
}
fun Canvas(c: android.graphics.Canvas): Canvas =
AndroidCanvas().apply { internalCanvas = c }
/**
* Holder class that is used to issue scoped calls to a [Canvas] from the framework
* equivalent canvas without having to allocate an object on each draw call
*/
class CanvasHolder {
@PublishedApi internal val androidCanvas = AndroidCanvas()
inline fun drawInto(targetCanvas: android.graphics.Canvas, block: Canvas.() -> Unit) {
val previousCanvas = androidCanvas.internalCanvas
androidCanvas.internalCanvas = targetCanvas
androidCanvas.block()
androidCanvas.internalCanvas = previousCanvas
}
}
/**
* Return an instance of the native primitive that implements the Canvas interface
*/
actual val Canvas.nativeCanvas: NativeCanvas
get() = (this as AndroidCanvas).internalCanvas
// Stub canvas instance used to keep the internal canvas parameter non-null during its
// scoped usage and prevent unnecessary byte code null checks from being generated
private val EmptyCanvas = android.graphics.Canvas()
@PublishedApi internal class AndroidCanvas() : Canvas {
// Keep the internal canvas as a var prevent having to allocate an AndroidCanvas
// instance on each draw call
@PublishedApi internal var internalCanvas: NativeCanvas = EmptyCanvas
private val srcRect = android.graphics.Rect()
private val dstRect = android.graphics.Rect()
/**
* @see Canvas.save
*/
override fun save() {
internalCanvas.save()
}
/**
* @see Canvas.restore
*/
override fun restore() {
internalCanvas.restore()
}
/**
* @see Canvas.saveLayer
*/
@SuppressWarnings("deprecation")
override fun saveLayer(bounds: Rect, paint: Paint) {
@Suppress("DEPRECATION")
internalCanvas.saveLayer(
bounds.left,
bounds.top,
bounds.right,
bounds.bottom,
paint.asFrameworkPaint(),
android.graphics.Canvas.ALL_SAVE_FLAG
)
}
/**
* @see Canvas.translate
*/
override fun translate(dx: Float, dy: Float) {
internalCanvas.translate(dx, dy)
}
/**
* @see Canvas.scale
*/
override fun scale(sx: Float, sy: Float) {
internalCanvas.scale(sx, sy)
}
/**
* @see Canvas.rotate
*/
override fun rotate(degrees: Float) {
internalCanvas.rotate(degrees)
}
/**
* @see Canvas.skew
*/
override fun skew(sx: Float, sy: Float) {
internalCanvas.skew(sx, sy)
}
/**
* @throws IllegalStateException if an arbitrary transform is provided
*/
override fun concat(matrix: Matrix) {
if (!matrix.isIdentity()) {
val frameworkMatrix = android.graphics.Matrix()
frameworkMatrix.setFrom(matrix)
internalCanvas.concat(frameworkMatrix)
}
}
@SuppressWarnings("deprecation")
override fun clipRect(left: Float, top: Float, right: Float, bottom: Float, clipOp: ClipOp) {
@Suppress("DEPRECATION")
internalCanvas.clipRect(left, top, right, bottom, clipOp.toRegionOp())
}
/**
* @see Canvas.clipPath
*/
override fun clipPath(path: Path, clipOp: ClipOp) {
@Suppress("DEPRECATION")
internalCanvas.clipPath(path.asAndroidPath(), clipOp.toRegionOp())
}
fun ClipOp.toRegionOp(): android.graphics.Region.Op =
when (this) {
ClipOp.Difference -> android.graphics.Region.Op.DIFFERENCE
else -> android.graphics.Region.Op.INTERSECT
}
/**
* @see Canvas.drawLine
*/
override fun drawLine(p1: Offset, p2: Offset, paint: Paint) {
internalCanvas.drawLine(
p1.x,
p1.y,
p2.x,
p2.y,
paint.asFrameworkPaint()
)
}
override fun drawRect(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) {
internalCanvas.drawRect(left, top, right, bottom, paint.asFrameworkPaint())
}
override fun drawRoundRect(
left: Float,
top: Float,
right: Float,
bottom: Float,
radiusX: Float,
radiusY: Float,
paint: Paint
) {
internalCanvas.drawRoundRect(
left,
top,
right,
bottom,
radiusX,
radiusY,
paint.asFrameworkPaint()
)
}
override fun drawOval(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) {
internalCanvas.drawOval(left, top, right, bottom, paint.asFrameworkPaint())
}
/**
* @see Canvas.drawCircle
*/
override fun drawCircle(center: Offset, radius: Float, paint: Paint) {
internalCanvas.drawCircle(
center.x,
center.y,
radius,
paint.asFrameworkPaint()
)
}
override fun drawArc(
left: Float,
top: Float,
right: Float,
bottom: Float,
startAngle: Float,
sweepAngle: Float,
useCenter: Boolean,
paint: Paint
) {
internalCanvas.drawArc(
left,
top,
right,
bottom,
startAngle,
sweepAngle,
useCenter,
paint.asFrameworkPaint()
)
}
/**
* @see Canvas.drawPath
*/
override fun drawPath(path: Path, paint: Paint) {
internalCanvas.drawPath(path.asAndroidPath(), paint.asFrameworkPaint())
}
/**
* @see Canvas.drawImage
*/
override fun drawImage(image: ImageBitmap, topLeftOffset: Offset, paint: Paint) {
internalCanvas.drawBitmap(
image.asAndroidBitmap(),
topLeftOffset.x,
topLeftOffset.y,
paint.asFrameworkPaint()
)
}
/**
* @See Canvas.drawImageRect
*/
override fun drawImageRect(
image: ImageBitmap,
srcOffset: IntOffset,
srcSize: IntSize,
dstOffset: IntOffset,
dstSize: IntSize,
paint: Paint
) {
// There is no framework API to draw a subset of a target bitmap
// that consumes only primitives so lazily allocate a src and dst
// rect to populate the dimensions and re-use across calls
internalCanvas.drawBitmap(
image.asAndroidBitmap(),
srcRect.apply {
left = srcOffset.x
top = srcOffset.y
right = srcOffset.x + srcSize.width
bottom = srcOffset.y + srcSize.height
},
dstRect.apply {
left = dstOffset.x
top = dstOffset.y
right = dstOffset.x + dstSize.width
bottom = dstOffset.y + dstSize.height
},
paint.asFrameworkPaint()
)
}
/**
* @see Canvas.drawPoints
*/
override fun drawPoints(pointMode: PointMode, points: List<Offset>, paint: Paint) {
when (pointMode) {
// Draw a line between each pair of points, each point has at most one line
// If the number of points is odd, then the last point is ignored.
PointMode.Lines -> drawLines(points, paint, 2)
// Connect each adjacent point with a line
PointMode.Polygon -> drawLines(points, paint, 1)
// Draw a point at each provided coordinate
PointMode.Points -> drawPoints(points, paint)
}
}
override fun enableZ() {
CanvasUtils.enableZ(internalCanvas, true)
}
override fun disableZ() {
CanvasUtils.enableZ(internalCanvas, false)
}
private fun drawPoints(points: List<Offset>, paint: Paint) {
points.fastForEach { point ->
internalCanvas.drawPoint(
point.x,
point.y,
paint.asFrameworkPaint()
)
}
}
/**
* Draw lines connecting points based on the corresponding step.
*
* ex. 3 points with a step of 1 would draw 2 lines between the first and second points
* and another between the second and third
*
* ex. 4 points with a step of 2 would draw 2 lines between the first and second and another
* between the third and fourth. If there is an odd number of points, the last point is
* ignored
*
* @see drawRawLines
*/
private fun drawLines(points: List<Offset>, paint: Paint, stepBy: Int) {
if (points.size >= 2) {
for (i in 0 until points.size - 1 step stepBy) {
val p1 = points[i]
val p2 = points[i + 1]
internalCanvas.drawLine(
p1.x,
p1.y,
p2.x,
p2.y,
paint.asFrameworkPaint()
)
}
}
}
/**
* @throws IllegalArgumentException if a non even number of points is provided
*/
override fun drawRawPoints(pointMode: PointMode, points: FloatArray, paint: Paint) {
if (points.size % 2 != 0) {
throw IllegalArgumentException("points must have an even number of values")
}
when (pointMode) {
PointMode.Lines -> drawRawLines(points, paint, 2)
PointMode.Polygon -> drawRawLines(points, paint, 1)
PointMode.Points -> drawRawPoints(points, paint, 2)
}
}
private fun drawRawPoints(points: FloatArray, paint: Paint, stepBy: Int) {
if (points.size % 2 == 0) {
for (i in 0 until points.size - 1 step stepBy) {
val x = points[i]
val y = points[i + 1]
internalCanvas.drawPoint(x, y, paint.asFrameworkPaint())
}
}
}
/**
* Draw lines connecting points based on the corresponding step. The points are interpreted
* as x, y coordinate pairs in alternating index positions
*
* ex. 3 points with a step of 1 would draw 2 lines between the first and second points
* and another between the second and third
*
* ex. 4 points with a step of 2 would draw 2 lines between the first and second and another
* between the third and fourth. If there is an odd number of points, the last point is
* ignored
*
* @see drawLines
*/
private fun drawRawLines(points: FloatArray, paint: Paint, stepBy: Int) {
// Float array is treated as alternative set of x and y coordinates
// x1, y1, x2, y2, x3, y3, ... etc.
if (points.size >= 4 && points.size % 2 == 0) {
for (i in 0 until points.size - 3 step stepBy * 2) {
val x1 = points[i]
val y1 = points[i + 1]
val x2 = points[i + 2]
val y2 = points[i + 3]
internalCanvas.drawLine(
x1,
y1,
x2,
y2,
paint.asFrameworkPaint()
)
}
}
}
override fun drawVertices(vertices: Vertices, blendMode: BlendMode, paint: Paint) {
// TODO(njawad) align drawVertices blendMode parameter usage with framework
// android.graphics.Canvas#drawVertices does not consume a blendmode argument
internalCanvas.drawVertices(
vertices.vertexMode.toAndroidVertexMode(),
vertices.positions.size,
vertices.positions,
0, // TODO(njawad) figure out proper vertOffset)
vertices.textureCoordinates,
0, // TODO(njawad) figure out proper texOffset)
vertices.colors,
0, // TODO(njawad) figure out proper colorOffset)
vertices.indices,
0, // TODO(njawad) figure out proper indexOffset)
vertices.indices.size,
paint.asFrameworkPaint()
)
}
}
| apache-2.0 | 88e2b63ec5a85b5026d8391abd5deb7e | 29.822014 | 97 | 0.588785 | 4.663714 | false | false | false | false |
nrizzio/Signal-Android | core-util/src/main/java/org/signal/core/util/CursorExtensions.kt | 1 | 2675 | package org.signal.core.util
import android.database.Cursor
import java.util.Optional
fun Cursor.requireString(column: String): String? {
return CursorUtil.requireString(this, column)
}
fun Cursor.requireNonNullString(column: String): String {
return CursorUtil.requireString(this, column)!!
}
fun Cursor.optionalString(column: String): Optional<String> {
return CursorUtil.getString(this, column)
}
fun Cursor.requireInt(column: String): Int {
return CursorUtil.requireInt(this, column)
}
fun Cursor.optionalInt(column: String): Optional<Int> {
return CursorUtil.getInt(this, column)
}
fun Cursor.requireFloat(column: String): Float {
return CursorUtil.requireFloat(this, column)
}
fun Cursor.requireLong(column: String): Long {
return CursorUtil.requireLong(this, column)
}
fun Cursor.optionalLong(column: String): Optional<Long> {
return CursorUtil.getLong(this, column)
}
fun Cursor.requireBoolean(column: String): Boolean {
return CursorUtil.requireInt(this, column) != 0
}
fun Cursor.optionalBoolean(column: String): Optional<Boolean> {
return CursorUtil.getBoolean(this, column)
}
fun Cursor.requireBlob(column: String): ByteArray? {
return CursorUtil.requireBlob(this, column)
}
fun Cursor.requireNonNullBlob(column: String): ByteArray {
return CursorUtil.requireBlob(this, column)!!
}
fun Cursor.optionalBlob(column: String): Optional<ByteArray> {
return CursorUtil.getBlob(this, column)
}
fun Cursor.isNull(column: String): Boolean {
return CursorUtil.isNull(this, column)
}
fun <T> Cursor.requireObject(column: String, serializer: LongSerializer<T>): T {
return serializer.deserialize(CursorUtil.requireLong(this, column))
}
fun <T> Cursor.requireObject(column: String, serializer: StringSerializer<T>): T {
return serializer.deserialize(CursorUtil.requireString(this, column))
}
@JvmOverloads
fun Cursor.readToSingleLong(defaultValue: Long = 0): Long {
return use {
if (it.moveToFirst()) {
it.getLong(0)
} else {
defaultValue
}
}
}
@JvmOverloads
inline fun <T> Cursor.readToList(predicate: (T) -> Boolean = { true }, mapper: (Cursor) -> T): List<T> {
val list = mutableListOf<T>()
use {
while (moveToNext()) {
val record = mapper(this)
if (predicate(record)) {
list += mapper(this)
}
}
}
return list
}
inline fun <T> Cursor.readToSet(predicate: (T) -> Boolean = { true }, mapper: (Cursor) -> T): Set<T> {
val set = mutableSetOf<T>()
use {
while (moveToNext()) {
val record = mapper(this)
if (predicate(record)) {
set += mapper(this)
}
}
}
return set
}
fun Boolean.toInt(): Int = if (this) 1 else 0
| gpl-3.0 | b7c883698b7ac13858d3ca73de5d1ca4 | 23.768519 | 104 | 0.705047 | 3.66941 | false | false | false | false |
InsanusMokrassar/IObjectK | src/main/kotlin/com/github/insanusmokrassar/IObjectK/realisations/SimpleCommonIObject.kt | 1 | 2017 | package com.github.insanusmokrassar.IObjectK.realisations
import com.github.insanusmokrassar.IObjectK.exceptions.ReadException
import com.github.insanusmokrassar.IObjectK.exceptions.WriteException
import com.github.insanusmokrassar.IObjectK.extensions.toJsonString
import com.github.insanusmokrassar.IObjectK.interfaces.CommonIObject
import com.github.insanusmokrassar.IObjectK.interfaces.IInputObject
import java.util.*
open class SimpleCommonIObject <K, V> : CommonIObject<K, V> {
protected val objects: MutableMap<K, V>
override val size: Int
get() = objects.size
constructor(from: Map<K, V>) {
objects = HashMap(from)
}
constructor(from: IInputObject<K, V>) : this() {
for (key in from.keys()) {
objects[key] = from[key]
}
}
constructor() {
objects = HashMap()
}
@Throws(WriteException::class)
override fun set(key: K, value: V) {
value ?.let {
objects[key] = it
} ?: objects.remove(key)
}
@Throws(WriteException::class)
override fun putAll(toPutMap: Map<K, V>) {
try {
toPutMap.forEach {
set(it.key, it.value)
}
} catch (e: Exception) {
throw ReadException("Can't return value - value from key - is null", e)
}
}
@Throws(ReadException::class)
override fun <T : V> get(key: K): T {
val toReturn = objects[key] ?: throw ReadException("Can't return value - value from key($key) - is null")
try {
return toReturn as T
} catch (e: Exception) {
throw ReadException("Can't return value - value from key($key) - is null", e)
}
}
@Throws(WriteException::class)
override fun remove(key: K) {
if (objects.remove(key) == null) {
throw WriteException("Can't remove value for key($key)")
}
}
override fun keys(): Set<K> = objects.keys
override fun toString(): String = toJsonString()
}
| mit | 0d57e062caca0c27c0ca7e832fb6eb73 | 28.661765 | 113 | 0.614774 | 4.05835 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | widgets/src/main/kotlin/com/commonsense/android/kotlin/views/datastructures/UpdateVariable.kt | 1 | 1301 | @file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.views.datastructures
import com.commonsense.android.kotlin.base.*
import com.commonsense.android.kotlin.base.extensions.collections.*
/**
* Created by Kasper Tvede on 13-06-2017.
*/
/**
* Represents an updateable variable for use in a custom view or custom view component
* @param T the type of the variable
* @property onUpdated Function0<Unit> the function to call when the value changes
* @property innerVariable T the real value
* @property value T the accessor for the inner variable, also calling the onUpdated callback
*/
class UpdateVariable<T>(initialValue: T,
private val onUpdated: EmptyFunction) {
/**
* the real hidden variable
*/
private var innerVariable = initialValue
/**
* The value
*/
var value: T
get() = innerVariable
set(value) {
val didChange = (innerVariable != value)
innerVariable = value
didChange.onTrue(onUpdated)
}
/**
* Does not call the onUpdated callback
*
* @param value T the new value to set the inner variable to
*/
fun setWithNoUpdate(value: T) {
innerVariable = value
}
} | mit | 0a0e04bf758ced7ad06cdcbb51d94a3c | 27.933333 | 93 | 0.662567 | 4.564912 | false | false | false | false |
inorichi/tachiyomi-extensions | src/id/bacakomik/src/eu/kanade/tachiyomi/extension/id/bacakomik/Bacakomik.kt | 1 | 12746 | package eu.kanade.tachiyomi.extension.id.bacakomik
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
class Bacakomik : ParsedHttpSource() {
override val name = "Bacakomik"
override val baseUrl = "https://bacakomik.co"
override val lang = "id"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
private val dateFormat: SimpleDateFormat = SimpleDateFormat("MMM d, yyyy", Locale.US)
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/daftar-manga/page/$page/?order=popular", headers)
}
override fun latestUpdatesRequest(page: Int): Request {
return GET("$baseUrl/daftar-manga/page/$page/?order=update", headers)
}
override fun popularMangaSelector() = "div.animepost"
override fun latestUpdatesSelector() = popularMangaSelector()
override fun searchMangaSelector() = popularMangaSelector()
override fun popularMangaFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun latestUpdatesFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun popularMangaNextPageSelector() = "a.next.page-numbers"
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
override fun searchMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.thumbnail_url = element.select("div.limit img").attr("src")
element.select("div.animposx > a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.attr("title")
}
return manga
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val builtUrl = if (page == 1) "$baseUrl/daftar-manga/" else "$baseUrl/daftar-manga/page/$page/?order="
val url = builtUrl.toHttpUrlOrNull()!!.newBuilder()
url.addQueryParameter("title", query)
url.addQueryParameter("page", page.toString())
filters.forEach { filter ->
when (filter) {
is AuthorFilter -> {
url.addQueryParameter("author", filter.state)
}
is YearFilter -> {
url.addQueryParameter("yearx", filter.state)
}
is StatusFilter -> {
val status = when (filter.state) {
Filter.TriState.STATE_INCLUDE -> "completed"
Filter.TriState.STATE_EXCLUDE -> "ongoing"
else -> ""
}
url.addQueryParameter("status", status)
}
is TypeFilter -> {
url.addQueryParameter("type", filter.toUriPart())
}
is SortByFilter -> {
url.addQueryParameter("order", filter.toUriPart())
}
is GenreListFilter -> {
filter.state
.filter { it.state != Filter.TriState.STATE_IGNORE }
.forEach { url.addQueryParameter("genre[]", it.id) }
}
}
}
return GET(url.build().toString(), headers)
}
override fun mangaDetailsParse(document: Document): SManga {
val infoElement = document.select("div.infoanime").first()
val descElement = document.select("div.desc > .entry-content.entry-content-single").first()
val sepName = infoElement.select(".infox > .spe > span:nth-child(2)").last()
val manga = SManga.create()
// need authorCleaner to take "pengarang:" string to remove it from author
val authorCleaner = document.select(".infox .spe b:contains(Pengarang)").text()
manga.author = document.select(".infox .spe span:contains(Pengarang)").text().substringAfter(authorCleaner)
manga.artist = manga.author
val genres = mutableListOf<String>()
infoElement.select(".infox > .genre-info > a").forEach { element ->
val genre = element.text()
genres.add(genre)
}
manga.genre = genres.joinToString(", ")
manga.status = parseStatus(infoElement.select(".infox > .spe > span:nth-child(1)").text())
manga.description = descElement.select("p").text()
manga.thumbnail_url = document.select(".thumb > img:nth-child(1)").attr("src")
return manga
}
private fun parseStatus(element: String): Int = when {
element.toLowerCase().contains("berjalan") -> SManga.ONGOING
element.toLowerCase().contains("tamat") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "#chapter_list li"
override fun chapterFromElement(element: Element): SChapter {
val urlElement = element.select(".lchx a").first()
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = urlElement.text()
chapter.date_upload = element.select(".dt a").first()?.text()?.let { parseChapterDate(it) } ?: 0
return chapter
}
fun parseChapterDate(date: String): Long {
return if (date.contains("yang lalu")) {
val value = date.split(' ')[0].toInt()
when {
"detik" in date -> Calendar.getInstance().apply {
add(Calendar.SECOND, value * -1)
}.timeInMillis
"menit" in date -> Calendar.getInstance().apply {
add(Calendar.MINUTE, value * -1)
}.timeInMillis
"jam" in date -> Calendar.getInstance().apply {
add(Calendar.HOUR_OF_DAY, value * -1)
}.timeInMillis
"hari" in date -> Calendar.getInstance().apply {
add(Calendar.DATE, value * -1)
}.timeInMillis
"minggu" in date -> Calendar.getInstance().apply {
add(Calendar.DATE, value * 7 * -1)
}.timeInMillis
"bulan" in date -> Calendar.getInstance().apply {
add(Calendar.MONTH, value * -1)
}.timeInMillis
"tahun" in date -> Calendar.getInstance().apply {
add(Calendar.YEAR, value * -1)
}.timeInMillis
else -> {
0L
}
}
} else {
try {
dateFormat.parse(date)?.time ?: 0
} catch (_: Exception) {
0L
}
}
}
override fun prepareNewChapter(chapter: SChapter, manga: SManga) {
val basic = Regex("""Chapter\s([0-9]+)""")
when {
basic.containsMatchIn(chapter.name) -> {
basic.find(chapter.name)?.let {
chapter.chapter_number = it.groups[1]?.value!!.toFloat()
}
}
}
}
override fun pageListParse(document: Document): List<Page> {
val pages = mutableListOf<Page>()
var i = 0
document.select("div.imgch-auh img").forEach { element ->
val url = element.attr("src")
i++
if (url.isNotEmpty()) {
pages.add(Page(i, "", url))
}
}
return pages
}
override fun imageUrlParse(document: Document) = ""
override fun imageRequest(page: Page): Request {
if (page.imageUrl!!.contains("i2.wp.com")) {
val headers = Headers.Builder()
headers.apply {
add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
}
return GET(page.imageUrl!!, headers.build())
} else {
val imgHeader = Headers.Builder().apply {
add("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.1.1; en-gb; Build/KLP) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30")
add("Referer", baseUrl)
}.build()
return GET(page.imageUrl!!, imgHeader)
}
}
private class AuthorFilter : Filter.Text("Author")
private class YearFilter : Filter.Text("Year")
private class TypeFilter : UriPartFilter(
"Type",
arrayOf(
Pair("Default", ""),
Pair("Manga", "Manga"),
Pair("Manhwa", "Manhwa"),
Pair("Manhua", "Manhua"),
Pair("Comic", "Comic")
)
)
private class SortByFilter : UriPartFilter(
"Sort By",
arrayOf(
Pair("Default", ""),
Pair("A-Z", "title"),
Pair("Z-A", "titlereverse"),
Pair("Latest Update", "update"),
Pair("Latest Added", "latest"),
Pair("Popular", "popular")
)
)
private class StatusFilter : UriPartFilter(
"Status",
arrayOf(
Pair("All", ""),
Pair("Ongoing", "ongoing"),
Pair("Completed", "completed")
)
)
private class Genre(name: String, val id: String = name) : Filter.TriState(name)
private class GenreListFilter(genres: List<Genre>) : Filter.Group<Genre>("Genre", genres)
override fun getFilterList() = FilterList(
Filter.Header("NOTE: Ignored if using text search!"),
Filter.Separator(),
AuthorFilter(),
YearFilter(),
StatusFilter(),
TypeFilter(),
SortByFilter(),
GenreListFilter(getGenreList())
)
private fun getGenreList() = listOf(
Genre("4-Koma", "4-koma"),
Genre("4-Koma. Comedy", "4-koma-comedy"),
Genre("Action", "action"),
Genre("Action. Adventure", "action-adventure"),
Genre("Adult", "adult"),
Genre("Adventure", "adventure"),
Genre("Comedy", "comedy"),
Genre("Cooking", "cooking"),
Genre("Demons", "demons"),
Genre("Doujinshi", "doujinshi"),
Genre("Drama", "drama"),
Genre("Ecchi", "ecchi"),
Genre("Echi", "echi"),
Genre("Fantasy", "fantasy"),
Genre("Game", "game"),
Genre("Gender Bender", "gender-bender"),
Genre("Gore", "gore"),
Genre("Harem", "harem"),
Genre("Historical", "historical"),
Genre("Horror", "horror"),
Genre("Isekai", "isekai"),
Genre("Josei", "josei"),
Genre("Magic", "magic"),
Genre("Manga", "manga"),
Genre("Manhua", "manhua"),
Genre("Manhwa", "manhwa"),
Genre("Martial Arts", "martial-arts"),
Genre("Mature", "mature"),
Genre("Mecha", "mecha"),
Genre("Medical", "medical"),
Genre("Military", "military"),
Genre("Music", "music"),
Genre("Mystery", "mystery"),
Genre("One Shot", "one-shot"),
Genre("Oneshot", "oneshot"),
Genre("Parody", "parody"),
Genre("Police", "police"),
Genre("Psychological", "psychological"),
Genre("Romance", "romance"),
Genre("Samurai", "samurai"),
Genre("School", "school"),
Genre("School Life", "school-life"),
Genre("Sci-fi", "sci-fi"),
Genre("Seinen", "seinen"),
Genre("Shoujo", "shoujo"),
Genre("Shoujo Ai", "shoujo-ai"),
Genre("Shounen", "shounen"),
Genre("Shounen Ai", "shounen-ai"),
Genre("Slice of Life", "slice-of-life"),
Genre("Smut", "smut"),
Genre("Sports", "sports"),
Genre("Super Power", "super-power"),
Genre("Supernatural", "supernatural"),
Genre("Thriller", "thriller"),
Genre("Tragedy", "tragedy"),
Genre("Vampire", "vampire"),
Genre("Webtoon", "webtoon"),
Genre("Webtoons", "webtoons"),
Genre("Yuri", "yuri")
)
private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) :
Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) {
fun toUriPart() = vals[state].second
}
}
| apache-2.0 | 116a3d4ae96c38fe395d530d527b5559 | 37.978593 | 157 | 0.565981 | 4.516655 | false | false | false | false |
MontpellierTechHub/ABCTestChronometer | app/src/main/java/fr/montpelliertechhub/abctestchronometer/utils/Timer.kt | 1 | 5015 | package fr.montpelliertechhub.abctestchronometer.utils;
import android.content.SharedPreferences
import android.os.SystemClock
import android.widget.Chronometer
import arrow.core.None
import arrow.core.Option
import arrow.core.Some
/**
* A timer that measure stuff
*
* Created by Hugo Gresse on 19/09/2017.
*/
private const val KEY_TIME_BASE = "TimeBase"
private const val KEY_TIME_PAUSED = "TimePaused"
private const val KEY_STATE = "ChronometerState"
class Timer(private val mChronometer: Chronometer, private val sharedPreferences: SharedPreferences) {
internal enum class ChronometerState {
Running, Paused, Stopped
}
private var isHourFormat = false
private var mTimeWhenPaused: Long = 0
private var mTimeBase: Long = 0
fun resumeState(): Option<Long> {
val state = ChronometerState.values()[sharedPreferences.getInt(KEY_STATE + mChronometer.id,
ChronometerState.Stopped.ordinal)]
return when {
state.ordinal == ChronometerState.Stopped.ordinal -> {
stopChronometer()
None
}
state.ordinal == ChronometerState.Paused.ordinal -> {
pauseStateChronometer()
None
}
else -> Some(startStateChronometer())
}
}
fun isRunning(): Boolean {
return ChronometerState.values()[sharedPreferences.getInt(KEY_STATE + mChronometer.id,
ChronometerState.Stopped.ordinal)] == ChronometerState.Running
}
fun isPaused(): Boolean {
return ChronometerState.values()[sharedPreferences.getInt(KEY_STATE + mChronometer.id,
ChronometerState.Stopped.ordinal)] == ChronometerState.Paused
}
fun pauseChronometer() {
storeState(ChronometerState.Paused)
saveTimeWhenPaused()
pauseStateChronometer()
}
fun startChronometer(): Long {
storeState(ChronometerState.Running)
saveTimeBase()
return startStateChronometer()
}
fun stopChronometer(): Long {
val elapsedTime = SystemClock.elapsedRealtime()
mChronometer.base = SystemClock.elapsedRealtime()
mChronometer.stop()
if (isHourFormat)
mChronometer.text = "00:00:00"
else
mChronometer.text = "00:00"
clearState()
return elapsedTime
}
fun hourFormat(hourFormat: Boolean) {
isHourFormat = hourFormat
if (isHourFormat) {
mChronometer.setOnChronometerTickListener { c ->
val elapsedMillis = SystemClock.elapsedRealtime() - c.base
if (elapsedMillis > 3600000L) {
c.format = "0%s"
} else {
c.format = "00:%s"
}
}
} else {
mChronometer.onChronometerTickListener = null
mChronometer.format = "%s"
}
}
private fun startStateChronometer(): Long {
mTimeBase = sharedPreferences.getLong(KEY_TIME_BASE + mChronometer.id, SystemClock.elapsedRealtime()) //0
mTimeWhenPaused = sharedPreferences.getLong(KEY_TIME_PAUSED + mChronometer.id, 0)
mChronometer.base = mTimeBase + mTimeWhenPaused
mChronometer.start()
return mTimeBase
}
private fun pauseStateChronometer() {
mTimeWhenPaused = sharedPreferences.getLong(KEY_TIME_PAUSED + mChronometer.id,
mChronometer.base - SystemClock.elapsedRealtime())
//some negative value
mChronometer.base = SystemClock.elapsedRealtime() + mTimeWhenPaused
mChronometer.stop()
if (isHourFormat) {
val text = mChronometer.text
if (text.length == 5) {
mChronometer.text = "00:" + text
} else if (text.length == 7) {
mChronometer.text = "0" + text
}
}
}
private fun clearState() {
storeState(ChronometerState.Stopped)
sharedPreferences.edit()
.remove(KEY_TIME_BASE + mChronometer.id)
.remove(KEY_TIME_PAUSED + mChronometer.id)
.apply()
mTimeWhenPaused = 0
}
private fun storeState(state: ChronometerState) {
sharedPreferences.edit().putInt(KEY_STATE + mChronometer.id, state.ordinal).apply()
}
private fun saveTimeBase() {
sharedPreferences.edit()
.putLong(KEY_TIME_BASE + mChronometer.id, SystemClock.elapsedRealtime())
.apply()
}
private fun saveTimeWhenPaused() {
sharedPreferences.edit()
.putLong(KEY_TIME_PAUSED + mChronometer.id,
mChronometer.base - SystemClock.elapsedRealtime())
.apply()
}
}
| apache-2.0 | 9f39894978dd2c5a1d211d4dc2fbe192 | 32.885135 | 128 | 0.583051 | 5.363636 | false | false | false | false |
Finnerale/ExaCalc | src/main/kotlin/de/leopoldluley/exacalc/view/CalculatorView.kt | 1 | 7570 | package de.leopoldluley.exacalc.view
import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIcon
import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIconView
import de.leopoldluley.exacalc.Calculation
import de.leopoldluley.exacalc.Store
import de.leopoldluley.exacalc.matches
import de.leopoldluley.exacalc.store
import javafx.beans.binding.Bindings
import javafx.beans.property.SimpleDoubleProperty
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.control.SelectionModel
import javafx.scene.control.TextField
import javafx.scene.control.ToggleButton
import javafx.scene.input.Clipboard
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.layout.StackPane
import javafx.scene.layout.VBox
import tornadofx.*
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
/**
* Created by leopold on 29.08.16.
*/
class CalculatorView : View() {
val navigation: NavigationView by inject()
val errorOpacityProp = SimpleDoubleProperty()
lateinit var listSelectionModel: SelectionModel<Calculation>
override val root = stackpane {
var inputField: TextField = TextField()
var toggleAdvancedButton = ToggleButton()
vbox {
spacing = 10.0
padding = Insets(10.0)
hbox {
spacing = 5.0
button {
prefWidth = 30.0
prefHeight = 30.0
graphic = MaterialDesignIconView(MaterialDesignIcon.MENU)
setOnAction { navigation.show() }
}
inputField = textfield(store.state.input) {
prefHeight = 30.0
promptText = "Input"
HBox.setHgrow(this, Priority.ALWAYS)
setOnKeyReleased { store.dispatch(Store.UInput(text)) }
store.subscribe { if (text != it.input) text = it.input }
setOnAction { calculate() }
}
stackpane {
button {
prefWidth = 30.0
prefHeight = 30.0
graphic = MaterialDesignIconView(MaterialDesignIcon.SEND)
setOnAction { calculate() }
}
region {
visibleProperty().bind(Bindings.greaterThan(opacityProperty(), 0.0))
opacityProperty().bind(errorOpacityProp)
style {
backgroundColor = MultiValue(arrayOf(c("#F00")))
backgroundRadius = MultiValue(arrayOf(box(3.0.px)))
}
}
}
}
listview<Calculation> {
VBox.setVgrow(this, Priority.ALWAYS)
setOnMouseClicked { if (it.clickCount >= 2) insertCalculation() }
setOnKeyPressed {
if (it.matches(store.state.shortcuts.copyResult))
Clipboard.getSystemClipboard().putString(selectionModel.selectedItem.result)
if (it.matches(store.state.shortcuts.copyCalculationInput))
Clipboard.getSystemClipboard().putString(selectionModel.selectedItem.input)
}
items.addAll(store.state.calculations)
scrollTo(items.size-1)
store.subscribe { items.clear(); items.addAll(it.calculations); scrollTo(items.size-1) }
listSelectionModel = selectionModel
}
hbox {
spacing = 10.0
val BW = 90.0
button {
prefWidth = BW
text = "Clear"
setOnAction { clear() }
}
button {
prefWidth = BW
text = "Remove"
setOnAction { remove() }
}
region {
HBox.setHgrow(this, Priority.ALWAYS)
}
button {
prefWidth = BW
text = "Reset"
setOnAction { engine = newEngine() }
}
toggleAdvancedButton = togglebutton {
prefWidth = BW
text = "Advanced"
}
}
}
textarea(store.state.input) {
promptText = "Input"
maxWidthProperty().bind(inputField.widthProperty())
visibleProperty().bind(Bindings.greaterThan(maxHeightProperty(), inputField.heightProperty()))
StackPane.setAlignment(this, Pos.TOP_CENTER)
setOnKeyReleased { store.dispatch(Store.UInput(text)) }
store.subscribe { if (text != it.input) text = it.input }
toggleAdvancedButton.setOnAction {
translateY = inputField.localToScene(inputField.boundsInLocal).minY
if (isVisible) {
maxHeightProperty().animate(inputField.height, 0.3.seconds)
toggleAdvancedButton.isSelected = false
} else {
maxHeight = inputField.height
maxHeightProperty().animate([email protected] - 100, 0.3.seconds)
toggleAdvancedButton.isSelected = true
}
}
}
}
var engine = newEngine()
fun calculate() {
if (errorOpacityProp.value > 0.0) return
try {
val input = modify(store.state.input)
var result = engine.eval(input)
if (result != null) {
engine.put("ans", result)
if (result.toString() == input) result = "null"
}
store.dispatch(Store.History.Add(input, result?.toString() ?: "null"))
store.dispatch(Store.UInput(""))
} catch(exception: Exception) {
exception.printStackTrace()
errorOpacityProp.animate(0.75, 0.2.seconds) { setOnFinished { errorOpacityProp.animate(0.0, 0.2.seconds) } }
}
}
fun modify(input: String): String {
var output = input
when (output[0]) {
'+', '-', '*', '/' -> output = "ans " + output
}
return output
}
fun newEngine(): ScriptEngine {
val engine = ScriptEngineManager().getEngineByExtension("js")
applyVariables(engine)
applyFunctions(engine)
return engine
}
fun applyVariables(e: ScriptEngine) {
store.state.variables.forEach {
try {
e.put(it.name, it.type.conver(it.value))
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun applyFunctions(e: ScriptEngine) {
store.state.functions.forEach {
try {
val brackets = if (it.name.endsWith(')')) "" else "()"
e.eval(
"""
function ${it.name}$brackets {
${it.body}
}
"""
)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun clear() {
store.dispatch(Store.History.Clear)
}
fun remove() {
if (listSelectionModel.selectedItem != null)
store.dispatch(Store.History.Remove(listSelectionModel.selectedItem))
}
fun insertCalculation() {
store.dispatch(Store.UInput(listSelectionModel.selectedItem.input))
}
} | gpl-3.0 | 38222d23fc14fd91e695566c3d511acc | 33.729358 | 120 | 0.534875 | 5.156676 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/grades/model/Exam.kt | 1 | 4407 | package de.tum.`in`.tumcampusapp.component.tumui.grades.model
import android.content.Context
import androidx.core.content.ContextCompat
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.api.tumonline.converters.DateTimeConverter
import de.tum.`in`.tumcampusapp.component.other.generic.adapter.SimpleStickyListHeadersAdapter
import de.tum.`in`.tumcampusapp.utils.tryOrNull
import org.joda.time.DateTime
import java.text.NumberFormat
import java.util.*
/**
* Exam passed by the user.
*
*
* Note: This model is based on the TUMOnline web service response format for a
* corresponding request.
*/
@Xml(name = "row")
data class Exam(
@PropertyElement(name = "lv_titel")
val course: String,
@PropertyElement(name = "lv_credits")
val credits: String? = null,
@PropertyElement(name = "datum", converter = DateTimeConverter::class)
val date: DateTime? = null,
@PropertyElement(name = "pruefer_nachname")
val examiner: String? = null,
@PropertyElement(name = "uninotenamekurz")
val grade: String? = null,
@PropertyElement(name = "modus")
val modus: String? = null,
@PropertyElement(name = "studienidentifikator")
val programID: String,
@PropertyElement(name = "lv_semester")
val semester: String = ""
) : Comparable<Exam>, SimpleStickyListHeadersAdapter.SimpleStickyListItem {
override fun getHeadName() = semester
override fun getHeaderId() = semester
override fun compareTo(other: Exam): Int {
return compareByDescending<Exam> { it.semester }
.thenByDescending { it.date }
.thenBy { it.course }
.compare(this, other)
}
private val gradeValue: Double?
get() = tryOrNull { NumberFormat.getInstance(Locale.GERMAN).parse(grade).toDouble() }
val isPassed: Boolean
get() {
val value = gradeValue ?: 5.0
return value <= 4.0
}
fun getGradeColor(context: Context): Int {
// While using getOrDefault() compiles, it results in a NoSuchMethodError on devices with
// API levels lower than 24.
// grade colors are assigned to grades like 1,52 as if they were a 1,5
var resId = R.color.grade_default
if (grade?.length!! > 2) {
resId = GRADE_COLORS[grade.subSequence(0, 3)] ?: R.color.grade_default
}
return ContextCompat.getColor(context, resId)
}
companion object {
private val GRADE_COLORS = mapOf(
"1,0" to R.color.grade_1_0,
"1,1" to R.color.grade_1_1,
"1,2" to R.color.grade_1_2,
"1,3" to R.color.grade_1_3,
"1,4" to R.color.grade_1_4,
"1,5" to R.color.grade_1_5,
"1,6" to R.color.grade_1_6,
"1,7" to R.color.grade_1_7,
"1,8" to R.color.grade_1_8,
"1,9" to R.color.grade_1_9,
"2,0" to R.color.grade_2_0,
"2,1" to R.color.grade_2_1,
"2,2" to R.color.grade_2_2,
"2,3" to R.color.grade_2_3,
"2,4" to R.color.grade_2_4,
"2,5" to R.color.grade_2_5,
"2,6" to R.color.grade_2_6,
"2,7" to R.color.grade_2_7,
"2,8" to R.color.grade_2_8,
"2,9" to R.color.grade_2_9,
"3,0" to R.color.grade_3_0,
"3,1" to R.color.grade_3_1,
"3,2" to R.color.grade_3_2,
"3,3" to R.color.grade_3_3,
"3,4" to R.color.grade_3_4,
"3,5" to R.color.grade_3_5,
"3,6" to R.color.grade_3_6,
"3,7" to R.color.grade_3_7,
"3,8" to R.color.grade_3_8,
"3,9" to R.color.grade_3_9,
"4,0" to R.color.grade_4_0,
"4,1" to R.color.grade_4_1,
"4,2" to R.color.grade_4_2,
"4,3" to R.color.grade_4_3,
"4,4" to R.color.grade_4_4,
"4,5" to R.color.grade_4_5,
"4,6" to R.color.grade_4_6,
"4,7" to R.color.grade_4_7,
"4,8" to R.color.grade_4_8,
"4,9" to R.color.grade_4_9,
"5,0" to R.color.grade_5_0,
)
}
} | gpl-3.0 | cf1366c9edde0995e74fba813d0d1ab7 | 36.355932 | 97 | 0.556841 | 3.301124 | false | false | false | false |
wax911/AniTrendApp | app/src/main/java/com/mxt/anitrend/adapter/recycler/detail/NotificationAdapter.kt | 1 | 9585 | package com.mxt.anitrend.adapter.recycler.detail
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.Adapter
import android.widget.Filter
import butterknife.OnClick
import butterknife.OnLongClick
import com.bumptech.glide.Glide
import com.mxt.anitrend.R
import com.mxt.anitrend.adapter.recycler.shared.UnresolvedViewHolder
import com.mxt.anitrend.base.custom.recycler.RecyclerViewAdapter
import com.mxt.anitrend.base.custom.recycler.RecyclerViewHolder
import com.mxt.anitrend.base.custom.view.image.AspectImageView
import com.mxt.anitrend.databinding.AdapterNotificationBinding
import com.mxt.anitrend.databinding.CustomRecyclerUnresolvedBinding
import com.mxt.anitrend.extension.getLayoutInflater
import com.mxt.anitrend.model.entity.anilist.Notification
import com.mxt.anitrend.model.entity.base.NotificationHistory
import com.mxt.anitrend.model.entity.base.NotificationHistory_
import com.mxt.anitrend.util.CompatUtil
import com.mxt.anitrend.util.KeyUtil
import com.mxt.anitrend.util.date.DateUtil
import io.objectbox.Box
/**
* Created by max on 2017/12/06.
* Notification adapter
*/
class NotificationAdapter(context: Context) : RecyclerViewAdapter<Notification>(context) {
private val historyBox: Box<NotificationHistory> by lazy {
presenter.database.getBoxStore(NotificationHistory::class.java)
}
override fun onCreateViewHolder(parent: ViewGroup, @KeyUtil.RecyclerViewType viewType: Int): RecyclerViewHolder<Notification> {
return when (viewType) {
KeyUtil.RECYCLER_TYPE_CONTENT ->
NotificationHolder(AdapterNotificationBinding.inflate(parent.context.getLayoutInflater(), parent, false))
else ->
UnresolvedViewHolder(CustomRecyclerUnresolvedBinding.inflate(parent.context.getLayoutInflater(), parent, false))
}
}
/**
* Return the view type of the item at `position` for the purposes
* of view recycling.
*
*
* The default implementation of this method returns 0, making the assumption of
* a single view type for the adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
*
* @param position position to query
* @return integer value identifying the type of the view needed to represent the item at
* `position`. Type codes need not be contiguous.
*/
override fun getItemViewType(position: Int): Int {
val notification = data[position]
return when (notification.user) {
null -> {
when (notification?.type) {
KeyUtil.AIRING, KeyUtil.RELATED_MEDIA_ADDITION -> KeyUtil.RECYCLER_TYPE_CONTENT
else -> KeyUtil.RECYCLER_TYPE_ERROR
}
}
else -> KeyUtil.RECYCLER_TYPE_CONTENT
}
}
/**
*
* Returns a filter that can be used to constrain data with a filtering
* pattern.
*
*
*
* This method is usually implemented by [Adapter]
* classes.
*
* @return a filter used to constrain data
*/
override fun getFilter(): Filter? {
return null
}
/**
* Default constructor which includes binding with butter knife
*
* @param binding
*/
inner class NotificationHolder(
private val binding: AdapterNotificationBinding
) : RecyclerViewHolder<Notification>(binding.root) {
/**
* Load image, text, buttons, etc. in this method from the given parameter
* <br></br>
*
* @param model Is the model at the current adapter position
*/
override fun onBindViewHolder(model: Notification) {
val notificationHistory = historyBox.query()
.equal(NotificationHistory_.id, model.id)
.build().findFirst()
if (notificationHistory != null)
binding.notificationIndicator.visibility = View.GONE
else
binding.notificationIndicator.visibility = View.VISIBLE
binding.notificationTime.text = DateUtil.getPrettyDateUnix(model.createdAt)
if (!CompatUtil.equals(model.type, KeyUtil.AIRING) && !CompatUtil.equals(model.type, KeyUtil.RELATED_MEDIA_ADDITION)) {
if (model.user != null && model.user.avatar != null)
AspectImageView.setImage(binding.notificationImg, model.user.avatar.large)
} else
AspectImageView.setImage(binding.notificationImg, model.media.coverImage.extraLarge)
when (model.type) {
KeyUtil.ACTIVITY_MESSAGE -> {
binding.notificationSubject.setText(R.string.notification_user_activity_message)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.FOLLOWING -> {
binding.notificationSubject.setText(R.string.notification_user_follow_activity)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.ACTIVITY_MENTION -> {
binding.notificationSubject.setText(R.string.notification_user_activity_mention)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.THREAD_COMMENT_MENTION -> {
binding.notificationSubject.setText(R.string.notification_user_comment_forum)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.THREAD_SUBSCRIBED -> {
binding.notificationSubject.setText(R.string.notification_user_comment_forum)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.THREAD_COMMENT_REPLY -> {
binding.notificationSubject.setText(R.string.notification_user_comment_forum)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.AIRING -> {
binding.notificationSubject.setText(R.string.notification_series)
binding.notificationHeader.text = model.media.title.userPreferred
binding.notificationContent.text = context.getString(R.string.notification_episode,
model.episode.toString(), model.media.title.userPreferred)
}
KeyUtil.ACTIVITY_LIKE -> {
binding.notificationSubject.setText(R.string.notification_user_like_activity)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.ACTIVITY_REPLY, KeyUtil.ACTIVITY_REPLY_SUBSCRIBED -> {
binding.notificationSubject.setText(R.string.notification_user_reply_activity)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.ACTIVITY_REPLY_LIKE -> {
binding.notificationSubject.setText(R.string.notification_user_like_reply)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.THREAD_LIKE -> {
binding.notificationSubject.setText(R.string.notification_user_like_activity)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.THREAD_COMMENT_LIKE -> {
binding.notificationSubject.setText(R.string.notification_user_like_comment)
binding.notificationHeader.text = model.user.name
binding.notificationContent.text = model.context
}
KeyUtil.RELATED_MEDIA_ADDITION -> {
binding.notificationSubject.setText(R.string.notification_media_added)
binding.notificationHeader.text = model.media.title.userPreferred
binding.notificationContent.text = model.context
}
}
binding.executePendingBindings()
}
/**
* If any image views are used within the view holder, clear any pending async img requests
* by using Glide.clear(ImageView) or Glide.with(context).clear(view) if using Glide v4.0
* <br></br>
*
* @see Glide
*/
override fun onViewRecycled() {
Glide.with(context).clear(binding.notificationImg)
binding.unbind()
}
@OnClick(R.id.container, R.id.notification_img)
override fun onClick(v: View) {
performClick(clickListener, data, v)
}
@OnLongClick(R.id.container)
override fun onLongClick(v: View): Boolean {
return performLongClick(clickListener, data, v)
}
}
}
| lgpl-3.0 | 8e94a6594d4283ae117267d3efafdb1e | 43.581395 | 131 | 0.62963 | 5.142167 | false | false | false | false |
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/options/HardwareBackButtonOptions.kt | 1 | 2406 | package com.reactnativenavigation.options
import com.reactnativenavigation.options.params.Bool
import com.reactnativenavigation.options.params.NullBool
import com.reactnativenavigation.options.parsers.BoolParser
import org.json.JSONObject
sealed class HwBackBottomTabsBehaviour {
object Undefined : HwBackBottomTabsBehaviour() {
override fun hasValue(): Boolean = false
}
object Exit : HwBackBottomTabsBehaviour()
object PrevSelection : HwBackBottomTabsBehaviour()
object JumpToFirst : HwBackBottomTabsBehaviour()
open fun hasValue(): Boolean = true
companion object {
private const val BEHAVIOUR_EXIT = "exit"
private const val BEHAVIOUR_PREV = "previous"
private const val BEHAVIOUR_FIRST = "first"
fun fromString(behaviour: String?): HwBackBottomTabsBehaviour {
return when (behaviour) {
BEHAVIOUR_PREV -> PrevSelection
BEHAVIOUR_FIRST -> JumpToFirst
BEHAVIOUR_EXIT -> Exit
else -> Undefined
}
}
}
}
open class HardwareBackButtonOptions(json: JSONObject? = null) {
@JvmField
var dismissModalOnPress: Bool = NullBool()
@JvmField
var popStackOnPress: Bool = NullBool()
var bottomTabOnPress: HwBackBottomTabsBehaviour = HwBackBottomTabsBehaviour.Undefined
init {
parse(json)
}
fun mergeWith(other: HardwareBackButtonOptions) {
if (other.dismissModalOnPress.hasValue()) dismissModalOnPress = other.dismissModalOnPress
if (other.popStackOnPress.hasValue()) popStackOnPress = other.popStackOnPress
if (other.bottomTabOnPress.hasValue()) bottomTabOnPress = other.bottomTabOnPress
}
fun mergeWithDefault(defaultOptions: HardwareBackButtonOptions) {
if (!dismissModalOnPress.hasValue()) dismissModalOnPress = defaultOptions.dismissModalOnPress
if (!popStackOnPress.hasValue()) popStackOnPress = defaultOptions.popStackOnPress
if (!bottomTabOnPress.hasValue()) bottomTabOnPress = defaultOptions.bottomTabOnPress
}
private fun parse(json: JSONObject?) {
json ?: return
dismissModalOnPress = BoolParser.parse(json, "dismissModalOnPress")
popStackOnPress = BoolParser.parse(json, "popStackOnPress")
bottomTabOnPress = HwBackBottomTabsBehaviour.fromString(json.optString("bottomTabsOnPress"))
}
} | mit | 2b973150fd75f12a839aad50a46e2842 | 35.469697 | 101 | 0.714048 | 5.687943 | false | false | false | false |
mitallast/netty-queue | src/main/java/org/mitallast/queue/crdt/rest/RestGCounter.kt | 1 | 2780 | package org.mitallast.queue.crdt.rest
import com.google.inject.Inject
import io.netty.handler.codec.http.HttpMethod
import io.vavr.concurrent.Future
import io.vavr.control.Option
import org.mitallast.queue.crdt.CrdtService
import org.mitallast.queue.crdt.commutative.GCounter
import org.mitallast.queue.crdt.routing.ResourceType
import org.mitallast.queue.rest.RestController
class RestGCounter @Inject constructor(controller: RestController, private val crdtService: CrdtService) {
init {
controller.handle(
{ id: Long -> this.create(id) },
controller.param().toLong("id"),
controller.response().futureEither(
controller.response().created(),
controller.response().badRequest()
)
).handle(HttpMethod.POST, HttpMethod.PUT, "_crdt/{id}/g-counter")
controller.handle(
{ id: Long -> this.value(id) },
controller.param().toLong("id"),
controller.response().optional(
controller.response().text()
)
).handle(HttpMethod.GET, "_crdt/{id}/g-counter/value")
controller.handle(
{ id: Long -> this.increment(id) },
controller.param().toLong("id"),
controller.response().optional(
controller.response().text()
)
).handle(HttpMethod.POST, HttpMethod.PUT, "_crdt/{id}/g-counter/increment")
controller.handle(
{ id: Long, value: Long -> this.add(id, value) },
controller.param().toLong("id"),
controller.param().toLong("value"),
controller.response().optional(
controller.response().text()
)
).handle(HttpMethod.POST, HttpMethod.PUT, "_crdt/{id}/g-counter/add")
}
private fun create(id: Long): Future<Boolean> {
return crdtService.addResource(id, ResourceType.GCounter)
}
private fun value(id: Long): Option<Long> {
val bucket = crdtService.bucket(id)
return if (bucket == null) {
Option.none()
} else {
bucket.registry().crdtOpt(id, GCounter::class.java).map { it.value() }
}
}
private fun increment(id: Long): Option<Long> {
val bucket = crdtService.bucket(id)
return if (bucket == null) {
Option.none()
} else {
bucket.registry().crdtOpt(id, GCounter::class.java).map { it.increment() }
}
}
private fun add(id: Long, value: Long): Option<Long> {
val bucket = crdtService.bucket(id)
return if (bucket == null) {
Option.none()
} else {
bucket.registry().crdtOpt(id, GCounter::class.java).map { c -> c.add(value) }
}
}
}
| mit | bcc9a2291ee23a229f62f06be7d59826 | 33.75 | 106 | 0.585252 | 4.224924 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/utils/AchievementListDeserializer.kt | 1 | 1585 | package com.habitrpg.android.habitica.utils
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.habitrpg.android.habitica.extensions.getAsString
import com.habitrpg.android.habitica.models.Achievement
import java.lang.reflect.Type
class AchievementListDeserializer : JsonDeserializer<List<Achievement?>> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): List<Achievement?> {
val achievements = mutableListOf<Achievement>()
for (categoryEntry in json?.asJsonObject?.entrySet() ?: emptySet()) {
val categoryIdentifier = categoryEntry.key
for (entry in categoryEntry.value.asJsonObject.getAsJsonObject("achievements").entrySet()) {
val obj = entry.value.asJsonObject
val achievement = Achievement()
achievement.key = entry.key
achievement.category = categoryIdentifier
achievement.earned = obj.get("earned").asBoolean
achievement.title = obj.getAsString("title")
achievement.text = obj.getAsString("text")
achievement.icon = obj.getAsString("icon")
achievement.index = if (obj.has("index")) obj["index"].asInt else 0
achievement.optionalCount = if (obj.has("optionalCount")) obj["optionalCount"].asInt else 0
achievements.add(achievement)
}
}
return achievements
}
}
| gpl-3.0 | bcc1bce48d9714e2cf5bc187a2bd0ab0 | 43.027778 | 107 | 0.661199 | 5.213816 | false | false | false | false |
dhleong/ideavim | src/com/maddyhome/idea/vim/action/motion/leftright/MotionRightAction.kt | 1 | 2515 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.action.motion.leftright
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.MotionEditorAction
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.handler.MotionActionHandler
import java.awt.event.KeyEvent
import java.util.*
import javax.swing.KeyStroke
class MotionRightAction : MotionEditorAction() {
override val mappingModes: Set<MappingMode> = MappingMode.NVO
override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("l")
override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_MOT_EXCLUSIVE)
override fun makeActionHandler(): MotionActionHandler = MotionRightActionHandler
}
class MotionRightInsertAction : MotionEditorAction() {
override val mappingModes: Set<MappingMode> = MappingMode.I
override val keyStrokesSet: Set<List<KeyStroke>> = setOf(
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0)),
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, 0))
)
override fun makeActionHandler(): MotionActionHandler = MotionRightActionHandler
}
private object MotionRightActionHandler : MotionActionHandler.ForEachCaret() {
override fun getOffset(editor: Editor,
caret: Caret,
context: DataContext,
count: Int,
rawCount: Int,
argument: Argument?): Int {
return VimPlugin.getMotion().moveCaretHorizontal(editor, caret, count, true)
}
}
| gpl-2.0 | c47d0d8bfba18add75c899458833c70d | 38.296875 | 89 | 0.74672 | 4.531532 | false | false | false | false |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/appearance/Language.kt | 1 | 3507 | package wangdaye.com.geometricweather.common.basic.models.options.appearance
import android.content.Context
import android.content.res.Resources
import android.os.Build
import android.text.TextUtils
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.basic.models.options._basic.BaseEnum
import wangdaye.com.geometricweather.common.basic.models.options._basic.Utils
import java.util.*
enum class Language(
override val id: String,
val locale: Locale
): BaseEnum {
FOLLOW_SYSTEM(
"follow_system",
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Resources.getSystem().configuration.locales[0]
} else {
Resources.getSystem().configuration.locale
}
),
CHINESE("chinese", Locale("zh", "CN")),
UNSIMPLIFIED_CHINESE("unsimplified_chinese", Locale("zh", "TW")),
ENGLISH_US("english_america", Locale("en", "US")),
ENGLISH_UK("english_britain", Locale("en", "GB")),
ENGLISH_AU("english_australia", Locale("en", "AU")),
TURKISH("turkish", Locale("tr")),
FRENCH("french", Locale("fr")),
RUSSIAN("russian", Locale("ru")),
GERMAN("german", Locale("de")),
SERBIAN("serbian", Locale("sr")),
SPANISH("spanish", Locale("es")),
ITALIAN("italian", Locale("it")),
DUTCH("dutch", Locale("nl")),
HUNGARIAN("hungarian", Locale("hu")),
PORTUGUESE("portuguese", Locale("pt")),
PORTUGUESE_BR("portuguese_brazilian", Locale("pt", "BR")),
SLOVENIAN("slovenian", Locale("sl", "SI")),
ARABIC("arabic", Locale("ar")),
CZECH("czech", Locale("cs")),
POLISH("polish", Locale("pl")),
KOREAN("korean", Locale("ko")),
GREEK("greek", Locale("el")),
JAPANESE("japanese", Locale("ja")),
ROMANIAN("romanian", Locale("ro"));
val code: String
get() {
val locale = locale
val language = locale.language
val country = locale.country
return if (!TextUtils.isEmpty(country)
&& (country.lowercase() == "tw" || country.lowercase() == "hk")
) {
language.lowercase() + "-" + country.lowercase()
} else {
language.lowercase()
}
}
val isChinese: Boolean
get() = code.startsWith("zh")
companion object {
fun getInstance(
value: String
) = when (value) {
"chinese" -> CHINESE
"unsimplified_chinese" -> UNSIMPLIFIED_CHINESE
"english_america" -> ENGLISH_US
"english_britain" -> ENGLISH_UK
"english_australia" -> ENGLISH_AU
"turkish" -> TURKISH
"french" -> FRENCH
"russian" -> RUSSIAN
"german" -> GERMAN
"serbian" -> SERBIAN
"spanish" -> SPANISH
"italian" -> ITALIAN
"dutch" -> DUTCH
"hungarian" -> HUNGARIAN
"portuguese" -> PORTUGUESE
"portuguese_brazilian" -> PORTUGUESE_BR
"slovenian" -> SLOVENIAN
"arabic" -> ARABIC
"czech" -> CZECH
"polish" -> POLISH
"korean" -> KOREAN
"greek" -> GREEK
"japanese" -> JAPANESE
"romanian" -> ROMANIAN
else -> FOLLOW_SYSTEM
}
}
override val valueArrayId = R.array.language_values
override val nameArrayId = R.array.languages
override fun getName(context: Context) = Utils.getName(context, this)
} | lgpl-3.0 | f2a4fca7a3ed8250674bcc54ab0920a4 | 32.730769 | 80 | 0.572284 | 4.017182 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/LlvmDeclarations.kt | 1 | 14645 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import kotlinx.cinterop.*
import llvm.*
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.KonanConfigKeys
import org.jetbrains.kotlin.backend.konan.descriptors.*
import org.jetbrains.kotlin.backend.konan.isKotlinObjCClass
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.serialization.deserialization.descriptors.*
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
internal fun createLlvmDeclarations(context: Context): LlvmDeclarations {
val generator = DeclarationsGeneratorVisitor(context)
context.ir.irModule.acceptChildrenVoid(generator)
return with(generator) {
LlvmDeclarations(
functions, classes, fields, staticFields, theUnitInstanceRef
)
}
}
internal class LlvmDeclarations(
private val functions: Map<FunctionDescriptor, FunctionLlvmDeclarations>,
private val classes: Map<ClassDescriptor, ClassLlvmDeclarations>,
private val fields: Map<PropertyDescriptor, FieldLlvmDeclarations>,
private val staticFields: Map<PropertyDescriptor, StaticFieldLlvmDeclarations>,
private val theUnitInstanceRef: ConstPointer?
) {
fun forFunction(descriptor: FunctionDescriptor) = functions[descriptor] ?:
error(descriptor.toString())
fun forClass(descriptor: ClassDescriptor) = classes[descriptor] ?:
error(descriptor.toString())
fun forField(descriptor: PropertyDescriptor) = fields[descriptor] ?:
error(descriptor.toString())
fun forStaticField(descriptor: PropertyDescriptor) = staticFields[descriptor] ?:
error(descriptor.toString())
fun forSingleton(descriptor: ClassDescriptor) = forClass(descriptor).singletonDeclarations ?:
error(descriptor.toString())
fun getUnitInstanceRef() = theUnitInstanceRef ?: error("")
}
internal class ClassLlvmDeclarations(
val bodyType: LLVMTypeRef,
val fields: List<PropertyDescriptor>, // TODO: it is not an LLVM declaration.
val typeInfoGlobal: StaticData.Global,
val typeInfo: ConstPointer,
val singletonDeclarations: SingletonLlvmDeclarations?,
val objCDeclarations: KotlinObjCClassLlvmDeclarations?)
internal class SingletonLlvmDeclarations(val instanceFieldRef: LLVMValueRef)
internal class KotlinObjCClassLlvmDeclarations(
val classPointerGlobal: StaticData.Global,
val classInfoGlobal: StaticData.Global,
val bodyOffsetGlobal: StaticData.Global
)
internal class FunctionLlvmDeclarations(val llvmFunction: LLVMValueRef)
internal class FieldLlvmDeclarations(val index: Int, val classBodyType: LLVMTypeRef)
internal class StaticFieldLlvmDeclarations(val storage: LLVMValueRef)
// TODO: rework getFields and getDeclaredFields.
/**
* All fields of the class instance.
* The order respects the class hierarchy, i.e. a class [fields] contains superclass [fields] as a prefix.
*/
internal fun ContextUtils.getFields(classDescriptor: ClassDescriptor): List<PropertyDescriptor> {
val superClass = classDescriptor.getSuperClassNotAny() // TODO: what if Any has fields?
val superFields = if (superClass != null) getFields(superClass) else emptyList()
return superFields + getDeclaredFields(classDescriptor)
}
/**
* Fields declared in the class.
*/
private fun ContextUtils.getDeclaredFields(classDescriptor: ClassDescriptor): List<PropertyDescriptor> {
// TODO: Here's what is going on here:
// The existence of a backing field for a property is only described in the IR,
// but not in the PropertyDescriptor.
//
// We mark serialized properties with a Konan protobuf extension bit,
// so it is present in DeserializedPropertyDescriptor.
//
// In this function we check the presence of the backing filed
// two ways: first we check IR, then we check the protobuf extension.
val irClass = context.ir.moduleIndexForCodegen.classes[classDescriptor]
val fields = if (irClass != null) {
val declarations = irClass.declarations
declarations.mapNotNull {
when (it) {
is IrProperty -> it.backingField?.descriptor
is IrField -> it.descriptor
else -> null
}
}
} else {
val properties = classDescriptor.unsubstitutedMemberScope.
getContributedDescriptors().
filterIsInstance<DeserializedPropertyDescriptor>()
properties.mapNotNull { it.backingField }
}
return fields.sortedBy {
it.fqNameSafe.localHash.value
}
}
private fun ContextUtils.createClassBodyType(name: String, fields: List<PropertyDescriptor>): LLVMTypeRef {
val fieldTypes = fields.map { getLLVMType(if (it.isDelegated) context.builtIns.nullableAnyType else it.type) }
val classType = LLVMStructCreateNamed(LLVMGetModuleContext(context.llvmModule), name)!!
LLVMStructSetBody(classType, fieldTypes.toCValues(), fieldTypes.size, 0)
return classType
}
private class DeclarationsGeneratorVisitor(override val context: Context) :
IrElementVisitorVoid, ContextUtils {
val functions = mutableMapOf<FunctionDescriptor, FunctionLlvmDeclarations>()
val classes = mutableMapOf<ClassDescriptor, ClassLlvmDeclarations>()
val fields = mutableMapOf<PropertyDescriptor, FieldLlvmDeclarations>()
val staticFields = mutableMapOf<PropertyDescriptor, StaticFieldLlvmDeclarations>()
var theUnitInstanceRef: ConstPointer? = null
private class Namer(val prefix: String) {
private val names = mutableMapOf<DeclarationDescriptor, Name>()
private val counts = mutableMapOf<FqName, Int>()
fun getName(parent: FqName, descriptor: DeclarationDescriptor): Name {
return names.getOrPut(descriptor) {
val count = counts.getOrDefault(parent, 0) + 1
counts[parent] = count
Name.identifier(prefix + count)
}
}
}
val objectNamer = Namer("object-")
private fun getLocalName(parent: FqName, descriptor: DeclarationDescriptor): Name {
if (DescriptorUtils.isAnonymousObject(descriptor)) {
return objectNamer.getName(parent, descriptor)
}
return descriptor.name
}
private fun getFqName(descriptor: DeclarationDescriptor): FqName {
if (descriptor is PackageFragmentDescriptor) {
return descriptor.fqName
}
val containingDeclaration = descriptor.containingDeclaration
val parent = if (containingDeclaration != null) {
getFqName(containingDeclaration)
} else {
FqName.ROOT
}
val localName = getLocalName(parent, descriptor)
return parent.child(localName)
}
/**
* Produces the name to be used for non-exported LLVM declarations corresponding to [descriptor].
*
* Note: since these declarations are going to be private, the name is only required not to clash with any
* exported declarations.
*/
private fun qualifyInternalName(descriptor: DeclarationDescriptor): String {
return getFqName(descriptor).asString() + "#internal"
}
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
}
override fun visitClass(declaration: IrClass) {
if (declaration.descriptor.isIntrinsic) {
// do not generate any declarations for intrinsic classes as they require special handling
} else {
this.classes[declaration.descriptor] = createClassDeclarations(declaration)
}
super.visitClass(declaration)
}
private fun createClassDeclarations(declaration: IrClass): ClassLlvmDeclarations {
val descriptor = declaration.descriptor
val internalName = qualifyInternalName(descriptor)
val fields = getFields(descriptor)
val bodyType = createClassBodyType("kclassbody:$internalName", fields)
val typeInfoPtr: ConstPointer
val typeInfoGlobal: StaticData.Global
val typeInfoSymbolName = if (descriptor.isExported()) {
descriptor.typeInfoSymbolName
} else {
"ktype:$internalName"
}
if (descriptor.typeInfoHasVtableAttached) {
// Create the special global consisting of TypeInfo and vtable.
val typeInfoGlobalName = "ktypeglobal:$internalName"
val typeInfoWithVtableType = structType(
runtime.typeInfoType,
LLVMArrayType(int8TypePtr, context.getVtableBuilder(descriptor).vtableEntries.size)!!
)
typeInfoGlobal = staticData.createGlobal(typeInfoWithVtableType, typeInfoGlobalName, isExported = false)
val llvmTypeInfoPtr = LLVMAddAlias(context.llvmModule,
kTypeInfoPtr,
typeInfoGlobal.pointer.getElementPtr(0).llvm,
typeInfoSymbolName)!!
if (!descriptor.isExported()) {
LLVMSetLinkage(llvmTypeInfoPtr, LLVMLinkage.LLVMInternalLinkage)
}
typeInfoPtr = constPointer(llvmTypeInfoPtr)
} else {
typeInfoGlobal = staticData.createGlobal(runtime.typeInfoType,
typeInfoSymbolName,
isExported = descriptor.isExported())
typeInfoPtr = typeInfoGlobal.pointer
}
val singletonDeclarations = if (descriptor.kind.isSingleton) {
createSingletonDeclarations(descriptor, typeInfoPtr, bodyType)
} else {
null
}
val objCDeclarations = if (descriptor.isKotlinObjCClass()) {
createKotlinObjCClassDeclarations(descriptor)
} else {
null
}
return ClassLlvmDeclarations(bodyType, fields, typeInfoGlobal, typeInfoPtr,
singletonDeclarations, objCDeclarations)
}
private fun createSingletonDeclarations(
descriptor: ClassDescriptor,
typeInfoPtr: ConstPointer,
bodyType: LLVMTypeRef
): SingletonLlvmDeclarations? {
if (descriptor.isUnit()) {
this.theUnitInstanceRef = staticData.createUnitInstance(descriptor, bodyType, typeInfoPtr)
return null
}
val isExported = descriptor.isExported()
val symbolName = if (isExported) {
descriptor.objectInstanceFieldSymbolName
} else {
"kobjref:" + qualifyInternalName(descriptor)
}
val instanceFieldRef = addGlobal(
symbolName, getLLVMType(descriptor.defaultType), isExported = isExported, threadLocal = true)
return SingletonLlvmDeclarations(instanceFieldRef)
}
private fun createKotlinObjCClassDeclarations(descriptor: ClassDescriptor): KotlinObjCClassLlvmDeclarations {
val internalName = qualifyInternalName(descriptor)
val classPointerGlobal = staticData.createGlobal(int8TypePtr, "kobjcclassptr:$internalName")
val classInfoGlobal = staticData.createGlobal(
context.llvm.runtime.kotlinObjCClassInfo,
"kobjcclassinfo:$internalName"
).apply {
setConstant(true)
}
val bodyOffsetGlobal = staticData.createGlobal(int32Type, "kobjcbodyoffs:$internalName")
return KotlinObjCClassLlvmDeclarations(classPointerGlobal, classInfoGlobal, bodyOffsetGlobal)
}
override fun visitField(declaration: IrField) {
super.visitField(declaration)
val descriptor = declaration.descriptor
val dispatchReceiverParameter = descriptor.dispatchReceiverParameter
if (dispatchReceiverParameter != null) {
val containingClass = dispatchReceiverParameter.containingDeclaration
val classDeclarations = this.classes[containingClass] ?: error(containingClass.toString())
val allFields = classDeclarations.fields
this.fields[descriptor] = FieldLlvmDeclarations(
allFields.indexOf(descriptor),
classDeclarations.bodyType
)
} else {
// Fields are module-private, so we use internal name:
val name = "kvar:" + qualifyInternalName(descriptor)
val storage = addGlobal(
name, getLLVMType(descriptor.type), isExported = false, threadLocal = true)
this.staticFields[descriptor] = StaticFieldLlvmDeclarations(storage)
}
}
override fun visitFunction(declaration: IrFunction) {
super.visitFunction(declaration)
if (!declaration.descriptor.kind.isReal) return
val descriptor = declaration.descriptor
val llvmFunctionType = getLlvmFunctionType(descriptor)
val llvmFunction = if (descriptor.isExternal) {
if (descriptor.isIntrinsic) {
return
}
context.llvm.externalFunction(descriptor.symbolName, llvmFunctionType)
} else {
val symbolName = if (descriptor.isExported()) {
descriptor.symbolName
} else {
"kfun:" + qualifyInternalName(descriptor)
}
LLVMAddFunction(context.llvmModule, symbolName, llvmFunctionType)!!
}
if (!context.config.configuration.getBoolean(KonanConfigKeys.OPTIMIZATION)) {
LLVMAddTargetDependentFunctionAttr(llvmFunction, "no-frame-pointer-elim", "true")
}
this.functions[descriptor] = FunctionLlvmDeclarations(llvmFunction)
}
}
| apache-2.0 | 3596d98b9be0dda63c9078aa56c83ab7 | 36.455243 | 116 | 0.691431 | 5.647898 | false | false | false | false |
world-federation-of-advertisers/virtual-people-core-serving | src/main/kotlin/org/wfanet/virtualpeople/core/labeler/Labeler.kt | 1 | 8279 | // Copyright 2022 The Cross-Media Measurement 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.wfanet.virtualpeople.core.labeler
import com.google.common.hash.Hashing
import java.nio.charset.StandardCharsets
import org.wfanet.virtualpeople.common.*
import org.wfanet.virtualpeople.core.model.ModelNode
class Labeler private constructor(private val rootNode: ModelNode) {
/** Apply the model to generate the labels. Invalid inputs will result in an error. */
fun label(input: LabelerInput): LabelerOutput {
/** Prepare labeler event. */
val eventBuilder = labelerEvent { labelerInput = input }.toBuilder()
setFingerprints(eventBuilder)
rootNode.apply(eventBuilder)
return labelerOutput {
people.addAll(eventBuilder.virtualPersonActivitiesList)
serializedDebugTrace = eventBuilder.toString()
}
}
companion object {
/**
* Always use Labeler::Build to get a Labeler object. Users should never call the constructor
* directly.
* ```
* There are 3 ways to represent a full model:
* - Option 1:
* A single root node, with all the other nodes in the model tree attached
* directly to their parent nodes. Example (node1 is the root node):
* _node1_
* | |
* node2 _node3_
* | | |
* node4 node5 node6
* - Option 2:
* A list of nodes. All nodes except the root node must have index set.
* For any node with child nodes, the child nodes are referenced by indexes.
* Example (node1 is the root node):
* node1: index = null, child_nodes = [2, 3]
* node2: index = 2, child_nodes = [4]
* node3: index = 3, child_nodes = [5, 6]
* node4: index = 4, child_nodes = []
* node5: index = 5, child_nodes = []
* node6: index = 6, child_nodes = []
* - Option 3:
* Mix of the above 2. Some nodes are referenced directly, while others are
* referenced by indexes. For any node referenced by index, an entry must be
* included in @nodes, with the index field set.
* Example (node1 is the root node):
* node1:
* _node1_
* | |
* 2 _node3_
* | |
* 5 6
* node2: index = 2
* node2
* |
* node4
* node5: index = 5
* node6: index = 6
* ```
* Build the model with the @root node. Handles option 1 above.
*
* All the other nodes are referenced directly in branch_node.branches.node of the parent nodes.
* Any index or node_index field is ignored.
*/
@JvmStatic
fun build(root: CompiledNode): Labeler {
return Labeler(ModelNode.build(root))
}
/**
* Build the model with all the [nodes]. Handles option 2 and 3 above.
*
* Nodes are allowed to be referenced by branch_node.branches.node_index.
*
* For CompiledNodes in [nodes], only the root node is allowed to not have index set.
*
* [nodes] must be sorted in the order that any child node is prior to its parent node.
*/
@JvmStatic
fun build(nodes: List<CompiledNode>): Labeler {
var root: ModelNode? = null
val nodeRefs = mutableMapOf<Int, ModelNode>()
nodes.forEach { nodeConfig ->
if (root != null) {
error("No node is allowed after the root node.")
}
if (nodeConfig.hasIndex()) {
if (nodeRefs.containsKey(nodeConfig.index)) {
error("Duplicated indexes: ${nodeConfig.index}")
}
nodeRefs[nodeConfig.index] = ModelNode.build(nodeConfig, nodeRefs)
} else {
root = ModelNode.build(nodeConfig, nodeRefs)
}
}
if (root == null) {
if (nodeRefs.isEmpty()) {
/** This should never happen. */
error("Cannot find root node.")
}
if (nodeRefs.size > 1) {
/** We expect only 1 node in the node_refs map, which is the root node. */
error("Only 1 root node is expected in the node_refs map")
}
val entry = nodeRefs.entries.first()
root = entry.value
nodeRefs.remove(entry.key)
}
if (nodeRefs.isNotEmpty()) {
error("Some nodes are not in the model tree.")
}
/** root is guaranteed to be not null at this point. */
return Labeler(root!!)
}
/**
* The fingerprint is expected to be a ULong, however, in Kotlin proto, uint64 is read/writen as
* Long.
*
* We need to convert it to ULong whenever we need to consume it, and convert it back to Long
* when we write back to proto.
*/
private fun getFingerprint64Long(seed: String): Long {
return Hashing.farmHashFingerprint64().hashString(seed, StandardCharsets.UTF_8).asLong()
}
private fun setUserInfoFingerprint(userInfo: UserInfo.Builder) {
if (userInfo.hasUserId()) {
userInfo.userIdFingerprint = getFingerprint64Long(userInfo.userId)
}
}
private fun setFingerprints(eventBuilder: LabelerEvent.Builder) {
val labelerInputBuilder = eventBuilder.labelerInputBuilder
if (labelerInputBuilder.hasEventId()) {
val eventIdFingerprint = getFingerprint64Long(labelerInputBuilder.eventId.id)
labelerInputBuilder.eventIdBuilder.idFingerprint = eventIdFingerprint
eventBuilder.actingFingerprint = eventIdFingerprint
}
if (!labelerInputBuilder.hasProfileInfo()) return
val profileInfoBuilder = labelerInputBuilder.profileInfoBuilder
if (profileInfoBuilder.hasEmailUserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.emailUserInfoBuilder)
}
if (profileInfoBuilder.hasPhoneUserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.phoneUserInfoBuilder)
}
if (profileInfoBuilder.hasLoggedInIdUserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.loggedInIdUserInfoBuilder)
}
if (profileInfoBuilder.hasLoggedOutIdUserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.loggedOutIdUserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace1UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace1UserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace2UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace2UserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace3UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace3UserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace4UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace4UserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace5UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace5UserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace6UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace6UserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace7UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace7UserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace8UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace8UserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace9UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace9UserInfoBuilder)
}
if (profileInfoBuilder.hasProprietaryIdSpace10UserInfo()) {
setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace10UserInfoBuilder)
}
}
}
}
| apache-2.0 | 86e27855e1338311c1c1ddb124ff8e49 | 38.42381 | 100 | 0.664935 | 4.755313 | false | false | false | false |
paslavsky/music-sync-manager | msm-server/src/main/kotlin/net/paslavsky/msm/Streaming.kt | 1 | 633 | package net.paslavsky.msm
import java.util.Properties
import java.util.LinkedHashMap
/**
* Extension functions for streaming
*
* @author Andrey Paslavsky
* @version 1.0
*/
public fun <T> Sequence<T>.each(operation: (T) -> T): Sequence<T> = ForEachStream(this, operation)
public class ForEachStream<T>(private val target: Sequence<T>, private val operation: (T) -> T) : Sequence<T> {
private val iterator = target.iterator()
override fun iterator(): Iterator<T> = object : Iterator<T> {
override fun hasNext(): Boolean = iterator.hasNext()
override fun next(): T = operation(iterator.next())
}
} | apache-2.0 | c5cf0c9952b4ef4989af87ada4abe921 | 26.565217 | 111 | 0.685624 | 3.790419 | false | false | false | false |
wbaumann/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/fragments/ReceiptImageFragment.kt | 1 | 11230 | package co.smartreceipts.android.fragments
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import co.smartreceipts.analytics.Analytics
import co.smartreceipts.analytics.events.Events
import co.smartreceipts.analytics.log.Logger
import co.smartreceipts.android.R
import co.smartreceipts.android.activities.NavigationHandler
import co.smartreceipts.android.activities.SmartReceiptsActivity
import co.smartreceipts.android.images.CropImageActivity
import co.smartreceipts.android.imports.CameraInteractionController
import co.smartreceipts.android.imports.RequestCodes
import co.smartreceipts.android.imports.importer.ActivityFileResultImporter
import co.smartreceipts.android.imports.locator.ActivityFileResultLocator
import co.smartreceipts.android.model.Receipt
import co.smartreceipts.android.model.factory.ReceiptBuilderFactory
import co.smartreceipts.android.persistence.database.controllers.impl.ReceiptTableController
import co.smartreceipts.android.persistence.database.controllers.impl.StubTableEventsListener
import co.smartreceipts.android.persistence.database.operations.DatabaseOperationMetadata
import co.smartreceipts.android.persistence.database.operations.OperationFamilyType
import co.smartreceipts.android.tooltip.image.data.ImageCroppingPreferenceStorage
import co.smartreceipts.android.utils.IntentUtils
import com.squareup.picasso.Callback
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.Picasso
import dagger.Lazy
import dagger.android.support.AndroidSupportInjection
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.receipt_image_view.*
import kotlinx.android.synthetic.main.receipt_image_view.view.*
import wb.android.flex.Flex
import javax.inject.Inject
class ReceiptImageFragment : WBFragment() {
companion object {
// Save state
private const val KEY_OUT_RECEIPT = "key_out_receipt"
private const val KEY_OUT_URI = "key_out_uri"
fun newInstance(): ReceiptImageFragment {
return ReceiptImageFragment()
}
}
@Inject
lateinit var flex: Flex
@Inject
lateinit var analytics: Analytics
@Inject
lateinit var receiptTableController: ReceiptTableController
@Inject
lateinit var navigationHandler: NavigationHandler<SmartReceiptsActivity>
@Inject
lateinit var activityFileResultLocator: ActivityFileResultLocator
@Inject
lateinit var activityFileResultImporter: ActivityFileResultImporter
@Inject
lateinit var imageCroppingPreferenceStorage: ImageCroppingPreferenceStorage
@Inject
lateinit var picasso: Lazy<Picasso>
private lateinit var imageUpdatedListener: ImageUpdatedListener
private lateinit var compositeDisposable: CompositeDisposable
private var imageUri: Uri? = null
private var receipt: Receipt? = null
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
receipt = arguments!!.getParcelable(Receipt.PARCEL_KEY)
} else {
receipt = savedInstanceState.getParcelable(KEY_OUT_RECEIPT)
imageUri = savedInstanceState.getParcelable(KEY_OUT_URI)
}
imageUpdatedListener = ImageUpdatedListener()
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.receipt_image_view, container, false)
rootView.button_edit_photo.setOnClickListener { view ->
analytics.record(Events.Receipts.ReceiptImageViewEditPhoto)
imageCroppingPreferenceStorage.setCroppingScreenWasShown(true)
navigationHandler.navigateToCropActivity(this, receipt!!.file!!, RequestCodes.EDIT_IMAGE_CROP)
}
rootView.button_retake_photo.setOnClickListener { view ->
analytics.record(Events.Receipts.ReceiptImageViewRetakePhoto)
imageUri = CameraInteractionController(this@ReceiptImageFragment).retakePhoto(receipt!!)
}
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loadImage()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val fragmentActivity = requireActivity()
val toolbar = fragmentActivity.findViewById<Toolbar>(R.id.toolbar)
(fragmentActivity as AppCompatActivity).setSupportActionBar(toolbar)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Logger.debug(this, "Result Code: $resultCode")
// Null out the last request
val cachedImageSaveLocation = imageUri
imageUri = null
if (requestCode == RequestCodes.EDIT_IMAGE_CROP) {
when (resultCode) {
CropImageActivity.RESULT_CROP_ERROR -> {
Logger.error(this, "An error occurred while cropping the image")
}
else -> {
picasso.get().invalidate(receipt!!.file!!)
loadImage()
}
}
} else {
activityFileResultLocator.onActivityResult(requestCode, resultCode, data, cachedImageSaveLocation)
}
}
private fun subscribe() {
compositeDisposable = CompositeDisposable()
compositeDisposable.add(activityFileResultLocator.uriStream
// uri always has SCHEME_CONTENT -> we don't need to check permissions
.subscribe { locatorResponse ->
when {
locatorResponse.throwable.isPresent -> {
receipt_image_progress.visibility = View.GONE
Toast.makeText(activity, getFlexString(R.string.FILE_SAVE_ERROR), Toast.LENGTH_SHORT).show()
activityFileResultLocator.markThatResultsWereConsumed()
}
else -> {
receipt_image_progress.visibility = View.VISIBLE
activityFileResultImporter.importFile(
locatorResponse.requestCode,
locatorResponse.resultCode, locatorResponse.uri!!, receipt!!.trip
)
}
}
})
compositeDisposable.add(activityFileResultImporter.resultStream
.subscribe { (throwable, file) ->
when {
throwable.isPresent -> Toast.makeText(activity, getFlexString(R.string.IMG_SAVE_ERROR), Toast.LENGTH_SHORT).show()
else -> {
val retakeReceipt = ReceiptBuilderFactory(receipt!!).setFile(file).build()
receiptTableController.update(receipt!!, retakeReceipt, DatabaseOperationMetadata())
}
}
receipt_image_progress.visibility = View.GONE
activityFileResultLocator.markThatResultsWereConsumed()
activityFileResultImporter.markThatResultsWereConsumed()
})
}
override fun onResume() {
super.onResume()
val actionBar = (requireActivity() as AppCompatActivity).supportActionBar
actionBar?.apply {
setHomeButtonEnabled(true)
setDisplayHomeAsUpEnabled(true)
title = receipt!!.name
}
receiptTableController.subscribe(imageUpdatedListener)
subscribe()
}
override fun onPause() {
receiptTableController.unsubscribe(imageUpdatedListener)
compositeDisposable.clear()
super.onPause()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Logger.debug(this, "onSaveInstanceState")
outState.apply {
putParcelable(KEY_OUT_RECEIPT, receipt)
putParcelable(KEY_OUT_URI, imageUri)
}
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.menu_share, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
navigationHandler.navigateBack()
true
}
R.id.action_share -> {
receipt!!.file?.let {
val sendIntent = IntentUtils.getSendIntent(requireActivity(), it)
startActivity(Intent.createChooser(sendIntent, resources.getString(R.string.send_email)))
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun loadImage() {
if (receipt!!.hasImage()) {
receipt!!.file?.let {
receipt_image_progress.visibility = View.VISIBLE
picasso.get().load(it).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).fit().centerInside()
.into(receipt_image_imageview, object : Callback {
override fun onSuccess() {
receipt_image_progress.visibility = View.GONE
receipt_image_imageview.visibility = View.VISIBLE
button_edit_photo.visibility = View.VISIBLE
button_retake_photo.visibility = View.VISIBLE
}
override fun onError(e: Exception) {
receipt_image_progress.visibility = View.GONE
Toast.makeText(requireContext(), getFlexString(R.string.IMG_OPEN_ERROR), Toast.LENGTH_SHORT).show()
}
})
}
}
}
private inner class ImageUpdatedListener : StubTableEventsListener<Receipt>() {
override fun onUpdateSuccess(oldReceipt: Receipt, newReceipt: Receipt, databaseOperationMetadata: DatabaseOperationMetadata) {
if (databaseOperationMetadata.operationFamilyType != OperationFamilyType.Sync) {
if (oldReceipt == receipt) {
receipt = newReceipt
loadImage()
}
}
}
override fun onUpdateFailure(oldReceipt: Receipt, e: Throwable?, databaseOperationMetadata: DatabaseOperationMetadata) {
if (databaseOperationMetadata.operationFamilyType != OperationFamilyType.Sync) {
receipt_image_progress.visibility = View.GONE
Toast.makeText(requireContext(), getFlexString(R.string.database_error), Toast.LENGTH_SHORT).show()
}
}
}
private fun getFlexString(id: Int): String = getFlexString(flex, id)
} | agpl-3.0 | c2f190250ba5e8a2acdd55baeb4b8862 | 37.727586 | 134 | 0.657792 | 5.540207 | false | false | false | false |
square/wire | wire-library/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/MathMethods.kt | 1 | 3068 | /*
* Copyright (c) 2016, the R8 project authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of Google Inc. 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.
*/
// Methods from https://r8.googlesource.com/r8/+/master/src/test/java/com/android/tools/r8/ir/desugar/backports/MathMethods.java
package com.squareup.wire.internal
internal fun addExactLong(x: Long, y: Long): Long {
val result: Long = x + y
if ((x xor y < 0L) or ((x xor result) >= 0L)) {
return result
}
throw ArithmeticException()
}
internal fun floorDivLong(dividend: Long, divisor: Long): Long {
val div = dividend / divisor
val rem = dividend - divisor * div
if (rem == 0L) {
return div
}
// Normal Java division rounds towards 0. We just have to deal with the cases where rounding
// towards 0 is wrong, which typically depends on the sign of dividend / divisor.
//
// signum is 1 if dividend and divisor are both nonnegative or negative, and -1 otherwise.
val signum = 1L or ((dividend xor divisor) shr Long.SIZE_BITS - 1)
return if (signum < 0L) div - 1L else div
}
internal fun floorModLong(dividend: Long, divisor: Long): Long {
val rem = dividend % divisor
if (rem == 0L) {
return 0L
}
// Normal Java remainder tracks the sign of the dividend. We just have to deal with the case
// where the resulting sign is incorrect which is when the signs do not match.
//
// signum is 1 if dividend and divisor are both nonnegative or negative, and -1 otherwise.
val signum = 1L or ((dividend xor divisor) shr Long.SIZE_BITS - 1)
return if (signum > 0L) rem else rem + divisor
}
internal const val NANOS_PER_SECOND = 1000_000_000L
| apache-2.0 | fb68be7129ad0b177dede4e3b244c2bb | 44.117647 | 128 | 0.734029 | 4.068966 | false | false | false | false |
square/wire | wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Service.kt | 1 | 4311 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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:Suppress("NAME_SHADOWING")
package com.squareup.wire.schema
import com.squareup.wire.schema.ProtoMember.Companion.get
import com.squareup.wire.schema.ProtoType.Companion.get
import com.squareup.wire.schema.Rpc.Companion.fromElements
import com.squareup.wire.schema.internal.parser.ServiceElement
import kotlin.jvm.JvmName
import kotlin.jvm.JvmStatic
data class Service(
@get:JvmName("type") // For binary compatibility.
val type: ProtoType,
@get:JvmName("location") // For binary compatibility.
val location: Location,
@get:JvmName("documentation") // For binary compatibility.
val documentation: String,
@get:JvmName("name") // For binary compatibility.
val name: String,
@get:JvmName("rpcs") // For binary compatibility.
val rpcs: List<Rpc>,
@get:JvmName("options") // For binary compatibility.
val options: Options
) {
/** Returns the RPC named `name`, or null if this service has no such method. */
fun rpc(name: String): Rpc? {
return rpcs.find { it.name == name }
}
fun link(linker: Linker) {
var linker = linker
linker = linker.withContext(this)
for (rpc in rpcs) {
rpc.link(linker)
}
}
fun linkOptions(linker: Linker, validate: Boolean) {
val linker = linker.withContext(this)
for (rpc in rpcs) {
rpc.linkOptions(linker, validate)
}
options.link(linker, location, validate)
}
fun validate(linker: Linker) {
var linker = linker
linker = linker.withContext(this)
validateRpcUniqueness(linker, rpcs)
for (rpc in rpcs) {
rpc.validate(linker)
}
}
private fun validateRpcUniqueness(
linker: Linker,
rpcs: List<Rpc>
) {
val nameToRpc = linkedMapOf<String, MutableSet<Rpc>>()
for (rpc in rpcs) {
nameToRpc.getOrPut(rpc.name, { mutableSetOf() }).add(rpc)
}
for ((key, values) in nameToRpc) {
if (values.size > 1) {
val error = buildString {
append("mutable rpcs share name $key:")
values.forEachIndexed { index, rpc ->
append("\n ${index + 1}. ${rpc.name} (${rpc.location})")
}
}
linker.errors += error
}
}
}
fun retainAll(
schema: Schema,
markSet: MarkSet
): Service? {
// If this service is not retained, prune it.
if (!markSet.contains(type)) {
return null
}
val retainedRpcs = mutableListOf<Rpc>()
for (rpc in rpcs) {
val retainedRpc = rpc.retainAll(schema, markSet)
if (retainedRpc != null && markSet.contains(get(type, rpc.name))) {
retainedRpcs.add(retainedRpc)
}
}
return Service(
type, location, documentation, name, retainedRpcs,
options.retainAll(schema, markSet)
)
}
companion object {
internal fun fromElement(
protoType: ProtoType,
element: ServiceElement
): Service {
val rpcs = fromElements(element.rpcs)
val options = Options(Options.SERVICE_OPTIONS, element.options)
return Service(
protoType, element.location, element.documentation, element.name, rpcs,
options
)
}
@JvmStatic internal fun fromElements(
packageName: String?,
elements: List<ServiceElement>
): List<Service> {
return elements.map { service ->
val protoType = get(packageName, service.name)
fromElement(protoType, service)
}
}
@JvmStatic internal fun toElements(services: List<Service>): List<ServiceElement> {
return services.map { service ->
ServiceElement(
service.location,
service.name,
service.documentation,
Rpc.toElements(service.rpcs),
service.options.elements
)
}
}
}
}
| apache-2.0 | aee971b665a4c564d9000c952a1af5f9 | 27.549669 | 87 | 0.653213 | 4.032741 | false | false | false | false |
Saketme/JRAW | lib/src/test/kotlin/net/dean/jraw/test/mock.kt | 2 | 4900 | package net.dean.jraw.test
import net.dean.jraw.RedditClient
import net.dean.jraw.http.*
import net.dean.jraw.models.OAuthData
import net.dean.jraw.oauth.AuthManager
import net.dean.jraw.oauth.AuthMethod
import net.dean.jraw.oauth.Credentials
import net.dean.jraw.oauth.TokenStore
import net.dean.jraw.ratelimit.NoopRateLimiter
import okhttp3.*
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import java.util.*
import java.util.concurrent.TimeUnit
/** Creates a totally BS OAuthData object */
fun createMockOAuthData(includeRefreshToken: Boolean = false) = OAuthData.create(
/* accessToken = */ "<access_token>",
/* scopes = */ listOf("*"), // '*' means all scopes
/* refreshToken = */ if (includeRefreshToken) "<refresh_token>" else null,
/* expiration = */ Date(Date().time + TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS))
)
fun createMockCredentials(type: AuthMethod) = when (type) {
AuthMethod.SCRIPT -> Credentials.script("", "", "", "")
AuthMethod.APP -> Credentials.installedApp("", "")
AuthMethod.WEBAPP -> Credentials.webapp("", "", "")
AuthMethod.USERLESS -> Credentials.userless("", "", UUID.randomUUID())
AuthMethod.USERLESS_APP -> Credentials.userlessApp("", UUID.randomUUID())
else -> throw IllegalArgumentException("Not implemented for $type")
}
/** Creates a RedditClient with mocked OAuthData, Credentials, an InMemoryTokenStore, and a NoopRateLimiter */
fun newMockRedditClient(adapter: NetworkAdapter): RedditClient {
val r = RedditClient(adapter, createMockOAuthData(), createMockCredentials(AuthMethod.SCRIPT), InMemoryTokenStore(), overrideUsername = "<mock>")
r.rateLimiter = NoopRateLimiter()
return r
}
/**
* An NetworkAdapter that we can pre-configure responses for.
*
* Use [enqueue] to add a response to the queue. Executing a request will send the response at the head of the queue and
* remove it.
*/
class MockNetworkAdapter : NetworkAdapter {
override var userAgent: UserAgent = UserAgent("doesn't matter, no requests are going to be sent")
val http = OkHttpClient()
var mockServer = MockWebServer()
private val responseCodeQueue: Queue<Int> = LinkedList()
override fun connect(url: String, listener: WebSocketListener): WebSocket {
throw NotImplementedError()
}
override fun execute(r: HttpRequest): HttpResponse {
val path = HttpUrl.parse(r.url)!!.encodedPath()
val res = http.newCall(Request.Builder()
.headers(r.headers)
.method(r.method, r.body)
.url(mockServer.url("")
.newBuilder()
.encodedPath(path)
.build())
.build()).execute()
return HttpResponse(res)
}
fun enqueue(json: String) = enqueue(MockHttpResponse(json))
fun enqueue(r: MockHttpResponse) {
mockServer.enqueue(MockResponse()
.setResponseCode(r.code)
.setBody(r.body)
.setHeader("Content-Type", r.contentType))
responseCodeQueue.add(r.code)
}
fun start() {
mockServer.start()
}
fun reset() {
mockServer.shutdown()
mockServer = MockWebServer()
}
}
/**
* Used exclusively with [MockNetworkAdapter]
*/
data class MockHttpResponse(
val body: String = """{"mock":"response"}""",
val code: Int = 200,
val contentType: String = "application/json"
)
class InMemoryTokenStore : TokenStore {
private val dataMap: MutableMap<String, OAuthData?> = HashMap()
private val refreshMap: MutableMap<String, String?> = HashMap()
override fun storeLatest(username: String, data: OAuthData) {
if (username == AuthManager.USERNAME_UNKOWN)
throw IllegalArgumentException("Username was ${AuthManager.USERNAME_UNKOWN}")
dataMap.put(username, data)
}
override fun storeRefreshToken(username: String, token: String) {
if (username == AuthManager.USERNAME_UNKOWN)
throw IllegalArgumentException("Username was ${AuthManager.USERNAME_UNKOWN}")
refreshMap.put(username, token)
}
override fun fetchLatest(username: String): OAuthData? {
return dataMap[username]
}
override fun fetchRefreshToken(username: String): String? {
return refreshMap[username]
}
override fun deleteLatest(username: String) {
dataMap.remove(username)
}
override fun deleteRefreshToken(username: String) {
refreshMap.remove(username)
}
fun reset() {
dataMap.clear()
refreshMap.clear()
}
fun resetDataOnly() {
dataMap.clear()
}
}
class InMemoryLogAdapter : LogAdapter {
private val data: MutableList<String> = arrayListOf()
override fun writeln(data: String) {
this.data.add(data)
}
fun output() = ArrayList(data)
fun reset() { data.clear() }
}
| mit | 8fe6c11326cae659cbc5456763cd03ce | 31.026144 | 149 | 0.673265 | 4.466727 | false | false | false | false |
PolymerLabs/arcs | java/arcs/sdk/wasm/WasmCollectionImpl.kt | 1 | 2273 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.sdk.wasm
/** [ReadWriteCollection] implementation for WASM. */
class WasmCollectionImpl<T : WasmEntity>(
particle: WasmParticleImpl,
name: String,
private val entitySpec: WasmEntitySpec<T>
) : WasmHandleEvents<Set<T>>(particle, name) {
private val entities: MutableMap<String, T> = mutableMapOf()
val size: Int
get() = entities.size
fun fetchAll() = entities.values.toSet()
override fun sync(encoded: ByteArray) {
entities.clear()
add(encoded)
}
override fun update(added: ByteArray, removed: ByteArray) {
add(added)
with(StringDecoder(removed)) {
var num = getInt(':')
while (num-- > 0) {
val len = getInt(':')
val chunk = chomp(len)
// TODO: just get the id, no need to decode the full entity
val entity = requireNotNull(entitySpec.decode(chunk))
entities.remove(entity.entityId)
}
}
notifyOnUpdateActions()
}
fun isEmpty() = entities.isEmpty()
fun store(entity: T) {
val encoded = entity.encodeEntity()
WasmRuntimeClient.collectionStore(particle, this, encoded)?.let { entity.entityId = it }
entities[entity.entityId] = entity
}
fun remove(entity: T) {
entities[entity.entityId]?.let {
val encoded = it.encodeEntity()
entities.remove(entity.entityId)
WasmRuntimeClient.collectionRemove(particle, this, encoded)
}
notifyOnUpdateActions()
}
private fun add(added: ByteArray) {
with(StringDecoder(added)) {
repeat(getInt(':')) {
val len = getInt(':')
val chunk = chomp(len)
val entity = requireNotNull(entitySpec.decode(chunk))
entities[entity.entityId] = entity
}
}
}
fun clear() {
entities.clear()
WasmRuntimeClient.collectionClear(particle, this)
notifyOnUpdateActions()
}
fun notifyOnUpdateActions() {
val s = entities.values.toSet()
onUpdateActions.forEach { action ->
action(s)
}
}
}
| bsd-3-clause | f4e6ee4abc93caeee2aefd26175c407f | 24.829545 | 96 | 0.657281 | 4.073477 | false | false | false | false |
Hexworks/zircon | zircon.jvm.swing/src/main/kotlin/org/hexworks/zircon/internal/tileset/Java2DCP437Tileset.kt | 1 | 3563 | package org.hexworks.zircon.internal.tileset
import org.hexworks.zircon.api.application.ModifierSupport
import org.hexworks.zircon.api.color.ANSITileColor
import org.hexworks.zircon.api.data.CharacterTile
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.modifier.*
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.api.tileset.TextureTransformer
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.api.tileset.base.BaseCP437Tileset
import org.hexworks.zircon.internal.config.RuntimeConfig
import org.hexworks.zircon.internal.modifier.TileCoordinate
import org.hexworks.zircon.internal.tileset.impl.CP437TextureMetadata
import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture
import org.hexworks.zircon.internal.tileset.transformer.*
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import kotlin.reflect.KClass
@Suppress("UNCHECKED_CAST")
class Java2DCP437Tileset(
resource: TilesetResource,
private val source: BufferedImage,
modifierSupports: Map<KClass<out TextureTransformModifier>,ModifierSupport<BufferedImage>>
) : BaseCP437Tileset<Graphics2D, BufferedImage>(
resource = resource,
targetType = Graphics2D::class
) {
private val transformers = modifierSupports.mapValues { it.value.transformer }
override fun drawTile(tile: Tile, surface: Graphics2D, position: Position) {
val texture = fetchTextureForTile(tile, position)
val x = position.x * width
val y = position.y * height
surface.drawImage(texture.texture, x, y, null)
}
override fun loadTileTexture(
tile: CharacterTile,
position: Position,
meta: CP437TextureMetadata
): TileTexture<BufferedImage> {
var image: TileTexture<BufferedImage> = DefaultTileTexture(
width = width,
height = height,
texture = source.getSubimage(meta.x * width, meta.y * height, width, height),
cacheKey = tile.cacheKey
)
TILE_INITIALIZERS.forEach {
image = it.transform(image, tile)
}
tile.modifiers.filterIsInstance<TextureTransformModifier>().forEach {
image = transformers[it::class]?.transform(image, tile) ?: image
}
image = applyDebugModifiers(image, tile, position)
return image
}
private fun applyDebugModifiers(
image: TileTexture<BufferedImage>,
tile: Tile,
position: Position
): TileTexture<BufferedImage> {
val config = RuntimeConfig.config
var result = image
val border = transformers[Border::class]
if (config.debugMode && config.debugConfig.displayGrid && border != null) {
result = border.transform(image, tile.withAddedModifiers(GRID_BORDER))
}
val tileCoordinate = transformers[TileCoordinate::class]
if (config.debugMode && config.debugConfig.displayCoordinates && tileCoordinate != null) {
result = tileCoordinate.transform(image, tile.withAddedModifiers(TileCoordinate(position)))
}
return result
}
companion object {
private val GRID_BORDER = Border.newBuilder()
.withBorderColor(ANSITileColor.BRIGHT_MAGENTA)
.withBorderWidth(1)
.withBorderType(BorderType.SOLID)
.build()
private val TILE_INITIALIZERS = listOf(
Java2DTextureCloner(),
Java2DTextureColorizer(),
)
}
}
| apache-2.0 | 8b02ccf9acbb24558ed6b68e63333cb9 | 37.311828 | 103 | 0.703621 | 4.481761 | false | true | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/model/repository/forum/ForumRepository.kt | 1 | 2343 | package forpdateam.ru.forpda.model.repository.forum
import forpdateam.ru.forpda.entity.db.forum.ForumItemFlatBd
import forpdateam.ru.forpda.entity.remote.forum.Announce
import forpdateam.ru.forpda.entity.remote.forum.ForumItemTree
import forpdateam.ru.forpda.entity.remote.forum.ForumRules
import forpdateam.ru.forpda.model.SchedulersProvider
import forpdateam.ru.forpda.model.data.cache.forum.ForumCache
import forpdateam.ru.forpda.model.data.remote.api.forum.ForumApi
import forpdateam.ru.forpda.model.repository.BaseRepository
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
/**
* Created by radiationx on 03.01.18.
*/
class ForumRepository(
private val schedulers: SchedulersProvider,
private val forumApi: ForumApi,
private val forumCache: ForumCache
) : BaseRepository(schedulers) {
fun getForums(): Single<ForumItemTree> = Single
.fromCallable { forumApi.getForums() }
.runInIoToUi()
fun getCache(): Single<ForumItemTree> = Single
.fromCallable {
ForumItemTree().apply {
forumApi.transformToTree(forumCache.getItems(), this)
}
}
.runInIoToUi()
fun markAllRead(): Single<Any> = Single
.fromCallable { forumApi.markAllRead() }
.runInIoToUi()
fun markRead(id: Int): Single<Any> = Single
.fromCallable { forumApi.markRead(id) }
.runInIoToUi()
fun getRules(): Single<ForumRules> = Single
.fromCallable { forumApi.getRules() }
.runInIoToUi()
fun getAnnounce(id: Int, forumId: Int): Single<Announce> = Single
.fromCallable { forumApi.getAnnounce(id, forumId) }
.runInIoToUi()
fun saveCache(rootForum: ForumItemTree): Completable = Completable
.fromRunnable {
val items = mutableListOf<ForumItemFlatBd>().apply {
transformToList(this, rootForum)
}
forumCache.saveItems(items)
}
.runInIoToUi()
private fun transformToList(list: MutableList<ForumItemFlatBd>, rootForum: ForumItemTree) {
rootForum.forums?.forEach {
list.add(ForumItemFlatBd(it))
transformToList(list, it)
}
}
}
| gpl-3.0 | 7c2c3dc2927296a7fa89b4e0095cef1f | 32.471429 | 95 | 0.653863 | 4.704819 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/viewmodel/pages/PostModelUploadUiStateUseCase.kt | 1 | 3197 | package org.wordpress.android.viewmodel.pages
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.post.PostStatus
import org.wordpress.android.fluxc.model.post.PostStatus.DRAFT
import org.wordpress.android.fluxc.store.UploadStore.UploadError
import org.wordpress.android.ui.posts.PostModelUploadStatusTracker
import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.NothingToUpload
import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadFailed
import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadQueued
import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadWaitingForConnection
import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadingMedia
import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadingPost
import javax.inject.Inject
class PostModelUploadUiStateUseCase @Inject constructor() {
/**
* Copied from PostListItemUiStateHelper since the behavior is similar for the Page List UI State.
*/
fun createUploadUiState(
post: PostModel,
site: SiteModel,
uploadStatusTracker: PostModelUploadStatusTracker
): PostUploadUiState {
val postStatus = PostStatus.fromPost(post)
val uploadStatus = uploadStatusTracker.getUploadStatus(post, site)
return when {
uploadStatus.hasInProgressMediaUpload -> UploadingMedia(
uploadStatus.mediaUploadProgress
)
uploadStatus.isUploading -> UploadingPost(
postStatus == DRAFT
)
// the upload error is not null on retry -> it needs to be evaluated after UploadingMedia and UploadingPost
uploadStatus.uploadError != null -> UploadFailed(
uploadStatus.uploadError,
uploadStatus.isEligibleForAutoUpload,
uploadStatus.uploadWillPushChanges
)
uploadStatus.hasPendingMediaUpload ||
uploadStatus.isQueued ||
uploadStatus.isUploadingOrQueued -> UploadQueued
uploadStatus.isEligibleForAutoUpload -> UploadWaitingForConnection(postStatus)
else -> NothingToUpload
}
}
/**
* Copied from PostListItemUiStateHelper since the behavior is similar for the Page List UI State.
*/
sealed class PostUploadUiState {
data class UploadingMedia(val progress: Int) : PostUploadUiState()
data class UploadingPost(val isDraft: Boolean) : PostUploadUiState()
data class UploadFailed(
val error: UploadError,
val isEligibleForAutoUpload: Boolean,
val retryWillPushChanges: Boolean
) : PostUploadUiState()
data class UploadWaitingForConnection(val postStatus: PostStatus) : PostUploadUiState()
object UploadQueued : PostUploadUiState()
object NothingToUpload : PostUploadUiState()
}
}
| gpl-2.0 | 96cd05674753e8b3c02b9f28b02b2bae | 48.184615 | 119 | 0.731623 | 5.729391 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/HistoryListFragment.kt | 1 | 7147 | package org.wordpress.android.ui.posts
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.annotation.NonNull
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.HistoryListFragmentBinding
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.history.HistoryAdapter
import org.wordpress.android.ui.history.HistoryListItem
import org.wordpress.android.ui.history.HistoryListItem.Revision
import org.wordpress.android.util.WPSwipeToRefreshHelper
import org.wordpress.android.util.helpers.SwipeToRefreshHelper
import org.wordpress.android.viewmodel.history.HistoryViewModel
import org.wordpress.android.viewmodel.history.HistoryViewModel.HistoryListStatus
import javax.inject.Inject
class HistoryListFragment : Fragment(R.layout.history_list_fragment) {
private lateinit var swipeToRefreshHelper: SwipeToRefreshHelper
private lateinit var viewModel: HistoryViewModel
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
companion object {
private const val KEY_POST_LOCAL_ID = "key_post_local_id"
private const val KEY_SITE = "key_site"
fun newInstance(postId: Int, @NonNull site: SiteModel): HistoryListFragment {
val fragment = HistoryListFragment()
val bundle = Bundle()
bundle.putInt(KEY_POST_LOCAL_ID, postId)
bundle.putSerializable(KEY_SITE, site)
fragment.arguments = bundle
return fragment
}
}
interface HistoryItemClickInterface {
fun onHistoryItemClicked(revision: Revision, revisions: List<Revision>)
}
private fun onItemClicked(item: HistoryListItem) {
viewModel.onItemClicked(item)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(requireActivity().application as WordPress).component().inject(this)
viewModel = ViewModelProvider(this, viewModelFactory).get(HistoryViewModel::class.java)
}
override fun onAttach(context: Context) {
super.onAttach(context)
check(activity is HistoryItemClickInterface) {
"Parent activity has to implement HistoryItemClickInterface"
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val nonNullActivity = requireActivity()
with(HistoryListFragmentBinding.bind(view)) {
emptyRecyclerView.layoutManager = LinearLayoutManager(nonNullActivity, RecyclerView.VERTICAL, false)
emptyRecyclerView.setEmptyView(actionableEmptyView)
actionableEmptyView.button.setText(R.string.button_retry)
actionableEmptyView.button.setOnClickListener {
viewModel.onPullToRefresh()
}
swipeToRefreshHelper = WPSwipeToRefreshHelper.buildSwipeToRefreshHelper(swipeRefreshLayout) {
viewModel.onPullToRefresh()
}
(nonNullActivity.application as WordPress).component().inject(this@HistoryListFragment)
viewModel = ViewModelProvider(this@HistoryListFragment, viewModelFactory).get(HistoryViewModel::class.java)
viewModel.create(
localPostId = arguments?.getInt(KEY_POST_LOCAL_ID) ?: 0,
site = arguments?.get(KEY_SITE) as SiteModel
)
updatePostOrPageEmptyView()
setObservers()
}
}
private fun HistoryListFragmentBinding.updatePostOrPageEmptyView() {
actionableEmptyView.title.text = getString(R.string.history_empty_title)
actionableEmptyView.button.visibility = View.GONE
actionableEmptyView.subtitle.visibility = View.VISIBLE
}
private fun HistoryListFragmentBinding.reloadList(data: List<HistoryListItem>) {
setList(data)
}
private fun HistoryListFragmentBinding.setList(list: List<HistoryListItem>) {
val adapter: HistoryAdapter
if (emptyRecyclerView.adapter == null) {
adapter = HistoryAdapter(requireActivity(), this@HistoryListFragment::onItemClicked)
emptyRecyclerView.adapter = adapter
} else {
adapter = emptyRecyclerView.adapter as HistoryAdapter
}
adapter.updateList(list)
}
private fun HistoryListFragmentBinding.setObservers() {
viewModel.revisions.observe(viewLifecycleOwner, Observer {
reloadList(it ?: emptyList())
})
viewModel.listStatus.observe(viewLifecycleOwner, Observer { listStatus ->
listStatus?.let {
if (isAdded && view != null) {
swipeToRefreshHelper.isRefreshing = listStatus == HistoryListStatus.FETCHING
}
when (listStatus) {
HistoryListStatus.DONE -> {
updatePostOrPageEmptyView()
}
HistoryListStatus.FETCHING -> {
actionableEmptyView.title.setText(R.string.history_fetching_revisions)
actionableEmptyView.subtitle.visibility = View.GONE
actionableEmptyView.button.visibility = View.GONE
}
HistoryListStatus.NO_NETWORK -> {
actionableEmptyView.title.setText(R.string.no_network_title)
actionableEmptyView.subtitle.setText(R.string.no_network_message)
actionableEmptyView.subtitle.visibility = View.VISIBLE
actionableEmptyView.button.visibility = View.VISIBLE
}
HistoryListStatus.ERROR -> {
actionableEmptyView.title.setText(R.string.no_network_title)
actionableEmptyView.subtitle.setText(R.string.error_generic_network)
actionableEmptyView.subtitle.visibility = View.VISIBLE
actionableEmptyView.button.visibility = View.VISIBLE
}
}
}
})
viewModel.showDialog.observe(viewLifecycleOwner, Observer { showDialogItem ->
if (showDialogItem != null && showDialogItem.historyListItem is Revision) {
(activity as HistoryItemClickInterface).onHistoryItemClicked(
showDialogItem.historyListItem,
showDialogItem.revisionsList
)
}
})
viewModel.post.observe(viewLifecycleOwner, Observer { post ->
actionableEmptyView.subtitle.text = if (post?.isPage == true) {
getString(R.string.history_empty_subtitle_page)
} else {
getString(R.string.history_empty_subtitle_post)
}
})
}
}
| gpl-2.0 | 06256b529f3c7417ce935fdecea5f113 | 41.041176 | 119 | 0.662796 | 5.518919 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt | 1 | 1824 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtTryExpression
class LiftAssignmentOutOfTryFix(element: KtTryExpression) : KotlinQuickFixAction<KtTryExpression>(element) {
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("lift.assignment.out.of.try.expression")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
BranchedFoldingUtils.tryFoldToAssignment(element)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val expression = diagnostic.psiElement as? KtExpression ?: return null
val originalCatch = expression.parent.parent?.parent as? KtCatchClause ?: return null
val tryExpression = originalCatch.parent as? KtTryExpression ?: return null
if (BranchedFoldingUtils.getFoldableAssignmentNumber(tryExpression) < 1) return null
return LiftAssignmentOutOfTryFix(tryExpression)
}
}
} | apache-2.0 | c2d2d76aaabf530e85a359f81d245d60 | 47.026316 | 158 | 0.780154 | 5.010989 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/base/fe10/highlighting/KotlinBaseFe10HighlightingBundle.kt | 7 | 834 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.fe10.highlighting
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.util.AbstractKotlinBundle
@NonNls
private const val BUNDLE = "messages.KotlinBaseFe10HighlightingBundle"
object KotlinBaseFe10HighlightingBundle : AbstractKotlinBundle(BUNDLE) {
@Nls
@JvmStatic
fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
@Nls
@JvmStatic
fun htmlMessage(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params).withHtml()
} | apache-2.0 | 5108adbf40e7465b6f9605718f477160 | 40.75 | 144 | 0.786571 | 4.233503 | 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.