repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
androidx/androidx
|
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/node/MeasureAndLayoutDelegate.kt
|
3
|
22685
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.node
import androidx.compose.runtime.collection.mutableVectorOf
import androidx.compose.ui.layout.OnGloballyPositionedModifier
import androidx.compose.ui.node.LayoutNode.LayoutState.Idle
import androidx.compose.ui.node.LayoutNode.LayoutState.LayingOut
import androidx.compose.ui.node.LayoutNode.LayoutState.Measuring
import androidx.compose.ui.node.LayoutNode.LayoutState.LookaheadLayingOut
import androidx.compose.ui.node.LayoutNode.LayoutState.LookaheadMeasuring
import androidx.compose.ui.node.LayoutNode.UsageByParent.InLayoutBlock
import androidx.compose.ui.node.LayoutNode.UsageByParent.InMeasureBlock
import androidx.compose.ui.unit.Constraints
/**
* Keeps track of [LayoutNode]s which needs to be remeasured or relaid out.
*
* Use [requestRemeasure] to schedule remeasuring or [requestRelayout] to schedule relayout.
*
* Use [measureAndLayout] to perform scheduled actions and [dispatchOnPositionedCallbacks] to
* dispatch [OnGloballyPositionedModifier] callbacks for the nodes affected by the previous
* [measureAndLayout] execution.
*/
internal class MeasureAndLayoutDelegate(private val root: LayoutNode) {
/**
* LayoutNodes that need measure or layout.
*/
private val relayoutNodes = DepthSortedSet(Owner.enableExtraAssertions)
/**
* Whether any LayoutNode needs measure or layout.
*/
val hasPendingMeasureOrLayout get() = relayoutNodes.isNotEmpty()
/**
* Flag to indicate that we're currently measuring.
*/
private var duringMeasureLayout = false
/**
* Dispatches on positioned callbacks.
*/
private val onPositionedDispatcher = OnPositionedDispatcher()
/**
* List of listeners that must be called after layout has completed.
*/
private val onLayoutCompletedListeners = mutableVectorOf<Owner.OnLayoutCompletedListener>()
/**
* The current measure iteration. The value is incremented during the [measureAndLayout]
* execution. Some [measureAndLayout] executions will increment it more than once.
*/
var measureIteration: Long = 1L
get() {
require(duringMeasureLayout) {
"measureIteration should be only used during the measure/layout pass"
}
return field
}
private set
/**
* Stores the list of [LayoutNode]s scheduled to be remeasured in the next measure/layout pass.
* We were unable to mark them as needsRemeasure=true previously as this request happened
* during the previous measure/layout pass and they were already measured as part of it.
* See [requestRemeasure] for more details.
*/
private val postponedMeasureRequests = mutableVectorOf<PostponedRequest>()
private var rootConstraints: Constraints? = null
/**
* @param constraints The constraints to measure the root [LayoutNode] with
*/
fun updateRootConstraints(constraints: Constraints) {
if (rootConstraints != constraints) {
require(!duringMeasureLayout)
rootConstraints = constraints
root.markMeasurePending()
relayoutNodes.add(root)
}
}
private val consistencyChecker: LayoutTreeConsistencyChecker? =
if (Owner.enableExtraAssertions) {
LayoutTreeConsistencyChecker(
root,
relayoutNodes,
postponedMeasureRequests.asMutableList(),
)
} else {
null
}
/**
* Requests lookahead remeasure for this [layoutNode] and nodes affected by its measure result
*
* Note: This should only be called on a [LayoutNode] in the subtree defined in a
* LookaheadLayout. The caller is responsible for checking with [LayoutNode.mLookaheadScope]
* is valid (i.e. non-null) before calling this method.
*
* @return true if the [measureAndLayout] execution should be scheduled as a result
* of the request.
*/
fun requestLookaheadRemeasure(layoutNode: LayoutNode, forced: Boolean = false): Boolean {
check(layoutNode.mLookaheadScope != null) {
"Error: requestLookaheadRemeasure cannot be called on a node outside" +
" LookaheadLayout"
}
return when (layoutNode.layoutState) {
LookaheadMeasuring -> {
// requestLookaheadRemeasure has already been called for this node or
// we're currently measuring it, let's swallow.
false
}
Measuring, LookaheadLayingOut, LayingOut -> {
// requestLookaheadRemeasure is currently laying out and it is incorrect to
// request lookahead remeasure now, let's postpone it.
postponedMeasureRequests.add(
PostponedRequest(node = layoutNode, isLookahead = true, isForced = forced)
)
consistencyChecker?.assertConsistent()
false
}
Idle -> {
if (layoutNode.lookaheadMeasurePending && !forced) {
false
} else {
layoutNode.markLookaheadMeasurePending()
layoutNode.markMeasurePending()
if (layoutNode.isPlacedInLookahead == true ||
layoutNode.canAffectParentInLookahead
) {
if (layoutNode.parent?.lookaheadMeasurePending != true) {
relayoutNodes.add(layoutNode)
}
}
!duringMeasureLayout
}
}
}
}
/**
* Requests remeasure for this [layoutNode] and nodes affected by its measure result.
*
* @return true if the [measureAndLayout] execution should be scheduled as a result
* of the request.
*/
fun requestRemeasure(layoutNode: LayoutNode, forced: Boolean = false): Boolean =
when (layoutNode.layoutState) {
Measuring, LookaheadMeasuring -> {
// requestMeasure has already been called for this node or
// we're currently measuring it, let's swallow. example when it happens: we compose
// DataNode inside BoxWithConstraints, this calls onRequestMeasure on DataNode's
// parent, but this parent is BoxWithConstraints which is currently measuring.
false
}
LookaheadLayingOut, LayingOut -> {
// requestMeasure is currently laying out and it is incorrect to request remeasure
// now, let's postpone it.
postponedMeasureRequests.add(
PostponedRequest(node = layoutNode, isLookahead = false, isForced = forced)
)
consistencyChecker?.assertConsistent()
false
}
Idle -> {
if (layoutNode.measurePending && !forced) {
false
} else {
layoutNode.markMeasurePending()
if (layoutNode.isPlaced || layoutNode.canAffectParent) {
if (layoutNode.parent?.measurePending != true) {
relayoutNodes.add(layoutNode)
}
}
!duringMeasureLayout
}
}
}
/**
* Requests lookahead relayout for this [layoutNode] and nodes affected by its position.
*
* @return true if the [measureAndLayout] execution should be scheduled as a result
* of the request.
*/
fun requestLookaheadRelayout(layoutNode: LayoutNode, forced: Boolean = false): Boolean =
when (layoutNode.layoutState) {
LookaheadMeasuring, LookaheadLayingOut -> {
// Don't need to do anything else since the parent is already scheduled
// for a lookahead relayout (lookahead measure will trigger lookahead
// relayout), or lookahead layout is in process right now
consistencyChecker?.assertConsistent()
false
}
Measuring, LayingOut, Idle -> {
if ((layoutNode.lookaheadMeasurePending || layoutNode.lookaheadLayoutPending) &&
!forced
) {
// Don't need to do anything else since the parent is already scheduled
// for a lookahead relayout (lookahead measure will trigger lookahead
// relayout)
consistencyChecker?.assertConsistent()
false
} else {
// Mark both lookahead layout and layout as pending, as layout has a
// dependency on lookahead layout.
layoutNode.markLookaheadLayoutPending()
layoutNode.markLayoutPending()
if (layoutNode.isPlacedInLookahead == true) {
val parent = layoutNode.parent
if (parent?.lookaheadMeasurePending != true &&
parent?.lookaheadLayoutPending != true
) {
relayoutNodes.add(layoutNode)
}
}
!duringMeasureLayout
}
}
}
/**
* Requests relayout for this [layoutNode] and nodes affected by its position.
*
* @return true if the [measureAndLayout] execution should be scheduled as a result
* of the request.
*/
fun requestRelayout(layoutNode: LayoutNode, forced: Boolean = false): Boolean =
when (layoutNode.layoutState) {
Measuring, LookaheadMeasuring, LookaheadLayingOut, LayingOut -> {
// don't need to do anything else since the parent is already scheduled
// for a relayout (measure will trigger relayout), or is laying out right now
consistencyChecker?.assertConsistent()
false
}
Idle -> {
if (!forced && (layoutNode.measurePending || layoutNode.layoutPending)) {
// don't need to do anything else since the parent is already scheduled
// for a relayout (measure will trigger relayout), or is laying out right now
consistencyChecker?.assertConsistent()
false
} else {
layoutNode.markLayoutPending()
if (layoutNode.isPlaced) {
val parent = layoutNode.parent
if (parent?.layoutPending != true && parent?.measurePending != true) {
relayoutNodes.add(layoutNode)
}
}
!duringMeasureLayout
}
}
}
/**
* Request that [layoutNode] and children should call their position change callbacks.
*/
fun requestOnPositionedCallback(layoutNode: LayoutNode) {
onPositionedDispatcher.onNodePositioned(layoutNode)
}
/**
* @return true if the [LayoutNode] size has been changed.
*/
private fun doLookaheadRemeasure(layoutNode: LayoutNode, constraints: Constraints?): Boolean {
if (layoutNode.mLookaheadScope == null) return false
val lookaheadSizeChanged = if (constraints != null) {
layoutNode.lookaheadRemeasure(constraints)
} else {
layoutNode.lookaheadRemeasure()
}
val parent = layoutNode.parent
if (lookaheadSizeChanged && parent != null) {
if (parent.mLookaheadScope == null) {
requestRemeasure(parent)
} else if (layoutNode.measuredByParentInLookahead == InMeasureBlock) {
requestLookaheadRemeasure(parent)
} else if (layoutNode.measuredByParentInLookahead == InLayoutBlock) {
requestLookaheadRelayout(parent)
}
}
return lookaheadSizeChanged
}
private fun doRemeasure(layoutNode: LayoutNode, constraints: Constraints?): Boolean {
val sizeChanged = if (constraints != null) {
layoutNode.remeasure(constraints)
} else {
layoutNode.remeasure()
}
val parent = layoutNode.parent
if (sizeChanged && parent != null) {
if (layoutNode.measuredByParent == InMeasureBlock) {
requestRemeasure(parent)
} else if (layoutNode.measuredByParent == InLayoutBlock) {
requestRelayout(parent)
}
}
return sizeChanged
}
/**
* Iterates through all LayoutNodes that have requested layout and measures and lays them out
*/
fun measureAndLayout(onLayout: (() -> Unit)? = null): Boolean {
var rootNodeResized = false
performMeasureAndLayout {
if (relayoutNodes.isNotEmpty()) {
relayoutNodes.popEach { layoutNode ->
val sizeChanged = remeasureAndRelayoutIfNeeded(layoutNode)
if (layoutNode === root && sizeChanged) {
rootNodeResized = true
}
}
onLayout?.invoke()
}
}
callOnLayoutCompletedListeners()
return rootNodeResized
}
/**
* Only does measurement from the root without doing any placement. This is intended
* to be called to determine only how large the root is with minimal effort.
*/
fun measureOnly() {
performMeasureAndLayout {
recurseRemeasure(root)
}
}
/**
* Walks the hierarchy from [layoutNode] and remeasures [layoutNode] and any
* descendants that affect its size.
*/
private fun recurseRemeasure(layoutNode: LayoutNode) {
remeasureOnly(layoutNode)
layoutNode._children.forEach { child ->
if (child.measureAffectsParent) {
recurseRemeasure(child)
}
}
// The child measurement may have invalidated layoutNode's measurement
remeasureOnly(layoutNode)
}
fun measureAndLayout(layoutNode: LayoutNode, constraints: Constraints) {
require(layoutNode != root)
performMeasureAndLayout {
relayoutNodes.remove(layoutNode)
// we don't check for the layoutState as even if the node doesn't need remeasure
// it could be remeasured because the constraints changed.
val lookaheadSizeChanged = doLookaheadRemeasure(layoutNode, constraints)
doRemeasure(layoutNode, constraints)
if ((lookaheadSizeChanged || layoutNode.lookaheadLayoutPending) &&
layoutNode.isPlacedInLookahead == true
) {
layoutNode.lookaheadReplace()
}
if (layoutNode.layoutPending && layoutNode.isPlaced) {
layoutNode.replace()
onPositionedDispatcher.onNodePositioned(layoutNode)
}
}
callOnLayoutCompletedListeners()
}
private inline fun performMeasureAndLayout(block: () -> Unit) {
require(root.isAttached)
require(root.isPlaced)
require(!duringMeasureLayout)
// we don't need to measure any children unless we have the correct root constraints
if (rootConstraints != null) {
duringMeasureLayout = true
try {
block()
} finally {
duringMeasureLayout = false
}
consistencyChecker?.assertConsistent()
}
}
fun registerOnLayoutCompletedListener(listener: Owner.OnLayoutCompletedListener) {
onLayoutCompletedListeners += listener
}
private fun callOnLayoutCompletedListeners() {
onLayoutCompletedListeners.forEach { it.onLayoutComplete() }
onLayoutCompletedListeners.clear()
}
/**
* Does actual remeasure and relayout on the node if it is required.
* The [layoutNode] should be already removed from [relayoutNodes] before running it.
*
* @return true if the [LayoutNode] size has been changed.
*/
private fun remeasureAndRelayoutIfNeeded(layoutNode: LayoutNode): Boolean {
var sizeChanged = false
if (layoutNode.isPlaced ||
layoutNode.canAffectParent ||
layoutNode.isPlacedInLookahead == true ||
layoutNode.canAffectParentInLookahead ||
layoutNode.alignmentLinesRequired
) {
var lookaheadSizeChanged = false
if (layoutNode.lookaheadMeasurePending || layoutNode.measurePending) {
val constraints = if (layoutNode === root) rootConstraints!! else null
if (layoutNode.lookaheadMeasurePending) {
lookaheadSizeChanged = doLookaheadRemeasure(layoutNode, constraints)
}
sizeChanged = doRemeasure(layoutNode, constraints)
}
if ((lookaheadSizeChanged || layoutNode.lookaheadLayoutPending) &&
layoutNode.isPlacedInLookahead == true
) {
layoutNode.lookaheadReplace()
}
if (layoutNode.layoutPending && layoutNode.isPlaced) {
if (layoutNode === root) {
layoutNode.place(0, 0)
} else {
layoutNode.replace()
}
onPositionedDispatcher.onNodePositioned(layoutNode)
consistencyChecker?.assertConsistent()
}
// execute postponed `onRequestMeasure`
if (postponedMeasureRequests.isNotEmpty()) {
postponedMeasureRequests.forEach { request ->
if (request.node.isAttached) {
if (!request.isLookahead) {
requestRemeasure(request.node, request.isForced)
} else {
requestLookaheadRemeasure(request.node, request.isForced)
}
}
}
postponedMeasureRequests.clear()
}
}
return sizeChanged
}
/**
* Remeasures [layoutNode] if it has [LayoutNode.measurePending] or
* [LayoutNode.lookaheadMeasurePending].
*/
private fun remeasureOnly(layoutNode: LayoutNode) {
if (!layoutNode.measurePending && !layoutNode.lookaheadMeasurePending) {
return // nothing needs to be remeasured
}
val constraints = if (layoutNode === root) rootConstraints!! else null
if (layoutNode.lookaheadMeasurePending) {
doLookaheadRemeasure(layoutNode, constraints)
}
doRemeasure(layoutNode, constraints)
}
/**
* Makes sure the passed [layoutNode] and its subtree is remeasured and has the final sizes.
*
* The node or some of the nodes in its subtree can still be kept unmeasured if they are
* not placed and don't affect the parent size. See [requestRemeasure] for details.
*/
fun forceMeasureTheSubtree(layoutNode: LayoutNode) {
// if there is nothing in `relayoutNodes` everything is remeasured.
if (relayoutNodes.isEmpty()) {
return
}
// assert that it is executed during the `measureAndLayout` pass.
check(duringMeasureLayout)
// if this node is not yet measured this invocation shouldn't be needed.
require(!layoutNode.measurePending)
layoutNode.forEachChild { child ->
if (child.measurePending && relayoutNodes.remove(child)) {
remeasureAndRelayoutIfNeeded(child)
}
// if the child is still in NeedsRemeasure state then this child remeasure wasn't
// needed. it can happen for example when this child is not placed and can't affect
// the parent size. we can skip the whole subtree.
if (!child.measurePending) {
// run recursively for the subtree.
forceMeasureTheSubtree(child)
}
}
// if the child was resized during the remeasurement it could request a remeasure on
// the parent. we need to remeasure now as this function assumes the whole subtree is
// fully measured as a result of the invocation.
if (layoutNode.measurePending && relayoutNodes.remove(layoutNode)) {
remeasureAndRelayoutIfNeeded(layoutNode)
}
}
/**
* Dispatch [OnPositionedModifier] callbacks for the nodes affected by the previous
* [measureAndLayout] execution.
*
* @param forceDispatch true means the whole tree should dispatch the callback (for example
* when the global position of the Owner has been changed)
*/
fun dispatchOnPositionedCallbacks(forceDispatch: Boolean = false) {
if (forceDispatch) {
onPositionedDispatcher.onRootNodePositioned(root)
}
onPositionedDispatcher.dispatch()
}
/**
* Removes [node] from the list of LayoutNodes being scheduled for the remeasure/relayout as
* it was detached.
*/
fun onNodeDetached(node: LayoutNode) {
relayoutNodes.remove(node)
}
private val LayoutNode.measureAffectsParent
get() = (measuredByParent == InMeasureBlock ||
layoutDelegate.alignmentLinesOwner.alignmentLines.required)
private val LayoutNode.canAffectParent
get() = measurePending && measureAffectsParent
private val LayoutNode.canAffectParentInLookahead
get() = lookaheadLayoutPending &&
(measuredByParentInLookahead == InMeasureBlock ||
layoutDelegate.lookaheadAlignmentLinesOwner?.alignmentLines?.required == true)
class PostponedRequest(val node: LayoutNode, val isLookahead: Boolean, val isForced: Boolean)
}
|
apache-2.0
|
a362f5598e181f5183d9f1edc6122b29
| 39.80036 | 99 | 0.606877 | 5.374319 | false | false | false | false |
androidx/androidx
|
room/room-compiler/src/main/kotlin/androidx/room/solver/binderprovider/RxQueryResultBinderProvider.kt
|
3
|
2603
|
/*
* Copyright (C) 2017 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.room.solver.binderprovider
import androidx.room.compiler.processing.XRawType
import androidx.room.compiler.processing.XType
import androidx.room.processor.Context
import androidx.room.solver.ObservableQueryResultBinderProvider
import androidx.room.solver.RxType
import androidx.room.solver.query.result.QueryResultAdapter
import androidx.room.solver.query.result.QueryResultBinder
import androidx.room.solver.query.result.RxQueryResultBinder
class RxQueryResultBinderProvider private constructor(
context: Context,
private val rxType: RxType
) : ObservableQueryResultBinderProvider(context) {
private val rawRxType: XRawType? by lazy {
context.processingEnv.findType(rxType.className)?.rawType
}
override fun extractTypeArg(declared: XType): XType = declared.typeArguments.first()
override fun create(
typeArg: XType,
resultAdapter: QueryResultAdapter?,
tableNames: Set<String>
): QueryResultBinder {
return RxQueryResultBinder(
rxType = rxType,
typeArg = typeArg,
queryTableNames = tableNames,
adapter = resultAdapter
)
}
override fun matches(declared: XType): Boolean =
declared.typeArguments.size == 1 && matchesRxType(declared)
private fun matchesRxType(declared: XType): Boolean {
if (rawRxType == null) {
return false
}
return declared.rawType.isAssignableFrom(rawRxType!!)
}
companion object {
fun getAll(context: Context) = listOf(
RxType.RX2_FLOWABLE,
RxType.RX2_OBSERVABLE,
RxType.RX3_FLOWABLE,
RxType.RX3_OBSERVABLE
).map {
RxQueryResultBinderProvider(context, it).requireArtifact(
context = context,
requiredType = it.version.rxRoomClassName,
missingArtifactErrorMsg = it.version.missingArtifactMessage
)
}
}
}
|
apache-2.0
|
93e4ff3bd88890eeb27129eb9732e979
| 33.72 | 88 | 0.694967 | 4.648214 | false | false | false | false |
djkovrik/YapTalker
|
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/forumslist/ForumsFragment.kt
|
1
|
3229
|
package com.sedsoftware.yaptalker.presentation.feature.forumslist
import android.os.Bundle
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.View
import com.arellomobile.mvp.presenter.InjectPresenter
import com.arellomobile.mvp.presenter.ProvidePresenter
import com.jakewharton.rxbinding2.support.v4.widget.RxSwipeRefreshLayout
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.common.annotation.LayoutResource
import com.sedsoftware.yaptalker.presentation.base.BaseFragment
import com.sedsoftware.yaptalker.presentation.base.enums.lifecycle.FragmentLifecycle
import com.sedsoftware.yaptalker.presentation.base.enums.navigation.NavigationSection
import com.sedsoftware.yaptalker.presentation.extensions.setIndicatorColorScheme
import com.sedsoftware.yaptalker.presentation.extensions.string
import com.sedsoftware.yaptalker.presentation.feature.forumslist.adapter.ForumsAdapter
import com.sedsoftware.yaptalker.presentation.model.base.ForumModel
import com.uber.autodispose.kotlin.autoDisposable
import kotlinx.android.synthetic.main.fragment_forums_list.forums_list
import kotlinx.android.synthetic.main.fragment_forums_list.forums_list_refresh_layout
import javax.inject.Inject
@LayoutResource(value = R.layout.fragment_forums_list)
class ForumsFragment : BaseFragment(), ForumsView {
companion object {
fun getNewInstance() = ForumsFragment()
}
@Inject
lateinit var forumsAdapter: ForumsAdapter
@Inject
@InjectPresenter
lateinit var presenter: ForumsPresenter
@ProvidePresenter
fun provideForumsPresenter() = presenter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(forums_list) {
val linearLayout = LinearLayoutManager(context)
layoutManager = linearLayout
adapter = forumsAdapter
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
setHasFixedSize(true)
}
forums_list_refresh_layout.setIndicatorColorScheme()
subscribeViews()
}
override fun showLoadingIndicator() {
forums_list_refresh_layout.isRefreshing = true
}
override fun hideLoadingIndicator() {
forums_list_refresh_layout.isRefreshing = false
}
override fun showErrorMessage(message: String) {
messagesDelegate.showMessageError(message)
}
override fun updateCurrentUiState() {
setCurrentAppbarTitle(string(R.string.nav_drawer_forums))
setCurrentNavDrawerItem(NavigationSection.FORUMS)
}
override fun appendForumItem(item: ForumModel) {
forumsAdapter.addForumsListItem(item)
}
override fun clearForumsList() {
forumsAdapter.clearForumsList()
}
private fun subscribeViews() {
RxSwipeRefreshLayout.refreshes(forums_list_refresh_layout)
.autoDisposable(event(FragmentLifecycle.DESTROY))
.subscribe({
presenter.loadForumsList()
}, { e: Throwable ->
e.message?.let { showErrorMessage(it) }
})
}
}
|
apache-2.0
|
f52af3c9e88d847a49e5edf55c6aecd7
| 34.483516 | 93 | 0.752555 | 4.952454 | false | false | false | false |
GunoH/intellij-community
|
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vscode/parsers/StateDatabaseParser.kt
|
3
|
2061
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.customize.transferSettings.providers.vscode.parsers
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.JsonNodeType
import com.fasterxml.jackson.databind.node.ObjectNode
import com.intellij.ide.customize.transferSettings.models.Settings
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.io.FileUtil
import java.io.File
import java.sql.Connection
import java.sql.DriverManager
private val logger = logger<StateDatabaseParser>()
class StateDatabaseParser(private val settings: Settings) {
private val recentsKey = "history.recentlyOpenedPathsList"
lateinit var connection: Connection
fun process(file: File) {
try {
Class.forName("org.sqlite.JDBC")
connection = DriverManager.getConnection("jdbc:sqlite:" + FileUtil.toSystemIndependentName(file.path))
parseRecents()
}
catch (t: Throwable) {
logger.warn(t)
}
}
private fun parseRecents() {
val recentProjectsRaw = getKey(recentsKey) ?: return
val root = ObjectMapper(JsonFactory().enable(JsonParser.Feature.ALLOW_COMMENTS)).readTree(recentProjectsRaw)
as? ObjectNode
?: error("Unexpected JSON data; expected: ${JsonNodeType.OBJECT}")
val paths = (root["entries"] as ArrayNode).mapNotNull { it["folderUri"]?.textValue() }
paths.forEach { uri ->
val res = StorageParser.parsePath(uri)
if (res != null) {
settings.recentProjects.add(res)
}
}
}
private fun getKey(key: String): String? {
val query = "SELECT value FROM ItemTable WHERE key is '$key' LIMIT 1"
val res = connection.createStatement().executeQuery(query)
if (!res.next()) {
return null
}
return res.getString("value")
}
}
|
apache-2.0
|
9d152df9198c43c1e2ff0bcf0887d499
| 32.258065 | 120 | 0.728287 | 4.197556 | false | false | false | false |
nonylene/PhotoLinkViewer-Core
|
photolinkviewer-core/src/main/java/net/nonylene/photolinkviewer/core/fragment/WifiFragment.kt
|
1
|
3070
|
package net.nonylene.photolinkviewer.core.fragment
import android.content.Intent
import android.os.Bundle
import android.preference.ListPreference
import net.nonylene.photolinkviewer.core.R
import net.nonylene.photolinkviewer.core.dialog.BatchDialogFragment
class WifiFragment : PreferenceSummaryFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.plv_core_quality_preference_wifi)
// on click batch
findPreference("quality_wifi_batch").setOnPreferenceClickListener {
// batch dialog
BatchDialogFragment().apply {
setTargetFragment(this@WifiFragment, 1)
show([email protected], "batch")
}
false
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// batch dialog listener
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
1 -> batchSelected(resultCode)
}
}
private fun batchSelected(resultCode: Int) {
// change preferences in a lump
val flickrPreference = findPreference("plv_core_flickr_quality_wifi") as ListPreference
val twitterPreference = findPreference("plv_core_twitter_quality_wifi") as ListPreference
val twipplePreference = findPreference("plv_core_twipple_quality_wifi") as ListPreference
val imglyPreference = findPreference("plv_core_imgly_quality_wifi") as ListPreference
val instagramPreference = findPreference("plv_core_instagram_quality_wifi") as ListPreference
val nicoPreference = findPreference("plv_core_nicoseiga_quality_wifi") as ListPreference
val tumblrPreference = findPreference("plv_core_tumblr_quality_wifi") as ListPreference
when (resultCode) {
0 -> {
flickrPreference.value = "original"
twitterPreference.value = "original"
twipplePreference.value = "original"
imglyPreference.value = "full"
instagramPreference.value = "large"
nicoPreference.value = "original"
tumblrPreference.value = "original"
}
1 -> {
flickrPreference.value = "large"
twitterPreference.value = "large"
twipplePreference.value = "large"
imglyPreference.value = "large"
instagramPreference.value = "large"
nicoPreference.value = "large"
tumblrPreference.value = "large"
}
2 -> {
flickrPreference.value = "medium"
twitterPreference.value = "medium"
twipplePreference.value = "large"
imglyPreference.value = "medium"
instagramPreference.value = "medium"
nicoPreference.value = "medium"
tumblrPreference.value = "medium"
}
}
}
}
|
gpl-2.0
|
6d63fa8ee71cb9239964a221c35be3d8
| 41.054795 | 101 | 0.626059 | 5.091211 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/intentions/HLUseExpressionBodyIntention.kt
|
1
|
6597
|
// 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.fir.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.api.applicator.HLApplicatorInput
import org.jetbrains.kotlin.idea.api.applicator.applicator
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.fir.api.AbstractHLIntention
import org.jetbrains.kotlin.idea.fir.api.applicator.HLApplicabilityRange
import org.jetbrains.kotlin.idea.fir.api.applicator.HLApplicatorInputProvider
import org.jetbrains.kotlin.idea.fir.api.applicator.applicabilityRanges
import org.jetbrains.kotlin.idea.fir.api.applicator.inputProvider
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class HLUseExpressionBodyIntention : AbstractHLIntention<KtDeclarationWithBody, HLUseExpressionBodyIntention.Input>(
KtDeclarationWithBody::class, applicator
) {
class Input : HLApplicatorInput
override val applicabilityRange: HLApplicabilityRange<KtDeclarationWithBody> =
applicabilityRanges { declaration: KtDeclarationWithBody ->
val returnExpression = declaration.singleReturnExpressionOrNull ?: return@applicabilityRanges emptyList()
val resultTextRanges = mutableListOf(TextRange(0, returnExpression.returnKeyword.endOffset - declaration.startOffset))
// Adding applicability to the end of the declaration block
val rBraceTextRange = declaration.rBraceOffSetTextRange ?: return@applicabilityRanges resultTextRanges
resultTextRanges.add(rBraceTextRange)
return@applicabilityRanges resultTextRanges
}
override val inputProvider: HLApplicatorInputProvider<KtDeclarationWithBody, Input> = inputProvider { Input() }
override fun skipProcessingFurtherElementsAfter(element: PsiElement) = false
companion object {
val applicator = applicator<KtDeclarationWithBody, Input> {
familyAndActionName(KotlinBundle.lazyMessage(("convert.body.to.expression")))
isApplicableByPsi { declaration ->
// Check if either property accessor or named function
if (declaration !is KtNamedFunction && declaration !is KtPropertyAccessor) return@isApplicableByPsi false
// Check if a named function has explicit type
if (declaration is KtNamedFunction && !declaration.hasDeclaredReturnType()) return@isApplicableByPsi false
// Check if function has block with single non-empty KtReturnExpression
val returnedExpression = declaration.singleReturnedExpressionOrNull ?: return@isApplicableByPsi false
// Check if the returnedExpression actually always returns (early return is possible)
// TODO: take into consideration other cases (???)
if (returnedExpression.anyDescendantOfType<KtReturnExpression>(
canGoInside = { it !is KtFunctionLiteral && it !is KtNamedFunction && it !is KtPropertyAccessor }))
return@isApplicableByPsi false
true
}
applyToWithEditorRequired { declaration, _, _, editor ->
val newFunctionBody = declaration.replaceWithPreservingComments()
editor.correctRightMargin(declaration, newFunctionBody)
if (declaration is KtNamedFunction) editor.selectFunctionColonType(declaration)
}
}
private fun KtDeclarationWithBody.replaceWithPreservingComments(): KtExpression {
val bodyBlock = bodyBlockExpression ?: return this
val returnedExpression = singleReturnedExpressionOrNull ?: return this
val commentSaver = CommentSaver(bodyBlock)
val factory = KtPsiFactory(this)
val eq = addBefore(factory.createEQ(), bodyBlockExpression)
addAfter(factory.createWhiteSpace(), eq)
val newBody = bodyBlock.replaced(returnedExpression)
commentSaver.restore(newBody)
return newBody
}
/**
* This function guarantees that the function with its old body replaced by returned expression
* will have this expression placed on the next line to the function's signature or property accessor's 'get() =' statement
* in case it goes beyond IDEA editor's right margin
* @param[declaration] the PSI element used as an anchor, as no indexes are built for newly generated body yet
* @param[newBody] the new "= <returnedExpression>" like body, which replaces the old one
*/
private fun Editor.correctRightMargin(
declaration: KtDeclarationWithBody, newBody: KtExpression
) {
val kotlinFactory = KtPsiFactory(declaration)
val startOffset = newBody.startOffset
val startLine = document.getLineNumber(startOffset)
val rightMargin = settings.getRightMargin(project)
if (document.getLineEndOffset(startLine) - document.getLineStartOffset(startLine) >= rightMargin) {
declaration.addBefore(kotlinFactory.createNewLine(), newBody)
}
}
private fun Editor.selectFunctionColonType(newFunctionBody: KtNamedFunction) {
val colon = newFunctionBody.colon ?: return
val typeReference = newFunctionBody.typeReference ?: return
selectionModel.setSelection(colon.startOffset, typeReference.endOffset)
caretModel.moveToOffset(typeReference.endOffset)
}
private val KtDeclarationWithBody.singleReturnExpressionOrNull: KtReturnExpression?
get() = bodyBlockExpression?.statements?.singleOrNull() as? KtReturnExpression
private val KtDeclarationWithBody.singleReturnedExpressionOrNull: KtExpression?
get() = singleReturnExpressionOrNull?.returnedExpression
private val KtDeclarationWithBody.rBraceOffSetTextRange: TextRange?
get() {
val rightBlockBodyBrace = bodyBlockExpression?.rBrace ?: return null
return rightBlockBodyBrace.textRange.shiftLeft(startOffset)
}
}
}
|
apache-2.0
|
73e5ff190d7615989c3ea87c8b172bb1
| 49.366412 | 158 | 0.716689 | 5.827739 | false | false | false | false |
GunoH/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsEditorTabFilesManager.kt
|
2
|
4121
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.changes
import com.intellij.diff.editor.DiffContentVirtualFile
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.fileEditor.impl.EditorWindow
import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.messages.Topic
@Service(Service.Level.APP)
@State(name = "VcsEditorTab.Settings", storages = [(Storage(value = "vcs.xml"))])
class VcsEditorTabFilesManager :
SimplePersistentStateComponent<VcsEditorTabFilesManager.State>(State()),
Disposable {
class State : BaseState() {
var openInNewWindow by property(false)
}
init {
val messageBus = ApplicationManager.getApplication().messageBus
messageBus.connect(this).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
//currently shouldOpenInNewWindow is bound only to diff files
if (file is DiffContentVirtualFile && source is FileEditorManagerEx) {
val isOpenInNewWindow = source.findFloatingWindowForFile(file)?.let {
it.tabCount == 1
} ?: false
shouldOpenInNewWindow = isOpenInNewWindow
messageBus.syncPublisher(VcsEditorTabFilesListener.TOPIC).shouldOpenInNewWindowChanged(file, isOpenInNewWindow)
}
}
})
}
var shouldOpenInNewWindow: Boolean
get() = state.openInNewWindow
private set(value) {
state.openInNewWindow = value
}
fun openFile(project: Project,
file: VirtualFile,
focusEditor: Boolean,
openInNewWindow: Boolean,
shouldCloseFile: Boolean): Array<out FileEditor> {
val editorManager = FileEditorManager.getInstance(project) as FileEditorManagerImpl
if (shouldCloseFile && editorManager.isFileOpen(file)) {
editorManager.closeFile(file)
}
shouldOpenInNewWindow = openInNewWindow
return openFile(project, file, focusEditor)
}
fun openFile(project: Project, file: VirtualFile, focusEditor: Boolean): Array<out FileEditor> {
val editorManager = FileEditorManager.getInstance(project) as FileEditorManagerImpl
if (editorManager.isFileOpen(file)) {
editorManager.selectAndFocusEditor(file, focusEditor)
return emptyArray()
}
if (shouldOpenInNewWindow) {
return editorManager.openFileInNewWindow(file).first
}
else {
return editorManager.openFile(file, focusEditor, true)
}
}
private fun FileEditorManagerImpl.selectAndFocusEditor(file: VirtualFile, focusEditor: Boolean) {
val window = windows.find { it.isFileOpen(file) } ?: return
val composite = window.getComposite(file) ?: return
window.setSelectedComposite(composite, focusEditor)
if (focusEditor) {
window.requestFocus(true)
window.toFront()
}
}
override fun dispose() {}
companion object {
@JvmStatic
fun getInstance(): VcsEditorTabFilesManager = service()
@JvmStatic
fun FileEditorManagerEx.findFloatingWindowForFile(file: VirtualFile): EditorWindow? {
return windows.find { it.owner.isFloating && it.isFileOpen(file) }
}
}
}
interface VcsEditorTabFilesListener {
@RequiresEdt
fun shouldOpenInNewWindowChanged(file: VirtualFile, shouldOpenInNewWindow: Boolean)
companion object {
@JvmField
val TOPIC: Topic<VcsEditorTabFilesListener> =
Topic(VcsEditorTabFilesListener::class.java, Topic.BroadcastDirection.NONE, true)
}
}
|
apache-2.0
|
b234396433c6f66b550d3ad31ba67475
| 35.469027 | 122 | 0.747149 | 4.731343 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/fir/testData/quickDoc/OnEnumUsage.kt
|
4
|
372
|
/**
* Enum of 1, 2
*/
enum class SomeEnum(val i: Int) {
One(1), Two(2);
}
fun use() {
Some<caret>Enum.One
}
//INFO: <div class='definition'><pre>enum class SomeEnum</pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Enum of 1, 2</p></div><table class='sections'></table><div class='bottom'><icon src="file"/> OnEnumUsage.kt<br/></div>
|
apache-2.0
|
7e1e4eb6d835e27d9e8e5663f1c9551b
| 30 | 251 | 0.629032 | 2.883721 | false | false | false | false |
smmribeiro/intellij-community
|
platform/script-debugger/protocol/protocol-reader/src/PrimitiveValueReader.kt
|
37
|
1318
|
package org.jetbrains.protocolReader
internal open class PrimitiveValueReader(val className: String, val defaultValue: String? = null, private val asRawString: Boolean = false, private val nullable: Boolean = false) : ValueReader() {
private val readPostfix: String
init {
if (Character.isLowerCase(className.get(0))) {
readPostfix = "${Character.toUpperCase(className.get(0))}${className.substring(1)}"
}
else {
readPostfix = if (asRawString) ("Raw$className") else className
}
}
override fun writeReadCode(scope: ClassScope, subtyping: Boolean, out: TextOutput) {
if (asRawString) {
out.append("readRawString(")
addReaderParameter(subtyping, out)
out.append(')')
}
else {
addReaderParameter(subtyping, out)
out.append(".next");
if (nullable) {
out.append("Nullable");
}
out.append(readPostfix).append("()")
}
}
override fun appendFinishedValueTypeName(out: TextOutput) {
out.append(className)
}
override fun writeArrayReadCode(scope: ClassScope, subtyping: Boolean, out: TextOutput) {
if (readPostfix == "String") {
out.append("nextList")
}
else {
out.append("read").append(readPostfix).append("Array")
}
out.append('(').append(READER_NAME).append(')')
}
}
|
apache-2.0
|
5fa099f4add6c48d76f288cfe1a71d8f
| 28.954545 | 196 | 0.656297 | 4.170886 | false | false | false | false |
vnesek/nmote-jwt-issuer
|
src/main/kotlin/com/nmote/jwti/web/AuthorizationController.kt
|
1
|
4072
|
/*
* Copyright 2017. Vjekoslav Nesek
* 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.nmote.jwti.web
import com.nmote.jwti.model.*
import com.nmote.jwti.repository.AppRepository
import com.nmote.jwti.repository.UserRepository
import com.nmote.jwti.service.ScopeService
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import java.util.*
@Controller
@RequestMapping("oauth/token")
class AuthorizationController(
val users: UserRepository,
val apps: AppRepository,
val scopes: ScopeService
) {
fun String.basicAuthorization(): Pair<String, String> {
val (type, encoded) = split(' ')
if (!type.equals("basic", true)) throw IllegalArgumentException("expected basic authorization: $type")
val decoded = String(Base64.getDecoder().decode(encoded))
val (username, password) = decoded.split(':', limit = 2)
return Pair(username, password)
}
fun authorizeClient(request: OAuth2Request, authorization: String?): Pair<App, Client> {
authorization?.basicAuthorization()?.let { request.client_id = it.first; request.client_secret = it.second }
val clientId = request.client_id ?: throw OAuthException(OAuthError.invalid_request)
val (app, client) = apps[clientId] ?: throw OAuthException(OAuthError.invalid_request)
if (client.clientSecret != request.client_secret) throw OAuthException(OAuthError.invalid_grant)
return Pair(app, client)
}
@RequestMapping(params = ["grant_type=password"])
@ResponseBody
fun resourceOwnerPasswordCredentials(request: OAuth2Request, @RequestHeader(value = "Authorization", required = false) authorization: String?): Map<String, *> {
val (app, client) = authorizeClient(request, authorization)
val username = request.username ?: throw OAuthException(OAuthError.invalid_request)
val user = users.findByUsername(username).orElseThrow { OAuthException(OAuthError.invalid_grant) }
if (user.password != request.password) throw OAuthException(OAuthError.invalid_grant)
// Determine expires
val expiresIn = client.expiresIn ?: 6000
// Determine scope
val scope = scopes.scopeFor(user, app)
val jws = issueToken(
user,
app,
scope,
apps.url,
expiresIn = expiresIn)
return mapOf(
"access_token" to jws,
"expires_in" to expiresIn,
"token_type" to "bearer",
"scope" to scope
)
}
@RequestMapping(params = ["grant_type=client_credentials"])
@ResponseBody
fun clientCredentials(request: OAuth2Request, @RequestHeader(value = "Authorization", required = false) authorization: String?): Map<String, *> {
val (app, client) = authorizeClient(request, authorization)
// Determine expires
val expiresIn = client.expiresIn ?: 6000
// Determine scope
val scope = client.roles
val user = User()
user.username = client.clientId
val jws = issueToken(
user,
app,
scope,
apps.url,
expiresIn = expiresIn)
return mapOf(
"access_token" to jws,
"expires_in" to expiresIn,
"token_type" to "bearer",
"scope" to scope
)
}
}
|
apache-2.0
|
17d3cb91b694ea511d6619d393758d5d
| 36.366972 | 164 | 0.666994 | 4.397408 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/settings/globalcode/GlobalScriptingViewState.kt
|
1
|
515
|
package ch.rmy.android.http_shortcuts.activities.settings.globalcode
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
import ch.rmy.android.http_shortcuts.data.models.ShortcutModel
import ch.rmy.android.http_shortcuts.data.models.VariableModel
data class GlobalScriptingViewState(
val dialogState: DialogState? = null,
val globalCode: String = "",
val saveButtonVisible: Boolean = false,
val variables: List<VariableModel>? = null,
val shortcuts: List<ShortcutModel>? = null,
)
|
mit
|
54ff3d72a80cb270d5f934a8a217559a
| 38.615385 | 68 | 0.782524 | 4.12 | false | false | false | false |
aurae/PermissionsDispatcher
|
processor/src/main/kotlin/permissions/dispatcher/processor/util/Helpers.kt
|
1
|
2895
|
package permissions.dispatcher.processor.util
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.TypeName
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.processor.ELEMENT_UTILS
import permissions.dispatcher.processor.RuntimePermissionsElement
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.type.TypeMirror
/**
* Class Reference to the kotlin.Metadata annotation class,
* used by the processor to tell apart Kotlin from Java files during code generation.
*/
val kotlinMetadataClass: Class<Annotation>? by lazy {
try {
@Suppress("UNCHECKED_CAST")
Class.forName("kotlin.Metadata") as Class<Annotation>
} catch (e: Throwable) {
// Java-only environment, or outdated Kotlin version
null
}
}
fun typeMirrorOf(className: String): TypeMirror = ELEMENT_UTILS.getTypeElement(className).asType()
fun typeNameOf(it: Element): TypeName = TypeName.get(it.asType())
fun requestCodeFieldName(e: ExecutableElement) = "$GEN_REQUESTCODE_PREFIX${e.simpleString().trimDollarIfNeeded().toUpperCase()}"
fun permissionFieldName(e: ExecutableElement) = "$GEN_PERMISSION_PREFIX${e.simpleString().trimDollarIfNeeded().toUpperCase()}"
fun pendingRequestFieldName(e: ExecutableElement) = "$GEN_PENDING_PREFIX${e.simpleString().trimDollarIfNeeded().toUpperCase()}"
fun WithPermissionCheckMethodName(e: ExecutableElement) = "${e.simpleString().trimDollarIfNeeded()}$GEN_WITH_PERMISSION_CHECK_SUFFIX"
fun permissionRequestTypeName(rpe: RuntimePermissionsElement, e: ExecutableElement) =
"${rpe.inputClassName}${e.simpleString().trimDollarIfNeeded().capitalize()}$GEN_PERMISSIONREQUEST_SUFFIX"
fun <A : Annotation> findMatchingMethodForNeeds(needsElement: ExecutableElement, otherElements: List<ExecutableElement>, annotationType: Class<A>): ExecutableElement? {
val value: List<String> = needsElement.getAnnotation(NeedsPermission::class.java).permissionValue()
return otherElements.firstOrNull {
it.getAnnotation(annotationType).permissionValue() == value
}
}
fun varargsParametersCodeBlock(needsElement: ExecutableElement): CodeBlock {
val varargsCall = CodeBlock.builder()
needsElement.parameters.forEachIndexed { i, it ->
varargsCall.add("\$L", it.simpleString())
if (i < needsElement.parameters.size - 1) {
varargsCall.add(", ")
}
}
return varargsCall.build()
}
fun varargsKtParametersCodeBlock(needsElement: ExecutableElement): com.squareup.kotlinpoet.CodeBlock {
val varargsCall = com.squareup.kotlinpoet.CodeBlock.builder()
needsElement.parameters.forEachIndexed { i, it ->
varargsCall.add("\$L", it.simpleString())
if (i < needsElement.parameters.size - 1) {
varargsCall.add(", ")
}
}
return varargsCall.build()
}
|
apache-2.0
|
e9f8769166ea52d5ca432f32a9ac2a90
| 41.573529 | 168 | 0.748877 | 4.453846 | false | false | false | false |
alexstyl/Memento-Namedays
|
android_mobile/src/main/java/com/alexstyl/specialdates/person/BottomSheetIntentDialog.kt
|
3
|
3573
|
package com.alexstyl.specialdates.person
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.BottomSheetDialog
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.widget.TextView
import com.alexstyl.specialdates.R
import com.alexstyl.specialdates.ui.base.MementoDialog
import com.alexstyl.specialdates.ui.widget.SpacesItemDecoration
import com.novoda.notils.caster.Classes
import com.novoda.notils.caster.Views.findById
class BottomSheetIntentDialog : MementoDialog() {
companion object {
private const val KEY_INTENTS = "key:intents"
private const val KEY_TITLE = "key:title"
fun newIntent(title: String, intents: ArrayList<Intent>): BottomSheetIntentDialog {
return BottomSheetIntentDialog().apply {
val bundle = Bundle()
bundle.putParcelableArrayList(KEY_INTENTS, intents)
bundle.putString(KEY_TITLE, title)
this.arguments = bundle
}
}
}
lateinit var listener: BottomSheetIntentListener
@Suppress("OverridingDeprecatedMember", "DEPRECATION")
override fun onAttach(activity: Activity?) {
super.onAttach(activity)
this.listener = Classes.from(activity)
}
@Suppress("UNCHECKED_CAST")
@SuppressLint("InflateParams")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = activity
val dialog = BottomSheetDialog(context!!)
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(R.layout.dialog_bottom_dialog, null, false)
val title = view.findViewById<TextView>(R.id.bottom_sheet_title)
title.text = arguments?.getString(KEY_TITLE)
val grid = findById<RecyclerView>(view, R.id.bottom_sheet_grid)
val gridLayoutManager = GridLayoutManager(context, resources.getInteger(R.integer.bottom_sheet_span_count))
grid.addItemDecoration(SpacesItemDecoration(
resources.getDimensionPixelSize(R.dimen.add_event_image_option_vertical),
gridLayoutManager.spanCount
))
grid.layoutManager = gridLayoutManager
val intents = arguments?.get(KEY_INTENTS) as ArrayList<Intent>
val createViewModelsFor = createViewModelsFor(intents)
val adapter = BottomSheetIntentAdapter(listener, createViewModelsFor)
grid.adapter = adapter
dialog.setContentView(view)
return dialog
}
private fun createViewModelsFor(intents: List<Intent>): List<IntentOptionViewModel> {
val packageManager = context!!.packageManager
val viewModels = ArrayList<IntentOptionViewModel>(intents.size)
for (intent in intents) {
val resolveInfos = packageManager.queryIntentActivities(intent, 0)
for (resolveInfo in resolveInfos) {
val icon = resolveInfo.loadIcon(packageManager)
val label = resolveInfo.loadLabel(packageManager).toString()
val launchingIntent = Intent(intent.action)
launchingIntent.data = intent.data
launchingIntent.setClassName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name)
viewModels.add(IntentOptionViewModel(icon, label, launchingIntent))
}
}
return viewModels
}
}
|
mit
|
75fe8237202d06d17038fbd123a7b060
| 38.7 | 115 | 0.703331 | 5.039492 | false | false | false | false |
aosp-mirror/platform_frameworks_support
|
buildSrc/src/main/kotlin/androidx/build/gmaven/GMavenVersionChecker.kt
|
1
|
6935
|
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.gmaven
import androidx.build.Version
import groovy.util.XmlSlurper
import groovy.util.slurpersupport.Node
import groovy.util.slurpersupport.NodeChild
import org.gradle.api.GradleException
import org.gradle.api.logging.Logger
import java.io.FileNotFoundException
import java.io.IOException
/**
* Queries maven.google.com to get the version numbers for each artifact.
* Due to the structure of maven.google.com, a new query is necessary for each group.
*
* @param logger Logger of the root project. No reason to create multiple instances of this.
*/
class GMavenVersionChecker(private val logger: Logger) {
private val versionCache: MutableMap<String, GroupVersionData> = HashMap()
/**
* Checks whether the given artifact is already on maven.google.com.
*
* @param group The project group on maven
* @param artifactName The artifact name on maven
* @param version The version on maven
* @return true if the artifact is already on maven.google.com
*/
fun isReleased(group: String, artifactName: String, version: String): Boolean {
return getVersions(group, artifactName)?.contains(Version(version)) ?: false
}
/**
* Return the available versions on maven.google.com for a given artifact
*
* @param group The group id of the artifact
* @param artifactName The name of the artifact
* @return The set of versions that are available on maven.google.com. Null if artifact is not
* available.
*/
private fun getVersions(group: String, artifactName: String): Set<Version>? {
val groupData = getVersionData(group)
return groupData?.artifacts?.get(artifactName)?.versions
}
/**
* Returns the version data for each artifact in a given group.
* <p>
* If data is not cached, this will make a web request to get it.
*
* @param group The group to query
* @return A data class which has the versions for each artifact
*/
private fun getVersionData(group: String): GroupVersionData? {
return versionCache.getOrMaybePut(group) {
fetchGroup(group, DEFAULT_RETRY_LIMIT)
}
}
/**
* Fetches the group version information from maven.google.com
*
* @param group The group name to fetch
* @param retryCount Number of times we'll retry before failing
* @return GroupVersionData that has the data or null if it is a new item.
*/
private fun fetchGroup(group: String, retryCount: Int): GroupVersionData? {
val url = buildGroupUrl(group)
for (run in 0..retryCount) {
logger.info("fetching maven XML from $url")
try {
val parsedXml = XmlSlurper(false, false).parse(url) as NodeChild
return GroupVersionData.from(parsedXml)
} catch (ignored: FileNotFoundException) {
logger.info("could not find version data for $group, seems like a new file")
return null
} catch (ioException: IOException) {
logger.warn("failed to fetch the maven info, retrying in 2 seconds. " +
"Run $run of $retryCount")
Thread.sleep(RETRY_DELAY)
}
}
throw GradleException("Could not access maven.google.com")
}
companion object {
/**
* Creates the URL which has the XML file that describes the available versions for each
* artifact in that group
*
* @param group Maven group name
* @return The URL of the XML file
*/
private fun buildGroupUrl(group: String) =
"$BASE${group.replace(".","/")}/$GROUP_FILE"
}
}
private fun <K, V> MutableMap<K, V>.getOrMaybePut(key: K, defaultValue: () -> V?): V? {
val value = get(key)
return if (value == null) {
val answer = defaultValue()
if (answer != null) put(key, answer)
answer
} else {
value
}
}
/**
* Data class that holds the artifacts of a single maven group.
*
* @param name Maven group name
* @param artifacts Map of artifact versions keyed by artifact name
*/
private data class GroupVersionData(
val name: String,
val artifacts: Map<String, ArtifactVersionData>
) {
companion object {
/**
* Constructs an instance from the given node.
*
* @param xml The information node fetched from {@code GROUP_FILE}
*/
fun from(xml: NodeChild): GroupVersionData {
/*
* sample input:
* <android.arch.core>
* <runtime versions="1.0.0-alpha4,1.0.0-alpha5,1.0.0-alpha6,1.0.0-alpha7"/>
* <common versions="1.0.0-alpha4,1.0.0-alpha5,1.0.0-alpha6,1.0.0-alpha7"/>
* </android.arch.core>
*/
val name = xml.name()
val artifacts: MutableMap<String, ArtifactVersionData> = HashMap()
xml.childNodes().forEach {
val node = it as Node
val versions = (node.attributes()["versions"] as String).split(",").map {
if (it == "0.1" || it == "0.2" || it == "0.3") {
// androidx.core:core-ktx shipped versions 0.1, 0.2, and 0.3 which do not
// comply with our versioning scheme.
Version(it + ".0")
} else {
Version(it)
}
}.toSet()
artifacts.put(it.name(), ArtifactVersionData(it.name(), versions))
}
return GroupVersionData(name, artifacts)
}
}
}
/**
* Data class that holds the version information about a single artifact
*
* @param name Name of the maven artifact
* @param versions set of version codes that are already on maven.google.com
*/
private data class ArtifactVersionData(val name: String, val versions: Set<Version>)
// wait 2 seconds before retrying if fetch fails
private const val RETRY_DELAY: Long = 2000 // ms
// number of times we'll try to reach maven.google.com before failing
private const val DEFAULT_RETRY_LIMIT = 20
private const val BASE = "https://dl.google.com/dl/android/maven2/"
private const val GROUP_FILE = "group-index.xml"
|
apache-2.0
|
7e7fc56a85e5dda3f4cd67265049725f
| 36.290323 | 98 | 0.627253 | 4.280864 | false | false | false | false |
kerubistan/kerub
|
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/create/CreateLv.kt
|
2
|
1586
|
package com.github.kerubistan.kerub.planner.steps.storage.lvm.create
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonTypeName
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.LvmStorageCapability
import com.github.kerubistan.kerub.model.VirtualStorageDevice
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.steps.storage.lvm.base.updateHostDynLvmWithAllocation
import io.github.kerubistan.kroki.collections.update
@JsonTypeName("create-lv")
data class CreateLv(
override val host: Host,
override val capability: LvmStorageCapability,
override val disk: VirtualStorageDevice
) : AbstractCreateLv() {
@get:JsonIgnore
override val allocation: VirtualStorageLvmAllocation by lazy {
VirtualStorageLvmAllocation(
hostId = host.id,
actualSize = disk.size,
path = "/dev/$volumeGroupName/${disk.id}",
vgName = volumeGroupName,
capabilityId = capability.id
)
}
override fun take(state: OperationalState): OperationalState = state.copy(
vStorage = state.vStorage.update(disk.id) {
it.copy(
dynamic = VirtualStorageDeviceDynamic(
id = disk.id,
allocations = listOf(allocation)
))
},
hosts = state.hosts.update(host.id) {
it.copy(dynamic = updateHostDynLvmWithAllocation(state, host, volumeGroupName, disk.size))
}
)
}
|
apache-2.0
|
427a9fb9901ced61cf54044e0f0e668d
| 34.266667 | 96 | 0.781211 | 4.066667 | false | false | false | false |
npryce/snodge
|
demo/com/natpryce/snodge/demo/ShonkyJsonEventFormat.kt
|
1
|
3269
|
package com.natpryce.snodge.demo
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException
import java.io.StringReader
import java.io.StringWriter
import java.net.URI
/*
* Defects in this class are corrected in the RobustJsonEventFormat
*/
class ShonkyJsonEventFormat : EventFormat {
override fun serialise(event: ServiceEvent): String {
val serialised = StringWriter()
val writer = JsonWriter(serialised)
writer.beginObject()
writer.name("timestamp")
writer.value(event.timestamp)
writer.name("service")
writer.value(event.service.toString())
writer.name("type")
writer.value(event.serviceState.javaClass.name)
if (event.serviceState is FAILED) {
writer.name("error")
writer.value(event.serviceState.error)
}
writer.endObject()
writer.flush()
return serialised.toString()
}
override fun deserialise(input: String): ServiceEvent {
val reader = JsonReader(StringReader(input))
expect(reader, JsonToken.BEGIN_OBJECT)
reader.beginObject()
// Defect: cannot handle properties in any order
// Caught by JsonEventFormatSnodgeTest.jsonPropertiesCanOccurInAnyOrder
expectProperty(reader, "timestamp", JsonToken.NUMBER)
val timestamp = reader.nextLong()
expectProperty(reader, "service", JsonToken.STRING)
// Defect: throws IllegalArgumentException on invalid URI syntax.
// Caught by JsonEventFormatSnodgeTest.parsesEventSuccessfullyOrThrowsIOException
val service = URI.create(reader.nextString())
expectProperty(reader, "type", JsonToken.STRING)
// Defect: throws ClassNotFoundException on unrecognised class name & loads arbitrary classes.
// Caught by JsonEventFormatSnodgeTest.parsesEventSuccessfullyOrThrowsIOException
val serviceStateClass = Class.forName(reader.nextString())
val serviceState = if (serviceStateClass == FAILED::class.java) {
expectProperty(reader, "error", JsonToken.STRING)
FAILED(reader.nextString())
} else {
serviceStateClass.kotlin.objectInstance as ServiceState
}
// Defect: fails if new fields added to protocol.
// Caught by JsonEventFormatSnodgeTest.ignoresUnrecognisedProperties
expect(reader, JsonToken.END_OBJECT)
return ServiceEvent(timestamp, service, serviceState)
}
private fun expectProperty(reader: JsonReader, expectedName: String, expectedJsonType: JsonToken) {
if (reader.peek() != JsonToken.NAME || reader.nextName() != expectedName || reader.peek() != expectedJsonType) {
throw IOException("expected property named " + expectedName + " of type " + expectedJsonType.name)
}
}
private fun expect(reader: JsonReader, expectedToken: JsonToken) {
val currentToken = reader.peek()
if (currentToken != expectedToken) {
throw IOException("expected $expectedToken but was $currentToken")
}
}
}
|
apache-2.0
|
fef011397bc5afa11f53e7c98d5f8a98
| 37.916667 | 120 | 0.668094 | 4.835799 | false | false | false | false |
seventhroot/elysium
|
bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/command/payment/set/PaymentSetCurrencyCommand.kt
|
1
|
6169
|
/*
* Copyright 2016 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.payments.bukkit.command.payment.set
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.economy.bukkit.currency.RPKCurrencyProvider
import com.rpkit.payments.bukkit.RPKPaymentsBukkit
import com.rpkit.payments.bukkit.group.RPKPaymentGroup
import com.rpkit.payments.bukkit.group.RPKPaymentGroupProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.conversations.*
import org.bukkit.entity.Player
/**
* Payment set currency command.
* Sets the currency a payment group charges in.
*/
class PaymentSetCurrencyCommand(private val plugin: RPKPaymentsBukkit): CommandExecutor {
private val conversationFactory = ConversationFactory(plugin)
.withModality(true)
.withFirstPrompt(CurrencyPrompt())
.withEscapeSequence("cancel")
.thatExcludesNonPlayersWithMessage(plugin.messages["not-from-console"])
.addConversationAbandonedListener { event ->
if (!event.gracefulExit()) {
val conversable = event.context.forWhom
if (conversable is Player) {
conversable.sendMessage(plugin.messages["operation-cancelled"])
}
}
}
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender.hasPermission("rpkit.payments.command.payment.set.currency")) {
if (sender is Player) {
if (args.isNotEmpty()) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
val paymentGroupProvider = plugin.core.serviceManager.getServiceProvider(RPKPaymentGroupProvider::class)
val paymentGroup = paymentGroupProvider.getPaymentGroup(args.joinToString(" "))
if (paymentGroup != null) {
if (paymentGroup.owners.contains(character)) {
val conversation = conversationFactory.buildConversation(sender)
conversation.context.setSessionData("payment_group", paymentGroup)
conversation.begin()
} else {
sender.sendMessage(plugin.messages["payment-set-currency-invalid-owner"])
}
} else {
sender.sendMessage(plugin.messages["payment-set-currency-invalid-group"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["payment-set-currency-usage"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-payment-set-currency"])
}
return true
}
private inner class CurrencyPrompt: ValidatingPrompt() {
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["payment-set-currency-prompt"] + "\n" +
plugin.messages["currency-list-title"] + "\n" +
plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class)
.currencies
.joinToString("\n") { currency -> plugin.messages["currency-list-item", mapOf(Pair("currency", currency.name))] }
}
override fun isInputValid(context: ConversationContext, input: String): Boolean {
return plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class).getCurrency(input) != null
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: String): String {
return plugin.messages["payment-set-currency-invalid-currency"]
}
override fun acceptValidatedInput(context: ConversationContext, input: String): Prompt {
val paymentGroupProvider = plugin.core.serviceManager.getServiceProvider(RPKPaymentGroupProvider::class)
val currencyProvider = plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class)
val paymentGroup = context.getSessionData("payment_group") as RPKPaymentGroup
paymentGroup.currency = currencyProvider.getCurrency(input)
paymentGroupProvider.updatePaymentGroup(paymentGroup)
return CurrencySetPrompt()
}
}
private inner class CurrencySetPrompt: MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt? {
return END_OF_CONVERSATION
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["payment-set-currency-valid"]
}
}
}
|
apache-2.0
|
844192dfb775ff7072e637f238ac6b0a
| 46.829457 | 141 | 0.645485 | 5.537702 | false | false | false | false |
badoualy/kotlogram
|
tl-builder/src/main/kotlin/com/github/badoualy/telegram/tl/builder/parser/TLModel.kt
|
1
|
3637
|
package com.github.badoualy.telegram.tl.builder.parser
import com.github.badoualy.telegram.tl.builder.hex
import java.util.*
// Main definition
class TLDefinition(val types: Map<String, TLType>, val constructors: List<TLConstructor>, val methods: List<TLMethod>)
// Types
abstract class TLType() {
open fun serializable() = true
}
class TLTypeRaw(val name: String) : TLType() {
override fun toString() = name
override fun equals(other: Any?) = other is TLTypeRaw && other.name == name
override fun hashCode() = toString().hashCode()
}
class TLTypeGeneric(val name: String, val generics: Array<TLType>) : TLType() {
override fun toString() = "Generic<$name>"
override fun equals(other: Any?) = other is TLTypeGeneric
override fun hashCode() = toString().hashCode()
}
class TLTypeAny() : TLType() {
override fun toString() = "#Any"
override fun equals(other: Any?) = other is TLTypeAny
override fun hashCode() = toString().hashCode()
}
class TLTypeFunctional() : TLType() {
override fun toString() = "#Functional"
override fun equals(other: Any?) = other is TLTypeFunctional
override fun hashCode() = toString().hashCode()
}
class TLTypeFlag() : TLType() {
override fun toString() = "#Flag"
override fun equals(other: Any?) = other is TLTypeFlag
override fun hashCode() = toString().hashCode()
}
class TLTypeConditional(val value: Int, val realType: TLType) : TLType() {
fun pow2Value() = Math.pow(2.toDouble(), value.toDouble()).toInt()
override fun serializable() = !(realType is TLTypeRaw && realType.name.equals("true", true))
override fun toString() = "flag.$value?$realType"
override fun equals(other: Any?) = other is TLTypeConditional && other.value == value && other.realType == realType
override fun hashCode() = toString().hashCode()
}
// 1 Constructor = 1 class = 1 type
class TLConstructor(val name: String, val id: Int, val parameters: ArrayList<TLParameter>, val tlType: TLTypeRaw) : Comparable<TLConstructor> {
override fun toString() = "$name#${hex(id)} -> $tlType"
override fun compareTo(other: TLConstructor) = name.compareTo(other.name)
override fun equals(other: Any?) = other is TLConstructor && other.name == name && other.id == id
override fun hashCode() = toString().hashCode()
}
class TLAbstractConstructor(val name: String, val parameters: List<TLParameter>, val tlType: TLTypeRaw, val abstractEmptyConstructor: Boolean) : Comparable<TLAbstractConstructor> {
override fun toString() = "$name -> $tlType"
override fun compareTo(other: TLAbstractConstructor) = name.compareTo(other.name)
override fun equals(other: Any?) = other is TLConstructor && other.name == name
override fun hashCode() = toString().hashCode()
}
// Method: 1 method = 1 class = 1 rpc call "model class"
class TLMethod(val name: String, val id: Int, val parameters: List<TLParameter>, val tlType: TLType) : Comparable<TLMethod> {
override fun toString() = "$name#${hex(id)}"
override fun compareTo(other: TLMethod) = name.compareTo(other.name)
override fun equals(other: Any?) = other is TLMethod && other.name == name && other.id == id
override fun hashCode() = toString().hashCode()
}
// A parameter
class TLParameter(val name: String, val tlType: TLType) : Comparable<TLParameter> {
var inherited = false
override fun toString() = "$name: $tlType"
override fun compareTo(other: TLParameter) = name.compareTo(other.name)
override fun equals(other: Any?) = other is TLParameter && other.name == name && other.tlType == tlType
override fun hashCode() = toString().hashCode()
}
|
mit
|
19802bf10e179f2837aa82f54b0b59ff
| 42.309524 | 180 | 0.700577 | 3.873269 | false | false | false | false |
square/sqldelight
|
sqldelight-gradle-plugin/src/main/kotlin/com/squareup/sqldelight/gradle/SqlDelightPlugin.kt
|
1
|
5988
|
/*
* Copyright (C) 2016 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.
*/
package com.squareup.sqldelight.gradle
import com.squareup.sqldelight.VERSION
import com.squareup.sqldelight.core.MINIMUM_SUPPORTED_VERSION
import com.squareup.sqldelight.core.SqlDelightPropertiesFile
import com.squareup.sqldelight.gradle.android.packageName
import com.squareup.sqldelight.gradle.android.sqliteVersion
import com.squareup.sqldelight.gradle.kotlin.linkSqlite
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.tooling.provider.model.ToolingModelBuilder
import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSet
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
abstract class SqlDelightPlugin : Plugin<Project> {
private val android = AtomicBoolean(false)
private val kotlin = AtomicBoolean(false)
@get:Inject
abstract val registry: ToolingModelBuilderRegistry
private lateinit var extension: SqlDelightExtension
override fun apply(project: Project) {
extension = project.extensions.create("sqldelight", SqlDelightExtension::class.java)
extension.project = project
val androidPluginHandler = { _: Plugin<*> ->
android.set(true)
project.afterEvaluate {
project.setupSqlDelightTasks(afterAndroid = true)
}
}
project.plugins.withId("com.android.application", androidPluginHandler)
project.plugins.withId("com.android.library", androidPluginHandler)
project.plugins.withId("com.android.instantapp", androidPluginHandler)
project.plugins.withId("com.android.feature", androidPluginHandler)
project.plugins.withId("com.android.dynamic-feature", androidPluginHandler)
val kotlinPluginHandler = { _: Plugin<*> -> kotlin.set(true) }
project.plugins.withId("org.jetbrains.kotlin.multiplatform", kotlinPluginHandler)
project.plugins.withId("org.jetbrains.kotlin.android", kotlinPluginHandler)
project.plugins.withId("org.jetbrains.kotlin.jvm", kotlinPluginHandler)
project.plugins.withId("kotlin2js", kotlinPluginHandler)
project.afterEvaluate {
project.setupSqlDelightTasks(afterAndroid = false)
}
}
private fun Project.setupSqlDelightTasks(afterAndroid: Boolean) {
if (android.get() && !afterAndroid) return
check(kotlin.get()) {
"SQL Delight Gradle plugin applied in " +
"project '${project.path}' but no supported Kotlin plugin was found"
}
val isMultiplatform = project.plugins.hasPlugin("org.jetbrains.kotlin.multiplatform")
// Add the runtime dependency.
if (isMultiplatform) {
val sourceSets =
project.extensions.getByType(KotlinMultiplatformExtension::class.java).sourceSets
val sourceSet = (sourceSets.getByName("commonMain") as DefaultKotlinSourceSet)
project.configurations.getByName(sourceSet.apiConfigurationName).dependencies.add(
project.dependencies.create("com.squareup.sqldelight:runtime:$VERSION")
)
} else {
project.configurations.getByName("api").dependencies.add(
project.dependencies.create("com.squareup.sqldelight:runtime-jvm:$VERSION")
)
}
if (extension.linkSqlite) {
project.linkSqlite()
}
extension.run {
if (databases.isEmpty() && android.get() && !isMultiplatform) {
// Default to a database for android named "Database" to keep things simple.
databases.add(
SqlDelightDatabase(
project = project,
name = "Database",
packageName = project.packageName(),
dialect = project.sqliteVersion()
)
)
} else if (databases.isEmpty()) {
logger.warn("SQLDelight Gradle plugin was applied but there are no databases set up.")
}
project.tasks.register("generateSqlDelightInterface") {
it.group = GROUP
it.description = "Aggregation task which runs every interface generation task for every given source"
}
project.tasks.register("verifySqlDelightMigration") {
it.group = GROUP
it.description = "Aggregation task which runs every migration task for every given source"
}
databases.forEach { database ->
if (database.packageName == null && android.get() && !isMultiplatform) {
database.packageName = project.packageName()
}
if (database.dialect == null && android.get() && !isMultiplatform) {
database.dialect = project.sqliteVersion()
}
if (database.dialect == null) {
database.dialect = "sqlite:3.18"
}
database.registerTasks()
}
val properties = SqlDelightPropertiesFileImpl(
databases = databases.map { it.getProperties() },
currentVersion = VERSION,
minimumSupportedVersion = MINIMUM_SUPPORTED_VERSION,
)
registry.register(PropertiesModelBuilder(properties))
}
}
class PropertiesModelBuilder(
private val properties: SqlDelightPropertiesFile
) : ToolingModelBuilder {
override fun canBuild(modelName: String): Boolean {
return modelName == SqlDelightPropertiesFile::class.java.name
}
override fun buildAll(modelName: String, project: Project): Any {
return properties
}
}
internal companion object {
const val GROUP = "sqldelight"
}
}
|
apache-2.0
|
da629db5ce087e4259b370acba50098f
| 36.660377 | 109 | 0.715264 | 4.718676 | false | false | false | false |
Esri/arcgis-runtime-samples-android
|
kotlin/query-with-cql-filters/src/main/java/com/esri/arcgisruntime/sample/querywithcqlfilters/MainActivity.kt
|
1
|
14359
|
/* Copyright 2021 Esri
*
* 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.esri.arcgisruntime.sample.querywithcqlfilters
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.OgcFeatureCollectionTable
import com.esri.arcgisruntime.data.QueryParameters
import com.esri.arcgisruntime.data.ServiceFeatureTable
import com.esri.arcgisruntime.geometry.Geometry
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.TimeExtent
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.querywithcqlfilters.databinding.ActivityMainBinding
import com.esri.arcgisruntime.sample.querywithcqlfilters.databinding.CqlFiltersLayoutBinding
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleRenderer
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.util.*
class MainActivity : AppCompatActivity() {
// Keep loadable in scope to avoid garbage collection
private lateinit var ogcFeatureCollectionTable: OgcFeatureCollectionTable
// List of CQL where clauses
private val cqlQueryList: List<String> = listOf(
"F_CODE = 'AP010'",
"{ \"op\": \"=\", \"args\": [ { \"property\": \"F_CODE\" }, \"AP010\" ] }",
"F_CODE LIKE 'AQ%'",
"{\"op\": \"and\", \"args\":[" +
"{ \"op\": \"=\", \"args\":[{ \"property\" : \"F_CODE\" }, \"AP010\"]}, " +
"{ \"op\": \"t_before\", \"args\":[{ \"property\" : \"ZI001_SDV\"},\"2013-01-01\"]}]}",
"No Query"
)
// Current selected where query
private var cqlQueryListPosition = 4
// Set a limit of 3000 on the number of returned features per request,
// the default on some services could be as low as 10
private var maxFeatures = 3000
// Defines date range in queryParameters.timeExtent
private var fromDate = Calendar.getInstance()
private var toDate = Calendar.getInstance()
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val fab: FloatingActionButton by lazy {
activityMainBinding.fab
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// Authentication with an API key or named user is required to
// access basemaps and other location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// Create a map with a topographic basemap
val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
// Set the map to be displayed in the layout's MapView
mapView.map = map
// Define strings for the service URL and collection id
// Note that the service defines the collection id which can be
// accessed via OgcFeatureCollectionInfo.getCollectionId()
val serviceUrl = "https://demo.ldproxy.net/daraa"
val collectionId = "TransportationGroundCrv"
// Create an OGC feature collection table from the service url and collection ID
ogcFeatureCollectionTable = OgcFeatureCollectionTable(serviceUrl, collectionId)
// Set the feature request mode to manual
// In this mode, the table must be manually populated
// and panning and zooming won't request features automatically
ogcFeatureCollectionTable.featureRequestMode =
ServiceFeatureTable.FeatureRequestMode.MANUAL_CACHE
ogcFeatureCollectionTable.addDoneLoadingListener {
if (ogcFeatureCollectionTable.loadStatus == LoadStatus.LOADED) {
// Create a feature layer and set a renderer to it to visualize the OGC API features
val featureLayer = FeatureLayer(ogcFeatureCollectionTable)
val simpleRenderer = SimpleRenderer(
SimpleLineSymbol(
SimpleLineSymbol.Style.SOLID,
Color.MAGENTA,
3f
)
)
featureLayer.renderer = simpleRenderer
// Add the layer to the map
map.operationalLayers.add(featureLayer)
// Zoom to the dataset extent
val datasetExtent = ogcFeatureCollectionTable.extent
if (datasetExtent != null && !datasetExtent.isEmpty) {
mapView.setViewpointGeometryAsync(datasetExtent)
}
val visibleExtentQuery = QueryParameters().apply {
// Create a query based on the current visible extent
geometry = datasetExtent
// Set a limit of 3000 on the number of returned features per request,
// the default on some services could be as low as 10
maxFeatures = [email protected]
}
try {
// Populate the table with the query, leaving existing table entries intact
// Setting the outfields parameter to null requests all fields
ogcFeatureCollectionTable.populateFromServiceAsync(
visibleExtentQuery,
false,
null
)
} catch (e: Exception) {
val errorMessage =
"Error populating OGC Feature Collection Table from service: " + e.message
Toast.makeText(
this,
errorMessage,
Toast.LENGTH_LONG
).show()
Log.e(
"OGC Service error: ",
errorMessage
)
}
} else {
val errorMessage =
"Failed to load OGC Feature Collection Table" + ogcFeatureCollectionTable.loadError.message
Toast.makeText(
this,
errorMessage,
Toast.LENGTH_LONG
).show()
Log.e(
"OGC Load error: ",
errorMessage
)
}
}
// Load the table
ogcFeatureCollectionTable.loadAsync()
// Handles CQL Filters in a Bottom Sheet View.
fab.setOnClickListener {
openBottomSheetView()
}
}
/**
* Handles CQL Filters in a Bottom Sheet View.
*/
private fun openBottomSheetView() {
// Resets views in bottomSheet to default values.
resetBottomSheetValues()
// Creates a new BottomSheetDialog
val dialog = BottomSheetDialog(this)
// Inflates layout file
val bottomSheetBinding = CqlFiltersLayoutBinding.inflate(layoutInflater)
bottomSheetBinding.apply {
// Set the current selection of CQL query
cqlQueryTextView.text = cqlQueryList[cqlQueryListPosition]
// Sets the Where Clause for CQL filter
whereClauseLayout.setOnClickListener {
// Creates a dialog to choose a where clause
val alertDialog: AlertDialog.Builder = AlertDialog.Builder(this@MainActivity)
alertDialog.setTitle("Select Query")
val checkedItem = cqlQueryListPosition
alertDialog.setSingleChoiceItems(
cqlQueryList.toTypedArray(), checkedItem
) { dialog, which ->
// Updates the selected where clause
cqlQueryListPosition = which
cqlQueryTextView.text = cqlQueryList[which]
// Dismiss dialog
dialog.dismiss()
}
// Displays the where clause dialog
val alert: AlertDialog = alertDialog.create()
alert.show()
}
// Sets the view to the default value of max features (3000)
maxFeaturesEditText.setText(maxFeatures.toString())
// Sets from date to Jun-13-2011 by default
fromDatePicker.updateDate(2011, 5, 13)
// Sets to date to Jan-7-2012 by default
toDatePicker.updateDate(2012, 0, 7)
// Sets up filters for the query when Apply is clicked.
applyTv.setOnClickListener {
// Retrieves the max features
val maxFeaturesText =
maxFeaturesEditText.text.toString()
maxFeatures = when {
maxFeaturesText == "" -> 3000
maxFeaturesText.toInt() <= 0 -> 3000
else -> maxFeaturesText.toInt()
}
// Retrieves if date filter is selected
val isDateFilterSelected = dateSwitch.isChecked
// Retrieves from & to dates from the DatePicker
val fromDatePicker = fromDatePicker
val toDatePicker = toDatePicker
fromDate.set(fromDatePicker.year, fromDatePicker.month, fromDatePicker.dayOfMonth)
toDate.set(toDatePicker.year, toDatePicker.month, toDatePicker.dayOfMonth)
// Dismiss bottom sheet view
dialog.dismiss()
// Runs the query using the selected filters
runQuery(isDateFilterSelected)
}
// Dismiss bottom sheet view when cancel is clicked
cancelTv.setOnClickListener { dialog.dismiss() }
}
dialog.setCancelable(false)
// Sets bottom sheet content view to layout
dialog.setContentView(bottomSheetBinding.root)
// Displays bottom sheet view
dialog.show()
}
/**
* Resets views in bottomSheet to default values.
*/
private fun resetBottomSheetValues() {
cqlQueryListPosition = 4
maxFeatures = 3000
fromDate.set(2011, 5, 13)
toDate.set(2012, 0, 7)
}
/**
* Populates features from provided query parameters, and displays the result on the map.
* If [isDateFilterSelected] is true, query searches between fromDate-toDate
*/
private fun runQuery(isDateFilterSelected: Boolean) {
val queryParameters = QueryParameters()
queryParameters.apply {
// Set the query parameter's where clause with the the selected query
// If position is 4 ("Empty Query") manually set [whereClause] to empty string ("")
whereClause = if (cqlQueryListPosition == 4) {
""
} else {
cqlQueryList[cqlQueryListPosition]
}
// Sets the max features to the number entered in the text field
maxFeatures = [email protected]
// If date filter is selected, retrieve the date selected from the date picker
// and set it to the query parameters time extent
if (isDateFilterSelected) {
// set the query parameters time extent
timeExtent = TimeExtent(fromDate, toDate)
}
}
// Populate the table with the query, clear existing table entries
// and set the outfields parameter to null requests all fields
val result = ogcFeatureCollectionTable.populateFromServiceAsync(
queryParameters,
true,
null
)
result.addDoneListener {
// Create a new list to store returned geometries in
val featureGeometryList: MutableList<Geometry> = ArrayList()
// Iterate through each result to get its geometry and add it to the geometry list
result.get().iterator().forEach { feature ->
featureGeometryList.add(feature.geometry)
}
if (featureGeometryList.isNotEmpty()) {
// Zoom to the total extent of the geometries returned by the query
val totalExtent = GeometryEngine.combineExtents(featureGeometryList)
mapView.setViewpointGeometryAsync(totalExtent, 20.0)
}
// Display number of features returned
showResultDialog(ogcFeatureCollectionTable.totalFeatureCount)
}
}
/**
* Function to show the number of features returned
*/
private fun showResultDialog(totalFeatureCount: Long) {
// Build an alert dialog
val dialogBuilder = AlertDialog.Builder(this)
// Display message using OGC Feature Collection Table
dialogBuilder.setMessage("Query returned $totalFeatureCount features")
.setPositiveButton("Ok") { dialog, _ -> dialog.dismiss() }
// Create dialog box
val alert = dialogBuilder.create()
alert.setTitle("Query Result")
// Shows alert dialog
alert.show()
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
|
apache-2.0
|
b8d56ce71bbdf6365485f724b32e8670
| 36.589005 | 111 | 0.611254 | 5.361837 | false | false | false | false |
cretz/asmble
|
compiler/src/main/kotlin/asmble/io/AstToBinary.kt
|
1
|
10592
|
package asmble.io
import asmble.ast.Node
import asmble.util.toRawIntBits
import asmble.util.toRawLongBits
import asmble.util.toUnsignedBigInt
import asmble.util.toUnsignedLong
import java.io.ByteArrayOutputStream
open class AstToBinary(val version: Long = 1L) {
fun fromCustomSection(b: ByteWriter, n: Node.CustomSection) {
b.writeVarUInt7(0)
b.withVarUInt32PayloadSizePrepended { b ->
b.writeString(n.name)
b.writeBytes(n.payload)
}
}
fun fromData(b: ByteWriter, n: Node.Data) {
b.writeVarUInt32(n.index)
fromInitExpr(b, n.offset)
b.writeVarUInt32(n.data.size)
b.writeBytes(n.data)
}
fun fromElem(b: ByteWriter, n: Node.Elem) {
b.writeVarUInt32(n.index)
fromInitExpr(b, n.offset)
b.writeVarUInt32(n.funcIndices.size)
n.funcIndices.forEach { b.writeVarUInt32(it) }
}
fun fromExport(b: ByteWriter, n: Node.Export) {
b.writeString(n.field)
b.writeByte(n.kind.externalKind)
b.writeVarUInt32(n.index)
}
fun fromFuncBody(b: ByteWriter, n: Node.Func) {
b.withVarUInt32PayloadSizePrepended { b ->
val localsWithCounts = n.locals.fold(emptyList<Pair<Node.Type.Value, Int>>()) { localsWithCounts, local ->
if (local != localsWithCounts.lastOrNull()?.first) localsWithCounts + (local to 1)
else localsWithCounts.dropLast(1) + (local to localsWithCounts.last().second + 1)
}
b.writeVarUInt32(localsWithCounts.size)
localsWithCounts.forEach { (localType, count) ->
b.writeVarUInt32(count)
b.writeVarInt7(localType.valueType)
}
n.instructions.forEach { fromInstr(b, it) }
fromInstr(b, Node.Instr.End)
}
}
fun fromFuncType(b: ByteWriter, n: Node.Type.Func) {
b.writeVarInt7(-0x20)
b.writeVarUInt32(n.params.size)
n.params.forEach { b.writeVarInt7(it.valueType) }
b.writeVarUInt1(n.ret != null)
n.ret?.let { b.writeVarInt7(it.valueType) }
}
fun fromGlobal(b: ByteWriter, n: Node.Global) {
fromGlobalType(b, n.type)
fromInitExpr(b, n.init)
}
fun fromGlobalType(b: ByteWriter, n: Node.Type.Global) {
b.writeVarInt7(n.contentType.valueType)
b.writeVarUInt1(n.mutable)
}
fun fromImport(b: ByteWriter, import: Node.Import) {
b.writeString(import.module)
b.writeString(import.field)
b.writeByte(import.kind.externalKind)
when (import.kind) {
is Node.Import.Kind.Func -> b.writeVarUInt32(import.kind.typeIndex)
is Node.Import.Kind.Table -> fromTableType(b, import.kind.type)
is Node.Import.Kind.Memory -> fromMemoryType(b, import.kind.type)
is Node.Import.Kind.Global -> fromGlobalType(b, import.kind.type)
}
}
fun fromInitExpr(b: ByteWriter, n: List<Node.Instr>) {
require(n.size == 1) { "Init expression should have 1 insn, got ${n.size}" }
fromInstr(b, n.single())
fromInstr(b, Node.Instr.End)
}
fun fromInstr(b: ByteWriter, n: Node.Instr) {
val op = n.op()
b.writeByte(op.opcode.toByte())
fun <A : Node.Instr.Args> Node.InstrOp<A>.args() = this.argsOf(n)
when (op) {
is Node.InstrOp.ControlFlowOp.NoArg, is Node.InstrOp.ParamOp.NoArg,
is Node.InstrOp.CompareOp.NoArg, is Node.InstrOp.NumOp.NoArg,
is Node.InstrOp.ConvertOp.NoArg, is Node.InstrOp.ReinterpretOp.NoArg ->
{ }
is Node.InstrOp.ControlFlowOp.TypeArg ->
b.writeVarInt7(op.args().type.valueType)
is Node.InstrOp.ControlFlowOp.DepthArg ->
b.writeVarUInt32(op.args().relativeDepth)
is Node.InstrOp.ControlFlowOp.TableArg -> op.args().let {
b.writeVarUInt32(it.targetTable.size)
it.targetTable.forEach { b.writeVarUInt32(it) }
b.writeVarUInt32(it.default)
}
is Node.InstrOp.CallOp.IndexArg ->
b.writeVarUInt32(op.args().index)
is Node.InstrOp.CallOp.IndexReservedArg -> op.args().let {
b.writeVarUInt32(it.index)
b.writeVarUInt1(it.reserved)
}
is Node.InstrOp.VarOp.IndexArg ->
b.writeVarUInt32(op.args().index)
is Node.InstrOp.MemOp.AlignOffsetArg -> op.args().let {
b.writeVarUInt32(it.align)
b.writeVarUInt32(it.offset)
}
is Node.InstrOp.MemOp.ReservedArg ->
b.writeVarUInt1(false)
is Node.InstrOp.ConstOp.IntArg ->
b.writeVarInt32(op.args().value)
is Node.InstrOp.ConstOp.LongArg ->
b.writeVarInt64(op.args().value)
is Node.InstrOp.ConstOp.FloatArg ->
b.writeUInt32(op.args().value.toRawIntBits().toUnsignedLong())
is Node.InstrOp.ConstOp.DoubleArg ->
b.writeUInt64(op.args().value.toRawLongBits().toUnsignedBigInt())
}
}
fun <T> fromListSection(b: ByteWriter, n: List<T>, fn: (ByteWriter, T) -> Unit) {
b.writeVarUInt32(n.size)
n.forEach { fn(b, it) }
}
fun fromMemoryType(b: ByteWriter, n: Node.Type.Memory) {
fromResizableLimits(b, n.limits)
}
fun fromModule(n: Node.Module) =
ByteArrayOutputStream().also { fromModule(ByteWriter.OutputStream(it), n) }.toByteArray()
fun fromModule(b: ByteWriter, n: Node.Module) {
b.writeUInt32(0x6d736100)
b.writeUInt32(version)
// Sections
// Add all custom sections after 0
n.customSections.filter { it.afterSectionId == 0 }.forEach { fromCustomSection(b, it) }
// We need to add all of the func decl types to the type list that are not already there
val funcTypes = n.types + n.funcs.mapNotNull { if (n.types.contains(it.type)) null else it.type }
wrapListSection(b, n, 1, funcTypes, this::fromFuncType)
wrapListSection(b, n, 2, n.imports, this::fromImport)
wrapListSection(b, n, 3, n.funcs) { b, f -> b.writeVarUInt32(funcTypes.indexOf(f.type)) }
wrapListSection(b, n, 4, n.tables, this::fromTableType)
wrapListSection(b, n, 5, n.memories, this::fromMemoryType)
wrapListSection(b, n, 6, n.globals, this::fromGlobal)
wrapListSection(b, n, 7, n.exports, this::fromExport)
if (n.startFuncIndex != null)
wrapSection(b, n, 8) { b -> b.writeVarUInt32(n.startFuncIndex) }
wrapListSection(b, n, 9, n.elems, this::fromElem)
wrapListSection(b, n, 10, n.funcs, this::fromFuncBody)
wrapListSection(b, n, 11, n.data, this::fromData)
n.names?.also { fromNames(b, it) }
// All other custom sections after the previous
n.customSections.filter { it.afterSectionId > 11 }.forEach { fromCustomSection(b, it) }
}
fun fromNames(b: ByteWriter, n: Node.NameSection) {
fun <T> indexMap(b: ByteWriter, map: Map<Int, T>, fn: (T) -> Unit) {
b.writeVarUInt32(map.size)
map.forEach { index, v -> b.writeVarUInt32(index).also { fn(v) } }
}
fun nameMap(b: ByteWriter, map: Map<Int, String>) = indexMap(b, map) { b.writeString(it) }
b.writeVarUInt7(0)
b.withVarUInt32PayloadSizePrepended { b ->
b.writeString("name")
n.moduleName?.also { moduleName ->
b.writeVarUInt7(0)
b.withVarUInt32PayloadSizePrepended { b -> b.writeString(moduleName) }
}
if (n.funcNames.isNotEmpty()) b.writeVarUInt7(1).also {
b.withVarUInt32PayloadSizePrepended { b -> nameMap(b, n.funcNames) }
}
if (n.localNames.isNotEmpty()) b.writeVarUInt7(2).also {
b.withVarUInt32PayloadSizePrepended { b -> indexMap(b, n.localNames) { nameMap(b, it) } }
}
}
}
fun fromResizableLimits(b: ByteWriter, n: Node.ResizableLimits) {
b.writeVarUInt1(n.maximum != null)
b.writeVarUInt32(n.initial)
n.maximum?.let { b.writeVarUInt32(it) }
}
fun fromTableType(b: ByteWriter, n: Node.Type.Table) {
b.writeVarInt7(n.elemType.elemType)
fromResizableLimits(b, n.limits)
}
fun <T> wrapListSection(
b: ByteWriter,
mod: Node.Module,
sectionId: Short,
n: List<T>,
fn: (ByteWriter, T) -> Unit
) {
// We wrap the section if it has items OR it has a custom section
val hasCustomSection = mod.customSections.find { it.afterSectionId == sectionId.toInt() } != null
if (n.isNotEmpty() || hasCustomSection) wrapSection(b, mod, sectionId) { b -> fromListSection(b, n, fn) }
}
fun wrapSection(
b: ByteWriter,
mod: Node.Module,
sectionId: Short,
handler: (ByteWriter) -> Unit
) {
b.writeVarUInt7(sectionId)
b.withVarUInt32PayloadSizePrepended(handler)
// Add any custom sections after myself
mod.customSections.filter { it.afterSectionId == sectionId.toInt() }.forEach { fromCustomSection(b, it) }
}
fun ByteWriter.writeVarUInt32(v: Int) {
this.writeVarUInt32(v.toUnsignedLong())
}
fun ByteWriter.withVarUInt32PayloadSizePrepended(fn: (ByteWriter) -> Unit) {
val temp = this.createTemp()
fn(temp)
this.writeVarUInt32(temp.written)
this.write(temp)
}
fun ByteWriter.writeString(str: String) {
val bytes = str.toByteArray()
this.writeVarUInt32(bytes.size)
this.writeBytes(bytes)
}
val Node.ExternalKind.externalKind: Byte get() = when(this) {
Node.ExternalKind.FUNCTION -> 0
Node.ExternalKind.TABLE -> 1
Node.ExternalKind.MEMORY -> 2
Node.ExternalKind.GLOBAL -> 3
}
val Node.Import.Kind.externalKind: Byte get() = when(this) {
is Node.Import.Kind.Func -> 0
is Node.Import.Kind.Table -> 1
is Node.Import.Kind.Memory -> 2
is Node.Import.Kind.Global -> 3
}
val Node.Type.Value?.valueType: Byte get() = when(this) {
null -> -0x40
Node.Type.Value.I32 -> -0x01
Node.Type.Value.I64 -> -0x02
Node.Type.Value.F32 -> -0x03
Node.Type.Value.F64 -> -0x04
}
val Node.ElemType.elemType: Byte get() = when(this) {
Node.ElemType.ANYFUNC -> -0x10
}
companion object : AstToBinary()
}
|
mit
|
fa05f4a9f929abc368ee792c3f4d0f80
| 37.802198 | 118 | 0.603852 | 3.483065 | false | false | false | false |
gradle/gradle
|
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/PluginAwareScript.kt
|
3
|
1471
|
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.support
import groovy.lang.Closure
import org.gradle.api.Action
import org.gradle.api.plugins.ObjectConfigurationAction
import org.gradle.api.plugins.PluginAware
import org.gradle.api.plugins.PluginContainer
import org.gradle.api.plugins.PluginManager
open class PluginAwareScript(
private val host: KotlinScriptHost<PluginAware>
) : PluginAware {
override fun getPlugins(): PluginContainer =
host.target.plugins
override fun getPluginManager(): PluginManager =
host.target.pluginManager
override fun apply(action: Action<in ObjectConfigurationAction>) =
host.applyObjectConfigurationAction(action)
override fun apply(options: Map<String, *>) =
host.applyObjectConfigurationAction(options)
override fun apply(closure: Closure<Any>) =
internalError()
}
|
apache-2.0
|
4b4bfa78bfffbc771b2b71bb35f3a3b6
| 31.688889 | 75 | 0.751869 | 4.391045 | false | true | false | false |
google/private-compute-libraries
|
java/com/google/android/libraries/pcc/chronicle/api/policy/builder/DeletionTriggerPolicyAnnotations.kt
|
1
|
2205
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.libraries.pcc.chronicle.api.policy.builder
import com.google.android.libraries.pcc.chronicle.api.DeletionTrigger
import com.google.android.libraries.pcc.chronicle.api.Trigger
import com.google.android.libraries.pcc.chronicle.api.policy.PolicyTarget
import com.google.android.libraries.pcc.chronicle.api.policy.annotation.Annotation
import com.google.android.libraries.pcc.chronicle.api.policy.annotation.AnnotationParam
/** The constants used to encode a [DeletionTrigger] onto a target of the [Policy]. */
object DeletionTriggerPolicyAnnotations {
const val ANNOTATION_NAME = "deletionTrigger"
const val TRIGGER_KEY = "trigger"
const val FIELD_KEY = "field"
}
/** Retrive [DeletionTrigger] from a [PolicyTarget]. */
fun PolicyTarget.deletionTriggers(): Set<DeletionTrigger> {
return annotations.deletionTriggers()
}
/** Encodes a trigger as a Policy annotation */
fun Trigger.toAnnotation(field: String): Annotation {
return Annotation(
DeletionTriggerPolicyAnnotations.ANNOTATION_NAME,
mapOf(
DeletionTriggerPolicyAnnotations.TRIGGER_KEY to AnnotationParam.Str(this.name),
DeletionTriggerPolicyAnnotations.FIELD_KEY to AnnotationParam.Str(field),
)
)
}
private fun Collection<Annotation>.deletionTriggers(): Set<DeletionTrigger> {
return this.filter { it.name == DeletionTriggerPolicyAnnotations.ANNOTATION_NAME }
.map {
DeletionTrigger(
Trigger.valueOf(it.getStringParam(DeletionTriggerPolicyAnnotations.TRIGGER_KEY)),
it.getStringParam(DeletionTriggerPolicyAnnotations.FIELD_KEY)
)
}
.toSet()
}
|
apache-2.0
|
89237bd49ffba9630b41586857bf8ff2
| 37.684211 | 89 | 0.766893 | 4.306641 | false | false | false | false |
VerifAPS/verifaps-lib
|
exec/src/main/kotlin/edu/kit/iti/formal/automation/St2Cpp.kt
|
1
|
1688
|
package edu.kit.iti.formal.automation
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.file
import edu.kit.iti.formal.automation.cpp.TranslateToCppFacade
import java.io.File
import java.util.*
/**
*
* @author Alexander Weigl
* @version 1 (16.07.19)
*/
object St2Cpp : CliktCommand() {
//val verbose by option().flag("-V", default = false)
//val comments by option().flag("C", default = true)
val files by argument("FILES").file(readable = true).multiple()
val st0 by option("-s").flag("-S", default = false)
val builtins by option("-b").flag("-B", default = true)
val output by option("-o").file().default(File("out.c"))
override fun run() {
var (pous, errors) = IEC61131Facade.filefr(files, builtins)
if (errors.isNotEmpty()) {
errors.forEach { System.err.println(it.toHuman()) }
}
if (st0) {
pous = SymbExFacade.simplify(pous)
}
output.bufferedWriter().use {
it.write("""
// Generated ${Date()}
#include <stdbool.h>
#include <stdint.h>
""".trimIndent())
TranslateToCppFacade.translate(it, pous)
}
}
}
object ST2CppApp {
@JvmStatic
fun main(argv: Array<String>) {
St2Cpp.main(argv.asList())
}
}
|
gpl-3.0
|
49a3b96cc981c61ae156adcd3902df72
| 29.709091 | 67 | 0.627962 | 3.734513 | false | false | false | false |
mpv-android/mpv-android
|
app/src/main/java/is/xyz/mpv/MainScreenFragment.kt
|
1
|
6022
|
package `is`.xyz.mpv
import `is`.xyz.filepicker.DocumentPickerFragment
import `is`.xyz.mpv.config.SettingsActivity
import `is`.xyz.mpv.databinding.FragmentMainScreenBinding
import android.content.*
import android.net.Uri
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
class MainScreenFragment : Fragment(R.layout.fragment_main_screen) {
private lateinit var binding: FragmentMainScreenBinding
private lateinit var documentTreeOpener: ActivityResultLauncher<Intent>
private var firstRun = true
// FilePickerActivity uses a broadcast intent (yes really) to inform us of a picked file
// so that the activity stack is preserved and the file picker stays in the activity stack
private val broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent == null) {
Log.v(TAG, "file picker cancelled")
return
}
val path = intent.getStringExtra("path")
if (path != null)
playFile(path)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
documentTreeOpener = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
it.data?.data?.let { root ->
requireContext().contentResolver.takePersistableUriPermission(
root, Intent.FLAG_GRANT_READ_URI_PERMISSION)
saveChoice("doc", root.toString())
val i = Intent(context, FilePickerActivity::class.java)
i.putExtra("skip", FilePickerActivity.DOC_PICKER)
i.putExtra("root", root.toString())
i.putExtra("broadcast", true)
startActivity(i)
}
}
LocalBroadcastManager.getInstance(requireContext()).registerReceiver(
broadcastReceiver, IntentFilter(FilePickerActivity.BROADCAST_INTENT))
}
override fun onDestroy() {
LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(broadcastReceiver)
super.onDestroy()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding = FragmentMainScreenBinding.bind(view)
binding.docBtn.setOnClickListener {
try {
documentTreeOpener.launch(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE))
} catch (e: ActivityNotFoundException) {
// Android TV doesn't come with a document picker and certain versions just throw
// instead of handling this gracefully
binding.docBtn.isEnabled = false
}
}
binding.urlBtn.setOnClickListener {
saveChoice("url")
val helper = Utils.OpenUrlDialog()
with (helper.getBuilder(requireContext())) {
setPositiveButton(R.string.dialog_ok) { _, _ ->
playFile(helper.text)
}
setNegativeButton(R.string.dialog_cancel) { dialog, _ -> dialog.cancel() }
show()
}
}
binding.filepickerBtn.setOnClickListener {
saveChoice("file")
val i = Intent(context, FilePickerActivity::class.java)
i.putExtra("skip", FilePickerActivity.FILE_PICKER)
i.putExtra("broadcast", true)
startActivity(i)
}
binding.settingsBtn.setOnClickListener {
saveChoice("") // will reset
startActivity(Intent(context, SettingsActivity::class.java))
}
}
override fun onResume() {
super.onResume()
if (firstRun) {
restoreChoice()
firstRun = false
}
}
private fun saveChoice(type: String, data: String? = null) {
if (!binding.switch1.isChecked)
return
binding.switch1.isChecked = false
with (PreferenceManager.getDefaultSharedPreferences(requireContext()).edit()) {
putString("MainScreenFragment_remember", type)
if (data == null)
remove("MainScreenFragment_remember_data")
else
putString("MainScreenFragment_remember_data", data)
commit()
}
}
private fun restoreChoice() {
val (type, data) = with (PreferenceManager.getDefaultSharedPreferences(requireContext())) {
Pair(
getString("MainScreenFragment_remember", "") ?: "",
getString("MainScreenFragment_remember_data", "") ?: ""
)
}
when (type) {
"doc" -> {
val uri = Uri.parse(data)
// check that we can still access the folder
if (!DocumentPickerFragment.isTreeUsable(requireContext(), uri))
return
val i = Intent(context, FilePickerActivity::class.java)
i.putExtra("skip", FilePickerActivity.DOC_PICKER)
i.putExtra("root", uri.toString())
i.putExtra("broadcast", true)
startActivity(i)
}
"url" -> binding.urlBtn.callOnClick()
"file" -> binding.filepickerBtn.callOnClick()
}
}
private fun playFile(filepath: String) {
val i: Intent
if (filepath.startsWith("content://")) {
i = Intent(Intent.ACTION_VIEW, Uri.parse(filepath))
} else {
i = Intent()
i.putExtra("filepath", filepath)
}
i.setClass(requireContext(), MPVActivity::class.java)
startActivity(i)
}
companion object {
private const val TAG = "mpv"
}
}
|
mit
|
5ded21ba9b109f13e4f52937c3229abd
| 35.719512 | 106 | 0.605447 | 5.200345 | false | false | false | false |
klose911/klose911.github.io
|
src/kotlin/src/tutorial/functional/LambdaExpression.kt
|
1
|
1670
|
package tutorial.functional
class IntTransformer : (Int) -> Int {
override operator fun invoke(x: Int): Int = TODO()
}
val intFunction: (Int) -> Int = IntTransformer()
val a = { i: Int -> i + 1 } // 推断出的类型是 (Int) -> Int
fun main() {
val items = listOf(1, 2, 3, 4, 5)
// Lambdas 表达式是花括号括起来的代码块。
items.fold(0, {
// 如果一个 lambda 表达式有参数,前面是参数,后跟“->”
acc: Int, i: Int ->
print("acc = $acc, i = $i, ")
val result = acc + i
println("result = $result")
// lambda 表达式中的最后一个表达式是返回值:
result
})
// lambda 表达式的参数类型是可选的,如果能够推断出来的话:
val joinedToString = items.fold("Elements:", { acc, i -> acc + " " + i })
// 函数引用也可以用于高阶函数调用:
val product = items.fold(1, Int::times)
println("joinedToString = $joinedToString")
println("product = $product")
val repeatFun: String.(Int) -> String = { times -> this.repeat(times) }
val twoParameters: (String, Int) -> String = repeatFun // OK
fun runTransformation(f: (String, Int) -> String): String {
return f("hello", 3)
}
val result = runTransformation(repeatFun) // OK
println("result = $result")
val stringPlus: (String, String) -> String = String::plus
val intPlus: Int.(Int) -> Int = Int::plus
println(stringPlus.invoke("<-", "->"))
println(stringPlus("Hello, ", "world!"))
println(intPlus.invoke(1, 1))
println(intPlus(1, 2))
println(2.intPlus(3)) // 类扩展调用
}
|
bsd-2-clause
|
81438b72f5c0afed8a06c387f8d7c95c
| 26.566038 | 77 | 0.582877 | 3.237251 | false | false | false | false |
saru95/DSA
|
Kotlin/BucketSort.kt
|
1
|
1433
|
import java.util.Random
class BucketSort {
internal fun sort(sequence: IntArray, maxValue: Int): IntArray {
// Bucket Sort
val Bucket = IntArray(maxValue + 1)
val sorted_sequence = IntArray(sequence.size)
for (i in sequence.indices)
Bucket[sequence[i]]++
var outPos = 0
for (i in Bucket.indices)
for (j in 0 until Bucket[i])
sorted_sequence[outPos++] = i
return sorted_sequence
}
internal fun printSequence(sorted_sequence: IntArray) {
for (i in sorted_sequence.indices)
System.out.print(sorted_sequence[i].toString() + " ")
}
internal fun maxValue(sequence: IntArray): Int {
var maxValue = 0
for (i in sequence.indices)
if (sequence[i] > maxValue)
maxValue = sequence[i]
return maxValue
}
fun main(args: Array<String>) {
System.out
.println("Sorting of randomly generated numbers using BUCKET SORT")
val random = Random()
val N = 20
val sequence = IntArray(N)
for (i in 0 until N)
sequence[i] = Math.abs(random.nextInt(100))
val maxValue = maxValue(sequence)
System.out.println("\nOriginal Sequence: ")
printSequence(sequence)
System.out.println("\nSorted Sequence: ")
printSequence(sort(sequence, maxValue))
}
}
|
mit
|
1e6717fcb4c0c0ab7ab23ff835e5923d
| 27.098039 | 83 | 0.579902 | 4.355623 | false | false | false | false |
vanniktech/Emoji
|
emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/EmojiArrayAdapter.kt
|
1
|
2121
|
/*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vanniktech.emoji.internal
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.vanniktech.emoji.Emoji
import com.vanniktech.emoji.EmojiTheming
import com.vanniktech.emoji.R
import com.vanniktech.emoji.listeners.OnEmojiClickListener
import com.vanniktech.emoji.variant.VariantEmoji
internal class EmojiArrayAdapter(
context: Context,
emojis: Collection<Emoji>,
private val variantEmoji: VariantEmoji?,
private val listener: OnEmojiClickListener?,
private val longListener: OnEmojiLongClickListener?,
private val theming: EmojiTheming,
) : ArrayAdapter<Emoji>(context, 0, emojis.filterNot { it.isDuplicate }) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var image = convertView as? EmojiImageView
val context = context
if (image == null) {
image = LayoutInflater.from(context).inflate(R.layout.emoji_adapter_item_emoji, parent, false) as EmojiImageView
image.clickListener = listener
image.longClickListener = longListener
}
val emoji = getItem(position)!!
val variantToUse = variantEmoji?.getVariant(emoji) ?: emoji
image.contentDescription = emoji.unicode
image.setEmoji(theming, variantToUse, variantEmoji)
return image
}
fun updateEmojis(emojis: Collection<Emoji>) {
clear()
addAll(emojis)
notifyDataSetChanged()
}
}
|
apache-2.0
|
aa1f6f163535171c13a0129287059bd2
| 35.534483 | 118 | 0.757905 | 4.298174 | false | false | false | false |
danrien/projectBlue
|
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/preparation/GivenAStandardQueue/AndTheSecondFileThrowsAnExceptionOnFirstPreparation/WhenTheQueueIsStarted.kt
|
2
|
2683
|
package com.lasthopesoftware.bluewater.client.playback.engine.preparation.GivenAStandardQueue.AndTheSecondFileThrowsAnExceptionOnFirstPreparation
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlayableFileQueue
import com.lasthopesoftware.bluewater.client.playback.file.PlayableFile
import com.lasthopesoftware.bluewater.client.playback.file.fakes.FakeBufferingPlaybackHandler
import com.lasthopesoftware.bluewater.client.playback.file.fakes.FakePreparedPlayableFile
import com.lasthopesoftware.bluewater.client.playback.file.preparation.PlayableFilePreparationSource
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import org.assertj.core.api.Assertions.assertThat
import org.joda.time.Duration
import org.junit.BeforeClass
import org.junit.Test
import org.mockito.Mockito
import java.util.concurrent.ExecutionException
class WhenTheQueueIsStarted {
companion object {
private val expectedPlaybackHandler = FakeBufferingPlaybackHandler()
private var returnedPlaybackHandler: PlayableFile? = null
private var error: Throwable? = null
@JvmStatic
@BeforeClass
fun before() {
val serviceFiles = intArrayOf(0, 1, 2).map { key -> ServiceFile(key) }
val playbackPreparer = Mockito.mock(PlayableFilePreparationSource::class.java)
Mockito.`when`(playbackPreparer.promisePreparedPlaybackFile(ServiceFile(0), Duration.ZERO))
.thenReturn(Promise(FakePreparedPlayableFile(FakeBufferingPlaybackHandler())))
Mockito.`when`(playbackPreparer.promisePreparedPlaybackFile(ServiceFile(1), Duration.ZERO))
.thenReturn(Promise(Exception()))
.thenReturn(Promise(FakePreparedPlayableFile(expectedPlaybackHandler)))
val bufferingPlaybackQueuesProvider = CompletingFileQueueProvider()
val startPosition = 0
val queue = PreparedPlayableFileQueue(
{ 2 },
playbackPreparer,
bufferingPlaybackQueuesProvider.provideQueue(serviceFiles, startPosition))
try {
returnedPlaybackHandler = queue.promiseNextPreparedPlaybackFile(Duration.ZERO)
?.eventually { queue.promiseNextPreparedPlaybackFile(Duration.ZERO) }
?.toFuture()?.get()?.playableFile
} catch (e: ExecutionException) {
error = e.cause
}
}
}
@Test
fun thenTheExpectedPlaybackHandlerIsReturned() {
assertThat(returnedPlaybackHandler).isEqualTo(expectedPlaybackHandler).isNotNull
}
@Test
fun thenTheErrorIsNotCaught() {
assertThat(error).isNull()
}
}
|
lgpl-3.0
|
9aeca6fc6ed61b3b1493dba644996e34
| 40.921875 | 145 | 0.821469 | 4.486622 | false | false | false | false |
kotlintest/kotlintest
|
kotest-assertions/src/jvmMain/kotlin/io/kotest/matchers/string/digest.kt
|
1
|
843
|
package io.kotest.matchers.string
import io.kotest.assertions.show.convertValueToString
import io.kotest.matchers.*
import java.math.BigInteger
import java.security.MessageDigest
fun String?.shouldHaveDigest(algo: String, digest: String) = this should haveDigest(algo, digest)
fun String?.shouldNotHaveDigest(algo: String, digest: String) = this shouldNot haveDigest(algo, digest)
fun haveDigest(algo: String, digest: String) : Matcher<String?> = neverNullMatcher { value ->
val alg = MessageDigest.getInstance(algo)
val result = alg.digest(value.toByteArray())
val bigInt = BigInteger(1, result)
val output = bigInt.toString(16)
MatcherResult(
output == digest,
"${convertValueToString(value)} should have $algo digest $digest but was $output",
"${convertValueToString(value)} should not have $algo digest $digest")
}
|
apache-2.0
|
7f7cc33ed3e888e3593a53290db9f600
| 43.368421 | 103 | 0.763938 | 4.072464 | false | true | false | false |
edsilfer/presence-control
|
app/src/main/java/br/com/edsilfer/android/presence_control/place/presentation/presenter/PlaceAddPresenter.kt
|
1
|
6102
|
package br.com.edsilfer.android.presence_control.place.presentation.presenter
import android.location.Geocoder
import br.com.edsilfer.android.presence_control.R
import br.com.edsilfer.android.presence_control.commons.utils.extension.asLatLng
import br.com.edsilfer.android.presence_control.core.services.contracts.IGeofenceAPI
import br.com.edsilfer.android.presence_control.core.services.contracts.ILocationAPI
import br.com.edsilfer.android.presence_control.core.presentation.BaseView
import br.com.edsilfer.android.presence_control.core.presentation.Validator
import br.com.edsilfer.android.presence_control.place.datasource.PlaceRepository
import br.com.edsilfer.android.presence_control.place.domain.observables.ObservableNewPlace
import br.com.edsilfer.android.presence_control.place.presentation.presenter.contract.IPlaceAddPresenter
import br.com.edsilfer.android.presence_control.place.presentation.model.MapCircle
import br.com.edsilfer.android.presence_control.place.presentation.view.contracts.IPlaceAddView
import com.google.android.gms.maps.model.LatLng
import io.reactivex.disposables.Disposable
import java.util.*
/**
* Created by ferna on 5/21/2017.
*/
class PlaceAddPresenter(
val locationAPI: ILocationAPI,
val geofenceApi: IGeofenceAPI,
val newPlaceValidator: Validator,
val placeRepository: PlaceRepository
) : IPlaceAddPresenter {
companion object {
private val ERR_001 = ""
}
private lateinit var view: IPlaceAddView
private var newPlaceObserver: Disposable? = null
private var isMapReady = false
private var isFirstUpdate = 0
/**
* LIFECYCLE
*/
override fun takeView(view: BaseView) {
placeRepository.openRealm()
this.view = view as IPlaceAddView
newPlaceObserver = onNewPlaceUpdated()
}
override fun dropView() {
super.dropView()
newPlaceObserver?.dispose()
placeRepository.closeRealm()
}
/**
* PUBLIC INTERFACE
*/
override fun onSearchClick(address: String) {
val geoCoder = Geocoder(view.getViewContext(), Locale.getDefault())
val addresses = geoCoder.getFromLocationName(address, 5)
if (addresses.size > 0) {
val lat = addresses[0].latitude
val lon = addresses[0].longitude
view.moveMap(LatLng(lat, lon))
}
}
override fun onMapReady() {
isMapReady = true
addExistingPlaces()
}
private fun addExistingPlaces() {
Thread().run {
placeRepository.list().forEach {
place ->
view.addCircleToMap(
MapCircle(
location = place.getLocation(),
radius = place.radius,
clearPrevious = false,
borderColor = R.color.color_existing_place_circle_border,
fillColor = R.color.color_existing_place_circle_fill,
moveCamera = false
)
)
}
}
}
override fun onAddPlaceClick() {
Thread().run {
view.doWait(R.string.str_commons_please_wait)
val newPlace = ObservableNewPlace.newPlace
val validationResult = newPlaceValidator.isValid(newPlace)
if (validationResult.first) {
val persistedPlace = placeRepository.create(newPlace)
if (persistedPlace != null) {
geofenceApi.addRegisterFence(
context = view.getViewContext(),
googleApiClient = view.getGeolocationServices()!!.getGoogleAPI()!!,
geofence = geofenceApi.createGeofenceWithLoiteringTime(persistedPlace)
)
} else {
timber.log.Timber.e("Unable to create place because it has same id as existent register")
}
view.stopWaiting()
view.exit()
} else {
view.showError(validationResult.second)
}
}
}
override fun onCenterClick() {
val currentLocation = view.getGeolocationServices()!!.getLastKnownLocation()
if (currentLocation != null) {
view.moveMap(LatLng(currentLocation.latitude, currentLocation.longitude))
}
}
override fun onCancelClick() {
view.exit()
}
/**
* EVENTS
*/
private fun onNewPlaceUpdated(): Disposable {
return ObservableNewPlace.register().subscribe {
place ->
if (isMapReady && place.latitude != 0.toDouble() && place.latitude != 0.toDouble()) {
view.addCircleToMap(
MapCircle(
location = place.getLocation(),
radius = place.radius,
clearPrevious = isFirstUpdate > 0
)
)
}
}
}
override fun onMapLongClick(location: LatLng?) {
val currentLocation = view.getGeolocationServices()!!.getLastKnownLocation()
if (location != null) {
run {
try {
val results = locationAPI.searchPlaceByCoordinates(
view.getViewContext(),
location.latitude,
location.longitude,
currentLocation?.asLatLng()
)
if (results.size > 1) {
ObservableNewPlace.update(
address = results[0].subheader,
location = location
)
isFirstUpdate++
}
} catch (e: Exception) {
view.showError("Search by location on tapped point has timed out")
}
}
}
}
}
|
apache-2.0
|
77f87f39b3de39086a02fe19ebce6565
| 35.112426 | 109 | 0.568338 | 5.158073 | false | false | false | false |
vhromada/Catalog-Spring
|
src/test/kotlin/cz/vhromada/catalog/web/mapper/EpisodeMapperTest.kt
|
1
|
1393
|
package cz.vhromada.catalog.web.mapper
import cz.vhromada.catalog.entity.Episode
import cz.vhromada.catalog.web.CatalogMapperTestConfiguration
import cz.vhromada.catalog.web.common.EpisodeUtils
import cz.vhromada.catalog.web.fo.EpisodeFO
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
/**
* A class represents test for mapper between [Episode] and [EpisodeFO].
*
* @author Vladimir Hromada
*/
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [CatalogMapperTestConfiguration::class])
class EpisodeMapperTest {
/**
* Mapper for episodes
*/
@Autowired
private lateinit var mapper: EpisodeMapper
/**
* Test method for [EpisodeMapper.map].
*/
@Test
fun map() {
val episode = EpisodeUtils.getEpisode()
val episodeFO = mapper.map(episode)
EpisodeUtils.assertEpisodeDeepEquals(episodeFO, episode)
}
/**
* Test method for [EpisodeMapper.mapBack].
*/
@Test
fun mapBack() {
val episodeFO = EpisodeUtils.getEpisodeFO()
val episode = mapper.mapBack(episodeFO)
EpisodeUtils.assertEpisodeDeepEquals(episodeFO, episode)
}
}
|
mit
|
8429326ee87a9c3b1636d3dad0f080d4
| 25.788462 | 72 | 0.730797 | 4.259939 | false | true | false | false |
gravidence/gravifon
|
lastfm4k/src/main/kotlin/org/gravidence/lastfm4k/api/user/UserApiResponse.kt
|
1
|
2580
|
package org.gravidence.lastfm4k.api.user
import kotlinx.datetime.Instant
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import org.gravidence.lastfm4k.misc.BooleanAsIntSerializer
import org.gravidence.lastfm4k.misc.InstantAsUnixTimeStringSerializer
@Serializable
class UserInfoResponse(
@SerialName("user")
val userInfo: UserInfo
)
@Serializable
class UserInfo(
@SerialName("type")
val type: String,
@SerialName("name")
val name: String,
@SerialName("realname")
val realname: String,
@SerialName("url")
val url: String,
@SerialName("image")
val images: List<Image>,
@SerialName("country")
val country: String,
@SerialName("age")
val age: Int,
@SerialName("gender")
val gender: String, // possible values are f/m/n?
@SerialName("subscriber")
@Serializable(with = BooleanAsIntSerializer::class)
val subscriber: Boolean,
@SerialName("playcount")
val playcount: Long,
@SerialName("playlists")
val playlists: Int,
@SerialName("bootstrap")
val bootstrap: Int,
@SerialName("registered")
val registrationInfo: RegistrationInfo,
)
@Serializable
class RegistrationInfo(
@SerialName("unixtime")
@Serializable(with = InstantAsUnixTimeStringSerializer::class)
val timestamp: Instant,
)
@Serializable
class Image(
@SerialName("size")
val size: ImageSize,
@SerialName("#text")
val url: String,
)
@Serializable(with = ImageSize.AsStringSerializer::class)
enum class ImageSize(val description: String) {
S("small"),
M("medium"),
L("large"),
XL("extralarge");
companion object {
fun valueOfDescription(description: String): ImageSize {
return values().first { it.description == description }
}
}
object AsStringSerializer : KSerializer<ImageSize> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ImageSize", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): ImageSize {
return valueOfDescription(decoder.decodeString())
}
override fun serialize(encoder: Encoder, value: ImageSize) {
encoder.encodeString(value.description)
}
}
}
|
mit
|
eda50e9bc556e04a87feca2b72b57bb6
| 26.168421 | 112 | 0.717054 | 4.534271 | false | false | false | false |
clarkcb/xsearch
|
kotlin/ktsearch/src/main/kotlin/ktsearch/SearchOptions.kt
|
1
|
12329
|
package ktsearch
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.json.simple.JSONValue
import org.json.simple.parser.JSONParser
import org.json.simple.parser.ParseException
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStreamReader
/**
* @author cary on 7/23/16.
*/
data class SearchOption(val shortarg: String?, val longarg: String, val desc: String) {
val sortarg =
if (shortarg == null) {
longarg.toLowerCase()
} else {
shortarg.toLowerCase() + "@" + longarg.toLowerCase()
}
}
class SearchOptions {
private val searchOptions : List<SearchOption>
init {
searchOptions = loadSearchOptionsFromJson()
}
private fun loadSearchOptionsFromJson() : List<SearchOption> {
val searchOptionsXmlPath = "/searchoptions.json"
val searchOptionsInputStream = javaClass.getResourceAsStream(searchOptionsXmlPath)
val obj: Any = JSONParser().parse(InputStreamReader(searchOptionsInputStream))
val jsonObj = obj as JSONObject
val searchoptionsArray = jsonObj["searchoptions"] as JSONArray
val options : MutableList<SearchOption> = mutableListOf()
for (o in searchoptionsArray) {
val searchoptionMap = o as Map<String, String>
val longArg = searchoptionMap["long"] as String
val desc = searchoptionMap["desc"] as String
var shortArg: String? = null
if (searchoptionMap.containsKey("short")) {
shortArg = searchoptionMap["short"] as String
}
options.add(SearchOption(shortArg, longArg, desc))
}
return options.toList().sortedBy { it.sortarg }
}
private fun getArgMap() : Map<String, String> {
val longOpts = searchOptions.map { Pair(it.longarg, it.longarg) }.toMap()
val shortOpts = searchOptions.filter { it.shortarg != null }.map { Pair(it.shortarg!!, it.longarg) }.toMap()
return longOpts.plus(shortOpts)
}
private val argActionMap: Map<String, ((String, SearchSettings) -> SearchSettings)> = mapOf(
"encoding" to
{ s, ss -> ss.copy(textFileEncoding = s) },
"in-archiveext" to
{ s, ss -> ss.copy(inArchiveExtensions = addExtensions(s, ss.inArchiveExtensions)) },
"in-archivefilepattern" to
{ s, ss -> ss.copy(inArchiveFilePatterns = ss.inArchiveFilePatterns.plus(Regex(s))) },
"in-dirpattern" to
{ s, ss -> ss.copy(inDirPatterns = ss.inDirPatterns.plus(Regex(s))) },
"in-ext" to
{ s, ss -> ss.copy(inExtensions = addExtensions(s, ss.inExtensions)) },
"in-filepattern" to
{ s, ss -> ss.copy(inFilePatterns = ss.inFilePatterns.plus(Regex(s))) },
"in-filetype" to
{ s, ss -> ss.copy(inFileTypes = addFileTypes(s, ss.inFileTypes)) },
"in-linesafterpattern" to
{ s, ss -> ss.copy(inLinesAfterPatterns = ss.inLinesAfterPatterns.plus(Regex(s))) },
"in-linesbeforepattern" to
{ s, ss -> ss.copy(inLinesBeforePatterns = ss.inLinesBeforePatterns.plus(Regex(s))) },
"linesafter" to
{ s, ss -> ss.copy(linesAfter = s.toInt()) },
"linesaftertopattern" to
{ s, ss -> ss.copy(linesAfterToPatterns = ss.linesAfterToPatterns.plus(Regex(s))) },
"linesafteruntilpattern" to
{ s, ss -> ss.copy(linesAfterUntilPatterns = ss.linesAfterUntilPatterns.plus(Regex(s))) },
"linesbefore" to
{ s, ss -> ss.copy(linesBefore = s.toInt()) },
"maxlinelength" to
{ s, ss -> ss.copy(maxLineLength = s.toInt()) },
"out-archiveext" to
{ s, ss -> ss.copy(outArchiveExtensions = addExtensions(s, ss.outArchiveExtensions)) },
"out-archivefilepattern" to
{ s, ss -> ss.copy(outArchiveFilePatterns = ss.outArchiveFilePatterns.plus(Regex(s))) },
"out-dirpattern" to
{ s, ss -> ss.copy(outDirPatterns = ss.outDirPatterns.plus(Regex(s))) },
"out-ext" to
{ s, ss -> ss.copy(outExtensions = addExtensions(s, ss.outExtensions)) },
"out-filepattern" to
{ s, ss -> ss.copy(outFilePatterns = ss.outFilePatterns.plus(Regex(s))) },
"out-filetype" to
{ s, ss -> ss.copy(outFileTypes = addFileTypes(s, ss.outFileTypes)) },
"out-linesafterpattern" to
{ s, ss -> ss.copy(outLinesAfterPatterns = ss.outLinesAfterPatterns.plus(Regex(s))) },
"out-linesbeforepattern" to
{ s, ss -> ss.copy(outLinesBeforePatterns = ss.outLinesBeforePatterns.plus(Regex(s))) },
"searchpattern" to
{ s, ss -> ss.copy(searchPatterns = ss.searchPatterns.plus(Regex(s))) },
"settings-file" to
{ s, ss -> settingsFromFile(s, ss) }
)
private val boolFlagActionMap: Map<String, ((Boolean, SearchSettings) -> SearchSettings)> = mapOf(
"archivesonly" to { b, ss -> if (b) ss.copy(archivesOnly = b,
searchArchives = b) else ss.copy(archivesOnly = b) },
"allmatches" to { b, ss -> ss.copy(firstMatch = !b) },
"colorize" to { b, ss -> ss.copy(colorize = b) },
"debug" to { b, ss -> if (b) ss.copy(debug = b, verbose = b) else
ss.copy(debug = b) },
"excludehidden" to { b, ss -> ss.copy(excludeHidden = b) },
"firstmatch" to { b, ss -> ss.copy(firstMatch = b) },
"help" to { b, ss -> ss.copy(printUsage = b) },
"includehidden" to { b, ss -> ss.copy(excludeHidden = !b) },
"listdirs" to { b, ss -> ss.copy(listDirs = b) },
"listfiles" to { b, ss -> ss.copy(listFiles = b) },
"listlines" to { b, ss -> ss.copy(listLines = b) },
"multilinesearch" to { b, ss -> ss.copy(multiLineSearch = b) },
"noprintmatches" to { b, ss -> ss.copy(printResults = !b) },
"norecursive" to { b, ss -> ss.copy(recursive = !b) },
"nosearcharchives" to { b, ss -> ss.copy(searchArchives = !b) },
"printmatches" to { b, ss -> ss.copy(printResults = b) },
"recursive" to { b, ss -> ss.copy(recursive = b) },
"searcharchives" to { b, ss -> ss.copy(searchArchives = b) },
"uniquelines" to { b, ss -> ss.copy(uniqueLines = b) },
"verbose" to { b, ss -> ss.copy(verbose = b) },
"version" to { b, ss -> ss.copy(printVersion = b) }
)
private fun settingsFromFile(filePath: String, settings: SearchSettings) : SearchSettings {
val file = File(filePath)
try {
val json = file.readText()
return settingsFromJson(json, settings)
} catch (e: FileNotFoundException) {
throw SearchException("Settings file not found: $filePath")
} catch (e: IOException) {
throw SearchException("IOException reading settings file: $filePath")
} catch (e: ParseException) {
throw SearchException("ParseException trying to parse the JSON in $filePath")
}
}
fun settingsFromJson(json: String, settings: SearchSettings): SearchSettings {
val obj = JSONValue.parseWithException(json)
val jsonObject = obj as JSONObject
fun recSettingsFromJson(keys: List<Any?>, settings: SearchSettings) : SearchSettings {
return if (keys.isEmpty()) settings
else {
val ko = keys.first()
val vo = jsonObject[ko]
if (ko != null && ko is String && vo != null) {
recSettingsFromJson(keys.drop(1), applySetting(ko, vo, settings))
} else {
recSettingsFromJson(keys.drop(1), settings)
}
}
}
return recSettingsFromJson(obj.keys.toList(), settings)
}
private fun applySetting(key: String, obj: Any, settings: SearchSettings): SearchSettings {
when (obj) {
is String -> {
return applySetting(key, obj, settings)
}
is Boolean -> {
return applySetting(key, obj, settings)
}
is Long -> {
return applySetting(key, obj.toString(), settings)
}
is JSONArray -> {
return applySetting(key, obj.toList().map { it as String }, settings)
}
else -> {
return settings
}
}
}
private fun applySetting(key: String, s: String, settings: SearchSettings): SearchSettings {
return when {
this.argActionMap.containsKey(key) -> {
this.argActionMap[key]!!.invoke(s, settings)
}
key == "startpath" -> {
settings.copy(startPath = s)
}
else -> {
throw SearchException("Invalid option: $key")
}
}
}
private fun applySetting(key: String, bool: Boolean, settings: SearchSettings): SearchSettings {
if (this.boolFlagActionMap.containsKey(key)) {
return this.boolFlagActionMap[key]!!.invoke(bool, settings)
} else {
throw SearchException("Invalid option: $key")
}
}
private fun applySetting(key: String, lst: List<String>, settings: SearchSettings): SearchSettings {
return if (lst.isEmpty()) settings
else {
applySetting(key, lst.drop(1), applySetting(key, lst.first(), settings))
}
}
fun settingsFromArgs(args : Array<String>) : SearchSettings {
val argMap = getArgMap()
fun recSettingsFromArgs(args: List<String>, settings: SearchSettings) : SearchSettings {
if (args.isEmpty()) return settings
val nextArg = args.first()
if (nextArg.startsWith("-")) {
val arg = nextArg.dropWhile { it == '-' }
if (argMap.containsKey(arg)) {
val longArg = argMap[arg]
return if (argActionMap.containsKey(longArg)) {
if (args.size > 1) {
val argVal = args.drop(1).first()
val ss = argActionMap[longArg]!!.invoke(argVal, settings)
recSettingsFromArgs(args.drop(2), ss)
} else {
throw SearchException("Missing value for option $arg")
}
} else if (boolFlagActionMap.containsKey(longArg)) {
val ss = boolFlagActionMap[longArg]!!.invoke(true, settings)
recSettingsFromArgs(args.drop(1), ss)
} else {
throw SearchException("Invalid option: $arg")
}
} else {
throw SearchException("Invalid option: $arg")
}
} else {
return recSettingsFromArgs(args.drop(1), settings.copy(startPath = nextArg))
}
}
return recSettingsFromArgs(args.toList(), getDefaultSettings().copy(printResults = true))
}
fun usage() {
log(getUsageString())
}
private fun getUsageString() : String {
val sb = StringBuilder()
sb.append("Usage:\n")
sb.append(" ktsearch [options] -s <searchpattern> <startpath>\n\n")
sb.append("Options:\n")
fun getOptString(so: SearchOption): String {
return (if (so.shortarg == null) "" else "-${so.shortarg},") + "--${so.longarg}"
}
val optPairs = searchOptions.map { Pair(getOptString(it), it.desc) }
val longest = optPairs.map { it.first.length }.max()
val format = " %1${'$'}-${longest}s %2${'$'}s\n"
for (o in optPairs) {
sb.append(String.format(format, o.first, o.second))
}
return sb.toString()
}
}
|
mit
|
b9b436b1ffa74421d60f131593c24cb5
| 44.662963 | 116 | 0.549031 | 4.176491 | false | false | false | false |
FredJul/TaskGame
|
TaskGame-Hero/src/main/java/net/fred/taskgame/hero/views/AutoResizer.kt
|
1
|
4179
|
/*
* Copyright (c) 2012-2017 Frederic Julian
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.hero.views
import android.content.Context
import android.text.Layout.Alignment
import android.text.StaticLayout
import android.util.AttributeSet
import android.util.TypedValue
import android.widget.TextView
import net.fred.taskgame.hero.R
class AutoResizer(private val textView: TextView) {
var maxTextSize: Float
get() = mMaxTextSize
set(maxTextSize) {
mMaxTextSize = maxTextSize
resizeText()
}
var minTextSize: Float
get() = mMinTextSize
set(minTextSize) {
mMinTextSize = minTextSize
resizeText()
}
private var mMinTextSize: Float = 0.toFloat()
private var mMaxTextSize: Float = 0.toFloat()
init {
val metrics = textView.context.resources.displayMetrics
mMinTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, MIN_TEXT_SIZE_IN_DP.toFloat(), metrics)
mMaxTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, MAX_TEXT_SIZE_IN_DP.toFloat(), metrics)
}
fun initAttrs(context: Context, attrs: AttributeSet) {
val a = context.obtainStyledAttributes(attrs, R.styleable.AutoResizeTextView)
mMinTextSize = a.getDimension(R.styleable.AutoResizeTextView_minTextSize, mMinTextSize)
mMaxTextSize = a.getDimension(R.styleable.AutoResizeTextView_maxTextSize, mMaxTextSize)
a.recycle()
}
/**
* Resize the text size with default width and height
*/
fun resizeText() {
val heightLimit = textView.height - textView.paddingBottom - textView.paddingTop
val widthLimit = textView.width - textView.paddingLeft - textView.paddingRight
val newText = textView.text
// Do not resize if the view does not have dimensions or there is no text
if (newText == null || newText.isEmpty() || heightLimit <= 0 || widthLimit <= 0) {
return
}
// Get the text view's paint object
val textPaint = textView.paint
val originalPaintTextSize = textPaint.textSize
// Bisection method: fast & precise
var lower = mMinTextSize
var upper = mMaxTextSize
var loopCounter = 1
var targetTextSize: Float
var textHeight: Int
while (loopCounter < BISECTION_LOOP_WATCH_DOG && upper - lower > 1) {
targetTextSize = (lower + upper) / 2
// Update the text paint object
textPaint.textSize = targetTextSize
// Measure using a static layout
val layout = StaticLayout(newText, textPaint, widthLimit, Alignment.ALIGN_NORMAL, textView.lineSpacingMultiplier, textView.lineSpacingExtra, true)
textHeight = layout.height
if (textHeight > heightLimit) {
upper = targetTextSize
} else {
lower = targetTextSize
}
loopCounter++
}
textPaint.textSize = originalPaintTextSize // need to restore the initial one to avoid graphical issues
targetTextSize = lower
// Some devices try to auto adjust line spacing, so force default line spacing
// and invalidate the layout as a side effect
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize)
}
companion object {
private val MIN_TEXT_SIZE_IN_DP = 9
private val MAX_TEXT_SIZE_IN_DP = 50
private val BISECTION_LOOP_WATCH_DOG = 30
}
}
|
gpl-3.0
|
cb7fec8bf1aa039491aa75d50ac813fe
| 34.117647 | 158 | 0.667385 | 4.587267 | false | false | false | false |
http4k/http4k
|
http4k-testing/chaos/src/test/kotlin/org/http4k/chaos/ChaosBehaviourTests.kt
|
1
|
9596
|
package org.http4k.chaos
import com.natpryce.hamkrest.and
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.matches
import com.natpryce.hamkrest.throws
import org.http4k.chaos.ChaosBehaviours.KillProcess
import org.http4k.chaos.ChaosBehaviours.Latency
import org.http4k.chaos.ChaosBehaviours.NoBody
import org.http4k.chaos.ChaosBehaviours.None
import org.http4k.chaos.ChaosBehaviours.ReturnStatus
import org.http4k.chaos.ChaosBehaviours.StackOverflow
import org.http4k.chaos.ChaosBehaviours.ThrowException
import org.http4k.chaos.ChaosBehaviours.Variable
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.NOT_FOUND
import org.http4k.core.Status.Companion.OK
import org.http4k.core.then
import org.http4k.format.Jackson.asJsonObject
import org.http4k.hamkrest.hasBody
import org.http4k.hamkrest.hasHeader
import org.http4k.hamkrest.hasMethod
import org.http4k.hamkrest.hasStatus
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import java.time.Duration.ofMillis
import java.util.Properties
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.MILLISECONDS
import kotlin.concurrent.thread
import kotlin.random.Random
private val request = Request(GET, "").body("hello")
private val response = Response(OK).body("hello")
abstract class ChaosBehaviourContract {
@Test
abstract fun `deserialises from JSON`()
}
class ThrowExceptionBehaviourTest : ChaosBehaviourContract() {
private val description = "ThrowException RuntimeException foo"
@Test
fun `exception throwing behaviour should throw exception`() {
val expected = RuntimeException("foo")
val throwException = ThrowException(expected)
assertThat(throwException.toString(), equalTo(description))
assertThat({ throwException.then { response }(request) }, throws(equalTo(expected)))
}
@Test
override fun `deserialises from JSON`() {
val behaviour = """{"type":"throw","message":"foo"}""".asJsonObject().asBehaviour()
assertThat(behaviour.toString(), equalTo("ThrowException RuntimeException foo"))
assertThat({ behaviour.then { response }(request) }, throws<Exception>())
}
}
class LatencyBehaviourTest : ChaosBehaviourContract() {
private val description = "Latency (range = PT0.1S to PT0.3S)"
@Test
fun `latency from env`() {
val props = Properties().apply {
put("CHAOS_LATENCY_MS_MIN", "100")
put("CHAOS_LATENCY_MS_MAX", "300")
}
assertThat(Latency.fromEnv(props::getProperty).toString(), equalTo(description))
assertThat(Latency.fromEnv().toString(), equalTo("Latency (range = PT0.1S to PT0.5S)"))
}
@Test
override fun `deserialises from JSON`() {
assertBehaviour("""{"type":"latency","min":"PT0.1S","max":"PT0.3S"}""",
description,
hasStatus(OK).and(hasHeader("x-http4k-chaos", Regex("Latency.*"))))
}
@Test
fun `latency behaviour should add extra latency`() {
val delay = 100L
val latency = Latency(ofMillis(delay), ofMillis(delay + 1))
assertThat(latency.toString(), equalTo("Latency (range = PT0.1S to PT0.101S)"))
val latch = CountDownLatch(1)
thread {
latency.then { response }(request)
latch.countDown()
}
assertThat(latch.await(delay - 1, MILLISECONDS), equalTo(false))
}
}
class ReturnStatusBehaviourTest : ChaosBehaviourContract() {
private val description = "ReturnStatus (404)"
@Test
fun `should return response with internal server error status`() {
val returnStatus: Behaviour = ReturnStatus(NOT_FOUND)
assertThat(returnStatus.toString(), equalTo(description))
val injectedResponse = returnStatus.then { response }(request)
assertEquals(NOT_FOUND, injectedResponse.status)
}
@Test
override fun `deserialises from JSON`() {
assertBehaviour("""{"type":"status","status":404}""",
description,
hasStatus(NOT_FOUND.description("x-http4k-chaos")).and(hasHeader("x-http4k-chaos", Regex("Status 404"))))
}
}
class NoBodyBehaviourTest : ChaosBehaviourContract() {
private val description = "SnipBody"
@Test
fun `should return no body`() {
val noBody = NoBody()
assertThat(noBody.toString(), equalTo(description))
assertThat(noBody.then { response }(request), hasHeader("x-http4k-chaos", "Snip body (0b)").and(hasBody("")))
}
@Test
override fun `deserialises from JSON`() {
assertBehaviour("""{"type":"body"}""",
description,
hasStatus(OK).and(hasHeader("x-http4k-chaos", "Snip body (0b)")))
}
}
class SnipBodyBehaviourTest : ChaosBehaviourContract() {
private val description = "SnipBody"
@Test
fun `should return snipped body`() {
val snipBody = ChaosBehaviours.SnipBody(Random(1)) { 3 }
assertThat(snipBody.toString(), equalTo(description))
assertThat(snipBody.then { response }(request), hasHeader("x-http4k-chaos", "Snip body (1b)").and(hasBody("h")))
}
@Test
override fun `deserialises from JSON`() {
assertBehaviour("""{"type":"snip"}""",
description,
hasStatus(OK).and(hasHeader("x-http4k-chaos", matches("""Snip body \(\db\)""".toRegex()))))
}
}
class SnipRequestBodyBehaviourTest : ChaosBehaviourContract() {
private val description = "SnipRequestBody"
@Test
fun `should snip request body`() {
val snipBody = ChaosBehaviours.SnipRequestBody(Random(1)) { 3 }
assertThat(snipBody.toString(), equalTo(description))
assertThat(snipBody.then {
assertThat(it, hasBody("h"))
response
}(request), equalTo(response))
}
@Test
override fun `deserialises from JSON`() {
assertBehaviour("""{"type":"sniprequest"}""",
description,
hasMethod(GET).and(hasHeader("x-http4k-chaos", matches("""Snip request body \(\db\)""".toRegex()))))
}
}
class BlockThreadBehaviourTest : ChaosBehaviourContract() {
private val description = "BlockThread"
@Test
fun `should block thread`() {
val blockThread = ChaosBehaviours.BlockThread()
assertThat(blockThread.toString(), equalTo(description))
val latch = CountDownLatch(1)
thread {
blockThread.then { response }(request)
latch.countDown()
}
assertThat(latch.await(100, MILLISECONDS), equalTo(false))
}
@Test
override fun `deserialises from JSON`() {
val behaviour = """{"type":"block"}""".asJsonObject().asBehaviour()
assertThat(behaviour.toString(), equalTo(description))
}
}
class EatMemoryBehaviourTest : ChaosBehaviourContract() {
private val description = "EatMemory"
@Test
fun `should eat memory`() {
val eatMemory = ChaosBehaviours.EatMemory()
assertThat(eatMemory.toString(), equalTo(description))
assertThat({ eatMemory.then { response }(request) }, throws<OutOfMemoryError>())
}
@Test
override fun `deserialises from JSON`() {
val behaviour = """{"type":"memory"}""".asJsonObject().asBehaviour()
assertThat(behaviour.toString(), equalTo(description))
}
}
class DoNothingBehaviourTest : ChaosBehaviourContract() {
private val description = "None"
@Test
fun `should do nothing memory`() {
assertThat(None().toString(), equalTo(description))
assertThat(None().then { response }(request), equalTo(response))
}
@Test
override fun `deserialises from JSON`() {
val behaviour = """{"type":"none"}""".asJsonObject().asBehaviour()
assertThat(behaviour.toString(), equalTo(description))
}
}
class StackOverflowBehaviourTest : ChaosBehaviourContract() {
private val description = "StackOverflow"
@Test
@Disabled // untestable
fun `should stack overflow`() {
val stackOverflow = StackOverflow()
assertThat(stackOverflow.toString(), equalTo(description))
stackOverflow.then { response }(request)
}
@Test
override fun `deserialises from JSON`() {
val behaviour = """{"type":"overflow"}""".asJsonObject().asBehaviour()
assertThat(behaviour.toString(), equalTo(description))
}
}
class KillProcessBehaviourTest : ChaosBehaviourContract() {
private val description = "KillProcess"
@Test
@Disabled // untestable
fun `should kill process`() {
val killProcess = KillProcess()
assertThat(killProcess.toString(), equalTo(description))
killProcess.then { response }(request)
}
@Test
override fun `deserialises from JSON`() {
val behaviour = """{"type":"kill"}""".asJsonObject().asBehaviour()
assertThat(behaviour.toString(), equalTo(description))
}
}
class VariableBehaviourTest {
@Test
fun `should provide ability to modify behaviour at runtime`() {
val variable = Variable()
assertThat(variable.toString(), equalTo(("None")))
assertThat(variable.then { response }(request), equalTo(response))
variable.current = NoBody()
assertThat(variable.toString(), equalTo(("SnipBody")))
assertThat(variable.then { response }(request), hasHeader("x-http4k-chaos", "Snip body (0b)").and(hasBody("")))
}
}
|
apache-2.0
|
e67d7b14f6c408ded7999a3734f4ef55
| 32.43554 | 120 | 0.669758 | 4.184911 | false | true | false | false |
martinlschumann/mal
|
kotlin/src/mal/types.kt
|
5
|
6720
|
package mal
import java.util.*
open class MalException(message: String?) : Exception(message), MalType {
override var metadata: MalType = NIL
override fun with_meta(meta: MalType): MalType {
val exception = MalException(message)
exception.metadata = meta
return exception
}
}
class MalContinue() : MalException("continue")
class MalReaderException(message: String) : MalException(message)
class MalPrinterException(message: String) : MalException(message)
class MalCoreException(message: String, val value: MalType) : MalException(message) {
override fun with_meta(meta: MalType): MalType {
val exception = MalCoreException(message as String, value)
exception.metadata = meta
return exception
}
}
interface MalType {
var metadata: MalType
fun with_meta(meta: MalType): MalType
}
open class MalConstant(val value: String) : MalType {
override var metadata: MalType = NIL
override fun equals(other: Any?): Boolean = other is MalConstant && value.equals(other.value)
override fun hashCode(): Int = value.hashCode()
override fun with_meta(meta: MalType): MalType {
val obj = MalConstant(value)
obj.metadata = meta
return obj
}
}
class MalInteger(val value: Long) : MalType {
override var metadata: MalType = NIL
operator fun plus(a: MalInteger): MalInteger = MalInteger(value + a.value)
operator fun minus(a: MalInteger): MalInteger = MalInteger(value - a.value)
operator fun times(a: MalInteger): MalInteger = MalInteger(value * a.value)
operator fun div(a: MalInteger): MalInteger = MalInteger(value / a.value)
operator fun compareTo(a: MalInteger): Int = value.compareTo(a.value)
override fun equals(other: Any?): Boolean = other is MalInteger && value.equals(other.value)
override fun with_meta(meta: MalType): MalType {
val obj = MalInteger(value)
obj.metadata = meta
return obj
}
}
class MalSymbol(val value: String) : MalType {
override var metadata: MalType = NIL
override fun equals(other: Any?): Boolean = other is MalSymbol && value.equals(other.value)
override fun with_meta(meta: MalType): MalType {
val obj = MalSymbol(value)
obj.metadata = meta
return obj
}
}
open class MalString(value: String) : MalConstant(value) {
override fun with_meta(meta: MalType): MalType {
val obj = MalString(value)
obj.metadata = meta
return obj
}
}
class MalKeyword(value: String) : MalString("\u029E" + value) {
override fun with_meta(meta: MalType): MalType {
val obj = MalKeyword(value)
obj.metadata = meta
return obj
}
}
interface ILambda : MalType {
fun apply(seq: ISeq): MalType
}
open class MalFunction(val lambda: (ISeq) -> MalType) : MalType, ILambda {
var is_macro: Boolean = false
override var metadata: MalType = NIL
override fun apply(seq: ISeq): MalType = lambda(seq)
override fun with_meta(meta: MalType): MalType {
val obj = MalFunction(lambda)
obj.metadata = meta
return obj
}
}
class MalFnFunction(val ast: MalType, val params: Sequence<MalSymbol>, val env: Env, lambda: (ISeq) -> MalType) : MalFunction(lambda) {
override fun with_meta(meta: MalType): MalType {
val obj = MalFnFunction(ast, params, env, lambda)
obj.metadata = meta
return obj
}
}
interface ISeq : MalType {
fun seq(): Sequence<MalType>
fun first(): MalType
fun rest(): ISeq
fun nth(n: Int): MalType
fun count(): Int
fun slice(fromIndex: Int, toIndex: Int): ISeq
fun conj(s: ISeq): ISeq
}
interface IMutableSeq : ISeq {
fun conj_BANG(form: MalType)
}
abstract class MalSequence(val elements: MutableList<MalType>) : MalType, IMutableSeq {
override var metadata: MalType = NIL
override fun seq(): Sequence<MalType> = elements.asSequence()
override fun first(): MalType = elements.first()
override fun nth(n: Int): MalType = elements.elementAt(n)
override fun count(): Int = elements.count()
override fun conj_BANG(form: MalType) {
elements.add(form)
}
override fun equals(other: Any?): Boolean =
(other is ISeq)
&& elements.size == other.count()
&& elements.asSequence().zip(other.seq()).all({ it -> it.first == it.second })
}
class MalList(elements: MutableList<MalType>) : MalSequence(elements) {
constructor() : this(LinkedList<MalType>())
constructor(s: ISeq) : this(s.seq().toCollection(LinkedList<MalType>()))
override fun rest(): ISeq = MalList(elements.drop(1).toCollection(LinkedList<MalType>()))
override fun slice(fromIndex: Int, toIndex: Int): MalList =
MalList(elements.subList(fromIndex, toIndex))
override fun conj(s: ISeq): ISeq {
val list = LinkedList<MalType>(elements)
s.seq().forEach({ it -> list.addFirst(it) })
return MalList(list)
}
override fun with_meta(meta: MalType): MalType {
val obj = MalList(elements)
obj.metadata = meta
return obj
}
}
class MalVector(elements: MutableList<MalType>) : MalSequence(elements) {
override var metadata: MalType = NIL
constructor() : this(ArrayList<MalType>())
constructor(s: ISeq) : this(s.seq().toCollection(ArrayList<MalType>()))
override fun rest(): ISeq = MalVector(elements.drop(1).toCollection(ArrayList<MalType>()))
override fun slice(fromIndex: Int, toIndex: Int): MalVector =
MalVector(elements.subList(fromIndex, toIndex))
override fun conj(s: ISeq): ISeq = MalVector(elements.plus(s.seq()).toCollection(ArrayList<MalType>()))
override fun with_meta(meta: MalType): MalType {
val obj = MalVector(elements)
obj.metadata = meta
return obj
}
}
class MalHashMap() : MalType {
override var metadata: MalType = NIL
val elements = HashMap<MalString, MalType>()
constructor(other: MalHashMap) : this() {
other.elements.forEach({ it -> assoc_BANG(it.key, it.value) })
}
fun assoc_BANG(key: MalString, value: MalType) = elements.put(key, value)
fun dissoc_BANG(key: MalString) {
elements.remove(key)
}
override fun with_meta(meta: MalType): MalType {
val obj = MalHashMap(this)
obj.metadata = meta
return obj
}
}
class MalAtom(var value: MalType) : MalType {
override var metadata: MalType = NIL
override fun with_meta(meta: MalType): MalType = throw UnsupportedOperationException()
}
val NIL = MalConstant("nil")
val TRUE = MalConstant("true")
val FALSE = MalConstant("false")
val ZERO = MalInteger(0)
|
mpl-2.0
|
10d6140c68a8fb18ad371ab16eb41c67
| 29.684932 | 135 | 0.659673 | 4.060423 | false | false | false | false |
strooooke/quickfit
|
app/src/main/java/com/lambdasoup/quickfit/Constants.kt
|
1
|
1614
|
/*
* Copyright 2016 Juliane Lehmann <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit
import com.google.android.gms.fitness.FitnessOptions
import com.google.android.gms.fitness.data.DataType
object Constants {
const val NOTIFICATION_PLAY_INTERACTION = 0
const val NOTIFICATION_CHANNEL_ID_PLAY_INTERACTION = "play_interaction"
const val NOTIFICATION_ALARM = 1
const val NOTIFICATION_CHANNEL_ID_ALARM = "alarm"
const val NOTIFICATION_ALARM_BG_IO_WORK = 2
const val NOTIFICATION_CHANNEL_ID_BG_IO = "bg_io"
const val PENDING_INTENT_ALARM_RECEIVER = 0
const val PENDING_INTENT_WORKOUT_LIST = 1
const val PENDING_INTENT_DID_IT = 2
const val PENDING_INTENT_SNOOZE = 3
const val PENDING_INTENT_DISMISS_ALARM = 4
const val JOB_ID_FIT_ACTIVITY_SERVICE = 100
val FITNESS_API_OPTIONS = FitnessOptions.builder()
.addDataType(DataType.TYPE_ACTIVITY_SEGMENT, FitnessOptions.ACCESS_WRITE)
.addDataType(DataType.TYPE_CALORIES_EXPENDED, FitnessOptions.ACCESS_WRITE)
.build()
}
|
apache-2.0
|
21ca3c1d83dbb48818971b235293e130
| 40.384615 | 86 | 0.73482 | 3.927007 | false | false | false | false |
blackbbc/Tucao
|
app/src/main/kotlin/me/sweetll/tucao/rxdownload/entity/BeanListConverter.kt
|
1
|
893
|
package me.sweetll.tucao.rxdownload.entity
import com.raizlabs.android.dbflow.converter.TypeConverter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
class BeanListConverter: TypeConverter<String, MutableList<DownloadBean>>() {
private val adapter by lazy {
val type = Types.newParameterizedType(MutableList::class.java, DownloadBean::class.java)
Moshi.Builder().build()
.adapter<MutableList<DownloadBean>>(type)
}
override fun getDBValue(model: MutableList<DownloadBean>?): String {
if (model == null) {
return "[]"
} else {
return adapter.toJson(model)
}
}
override fun getModelValue(data: String?): MutableList<DownloadBean> {
if (data == null) {
return mutableListOf()
} else {
return adapter.fromJson(data)!!
}
}
}
|
mit
|
65a61d67bdf5ddda80e3cd739fdc61d5
| 28.766667 | 96 | 0.637178 | 4.510101 | false | false | false | false |
rustamgaifullin/TranslateIt
|
app/src/androidTest/java/com/rm/translateit/ui/activities/MainActivityTest.kt
|
1
|
2039
|
package com.rm.translateit.ui.activities
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import com.rm.translateit.R
import com.rm.translateit.api.languages.Languages
import com.rm.translateit.utils.checkSpinnerEqualsToText
import com.rm.translateit.utils.checkTextInSpinner
import com.rm.translateit.utils.checkTextNotInSpinner
import com.rm.translateit.utils.clickOnButton
import com.rm.translateit.utils.clickOnSpinner
import com.rm.translateit.utils.selectTextInSpinner
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import javax.inject.Inject
@LargeTest
@RunWith(AndroidJUnit4::class)
open class MainActivityTest {
@JvmField
@Rule
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Inject
lateinit var languageService: Languages
@Test
fun checkLanguageButtonSwapLanguagesProperly() {
val originLanguage = "English"
val destinationLanguage = "Polish"
clickOnSpinner(R.id.origin_spinner)
selectTextInSpinner(originLanguage)
clickOnSpinner(R.id.destination_spinner)
selectTextInSpinner(destinationLanguage)
clickOnButton(R.id.changeLanguage_button)
checkSpinnerEqualsToText(R.id.origin_spinner, destinationLanguage)
checkSpinnerEqualsToText(R.id.destination_spinner, originLanguage)
}
@Test
fun checkDestinationSpinnerShowsCorrectLanguages() {
val listOfLanguages = languageService.all()
val localeCode = "en"
listOfLanguages.forEach { language ->
clickOnSpinner(R.id.origin_spinner)
selectTextInSpinner(language.findName(localeCode).capitalize())
val expectedDestinationLanguages = listOfLanguages
.asSequence()
.filter { it != language }
.mapNotNull { it.findName(localeCode) }
.toList()
checkTextInSpinner(R.id.destination_spinner, expectedDestinationLanguages)
checkTextNotInSpinner(R.id.destination_spinner, language.findName(localeCode))
}
}
}
|
mit
|
10e3a6dc1a9a61b5e1c7c044ebeb33f6
| 30.875 | 84 | 0.781756 | 4.221532 | false | true | false | false |
kannix68/advent_of_code_2016
|
day24/src_kotlin/World.kt
|
1
|
2321
|
/**
* World class.
*/
class World(val dimx: Int, val dimy: Int) : AocBase() {
val grid: Array<IntArray>
var pointnodes = mutableListOf<PointNode>()
init {
grid = Array(dimy){IntArray(dimx)}
deblog("init-world dimx=$dimx, dimy=$dimy")
deblog(" World-grid=$grid")
}
//companion object Factory {
// fun create(): World = World()
//}
companion object {
/**
* Create from a string representation.
*/
fun create(repr2d: String): World {
var dimx = 0
var linenum = 0
repr2d.split("\n").forEach { line ->
linenum += 1
tracelog("found >$line<")
if (line.length > dimx) {
dimx = line.length
}
}
val dimy = linenum
val world = World(dimx, dimy)
var y = -1
repr2d.split("\n").forEach { line ->
y += 1
for (x in 0..line.length-1) {
val c = line[x].toString()
if (c == "#") { // wall:
world.grid[y][x] = 0
} else if (c == "."){ // room:
world.grid[y][x] = 1
} else { // "1" room with node:
world.grid[y][x] = 1
val pointnode = PointNode("$x,$y", c)
deblog("create pointnode $pointnode.")
world.pointnodes.add(pointnode)
}
}
}
return world
}
/**
* Create alogrithmicly with dimensions and a numeric seed/salt.
*/
fun create(dimx: Int, dimy: Int, seed: Int): World {
val world = World(dimx, dimy)
for (y in 0..dimy-1) {
for (x in 0..dimx-1) {
val z = x*x + 3*x + 2*x*y + y + y*y + seed
val bs = Integer.toBinaryString(z)
val cts = bs.split("").filter{it=="1"}.joinToString("")
val ct = cts.length
if (ct%2 == 0) { // room:
world.grid[y][x] = 1
} else { // wall:
world.grid[y][x] = 0
}
}
}
return world
}
}
override fun toString(): String {
return "world($dimx,$dimy)"
}
fun printgrid() {
println("v/>0123456789abcdef")
grid.forEachIndexed { y, ar ->
//var s = "$y:: "
var s = "$y: "
ar.forEachIndexed { x, v ->
if (v == 1) {
s += "."
} else {
s += "#"
}
}
println(s)
}
}
}
|
mit
|
a416921e495a3c0bcfe5d6dceccd62c4
| 23.691489 | 68 | 0.464886 | 3.398243 | false | false | false | false |
cemrich/zapp
|
app/src/main/java/de/christinecoenen/code/zapp/utils/system/ImageHelper.kt
|
1
|
1673
|
package de.christinecoenen.code.zapp.utils.system
import android.content.Context
import android.graphics.Bitmap
import android.media.ThumbnailUtils
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Size
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
object ImageHelper {
private val THUMBNAIL_SIZE = Size(640, 240)
@JvmStatic
suspend fun loadThumbnailAsync(context: Context, filePath: String?): Bitmap =
withContext(Dispatchers.Default) {
loadThumbnail(context, filePath)
}
private fun loadThumbnail(context: Context, filePath: String?): Bitmap {
if (filePath == null) {
throw Exception("Could not generate thumbnail when filePath is null.")
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val contentResolver = context.contentResolver
try {
// with api level this high we can use content resolver to generate thumbnails
contentResolver.loadThumbnail(Uri.parse(filePath), THUMBNAIL_SIZE, null)
} catch (e: IOException) {
try {
// fall back to ThumbnailUtils when content resolver failed
ThumbnailUtils.createVideoThumbnail(File(filePath), THUMBNAIL_SIZE, null)
} catch (e: IOException) {
// complete failure
throw Exception("Could not generate thumbnail for file $filePath")
}
}
} else {
// old method of loading thumbnails
@Suppress("DEPRECATION")
ThumbnailUtils.createVideoThumbnail(
filePath,
MediaStore.Images.Thumbnails.FULL_SCREEN_KIND
)
?: throw Exception("Could not generate thumbnail for file $filePath")
}
}
}
|
mit
|
595b0ac77ab833184363c578e25b0926
| 28.350877 | 82 | 0.746563 | 4.041063 | false | false | false | false |
strazzere/simplify
|
sdbg/src/main/java/org/cf/sdbg/command/CliCommands.kt
|
2
|
1236
|
package org.cf.sdbg.command
import org.cf.sdbg.Main
import org.jline.reader.LineReader
import org.jline.reader.impl.LineReaderImpl
import picocli.CommandLine
import java.io.PrintWriter
@CommandLine.Command(name = "", version = [Main.version], footer = ["", "Press Ctl-D to exit."],
description = [
"Smali DeBuGger (SDBG) Hit @|magenta <TAB>|@ to see available commands.",
"Type `@|bold,yellow keymap ^[s tailtip-toggle|@`, then hit @|magenta ALT-S|@ to toggle tailtips.",
""
],
subcommands = [
CommandLine.HelpCommand::class,
ClearScreenCommand::class,
ListCommand::class,
WhereCommand::class,
StepCommand::class,
NextCommand::class,
InfoCommand::class,
PrintCommand::class,
BreakCommand::class,
ContinueCommand::class
])
class CliCommands : Runnable {
lateinit var reader: LineReaderImpl
lateinit var out: PrintWriter
fun setReader(reader: LineReader) {
this.reader = reader as LineReaderImpl
out = reader.terminal.writer()
}
override fun run() {
out.println(CommandLine(this).usageMessage)
}
}
|
mit
|
d7d464f9bdd8d47364788ba97e4fdd31
| 30.692308 | 111 | 0.614078 | 4.12 | false | false | false | false |
ankidroid/Anki-Android
|
AnkiDroid/src/main/java/com/ichi2/anki/Onboarding.kt
|
2
|
15267
|
/****************************************************************************************
* *
* Copyright (c) 2021 Shridhar Goel <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki
import android.content.Context
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.VisibleForTesting
import androidx.recyclerview.widget.LinearLayoutManager
import com.ichi2.anki.OnboardingUtils.Companion.addFeatures
import com.ichi2.anki.OnboardingUtils.Companion.isVisited
import com.ichi2.anki.OnboardingUtils.Companion.setVisited
import com.ichi2.utils.HandlerUtils.executeFunctionUsingHandler
/**
* Suppose a tutorial needs to be added for an activity called MyActivity.
* Steps for doing it:
*
* 1. If an inner class for MyActivity exists, then use it otherwise create a new class
* inside Onboarding and initialise an object of that class inside MyActivity. In this case,
* call onCreate() if the tutorial needs to be displayed when the screen is opened and does not have
* any particular time or view visibility on which it depends. If the class already exists,
* go to step 3.
*
* 2. If MyActivity does not already exist, then create it by extending Onboarding and
* then create a new enum class implementing OnboardingFlag.
*
* 3. Create a new method to display the tutorial.
*
* 4. Add the function using TutorialArgument data class to the list of tutorials in the init block
* if it has to be invoked which the screen is opened. If the function has to be invoked at a particular
* time, then call it from MyActivity.
*
* 5. For any extra condition that needs to be checked before displaying a tutorial, add it as the
* 'mOnboardingCondition' parameter in TutorialArguments.
*/
// Contains classes for various screens. Each sub-class has methods to show onboarding tutorials.
// TODO: Move OnboardingUtils.featureConstants to a DI container rather than a mutable singleton
abstract class Onboarding<Feature>(
private val context: Context,
val tutorials: MutableList<TutorialArguments<Feature>>
) where Feature : Enum<Feature>, Feature : OnboardingFlag {
companion object {
// Constants being used for onboarding preferences should not be modified.
const val DECK_PICKER_ONBOARDING = "DeckPickerOnboarding"
const val REVIEWER_ONBOARDING = "ReviewerOnboarding"
const val NOTE_EDITOR_ONBOARDING = "NoteEditorOnboarding"
const val CARD_BROWSER_ONBOARDING = "CardBrowserOnboarding"
init {
addDefaultFeatures()
}
@VisibleForTesting
fun resetOnboardingForTesting() {
OnboardingUtils.featureConstants.clear()
addDefaultFeatures()
}
private fun addDefaultFeatures() {
addFeatures(
listOf(
DECK_PICKER_ONBOARDING,
REVIEWER_ONBOARDING,
NOTE_EDITOR_ONBOARDING,
CARD_BROWSER_ONBOARDING,
)
)
}
}
/**
* Contains the logic for iterating through various tutorials of a screen and displaying the first one
* in the list which is not visited yet and condition (if any) also holds true for it.
*
* @param mContext Context of the Activity
* @param mTutorials List of tutorials for the Activity
*/
fun onCreate() {
tutorials.forEach {
// If tutorial is visited or condition is false then return from the loop.
if (isVisited(it.featureIdentifier, context) || it.onboardingCondition?.invoke() == false) {
return@forEach
}
// Invoke the function to display the tutorial.
it.onboardingFunction.invoke()
// Return so that other tutorials are not displayed.
return
}
}
/**
* Arguments required to handle the tutorial for a screen.
*
* @param featureIdentifier Enum constant for the feature.
* @param onboardingFunction Function which has to be invoked if the tutorial needs to be displayed.
* @param onboardingCondition Condition to be checked before displaying the tutorial. Tutorial should
* be displayed only if mOnboardingCondition is not null and returns true. Default value is null
* which indicates that no condition is required.
*/
data class TutorialArguments<Feature>(
val featureIdentifier: Feature,
val onboardingFunction: () -> Unit,
val onboardingCondition: (() -> Boolean)? = null
)
where Feature : Enum<Feature>, Feature : OnboardingFlag
class DeckPicker(
private val activityContext: com.ichi2.anki.DeckPicker,
private val recyclerViewLayoutManager: LinearLayoutManager
) : Onboarding<DeckPicker.DeckPickerOnboardingEnum>(activityContext, mutableListOf()) {
init {
tutorials.add(TutorialArguments(DeckPickerOnboardingEnum.FAB, this::showTutorialForFABIfNew))
tutorials.add(TutorialArguments(DeckPickerOnboardingEnum.DECK_NAME, this::showTutorialForDeckIfNew, activityContext::hasAtLeastOneDeckBeingDisplayed))
tutorials.add(TutorialArguments(DeckPickerOnboardingEnum.COUNTS_LAYOUT, this::showTutorialForCountsLayoutIfNew, activityContext::hasAtLeastOneDeckBeingDisplayed))
}
private fun showTutorialForFABIfNew() {
CustomMaterialTapTargetPromptBuilder(activityContext, DeckPickerOnboardingEnum.FAB)
.createCircleWithDimmedBackground()
.setFocalColourResource(R.color.material_blue_500)
.setDismissedListener { onCreate() }
.setTarget(R.id.fab_main)
.setPrimaryText(R.string.fab_tutorial_title)
.setSecondaryText(R.string.fab_tutorial_desc)
.show()
}
private fun showTutorialForDeckIfNew() {
CustomMaterialTapTargetPromptBuilder(activityContext, DeckPickerOnboardingEnum.DECK_NAME)
.createRectangleWithDimmedBackground()
.setDismissedListener { showTutorialForCountsLayoutIfNew() }
.setTarget(recyclerViewLayoutManager.getChildAt(0)?.findViewById(R.id.deck_name_linear_layout))
.setPrimaryText(R.string.start_studying)
.setSecondaryText(R.string.start_studying_desc)
.show()
}
private fun showTutorialForCountsLayoutIfNew() {
CustomMaterialTapTargetPromptBuilder(activityContext, DeckPickerOnboardingEnum.COUNTS_LAYOUT)
.createRectangleWithDimmedBackground()
.setTarget(recyclerViewLayoutManager.getChildAt(0)?.findViewById(R.id.counts_layout))
.setPrimaryText(R.string.menu__study_options)
.setSecondaryText(R.string.study_options_desc)
.show()
}
enum class DeckPickerOnboardingEnum(var value: Int) : OnboardingFlag {
FAB(0), DECK_NAME(1), COUNTS_LAYOUT(2);
override fun getOnboardingEnumValue(): Int {
return value
}
override fun getFeatureConstant(): String {
return DECK_PICKER_ONBOARDING
}
}
}
class Reviewer(private val activityContext: com.ichi2.anki.Reviewer) :
Onboarding<Reviewer.ReviewerOnboardingEnum>(activityContext, mutableListOf()) {
init {
tutorials.add(TutorialArguments(ReviewerOnboardingEnum.SHOW_ANSWER, this::onQuestionShown))
tutorials.add(TutorialArguments(ReviewerOnboardingEnum.FLAG, this::showTutorialForFlagIfNew))
}
private fun onQuestionShown() {
CustomMaterialTapTargetPromptBuilder(activityContext, ReviewerOnboardingEnum.SHOW_ANSWER)
.createRectangleWithDimmedBackground()
.setDismissedListener { onCreate() }
.setTarget(R.id.flip_card)
.setPrimaryText(R.string.see_answer)
.setSecondaryText(R.string.see_answer_desc)
.show()
}
/**
* Called when the difficulty buttons are displayed after clicking on 'Show Answer'.
*/
fun onAnswerShown() {
if (isVisited(ReviewerOnboardingEnum.DIFFICULTY_RATING, activityContext)) {
return
}
CustomMaterialTapTargetPromptBuilder(activityContext, ReviewerOnboardingEnum.DIFFICULTY_RATING)
.createRectangleWithDimmedBackground()
.setTarget(R.id.ease_buttons)
.setPrimaryText(R.string.select_difficulty)
.setSecondaryText(R.string.select_difficulty_desc)
.show()
}
private fun showTutorialForFlagIfNew() {
// Handler is required here to show feature prompt on menu items. Reference: https://github.com/sjwall/MaterialTapTargetPrompt/issues/73#issuecomment-320681655
executeFunctionUsingHandler {
CustomMaterialTapTargetPromptBuilder(activityContext, ReviewerOnboardingEnum.FLAG)
.createCircle()
.setFocalColourResource(R.color.material_blue_500)
.setTarget(R.id.action_flag)
.setPrimaryText(R.string.menu_flag_card)
.setSecondaryText(R.string.flag_card_desc)
.show()
}
}
/**
* Show after undo button goes into enabled state
*/
fun onUndoButtonEnabled() {
if (isVisited(ReviewerOnboardingEnum.UNDO, activityContext)) {
return
}
CustomMaterialTapTargetPromptBuilder(activityContext, ReviewerOnboardingEnum.UNDO)
.createCircleWithDimmedBackground()
.setFocalColourResource(R.color.material_blue_500)
.setTarget(R.id.action_undo)
.setPrimaryText(R.string.undo)
.setSecondaryText(R.string.undo_desc)
.show()
}
enum class ReviewerOnboardingEnum(var value: Int) : OnboardingFlag {
SHOW_ANSWER(0), DIFFICULTY_RATING(1), FLAG(2), UNDO(3);
override fun getOnboardingEnumValue(): Int {
return value
}
override fun getFeatureConstant(): String {
return REVIEWER_ONBOARDING
}
}
}
class NoteEditor(private val activityContext: com.ichi2.anki.NoteEditor) :
Onboarding<NoteEditor.NoteEditorOnboardingEnum>(activityContext, mutableListOf()) {
init {
tutorials.add(TutorialArguments(NoteEditorOnboardingEnum.FRONT_BACK, this::showTutorialForFrontAndBackIfNew))
tutorials.add(TutorialArguments(NoteEditorOnboardingEnum.FORMATTING_TOOLS, this::showTutorialForFormattingTools))
}
private fun showTutorialForFrontAndBackIfNew() {
CustomMaterialTapTargetPromptBuilder(activityContext, NoteEditorOnboardingEnum.FRONT_BACK)
.createRectangleWithDimmedBackground()
.setDismissedListener { onCreate() }
.setTarget(R.id.CardEditorEditFieldsLayout)
.setPrimaryText(R.string.card_contents)
.setSecondaryText(R.string.card_contents_desc)
.show()
}
private fun showTutorialForFormattingTools() {
CustomMaterialTapTargetPromptBuilder(activityContext, NoteEditorOnboardingEnum.FORMATTING_TOOLS)
.createRectangleWithDimmedBackground()
.setTarget(R.id.editor_toolbar)
.setPrimaryText(R.string.format_content)
.setSecondaryText(R.string.format_content_desc)
.show()
}
enum class NoteEditorOnboardingEnum(var value: Int) : OnboardingFlag {
FRONT_BACK(0), FORMATTING_TOOLS(1);
override fun getOnboardingEnumValue(): Int {
return value
}
override fun getFeatureConstant(): String {
return NOTE_EDITOR_ONBOARDING
}
}
}
class CardBrowser(private val activityContext: com.ichi2.anki.CardBrowser) :
Onboarding<CardBrowser.CardBrowserOnboardingEnum>(activityContext, mutableListOf()) {
init {
tutorials.add(TutorialArguments(CardBrowserOnboardingEnum.DECK_CHANGER, this::showTutorialForDeckChangerIfNew))
tutorials.add(TutorialArguments(CardBrowserOnboardingEnum.CARD_PRESS_AND_HOLD, this::showTutorialForCardClickIfNew))
}
private fun showTutorialForDeckChangerIfNew() {
CustomMaterialTapTargetPromptBuilder(activityContext, CardBrowserOnboardingEnum.DECK_CHANGER)
.createRectangleWithDimmedBackground()
.setFocalColourResource(R.color.material_blue_500)
.setDismissedListener { onCreate() }
.setTarget(R.id.toolbar_spinner)
.setPrimaryText(R.string.deck_changer_card_browser)
.setSecondaryText(R.string.deck_changer_card_browser_desc)
.show()
}
private fun showTutorialForCardClickIfNew() {
val cardBrowserTutorial: FrameLayout = activityContext.findViewById(R.id.card_browser_tutorial)
cardBrowserTutorial.apply {
visibility = View.VISIBLE
setOnClickListener {
visibility = View.GONE
}
}
setVisited(CardBrowserOnboardingEnum.CARD_PRESS_AND_HOLD, activityContext)
}
enum class CardBrowserOnboardingEnum(var value: Int) : OnboardingFlag {
DECK_CHANGER(0), CARD_PRESS_AND_HOLD(1);
override fun getOnboardingEnumValue(): Int {
return value
}
override fun getFeatureConstant(): String {
return CARD_BROWSER_ONBOARDING
}
}
}
}
|
gpl-3.0
|
af69bfc53cc416507b94ca05bf36e296
| 43.902941 | 174 | 0.625205 | 5.10602 | false | false | false | false |
Aidanvii7/Toolbox
|
adapterviews-databinding/src/main/java/com/aidanvii/toolbox/adapterviews/databinding/BindableAdapter.kt
|
1
|
5263
|
package com.aidanvii.toolbox.adapterviews.databinding
import androidx.databinding.ViewDataBinding
import androidx.annotation.LayoutRes
import androidx.annotation.RestrictTo
import android.view.View
import android.view.ViewGroup
import com.aidanvii.toolbox.databinding.IntBindingConsumer
import com.aidanvii.toolbox.databinding.NotifiableObservable
/**
* Represents A data-binding adapter that can automatically bind a list of type [BindableAdapterItem].
*
* You shouldn't implement this directly.
*
* If you need to override methods, subclass [BindingRecyclerPagerAdapter] or [BindingRecyclerViewAdapter],
*
* See [BindingRecyclerViewBinder] or [BindingRecyclerPagerBinder] for typical usage.
*/
interface BindableAdapter<Item : BindableAdapterItem, VH : BindableAdapter.ViewHolder<*, Item>> {
@RestrictTo(RestrictTo.Scope.LIBRARY)
interface ViewHolder<out Binding : ViewDataBinding, Item : BindableAdapterItem> {
val bindingResourceId: Int
val viewDataBinding: Binding
val view: View get() = viewDataBinding.root
var boundAdapterItem: Item?
}
@RestrictTo(RestrictTo.Scope.LIBRARY)
interface ViewTypeHandler<Item : BindableAdapterItem> {
fun initBindableAdapter(bindableAdapter: BindableAdapter<Item, *>)
fun getItemViewType(position: Int): Int
fun getLayoutId(viewType: Int): Int
fun getBindingId(@LayoutRes layoutId: Int): Int
}
/**
* represents the current data-set in the [BindableAdapter]
*/
var items: List<Item>
/**
* Retrieves the current [Item] at the given [position] from [items]
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
fun getItem(position: Int): Item = items[position]
/**
* Retrieves the current position of the given [Item] from [items]
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
fun getItemPosition(item: Item): Int = items.indexOf(item)
@RestrictTo(RestrictTo.Scope.LIBRARY)
fun createWith(bindingResourceId: Int, viewDataBinding: ViewDataBinding): VH
/**
* Called when the [BindableAdapter] has created a [ViewHolder]
*/
fun onCreated(adapterView: ViewGroup, viewHolder: VH) {}
/**
* Called when the [BindableAdapter] is binding a [ViewHolder] for the given [adapterPosition]
*
* @return
* true to signal to the [BindableAdapter] that you do not want the default binding to occur,
* and that it has been taken care of in the overridden implementation of [onInterceptOnBind].
*
* false (default) to signal to the [BindableAdapter] to execute the default binding.
* The default will call [ViewDataBinding.setVariable] with the
* [BindableAdapterItem.bindingId] as the variableId and [BindableAdapterItem.bindableItem] as the value.
*/
fun onInterceptOnBind(viewHolder: VH, adapterPosition: Int, observable: NotifiableObservable?): Boolean = false
/**
* Called when the [BindableAdapter] is binding a [ViewHolder] for the given [adapterPosition]
*
* regardless of what [onInterceptOnBind] returns, this will always be called.
* This gives you the opportunity to bind extra data bound variables for the current [Item].
*/
fun onBindExtras(viewHolder: VH, adapterPosition: Int) {}
/**
* Called when the [BindableAdapter] has finished binding a [ViewHolder] for the given [adapterPosition]
*/
fun onBound(viewHolder: VH, adapterPosition: Int) {}
/**
* Called when the [BindableAdapter] is un-binding a [ViewHolder] from the given [adapterPosition]
*
* @return
* true to signal to the [BindableAdapter] that you do not want the default un-binding to occur,
* and that it has been taken care of in the overridden implementation of [onInterceptUnbind].
*
* false (default) to signal to the [BindableAdapter] to execute the default binding.
* The default will call [ViewDataBinding.setVariable] with the
* [BindableAdapterItem.bindingId] as the variableId and null as the value.
*/
fun onInterceptUnbind(viewHolder: VH, adapterPosition: Int): Boolean = false
/**
* Called when the [BindableAdapter] is un-binding a [ViewHolder] from the given [adapterPosition]
*
* regardless of what [onInterceptOnBind] returns, this will always be called.
* This gives you the opportunity to un-bind extra data bound variables for the current [Item].
*/
fun onUnbindExtras(viewHolder: VH, adapterPosition: Int) {}
/**
* Called when the [BindableAdapter] has finished un-binding a [ViewHolder] from the given [adapterPosition]
*/
fun onUnbound(viewHolder: VH, adapterPosition: Int) {}
/**
* Called when the [BindableAdapter] no longer needs the [ViewHolder] at the given [adapterPosition]
*
* If an [Item] is bound at the given [adapterPosition], the [viewHolder] will be unbound as well.
*/
fun onDestroyed(viewHolder: VH, adapterPosition: Int) {}
@get:RestrictTo(RestrictTo.Scope.LIBRARY)
val viewTypeHandler: ViewTypeHandler<Item>
@get:RestrictTo(RestrictTo.Scope.LIBRARY)
val bindingInflater: BindingInflater
@get:RestrictTo(RestrictTo.Scope.LIBRARY)
var itemBoundListener: IntBindingConsumer?
}
|
apache-2.0
|
ed071f2971389c8e1ada7c2c6c31b825
| 39.492308 | 115 | 0.715371 | 4.66992 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp
|
app/src/main/java/co/timetableapp/TimetableApplication.kt
|
1
|
1611
|
/*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp
import android.app.Application
import android.content.Context
import android.util.Log
import co.timetableapp.model.Timetable
import co.timetableapp.util.NotificationUtils
import co.timetableapp.util.PrefUtils
import com.jakewharton.threetenabp.AndroidThreeTen
class TimetableApplication : Application() {
private val LOG_TAG = "TimetableApplication"
var currentTimetable: Timetable? = null
private set(value) {
field = value
value?.let {
PrefUtils.setCurrentTimetable(this, it)
Log.i(LOG_TAG, "Switched current timetable to that with id ${it.id}")
}
}
override fun onCreate() {
super.onCreate()
AndroidThreeTen.init(this)
currentTimetable = PrefUtils.getCurrentTimetable(this)
}
fun setCurrentTimetable(context: Context, timetable: Timetable) {
currentTimetable = timetable
NotificationUtils.refreshAlarms(context, this)
}
}
|
apache-2.0
|
d0c39949553d149f244adb8a91dd8e9f
| 29.396226 | 85 | 0.707635 | 4.5 | false | false | false | false |
wcaokaze/cac2er
|
src/main/kotlin/com/wcaokaze/cac2er/Cacher.kt
|
1
|
12367
|
package com.wcaokaze.cac2er
import com.wcaokaze.io.*
import com.wcaokaze.util.Pool
import kotlinx.coroutines.experimental.sync.Mutex
import kotlinx.coroutines.experimental.sync.withLock
import java.io.*
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
object Cacher {
private const val MAGIC_NUMBER = 0xcac2e000.toInt()
private val mutexPool = Pool<File, Mutex> { Mutex() }
class FileMutex internal constructor(private val mutexList: List<Mutex>) {
companion object {
/** to avoid deadlock. */
private val masterMutex = Mutex()
}
suspend fun lock() {
when (mutexList.size) {
0 -> return
1 -> mutexList.first().lock()
else -> masterMutex.withLock {
for (mutex in mutexList) {
mutex.lock()
}
}
}
}
fun unlock() {
for (mutex in mutexList) {
mutex.unlock()
}
}
}
fun getFileMutex(files: Iterable<File>) = FileMutex(files.map { mutexPool[it] })
/**
* locks the specified files and runs operation.
*
* If any of the files are already locked, suspends until all of them are
* unlocked. Functions in [Cacher] don't lock file(s). Invoke them with this
* function.
*
* ```kotlin
* launch (CommonPool) {
* transaction (file) {
* Cacher.load(file)
* }
* }
* ```
*
* Functions in [CacheMap] and extensions for [Cacher], [Cache] call
* [transaction] internal. You must mind transaction only when calling
* primitive functions([save], [saveCirculationRecord], [load], [gc]).
* Transactions can NOT be nested. In operation call only primitive
* functions to make sure that transaction is not in another transaction.
*
* @since 4.0.0
*/
suspend inline fun <R> transaction(vararg files: File, operation: () -> R): R
= transaction(files.toList(), operation)
suspend inline fun <R> transaction(files: Iterable<File>, operation: () -> R): R {
val fileMutex = getFileMutex(files)
fileMutex.lock()
try {
return operation()
} finally {
fileMutex.unlock()
}
}
/**
* checks the major version of Cac2er which saved the specified file. If this
* value mismatches, Cac2er can not load the file.
*
* @return
* The major version of Cac2er which saved the specified file or `null` if
* the specified file is not a cache file.
*
* @since 4.0.0
*/
fun checkFileFormat(file: File): Int? {
try {
val (magicNumber, majorVersion)
= DataInputStream(file.inputStream().buffered(16)).use {
it.readInt()
}
if (magicNumber != MAGIC_NUMBER) return null
return majorVersion
} catch (e: IOException) {
return null
}
}
/**
* writes the [content][Cache.content] of the specified cache into the
* [file][Cache.file].
*
* NOTE:
* This function is not recursive. If the [content][Cache.content] of the
* specified cache has other [Cache]s, this function does NOT save it.
*
* @throws IOException
*
* @since 4.0.0
*/
fun save(cache: Cache<*>) {
val uniformizer = cache.uniformizer
if (uniformizer.file.name.endsWith(".tmp")) {
throw IllegalArgumentException(
"The name of cache file must not end with \".tmp\"")
}
val tmpFile = uniformizer.file.resolveSibling(uniformizer.file.name + ".tmp")
RandomAccessFile(tmpFile, "rw").use {
// filePointer == 0
it.writeInt(MAGIC_NUMBER + MAJOR_VERSION)
// filePointer == 4
it.seek(8L)
val dependence = Dependence()
CacheOutputStream(
GZIPOutputStream(it.asOutputStream()),
uniformizer,
dependence
).use {
it.writeAny(uniformizer.content)
}
val dependencePosition = it.filePointer
DataOutputStream(GZIPOutputStream(it.asOutputStream())).use {
Dependence.Serializer.serialize(dependence, it)
}
val circulationRecordPosition = it.filePointer
CirculationRecordImpl.Serializer
.serialize(uniformizer.circulationRecord, it)
if (circulationRecordPosition > 65535) {
throw IOException("The cache is too huge.")
}
it.seek(4L)
it.writeShort(dependencePosition.toInt())
// filePointer == 6
it.writeShort(circulationRecordPosition.toInt())
// filePointer == 8
}
tmpFile.renameTo(uniformizer.file)
}
/**
* writes only [circulationRecord][Cache.circulationRecord] of the specified
* cache or also the content if it has not written yet.
*
* @throws IOException
*
* @since 4.0.0
*/
fun saveCirculationRecord(cache: Cache<*>) {
val uniformizer = cache.uniformizer
if (uniformizer.file.exists()) {
RandomAccessFile(uniformizer.file, "rw").use {
it.seek(6L)
val circulationRecordPosition = it.readUnsignedShort().toLong()
it.seek(circulationRecordPosition)
CirculationRecordImpl.Serializer
.serialize(uniformizer.circulationRecord, it)
}
} else {
save(cache)
}
}
/**
* loads a cache.
*
* @return
* A [Pair] of the [content][Cache.content] and
* [CirculationRecord][Cache.CirculationRecord] of the cache.
*
* @throws IOException
* when file I/O fails, or the specified file is not a cache file.
*
* @since 4.0.0
*/
fun load(file: File): Pair<*, Cache.CirculationRecord> {
RandomAccessFile(file, "r").use {
checkFileFormat(it, file)
@Suppress("UNUSED_VARIABLE")
val dependencePosition = it.readUnsignedShort().toLong()
val circulationRecordPosition = it.readUnsignedShort().toLong()
val content = CacheInputStream(
GZIPInputStream(it.asInputStream()),
file.parentFile
).use { it.readAny() }
it.seek(circulationRecordPosition)
val circulationRecord = try {
CirculationRecordImpl.Serializer.deserialize(it)
} catch (e: Exception) {
CirculationRecordImpl()
}
return content to circulationRecord
}
}
/**
* runs the garbage collector. GC deletes some files whose `importance` are
* low.
*
* It is guaranteed that cache files that are depended by any other cache
* which is not deleted are also not deleted. For example:
*
* ```kotlin
* class A
* class B(val aCache: Cache<A>)
*
* val aCache = Cacher.save(File("~/.foo/cache/a"), A())
* val bCache = Cacher.save(File("~/.foo/cache/b"), B(aCache))
*
* // ...
*
* Cacher.gc(arrayOf(File("~/.foo/cache/a"),
* File("~/.foo/cache/b")), 100L)
* ```
*
* Then, if `b` is not deleted, `a` is never deleted. If `a` is deleted, `b`
* is also deleted.
*
* Note that GC reads files, not instances. Some instances can remain although
* the corresponding files are deleted. Then [Cacher.save] may revives the
* files. And, if calling [Cacher.saveCirculationRecord] is too late, GC
* cannot read it.
*
* @param idealTotalFileSize The ideal total size of files.
*
* @throws IOException when any file could not be loaded
*
* @throws IllegalArgumentException
* When any cache of the specified files depends on other cache not in the
* specified files.
*
* @see Cache.CirculationRecord
*
* @see WeakCache
*
* @since 4.0.0
*/
fun gc(files: Iterable<File>, idealTotalFileSize: Long) {
gc(files.asSequence(), idealTotalFileSize)
}
fun gc(files: Sequence<File>, idealTotalFileSize: Long) {
val metadataSeq = files.map { loadMetadata(it) }
val relationshipMap = metadataSeq
.map { it.file to CacheRelationship() }
.toMap()
// ---- resolve dependency relationship
for (metadata in metadataSeq) {
val file = metadata.file
relationshipMap[file]!!.dependees =
metadata.dependeeFiles.map { relationshipMap[it]!! }
}
// ---- set raw importance
val currentPeriod = periodOf(System.currentTimeMillis())
for (metadata in metadataSeq) {
relationshipMap[metadata.file]!!.importance =
metadata.circulationRecord.calcImportance(currentPeriod)
}
// ---- update the importance of depended files
fun CacheRelationship.updateImportanceIfNecessary(importance: Float) {
if (importance <= this.importance) return
this.importance = importance
for (dependee in dependees) {
dependee.updateImportanceIfNecessary(importance)
}
}
for ((_, relationship) in relationshipMap) {
relationship.dependees.forEach {
it.updateImportanceIfNecessary(relationship.importance)
}
}
// ---- remove unaffectable records
for (metadata in metadataSeq) {
val removingPeriods = metadata.circulationRecord.asSequence()
.map { it.period to it.calcImportance(currentPeriod) }
.filter { (_, importance) -> importance < .25f }
.map { (period, _) -> period }
.toList()
if (removingPeriods.isEmpty()) continue
val circulationRecord =
CacheUniformizer.Pool[metadata.file]?.circulationRecord
?: metadata.circulationRecord
circulationRecord.removeAll(removingPeriods)
RandomAccessFile(metadata.file, "rw").use {
try {
it.seek(6L)
val circulationRecordPosition = it.readUnsignedShort().toLong()
it.seek(circulationRecordPosition)
CirculationRecordImpl
.Serializer.serialize(circulationRecord, it)
} catch (e: IOException) {
// continue
}
}
}
// ---- delete files while totalFileSize > idealTotalFileSize
/*
* Files whose importance are equal must be deleted at once. So it needs a
* list of lists of files.
*
* [
* [ file1, file2 ], // Files whose importance is the lowest.
* [ file3 ], // The 2nd lowest
* // ... // And so on.
* ]
*/
val sortedFileList = run {
val fileListMappedImportance = relationshipMap
.asIterable()
.groupBy({ it.value.importance }, { it.key })
fileListMappedImportance.asSequence()
.sortedBy { it.key }
.map { it.value }
}
var totalFileSize = sortedFileList
.flatten()
.map { it.length() }
.sum()
for (fileList in sortedFileList) {
if (totalFileSize <= idealTotalFileSize) break
for (file in fileList) {
totalFileSize -= file.length()
file.delete()
}
}
}
private operator fun Int.component1() = this and 0xfffff000.toInt()
private operator fun Int.component2() = this and 0x00000fff
private fun checkFileFormat(fileInput: RandomAccessFile, file: File) {
val (magicNumber, majorVersion) = fileInput.readInt()
if (magicNumber != MAGIC_NUMBER) {
throw IOException("not a cache file: $file")
}
if (majorVersion != MAJOR_VERSION) {
throw IOException("version mismatched($majorVersion): $file")
}
}
private class CacheMetadata(
val file: File,
val dependence: Dependence,
val circulationRecord: CirculationRecordImpl
)
private class CacheRelationship {
var dependees = emptyList<CacheRelationship>()
var importance = .0f
}
private fun loadMetadata(file: File): CacheMetadata {
RandomAccessFile(file, "r").use {
checkFileFormat(it, file)
val dependencePosition = it.readUnsignedShort().toLong()
val circulationRecordPosition = it.readUnsignedShort().toLong()
it.seek(dependencePosition)
val dependence = DataInputStream(GZIPInputStream(it.asInputStream())).use {
Dependence.Serializer.deserialize(it)
}
it.seek(circulationRecordPosition)
val circulationRecord = CirculationRecordImpl.Serializer.deserialize(it)
return CacheMetadata(file, dependence, circulationRecord)
}
}
private val CacheMetadata.dependeeFiles
get() = dependence.map { file.resolveSibling(it) }
private fun CirculationRecordImpl.calcImportance(currentPeriod: Period)
= map { it.calcImportance(currentPeriod) }.sum()
private fun PeriodAccessCount.calcImportance(currentPeriod: Period)
= accessCount / (currentPeriod - period + 2)
}
|
mit
|
084465899c93452041790109298dcf08
| 27.043084 | 84 | 0.634349 | 4.251289 | false | false | false | false |
WijayaPrinting/wp-javafx
|
openpss-client-javafx/src/com/hendraanggrian/openpss/ui/finance/ViewTotalPopOver.kt
|
1
|
1162
|
package com.hendraanggrian.openpss.ui.finance
import com.hendraanggrian.openpss.FxComponent
import com.hendraanggrian.openpss.R
import com.hendraanggrian.openpss.R2
import com.hendraanggrian.openpss.ui.BasePopOver
import javafx.geometry.HPos
import ktfx.controls.columnConstraints
import ktfx.layouts.gridPane
import ktfx.layouts.label
import ktfx.text.invoke
class ViewTotalPopOver(
component: FxComponent,
private val cash: Double,
private val nonCash: Double
) : BasePopOver(component, R2.string.view_total) {
init {
gridPane {
columnConstraints {
append()
append { halignment = HPos.RIGHT }
}
vgap = 20.0
hgap = 40.0
label(getString(R2.string.cash)) col 0 row 0
label(currencyConverter(cash)) col 1 row 0
label(getString(R2.string.non_cash)) col 0 row 1
label(currencyConverter(nonCash)) col 1 row 1
label(getString(R2.string.total)) { styleClass += R.style.bold } col 0 row 2
label(currencyConverter(cash + nonCash)) { styleClass += R.style.bold } col 1 row 2
}
}
}
|
apache-2.0
|
e92a54d61b5fc0975fba8bcefb564255
| 32.2 | 95 | 0.659208 | 3.993127 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android
|
fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/scan/threat/RowsDeserializer.kt
|
2
|
2583
|
package org.wordpress.android.fluxc.network.rest.wpcom.scan.threat
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import org.wordpress.android.fluxc.model.scan.threat.ThreatModel.DatabaseThreatModel.Row
import java.lang.reflect.Type
class RowsDeserializer : JsonDeserializer<List<Row>?> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): List<Row>? {
return if (context != null && json != null && json.isJsonObject) {
/**
* Rows example:
* "rows": {
* "949": {
* "id": 1849,
* "description": "KiethAbare - 2019-01-20 18:41:40",
* "url": "http://to.ht/bestforex48357\\n"
* },
* "950": {
* "id": 1850,
* "description": "KiethAbare - 2019-01-20 18:41:45",
* "url": "http://to.ht/bestforex48357\\n"
* }
* }
*/
val rows: ArrayList<Row> = arrayListOf()
val rowsJsonObject = json.asJsonObject
rowsJsonObject.keySet().iterator().forEach { key ->
val row = getRow(key, rowsJsonObject)
row?.let { rows.add(it) }
}
if (rows.isNotEmpty()) {
rows.sortBy(Row::rowNumber)
}
return rows
} else {
null
}
}
@Suppress("SwallowedException")
private fun getRow(
key: String,
rowJsonObject: JsonObject
): Row? {
return rowJsonObject.get(key)?.takeIf { it.isJsonObject }?.asJsonObject?.let { contents ->
try {
Row(
rowNumber = key.toInt(),
id = contents.get(ID)?.asInt ?: 0,
description = contents.get(DESCRIPTION)?.asString,
code = contents.get(CODE)?.asString,
url = contents.get(URL)?.asString
)
} catch (ex: ClassCastException) {
null
} catch (ex: IllegalStateException) {
null
} catch (ex: NumberFormatException) {
null
}
}
}
companion object {
private const val ID = "id"
private const val DESCRIPTION = "description"
private const val CODE = "code"
private const val URL = "url"
}
}
|
gpl-2.0
|
26ce1fce0145b519c7ef0eae39eecd43
| 31.2875 | 98 | 0.511034 | 4.555556 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android
|
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/product/attributes/terms/AttributeTermApiResponse.kt
|
2
|
452
|
package org.wordpress.android.fluxc.network.rest.wpcom.wc.product.attributes.terms
import com.google.gson.annotations.SerializedName
import org.wordpress.android.fluxc.network.Response
class AttributeTermApiResponse : Response {
val id: String? = null
val name: String? = null
val slug: String? = null
val description: String? = null
val count: String? = null
@SerializedName("menu_order")
val menuOrder: String? = null
}
|
gpl-2.0
|
7d2410914d022829132bb29810a62710
| 31.285714 | 82 | 0.736726 | 3.896552 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/inventory/container/ClientWindowTypes.kt
|
1
|
2122
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.inventory.container
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.key.resolveNamespacedKey
import org.lanternpowered.server.game.registry.InternalRegistries
object ClientWindowTypes {
private val keyToIdMap = HashMap<NamespacedKey, ClientWindowType>()
init {
InternalRegistries.visit("menu") { name, internalId ->
val key = resolveNamespacedKey(name)
this.keyToIdMap[key] = ClientWindowType(key, internalId)
}
}
fun get(key: String) = get(resolveNamespacedKey(key))
fun get(key: NamespacedKey) = requireNotNull(this.keyToIdMap[key]) { "Cannot find mapping for $key" }
@JvmField val ANVIL = get("anvil")
@JvmField val BEACON = get("beacon")
@JvmField val BLAST_FURNACE = get("blast_furnace")
@JvmField val BREWING_STAND = get("brewing_stand")
@JvmField val CARTOGRAPHY = get("cartography")
@JvmField val CRAFTING = get("crafting")
@JvmField val ENCHANTMENT = get("enchantment")
@JvmField val FURNACE = get("furnace")
@JvmField val GENERIC_3x3 = get("generic_3x3")
@JvmField val GENERIC_9x1 = get("generic_9x1")
@JvmField val GENERIC_9x2 = get("generic_9x2")
@JvmField val GENERIC_9x3 = get("generic_9x3")
@JvmField val GENERIC_9x4 = get("generic_9x4")
@JvmField val GENERIC_9x5 = get("generic_9x5")
@JvmField val GENERIC_9x6 = get("generic_9x6")
@JvmField val GRINDSTONE = get("grindstone")
@JvmField val HOPPER = get("hopper")
@JvmField val LECTERN = get("lectern")
@JvmField val LOOM = get("loom")
@JvmField val MERCHANT = get("merchant")
@JvmField val SHULKER_BOX = get("shulker_box")
@JvmField val SMOKER = get("smoker")
@JvmField val STONE_CUTTER = get("stonecutter")
}
|
mit
|
e1b25d973371882c7defdb7d9900c14b
| 38.296296 | 105 | 0.693214 | 3.578415 | false | false | false | false |
ekager/focus-android
|
app/src/main/java/org/mozilla/focus/searchsuggestions/SearchSuggestionsFetcher.kt
|
1
|
3248
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.searchsuggestions
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import mozilla.components.browser.search.SearchEngine
import mozilla.components.browser.search.suggestions.SearchSuggestionClient
import okhttp3.OkHttpClient
import okhttp3.Request
import org.mozilla.focus.utils.debounce
import kotlin.coroutines.CoroutineContext
class SearchSuggestionsFetcher(searchEngine: SearchEngine) : CoroutineScope {
private var job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
data class SuggestionResult(val query: String, val suggestions: List<String>)
private var client: SearchSuggestionClient? = null
private var httpClient = OkHttpClient()
private val fetchChannel = Channel<String>(capacity = Channel.UNLIMITED)
private val _results = MutableLiveData<SuggestionResult>()
val results: LiveData<SuggestionResult> = _results
var canProvideSearchSuggestions = false
private set
init {
updateSearchEngine(searchEngine)
launch(IO) {
debounce(THROTTLE_AMOUNT, fetchChannel)
.consumeEach { getSuggestions(it) }
}
}
fun requestSuggestions(query: String) {
if (query.isBlank()) { _results.value = SuggestionResult(query, listOf()); return }
fetchChannel.offer(query)
}
fun updateSearchEngine(searchEngine: SearchEngine) {
canProvideSearchSuggestions = searchEngine.canProvideSearchSuggestions
client = if (canProvideSearchSuggestions) SearchSuggestionClient(searchEngine, { fetch(it) }) else null
}
private suspend fun getSuggestions(query: String) = coroutineScope {
val suggestions = try {
client?.getSuggestions(query) ?: listOf()
} catch (ex: SearchSuggestionClient.ResponseParserException) {
listOf<String>()
} catch (ex: SearchSuggestionClient.FetchException) {
listOf<String>()
}
launch(Main) {
_results.value = SuggestionResult(query, suggestions)
}
}
private fun fetch(url: String): String? {
httpClient.dispatcher().queuedCalls()
.filter { it.request().tag() == REQUEST_TAG }
.forEach { it.cancel() }
val request = Request.Builder()
.tag(REQUEST_TAG)
.url(url)
.build()
return httpClient.newCall(request).execute().body()?.string() ?: ""
}
companion object {
private const val REQUEST_TAG = "searchSuggestionFetch"
private const val THROTTLE_AMOUNT: Long = 100
}
}
|
mpl-2.0
|
47a46ed9ca50ead1633f8f91df34a715
| 33.924731 | 111 | 0.6992 | 4.869565 | false | false | false | false |
ns2j/nos2jdbc-tutorial
|
nos2jdbc-tutorial-kotlin-spring/src/main/kotlin/nos2jdbc/tutorial/kotlinspring/entity/nonauto/YmItem.kt
|
1
|
653
|
package nos2jdbc.tutorial.kotlinspring.entity.nonauto
import java.math.BigDecimal
import java.time.LocalDate
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.ManyToOne
import javax.persistence.OneToOne
import javax.persistence.Transient
import nos2jdbc.annotation.NoFk
import nos2jdbc.annotation.NonAuto
@Entity @NonAuto
class YmItem {
@Id
var lunchFeeId: Long? = null
@OneToOne(mappedBy = "ymItem")
var member: YmItemMember? = null
var payOn: LocalDate? = null
var amount: BigDecimal = BigDecimal.ZERO
var count: Int = 0
@Transient @ManyToOne @NoFk
var ym: Ym? = null
}
|
apache-2.0
|
193e0124aa4e4aaeb87b8c5370161e60
| 23.185185 | 53 | 0.751914 | 3.710227 | false | false | false | false |
ziggy42/Blum
|
app/src/main/java/com/andreapivetta/blu/ui/notifications/NotificationsFragment.kt
|
1
|
3761
|
package com.andreapivetta.blu.ui.notifications
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.andreapivetta.blu.R
import com.andreapivetta.blu.common.utils.Utils
import com.andreapivetta.blu.common.utils.visible
import com.andreapivetta.blu.data.jobs.NotificationsIntentService
import com.andreapivetta.blu.data.model.Notification
import com.andreapivetta.blu.data.storage.AppStorageFactory
import com.andreapivetta.blu.ui.custom.Theme
import com.andreapivetta.blu.ui.custom.decorators.SpaceTopItemDecoration
/**
* Created by andrea on 28/07/16.
*/
class NotificationsFragment : Fragment(), NotificationsMvpView {
companion object {
fun newInstance() = NotificationsFragment()
}
private val presenter by lazy { NotificationsPresenter(AppStorageFactory.getAppStorage()) }
private val receiver: NotificationUpdatesReceiver? by lazy { NotificationUpdatesReceiver() }
private var adapter = NotificationsAdapter()
private lateinit var emptyView: ViewGroup
override fun onResume() {
super.onResume()
activity.registerReceiver(receiver, IntentFilter(Notification.NEW_NOTIFICATION_INTENT))
}
@Suppress("UNCHECKED_CAST")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter.attachView(this)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater?.inflate(R.layout.fragment_notifications, container, false)
val recyclerView = rootView?.findViewById(R.id.notificationsRecyclerView) as RecyclerView
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.setHasFixedSize(true)
recyclerView.addItemDecoration(SpaceTopItemDecoration(Utils.dpToPx(context, 10)))
recyclerView.adapter = adapter
val refreshLayout = rootView.findViewById(R.id.swipeRefreshLayout) as SwipeRefreshLayout
refreshLayout.setColorSchemeColors(Theme.getColorPrimary(context))
refreshLayout.setOnRefreshListener {
NotificationsIntentService.startService(context)
Toast.makeText(context, R.string.checking_notifications, Toast.LENGTH_SHORT).show()
Handler().postDelayed({ refreshLayout.isRefreshing = false }, 2000)
}
emptyView = rootView.findViewById(R.id.emptyLinearLayout) as ViewGroup
presenter.getNotifications()
return rootView
}
override fun onDestroy() {
super.onDestroy()
activity.unregisterReceiver(receiver)
}
override fun showNotifications(readNotifications: List<Notification>,
unreadNotifications: List<Notification>) {
adapter.unreadNotifications = unreadNotifications
adapter.readNotifications = readNotifications
adapter.notifyDataSetChanged()
}
override fun hideEmptyMessage() {
emptyView.visible(false)
}
inner class NotificationUpdatesReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action === Notification.NEW_NOTIFICATION_INTENT) {
presenter.onNewNotification()
}
}
}
}
|
apache-2.0
|
6ac90c767cf466dfb730c3e880024f6d
| 37.387755 | 97 | 0.73757 | 5.223611 | false | false | false | false |
crunchersaspire/worshipsongs-android
|
app/src/main/java/org/worshipsongs/fragment/AlertDialogFragment.kt
|
3
|
3787
|
package org.worshipsongs.fragment
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import org.apache.commons.lang3.StringUtils
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
/**
* @author Madasamy
* @version 3.x
*/
class AlertDialogFragment : DialogFragment()
{
private var dialogListener: DialogListener? = null
private var visiblePositiveButton = true
private var visibleNegativeButton = true
private val customTitleVIew: View
get()
{
val inflater = activity!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val titleView = inflater.inflate(R.layout.dialog_custom_title, null)
val titleTextView = titleView.findViewById<View>(R.id.title) as TextView
titleTextView.text = arguments!!.getString(CommonConstants.TITLE_KEY)
titleTextView.visibility = if (StringUtils.isBlank(titleTextView.text.toString())) View.GONE else View.VISIBLE
val messageTextView = titleView.findViewById<View>(R.id.subtitle) as TextView
messageTextView.setTextColor(activity!!.resources.getColor(R.color.black_semi_transparent))
messageTextView.text = arguments!!.getString(CommonConstants.MESSAGE_KEY)
return titleView
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog
{
val alertDialogBuilder = AlertDialog.Builder(ContextThemeWrapper(activity, R.style.DialogTheme))
alertDialogBuilder.setCustomTitle(customTitleVIew)
if (visibleNegativeButton)
{
alertDialogBuilder.setNegativeButton(R.string.cancel) { dialog, id ->
dialog.cancel()
if (dialogListener != null)
{
dialogListener!!.onClickNegativeButton()
}
}
}
if (visiblePositiveButton)
{
alertDialogBuilder.setPositiveButton(R.string.ok) { dialog, which ->
dialog.cancel()
if (dialogListener != null)
{
dialogListener!!.onClickPositiveButton(arguments, tag)
}
}
}
return alertDialogBuilder.create()
}
interface DialogListener
{
fun onClickPositiveButton(bundle: Bundle?, tag: String?)
fun onClickNegativeButton()
}
fun setDialogListener(dialogListener: DialogListener)
{
this.dialogListener = dialogListener
}
fun setVisiblePositiveButton(visiblePositiveButton: Boolean)
{
this.visiblePositiveButton = visiblePositiveButton
}
fun setVisibleNegativeButton(visibleNegativeButton: Boolean)
{
this.visibleNegativeButton = visibleNegativeButton
}
override fun show(manager: FragmentManager, tag: String?)
{
try
{
val fragmentTransaction = manager.beginTransaction()
fragmentTransaction.add(this, tag).addToBackStack(null)
fragmentTransaction.commitAllowingStateLoss()
} catch (e: IllegalStateException)
{
Log.e(AlertDialogFragment::class.java.simpleName, "Error", e)
}
}
companion object
{
fun newInstance(bundle: Bundle): AlertDialogFragment
{
val fragment = AlertDialogFragment()
fragment.arguments = bundle
return fragment
}
}
}
|
gpl-3.0
|
d0ecffe49d78d4c3bd34b467f3f3eb7d
| 29.796748 | 122 | 0.663586 | 5.379261 | false | false | false | false |
mgolokhov/dodroid
|
app/src/main/java/doit/study/droid/quiz/domain/SaveQuizResultUseCase.kt
|
1
|
1022
|
package doit.study.droid.quiz.domain
import doit.study.droid.data.QuizRepository
import doit.study.droid.quiz.QuizItem
import java.util.Date
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class SaveQuizResultUseCase @Inject constructor(
private val quizRepository: QuizRepository,
private val isQuizAnsweredRightUseCase: IsQuizAnsweredRightUseCase
) {
suspend operator fun invoke(quizItems: List<QuizItem>?) = withContext(Dispatchers.IO) {
// TODO: dirty stub, replace with real logic
// yeah, batching
quizItems?.forEach {
val isQuizAnsweredRight = isQuizAnsweredRightUseCase(it)
quizRepository.saveStatistics(
questionId = it.questionId,
rightCount = if (isQuizAnsweredRight) 1 else 0,
wrongCount = if (isQuizAnsweredRight) 0 else 1,
studiedAt = if (isQuizAnsweredRight) Date().time else 0
)
}
}
}
|
mit
|
5a1df716a80aeb9f1ffb896efa19d7f4
| 36.851852 | 91 | 0.684932 | 4.405172 | false | false | false | false |
FHannes/intellij-community
|
platform/projectModel-api/src/com/intellij/openapi/module/ModuleGrouper.kt
|
3
|
3924
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.annotations.ApiStatus
import java.util.*
/**
* Use this class to determine how modules show by organized in a tree. It supports the both ways of module grouping: the old one where
* groups are specified explicitly and the new one where modules are grouped accordingly to their qualified names.
*
* @author nik
*/
@ApiStatus.Experimental
abstract class ModuleGrouper {
/**
* Returns names of parent groups for a module
*/
abstract fun getGroupPath(module: Module): List<String>
/**
* Returns name which should be used for a module when it's shown under its group
*/
abstract fun getShortenedName(module: Module): String
abstract fun getShortenedNameByFullModuleName(name: String): String
abstract fun getGroupPathByModuleName(name: String): List<String>
/**
* If [module] itself can be considered as a group, returns its groups. Otherwise returns null.
*/
abstract fun getModuleAsGroupPath(module: Module): List<String>?
abstract fun getAllModules(): Array<Module>
companion object {
@JvmStatic
@JvmOverloads
fun instanceFor(project: Project, moduleModel: ModifiableModuleModel? = null): ModuleGrouper {
val hasGroups = moduleModel?.hasModuleGroups() ?: ModuleManager.getInstance(project).hasModuleGroups()
if (!isQualifiedModuleNamesEnabled() || hasGroups) {
return ExplicitModuleGrouper(project, moduleModel)
}
return QualifiedNameGrouper(project, moduleModel)
}
}
}
fun isQualifiedModuleNamesEnabled() = Registry.`is`("project.qualified.module.names")
private abstract class ModuleGrouperBase(protected val project: Project, protected val model: ModifiableModuleModel?) : ModuleGrouper() {
override fun getAllModules(): Array<Module> = model?.modules ?: ModuleManager.getInstance(project).modules
protected fun getModuleName(module: Module) = model?.getNewName(module) ?: module.name
override fun getShortenedName(module: Module) = getShortenedNameByFullModuleName(getModuleName(module))
}
private class QualifiedNameGrouper(project: Project, model: ModifiableModuleModel?) : ModuleGrouperBase(project, model) {
override fun getGroupPath(module: Module): List<String> {
return getGroupPathByModuleName(getModuleName(module))
}
override fun getShortenedNameByFullModuleName(name: String) = StringUtil.getShortName(name)
override fun getGroupPathByModuleName(name: String) = name.split('.').dropLast(1)
override fun getModuleAsGroupPath(module: Module) = getModuleName(module).split('.')
}
private class ExplicitModuleGrouper(project: Project, model: ModifiableModuleModel?): ModuleGrouperBase(project, model) {
override fun getGroupPath(module: Module): List<String> {
val path = if (model != null) model.getModuleGroupPath(module) else ModuleManager.getInstance(project).getModuleGroupPath(module)
return if (path != null) Arrays.asList(*path) else emptyList()
}
override fun getShortenedNameByFullModuleName(name: String) = name
override fun getGroupPathByModuleName(name: String): List<String> = emptyList()
override fun getModuleAsGroupPath(module: Module) = null
}
|
apache-2.0
|
b3be8ffa8ac5b18f1673650fb176febc
| 38.636364 | 137 | 0.762997 | 4.665874 | false | false | false | false |
AgileVentures/MetPlus_resumeCruncher
|
core/src/test/kotlin/org/metplus/cruncher/resume/MatchWithJobTest.kt
|
1
|
4312
|
package org.metplus.cruncher.resume
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.metplus.cruncher.job.Job
import org.metplus.cruncher.job.JobRepositoryFake
import org.metplus.cruncher.rating.MatcherList
import org.metplus.cruncher.rating.MatcherStub
import org.metplus.cruncher.rating.emptyMetaData
internal class MatchWithJobTest {
private lateinit var matchWithJob: MatchWithJob
private lateinit var jobRepositoryFake: JobRepositoryFake
private lateinit var resumeRepositoryFake: ResumeRepositoryFake
private lateinit var matcherStub: MatcherStub
@BeforeEach
fun beforeEach() {
jobRepositoryFake = JobRepositoryFake()
resumeRepositoryFake = ResumeRepositoryFake()
matcherStub = MatcherStub()
matchWithJob = MatchWithJob(resumeRepositoryFake, jobRepositoryFake, MatcherList(listOf(matcherStub)))
}
@Test
fun `when job does not exist, it calls jobNotFound callback with the job id provided`() {
var wasCalledWith = ""
matchWithJob.process("not-found", observer = object : MatchWithJobObserver<Boolean> {
override fun success(matchedResumes: Map<String, List<Resume>>): Boolean {
fail("Should have called jobNotFound")
return false
}
override fun noMatchFound(jobId: String, matchers: Map<String, List<Resume>>): Boolean {
fail("Should have called jobNotFound")
return false
}
override fun jobNotFound(jobId: String): Boolean {
wasCalledWith = jobId
return true
}
})
assertThat(wasCalledWith).isEqualTo("not-found")
}
@Test
fun `when job exists but have no match, it calls noMatchFound callback with the job id provided`() {
var wasCalledWith = ""
jobRepositoryFake.save(Job("some-job-id", "some title", "some description", mapOf(), mapOf()))
matchWithJob.process("some-job-id", observer = object : MatchWithJobObserver<Boolean> {
override fun success(matchedResumes: Map<String, List<Resume>>): Boolean {
fail("Should have called noMatchFound")
return false
}
override fun noMatchFound(jobId: String, matchers: Map<String, List<Resume>>): Boolean {
wasCalledWith = jobId
return true
}
override fun jobNotFound(jobId: String): Boolean {
fail("Should have called noMatchFound")
return false
}
})
assertThat(wasCalledWith).isEqualTo("some-job-id")
}
@Test
fun `when job exists and matches two resumes, it calls success callback with the two matched resumes`() {
var wasCalledWith = mapOf<String, List<Resume>>()
jobRepositoryFake.save(Job("some-job-id", "some title", "some description", mapOf(), mapOf()))
val resume1 = Resume("some-file", "some-user-id", "pdf", mapOf())
resumeRepositoryFake.save(resume1)
resumeRepositoryFake.save(Resume("some-other-file", "yet-other-user-id", "pdf", mapOf()))
val resume2 = Resume("some-other-file", "some-other-user-id", "pdf", mapOf())
resumeRepositoryFake.save(resume2)
matcherStub.matchInverseReturnValue = listOf(resume2.copy(starRating = 4.1), resume1.copy(starRating = 0.1))
matchWithJob.process("some-job-id", observer = object : MatchWithJobObserver<Boolean> {
override fun success(matchedResumes: Map<String, List<Resume>>): Boolean {
wasCalledWith = matchedResumes
return true
}
override fun noMatchFound(jobId: String, matchers: Map<String, List<Resume>>): Boolean {
fail("Should have called success")
return false
}
override fun jobNotFound(jobId: String): Boolean {
fail("Should have called success")
return false
}
})
assertThat(wasCalledWith).isEqualTo(mapOf("matcher-1" to listOf(resume2.copy(starRating = 4.1), resume1.copy(starRating = 0.1))))
}
}
|
gpl-3.0
|
8b64b10da558d585ab4697f8dfa734b1
| 40.07619 | 137 | 0.643089 | 4.616702 | false | false | false | false |
FHannes/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/compile/ModuleXmlBuilder.kt
|
8
|
1412
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder.compile
/**
* @author Sergey Karashevich
*/
object ModuleXmlBuilder {
fun module(function: () -> String): String = "<modules>\n${function.invoke()}\n</modules>"
fun modules(outputDir: String,
function: () -> String): String = "<module name=\"main\" outputDir=\"$outputDir\" type=\"java-production\">\n${function.invoke()}\n</module>"
fun addSource(path: String) = "<sources path=\"$path\"/>"
fun addClasspath(path: String) = "<classpath path=\"$path\"/>"
fun build(outputDir: String, classPath: List<String>, sourcePath: String) =
module {
modules(outputDir = outputDir) {
classPath
.map { path -> addClasspath(path) }
.plus(addSource(sourcePath))
.joinToString("\n")
}
}
}
|
apache-2.0
|
a395c393d3c4409bea38b6191199a798
| 32.642857 | 155 | 0.673513 | 4.189911 | false | false | false | false |
hanks-zyh/KotlinExample
|
src/LearnNull.kt
|
1
|
815
|
/**
* Created by hanks on 15-10-28.
*/
fun main(args: Array<String>) {
val input1 = "23"
val input2 = "32"
val x = parseInt(input1)
val y = parseInt(input2)
// 直接使用 `x * y` 可能会报错,因为他们可能为 null
if (x != null && y != null) {
// 在空指针判断后,x 和 y 会自动变成非空(non-nullable)值
print(x * y)
} else {
print("your get wrong number")
}
val xx = parseInt(input1)
val yy = parseInt(input2)
if (xx == null) {
print("input1 is wrong number")
return
}
if (yy == null) {
print("input2 is wrong number")
return
}
//不判读xx和yy是否为空直接调用的话编译器报错
print(xx * yy)
}
fun parseInt(str: String): Int? {
return null
}
|
apache-2.0
|
655eb9af375e77a116d450456d0399fb
| 18.694444 | 47 | 0.533145 | 2.954167 | false | false | false | false |
ksmirenko/flexicards-android
|
app/src/main/java/com/ksmirenko/flexicards/app/CardContainerFragment.kt
|
1
|
6774
|
/*
* Copyright 2012 The Android Open Source Project
* Modifications copyright 2016 Kirill Smirenko
*
* 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.ksmirenko.flexicards.app
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.os.Bundle
import android.support.annotation.ColorRes
import android.support.v4.content.ContextCompat
import android.view.*
import android.widget.ImageView
//import android.support.v4.app.Fragment
import android.widget.TextView
/**
* Fragment that represents a single viewed card.
*/
class CardContainerFragment : Fragment() {
companion object {
// arguments
val ARG_FRONT_CONTENT = "front"
val ARG_BACK_CONTENT = "back"
val ARG_IS_BACK_FIRST = "backfirst"
private val dummyCallbacks = DummyCallbacks()
}
private var callbacks : Callbacks = dummyCallbacks
private var isShowingBack = false
override fun onAttach(context : Context) {
super.onAttach(context)
callbacks = context as Callbacks
}
// this is needed to support lower APIs
@Suppress("OverridingDeprecatedMember", "DEPRECATION")
override fun onAttach(activity : Activity) {
super.onAttach(activity)
callbacks = activity as Callbacks
}
override fun onCreateView(inflater : LayoutInflater?, container : ViewGroup?,
savedInstanceState : Bundle?) : View? {
val rootView = inflater!!.inflate(R.layout.fragment_cards_container, container, false)
val args = arguments
isShowingBack = args.getBoolean(ARG_IS_BACK_FIRST, false)
// adding card layout
val cardFragment = if (isShowingBack) CardBackFragment(callbacks) else CardFrontFragment(callbacks)
cardFragment.arguments = args // small workaround
childFragmentManager
.beginTransaction()
.add(R.id.layout_card_container, cardFragment)
.commit()
// adding event handler
val gestureDetector = GestureDetector(activity, CardGestureDetector(flipCard))
val layout = rootView.findViewById(R.id.layout_card_container)
layout.setOnTouchListener { view, motionEvent ->
gestureDetector.onTouchEvent(motionEvent)
}
return rootView
}
override fun onDetach() {
super.onDetach()
callbacks = dummyCallbacks
}
private val flipCard = {
val newFragment = if (isShowingBack) CardFrontFragment(callbacks) else CardBackFragment(callbacks)
newFragment.arguments = arguments
childFragmentManager
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out
)
.replace(R.id.layout_card_container, newFragment)
.commit()
isShowingBack = !isShowingBack
}
class CardFrontFragment(val callbacks : Callbacks) : Fragment() {
override fun onCreateView(inflater : LayoutInflater?, container : ViewGroup?,
savedInstanceState : Bundle?) : View? {
val rootView = inflater!!.inflate(R.layout.fragment_card, container, false)
rootView.setBackgroundColor(ContextCompat.getColor(MainActivity.getAppContext(), R.color.background))
val textView = rootView.findViewById(R.id.textview_cardview_mainfield) as TextView
textView.text = arguments.getString(CardContainerFragment.ARG_FRONT_CONTENT)
rootView.findViewById(R.id.button_cardview_know).setOnClickListener { callbacks.onCardButtonClicked(true) }
rootView.findViewById(R.id.button_cardview_notknow).setOnClickListener { callbacks.onCardButtonClicked(false) }
val iconQuit = rootView.findViewById(R.id.icon_cardview_quit) as ImageView
iconQuit.setOnClickListener { callbacks.onQuitButtonClicked() }
return rootView
}
}
class CardBackFragment(val callbacks : Callbacks) : Fragment() {
override fun onCreateView(inflater : LayoutInflater?, container : ViewGroup?,
savedInstanceState : Bundle?) : View? {
val rootView = inflater!!.inflate(R.layout.fragment_card, container, false)
rootView.setBackgroundColor(ContextCompat.getColor(MainActivity.getAppContext(), R.color.backgroundDark))
val textView = rootView.findViewById(R.id.textview_cardview_mainfield) as TextView
textView.text = arguments.getString(CardContainerFragment.ARG_BACK_CONTENT)
rootView.findViewById(R.id.button_cardview_know).setOnClickListener { callbacks.onCardButtonClicked(true) }
rootView.findViewById(R.id.button_cardview_notknow).setOnClickListener { callbacks.onCardButtonClicked(false) }
val iconQuit = rootView.findViewById(R.id.icon_cardview_quit) as ImageView
iconQuit.setOnClickListener { callbacks.onQuitButtonClicked() }
return rootView
}
}
class DummyCallbacks() : Callbacks {
override fun onCardButtonClicked(knowIt : Boolean) {
}
override fun onQuitButtonClicked() {
}
}
private class CardGestureDetector(val onTapAction : () -> Unit) : GestureDetector.OnGestureListener {
override fun onScroll(p0 : MotionEvent?, p1 : MotionEvent?, p2 : Float, p3 : Float) : Boolean = false
override fun onFling(p0 : MotionEvent?, p1 : MotionEvent?, p2 : Float, p3 : Float) : Boolean = false
override fun onShowPress(p0 : MotionEvent?) {
}
override fun onLongPress(p0 : MotionEvent?) {
}
/*
If set to true, this nasty thing won't let me scroll textviews.
If set to false, card flipping won't work.
Have no idea what to do with this thing.
*/
override fun onDown(e : MotionEvent) = true
override fun onSingleTapUp(e : MotionEvent?) : Boolean {
onTapAction()
return true
}
}
interface Callbacks {
fun onCardButtonClicked(knowIt : Boolean)
fun onQuitButtonClicked()
}
}
|
apache-2.0
|
1e8d465f27c71eb85ace47f9443053ea
| 39.813253 | 123 | 0.673014 | 4.770423 | false | false | false | false |
nextcloud/android
|
app/src/main/java/com/nextcloud/client/database/entity/CapabilityEntity.kt
|
1
|
6565
|
/*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.nextcloud.client.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@Entity(tableName = ProviderTableMeta.CAPABILITIES_TABLE_NAME)
data class CapabilityEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ProviderTableMeta._ID)
val id: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME)
val accountName: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_MAYOR)
val versionMajor: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_MINOR)
val versionMinor: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_MICRO)
val versionMicro: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_STRING)
val versionString: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_EDITION)
val versionEditor: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_EXTENDED_SUPPORT)
val extendedSupport: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL)
val corePollinterval: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED)
val sharingApiEnabled: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED)
val sharingPublicEnabled: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED)
val sharingPublicPasswordEnforced: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED)
val sharingPublicExpireDateEnabled: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS)
val sharingPublicExpireDateDays: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED)
val sharingPublicExpireDateEnforced: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL)
val sharingPublicSendMail: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD)
val sharingPublicUpload: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL)
val sharingUserSendMail: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_RESHARING)
val sharingResharing: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING)
val sharingFederationOutgoing: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING)
val sharingFederationIncoming: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING)
val filesBigfilechunking: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_FILES_UNDELETE)
val filesUndelete: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_FILES_VERSIONING)
val filesVersioning: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_EXTERNAL_LINKS)
val externalLinks: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SERVER_NAME)
val serverName: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SERVER_COLOR)
val serverColor: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SERVER_TEXT_COLOR)
val serverTextColor: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SERVER_ELEMENT_COLOR)
val serverElementColor: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SERVER_SLOGAN)
val serverSlogan: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SERVER_LOGO)
val serverLogo: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SERVER_BACKGROUND_URL)
val serverBackgroundUrl: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_END_TO_END_ENCRYPTION)
val endToEndEncryption: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_END_TO_END_ENCRYPTION_KEYS_EXIST)
val endToEndEncryptionKeysExist: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_ACTIVITY)
val activity: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SERVER_BACKGROUND_DEFAULT)
val serverBackgroundDefault: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SERVER_BACKGROUND_PLAIN)
val serverBackgroundPlain: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_RICHDOCUMENT)
val richdocument: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_RICHDOCUMENT_MIMETYPE_LIST)
val richdocumentMimetypeList: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_RICHDOCUMENT_DIRECT_EDITING)
val richdocumentDirectEditing: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_RICHDOCUMENT_TEMPLATES)
val richdocumentTemplates: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_RICHDOCUMENT_OPTIONAL_MIMETYPE_LIST)
val richdocumentOptionalMimetypeList: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ASK_FOR_OPTIONAL_PASSWORD)
val sharingPublicAskForOptionalPassword: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_RICHDOCUMENT_PRODUCT_NAME)
val richdocumentProductName: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_DIRECT_EDITING_ETAG)
val directEditingEtag: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_USER_STATUS)
val userStatus: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_USER_STATUS_SUPPORTS_EMOJI)
val userStatusSupportsEmoji: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_ETAG)
val etag: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_FILES_LOCKING_VERSION)
val filesLockingVersion: String?
)
|
gpl-2.0
|
442f6fb22800c73f984f7e59549b4f1d
| 49.099237 | 95 | 0.774189 | 4.507555 | false | false | false | false |
LarsKrogJensen/graphql-kotlin
|
src/main/kotlin/graphql/Scalars.kt
|
1
|
10349
|
package graphql
import graphql.language.BooleanValue
import graphql.language.FloatValue
import graphql.language.IntValue
import graphql.language.StringValue
import graphql.schema.Coercing
import graphql.schema.GraphQLNonNull
import graphql.schema.GraphQLScalarType
import java.math.BigDecimal
import java.math.BigInteger
import java.text.SimpleDateFormat
import java.util.*
private val LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE)
private val LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE)
private val INT_MAX = BigInteger.valueOf(Int.MAX_VALUE.toLong())
private val INT_MIN = BigInteger.valueOf(Int.MIN_VALUE.toLong())
private val BYTE_MAX = BigInteger.valueOf(Byte.MAX_VALUE.toLong())
private val BYTE_MIN = BigInteger.valueOf(Byte.MIN_VALUE.toLong())
private val SHORT_MAX = BigInteger.valueOf(Short.MAX_VALUE.toLong())
private val SHORT_MIN = BigInteger.valueOf(Short.MIN_VALUE.toLong())
private fun isWholeNumber(input: Any?) = input is Long || input is Int || input is Short || input is Byte
// true if its a number or string that we will attempt to convert to a number via toNumber()
private fun isNumberIsh(input: Any?): Boolean = input is Number || input is String
private fun toNumber(input: Any?) = when (input) {
is Number -> input
is String -> input.toDouble() // Use double as a intermediate Number representation
else -> throw AssertException("Unexpected case - this call should be protected by a previous call to isNumberIsh()")
}
private fun verifyRange(input: IntValue, min: BigInteger, max: BigInteger): IntValue {
val value = input.value
if (value.compareTo(min) == -1 || value.compareTo(max) == 1) {
throw GraphQLException("Scalar literal is too big or too small")
}
return input
}
val GraphQLInt = GraphQLScalarType("Int", "Built-in Int", object : Coercing<Int?, Int?> {
override fun serialize(input: Any?): Int? =
when {
input is Int -> input
isNumberIsh(input) -> toNumber(input).toInt()
else -> null
}
override fun parseValue(input: Any?): Int? = serialize(input)
override fun parseLiteral(input: Any?): Int? =
when (input) {
is IntValue -> verifyRange(input, INT_MIN, INT_MAX).value.toInt()
else -> null
}
})
val GraphQLLong = GraphQLScalarType("Long", "Long type", object : Coercing<Long?, Long?> {
override fun serialize(input: Any?): Long? =
when {
input is Long -> input
isNumberIsh(input) -> toNumber(input).toLong()
else -> null
}
override fun parseValue(input: Any?): Long? = serialize(input)
override fun parseLiteral(input: Any?): Long? =
when (input) {
is StringValue -> input.value.toLong()
is IntValue -> verifyRange(input, LONG_MIN, LONG_MAX).value.toLong()
else -> null
}
})
val GraphQLShort = GraphQLScalarType("Short", "Built-in Short as Int", object : Coercing<Short?, Short?> {
override fun serialize(input: Any?): Short? =
when {
input is Short -> input
isNumberIsh(input) -> toNumber(input).toShort()
else -> null
}
override fun parseValue(input: Any?): Short? = serialize(input)
override fun parseLiteral(input: Any?): Short? =
when (input) {
is StringValue -> input.value.toShort()
is IntValue -> verifyRange(input, SHORT_MIN, SHORT_MAX).value.toShort()
else -> null
}
})
val GraphQLByte = GraphQLScalarType("Byte", "Built-in Byte as Int", object : Coercing<Byte?, Byte?> {
override fun serialize(input: Any?): Byte? =
when {
input is Byte -> input
isNumberIsh(input) -> toNumber(input).toByte()
else -> null
}
override fun parseValue(input: Any?): Byte? = serialize(input)
override fun parseLiteral(input: Any?): Byte? =
when (input) {
is StringValue -> input.value.toByte()
is IntValue -> verifyRange(input, BYTE_MIN, BYTE_MAX).value.toByte()
else -> null
}
})
val GraphQLFloat = GraphQLScalarType("Float", "Built-in Float", object : Coercing<Number?, Number?> {
override fun serialize(input: Any?): Number? = when {
input is Float -> input //toNumber(input.toString()).toDouble()
input is Double -> input
isNumberIsh(input) -> toNumber(input).toDouble()
else -> null
}
override fun parseValue(input: Any?): Number? = serialize(input)
override fun parseLiteral(input: Any?): Number? =
when (input) {
is FloatValue -> input.value.toDouble()
is IntValue -> input.value.toDouble()
else -> null
}
})
val GraphQLBigInteger = GraphQLScalarType("BigInteger", "Built-in java.math.BigInteger", object : Coercing<BigInteger?, BigInteger?> {
override fun serialize(input: Any?): BigInteger? =
when {
input is BigInteger -> input
input is String -> BigInteger(input)
isNumberIsh(input) -> BigInteger.valueOf(toNumber(input).toLong())
else -> null
}
override fun parseValue(input: Any?): BigInteger? = serialize(input)
override fun parseLiteral(input: Any?): BigInteger? =
when (input) {
is StringValue -> BigInteger(input.value)
is IntValue -> input.value
else -> null
}
})
val GraphQLBigDecimal = GraphQLScalarType("BigDecimal", "Built-in java.math.BigDecimal", object : Coercing<BigDecimal?, BigDecimal?> {
override fun serialize(input: Any?): BigDecimal? =
when {
input is BigDecimal -> input
input is String -> BigDecimal(input)
isWholeNumber(input) -> BigDecimal.valueOf(toNumber(input).toLong())
input is Number -> BigDecimal.valueOf(toNumber(input).toDouble())
else -> null
}
override fun parseValue(input: Any?): BigDecimal? = serialize(input)
override fun parseLiteral(input: Any?): BigDecimal? =
when (input) {
is StringValue -> BigDecimal(input.value)
is IntValue -> BigDecimal(input.value)
is FloatValue -> input.value
else -> null
}
})
val GraphQLString = GraphQLScalarType("String", "Built-in String", object : Coercing<String?, String?> {
override fun serialize(input: Any?): String? = input?.toString()
override fun parseValue(input: Any?): String? = serialize(input)
override fun parseLiteral(input: Any?): String? =
when (input) {
is StringValue -> input.value
else -> null
}
})
val GraphQLStringNonNull = GraphQLNonNull(GraphQLString)
val GraphQLBoolean = GraphQLScalarType("Boolean", "Built-in Boolean", object : Coercing<Boolean?, Boolean?> {
override fun serialize(input: Any?): Boolean? =
when (input) {
is Boolean -> input
is Int -> input > 0
is String -> input.toBoolean()
else -> null
}
override fun parseValue(input: Any?): Boolean? = serialize(input)
override fun parseLiteral(input: Any?): Boolean? =
when (input) {
is BooleanValue -> input.value
else -> null
}
})
val GraphQLID = GraphQLScalarType("ID", "Built-in ID", object : Coercing<String?, String?> {
override fun serialize(input: Any?): String? =
when (input) {
is String -> input
is Int -> input.toString()
else -> null
}
override fun parseValue(input: Any?): String? = serialize(input)
override fun parseLiteral(input: Any?): String? =
when (input) {
is StringValue -> input.value
is IntValue -> input.value.toString()
else -> null
}
})
val GraphQLChar = GraphQLScalarType("Char", "Built-in Char as Character", object : Coercing<Char?, Char?> {
override fun serialize(input: Any?): Char? =
when (input) {
is Char -> input
is String -> if (input.length == 1) input[0] else null
else -> null
}
override fun parseValue(input: Any?): Char? = serialize(input)
override fun parseLiteral(input: Any?): Char? =
when (input) {
is StringValue -> if (input.value.length == 1) input.value[0] else null
else -> null
}
})
val GraphQLDate = GraphQLScalarType("DateTime", "DateTime type", object : Coercing<Date?, Date?> {
private val dateFormat = "yyyy-MM-dd'T'HH:mm'Z'"
private val timeZone = TimeZone.getTimeZone("UTC")
override fun serialize(input: Any?): Date? {
when (input) {
is String -> return parse(input as String?)
is Date -> return input
is Long -> return Date(input)
is Int -> return Date(input.toLong())
else -> throw GraphQLException("Wrong timestamp value")
}
}
override fun parseValue(input: Any?): Date? {
return serialize(input)
}
override fun parseLiteral(input: Any?): Date? {
if (input !is StringValue) return null
return parse(input.value)
}
private fun parse(input: String?): Date {
try {
return simpleDateFormat.parse(input)
} catch (e: Exception) {
throw GraphQLException("Can not parse input date", e)
}
}
private val simpleDateFormat: SimpleDateFormat
get() {
val df = SimpleDateFormat(dateFormat)
df.timeZone = timeZone
return df
}
})
|
mit
|
397e7a08ffe65652f59a2b220b8a1a7b
| 35.829181 | 134 | 0.571843 | 4.491753 | false | false | false | false |
LarsKrogJensen/graphql-kotlin
|
src/main/kotlin/graphql/language/FieldDefinition.kt
|
1
|
1284
|
package graphql.language
import java.util.ArrayList
class FieldDefinition : AbstractNode {
val name: String
var type: Type? = null
val inputValueDefinitions: MutableList<InputValueDefinition> = ArrayList()
val directives: MutableList<Directive> = ArrayList()
constructor(name: String) {
this.name = name
}
constructor(name: String, type: Type) {
this.name = name
this.type = type
}
override val children: List<Node>
get() {
val result = ArrayList<Node>()
type?.let { result.add(it) }
result.addAll(inputValueDefinitions)
result.addAll(directives)
return result
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
val that = node as FieldDefinition
if (name != that.name) {
return false
}
return true
}
override fun toString(): String {
return "FieldDefinition{" +
"name='" + name + '\'' +
", type=" + type +
", inputValueDefinitions=" + inputValueDefinitions +
", directives=" + directives +
'}'
}
}
|
mit
|
2a4a448cd1dfa6f9d48b8b8e748241a8
| 24.176471 | 78 | 0.553738 | 4.882129 | false | false | false | false |
usbpc102/usbBot
|
src/main/kotlin/usbbot/commands/CommandHandler.kt
|
1
|
7279
|
package usbbot.commands
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.newFixedThreadPoolContext
import kotlinx.coroutines.experimental.newSingleThreadContext
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import usbbot.commands.core.Command
import usbbot.commands.security.PermissionManager
import usbbot.modules.SimpleTextResponses
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import sx.blah.discord.handle.obj.IMessage
import sx.blah.discord.handle.obj.Permissions
import usbbot.config.*
import usbbot.util.MessageSending
import util.sendSuccess
import kotlin.system.measureTimeMillis
class CommandHandler {
companion object {
val logger : Logger = LoggerFactory.getLogger(CommandHandler::class.java)
val stc = newFixedThreadPoolContext(4,"commandExecutor")
}
private var cmdMap = HashMap<String, Command>()
init {
cmdMap.put("list", object: Command() {
override fun execute(msg: IMessage, args: Array<String>) {
val iterator = cmdMap.keys.iterator()
val builder = StringBuilder()
while (iterator.hasNext()) {
builder.append('`').append(iterator.next()).append("`").append(", ")
}
var iterator2 : Iterator<DBTextCommand>? = null
val time = measureTimeMillis {
iterator2 = getDBTextCommandsForGuild(msg.guild.longID).iterator()
}
logger.trace("It took me {}ms to look up how many text commands there are.", time)
while (iterator2!!.hasNext()) {
builder.append('`').append(iterator2!!.next().name).append("`")
if (iterator2!!.hasNext()) {
builder.append(", ")
}
}
msg.channel.sendSuccess("Commands are: " + builder.toString())
}
})
}
fun createMissingPermissions(guildID: Long) {
var guildCommands = getCommandsForGuild(guildID)
cmdMap.keys.filter { cmdName -> guildCommands.find { it.name == cmdName} == null }.forEach {
createDBCommand(guildID, it, "whitelist", "whitelist")
}
}
fun registerCommand(cmd: Command) = cmdMap.put(cmd.name, cmd)
fun registerCommands(cmds: DiscordCommands) = cmds.discordCommands.forEach({registerCommand(it)})
fun discordCommandExists(name: String, guildID: Long) : Boolean {
if (cmdMap.containsKey(name)) return true
//FIXME: This only exists so that the SimpleTextResponses Module knows that a command with that name is already registered, so remove this
if (getCommandForGuild(guildID, name) != null) return true
return false
}
fun getArguments(input: String, prefix: String): Array<String> {
return input.substring(input.indexOf(prefix) + prefix.length).split(" +".toRegex()).dropWhile({ it.isEmpty() }).toTypedArray()
}
fun onMessageRecivedEvent(event: MessageReceivedEvent) {
//Check that the message was not send in a private channel, if it was just ignore it.
//repeat(10) {
val timeForCoroutineStart = measureTimeMillis {
launch(stc) {
val timeCoroutineStart = System.currentTimeMillis()
if (!(event.author.isBot || event.channel.isPrivate)) {
//TODO: Check if the message is on the word/regex blacklist, remove it if it is (blacklist may not apply to all users)
//Check if the message starts with the server command prefix, if not ignore it
val guild = getGuildById(event.guild.longID) ?:
throw IllegalStateException("A Command was tried to be executed on a Guild that has no DB entry")
if (event.message.content.startsWith(guild.prefix)) {
val args = getArguments(event.message.content, guild.prefix)
//check if the message contains a valid command for that guild and check permissions
//I need to check if the command exists before testing for permissions, otherwise a permission entry will be created
logger.trace("IT took me {}ms to get before StupidWrapper", System.currentTimeMillis() - timeCoroutineStart)
val stupidWrapper = StupidWrapper()
logger.trace("IT took me {}ms to get after StupidWrapper", System.currentTimeMillis() - timeCoroutineStart)
if(stupidWrapper.isCommand(cmdMap, event.guild.longID, args[0])) {
logger.trace("IT took me {}ms to check if it is a command", System.currentTimeMillis() - timeCoroutineStart)
val isAdministrator = event.author.getPermissionsForGuild(event.guild).contains(Permissions.ADMINISTRATOR)
if(isAdministrator || PermissionManager.hasPermission(
event.guild.longID,
event.author.longID,
event.message.guild.getRolesForUser(event.author).map { it.longID },
args[0])) {
logger.trace("IT took me {}ms to check permissions (successful)", System.currentTimeMillis() - timeCoroutineStart)
if (stupidWrapper.stc == null) {
cmdMap[args[0]]?.execute(event.message, args)
} else {
SimpleTextResponses.answer(event.message, stupidWrapper.stc)
}
} else {
logger.trace("IT took me {}ms to check permissions (unsuccessful)", System.currentTimeMillis() - timeCoroutineStart)
MessageSending.sendMessage(event.channel, "You don't have permissions required to use this command!")
}
logger.trace("IT took me {}ms to run the command", System.currentTimeMillis() - timeCoroutineStart)
}
}
}
logger.trace("It took me {} ms to execute the Coroutine for message {}", System.currentTimeMillis() - timeCoroutineStart, event.message.content)
}
}
logger.trace("It took me {} ms to start the Coroutine for message {}", timeForCoroutineStart, event.message.content)
// }
}
}
private class StupidWrapper {
var stc : DBTextCommand? = null
fun isCommand(cmdMap: HashMap<String, Command>, guildID: Long, name: String) : Boolean {
if (cmdMap.containsKey(name)) return true
stc = getDBTextCommand(guildID, name)
if (stc != null) return true
return false
}
}
|
mit
|
456a5aad0583e0a670889c8c8461fae6
| 54.564885 | 164 | 0.576315 | 5.282293 | false | false | false | false |
Ztiany/Repository
|
Kotlin/Kotlin-github/app/src/main/java/retrofit2/adapter/rxjava/GitHubPaging.kt
|
2
|
1644
|
package retrofit2.adapter.rxjava
import com.bennyhuo.common.log.logger
import okhttp3.HttpUrl
class GitHubPaging<T>: ArrayList<T>() {
companion object {
const val URL_PATTERN = """(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"""
}
private val relMap = HashMap<String, String?>().withDefault { null }
private val first by relMap
private val last by relMap
private val next by relMap
private val prev by relMap
val isLast
get() = last == null
val hasNext
get() = next != null
val isFirst
get() = first == null
val hasPrev
get() = prev != null
var since: Int = 0
operator fun get(key: String): String?{
return relMap[key]
}
fun setupLinks(link: String){
logger.warn("setupLinks: $link")
Regex("""<($URL_PATTERN)>; rel="(\w+)"""").findAll(link).asIterable()
.map {
matchResult ->
val url = matchResult.groupValues[1]
relMap[matchResult.groupValues[3]] = url // next=....
if(url.contains("since")){
HttpUrl.parse(url)?.queryParameter("since")?.let{
since = it.toInt()
}
}
logger.warn("${matchResult.groupValues[3]} => ${matchResult.groupValues[1]}")
}
}
fun mergeData(paging: GitHubPaging<T>): GitHubPaging<T>{
addAll(paging)
relMap.clear()
relMap.putAll(paging.relMap)
since = paging.since
return this
}
}
|
apache-2.0
|
7541811d4eafc267819f0d8a7c0193d0
| 26.881356 | 109 | 0.51764 | 4.162025 | false | false | false | false |
rhdunn/marklogic-intellij-plugin
|
src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/query/Function.kt
|
1
|
7585
|
/*
* Copyright (C) 2017 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.marklogic.query
import com.intellij.execution.ExecutionException
import org.apache.xmlbeans.impl.common.IOUtil
import uk.co.reecedunn.intellij.plugin.marklogic.ui.configuration.MarkLogicRunConfiguration
import uk.co.reecedunn.intellij.plugin.marklogic.query.options.EvalOptionsBuilder
import uk.co.reecedunn.intellij.plugin.marklogic.query.options.OptionsBuilder
import uk.co.reecedunn.intellij.plugin.marklogic.query.vars.KeyValueVarsBuilder
import uk.co.reecedunn.intellij.plugin.marklogic.query.vars.MapVarsBuilder
import uk.co.reecedunn.intellij.plugin.marklogic.query.vars.VarsBuilder
import java.io.*
enum class Function constructor(
private val function: String,
private val varsBuilder: VarsBuilder?,
private val optionsBuilder: OptionsBuilder?,
private val parameters: Parameters) {
DBG_EVAL_50(
"dbg:eval(\$query, \$vars, \$options)",
KeyValueVarsBuilder,
EvalOptionsBuilder,
Parameters.Eval),
DBG_EVAL_80(
"dbg:eval(\$query, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.Eval),
DBG_INVOKE_50(
"dbg:invoke(\$path, \$vars, \$options)",
KeyValueVarsBuilder,
EvalOptionsBuilder,
Parameters.Invoke),
DBG_INVOKE_80(
"dbg:invoke(\$path, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.Invoke),
PROF_EVAL_50(
"prof:eval(\$query, \$vars, \$options)",
KeyValueVarsBuilder,
EvalOptionsBuilder,
Parameters.Eval),
PROF_EVAL_80(
"prof:eval(\$query, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.Eval),
PROF_INVOKE_50(
"prof:invoke(\$path, \$vars, \$options)",
KeyValueVarsBuilder,
EvalOptionsBuilder,
Parameters.Invoke),
PROF_INVOKE_80(
"prof:invoke(\$path, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.Invoke),
PROF_XSLT_EVAL_50(
"prof:xslt-eval(\$query, \$input, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.EvalStylesheet),
PROF_XSLT_INVOKE_50(
"prof:xslt-invoke(\$path, \$input, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.InvokeStylesheet),
SEM_SPARQL_70(
"sem:sparql(\$query, \$vars)",
MapVarsBuilder, null,
Parameters.Eval),
SEM_SPARQL_UPDATE_80(
"sem:sparql-update(\$query, \$vars)",
MapVarsBuilder, null,
Parameters.Eval),
XDMP_EVAL_50(
"xdmp:eval(\$query, \$vars, \$options)",
KeyValueVarsBuilder,
EvalOptionsBuilder,
Parameters.Eval),
XDMP_EVAL_70(
"xdmp:eval(\$query, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.Eval),
XDMP_INVOKE_50(
"xdmp:invoke(\$path, \$vars, \$options)",
KeyValueVarsBuilder,
EvalOptionsBuilder,
Parameters.Invoke),
XDMP_INVOKE_70(
"xdmp:invoke(\$path, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.Invoke),
XDMP_JAVASCRIPT_EVAL_80(
"xdmp:javascript-eval(\$query, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.Eval),
XDMP_SQL_80(
"xdmp:sql(\$query)", null, null,
Parameters.Eval),
XDMP_SQL_90(
"xdmp:sql(\$query, (), \$vars)",
MapVarsBuilder, null,
Parameters.Eval),
XDMP_XSLT_EVAL_50(
"xdmp:xslt-eval(\$query, \$input, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.EvalStylesheet),
XDMP_XSLT_INVOKE_50(
"xdmp:xslt-invoke(\$path, \$input, \$vars, \$options)",
MapVarsBuilder,
EvalOptionsBuilder,
Parameters.InvokeStylesheet);
enum class Parameters {
// // $query | $path | $input | $vars | $options |
//----------------//-----------|-----------|--------|---------|----------|
Eval, // xs:string | - | - | item()* | item()* |
Invoke, // - | xs:string | - | item()* | item()* |
EvalStylesheet, // node() | - | node() | item()* | item()* |
InvokeStylesheet // - | xs:string | node() | item()* | item()* |
}
@Throws(ExecutionException::class)
fun buildQuery(configuration: MarkLogicRunConfiguration): String {
val query = readFileContent(configuration)
val options: String
if (optionsBuilder != null) {
optionsBuilder.reset()
optionsBuilder.contentDatabase = configuration.contentDatabase
optionsBuilder.modulesDatabase = configuration.moduleDatabase
optionsBuilder.modulesRoot = configuration.moduleRoot
options = optionsBuilder.build()
} else {
options = "()"
}
val tripleFormat = configuration.tripleFormat
val markLogicVersion = configuration.markLogicVersion
return if (tripleFormat == SEM_TRIPLE || markLogicVersion.major < 7) {
RUN_QUERY.query
.replace("\$QUERY_STRING", asXQueryStringContent(query))
.replace("\$OPTIONS", options)
.replace("\$FUNCTION", function)
} else {
RUN_QUERY_AS_RDF.query
.replace("\$QUERY_STRING", asXQueryStringContent(query))
.replace("\$OPTIONS", options)
.replace("\$FUNCTION", function)
.replace("\$TRIPLE_FORMAT", tripleFormat.markLogicName)
.replace("\$CONTENT_TYPE", tripleFormat.contentType)
}
}
@Throws(ExecutionException::class)
private fun readFileContent(configuration: MarkLogicRunConfiguration): String {
val file = configuration.mainModuleFile ?: throw ExecutionException("Missing query file: " + configuration.mainModulePath)
try {
return streamToString(file.inputStream)
} catch (e: IOException) {
throw ExecutionException(e)
}
}
@Throws(IOException::class)
private fun streamToString(stream: InputStream): String {
val writer = StringWriter()
IOUtil.copyCompletely(InputStreamReader(stream), writer)
return writer.toString()
}
private fun asXQueryStringContent(query: String): String {
return query.replace("\"".toRegex(), "\"\"").replace("&".toRegex(), "&")
}
}
|
apache-2.0
|
2aa91a4f09ae5048ef3c6551b92fc6a5
| 35.119048 | 130 | 0.581411 | 4.482861 | false | true | false | false |
pennlabs/penn-mobile-android
|
PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/FlingRecyclerViewAdapter.kt
|
1
|
2492
|
package com.pennapps.labs.pennmobile.adapters
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.pennapps.labs.pennmobile.R
import com.pennapps.labs.pennmobile.classes.FlingEvent
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fling_performance_item.view.*
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import org.joda.time.format.ISODateTimeFormat
class FlingRecyclerViewAdapter(private val context: Context?, private val sampleData: List<FlingEvent>) : RecyclerView.Adapter<FlingRecyclerViewAdapter.ViewHolder>() {
private val timeFormatter: DateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis()
override fun getItemCount(): Int {
return sampleData.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.fling_performance_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (position < itemCount) {
val flingEvent = sampleData[position]
val picasso = Picasso.get()
picasso.isLoggingEnabled = true
if (holder.flingview_image != null) picasso.load(flingEvent.imageUrl).into(holder.flingview_image)
holder.flingview_name?.text = flingEvent.name
holder.flingview_description?.text = flingEvent.description
val startTime = timeFormatter.parseDateTime(flingEvent.startTime)
val endTime = timeFormatter.parseDateTime(flingEvent.endTime)
val dtfStart = DateTimeFormat.forPattern("h:mm")
val dtfEnd = DateTimeFormat.forPattern("h:mm a")
holder.flingview_time?.text = String.format(context?.resources?.getString(R.string.fling_event_time).toString(), dtfStart.print(startTime), dtfEnd.print(endTime))
}
}
class ViewHolder (view: View) : RecyclerView.ViewHolder(view) {
internal var flingview_image: ImageView? = view.flingview_image
internal var flingview_name: TextView? = view.flingview_name
internal var flingview_description: TextView? = view.flingview_description
internal var flingview_time: TextView? = view.flingview_time
}
}
|
mit
|
76bccf5c896ca8979acf348dece27790
| 45.166667 | 174 | 0.739968 | 4.45 | false | false | false | false |
vondear/RxTools
|
RxKit/src/main/java/com/tamsiree/rxkit/RxExifTool.kt
|
1
|
2322
|
package com.tamsiree.rxkit
import android.location.Location
import android.media.ExifInterface
import com.orhanobut.logger.Logger
import java.io.File
/**
*
* @author Tamsiree
* @date 2017/7/28
*/
object RxExifTool {
/**
* 将经纬度信息写入JPEG图片文件里
*
* @param picPath JPEG图片文件路径
* @param dLat 纬度
* @param dLon 经度
*/
@JvmStatic
fun writeLatLonIntoJpeg(picPath: String, dLat: Double, dLon: Double) {
val file = File(picPath)
if (file.exists()) {
try {
val exif = ExifInterface(picPath)
val tagLat = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE)
val tagLon = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE)
if (tagLat == null && tagLon == null) { // 无经纬度信息
exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, gpsInfoConvert(dLat))
exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, if (dLat > 0) "N" else "S") // 区分南北半球
exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, gpsInfoConvert(dLon))
exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, if (dLon > 0) "E" else "W") // 区分东经西经
exif.saveAttributes()
}
exif.saveAttributes()
Logger.d("""
${exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE)}
${exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE)}
${exif.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD)}
${exif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH)}
${exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH)}
""".trimIndent())
} catch (e: Exception) {
}
}
}
private fun gpsInfoConvert(gpsInfo: Double): String {
var gpsInfo = gpsInfo
gpsInfo = Math.abs(gpsInfo)
val dms = Location.convert(gpsInfo, Location.FORMAT_SECONDS)
val splits = dms.split(":").toTypedArray()
val secnds = splits[2].split("\\.").toTypedArray()
val seconds: String
seconds = if (secnds.size == 0) {
splits[2]
} else {
secnds[0]
}
return splits[0] + "/1," + splits[1] + "/1," + seconds + "/1"
}
}
|
apache-2.0
|
e9d6156f32c270137849f79b9ed8c5f4
| 34.571429 | 112 | 0.584375 | 3.79661 | false | false | false | false |
shlusiak/Freebloks-Android
|
app/src/main/java/de/saschahlusiak/freebloks/view/effects/ShapeUndoEffect.kt
|
1
|
1999
|
package de.saschahlusiak.freebloks.view.effects
import de.saschahlusiak.freebloks.model.Turn
import de.saschahlusiak.freebloks.view.BoardRenderer
import de.saschahlusiak.freebloks.view.scene.Scene
import javax.microedition.khronos.opengles.GL11
import kotlin.math.pow
class ShapeUndoEffect(model: Scene, turn: Turn) : AbsShapeEffect(model, turn) {
private val timeMax = 1.1f
private var phase = 0f
private var z = 0f
private var alpha = 0f
private var rot = 0f
override fun isDone(): Boolean {
return time > timeMax
}
override fun execute(elapsed: Float): Boolean {
super.execute(elapsed)
phase = (time / timeMax).pow(0.8f)
alpha = 1.0f - phase
z = 13.0f * phase
rot = phase * 65.0f
return true
}
override fun renderShadow(gl: GL11, renderer: BoardRenderer) {
gl.glPushMatrix()
gl.glTranslatef(
-BoardRenderer.stoneSize * (scene.board.width - 1).toFloat() + BoardRenderer.stoneSize * 2.0f * x,
0f,
-BoardRenderer.stoneSize * (scene.board.height - 1).toFloat() + BoardRenderer.stoneSize * 2.0f * y
)
renderer.renderShapeShadow(gl,
shape, color, orientation,
z,
rot, 0f, 1f, 0f,
scene.boardObject.currentAngle - scene.baseAngle,
alpha, 1.0f
)
gl.glPopMatrix()
}
override fun render(gl: GL11, renderer: BoardRenderer) {
gl.glPushMatrix()
gl.glTranslatef(0f, z, 0f)
gl.glTranslatef(
-BoardRenderer.stoneSize * (scene.board.width - 1).toFloat() + BoardRenderer.stoneSize * 2.0f * x.toFloat(),
0f,
-BoardRenderer.stoneSize * (scene.board.height - 1).toFloat() + BoardRenderer.stoneSize * 2.0f * y.toFloat()
)
gl.glRotatef(rot, 0f, 1f, 0f)
renderer.renderShape(gl, color, shape, orientation, alpha * BoardRenderer.defaultStoneAlpha)
gl.glPopMatrix()
}
}
|
gpl-2.0
|
3d870e981a9a23d3738f0ce84e62c95e
| 31.786885 | 120 | 0.622311 | 3.654479 | false | false | false | false |
vondear/RxTools
|
RxKit/src/main/java/com/tamsiree/rxkit/RxEncryptTool.kt
|
1
|
16083
|
package com.tamsiree.rxkit
import com.tamsiree.rxkit.RxDataTool.Companion.bytes2HexString
import com.tamsiree.rxkit.RxDataTool.Companion.hexString2Bytes
import com.tamsiree.rxkit.RxEncodeTool.base64Decode
import com.tamsiree.rxkit.RxEncodeTool.base64Encode
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.nio.channels.FileChannel
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
/**
*
* @author tamsiree
* @date 2016/1/24
* 加密解密相关的工具类
*/
object RxEncryptTool {
/*********************** 哈希加密相关 */
private const val DES_Algorithm = "DES"
private const val TripleDES_Algorithm = "DESede"
private const val AES_Algorithm = "AES"
/**
* DES转变
*
* 法算法名称/加密模式/填充方式
*
* 加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB
*
* 填充方式有:NoPadding、ZerosPadding、PKCS5Padding
*/
var DES_Transformation = "DES/ECB/NoPadding"
/**
* 3DES转变
*
* 法算法名称/加密模式/填充方式
*
* 加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB
*
* 填充方式有:NoPadding、ZerosPadding、PKCS5Padding
*/
var TripleDES_Transformation = "DESede/ECB/NoPadding"
/**
* AES转变
*
* 法算法名称/加密模式/填充方式
*
* 加密模式有:电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB
*
* 填充方式有:NoPadding、ZerosPadding、PKCS5Padding
*/
var AES_Transformation = "AES/ECB/NoPadding"
/**
* MD2加密
*
* @param data 明文字符串
* @return 16进制密文
*/
@JvmStatic
fun encryptMD2ToString(data: String): String {
return encryptMD2ToString(data.toByteArray())
}
/**
* MD2加密
*
* @param data 明文字节数组
* @return 16进制密文
*/
@JvmStatic
fun encryptMD2ToString(data: ByteArray?): String {
return bytes2HexString(encryptMD2(data))
}
/**
* MD2加密
*
* @param data 明文字节数组
* @return 密文字节数组
*/
@JvmStatic
fun encryptMD2(data: ByteArray?): ByteArray {
return encryptAlgorithm(data, "MD2")
}
/**
* MD5加密
*
* @param data 明文字符串
* @return 16进制密文
*/
@JvmStatic
fun encryptMD5ToString(data: String): String {
return encryptMD5ToString(data.toByteArray())
}
/**
* MD5加密
*
* @param data 明文字符串
* @param salt 盐
* @return 16进制加盐密文
*/
@JvmStatic
fun encryptMD5ToString(data: String, salt: String): String {
return bytes2HexString(encryptMD5((data + salt).toByteArray()))
}
/**
* MD5加密
*
* @param data 明文字节数组
* @return 16进制密文
*/
@JvmStatic
fun encryptMD5ToString(data: ByteArray?): String {
return bytes2HexString(encryptMD5(data))
}
/**
* MD5加密
*
* @param data 明文字节数组
* @param salt 盐字节数组
* @return 16进制加盐密文
*/
@JvmStatic
fun encryptMD5ToString(data: ByteArray, salt: ByteArray): String {
val dataSalt = ByteArray(data.size + salt.size)
System.arraycopy(data, 0, dataSalt, 0, data.size)
System.arraycopy(salt, 0, dataSalt, data.size, salt.size)
return bytes2HexString(encryptMD5(dataSalt))
}
/**
* MD5加密
*
* @param data 明文字节数组
* @return 密文字节数组
*/
@JvmStatic
fun encryptMD5(data: ByteArray?): ByteArray {
return encryptAlgorithm(data, "MD5")
}
/**
* MD5加密文件
*
* @param filePath 文件路径
* @return 文件的16进制密文
*/
@JvmStatic
fun encryptMD5File2String(filePath: String?): String {
return encryptMD5File2String(File(filePath))
}
/**
* MD5加密文件
*
* @param filePath 文件路径
* @return 文件的MD5校验码
*/
@JvmStatic
fun encryptMD5File(filePath: String?): ByteArray? {
return encryptMD5File(File(filePath))
}
/**
* MD5加密文件
*
* @param file 文件
* @return 文件的16进制密文
*/
@JvmStatic
fun encryptMD5File2String(file: File): String {
return if (encryptMD5File(file) != null) bytes2HexString(encryptMD5File(file)!!) else ""
}
/**
* MD5加密文件
*
* @param file 文件
* @return 文件的MD5校验码
*/
@JvmStatic
fun encryptMD5File(file: File): ByteArray? {
var fis: FileInputStream? = null
try {
fis = FileInputStream(file)
val channel = fis.channel
val buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length())
val md = MessageDigest.getInstance("MD5")
md.update(buffer)
return md.digest()
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
} finally {
RxFileTool.closeIO(fis)
}
return null
}
/**
* SHA1加密
*
* @param data 明文字符串
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA1ToString(data: String): String {
return encryptSHA1ToString(data.toByteArray())
}
/**
* SHA1加密
*
* @param data 明文字节数组
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA1ToString(data: ByteArray?): String {
return bytes2HexString(encryptSHA1(data))
}
/**
* SHA1加密
*
* @param data 明文字节数组
* @return 密文字节数组
*/
@JvmStatic
fun encryptSHA1(data: ByteArray?): ByteArray {
return encryptAlgorithm(data, "SHA-1")
}
/**
* SHA224加密
*
* @param data 明文字符串
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA224ToString(data: String): String {
return encryptSHA224ToString(data.toByteArray())
}
/**
* SHA224加密
*
* @param data 明文字节数组
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA224ToString(data: ByteArray?): String {
return bytes2HexString(encryptSHA224(data))
}
/**
* SHA224加密
*
* @param data 明文字节数组
* @return 密文字节数组
*/
@JvmStatic
fun encryptSHA224(data: ByteArray?): ByteArray {
return encryptAlgorithm(data, "SHA-224")
}
/**
* SHA256加密
*
* @param data 明文字符串
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA256ToString(data: String): String {
return encryptSHA256ToString(data.toByteArray())
}
/**
* SHA256加密
*
* @param data 明文字节数组
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA256ToString(data: ByteArray?): String {
return bytes2HexString(encryptSHA256(data))
}
/**
* SHA256加密
*
* @param data 明文字节数组
* @return 密文字节数组
*/
@JvmStatic
fun encryptSHA256(data: ByteArray?): ByteArray {
return encryptAlgorithm(data, "SHA-256")
}
/**
* SHA384加密
*
* @param data 明文字符串
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA384ToString(data: String): String {
return encryptSHA384ToString(data.toByteArray())
}
/************************ DES加密相关 */
/**
* SHA384加密
*
* @param data 明文字节数组
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA384ToString(data: ByteArray?): String {
return bytes2HexString(encryptSHA384(data))
}
/**
* SHA384加密
*
* @param data 明文字节数组
* @return 密文字节数组
*/
@JvmStatic
fun encryptSHA384(data: ByteArray?): ByteArray {
return encryptAlgorithm(data, "SHA-384")
}
/**
* SHA512加密
*
* @param data 明文字符串
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA512ToString(data: String): String {
return encryptSHA512ToString(data.toByteArray())
}
/**
* SHA512加密
*
* @param data 明文字节数组
* @return 16进制密文
*/
@JvmStatic
fun encryptSHA512ToString(data: ByteArray?): String {
return bytes2HexString(encryptSHA512(data))
}
/**
* SHA512加密
*
* @param data 明文字节数组
* @return 密文字节数组
*/
@JvmStatic
fun encryptSHA512(data: ByteArray?): ByteArray {
return encryptAlgorithm(data, "SHA-512")
}
/**
* 对data进行algorithm算法加密
*
* @param data 明文字节数组
* @param algorithm 加密算法
* @return 密文字节数组
*/
private fun encryptAlgorithm(data: ByteArray?, algorithm: String): ByteArray {
try {
val md = MessageDigest.getInstance(algorithm)
md.update(data)
return md.digest()
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
}
return ByteArray(0)
}
/**
* @param data 数据
* @param key 秘钥
* @param algorithm 采用何种DES算法
* @param transformation 转变
* @param isEncrypt 是否加密
* @return 密文或者明文,适用于DES,3DES,AES
*/
@JvmStatic
fun DESTemplet(data: ByteArray?, key: ByteArray?, algorithm: String?, transformation: String?, isEncrypt: Boolean): ByteArray? {
try {
val keySpec = SecretKeySpec(key, algorithm)
val cipher = Cipher.getInstance(transformation)
val random = SecureRandom()
cipher.init(if (isEncrypt) Cipher.ENCRYPT_MODE else Cipher.DECRYPT_MODE, keySpec, random)
return cipher.doFinal(data)
} catch (e: Throwable) {
e.printStackTrace()
}
return null
}
/**
* DES加密后转为Base64编码
*
* @param data 明文
* @param key 8字节秘钥
* @return Base64密文
*/
@JvmStatic
fun encryptDES2Base64(data: ByteArray?, key: ByteArray?): ByteArray {
return base64Encode(encryptDES(data, key))
}
/**
* DES加密后转为16进制
*
* @param data 明文
* @param key 8字节秘钥
* @return 16进制密文
*/
@JvmStatic
fun encryptDES2HexString(data: ByteArray?, key: ByteArray?): String {
return bytes2HexString(encryptDES(data, key)!!)
}
/************************ 3DES加密相关 */
/**
* DES加密
*
* @param data 明文
* @param key 8字节秘钥
* @return 密文
*/
@JvmStatic
fun encryptDES(data: ByteArray?, key: ByteArray?): ByteArray? {
return DESTemplet(data, key, DES_Algorithm, DES_Transformation, true)
}
/**
* DES解密Base64编码密文
*
* @param data Base64编码密文
* @param key 8字节秘钥
* @return 明文
*/
@JvmStatic
fun decryptBase64DES(data: ByteArray?, key: ByteArray?): ByteArray? {
return decryptDES(base64Decode(data), key)
}
/**
* DES解密16进制密文
*
* @param data 16进制密文
* @param key 8字节秘钥
* @return 明文
*/
@JvmStatic
fun decryptHexStringDES(data: String?, key: ByteArray?): ByteArray? {
return decryptDES(hexString2Bytes(data!!), key)
}
/**
* DES解密
*
* @param data 密文
* @param key 8字节秘钥
* @return 明文
*/
@JvmStatic
fun decryptDES(data: ByteArray?, key: ByteArray?): ByteArray? {
return DESTemplet(data, key, DES_Algorithm, DES_Transformation, false)
}
/**
* 3DES加密后转为Base64编码
*
* @param data 明文
* @param key 24字节秘钥
* @return Base64密文
*/
@JvmStatic
fun encrypt3DES2Base64(data: ByteArray?, key: ByteArray?): ByteArray {
return base64Encode(encrypt3DES(data, key))
}
/**
* 3DES加密后转为16进制
*
* @param data 明文
* @param key 24字节秘钥
* @return 16进制密文
*/
@JvmStatic
fun encrypt3DES2HexString(data: ByteArray?, key: ByteArray?): String {
return bytes2HexString(encrypt3DES(data, key)!!)
}
/**
* 3DES加密
*
* @param data 明文
* @param key 24字节密钥
* @return 密文
*/
@JvmStatic
fun encrypt3DES(data: ByteArray?, key: ByteArray?): ByteArray? {
return DESTemplet(data, key, TripleDES_Algorithm, TripleDES_Transformation, true)
}
/**
* 3DES解密Base64编码密文
*
* @param data Base64编码密文
* @param key 24字节秘钥
* @return 明文
*/
@JvmStatic
fun decryptBase64_3DES(data: ByteArray?, key: ByteArray?): ByteArray? {
return decrypt3DES(base64Decode(data), key)
}
/************************ AES加密相关 */
/**
* 3DES解密16进制密文
*
* @param data 16进制密文
* @param key 24字节秘钥
* @return 明文
*/
@JvmStatic
fun decryptHexString3DES(data: String?, key: ByteArray?): ByteArray? {
return decrypt3DES(hexString2Bytes(data!!), key)
}
/**
* 3DES解密
*
* @param data 密文
* @param key 24字节密钥
* @return 明文
*/
@JvmStatic
fun decrypt3DES(data: ByteArray?, key: ByteArray?): ByteArray? {
return DESTemplet(data, key, TripleDES_Algorithm, TripleDES_Transformation, false)
}
/**
* AES加密后转为Base64编码
*
* @param data 明文
* @param key 16、24、32字节秘钥
* @return Base64密文
*/
@JvmStatic
fun encryptAES2Base64(data: ByteArray?, key: ByteArray?): ByteArray {
return base64Encode(encryptAES(data, key))
}
/**
* AES加密后转为16进制
*
* @param data 明文
* @param key 16、24、32字节秘钥
* @return 16进制密文
*/
@JvmStatic
fun encryptAES2HexString(data: ByteArray?, key: ByteArray?): String {
return bytes2HexString(encryptAES(data, key)!!)
}
/**
* AES加密
*
* @param data 明文
* @param key 16、24、32字节秘钥
* @return 密文
*/
@JvmStatic
fun encryptAES(data: ByteArray?, key: ByteArray?): ByteArray? {
return DESTemplet(data, key, AES_Algorithm, AES_Transformation, true)
}
/**
* AES解密Base64编码密文
*
* @param data Base64编码密文
* @param key 16、24、32字节秘钥
* @return 明文
*/
@JvmStatic
fun decryptBase64AES(data: ByteArray?, key: ByteArray?): ByteArray? {
return decryptAES(base64Decode(data), key)
}
/**
* AES解密16进制密文
*
* @param data 16进制密文
* @param key 16、24、32字节秘钥
* @return 明文
*/
@JvmStatic
fun decryptHexStringAES(data: String?, key: ByteArray?): ByteArray? {
return decryptAES(hexString2Bytes(data!!), key)
}
/**
* AES解密
*
* @param data 密文
* @param key 16、24、32字节秘钥
* @return 明文
*/
@JvmStatic
fun decryptAES(data: ByteArray?, key: ByteArray?): ByteArray? {
return DESTemplet(data, key, AES_Algorithm, AES_Transformation, false)
}
}
|
apache-2.0
|
f41c2260ee4cda2e18db006c71a67ca2
| 21.656151 | 132 | 0.572443 | 3.481939 | false | false | false | false |
panpf/sketch
|
sketch-svg/src/main/java/com/github/panpf/sketch/request/SvgExtensions.kt
|
1
|
3104
|
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.request
import androidx.annotation.ColorInt
private const val SVG_BACKGROUND_COLOR_KEY = "sketch#svg_background_color"
private const val SVG_CSS_KEY = "sketch#svg_css"
/**
* Set the background color of the SVG image, the default is transparent
*/
fun ImageRequest.Builder.svgBackgroundColor(@ColorInt color: Int): ImageRequest.Builder = apply {
setParameter(SVG_BACKGROUND_COLOR_KEY, color)
}
/**
* Set the background color of the SVG image, the default is transparent
*/
fun DisplayRequest.Builder.svgBackgroundColor(@ColorInt color: Int): DisplayRequest.Builder =
apply {
setParameter(SVG_BACKGROUND_COLOR_KEY, color)
}
/**
* Set the background color of the SVG image, the default is transparent
*/
fun LoadRequest.Builder.svgBackgroundColor(@ColorInt color: Int): LoadRequest.Builder = apply {
setParameter(SVG_BACKGROUND_COLOR_KEY, color)
}
/**
* Get the background color of the SVG image
*/
val ImageRequest.svgBackgroundColor: Int?
get() = parameters?.value<Int>(SVG_BACKGROUND_COLOR_KEY)
/**
* Set the background color of the SVG image, the default is transparent
*/
fun ImageOptions.Builder.svgBackgroundColor(@ColorInt color: Int) = apply {
setParameter(SVG_BACKGROUND_COLOR_KEY, color)
}
/**
* Get the background color of the SVG image
*/
val ImageOptions.svgBackgroundColor: Int?
get() = parameters?.value<Int>(SVG_BACKGROUND_COLOR_KEY)
/**
* Set the background color of the SVG image, the default is transparent
*/
fun ImageRequest.Builder.svgCss(css: String): ImageRequest.Builder = apply {
setParameter(SVG_CSS_KEY, css)
}
/**
* Set the background color of the SVG image, the default is transparent
*/
fun DisplayRequest.Builder.svgCss(css: String): DisplayRequest.Builder =
apply {
setParameter(SVG_CSS_KEY, css)
}
/**
* Set the background color of the SVG image, the default is transparent
*/
fun LoadRequest.Builder.svgCss(css: String): LoadRequest.Builder = apply {
setParameter(SVG_CSS_KEY, css)
}
/**
* Get the background color of the SVG image
*/
val ImageRequest.svgCss: String?
get() = parameters?.value<String>(SVG_CSS_KEY)
/**
* Set the background color of the SVG image, the default is transparent
*/
fun ImageOptions.Builder.svgCss(css: String) = apply {
setParameter(SVG_CSS_KEY, css)
}
/**
* Get the background color of the SVG image
*/
val ImageOptions.svgCss: String?
get() = parameters?.value<String>(SVG_CSS_KEY)
|
apache-2.0
|
5bbfc229311e49f8f1dbbec914c9cbde
| 28.855769 | 97 | 0.729059 | 3.904403 | false | false | false | false |
Popalay/Cardme
|
presentation/src/main/kotlin/com/popalay/cardme/utils/recycler/DiffObservableList.kt
|
1
|
3941
|
package com.popalay.cardme.utils.recycler
import android.databinding.ListChangeRegistry
import android.databinding.ObservableList
import android.support.annotation.MainThread
import android.support.v7.util.DiffUtil
import android.support.v7.util.ListUpdateCallback
import com.popalay.cardme.data.models.StableId
import java.util.*
import kotlin.collections.ArrayList
class DiffObservableList<T : StableId> @JvmOverloads constructor(
private val callback: Callback<T> = StableIdDiffListCallback<T>(),
private val detectMoves: Boolean = true
) : AbstractList<T>(), ObservableList<T> {
private val LIST_LOCK = Any()
private var list = mutableListOf<T>()
private val listeners = ListChangeRegistry()
private val listCallback = ObservableListUpdateCallback()
override val size: Int
get() = list.size
fun calculateDiff(newItems: List<T>): DiffUtil.DiffResult {
var frozenList: ArrayList<T> = arrayListOf()
synchronized(LIST_LOCK) {
frozenList = ArrayList(list)
}
return doCalculateDiff(frozenList, newItems)
}
@MainThread fun update(newItems: List<T>, diffResult: DiffUtil.DiffResult) {
synchronized(LIST_LOCK) {
list = newItems.toMutableList()
}
diffResult.dispatchUpdatesTo(listCallback)
}
@MainThread fun update(newItems: List<T>) {
val diffResult = doCalculateDiff(list, newItems)
list = newItems.toMutableList()
diffResult.dispatchUpdatesTo(listCallback)
}
override fun addOnListChangedCallback(listener: ObservableList.OnListChangedCallback<out ObservableList<T>>) {
listeners.add(listener)
}
override fun removeOnListChangedCallback(listener: ObservableList.OnListChangedCallback<out ObservableList<T>>) {
listeners.remove(listener)
}
override fun get(index: Int): T {
return list[index]
}
override fun set(index: Int, element: T): T {
list[index] = element
return element
}
private fun doCalculateDiff(oldItems: List<T>, newItems: List<T>): DiffUtil.DiffResult {
return DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldItems.size
}
override fun getNewListSize(): Int {
return newItems.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldItems[oldItemPosition]
val newItem = newItems[newItemPosition]
return callback.areItemsTheSame(oldItem, newItem)
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldItems[oldItemPosition]
val newItem = newItems[newItemPosition]
return callback.areContentsTheSame(oldItem, newItem)
}
}, detectMoves)
}
interface Callback<in T> {
fun areItemsTheSame(oldItem: T, newItem: T): Boolean
fun areContentsTheSame(oldItem: T, newItem: T): Boolean
}
internal inner class ObservableListUpdateCallback : ListUpdateCallback {
override fun onChanged(position: Int, count: Int, payload: Any?) {
listeners.notifyChanged(this@DiffObservableList, position, count)
}
override fun onInserted(position: Int, count: Int) {
modCount += 1
listeners.notifyInserted(this@DiffObservableList, position, count)
}
override fun onRemoved(position: Int, count: Int) {
modCount += 1
listeners.notifyRemoved(this@DiffObservableList, position, count)
}
override fun onMoved(fromPosition: Int, toPosition: Int) {
listeners.notifyMoved(this@DiffObservableList, fromPosition, toPosition, 1)
}
}
}
|
apache-2.0
|
205a9a696a3ccc4803691b1646d48600
| 33.578947 | 117 | 0.662776 | 5.039642 | false | false | false | false |
deeplearning4j/deeplearning4j
|
nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowStringEqualsAdapterRule.kt
|
1
|
5094
|
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.argDescriptorType
import org.nd4j.samediff.frameworkimport.findOp
import org.nd4j.samediff.frameworkimport.ir.IRAttribute
import org.nd4j.samediff.frameworkimport.isNd4jTensorName
import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.process.MappingProcess
import org.nd4j.samediff.frameworkimport.rule.MappingRule
import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType
import org.nd4j.samediff.frameworkimport.rule.attribute.StringEqualsAdapterRule
import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor
import org.tensorflow.framework.*
@MappingRule("tensorflow","stringequals","attribute")
class TensorflowStringEqualsAdapterRule(mappingNamesToPerform: Map<String, String> = emptyMap(),
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>> = emptyMap()) :
StringEqualsAdapterRule<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>
( mappingNamesToPerform, transformerArgs) {
override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> {
return TensorflowIRAttr(attrDef, attributeValueType)
}
override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> {
TODO("Not yet implemented")
}
override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowTensorName(name, opDef)
}
override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isNd4jTensorName(name,nd4jOpDescriptor)
}
override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowAttributeName(name, opDef)
}
override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isOutputFrameworkAttributeName(name,nd4jOpDescriptor)
}
override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return argDescriptorType(name,nd4jOpDescriptor)
}
override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef)
}
}
|
apache-2.0
|
b970f13c7e29bfd788613d37a725dfc6
| 58.941176 | 221 | 0.762073 | 5.01378 | false | false | false | false |
AndroidX/androidx
|
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/focus/FocusTargetAttachDetachTest.kt
|
3
|
24095
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.focus
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
class FocusTargetAttachDetachTest {
@get:Rule
val rule = createComposeRule()
@Test
fun reorderedFocusRequesterModifiers_onFocusChangedInSameModifierChain() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var observingFocusTarget1 by mutableStateOf(true)
rule.setFocusableContent {
val focusRequesterModifier = Modifier.focusRequester(focusRequester)
val onFocusChanged = Modifier.onFocusChanged { focusState = it }
val focusTarget1 = Modifier.focusTarget()
val focusTarget2 = Modifier.focusTarget()
Box {
Box(
modifier = if (observingFocusTarget1) {
onFocusChanged
.then(focusRequesterModifier)
.then(focusTarget1)
.then(focusTarget2)
} else {
focusTarget1
.then(onFocusChanged)
.then(focusRequesterModifier)
.then(focusTarget2)
}
)
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.isFocused).isTrue()
}
// Act.
rule.runOnIdle { observingFocusTarget1 = false }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isFalse() }
}
@Test
fun removedModifier_onFocusChangedDoesNotHaveAFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var onFocusChangedHasFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
val focusRequesterModifier = Modifier.focusRequester(focusRequester)
val onFocusChanged = Modifier.onFocusChanged { focusState = it }
val focusTarget = Modifier.focusTarget()
Box {
Box(
modifier = if (onFocusChangedHasFocusTarget) {
onFocusChanged
.then(focusRequesterModifier)
.then(focusTarget)
} else {
focusTarget
.then(onFocusChanged)
.then(focusRequesterModifier)
}
)
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.isFocused).isTrue()
}
// Act.
rule.runOnIdle { onFocusChangedHasFocusTarget = false }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isFalse() }
}
@Test
fun removedFocusTarget_withNoNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier.onFocusChanged { focusState = it }
.focusRequester(focusRequester)
.then(if (optionalFocusTarget) Modifier.focusTarget() else Modifier)
)
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.isFocused).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isFalse() }
}
@Test
fun removedActiveFocusTarget_pointsToNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier.onFocusChanged { focusState = it }
.focusRequester(focusRequester)
.then(if (optionalFocusTarget) Modifier.focusTarget() else Modifier)
) {
Box(modifier = Modifier.focusTarget())
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.isFocused).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isFalse() }
}
@Test
fun removedCapturedFocusTarget_pointsToNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier.onFocusChanged { focusState = it }
.focusRequester(focusRequester)
.then(if (optionalFocusTarget) Modifier.focusTarget() else Modifier)
) {
Box(modifier = Modifier.focusTarget())
}
}
rule.runOnIdle {
focusRequester.requestFocus()
focusRequester.captureFocus()
assertThat(focusState.isCaptured).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isFalse() }
}
@Test
fun removedActiveParentFocusTarget_pointsToNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.then(if (optionalFocusTarget) Modifier.focusTarget() else Modifier)
) {
Box(modifier = Modifier
.focusRequester(focusRequester)
.focusTarget()
)
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.hasFocus).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isTrue() }
}
@Test
fun removedActiveParentFocusTarget_withNoNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier.onFocusChanged { focusState = it }
.then(
if (optionalFocusTarget) {
Modifier
.focusTarget()
.focusRequester(focusRequester)
.focusTarget()
} else {
Modifier
}
)
)
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.hasFocus).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isFalse() }
}
@Test
fun removedActiveParentFocusTargetAndFocusedChild_clearsFocusFromAllParents() {
// Arrange.
lateinit var focusState: FocusState
lateinit var parentFocusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTargets by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { parentFocusState = it }
.focusTarget()
) {
Box(
modifier = Modifier.onFocusChanged { focusState = it }.then(
if (optionalFocusTargets) {
Modifier.focusTarget()
.focusRequester(focusRequester)
.focusTarget()
} else {
Modifier
}
)
)
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.hasFocus).isTrue()
assertThat(parentFocusState.hasFocus).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTargets = false }
// Assert.
rule.runOnIdle {
assertThat(focusState.isFocused).isFalse()
assertThat(parentFocusState.isFocused).isFalse()
}
}
@Test
fun removedDeactivatedParentFocusTarget_pointsToNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.then(
if (optionalFocusTarget)
Modifier
.focusProperties { canFocus = false }
.focusTarget()
else
Modifier
)
) {
Box(modifier = Modifier
.focusRequester(focusRequester)
.focusTarget()
)
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.hasFocus).isTrue()
assertThat(focusState.isDeactivated).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle {
assertThat(focusState.isFocused).isTrue()
assertThat(focusState.isDeactivated).isFalse()
}
}
@Test
fun removedDeactivatedParentFocusTarget_pointsToNextDeactivatedParentFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.then(
if (optionalFocusTarget)
Modifier
.focusProperties { canFocus = false }
.focusTarget()
else
Modifier
)
) {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.focusProperties { canFocus = false }
.focusTarget()
) {
Box(
modifier = Modifier
.focusRequester(focusRequester)
.focusTarget()
)
}
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.hasFocus).isTrue()
assertThat(focusState.isDeactivated).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle {
assertThat(focusState.isFocused).isFalse()
assertThat(focusState.hasFocus).isTrue()
assertThat(focusState.isDeactivated).isTrue()
}
}
@Test
fun removedDeactivatedParent_parentsFocusTarget_isUnchanged() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.focusProperties { canFocus = false }
.focusTarget()
) {
Box(
modifier = Modifier.then(
if (optionalFocusTarget)
Modifier
.focusProperties { canFocus = false }
.focusTarget()
else
Modifier
)
) {
Box(
modifier = Modifier
.focusRequester(focusRequester)
.focusTarget()
)
}
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.isFocused).isFalse()
assertThat(focusState.hasFocus).isTrue()
assertThat(focusState.isDeactivated).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle {
assertThat(focusState.isFocused).isFalse()
assertThat(focusState.hasFocus).isTrue()
assertThat(focusState.isDeactivated).isTrue()
}
}
@Test
fun removedDeactivatedParentAndActiveChild_grandparent_retainsDeactivatedState() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.focusProperties { canFocus = false }
.focusTarget()
) {
Box(
modifier = Modifier
.then(
if (optionalFocusTarget)
Modifier
.focusProperties { canFocus = false }
.focusTarget()
else
Modifier
)
) {
Box(
modifier = Modifier
.focusRequester(focusRequester)
.then(
if (optionalFocusTarget)
Modifier.focusTarget()
else
Modifier
)
)
}
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.hasFocus).isTrue()
assertThat(focusState.isDeactivated).isTrue()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle {
assertThat(focusState.isFocused).isFalse()
assertThat(focusState.hasFocus).isFalse()
assertThat(focusState.isDeactivated).isTrue()
}
}
@Test
fun removedNonDeactivatedParentAndActiveChild_grandParent_retainsNonDeactivatedState() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.focusTarget()
) {
Box(
modifier = Modifier.then(
if (optionalFocusTarget)
Modifier
.focusProperties { canFocus = false }
.focusTarget()
else
Modifier
)
) {
Box(
modifier = Modifier
.focusRequester(focusRequester)
.then(
if (optionalFocusTarget)
Modifier.focusTarget()
else
Modifier
)
)
}
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.hasFocus).isTrue()
assertThat(focusState.isDeactivated).isFalse()
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle {
assertThat(focusState.isFocused).isFalse()
assertThat(focusState.hasFocus).isFalse()
assertThat(focusState.isDeactivated).isFalse()
}
}
@Test
fun removedInactiveFocusTarget_pointsToNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var optionalFocusTarget by mutableStateOf(true)
rule.setFocusableContent {
Box(
modifier = Modifier.onFocusChanged { focusState = it }
.then(if (optionalFocusTarget) Modifier.focusTarget() else Modifier)
.focusRequester(focusRequester)
.focusTarget()
)
}
// Act.
rule.runOnIdle { optionalFocusTarget = false }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isFalse() }
}
@Test
fun addedFocusTarget_pointsToTheFocusTargetJustAdded() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var addFocusTarget by mutableStateOf(false)
rule.setFocusableContent {
Box(
modifier = Modifier.onFocusChanged { focusState = it }
.focusRequester(focusRequester)
.then(if (addFocusTarget) Modifier.focusTarget() else Modifier)
) {
Box(modifier = Modifier.focusTarget())
}
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.isFocused).isTrue()
}
// Act.
rule.runOnIdle { addFocusTarget = true }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isFalse() }
}
@Test
fun addedFocusTarget_withNoNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
var addFocusTarget by mutableStateOf(false)
rule.setFocusableContent {
Box(
modifier = Modifier.onFocusChanged { focusState = it }
.focusRequester(focusRequester)
.then(if (addFocusTarget) Modifier.focusTarget() else Modifier)
)
}
rule.runOnIdle {
focusRequester.requestFocus()
assertThat(focusState.isFocused).isFalse()
}
// Act.
rule.runOnIdle { addFocusTarget = true }
// Assert.
rule.runOnIdle { assertThat(focusState.isFocused).isFalse() }
}
@Test
fun removingDeactivatedItem_withNoNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
var removeDeactivatedItem by mutableStateOf(false)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.then(
if (removeDeactivatedItem)
Modifier
else
Modifier
.focusProperties { canFocus = false }
.focusTarget()
)
)
}
// Act.
rule.runOnIdle { removeDeactivatedItem = true }
// Assert.
rule.runOnIdle {
assertThat(focusState.isFocused).isFalse()
assertThat(focusState.isDeactivated).isFalse()
}
}
@Test
fun removingDeactivatedItem_withInactiveNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
var removeDeactivatedItem by mutableStateOf(false)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.then(
if (removeDeactivatedItem)
Modifier
else
Modifier
.focusProperties { canFocus = false }
.focusTarget()
)
) {
Box(modifier = Modifier.focusTarget())
}
}
// Act.
rule.runOnIdle { removeDeactivatedItem = true }
// Assert.
rule.runOnIdle {
assertThat(focusState.isFocused).isFalse()
assertThat(focusState.isDeactivated).isFalse()
}
}
@Test
fun removingDeactivatedItem_withDeactivatedNextFocusTarget() {
// Arrange.
lateinit var focusState: FocusState
var removeDeactivatedItem by mutableStateOf(false)
rule.setFocusableContent {
Box(
modifier = Modifier
.onFocusChanged { focusState = it }
.then(
if (removeDeactivatedItem)
Modifier
else
Modifier
.focusProperties { canFocus = false }
.focusTarget()
)
) {
Box(modifier = Modifier
.focusProperties { canFocus = false }
.focusTarget()
)
}
}
// Act.
rule.runOnIdle { removeDeactivatedItem = true }
// Assert.
rule.runOnIdle {
assertThat(focusState.isFocused).isFalse()
assertThat(focusState.isDeactivated).isTrue()
}
}
}
private val FocusState.isDeactivated: Boolean
get() = (this as FocusStateImpl).isDeactivated
|
apache-2.0
|
f51eb79e59cb18d5b5817e68f53b98f9
| 32.6053 | 92 | 0.507657 | 6.384473 | false | false | false | false |
exponent/exponent
|
packages/expo-splash-screen/android/src/main/java/expo/modules/splashscreen/SplashScreenModule.kt
|
2
|
1920
|
package expo.modules.splashscreen
import android.content.Context
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.Promise
import expo.modules.core.errors.CurrentActivityNotFoundException
import expo.modules.core.interfaces.ActivityProvider
import expo.modules.core.interfaces.ExpoMethod
// Below import must be kept unversioned even in versioned code to provide a redirection from
// versioned code realm to unversioned code realm.
// Without this import any `SplashScreen.anyMethodName(...)` invocation on JS side ends up
// in versioned SplashScreen kotlin object that stores no information about the ExperienceActivity.
import expo.modules.splashscreen.singletons.SplashScreen
class SplashScreenModule(context: Context) : ExportedModule(context) {
companion object {
private const val NAME = "ExpoSplashScreen"
private const val ERROR_TAG = "ERR_SPLASH_SCREEN"
}
private lateinit var activityProvider: ActivityProvider
override fun getName(): String {
return NAME
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
activityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
}
@ExpoMethod
fun preventAutoHideAsync(promise: Promise) {
val activity = activityProvider.currentActivity
if (activity == null) {
promise.reject(CurrentActivityNotFoundException())
return
}
SplashScreen.preventAutoHide(
activity,
{ hasEffect -> promise.resolve(hasEffect) },
{ m -> promise.reject(ERROR_TAG, m) }
)
}
@ExpoMethod
fun hideAsync(promise: Promise) {
val activity = activityProvider.currentActivity
if (activity == null) {
promise.reject(CurrentActivityNotFoundException())
return
}
SplashScreen.hide(
activity,
{ hasEffect -> promise.resolve(hasEffect) },
{ m -> promise.reject(ERROR_TAG, m) }
)
}
}
|
bsd-3-clause
|
31b29b8d4292905915b726fa4c2def15
| 30.47541 | 99 | 0.744271 | 4.752475 | false | false | false | false |
MeilCli/Twitter4HK
|
library/src/androidTest/kotlin/com/twitter/meil_mitu/twitter4hk/api/users/ShowTest.kt
|
1
|
846
|
package com.twitter.meil_mitu.twitter4hk.api.users
import com.twitter.meil_mitu.twitter4hk.testTargetUserScreenName
import com.twitter.meil_mitu.twitter4hk.twitter
import com.twitter.meil_mitu.twitter4hk.twitter2
import junit.framework.TestCase
class ShowTest : TestCase(){
@Throws(Exception::class)
fun testShow(){
val show =twitter.users.show(testTargetUserScreenName).apply {
this.includeEntities=true
}
val result = show.call()
assertEquals(result.response.screenName,testTargetUserScreenName)
}
@Throws(Exception::class)
fun testShow2(){
val show =twitter2.users.show(testTargetUserScreenName).apply {
this.includeEntities=true
}
val result = show.call()
assertEquals(result.response.screenName,testTargetUserScreenName)
}
}
|
mit
|
37b6651498f681b5db6e6ee926f1dbae
| 29.25 | 73 | 0.710402 | 4.126829 | false | true | false | false |
pistatium/mahougen
|
app/src/main/kotlin/com/appspot/pistatium/mahougen/views/MahouCanvasView.kt
|
1
|
3348
|
package com.appspot.pistatium.mahougen.views
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.appspot.pistatium.mahougen.R
import com.appspot.pistatium.mahougen.utils.Vector
/**
* Created by kimihiro on 16/03/25.
*/
class MahouCanvasView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private var vertexCount = 10
private var center: Vector = Vector(0.0, 0.0)
private var paint: Paint = Paint()
var pathArray: Array<Path>
init {
this.setBackgroundColor(ContextCompat.getColor(context, R.color.background))
this.pathArray = Array(this.vertexCount, { i -> Path()})
this.paint.color = Color.WHITE
this.paint.style = Paint.Style.STROKE
this.paint.isAntiAlias = true
this.paint.strokeWidth = 3f
}
override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
super.onWindowFocusChanged(hasWindowFocus)
this.center = Vector(width / 2.0, height / 2.0)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
pathArray.forEach { p ->
canvas.drawPath(p, paint)
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val current = Vector(event.x.toDouble(), event.y.toDouble())
val direction = current - this.center
val r = direction.size()
val alpha = (2.0 * Math.PI / this.vertexCount.toDouble())
var theta = direction.angle()
for (i in 0 .. this.vertexCount) {
if (i * alpha > theta) {
theta -= (i - 1) * alpha
break
}
}
when (event.action) {
MotionEvent.ACTION_DOWN -> {
for ((i, p) in this.pathArray.withIndex()) {
var target = this.center + Vector.ofAngle(theta + i * alpha) * r
if (vertexCount % 2 == 0 && i % 2 == 0) {
target = this.center + Vector.ofAngle(-theta + (i + 1) * alpha) * r
}
p.moveTo(target)
}
}
MotionEvent.ACTION_MOVE,
MotionEvent.ACTION_UP -> {
for ((i, p) in this.pathArray.withIndex()) {
var target = this.center + Vector.ofAngle(theta + i * alpha) * r
if (vertexCount % 2 == 0 &&i % 2 == 0) {
target = this.center + Vector.ofAngle(-theta + (i + 1) * alpha) * r
}
p.lineTo(target)
}
}
}
invalidate()
return true
}
fun configure(vertexCount: Int, paint: Paint? = null) {
this.vertexCount = vertexCount
pathArray = Array(this.vertexCount, { i -> Path()})
paint?.let {
this.paint = paint
}
invalidate()
}
fun clear() {
this.pathArray.forEach { p -> p.reset() }
invalidate()
}
}
fun Path.moveTo(v: Vector) {
this.moveTo(v.x.toFloat(), v.y.toFloat())
}
fun Path.lineTo(v: Vector) {
this.lineTo(v.x.toFloat(), v.y.toFloat())
}
|
apache-2.0
|
485b28825a1cf3d93a0dce2007607b63
| 30.009259 | 91 | 0.562724 | 4 | false | false | false | false |
google/ide-perf
|
src/main/java/com/google/idea/perf/tracer/ui/TracepointDetailsDialog.kt
|
1
|
1981
|
/*
* Copyright 2020 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.idea.perf.tracer.ui
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBTextArea
import com.intellij.util.ui.JBEmptyBorder
import java.awt.Component
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.text.DefaultCaret
/**
* A popup showing details for a specific tracepoint.
* Manged by [TracepointDetailsManager].
*/
class TracepointDetailsDialog(parent: Component, text: String) : DialogWrapper(parent, false) {
val textArea: JBTextArea
init {
title = "Tracepoint Details"
isModal = false
// Text area.
textArea = JBTextArea(text)
textArea.font = EditorUtil.getEditorFont()
textArea.isEditable = false
textArea.border = JBEmptyBorder(5)
val caret = textArea.caret
if (caret is DefaultCaret) {
// Disable caret movement so that changing the text does not affect scroll position.
caret.updatePolicy = DefaultCaret.NEVER_UPDATE
}
init()
}
override fun createCenterPanel(): JComponent = JBScrollPane(textArea)
override fun getDimensionServiceKey(): String = "${javaClass.packageName}.TracepointDetails"
override fun createActions(): Array<Action> = arrayOf(okAction)
}
|
apache-2.0
|
30ad630267ffd720d2e67455a357db1a
| 33.754386 | 96 | 0.725896 | 4.471783 | false | false | false | false |
andstatus/andstatus
|
app/src/main/kotlin/org/andstatus/app/graphics/ImageCaches.kt
|
1
|
7961
|
/*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.graphics
import android.app.ActivityManager
import android.content.Context
import android.graphics.Point
import android.view.WindowManager
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.context.MyTheme
import org.andstatus.app.data.AvatarFile
import org.andstatus.app.data.MediaFile
import org.andstatus.app.util.I18n
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.SharedPreferencesUtil
import org.andstatus.app.util.StopWatch
import java.util.concurrent.ConcurrentHashMap
/**
* @author [email protected]
*/
object ImageCaches {
private const val ATTACHED_IMAGES_CACHE_PART_OF_TOTAL_APP_MEMORY = 0.20f
const val ATTACHED_IMAGES_CACHE_SIZE_MIN = 10
const val ATTACHED_IMAGES_CACHE_SIZE_MAX = 20
private const val AVATARS_CACHE_PART_OF_TOTAL_APP_MEMORY = 0.05f
const val AVATARS_CACHE_SIZE_MIN = 200
const val AVATARS_CACHE_SIZE_MAX = 700
@Volatile
private var attachedImagesCache: ImageCache? = null
@Volatile
private var avatarsCache: ImageCache? = null
@Synchronized
fun initialize(context: Context) {
val stopWatch: StopWatch = StopWatch.createStarted()
styledImages.clear()
initializeAttachedImagesCache(context)
initializeAvatarsCache(context)
MyLog.i(ImageCaches::class, "imageCachesInitializedMs:" + stopWatch.time + "; " + getCacheInfo())
}
private fun initializeAttachedImagesCache(context: Context) {
// We assume that current display orientation is preferred, so we use "y" size only
var imageSize = Math.round(AttachedImageView.MAX_ATTACHED_IMAGE_PART *
getDisplaySize(context).y).toInt()
var cacheSize = 0
for (i in 0..4) {
cacheSize = calcCacheSize(context, imageSize,
ATTACHED_IMAGES_CACHE_PART_OF_TOTAL_APP_MEMORY)
if (cacheSize >= ATTACHED_IMAGES_CACHE_SIZE_MIN || imageSize < 2) {
break
}
imageSize = imageSize * 2 / 3
}
if (cacheSize > ATTACHED_IMAGES_CACHE_SIZE_MAX) {
cacheSize = ATTACHED_IMAGES_CACHE_SIZE_MAX
}
attachedImagesCache = ImageCache(context, CacheName.ATTACHED_IMAGE, imageSize,
cacheSize)
}
private fun initializeAvatarsCache(context: Context) {
val displayDensity = context.getResources().displayMetrics.density
var imageSize: Int = Math.round(AvatarFile.AVATAR_SIZE_DIP * displayDensity)
var cacheSize = 0
for (i in 0..4) {
cacheSize = calcCacheSize(context, imageSize, AVATARS_CACHE_PART_OF_TOTAL_APP_MEMORY)
if (cacheSize >= AVATARS_CACHE_SIZE_MIN || imageSize < 48) {
break
}
imageSize = imageSize * 2 / 3
}
if (cacheSize > AVATARS_CACHE_SIZE_MAX) {
cacheSize = AVATARS_CACHE_SIZE_MAX
}
avatarsCache = ImageCache(context, CacheName.AVATAR, imageSize, cacheSize)
setAvatarsRounded()
}
fun setAvatarsRounded() {
avatarsCache?.evictAll()
avatarsCache?.rounded = SharedPreferencesUtil.getBoolean(MyPreferences.KEY_ROUNDED_AVATARS, true)
}
private fun calcCacheSize(context: Context?, imageSize: Int, partOfAvailableMemory: Float): Int {
return Math.round(partOfAvailableMemory * getTotalAppMemory(context) / imageSize / imageSize / ImageCache.BYTES_PER_PIXEL)
}
private fun getTotalAppMemory(context: Context?): Long {
var memoryClass = 16
if (context != null) {
val actManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
memoryClass = actManager.memoryClass
}
return memoryClass * 1024L * 1024L
}
private fun getMemoryInfo(context: Context?): ActivityManager.MemoryInfo {
val memInfo = ActivityManager.MemoryInfo()
if (context != null) {
val actManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
actManager.getMemoryInfo(memInfo)
}
return memInfo
}
fun loadAndGetImage(cacheName: CacheName, mediaFile: MediaFile): CachedImage? {
return getCache(cacheName).loadAndGetImage(mediaFile)
}
fun getCachedImage(cacheName: CacheName, mediaFile: MediaFile): CachedImage? {
return getCache(cacheName).getCachedImage(mediaFile)
}
fun getCache(cacheName: CacheName): ImageCache {
return when (cacheName) {
CacheName.ATTACHED_IMAGE -> attachedImagesCache ?: throw IllegalStateException("No attached images cache")
else -> avatarsCache ?: throw IllegalStateException("No avatars cache")
}
}
fun getCacheInfo(): String {
val builder = StringBuilder("ImageCaches: ")
if (avatarsCache == null || attachedImagesCache == null) {
builder.append("not initialized")
} else {
builder.append(avatarsCache?.getInfo() + "; ")
builder.append(attachedImagesCache?.getInfo() + "; ")
builder.append("Styled images: " + styledImages.size + "; ")
}
val myContext = MyContextHolder.myContextHolder.getNow()
if (!myContext.isEmpty) {
val context: Context = myContext.context
builder.append("Memory. App total: " + I18n.formatBytes(getTotalAppMemory(context)))
val memInfo = getMemoryInfo(context)
builder.append("; Device: available " + I18n.formatBytes(memInfo.availMem) + " of "
+ I18n.formatBytes(memInfo.totalMem))
}
return builder.toString()
}
/**
* See http://stackoverflow.com/questions/1016896/how-to-get-screen-dimensions
*/
fun getDisplaySize(context: Context): Point {
val size = Point()
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
if (windowManager != null) {
val display = windowManager.defaultDisplay
display?.getSize(size)
}
if (size.x < 480 || size.y < 480) {
// This is needed for preview in Layout editor
size.x = 1280
size.y = 768
}
return size
}
fun getImageCompat(context: Context, resourceId: Int): CachedImage {
return CachedImage(resourceId.toLong(), context.getTheme().getDrawable(resourceId))
}
private val styledImages: MutableMap<Int, Array<CachedImage>> = ConcurrentHashMap()
fun getStyledImage(resourceIdLight: Int, resourceId: Int): CachedImage {
var styledImage = styledImages[resourceId]
if (styledImage == null) {
val myContext = MyContextHolder.myContextHolder.getNow()
if (!myContext.isEmpty) {
val context: Context = myContext.context
val image = getImageCompat(context, resourceId)
val imageLight = getImageCompat(context, resourceIdLight)
styledImage = arrayOf(image, imageLight)
styledImages[resourceId] = styledImage
} else {
return CachedImage.EMPTY
}
}
return styledImage[if (MyTheme.isThemeLight()) 1 else 0]
}
}
|
apache-2.0
|
b904c251998431e0430fc1b171e08af1
| 39.005025 | 130 | 0.658083 | 4.469961 | false | false | false | false |
teobaranga/T-Tasks
|
t-tasks/src/main/java/com/teo/ttasks/UserManager.kt
|
1
|
1946
|
package com.teo.ttasks
import android.content.Context
import android.content.Intent
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.Scopes
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.Scope
import com.google.android.gms.tasks.Task
import com.teo.ttasks.injection.SCOPE_TASKS
import io.reactivex.Completable
/**
* Manages users (sign in / out).
*
* @param context the application context
*/
@OpenClassOnDebug
class UserManager(private val context: Context) {
val signInIntent: Intent
get() = googleSignInClient.signInIntent
private val googleSignInClient by lazy {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(context.getString(R.string.default_web_client_id))
.requestScopes(Scope(SCOPE_TASKS), Scope(Scopes.PLUS_ME))
.build()
return@lazy GoogleSignIn.getClient(context, gso)
}
private var signedInUser: GoogleSignInAccount? = null
/**
* @throws ApiException if the user could not be extracted from the intent
*/
@Throws(ApiException::class)
fun getSignedInAccountFromIntent(intent: Intent?): GoogleSignInAccount {
val account = GoogleSignIn.getSignedInAccountFromIntent(intent).getResult(ApiException::class.java)!!
signedInUser = account
return account
}
fun signOut() = Completable.create { emitter ->
googleSignInClient.signOut()
.addOnCompleteListener { task: Task<Void> ->
if (task.isSuccessful) {
emitter.onComplete()
} else {
emitter.onError(task.exception!!)
}
}
}
}
|
apache-2.0
|
afb9b509816add193d3010884b2cac31
| 32.551724 | 109 | 0.68962 | 4.536131 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/lang-xqdoc/main/uk/co/reecedunn/intellij/plugin/xqdoc/documentation/settings/XQDocDocumentationSourcesTable.kt
|
1
|
2175
|
/*
* Copyright (C) 2019-2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xqdoc.documentation.settings
import com.intellij.util.ui.ColumnInfo
import uk.co.reecedunn.intellij.plugin.core.ui.layout.columnInfo
import uk.co.reecedunn.intellij.plugin.xpm.lang.documentation.XpmDocumentationSource
import uk.co.reecedunn.intellij.plugin.xqdoc.documentation.XQDocDocumentationDownloader
import uk.co.reecedunn.intellij.plugin.xqdoc.resources.XQDocBundle
import javax.swing.table.DefaultTableCellRenderer
fun ArrayList<ColumnInfo<XpmDocumentationSource, *>>.nameColumn() {
val column = columnInfo<XpmDocumentationSource, String>(
heading = XQDocBundle.message("documentation-source-table.column.name.title"),
getter = { item -> item.presentation.presentableText!! },
renderer = { value ->
val renderer = DefaultTableCellRenderer()
renderer.icon = value.presentation.getIcon(false)
renderer
}
)
add(column)
}
fun ArrayList<ColumnInfo<XpmDocumentationSource, *>>.versionColumn() {
val column = columnInfo<XpmDocumentationSource, String>(
heading = XQDocBundle.message("documentation-source-table.column.version.title"),
getter = { item -> item.version }
)
add(column)
}
fun ArrayList<ColumnInfo<XpmDocumentationSource, *>>.statusColumn() {
val column = columnInfo<XpmDocumentationSource, String>(
heading = XQDocBundle.message("documentation-source-table.column.status.title"),
getter = { item -> XQDocDocumentationDownloader.getInstance().status(item).label }
)
add(column)
}
|
apache-2.0
|
fda638037b6eeda6d7d213c08822eaf9
| 40.826923 | 90 | 0.737471 | 4.231518 | false | false | false | false |
apollostack/apollo-android
|
apollo-runtime/src/main/java/com/apollographql/apollo3/interceptor/ApolloAutoPersistedOperationInterceptor.kt
|
1
|
4815
|
package com.apollographql.apollo3.interceptor
import com.apollographql.apollo3.api.Error
import com.apollographql.apollo3.api.Mutation
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.Query
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.internal.ApolloLogger
import com.apollographql.apollo3.api.internal.Function
import com.apollographql.apollo3.api.internal.Optional
import com.apollographql.apollo3.exception.ApolloException
import com.apollographql.apollo3.interceptor.ApolloInterceptor.CallBack
import com.apollographql.apollo3.interceptor.ApolloInterceptor.FetchSourceType
import com.apollographql.apollo3.interceptor.ApolloInterceptor.InterceptorRequest
import com.apollographql.apollo3.interceptor.ApolloInterceptor.InterceptorResponse
import java.util.concurrent.Executor
class ApolloAutoPersistedOperationInterceptor(private val logger: ApolloLogger,
val useHttpGetMethodForPersistedOperations: Boolean) : ApolloInterceptor {
@Volatile
private var disposed = false
override fun interceptAsync(request: InterceptorRequest, chain: ApolloInterceptorChain,
dispatcher: Executor, callBack: CallBack) {
val newRequest = request.toBuilder()
.sendQueryDocument(false)
.autoPersistQueries(true)
.useHttpGetMethodForQueries(request.useHttpGetMethodForQueries || useHttpGetMethodForPersistedOperations)
.build()
chain.proceedAsync(newRequest, dispatcher, object : CallBack {
override fun onResponse(response: InterceptorResponse) {
if (disposed) return
val retryRequest = handleProtocolNegotiation(request, response)
if (retryRequest.isPresent) {
chain.proceedAsync(retryRequest.get(), dispatcher, callBack)
} else {
callBack.onResponse(response)
callBack.onCompleted()
}
}
override fun onFetch(sourceType: FetchSourceType) {
callBack.onFetch(sourceType)
}
override fun onFailure(e: ApolloException) {
callBack.onFailure(e)
}
override fun onCompleted() {
// call onCompleted in onResponse
}
})
}
override fun dispose() {
disposed = true
}
fun handleProtocolNegotiation(request: InterceptorRequest,
response: InterceptorResponse): Optional<InterceptorRequest> {
return (response.parsedResponse as Optional<ApolloResponse<Operation.Data>>).flatMap(object: Function<ApolloResponse<Operation.Data>, Optional<InterceptorRequest>> {
override fun apply(response: ApolloResponse<Operation.Data>): Optional<InterceptorRequest> {
if (response.hasErrors()) {
if (isPersistedQueryNotFound(response.errors)) {
logger.w("GraphQL server couldn't find Automatic Persisted Query for operation name: "
+ request.operation.name() + " id: " + request.operation.id())
val retryRequest = request.toBuilder()
.autoPersistQueries(true)
.sendQueryDocument(true)
.build()
return Optional.of(retryRequest)
}
if (isPersistedQueryNotSupported(response.errors)) {
// TODO how to disable Automatic Persisted Queries in future and how to notify user about this
logger.e("GraphQL server doesn't support Automatic Persisted Queries")
return Optional.of(request)
}
}
return Optional.absent()
}
})
}
fun isPersistedQueryNotFound(errors: List<Error>?): Boolean {
for (error in errors!!) {
if (PROTOCOL_NEGOTIATION_ERROR_QUERY_NOT_FOUND.equals(error.message, ignoreCase = true)) {
return true
}
}
return false
}
fun isPersistedQueryNotSupported(errors: List<Error>?): Boolean {
for (error in errors!!) {
if (PROTOCOL_NEGOTIATION_ERROR_NOT_SUPPORTED.equals(error.message, ignoreCase = true)) {
return true
}
}
return false
}
class Factory @JvmOverloads constructor(val useHttpGet: Boolean = false, val persistQueries: Boolean = true, val persistMutations: Boolean = true) : ApolloInterceptorFactory {
override fun newInterceptor(logger: ApolloLogger, operation: Operation<*>): ApolloInterceptor? {
if (operation is Query<*> && !persistQueries) {
return null
}
return if (operation is Mutation<*> && !persistMutations) {
null
} else ApolloAutoPersistedOperationInterceptor(logger, useHttpGet)
}
}
companion object {
private const val PROTOCOL_NEGOTIATION_ERROR_QUERY_NOT_FOUND = "PersistedQueryNotFound"
private const val PROTOCOL_NEGOTIATION_ERROR_NOT_SUPPORTED = "PersistedQueryNotSupported"
}
}
|
mit
|
02147ad673f3ca43de85373f97002be7
| 40.153846 | 177 | 0.701973 | 4.815 | false | false | false | false |
slak44/gitforandroid
|
app/src/main/java/slak/gitforandroid/Util.kt
|
1
|
2455
|
package slak.gitforandroid
import android.content.Context
import android.content.res.Resources
import android.graphics.PorterDuff
import android.preference.PreferenceManager
import android.support.annotation.ColorRes
import android.support.annotation.StringRes
import android.support.design.widget.Snackbar
import android.util.Log
import android.view.MenuItem
import android.view.View
import kotlinx.coroutines.experimental.*
import kotlin.coroutines.experimental.CoroutineContext
/**
* Wraps [async], except it also rethrows exceptions synchronously.
*/
fun <T> async2(
context: CoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T> {
val c = async(context, start, block)
c.invokeOnCompletion { e -> if (e != null) throw e }
return c
}
inline fun Job.withSnackResult(view: View,
@StringRes success: Int,
@StringRes failure: Int,
crossinline callback: (t: Throwable?) -> Unit = {}): Job {
return this.withSnackResult(view, view.context.resources.getString(success),
view.context.resources.getString(failure), callback)
}
inline fun Job.withSnackResult(view: View,
success: String,
failure: String,
crossinline callback: (t: Throwable?) -> Unit = {}): Job {
invokeOnCompletion { throwable ->
if (throwable == null) {
Snackbar.make(view, success, Snackbar.LENGTH_LONG)
} else {
Snackbar.make(view, failure, Snackbar.LENGTH_LONG)
Log.e("withSnackResult", "caught", throwable)
}
callback(throwable)
}
return this
}
fun reportError(snack: View, formatted: String, e: Throwable) {
Log.e("GitForAndroid", formatted, e)
// TODO: make 'more' button on snack, to lead to err text
Snackbar.make(snack, formatted, Snackbar.LENGTH_LONG).show()
}
// FIXME
fun getStringSetting(context: Context, key: String): String {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, "")
}
/**
* Emulates android:iconTint. Must be called in onPrepareOptionsMenu for each icon.
*/
fun MenuItem.iconTint(context: Context, @ColorRes colorRes: Int) {
val color = context.resources.getColor(colorRes, context.theme)
val drawable = this.icon
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN)
this.icon = drawable
}
|
mit
|
cc4c7cd4578c91e407d2899822978d8b
| 33.097222 | 89 | 0.689206 | 4.284468 | false | false | false | false |
square/wire
|
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/CommonSchemaLoader.kt
|
1
|
9963
|
/*
* Copyright 2018 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.
*/
package com.squareup.wire.schema.internal
import com.squareup.wire.schema.CoreLoader
import com.squareup.wire.schema.ErrorCollector
import com.squareup.wire.schema.Linker
import com.squareup.wire.schema.Loader
import com.squareup.wire.schema.Location
import com.squareup.wire.schema.Profile
import com.squareup.wire.schema.ProfileLoader
import com.squareup.wire.schema.ProtoFile
import com.squareup.wire.schema.ProtoFilePath
import com.squareup.wire.schema.ProtoType
import com.squareup.wire.schema.Root
import com.squareup.wire.schema.Schema
import com.squareup.wire.schema.internal.parser.ProtoFileElement
import com.squareup.wire.schema.isWireRuntimeProto
import com.squareup.wire.schema.parse
import com.squareup.wire.schema.roots
import okio.FileSystem
import okio.IOException
/**
* Load proto files and their transitive dependencies and parse them. Keep track of which files were
* loaded from where so that we can use that information later when deciding what to generate.
*/
internal class CommonSchemaLoader : Loader, ProfileLoader {
private val fileSystem: FileSystem
/** Errors accumulated by this load. */
private val errors: ErrorCollector
/** Source path roots that need to be closed */
private var sourcePathRoots: List<Root>?
/** Proto path roots that need to be closed */
private var protoPathRoots: List<Root>?
/** Strict by default. Note that golang cannot build protos with package cycles. */
var permitPackageCycles = false
/**
* If true, the schema loader will load the whole graph, including files and types not used by
* anything in the source path.
*/
var loadExhaustively = false
/** Subset of the schema that was loaded from the source path. */
var sourcePathFiles: List<ProtoFile>
private set
/** Keys are a [Location.base]; values are the roots that those locations loaded from. */
private val baseToRoots: MutableMap<String, List<Root>>
constructor(fileSystem: FileSystem) {
this.fileSystem = fileSystem
this.errors = ErrorCollector()
this.sourcePathRoots = null
this.protoPathRoots = null
this.sourcePathFiles = listOf()
this.baseToRoots = mutableMapOf()
}
internal constructor(enclosing: CommonSchemaLoader, errors: ErrorCollector) {
this.fileSystem = enclosing.fileSystem
this.errors = errors
this.sourcePathRoots = enclosing.sourcePathRoots
this.protoPathRoots = enclosing.protoPathRoots
this.sourcePathFiles = enclosing.sourcePathFiles
this.baseToRoots = enclosing.baseToRoots
}
override fun withErrors(errors: ErrorCollector) = CommonSchemaLoader(this, errors)
/** Initialize the [WireRun.sourcePath] and [WireRun.protoPath] from which files are loaded. */
fun initRoots(
sourcePath: List<Location>,
protoPath: List<Location> = listOf()
) {
check(sourcePathRoots == null && protoPathRoots == null)
sourcePathRoots = allRoots(sourcePath)
protoPathRoots = allRoots(protoPath)
}
@Throws(IOException::class)
fun loadSchema(): Schema {
sourcePathFiles = loadSourcePathFiles()
val linker = Linker(this, errors, permitPackageCycles, loadExhaustively)
val result = linker.link(sourcePathFiles)
errors.throwIfNonEmpty()
return result
}
/** Returns the files in the source path. */
@Throws(IOException::class)
internal fun loadSourcePathFiles(): List<ProtoFile> {
check(sourcePathRoots != null && protoPathRoots != null) {
"call initRoots() before calling loadSourcePathFiles()"
}
val result = mutableListOf<ProtoFile>()
for (sourceRoot in sourcePathRoots!!) {
for (locationAndPath in sourceRoot.allProtoFiles()) {
result += load(locationAndPath)
}
}
if (result.isEmpty()) {
errors += "no sources"
}
errors.throwIfNonEmpty()
return result
}
override fun load(path: String): ProtoFile {
// Traverse roots in search of the one that has this path.
var loadFrom: ProtoFilePath? = null
for (protoPathRoot in protoPathRoots!!) {
val locationAndPath: ProtoFilePath = protoPathRoot.resolve(path) ?: continue
if (loadFrom != null) {
errors += "$path is ambiguous:\n $locationAndPath\n $loadFrom"
continue
}
loadFrom = locationAndPath
}
if (loadFrom != null) {
return load(loadFrom)
}
if (isWireRuntimeProto(path)) {
return CoreLoader.load(path)
}
errors += """
|unable to find $path
| searching ${protoPathRoots!!.size} proto paths:
| ${protoPathRoots!!.joinToString(separator = "\n ")}
""".trimMargin()
return ProtoFile.get(ProtoFileElement.empty(path))
}
private fun load(protoFilePath: ProtoFilePath): ProtoFile {
if (isWireRuntimeProto(protoFilePath.location)) {
return CoreLoader.load(protoFilePath.location.path)
}
val protoFile = protoFilePath.parse()
val importPath = protoFile.importPath(protoFilePath.location)
// If the .proto was specified as a full path without a separate base directory that it's
// relative to, confirm that the import path and file system path agree.
if (protoFilePath.location.base.isEmpty() &&
protoFilePath.location.path != importPath &&
!protoFilePath.location.path.endsWith("/$importPath")
) {
errors += "expected ${protoFilePath.location.path} to have a path ending with $importPath"
}
return protoFile
}
/** Convert `pathStrings` into roots that can be searched. */
private fun allRoots(locations: List<Location>): List<Root> {
val result = mutableListOf<Root>()
for (location in locations) {
try {
result += location.roots(fileSystem, baseToRoots)
} catch (e: IllegalArgumentException) {
errors += e.message!!
}
}
return result
}
internal fun reportLoadingErrors() {
errors.throwIfNonEmpty()
}
override fun loadProfile(name: String, schema: Schema): Profile {
val allLocations = schema.protoFiles.map { it.location }
val locationsToCheck = locationsToCheck(name, allLocations)
val profileElements = mutableListOf<ProfileFileElement>()
for (location in locationsToCheck) {
val roots = baseToRoots[location.base] ?: continue
for (root in roots) {
val resolved = root.resolve(location.path) ?: continue
profileElements += resolved.parseProfile()
}
}
val profile = Profile(profileElements)
validate(schema, profileElements)
return profile
}
/** Confirms that `protoFiles` link correctly against `schema`. */
private fun validate(schema: Schema, profileFiles: List<ProfileFileElement>) {
for (profileFile in profileFiles) {
for (typeConfig in profileFile.typeConfigs) {
val type = importedType(ProtoType.get(typeConfig.type)) ?: continue
val resolvedType = schema.getType(type)
if (resolvedType == null) {
// This type is either absent from .proto files, or merely not loaded because our schema
// is incomplete. Unfortunately we can't tell the difference! Assume that this type is
// just absent from the schema-as-loaded and therefore irrelevant to the current project.
// Ignore it!
//
// (A fancier implementation would load the schema and profile in one step and they would
// be mutually complete. We aren't bothering with this correctness at this phase.)
continue
}
val requiredImport = resolvedType.location.path
if (!profileFile.imports.contains(requiredImport)) {
errors += "${typeConfig.location.path} needs to import $requiredImport " +
"(${typeConfig.location})"
}
}
}
errors.throwIfNonEmpty()
}
/** Returns the type to import for `type`. */
private fun importedType(type: ProtoType): ProtoType? {
var type = type
// Map key type is always scalar.
if (type.isMap) type = type.valueType!!
return if (type.isScalar) null else type
}
/**
* Returns a list of locations to check for profile files. This is the profile file name (like
* "java.wire") in the same directory, and in all parent directories up to the base.
*/
internal fun locationsToCheck(name: String, input: List<Location>): Set<Location> {
val queue = ArrayDeque(input)
val result = mutableSetOf<Location>()
while (true) {
val protoLocation = queue.removeFirstOrNull() ?: break
val lastSlash = protoLocation.path.lastIndexOf("/")
val parentPath = protoLocation.path.substring(0, lastSlash + 1)
val profileLocation = protoLocation.copy(path = "$parentPath$name.wire")
if (!result.add(profileLocation)) continue // Already added.
if (!parentPath.isNotEmpty()) continue // No more parents to enqueue.
queue += protoLocation.copy(path = parentPath.dropLast(1)) // Drop trailing '/'.
}
return result
}
}
internal fun ProtoFile.importPath(location: Location): String {
return when {
location.base.isEmpty() -> canonicalImportPath(location)
else -> location.path
}
}
internal fun ProtoFile.canonicalImportPath(location: Location): String {
val filename = location.path.substringAfterLast('/')
return when (val packageName = packageName) {
null -> filename
else -> packageName.replace('.', '/') + "/" + filename
}
}
|
apache-2.0
|
9e5ec847a1d14305293e9743e95619a3
| 33.835664 | 100 | 0.698685 | 4.392857 | false | false | false | false |
onoderis/failchat
|
src/main/kotlin/failchat/util/Threads.kt
|
2
|
828
|
package failchat.util
val hotspotThreads: Set<String> = setOf("Attach Listener", "Disposer", "Finalizer", "Prism Font Disposer",
"Reference Handler", "Signal Dispatcher","DestroyJavaVM")
fun formatStackTraces(stackTraces: Map<Thread, Array<StackTraceElement>>): String {
return stackTraces
.map { (thread, stackTraceElements) ->
with(thread) {
"Thread[name=$name; id=$id; state=$state; isDaemon=$isDaemon; isInterrupted=$isInterrupted; " +
"priority=$priority; threadGroup=${threadGroup.name}]"
} +
if (stackTraceElements.isEmpty()) ""
else stackTraceElements.joinToString(prefix = ls + "\t", separator = ls + "\t")
}
.joinToString(separator = ls)
}
|
gpl-3.0
|
4b22043706c2aae56aba7126073336cb
| 47.705882 | 115 | 0.582126 | 4.928571 | false | false | false | false |
Maccimo/intellij-community
|
plugins/kotlin/fir/test/org/jetbrains/kotlin/idea/fir/completion/AbstractHighLevelMultiFileJvmBasicCompletionTest.kt
|
2
|
1695
|
// 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.fir.completion
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.completion.test.KotlinFixtureCompletionBaseTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.test.utils.IgnoreTests
import java.io.File
abstract class AbstractHighLevelMultiFileJvmBasicCompletionTest : KotlinFixtureCompletionBaseTestCase() {
override val testDataDirectory: File
get() = super.testDataDirectory.resolve(getTestName(false))
override val captureExceptions: Boolean = false
override fun executeTest(test: () -> Unit) {
IgnoreTests.runTestIfEnabledByFileDirective(dataFile().toPath(), IgnoreTests.DIRECTIVES.FIR_COMPARISON) {
test()
}
}
override fun fileName(): String = getTestName(false) + ".kt"
override fun configureFixture(testPath: String) {
// We need to copy all files from the testDataPath (= "") to the tested project
myFixture.copyDirectoryToProject("", "")
super.configureFixture(testPath)
}
override fun defaultCompletionType(): CompletionType = CompletionType.BASIC
override fun getPlatform(): TargetPlatform = JvmPlatforms.unspecifiedJvmPlatform
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
|
apache-2.0
|
8d419206e1eaee57037f7a1c7466754c
| 43.631579 | 120 | 0.783481 | 5.380952 | false | true | false | false |
AcornUI/Acorn
|
acornui-core/src/main/kotlin/com/acornui/dom/components.kt
|
1
|
7485
|
/*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.dom
import com.acornui.component.*
import com.acornui.component.style.CommonStyleTags
import com.acornui.di.Context
import com.acornui.input.mousePressOnKey
import com.acornui.signal.event
import kotlinx.browser.document
import org.w3c.dom.*
import org.w3c.dom.events.Event
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
inline fun <T : HTMLElement> Context.component(localName: String, init: ComponentInit<UiComponentImpl<T>> = {}): UiComponentImpl<T> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return UiComponentImpl(this, createElement<Element>(localName).unsafeCast<T>()).apply(init)
}
open class A(owner: Context) : UiComponentImpl<HTMLAnchorElement>(owner, createElement("a")) {
init {
mousePressOnKey()
}
var href: String
get() = dom.href
set(value) {
dom.href = value
}
var target: String
get() = dom.target
set(value) {
dom.target = value
}
}
inline fun Context.a(href: String = "javascript:void(0)", target: String = "", init: ComponentInit<A> = {}): A {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return A(this).apply {
this.href = href
this.target = target
init()
}
}
inline fun Context.br(init: ComponentInit<UiComponentImpl<HTMLBRElement>> = {}): UiComponentImpl<HTMLBRElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("br", init)
}
inline fun Context.hr(init: ComponentInit<UiComponentImpl<HTMLHRElement>> = {}): UiComponentImpl<HTMLHRElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("hr", init)
}
inline fun Context.ul(init: ComponentInit<UiComponentImpl<HTMLUListElement>> = {}): UiComponentImpl<HTMLUListElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("ul", init)
}
inline fun Context.ol(init: ComponentInit<UiComponentImpl<HTMLOListElement>> = {}): UiComponentImpl<HTMLOListElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("ol", init)
}
inline fun Context.li(text: String = "", init: ComponentInit<UiComponentImpl<HTMLLIElement>> = {}): UiComponentImpl<HTMLLIElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("li") {
if (text.isNotEmpty()) +text
init()
}
}
inline fun Context.h1(text: String = "", init: ComponentInit<UiComponentImpl<HTMLHeadingElement>> = {}): UiComponentImpl<HTMLHeadingElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("h1") {
if (text.isNotEmpty()) +text
init()
}
}
inline fun Context.h2(text: String = "", init: ComponentInit<UiComponentImpl<HTMLHeadingElement>> = {}): UiComponentImpl<HTMLHeadingElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("h2") {
if (text.isNotEmpty()) +text
init()
}
}
inline fun Context.h3(text: String = "", init: ComponentInit<UiComponentImpl<HTMLHeadingElement>> = {}): UiComponentImpl<HTMLHeadingElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("h3") {
if (text.isNotEmpty()) +text
init()
}
}
inline fun Context.h4(text: String = "", init: ComponentInit<UiComponentImpl<HTMLHeadingElement>> = {}): UiComponentImpl<HTMLHeadingElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("h4") {
if (text.isNotEmpty()) +text
init()
}
}
inline fun Context.h5(text: String = "", init: ComponentInit<UiComponentImpl<HTMLHeadingElement>> = {}): UiComponentImpl<HTMLHeadingElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("h5") {
if (text.isNotEmpty()) +text
init()
}
}
inline fun Context.h6(text: String = "", init: ComponentInit<UiComponentImpl<HTMLHeadingElement>> = {}): UiComponentImpl<HTMLHeadingElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("h6") {
if (text.isNotEmpty()) +text
init()
}
}
open class Img(owner: Context) : UiComponentImpl<Image>(owner, Image()) {
var alt: String
get() = dom.alt
set(value) {
dom.alt = value
}
var src: String
get() = dom.src
set(value) {
dom.src = value
}
var srcset: String
get() = dom.srcset
set(value) {
dom.srcset = value
}
val naturalWidth: Int
get() = dom.naturalWidth
val naturalHeight: Int
get() = dom.naturalHeight
}
inline fun Context.img(src: String = "", alt: String = "", init: ComponentInit<Img> = {}): Img {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return Img(this).apply {
this.src = src
this.alt = alt
this.title = alt
init()
}
}
open class Form(owner: Context) : UiComponentImpl<HTMLFormElement>(owner, createElement("form")) {
val submitted = event<Event>("submit")
var acceptCharset: String
get() = dom.acceptCharset
set(value) {
dom.acceptCharset = value
}
var action: String
get() = dom.action
set(value) {
dom.action = value
}
var autocomplete: String
get() = dom.autocomplete
set(value) {
dom.autocomplete = value
}
var enctype: String
get() = dom.enctype
set(value) {
dom.enctype = value
}
var encoding: String
get() = dom.encoding
set(value) {
dom.encoding = value
}
var method: String
get() = dom.method
set(value) {
dom.method = value
}
var noValidate: Boolean
get() = dom.noValidate
set(value) {
dom.noValidate = value
}
/**
* Sets [action] to `"javascript:void(0);"`, thus preventing a page redirect on form submission.
*/
fun preventAction() {
dom.onsubmit = {
it.preventDefault()
it.asDynamic().returnValue = false
false
}
}
fun submit() = dom.submit()
fun reset() = dom.reset()
fun checkValidity(): Boolean = dom.checkValidity()
fun reportValidity(): Boolean = dom.reportValidity()
}
inline fun Context.form(init: ComponentInit<Form> = {}): Form {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return Form(this).apply(init)
}
/**
* Returns an input element of type 'submit' styled to be invisible.
*/
fun Context.hiddenSubmit(init: ComponentInit<UiComponentImpl<HTMLInputElement>> = {}): UiComponentImpl<HTMLInputElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("input") {
addClass(CommonStyleTags.hidden)
dom.type = "submit"
tabIndex = -1
}
}
inline fun Context.footer(init: ComponentInit<UiComponentImpl<HTMLElement>> = {}): UiComponentImpl<HTMLElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("footer", init)
}
/**
* Creates a [DocumentFragment].
*/
inline fun fragment(init: ComponentInit<WithNode> = {}): WithNode =
document.createDocumentFragment().asWithNode().apply(init)
/**
* Creates an HTMLDivElement.
*/
inline fun divElement(init: ComponentInit<HTMLDivElement> = {}): HTMLDivElement =
createElement("div", init)
|
apache-2.0
|
449a7b150095cfc961904002f14ac409
| 26.623616 | 142 | 0.715698 | 3.497664 | false | false | false | false |
Tiofx/semester_6
|
TOPK/TOPK_lab_4/src/main/kotlin/lab4/util/simplePrecedence/Error.kt
|
1
|
285
|
package lab4.util.simplePrecedence
object Error {
const val PROGRAM_STRUCTURE_OUT = 4
const val PROGRAM_STRUCTURE_IN = 5
const val OPERATOR_END = 6
const val OPERATOR = 7
const val SIGN_COMBINATION = 8
const val RULE_NOT_FOUND = 9
const val UNKNOWN = 66
}
|
gpl-3.0
|
a6a99c1644b027cb2059dfedb7f0d011
| 22.833333 | 39 | 0.687719 | 3.75 | false | false | false | false |
Hexworks/zircon
|
zircon.jvm.swing/src/main/kotlin/org/hexworks/zircon/internal/tileset/transformer/Java2DCropTransformer.kt
|
1
|
1044
|
package org.hexworks.zircon.internal.tileset.transformer
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.modifier.Crop
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.api.tileset.transformer.Java2DTextureTransformer
import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture
import java.awt.image.BufferedImage
class Java2DCropTransformer : Java2DTextureTransformer() {
override fun transform(texture: TileTexture<BufferedImage>, tile: Tile): TileTexture<BufferedImage> {
val (x, y, width, height) = tile.modifiers.first { it is Crop } as Crop
val txt = texture.texture
val newImage = BufferedImage(texture.width, texture.width, BufferedImage.TRANSLUCENT)
newImage.createGraphics()
.drawImage(txt.getSubimage(x, y, width, height), x, y, null)
return DefaultTileTexture(
width = txt.width,
height = txt.height,
texture = newImage,
cacheKey = tile.cacheKey
)
}
}
|
apache-2.0
|
6ddf79edb49f7e1993ff495e1715f708
| 39.153846 | 105 | 0.717433 | 4.296296 | false | false | false | false |
DiUS/pact-jvm
|
provider/maven/src/main/kotlin/au/com/dius/pact/provider/maven/Consumer.kt
|
1
|
1032
|
package au.com.dius.pact.provider.maven
import au.com.dius.pact.core.model.Interaction
import au.com.dius.pact.core.model.UrlSource
import au.com.dius.pact.provider.ConsumerInfo
import au.com.dius.pact.provider.PactVerification
import java.net.URL
/**
* Consumer Info for maven projects
*/
class Consumer(
override var name: String = "",
override var stateChange: Any? = null,
override var stateChangeUsesBody: Boolean = true,
override var packagesToScan: List<String> = emptyList(),
override var verificationType: PactVerification? = null,
override var pactSource: Any? = null,
override var pactFileAuthentication: List<Any?> = emptyList()
) : ConsumerInfo(name, stateChange, stateChangeUsesBody, packagesToScan, verificationType, pactSource, pactFileAuthentication) {
fun getPactUrl() = if (pactSource is UrlSource<*>) {
URL((pactSource as UrlSource<*>).url)
} else {
URL(pactSource.toString())
}
fun setPactUrl(pactUrl: URL) {
pactSource = UrlSource<Interaction>(pactUrl.toString())
}
}
|
apache-2.0
|
33d1e451ed3780319b947ac337c69104
| 32.290323 | 128 | 0.747093 | 3.71223 | false | false | false | false |
greenspand/kotlin-extensions
|
kotlin-ext/src/main/java/com/sorinirimies/kotlinx/logUtils.kt
|
1
|
524
|
@file:JvmName("LogUtils")
package com.sorinirimies.kotlinx
import android.content.Context
import android.support.annotation.Keep
import android.util.Log
@Keep
fun Context.d(message: String) = Log.d(this.packageName, message)
@Keep
fun Context.i(message: String) = Log.i(this.packageName, message)
@Keep
fun Context.e(message: String) = Log.e(this.packageName, message)
@Keep
fun Context.w(message: String) = Log.w(this.packageName, message)
@Keep
fun Context.wtf(message: String) = Log.wtf(this.packageName, message)
|
mit
|
bca413e68bed3e9e6632ee91708ce343
| 22.818182 | 69 | 0.769084 | 3.119048 | false | false | false | false |
michaelkourlas/voipms-sms-client
|
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/sms/receivers/SyncBootReceiver.kt
|
1
|
1652
|
/*
* VoIP.ms SMS
* Copyright (C) 2017-2021 Michael Kourlas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kourlas.voipms_sms.sms.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import net.kourlas.voipms_sms.sms.workers.SyncWorker
import net.kourlas.voipms_sms.utils.logException
/**
* Receiver called on system startup and used to set up the synchronization
* interval.
*/
class SyncBootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
try {
if (context == null || intent == null) {
throw Exception("No context or intent provided")
}
if (intent.action != "android.intent.action.BOOT_COMPLETED"
&& intent.action != "android.intent.action.ACTION_LOCKED_BOOT_COMPLETED"
) {
throw Exception("Unrecognized action " + intent.action)
}
SyncWorker.performFullSynchronization(context, scheduleOnly = true)
} catch (e: Exception) {
logException(e)
}
}
}
|
apache-2.0
|
5b09d20f8ab58064a1ad7ce6eba33d91
| 34.913043 | 88 | 0.679782 | 4.37037 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextBaseTest.kt
|
1
|
3986
|
// 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.decompiler.textBuilder
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.PsiRecursiveElementVisitor
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.test.*
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.test.TargetBackend
import java.io.File
abstract class AbstractDecompiledTextBaseTest(
baseDirectory: String,
private val isJsLibrary: Boolean = false,
private val withRuntime: Boolean = false
) : KotlinLightCodeInsightFixtureTestCase() {
protected companion object {
const val TEST_PACKAGE = "test"
}
protected abstract fun getFileToDecompile(): VirtualFile
protected abstract fun checkPsiFile(psiFile: PsiFile)
protected abstract fun textToCheck(psiFile: PsiFile): String
protected open fun checkStubConsistency(file: VirtualFile, decompiledText: String) {}
protected val mockSourcesBase = File(IDEA_TEST_DATA_DIR, baseDirectory)
private lateinit var mockLibraryFacility: MockLibraryFacility
override val testDataDirectory: File
get() = File(mockSourcesBase, getTestName(false))
override fun shouldRunTest(): Boolean {
val targetBackend = if (isJsLibrary) TargetBackend.JS else TargetBackend.JVM
return InTextDirectivesUtils.isCompatibleTarget(targetBackend, testDataDirectory)
}
override fun setUp() {
super.setUp()
val platform = when {
isJsLibrary -> KotlinCompilerStandalone.Platform.JavaScript(MockLibraryFacility.MOCK_LIBRARY_NAME, TEST_PACKAGE)
else -> KotlinCompilerStandalone.Platform.Jvm()
}
val directivesText = InTextDirectivesUtils.textWithDirectives(testDataDirectory)
mockLibraryFacility = MockLibraryFacility(
source = testDataDirectory,
attachSources = false,
platform = platform,
options = getCompilationOptions(directivesText),
classpath = getCompilationClasspath(directivesText),
)
mockLibraryFacility.setUp(module)
}
private fun getCompilationOptions(directivesText: String): List<String> =
if (InTextDirectivesUtils.isDirectiveDefined(directivesText, "ALLOW_KOTLIN_PACKAGE")) {
listOf("-Xallow-kotlin-package")
} else {
emptyList()
}
private fun getCompilationClasspath(directivesText: String): List<File> =
if (InTextDirectivesUtils.isDirectiveDefined(directivesText, "STDLIB_JDK_8")) {
listOf(TestKotlinArtifacts.kotlinStdlibJdk8)
} else {
emptyList()
}
override fun tearDown() {
runAll(
ThrowableRunnable { mockLibraryFacility.tearDown(module) },
ThrowableRunnable { super.tearDown() }
)
}
fun doTest(path: String) {
val fileToDecompile = getFileToDecompile()
val psiFile = PsiManager.getInstance(project).findFile(fileToDecompile)!!
checkPsiFile(psiFile)
val checkedText = textToCheck(psiFile)
KotlinTestUtils.assertEqualsToFile(File("$path.expected.kt"), checkedText)
checkStubConsistency(fileToDecompile, checkedText)
checkThatFileWasParsedCorrectly(psiFile)
}
private fun checkThatFileWasParsedCorrectly(clsFile: PsiFile) {
clsFile.accept(object : PsiRecursiveElementVisitor() {
override fun visitErrorElement(element: PsiErrorElement) {
fail("Decompiled file should not contain error elements!\n${element.getElementTextWithContext()}")
}
})
}
}
|
apache-2.0
|
c2a0e2cfc76bd1e80183ca91f3dc2934
| 35.907407 | 158 | 0.714752 | 5.244737 | false | true | false | false |
sys1yagi/longest-streak-android
|
app/src/main/java/com/sys1yagi/longeststreakandroid/db/EventLog.kt
|
1
|
966
|
package com.sys1yagi.longeststreakandroid.db
import com.github.gfx.android.orma.annotation.Column
import com.github.gfx.android.orma.annotation.OnConflict
import com.github.gfx.android.orma.annotation.PrimaryKey
import com.github.gfx.android.orma.annotation.Table
import com.sys1yagi.longeststreakandroid.model.Event
import java.util.Date
@Table
class EventLog {
@PrimaryKey
var id: Long = 0
@Column(uniqueOnConflict = OnConflict.IGNORE)
var eventId: Long = 0
@Column
lateinit var name: String
@Column(indexed = true)
var createdAt: Long = 0
@Column
lateinit var type: Event.Type
companion object {
fun toEventLog(name: String, event: Event): EventLog {
val eventLog = EventLog()
eventLog.eventId = event.id
eventLog.name = name
eventLog.createdAt = event.createdAt.time
eventLog.type = event.type
return eventLog
}
}
}
|
mit
|
dce21c9cf8d5a8537edc908f27e3aa13
| 23.15 | 62 | 0.680124 | 4.041841 | false | false | false | false |
micolous/metrodroid
|
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/TransactionTrip.kt
|
1
|
6429
|
/*
* TransactionTrip.kt
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Parcelable
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.time.TimestampFull
@Parcelize
class TransactionTripCapsule(var start: Transaction? = null,
var end: Transaction? = null): Parcelable
@Parcelize
class TransactionTrip(override val capsule: TransactionTripCapsule): TransactionTripAbstract() {
override val fare: TransitCurrency?
get() {
// No fare applies to the trip, as the tap-on was reversed.
if (end?.isCancel == true) {
return null
}
return start?.fare?.let {
// These is a start fare, add the end fare to it, if present
return it + end?.fare
} ?: end?.fare // Otherwise use the end fare.
}
companion object {
fun merge(transactionsIn: List<Transaction>) =
TransactionTripAbstract.merge(transactionsIn) { TransactionTrip(makeCapsule(it)) }
fun merge(vararg transactions: Transaction): List<TransactionTripAbstract> =
merge(transactions.toList())
}
}
@Parcelize
class TransactionTripLastPrice(override val capsule: TransactionTripCapsule): TransactionTripAbstract() {
override val fare: TransitCurrency? get() = end?.fare ?: start?.fare
companion object {
fun merge(transactionsIn: List<Transaction>) =
TransactionTripAbstract.merge(transactionsIn) { TransactionTripLastPrice(makeCapsule(it)) }
fun merge(vararg transactions: Transaction): List<TransactionTripAbstract> =
merge(transactions.toList())
}
}
abstract class TransactionTripAbstract: Trip() {
abstract val capsule: TransactionTripCapsule
protected val start get() = capsule.start
protected val end get() = capsule.end
private val any: Transaction?
get() = start ?: end
override// Try to get the route from the nested transactions.
// This automatically falls back to using the MdST.
val routeName: FormattedString?
get() {
val startLines = start?.routeNames ?: emptyList()
val endLines = end?.routeNames ?: emptyList()
return Trip.getRouteName(startLines, endLines)
}
override// Try to get the route from the nested transactions.
// This automatically falls back to using the MdST.
val humanReadableRouteID: String?
get() {
val startLines = start?.humanReadableLineIDs ?: emptyList()
val endLines = end?.humanReadableLineIDs ?: emptyList()
return Trip.getRouteName(startLines, endLines)
}
override val passengerCount: Int
get() = any?.passengerCount ?: -1
override val vehicleID: String?
get() = any?.vehicleID
override val machineID: String?
get() = any?.machineID
override val startStation: Station?
get() = start?.station
override val endStation: Station?
get() = end?.station
override val startTimestamp: Timestamp?
get() = start?.timestamp
override val endTimestamp: Timestamp?
get() = end?.timestamp
override val mode: Trip.Mode
get() = any?.mode ?: Trip.Mode.OTHER
abstract override val fare: TransitCurrency?
override val isTransfer: Boolean
get() = any?.isTransfer ?: false
override val isRejected: Boolean
get() = any?.isRejected ?: false
override fun getRawFields(level: TransitData.RawLevel): String? {
val from = start?.getRawFields(level)
val to = end?.getRawFields(level)
return when {
from != null && to != null -> "$from → $to"
to != null -> "→ $to"
from != null -> from
else -> null
}
}
override fun getAgencyName(isShort: Boolean): FormattedString? = any?.getAgencyName(isShort)
companion object {
fun makeCapsule(transaction: Transaction) : TransactionTripCapsule =
if (transaction.isTapOff || transaction.isCancel)
TransactionTripCapsule(null, transaction)
else
TransactionTripCapsule(transaction, null)
fun merge(transactionsIn: List<Transaction>,
factory: (Transaction) -> TransactionTripAbstract):
List<TransactionTripAbstract> {
val timedTransactions = mutableListOf<Pair<Transaction, TimestampFull>>()
val unmergeableTransactions = mutableListOf<Transaction>()
for (transaction in transactionsIn) {
val ts = transaction.timestamp
if (!transaction.isTransparent && ts is TimestampFull)
timedTransactions.add(Pair(transaction, ts))
else
unmergeableTransactions.add(transaction)
}
val transactions = timedTransactions.sortedBy { it.second.timeInMillis }
val trips = mutableListOf<TransactionTripAbstract>()
for ((first) in transactions) {
if (trips.isEmpty()) {
trips.add(factory(first))
continue
}
val previous = trips[trips.size - 1]
if (previous.end == null && previous.start?.shouldBeMerged(first) == true)
previous.capsule.end = first
else
trips.add(factory(first))
}
return trips + unmergeableTransactions.map { factory(it) }
}
}
}
|
gpl-3.0
|
858e4aa9366a5eea34e7a3c7a84cdd52
| 35.095506 | 107 | 0.631907 | 4.816342 | false | false | false | false |
square/picasso
|
picasso/src/main/java/com/squareup/picasso3/DrawableTargetAction.kt
|
1
|
1962
|
/*
* Copyright (C) 2022 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.
*/
package com.squareup.picasso3
import android.graphics.drawable.Drawable
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import com.squareup.picasso3.RequestHandler.Result
import com.squareup.picasso3.RequestHandler.Result.Bitmap
internal class DrawableTargetAction(
picasso: Picasso,
private val target: DrawableTarget,
data: Request,
private val noFade: Boolean,
private val placeholderDrawable: Drawable?,
private val errorDrawable: Drawable?,
@DrawableRes val errorResId: Int
) : Action(picasso, data) {
override fun complete(result: Result) {
if (result is Bitmap) {
val bitmap = result.bitmap
target.onDrawableLoaded(
PicassoDrawable(
context = picasso.context,
bitmap = bitmap,
placeholder = placeholderDrawable,
loadedFrom = result.loadedFrom,
noFade = noFade,
debugging = picasso.indicatorsEnabled
),
result.loadedFrom
)
check(!bitmap.isRecycled) { "Target callback must not recycle bitmap!" }
}
}
override fun error(e: Exception) {
val drawable = if (errorResId != 0) {
ContextCompat.getDrawable(picasso.context, errorResId)
} else {
errorDrawable
}
target.onDrawableFailed(e, drawable)
}
override fun getTarget(): Any {
return target
}
}
|
apache-2.0
|
b09de60ea3e5ad60ac8142f99ba53ea5
| 29.65625 | 78 | 0.705912 | 4.36971 | false | false | false | false |
JavaEden/Orchid-Core
|
OrchidCore/src/main/kotlin/com/eden/orchid/api/generators/BuildMetrics.kt
|
2
|
7568
|
package com.eden.orchid.api.generators
import com.caseyjbrooks.clog.Clog
import com.copperleaf.krow.HorizontalAlignment
import com.copperleaf.krow.KrowTable
import com.eden.orchid.Orchid
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.theme.pages.OrchidPage
import java.util.ArrayList
import java.util.HashMap
import javax.inject.Inject
class BuildMetrics
@Inject
constructor(val context: OrchidContext) {
var progress: Int = 0
var maxProgress: Int = 0
var totalPageCount: Int = 0
private var generatorMetricsMap = mutableMapOf<String, GeneratorMetrics>()
var compositeMetrics: GeneratorMetrics? = null
val summary: String
get() {
if (compositeMetrics == null) throw IllegalStateException("Cannot get build summary: build not complete")
return Clog.format(
"Generated {} {} in {}",
"" + compositeMetrics!!.pageCount,
if (compositeMetrics!!.pageCount == 1) "page" else "pages",
compositeMetrics!!.totalTime
)
}
val detail: KrowTable
get() {
if (compositeMetrics == null) throw IllegalStateException("Cannot get build summary: build not complete")
titleColumnWidth = "Generator".length
pageCountColumnWidth = "Page Count".length
indexingTimeColumnWidth = "Indexing Time".length
generationTimeColumnWidth = "Generation Time".length
meanPageTimeColumnWidth = "Mean Page Generation Time".length
medianPageTimeColumnWidth = "Median Page Generation Time".length
val table = KrowTable()
table.columns(
"Page Count",
"Indexing Time",
"Generation Time",
"Mean Page Generation Time",
"Median Page Generation Time"
)
val metricsList = ArrayList(generatorMetricsMap.values)
metricsList.add(compositeMetrics)
for (metric in metricsList) {
if (metric.pageCount == 0) continue
table.cell("Page Count", metric.key!!) {
content = "" + metric.pageCount
}
table.cell("Indexing Time", metric.key!!) {
content = "" + metric.indexingTime
}
table.cell("Generation Time", metric.key!!) {
content = "" + metric.generatingTime
}
table.cell("Mean Page Generation Time", metric.key!!) {
content = "" + metric.meanPageTime
}
table.cell("Median Page Generation Time", metric.key!!) {
content = "" + metric.medianPageTime
}
}
table.column("Page Count") {
wrapTextAt = pageCountColumnWidth
}
table.column("Indexing Time") {
wrapTextAt = indexingTimeColumnWidth
}
table.column("Generation Time") {
wrapTextAt = generationTimeColumnWidth
}
table.column("Mean Page Generation Time") {
wrapTextAt = meanPageTimeColumnWidth
}
table.column("Median Page Generation Time") {
wrapTextAt = medianPageTimeColumnWidth
}
table.table {
horizontalAlignment = HorizontalAlignment.CENTER
}
table.row("TOTAL") {
horizontalAlignment = HorizontalAlignment.RIGHT
}
return table
}
var titleColumnWidth: Int = 0
var pageCountColumnWidth: Int = 0
var indexingTimeColumnWidth: Int = 0
var generationTimeColumnWidth: Int = 0
var meanPageTimeColumnWidth: Int = 0
var medianPageTimeColumnWidth: Int = 0
// Measure Indexing Phase
//----------------------------------------------------------------------------------------------------------------------
fun startIndexing(generators: Set<OrchidGenerator<*>>) {
generatorMetricsMap = HashMap()
compositeMetrics = null
progress = 0
totalPageCount = 0
maxProgress = generators.size
}
fun startIndexingGenerator(generator: String) {
ensureMetricsExist(generator)
generatorMetricsMap[generator]!!.startIndexing()
context.broadcast(Orchid.Lifecycle.ProgressEvent.fire(this, "indexing", progress, maxProgress))
}
fun stopIndexingGenerator(generator: String, numberOfPages: Int) {
ensureMetricsExist(generator)
generatorMetricsMap[generator]!!.stopIndexing()
progress++
totalPageCount += numberOfPages
}
fun stopIndexing() {
context.broadcast(Orchid.Lifecycle.ProgressEvent.fire(this, "indexing", maxProgress, maxProgress))
}
// Measure Generation Phase
//----------------------------------------------------------------------------------------------------------------------
fun startGeneration() {
progress = 0
maxProgress = totalPageCount
}
fun startGeneratingGenerator(generator: String) {
ensureMetricsExist(generator)
generatorMetricsMap[generator]!!.startGenerating()
}
fun stopGeneratingGenerator(generator: String) {
ensureMetricsExist(generator)
generatorMetricsMap[generator]!!.stopGenerating()
}
fun onPageGenerated(page: OrchidPage, millis: Long) {
if (page.isIndexed) {
progress++
context.broadcast(Orchid.Lifecycle.ProgressEvent.fire(this, "building", progress, maxProgress, millis))
if (page.generator != null) {
ensureMetricsExist(page.generator.key)
generatorMetricsMap[page.generator.key]!!.addPageGenerationTime(millis)
}
}
}
fun stopGeneration() {
compositeMetrics = GeneratorMetrics("TOTAL")
generatorMetricsMap
.values
.stream()
.peek { compositeMetrics!!.compose(it) }
.forEach { this.setColumnWidths(it) }
setColumnWidths(compositeMetrics!!)
context.broadcast(Orchid.Lifecycle.ProgressEvent.fire(this, "building", maxProgress, maxProgress, 0))
}
// Print Metrics
//----------------------------------------------------------------------------------------------------------------------
private fun ensureMetricsExist(generator: String?) {
if (generator != null && !generatorMetricsMap.containsKey(generator)) {
generatorMetricsMap[generator] = GeneratorMetrics(generator)
}
}
private fun setColumnWidths(metric: GeneratorMetrics) {
titleColumnWidth = Math.max(titleColumnWidth, metric.key!!.length)
pageCountColumnWidth = Math.max(pageCountColumnWidth, ("" + metric.pageCount).length)
indexingTimeColumnWidth = Math.max(indexingTimeColumnWidth, metric.indexingTime.length)
generationTimeColumnWidth = Math.max(generationTimeColumnWidth, metric.generatingTime.length)
meanPageTimeColumnWidth = Math.max(meanPageTimeColumnWidth, metric.meanPageTime.length)
medianPageTimeColumnWidth = Math.max(medianPageTimeColumnWidth, metric.medianPageTime.length)
}
fun setGeneratorMetricsMap(generatorMetricsMap: MutableMap<String, GeneratorMetrics>) {
this.generatorMetricsMap = generatorMetricsMap
}
fun getGeneratorMetricsMap(): Map<String, GeneratorMetrics>? {
return this.generatorMetricsMap
}
}
|
mit
|
e479b7dcce00912efc7be2ab0317b93a
| 37.810256 | 124 | 0.594477 | 5.352192 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/VerboseNullabilityAndEmptinessInspection.kt
|
5
|
17386
|
// 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.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class VerboseNullabilityAndEmptinessInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = binaryExpressionVisitor(fun(unwrappedNullCheckExpression) {
val nullCheckExpression = findNullCheckExpression(unwrappedNullCheckExpression)
val nullCheck = getNullCheck(nullCheckExpression) ?: return
val binaryExpression = findBinaryExpression(nullCheckExpression) ?: return
val operationToken = binaryExpression.operationToken
val isPositiveCheck = when {
!nullCheck.isEqualNull && operationToken == KtTokens.ANDAND -> true // a != null && a.isNotEmpty()
nullCheck.isEqualNull && operationToken == KtTokens.OROR -> false // a == null || a.isEmpty()
else -> return
}
val contentCheckExpression = findContentCheckExpression(nullCheckExpression, binaryExpression) ?: return
val contentCheck = getContentCheck(contentCheckExpression) ?: return
if (isPositiveCheck != contentCheck.isPositiveCheck) return
if (!isSimilar(nullCheck.target, contentCheck.target, ::psiOnlyTargetCheck)) return
val bindingContext = binaryExpression.analyze(BodyResolveMode.PARTIAL)
if (!isSimilar(nullCheck.target, contentCheck.target, resolutionTargetCheckFactory(bindingContext))) return
// Lack of smart-cast in 'a != null && <<a>>.isNotEmpty()' means it's rather some complex expression. Skip those for now
if (!contentCheck.target.last().hasSmartCast(bindingContext)) return
val contentCheckCall = contentCheck.call.getResolvedCall(bindingContext) ?: return
val contentCheckFunction = contentCheckCall.resultingDescriptor as? SimpleFunctionDescriptor ?: return
if (!checkTargetFunctionReceiver(contentCheckFunction)) return
val overriddenFunctions = contentCheckFunction.findOriginalTopMostOverriddenDescriptors()
if (overriddenFunctions.none { it.fqNameOrNull()?.asString() in contentCheck.data.callableNames }) return
val hasExplicitReceiver = contentCheck.target.singleOrNull() !is TargetChunk.ImplicitThis
val replacementName = contentCheck.data.replacementName
holder.registerProblem(
nullCheckExpression,
KotlinBundle.message("inspection.verbose.nullability.and.emptiness.call", (if (isPositiveCheck) "!" else "") + replacementName),
ReplaceFix(replacementName, hasExplicitReceiver, isPositiveCheck)
)
})
private fun checkTargetFunctionReceiver(function: SimpleFunctionDescriptor): Boolean {
val type = getSingleReceiver(function.dispatchReceiverParameter?.value, function.extensionReceiverParameter?.value)?.type
return type != null && !type.isError && !type.isMarkedNullable && !KotlinBuiltIns.isPrimitiveArray(type)
}
private fun psiOnlyTargetCheck(left: TargetChunk, right: TargetChunk) = left.kind == right.kind && left.name == right.name
private fun resolutionTargetCheckFactory(bindingContext: BindingContext): (TargetChunk, TargetChunk) -> Boolean = r@ { left, right ->
val leftValue = left.resolve(bindingContext) ?: return@r false
val rightValue = right.resolve(bindingContext) ?: return@r false
return@r leftValue == rightValue
}
private fun getTargetChain(targetExpression: KtExpression): TargetChain? {
val result = mutableListOf<TargetChunk>()
fun processDepthFirst(expression: KtExpression): Boolean {
when (val unwrapped = expression.deparenthesize()) {
is KtNameReferenceExpression -> result += TargetChunk.Name(unwrapped)
is KtDotQualifiedExpression -> {
if (!processDepthFirst(unwrapped.receiverExpression)) return false
val selectorExpression = unwrapped.selectorExpression as? KtNameReferenceExpression ?: return false
result += TargetChunk.Name(selectorExpression)
}
is KtThisExpression -> result += TargetChunk.ExplicitThis(unwrapped)
else -> return false
}
return true
}
return if (processDepthFirst(targetExpression)) result.takeIf { it.isNotEmpty() } else null
}
private fun isSimilar(left: TargetChain, right: TargetChain, checker: (TargetChunk, TargetChunk) -> Boolean): Boolean {
return left.size == right.size && left.indices.all { index -> checker(left[index], right[index]) }
}
private fun <T: Any> unwrapNegation(expression: KtExpression, block: (KtExpression, Boolean) -> T?): T? {
if (expression is KtPrefixExpression && expression.operationToken == KtTokens.EXCL) {
val baseExpression = expression.baseExpression?.deparenthesize() as? KtExpression ?: return null
return block(baseExpression, true)
}
return block(expression, false)
}
private class NullCheck(val target: TargetChain, val isEqualNull: Boolean)
private fun getNullCheck(expression: KtExpression) = unwrapNegation(expression, fun(expression, isNegated): NullCheck? {
if (expression !is KtBinaryExpression) return null
val isNull = when (expression.operationToken) {
KtTokens.EQEQ -> true
KtTokens.EXCLEQ -> false
else -> return null
} xor isNegated
val left = expression.left ?: return null
val right = expression.right ?: return null
fun createTarget(targetExpression: KtExpression, isNull: Boolean): NullCheck? {
val targetReferenceExpression = getTargetChain(targetExpression) ?: return null
return NullCheck(targetReferenceExpression, isNull)
}
return when {
left.isNullLiteral() -> createTarget(right, isNull)
right.isNullLiteral() -> createTarget(left, isNull)
else -> null
}
})
private class ContentCheck(val target: TargetChain, val call: KtCallExpression, val data: ContentFunction, val isPositiveCheck: Boolean)
private fun getContentCheck(expression: KtExpression) = unwrapNegation(expression, fun(expression, isNegated): ContentCheck? {
val (callExpression, target) = when (expression) {
is KtCallExpression -> expression to listOf(TargetChunk.ImplicitThis(expression))
is KtDotQualifiedExpression -> {
val targetChain = getTargetChain(expression.receiverExpression) ?: return null
(expression.selectorExpression as? KtCallExpression) to targetChain
}
else -> return null
}
val calleeText = callExpression?.calleeExpression?.text ?: return null
val contentFunction = contentCheckingFunctions[calleeText] ?: return null
return ContentCheck(target, callExpression, contentFunction, contentFunction.isPositiveCheck xor isNegated)
})
private class ReplaceFix(
private val functionName: String,
private val hasExplicitReceiver: Boolean,
private val isPositiveCheck: Boolean
) : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("replace.with.0.call", functionName)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val nullCheckExpression = descriptor.psiElement as? KtExpression ?: return
val binaryExpression = findBinaryExpression(nullCheckExpression) ?: return
val parenthesizedParent = binaryExpression.getTopmostParenthesizedParent() as? KtParenthesizedExpression
val expressionText = buildString {
if (isPositiveCheck) append("!")
if (hasExplicitReceiver) {
val receiverExpression = getReceiver(nullCheckExpression) ?: return
append(receiverExpression.text).append(".")
}
append(functionName).append("()")
}
val callExpression = KtPsiFactory(project).createExpression(expressionText)
when (nullCheckExpression.parenthesize()) {
binaryExpression.left -> binaryExpression.replace(callExpression)
binaryExpression.right -> {
val outerBinaryExpression = binaryExpression.parent as? KtBinaryExpression ?: return
val leftExpression = binaryExpression.left ?: return
binaryExpression.replace(leftExpression) // flag && a != null && a.isNotEmpty() -> flag && a.isNotEmpty()
outerBinaryExpression.right?.replace(callExpression) // flag && a.isNotEmpty() -> flag && !a.isNullOrEmpty()
}
}
if (parenthesizedParent != null && KtPsiUtil.areParenthesesUseless(parenthesizedParent)) {
parenthesizedParent.replace(parenthesizedParent.deparenthesize())
}
}
private fun getReceiver(expression: KtExpression?): KtExpression? = when {
expression is KtPrefixExpression && expression.operationToken == KtTokens.EXCL -> {
val baseExpression = expression.baseExpression?.deparenthesize()
if (baseExpression is KtExpression) getReceiver(baseExpression) else null
}
expression is KtBinaryExpression -> when {
expression.left?.isNullLiteral() == true -> expression.right
expression.right?.isNullLiteral() == true -> expression.left
else -> null
}
else -> null
}
}
private class ContentFunction(val isPositiveCheck: Boolean, val replacementName: String, vararg val callableNames: String)
companion object {
private val contentCheckingFunctions = mapOf(
"isEmpty" to ContentFunction(
isPositiveCheck = false, replacementName = "isNullOrEmpty",
"kotlin.collections.Collection.isEmpty",
"kotlin.collections.Map.isEmpty",
"kotlin.collections.isEmpty",
"kotlin.text.isEmpty"
),
"isBlank" to ContentFunction(
isPositiveCheck = false, replacementName = "isNullOrBlank",
"kotlin.text.isBlank"
),
"isNotEmpty" to ContentFunction(
isPositiveCheck = true, replacementName = "isNullOrEmpty",
"kotlin.collections.isNotEmpty",
"kotlin.text.isNotEmpty"
),
"isNotBlank" to ContentFunction(
isPositiveCheck = true, replacementName = "isNullOrBlank",
"kotlin.text.isNotBlank"
)
)
private fun findNullCheckExpression(unwrappedNullCheckExpression: KtExpression): KtExpression {
// Find topmost binary negation (!a), skipping intermediate parentheses, annotations and other miscellaneous expressions
var result = unwrappedNullCheckExpression
for (parent in unwrappedNullCheckExpression.parents) {
when (parent) {
!is KtExpression -> break
is KtPrefixExpression -> if (parent.operationToken != KtTokens.EXCL) break
else -> if (KtPsiUtil.deparenthesizeOnce(parent) === result) continue else break
}
result = parent
}
return result
}
private fun findBinaryExpression(nullCheckExpression: KtExpression): KtBinaryExpression? {
return nullCheckExpression.parenthesize().parent as? KtBinaryExpression
}
private fun findContentCheckExpression(nullCheckExpression: KtExpression, binaryExpression: KtBinaryExpression): KtExpression? {
// There's no polyadic expression in Kotlin, so nullability and emptiness checks might be in different 'KtBinaryExpression's
when (nullCheckExpression.parenthesize()) {
binaryExpression.left -> {
// [[a != null && a.isNotEmpty()] && flag] && flag2
return binaryExpression.right?.deparenthesize() as? KtExpression
}
binaryExpression.right -> {
// [[flag && flag2] && a != null] && a.isNotEmpty()
val outerBinaryExpression = binaryExpression.parent as? KtBinaryExpression
if (outerBinaryExpression != null && outerBinaryExpression.operationToken == binaryExpression.operationToken) {
return outerBinaryExpression.right?.deparenthesize() as? KtExpression
}
}
}
return null
}
}
}
private typealias TargetChain = List<TargetChunk>
private sealed class TargetChunk(val kind: Kind) {
enum class Kind { THIS, NAME }
class ExplicitThis(val expression: KtThisExpression) : TargetChunk(Kind.THIS) {
override val name: String?
get() = null
override fun resolve(bindingContext: BindingContext): Any? {
val descriptor = expression.getResolvedCall(bindingContext)?.resultingDescriptor
return (descriptor as? ReceiverParameterDescriptor)?.value ?: descriptor
}
override fun hasSmartCast(bindingContext: BindingContext): Boolean {
return bindingContext[BindingContext.SMARTCAST, expression] != null
}
}
class ImplicitThis(val expression: KtCallExpression) : TargetChunk(Kind.THIS) {
override val name: String?
get() = null
override fun resolve(bindingContext: BindingContext): Any? {
val resolvedCall = expression.getResolvedCall(bindingContext) ?: return null
return getSingleReceiver(resolvedCall.dispatchReceiver, resolvedCall.extensionReceiver)
}
override fun hasSmartCast(bindingContext: BindingContext): Boolean {
return bindingContext[BindingContext.IMPLICIT_RECEIVER_SMARTCAST, expression.calleeExpression] != null
}
}
class Name(val expression: KtNameReferenceExpression) : TargetChunk(Kind.NAME) {
override val name: String
get() = expression.getReferencedName()
override fun resolve(bindingContext: BindingContext) = bindingContext[BindingContext.REFERENCE_TARGET, expression]
override fun hasSmartCast(bindingContext: BindingContext): Boolean {
var current = expression.getQualifiedExpressionForSelectorOrThis()
while (true) {
if (bindingContext[BindingContext.SMARTCAST, current] != null) return true
current = current.getParenthesizedParent() ?: return false
}
}
}
abstract val name: String?
abstract fun resolve(bindingContext: BindingContext): Any?
abstract fun hasSmartCast(bindingContext: BindingContext): Boolean
}
private fun getSingleReceiver(dispatchReceiver: ReceiverValue?, extensionReceiver: ReceiverValue?): ReceiverValue? {
if (dispatchReceiver != null && extensionReceiver != null) {
// Sic! Functions such as 'isEmpty()' never have both dispatch and extension receivers
return null
}
return dispatchReceiver ?: extensionReceiver
}
private fun KtExpression.isNullLiteral(): Boolean {
return (deparenthesize() as? KtConstantExpression)?.text == KtTokens.NULL_KEYWORD.value
}
private fun KtExpression.getParenthesizedParent(): KtExpression? {
return (parent as? KtExpression)?.takeIf { KtPsiUtil.deparenthesizeOnce(it) === this }
}
private fun KtExpression.getTopmostParenthesizedParent(): KtExpression? {
var current = getParenthesizedParent() ?: return null
while (true) {
current = current.getParenthesizedParent() ?: break
}
return current
}
private fun KtExpression.parenthesize(): KtExpression {
return getTopmostParenthesizedParent() ?: this
}
|
apache-2.0
|
b7e5ff4592bc6502fea600fc79919032
| 47.297222 | 140 | 0.681755 | 5.624717 | false | false | false | false |
dhis2/dhis2-android-sdk
|
core/src/main/java/org/hisp/dhis/android/core/arch/storage/internal/Credentials.kt
|
1
|
2592
|
/*
* Copyright (c) 2004-2022, University of Oslo
* 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 the HISP project 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 OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.arch.storage.internal
import net.openid.appauth.AuthState
import org.hisp.dhis.android.core.arch.helpers.UserHelper
data class Credentials(
val username: String,
val serverUrl: String,
val password: String?,
val openIDConnectState: AuthState?
) {
fun getHash(): String? {
return password.let { UserHelper.md5(username, it) }
}
override fun equals(other: Any?) =
(other is Credentials) &&
username == other.username &&
password == other.password &&
serverUrl == other.serverUrl &&
openIDConnectState?.jsonSerializeString() == other.openIDConnectState?.jsonSerializeString()
override fun hashCode(): Int {
var result = username.hashCode()
result = 31 * result + serverUrl.hashCode()
result = 31 * result + (password?.hashCode() ?: 0)
result = 31 * result + (openIDConnectState?.jsonSerializeString()?.hashCode() ?: 0)
return result
}
}
|
bsd-3-clause
|
7aa1a2192523b625de28bfefbecdea51
| 44.473684 | 104 | 0.720293 | 4.531469 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.