repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/GithubAuthenticationManager.kt | 2 | 2450 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication
import com.intellij.collaboration.async.collectWithPrevious
import com.intellij.collaboration.async.disposingMainScope
import com.intellij.collaboration.auth.AccountsListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.annotations.RequiresEdt
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import java.awt.Component
/**
* Entry point for interactions with Github authentication subsystem
*/
@Deprecated("deprecated in favor of GHAccountsUtil")
class GithubAuthenticationManager internal constructor() {
private val accountManager: GHAccountManager get() = service()
@CalledInAny
fun getAccounts(): Set<GithubAccount> = accountManager.accountsState.value
@CalledInAny
fun hasAccounts() = accountManager.accountsState.value.isNotEmpty()
@RequiresEdt
@JvmOverloads
fun ensureHasAccounts(project: Project?, parentComponent: Component? = null): Boolean {
if (accountManager.accountsState.value.isNotEmpty()) return true
return GHAccountsUtil.requestNewAccount(project = project, parentComponent = parentComponent) != null
}
fun getSingleOrDefaultAccount(project: Project): GithubAccount? = GHAccountsUtil.getSingleOrDefaultAccount(project)
@Deprecated("replaced with stateFlow", ReplaceWith("accountManager.accountsState"))
@RequiresEdt
fun addListener(disposable: Disposable, listener: AccountsListener<GithubAccount>) {
disposable.disposingMainScope().launch {
accountManager.accountsState.collectWithPrevious(setOf()) { prev, current ->
listener.onAccountListChanged(prev, current)
current.forEach { acc ->
async {
accountManager.getCredentialsFlow(acc).collectLatest {
listener.onAccountCredentialsChanged(acc)
}
}
}
}
}
}
companion object {
@JvmStatic
fun getInstance(): GithubAuthenticationManager = service()
}
} | apache-2.0 | b05ce38952eb6081ce1ae52697a6f09d | 37.904762 | 140 | 0.780408 | 5.114823 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsQuickActionsToolbarPopup.kt | 6 | 5224 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.actions
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.HelpTooltip
import com.intellij.ide.actions.GotoClassPresentationUpdater.getActionTitlePluralized
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButtonWithText
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ui.configuration.actions.IconWithTextAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopup
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsActions
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.util.ui.JBInsets
import java.awt.Color
import java.awt.Insets
import java.awt.Point
import java.awt.event.MouseEvent
import javax.swing.FocusManager
import javax.swing.JComponent
/**
* Vcs quick popup action which is shown in the new toolbar and has two different presentations
* depending on vcs repo availability
*/
open class VcsQuickActionsToolbarPopup : IconWithTextAction(), CustomComponentAction, DumbAware {
inner class MyActionButtonWithText(
action: AnAction,
presentation: Presentation,
place: String,
) : ActionButtonWithText(action, presentation, place, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) {
override fun getInactiveTextColor(): Color = foreground
override fun getInsets(): Insets = JBInsets(0, 0, 0, 0)
override fun updateToolTipText() {
val shortcut = KeymapUtil.getShortcutText("Vcs.QuickListPopupAction")
val classesTabName = java.lang.String.join("/", getActionTitlePluralized())
if (Registry.`is`("ide.helptooltip.enabled")) {
HelpTooltip.dispose(this)
HelpTooltip()
.setTitle(ActionsBundle.message("action.Vcs.Toolbar.ShowMoreActions.description"))
.setShortcut(shortcut)
.installOn(this)
}
else {
toolTipText = ActionsBundle.message("action.Vcs.Toolbar.ShowMoreActions.description", shortcutText, classesTabName)
}
}
fun getShortcut(): String {
val shortcuts = KeymapUtil.getActiveKeymapShortcuts(VcsActions.VCS_OPERATIONS_POPUP).shortcuts
return KeymapUtil.getShortcutsText(shortcuts)
}
}
open fun getName(project: Project): String? {
return null
}
protected fun updateVcs(project: Project?, e: AnActionEvent): Boolean {
if (project == null || e.place !== ActionPlaces.MAIN_TOOLBAR || getName(project) == null ||
!ProjectLevelVcsManager.getInstance(project).checkVcsIsActive(getName(project))) {
e.presentation.isEnabledAndVisible = false
return false
}
return true
}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
return MyActionButtonWithText(this, presentation, place)
}
override fun actionPerformed(e: AnActionEvent) {
val group = DefaultActionGroup()
CustomActionsSchema.getInstance().getCorrectedAction(VcsActions.VCS_OPERATIONS_POPUP)?.let {
group.add(
it)
}
if (group.childrenCount == 0) return
val focusOwner = FocusManager.getCurrentManager().focusOwner
if (focusOwner == null) return
val dataContext = DataManager.getInstance().getDataContext(focusOwner)
val popup = JBPopupFactory.getInstance().createActionGroupPopup(
VcsBundle.message("action.Vcs.Toolbar.QuickListPopupAction.text"),
group, dataContext, JBPopupFactory.ActionSelectionAid.NUMBERING, true, null, -1,
{ action: AnAction? -> true }, ActionPlaces.RUN_TOOLBAR_LEFT_SIDE)
val component = e.inputEvent.component
popup.showUnderneathOf(component)
}
override fun update(e: AnActionEvent) {
val presentation = e.presentation
if (e.project == null ||
e.place !== ActionPlaces.MAIN_TOOLBAR || ProjectLevelVcsManager.getInstance(e.project!!).hasActiveVcss()) {
presentation.isEnabledAndVisible = false
return
}
presentation.isEnabledAndVisible = true
presentation.icon = AllIcons.Vcs.BranchNode
presentation.text = ActionsBundle.message("action.Vcs.Toolbar.ShowMoreActions.text") + " "
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
companion object {
private fun showPopup(e: AnActionEvent, popup: ListPopup) {
val mouseEvent = e.inputEvent
if (mouseEvent is MouseEvent) {
val source = mouseEvent.getSource()
if (source is JComponent) {
val topLeftCorner = source.locationOnScreen
val bottomLeftCorner = Point(topLeftCorner.x, topLeftCorner.y + source.height)
popup.setLocation(bottomLeftCorner)
popup.show(source)
}
}
}
}
} | apache-2.0 | e1fbada0cb9ca8635e80f0a8c36bc8d4 | 38.885496 | 140 | 0.746937 | 4.668454 | false | false | false | false |
idea4bsd/idea4bsd | platform/platform-impl/src/com/intellij/codeInsight/hints/filtering/MethodMatcher.kt | 2 | 3082 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hints.filtering
import com.intellij.openapi.util.Couple
interface ParamMatcher {
fun isMatching(paramNames: List<String>): Boolean
}
interface MethodMatcher {
fun isMatching(fullyQualifiedMethodName: String, paramNames: List<String>): Boolean
}
object AnyParamMatcher: ParamMatcher {
override fun isMatching(paramNames: List<String>) = true
}
class StringParamMatcher(private val paramMatchers: List<StringMatcher>): ParamMatcher {
override fun isMatching(paramNames: List<String>): Boolean {
if (paramNames.size != paramMatchers.size) {
return false
}
return paramMatchers
.zip(paramNames)
.find { !it.first.isMatching(it.second) } == null
}
}
class Matcher(private val methodNameMatcher: StringMatcher,
private val paramMatchers: ParamMatcher): MethodMatcher
{
override fun isMatching(fullyQualifiedMethodName: String, paramNames: List<String>): Boolean {
return methodNameMatcher.isMatching(fullyQualifiedMethodName) && paramMatchers.isMatching(paramNames)
}
}
object MatcherConstructor {
fun extract(matcher: String): Couple<String>? {
val trimmedMatcher = matcher.trim()
if (trimmedMatcher.isEmpty()) return null
val index = trimmedMatcher.indexOf('(')
if (index < 0) {
return Couple(trimmedMatcher, "")
}
else if (index == 0) {
return Couple("", trimmedMatcher)
}
val methodMatcher = trimmedMatcher.substring(0, index)
val paramsMatcher = trimmedMatcher.substring(index)
return Couple(methodMatcher.trim(), paramsMatcher.trim())
}
private fun createParametersMatcher(paramsMatcher: String): ParamMatcher? {
if (paramsMatcher.length <= 2) return null
val paramsString = paramsMatcher.substring(1, paramsMatcher.length - 1)
val params = paramsString.split(',').map(String::trim)
if (params.find(String::isEmpty) != null) return null
val matchers = params.mapNotNull { StringMatcherBuilder.create(it) }
return if (matchers.size == params.size) StringParamMatcher(matchers) else null
}
fun createMatcher(matcher: String): Matcher? {
val pair = extract(matcher) ?: return null
val methodNameMatcher = StringMatcherBuilder.create(pair.first) ?: return null
val paramMatcher = if (pair.second.isEmpty()) AnyParamMatcher else createParametersMatcher(pair.second)
return if (paramMatcher != null) Matcher(methodNameMatcher, paramMatcher) else null
}
}
| apache-2.0 | 48f712b4f032635332251c99612e747c | 31.104167 | 107 | 0.728748 | 4.460203 | false | false | false | false |
ZhangQinglian/dcapp | src/main/kotlin/com/zqlite/android/diycode/device/view/favorite/FavoritePresenter.kt | 1 | 3366 | /*
* Copyright 2017 zhangqinglian
*
* 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.zqlite.android.diycode.device.view.favorite
import com.zqlite.android.dclib.DiyCodeApi
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* Created by scott on 2017/8/19.
*/
class FavoritePresenter(val mView: FavoriteContract.View) : FavoriteContract.Presenter {
init {
mView.setPresenter(this)
}
private var mCurrentOffset = 0
private val LIMIT = 20
override fun start() {
}
override fun stop() {
}
override fun loadTopic(login: String,type :Int) {
when(type){
0->{
DiyCodeApi.getFavoriteTopics(login, 0, LIMIT).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
mView.loadFavoriteSuccess(it)
},
{
mView.loadFavoriteError()
}
)
}
1->{
DiyCodeApi.loadUserTopics(login, 0, LIMIT).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
mView.loadFavoriteSuccess(it)
},
{
mView.loadFavoriteError()
}
)
}
}
}
override fun loadNext(login: String,type:Int) {
val offset = mCurrentOffset + LIMIT
when(type){
0->{
DiyCodeApi.getFavoriteTopics(login, offset, LIMIT).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
if(it.isEmpty()){
return@subscribe
}
mView.loadFavoriteSuccess(it)
mCurrentOffset+=it.size
},
{
mView.loadFavoriteError()
}
)
}
1->{
DiyCodeApi.loadUserTopics(login, offset, LIMIT).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
if(it.isEmpty()){
return@subscribe
}
mView.loadFavoriteSuccess(it)
mCurrentOffset+=it.size
},
{
mView.loadFavoriteError()
}
)
}
}
}
} | apache-2.0 | 73464a40372e24ad14a6c1e6c809883b | 31.375 | 148 | 0.489008 | 5.619366 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToWithInfixFormInspection.kt | 4 | 2715 | // 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.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.calleeName
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.dotQualifiedExpressionVisitor
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ReplaceToWithInfixFormInspection : AbstractKotlinInspection() {
private val compatibleNames = setOf("to")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return dotQualifiedExpressionVisitor(fun(expression) {
val callExpression = expression.callExpression ?: return
if (callExpression.valueArguments.size != 1 || callExpression.typeArgumentList != null) return
if (expression.calleeName !in compatibleNames) return
val resolvedCall = expression.resolveToCall() ?: return
val function = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return
if (!function.isInfix) return
holder.registerProblem(
expression,
KotlinBundle.message("inspection.replace.to.with.infix.form.display.name"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceToWithInfixFormQuickfix()
)
})
}
}
class ReplaceToWithInfixFormQuickfix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.to.with.infix.form.quickfix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtDotQualifiedExpression
element.replace(
KtPsiFactory(element).createExpressionByPattern(
"$0 to $1", element.receiverExpression,
element.callExpression?.valueArguments?.get(0)?.getArgumentExpression() ?: return
)
)
}
}
| apache-2.0 | 502ffdc11273560322fe7e96deb977a7 | 43.508197 | 120 | 0.750645 | 5.261628 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/ImportInsertHelperImpl.kt | 1 | 23661 | // 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.util
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
import org.jetbrains.kotlin.idea.core.targetDescriptors
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.imports.getImportableTargets
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.project.findAnalyzerServices
import org.jetbrains.kotlin.idea.refactoring.fqName.isImported
import org.jetbrains.kotlin.idea.resolve.getLanguageVersionSettings
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.utils.*
import org.jetbrains.kotlin.scripting.definitions.ScriptDependenciesProvider
import org.jetbrains.kotlin.utils.addIfNotNull
class ImportInsertHelperImpl(private val project: Project) : ImportInsertHelper() {
private fun getCodeStyleSettings(contextFile: KtFile): KotlinCodeStyleSettings = contextFile.kotlinCustomSettings
override fun getImportSortComparator(contextFile: KtFile): Comparator<ImportPath> = ImportPathComparator(
getCodeStyleSettings(contextFile).PACKAGES_IMPORT_LAYOUT
)
override fun isImportedWithDefault(importPath: ImportPath, contextFile: KtFile): Boolean {
val languageVersionSettings = contextFile.getResolutionFacade().getLanguageVersionSettings()
val platform = TargetPlatformDetector.getPlatform(contextFile)
val analyzerServices = platform.findAnalyzerServices(contextFile.project)
val allDefaultImports = analyzerServices.getDefaultImports(languageVersionSettings, includeLowPriorityImports = true)
val scriptExtraImports = contextFile.takeIf { it.isScript() }?.let { ktFile ->
val scriptDependencies = ScriptDependenciesProvider.getInstance(ktFile.project)
?.getScriptConfiguration(ktFile.originalFile as KtFile)
scriptDependencies?.defaultImports?.map { ImportPath.fromString(it) }
}.orEmpty()
return importPath.isImported(allDefaultImports + scriptExtraImports, analyzerServices.excludedImports)
}
override fun isImportedWithLowPriorityDefaultImport(importPath: ImportPath, contextFile: KtFile): Boolean {
val platform = TargetPlatformDetector.getPlatform(contextFile)
val analyzerServices = platform.findAnalyzerServices(contextFile.project)
return importPath.isImported(analyzerServices.defaultLowPriorityImports, analyzerServices.excludedImports)
}
override fun mayImportOnShortenReferences(descriptor: DeclarationDescriptor, contextFile: KtFile): Boolean {
return when (descriptor.getImportableDescriptor()) {
is PackageViewDescriptor -> false // now package cannot be imported
is ClassDescriptor -> {
descriptor.getImportableDescriptor().containingDeclaration is PackageFragmentDescriptor || getCodeStyleSettings(contextFile).IMPORT_NESTED_CLASSES
}
else -> descriptor.getImportableDescriptor().containingDeclaration is PackageFragmentDescriptor // do not import members (e.g. java static members)
}
}
override fun importDescriptor(
element: KtElement,
descriptor: DeclarationDescriptor,
actionRunningMode: ActionRunningMode,
forceAllUnderImport: Boolean
): ImportDescriptorResult {
val importer = Importer(element, actionRunningMode)
return if (forceAllUnderImport) {
importer.importDescriptorWithStarImport(descriptor)
} else {
importer.importDescriptor(descriptor)
}
}
override fun importPsiClass(element: KtElement, psiClass: PsiClass, actionRunningMode: ActionRunningMode): ImportDescriptorResult {
return Importer(element, actionRunningMode).importPsiClass(psiClass)
}
private inner class Importer(
private val element: KtElement,
private val actionRunningMode: ActionRunningMode
) {
private val file = element.containingKtFile
private val resolutionFacade = file.getResolutionFacade()
private fun alreadyImported(target: DeclarationDescriptor, scope: LexicalScope, targetFqName: FqName): ImportDescriptorResult? {
val name = target.name
return when (target) {
is ClassifierDescriptorWithTypeParameters -> {
val classifiers = scope.findClassifiers(name, NoLookupLocation.FROM_IDE)
.takeIf { it.isNotEmpty() } ?: return null
if (classifiers.all { it is TypeAliasDescriptor }) {
return when {
classifiers.all { it.importableFqName == targetFqName } -> ImportDescriptorResult.ALREADY_IMPORTED
// no actual conflict
classifiers.size == 1 -> null
else -> ImportDescriptorResult.FAIL
}
}
// kotlin.collections.ArrayList is not a conflict, it's an alias to java.util.ArrayList
val nonAliasClassifiers = classifiers.filter { it !is TypeAliasDescriptor || it.importableFqName == targetFqName }
// top-level classifiers could/should be resolved with imports
if (nonAliasClassifiers.size > 1 && nonAliasClassifiers.all { it.containingDeclaration is PackageFragmentDescriptor }) {
return null
}
val classifier: ClassifierDescriptor = nonAliasClassifiers.singleOrNull() ?: return ImportDescriptorResult.FAIL
ImportDescriptorResult.ALREADY_IMPORTED.takeIf { classifier.importableFqName == targetFqName }
}
is FunctionDescriptor ->
ImportDescriptorResult.ALREADY_IMPORTED.takeIf { scope.findFunction(name, NoLookupLocation.FROM_IDE) { it.importableFqName == targetFqName } != null }
is PropertyDescriptor ->
ImportDescriptorResult.ALREADY_IMPORTED.takeIf { scope.findVariable(name, NoLookupLocation.FROM_IDE) { it.importableFqName == targetFqName } != null }
else -> null
}
}
private fun HierarchicalScope.findClassifiers(name: Name, location: LookupLocation): Set<ClassifierDescriptor> {
val result = mutableSetOf<ClassifierDescriptor>()
processForMeAndParent { it.getContributedClassifier(name, location)?.let(result::add) }
return result
}
fun importPsiClass(psiClass: PsiClass): ImportDescriptorResult {
val qualifiedName = psiClass.qualifiedName!!
val targetFqName = FqName(qualifiedName)
val name = Name.identifier(psiClass.name!!)
val scope = if (element == file) resolutionFacade.getFileResolutionScope(file) else element.getResolutionScope()
scope.findClassifier(name, NoLookupLocation.FROM_IDE)?.let {
return if (it.fqNameSafe == targetFqName) ImportDescriptorResult.ALREADY_IMPORTED else ImportDescriptorResult.FAIL
}
val imports = file.importDirectives
if (imports.any { !it.isAllUnder && (it.importPath?.alias == name || it.importPath?.fqName == targetFqName) }) {
return ImportDescriptorResult.FAIL
}
addImport(targetFqName, false)
return ImportDescriptorResult.IMPORT_ADDED
}
fun importDescriptor(descriptor: DeclarationDescriptor): ImportDescriptorResult {
val target = descriptor.getImportableDescriptor()
val name = target.name
val topLevelScope = resolutionFacade.getFileResolutionScope(file)
// check if import is not needed
val targetFqName = target.importableFqName ?: return ImportDescriptorResult.FAIL
val scope = if (element == file) topLevelScope else element.getResolutionScope()
alreadyImported(target, scope, targetFqName)?.let { return it }
val imports = file.importDirectives
if (imports.any { !it.isAllUnder && it.importPath?.fqName == targetFqName }) {
return ImportDescriptorResult.FAIL
}
// check there is an explicit import of a class/package with the same name already
val conflict = when (target) {
is ClassDescriptor -> topLevelScope.findClassifier(name, NoLookupLocation.FROM_IDE)
is PackageViewDescriptor -> topLevelScope.findPackage(name)
else -> null
}
if (conflict != null && imports.any {
!it.isAllUnder && it.importPath?.fqName == conflict.importableFqName && it.importPath?.importedName == name
}
) {
return ImportDescriptorResult.FAIL
}
val fqName = target.importableFqName!!
val containerFqName = fqName.parent()
val tryStarImport = shouldTryStarImport(containerFqName, target, imports) && when (target) {
// this check does not give a guarantee that import with * will import the class - for example,
// there can be classes with conflicting name in more than one import with *
is ClassifierDescriptorWithTypeParameters -> topLevelScope.findClassifier(name, NoLookupLocation.FROM_IDE) == null
is FunctionDescriptor, is PropertyDescriptor -> true
else -> error("Unknown kind of descriptor to import:$target")
}
if (tryStarImport) {
val result = addStarImport(target)
if (result != ImportDescriptorResult.FAIL) return result
}
return addExplicitImport(target)
}
fun importDescriptorWithStarImport(descriptor: DeclarationDescriptor): ImportDescriptorResult {
val target = descriptor.getImportableDescriptor()
val fqName = target.importableFqName ?: return ImportDescriptorResult.FAIL
val containerFqName = fqName.parent()
val imports = file.importDirectives
val starImportPath = ImportPath(containerFqName, true)
if (imports.any { it.importPath == starImportPath }) {
return alreadyImported(target, resolutionFacade.getFileResolutionScope(file), fqName) ?: ImportDescriptorResult.FAIL
}
if (!canImportWithStar(containerFqName, target)) return ImportDescriptorResult.FAIL
return addStarImport(target)
}
private fun shouldTryStarImport(
containerFqName: FqName,
target: DeclarationDescriptor,
imports: Collection<KtImportDirective>,
): Boolean {
if (!canImportWithStar(containerFqName, target)) return false
val starImportPath = ImportPath(containerFqName, true)
if (imports.any { it.importPath == starImportPath }) return false
val codeStyle = getCodeStyleSettings(file)
if (containerFqName.asString() in codeStyle.PACKAGES_TO_USE_STAR_IMPORTS) return true
val importsFromPackage = imports.count {
val path = it.importPath
path != null && !path.isAllUnder && !path.hasAlias() && path.fqName.parent() == containerFqName
}
val nameCountToUseStar = if (target.containingDeclaration is ClassDescriptor)
codeStyle.NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS
else
codeStyle.NAME_COUNT_TO_USE_STAR_IMPORT
return importsFromPackage + 1 >= nameCountToUseStar
}
private fun canImportWithStar(containerFqName: FqName, target: DeclarationDescriptor): Boolean {
if (containerFqName.isRoot) return false
val container = target.containingDeclaration
if (container is ClassDescriptor && container.kind == ClassKind.OBJECT) return false // cannot import with '*' from object
return true
}
private fun addStarImport(targetDescriptor: DeclarationDescriptor): ImportDescriptorResult {
val targetFqName = targetDescriptor.importableFqName!!
val parentFqName = targetFqName.parent()
val moduleDescriptor = resolutionFacade.moduleDescriptor
val scopeToImport = getMemberScope(parentFqName, moduleDescriptor) ?: return ImportDescriptorResult.FAIL
val filePackage = moduleDescriptor.getPackage(file.packageFqName)
fun isVisible(descriptor: DeclarationDescriptor): Boolean {
if (descriptor !is DeclarationDescriptorWithVisibility) return true
val visibility = descriptor.visibility
return !visibility.mustCheckInImports() || DescriptorVisibilities.isVisibleIgnoringReceiver(descriptor, filePackage)
}
val kindFilter = DescriptorKindFilter.ALL.withoutKinds(DescriptorKindFilter.PACKAGES_MASK)
val allNamesToImport = scopeToImport.getDescriptorsFiltered(kindFilter).filter(::isVisible).map { it.name }.toSet()
fun targetFqNameAndType(ref: KtReferenceExpression): Pair<FqName, Class<out Any>>? {
val descriptors = ref.resolveTargets()
val fqName: FqName? = descriptors.filter(::isVisible).map { it.importableFqName }.toSet().singleOrNull()
return if (fqName != null) {
Pair(fqName, descriptors.elementAt(0).javaClass)
} else null
}
val futureCheckMap = HashMap<KtSimpleNameExpression, Pair<FqName, Class<out Any>>>()
file.accept(object : KtVisitorVoid() {
override fun visitElement(element: PsiElement): Unit = element.acceptChildren(this)
override fun visitImportList(importList: KtImportList) {}
override fun visitPackageDirective(directive: KtPackageDirective) {}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val refName = expression.getReferencedNameAsName()
if (allNamesToImport.contains(refName)) {
val target = targetFqNameAndType(expression)
if (target != null) {
futureCheckMap += Pair(expression, target)
}
}
}
})
val addedImport = addImport(parentFqName, true)
if (alreadyImported(targetDescriptor, resolutionFacade.getFileResolutionScope(file), targetFqName) == null) {
actionRunningMode.runAction { addedImport.delete() }
return ImportDescriptorResult.FAIL
}
dropRedundantExplicitImports(parentFqName)
val conflicts = futureCheckMap
.mapNotNull { (expr, fqNameAndType) ->
if (targetFqNameAndType(expr) != fqNameAndType) fqNameAndType.first else null
}
.toSet()
fun isNotImported(fqName: FqName): Boolean {
return file.importDirectives.none { directive ->
!directive.isAllUnder && directive.alias == null && directive.importedFqName == fqName
}
}
for (conflict in conflicts.filter(::isNotImported)) {
addImport(conflict, false)
}
return ImportDescriptorResult.IMPORT_ADDED
}
private fun getMemberScope(fqName: FqName, moduleDescriptor: ModuleDescriptor): MemberScope? {
val packageView = moduleDescriptor.getPackage(fqName)
if (!packageView.isEmpty()) {
return packageView.memberScope
}
val parentScope = getMemberScope(fqName.parent(), moduleDescriptor) ?: return null
val classifier = parentScope.getContributedClassifier(fqName.shortName(), NoLookupLocation.FROM_IDE)
val classDescriptor = classifier as? ClassDescriptor ?: return null
return classDescriptor.defaultType.memberScope
}
private fun addExplicitImport(target: DeclarationDescriptor): ImportDescriptorResult {
if (target is ClassDescriptor || target is PackageViewDescriptor) {
val topLevelScope = resolutionFacade.getFileResolutionScope(file)
val name = target.name
// check if there is a conflicting class imported with * import
// (not with explicit import - explicit imports are checked before this method invocation)
val classifier = topLevelScope.findClassifier(name, NoLookupLocation.FROM_IDE)
if (classifier != null && detectNeededImports(listOf(classifier)).isNotEmpty()) {
return ImportDescriptorResult.FAIL
}
}
addImport(target.importableFqName!!, false)
return ImportDescriptorResult.IMPORT_ADDED
}
private fun dropRedundantExplicitImports(packageFqName: FqName) {
val dropCandidates = file.importDirectives.filter {
!it.isAllUnder && it.aliasName == null && it.importPath?.fqName?.parent() == packageFqName
}
val importsToCheck = ArrayList<FqName>()
for (import in dropCandidates) {
if (import.importedReference == null) continue
val targets = import.targetDescriptors()
if (targets.any { it is PackageViewDescriptor }) continue // do not drop import of package
val classDescriptor = targets.filterIsInstance<ClassDescriptor>().firstOrNull()
importsToCheck.addIfNotNull(classDescriptor?.importableFqName)
actionRunningMode.runAction { import.delete() }
}
if (importsToCheck.isNotEmpty()) {
val topLevelScope = resolutionFacade.getFileResolutionScope(file)
for (classFqName in importsToCheck) {
val classifier = topLevelScope.findClassifier(classFqName.shortName(), NoLookupLocation.FROM_IDE)
if (classifier?.importableFqName != classFqName) {
addImport(classFqName, false) // restore explicit import
}
}
}
}
private fun detectNeededImports(importedClasses: Collection<ClassifierDescriptor>): Set<ClassifierDescriptor> {
if (importedClasses.isEmpty()) return setOf()
val classesToCheck = importedClasses.associateByTo(mutableMapOf()) { it.name }
val result = LinkedHashSet<ClassifierDescriptor>()
file.accept(object : KtVisitorVoid() {
override fun visitElement(element: PsiElement) {
if (classesToCheck.isEmpty()) return
element.acceptChildren(this)
}
override fun visitImportList(importList: KtImportList) {
}
override fun visitPackageDirective(directive: KtPackageDirective) {
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
if (KtPsiUtil.isSelectorInQualified(expression)) return
val refName = expression.getReferencedNameAsName()
val descriptor = classesToCheck[refName]
if (descriptor != null) {
val targetFqName = targetFqName(expression)
if (targetFqName != null && targetFqName == DescriptorUtils.getFqNameSafe(descriptor)) {
classesToCheck.remove(refName)
result.add(descriptor)
}
}
}
})
return result
}
private fun targetFqName(ref: KtReferenceExpression): FqName? =
ref.resolveTargets().map { it.importableFqName }.toSet().singleOrNull()
private fun KtReferenceExpression.resolveTargets(): Collection<DeclarationDescriptor> =
this.getImportableTargets(resolutionFacade.analyze(this, BodyResolveMode.PARTIAL))
private fun addImport(fqName: FqName, allUnder: Boolean): KtImportDirective = actionRunningMode.runAction {
addImport(project, file, fqName, allUnder)
}
}
companion object {
fun addImport(project: Project, file: KtFile, fqName: FqName, allUnder: Boolean = false, alias: Name? = null): KtImportDirective {
val importPath = ImportPath(fqName, allUnder, alias)
val psiFactory = KtPsiFactory(project)
if (file is KtCodeFragment) {
val newDirective = psiFactory.createImportDirective(importPath)
file.addImportsFromString(newDirective.text)
return newDirective
}
val importList = file.importList
if (importList != null) {
val isInjectedScript = file.virtualFile is VirtualFileWindow && file.isScript()
val newDirective = psiFactory.createImportDirective(importPath)
val imports = importList.imports
return if (imports.isEmpty()) { //TODO: strange hack
importList.add(psiFactory.createNewLine())
(importList.add(newDirective) as KtImportDirective).also {
if (isInjectedScript) {
importList.add(psiFactory.createNewLine())
}
}
} else {
val importPathComparator = ImportInsertHelperImpl(project).getImportSortComparator(file)
val insertAfter = imports.lastOrNull {
val directivePath = it.importPath
directivePath != null && importPathComparator.compare(directivePath, importPath) <= 0
}
(importList.addAfter(newDirective, insertAfter) as KtImportDirective).also { insertedDirective ->
if (isInjectedScript) {
importList.addBefore(psiFactory.createNewLine(1), insertedDirective)
}
}
}
} else {
error("Trying to insert import $fqName into a file ${file.name} of type ${file::class.java} with no import list.")
}
}
}
}
| apache-2.0 | f535e0501b508fd062f6e52fafb79771 | 48.917722 | 170 | 0.645957 | 6.129793 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinInnerClassAllUsages.1.kt | 9 | 818 | package b
import a.Outer
public class KOuter : Outer() {
public inner class X(bar: String? = (this@KOuter as Outer).A().bar) : Outer.A() {
var next: Outer.A? = (this@KOuter as Outer).A()
val myBar: String? = (this@KOuter as Outer).A().bar
init {
(this@KOuter as Outer).A().bar = ""
}
fun foo(a: Outer.A) {
val aa: Outer.A = a
aa.bar = ""
}
fun getNext2(): Outer.A? {
return next
}
public override fun foo() {
super<Outer.A>.foo()
}
}
}
fun KOuter.X.bar(a: Outer.A = Outer().A()) {
}
fun Any.toA(): Outer.A? {
return if (this is Outer.A) this as Outer.A else null
}
fun Any.asServer(): Outer.A? {
return if (this is Outer.A) this as Outer.A else null
}
| apache-2.0 | 7451491021897d28bc9b4c41cf20cf78 | 19.974359 | 85 | 0.511002 | 3.182879 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/util/CoroutineFrameBuilder.kt | 5 | 9572 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.util
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl
import com.intellij.xdebugger.frame.XNamedValue
import com.sun.jdi.ObjectReference
import org.jetbrains.kotlin.idea.debugger.coroutine.data.*
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.ContinuationHolder
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.safeSkipCoroutineStackFrameProxy
import java.lang.Integer.min
class CoroutineFrameBuilder {
companion object {
val log by logger
private const val PRE_FETCH_FRAME_COUNT = 5
fun build(coroutine: CoroutineInfoData, suspendContext: SuspendContextImpl): CoroutineFrameItemLists? =
when {
coroutine.isRunning() -> buildStackFrameForActive(coroutine, suspendContext)
coroutine.isSuspended() -> CoroutineFrameItemLists(coroutine.stackTrace, coroutine.creationStackTrace)
else -> null
}
private fun buildStackFrameForActive(coroutine: CoroutineInfoData, suspendContext: SuspendContextImpl): CoroutineFrameItemLists? {
val activeThread = coroutine.activeThread ?: return null
val coroutineStackFrameList = mutableListOf<CoroutineStackFrameItem>()
val threadReferenceProxyImpl = ThreadReferenceProxyImpl(suspendContext.debugProcess.virtualMachineProxy, activeThread)
val realFrames = threadReferenceProxyImpl.forceFrames()
for (runningStackFrameProxy in realFrames) {
val preflightStackFrame = coroutineExitFrame(runningStackFrameProxy, suspendContext)
if (preflightStackFrame != null) {
buildRealStackFrameItem(preflightStackFrame.stackFrameProxy)?.let {
coroutineStackFrameList.add(it)
}
val coroutineFrameLists = build(preflightStackFrame, suspendContext)
coroutineStackFrameList.addAll(coroutineFrameLists.frames)
return CoroutineFrameItemLists(coroutineStackFrameList, coroutine.creationStackTrace)
} else {
buildRealStackFrameItem(runningStackFrameProxy)?.let {
coroutineStackFrameList.add(it)
}
}
}
return CoroutineFrameItemLists(coroutineStackFrameList, coroutine.creationStackTrace)
}
/**
* Used by CoroutineAsyncStackTraceProvider to build XFramesView
*/
fun build(preflightFrame: CoroutinePreflightFrame, suspendContext: SuspendContextImpl): CoroutineFrameItemLists {
val stackFrames = mutableListOf<CoroutineStackFrameItem>()
val (restoredStackTrace, _) = restoredStackTrace(
preflightFrame,
)
stackFrames.addAll(restoredStackTrace)
// @TODO perhaps we need to merge the dropped variables with the frame below...
val framesLeft = preflightFrame.threadPreCoroutineFrames
stackFrames.addAll(framesLeft.mapIndexedNotNull { _, stackFrameProxyImpl ->
suspendContext.invokeInManagerThread { buildRealStackFrameItem(stackFrameProxyImpl) }
})
return CoroutineFrameItemLists(stackFrames, preflightFrame.coroutineInfoData.creationStackTrace)
}
private fun restoredStackTrace(
preflightFrame: CoroutinePreflightFrame,
): Pair<List<CoroutineStackFrameItem>, List<XNamedValue>> {
val preflightFrameLocation = preflightFrame.stackFrameProxy.location()
val coroutineStackFrame = preflightFrame.coroutineInfoData.stackTrace
val preCoroutineTopFrameLocation = preflightFrame.threadPreCoroutineFrames.firstOrNull()?.location()
val variablesRemovedFromTopRestoredFrame = mutableListOf<XNamedValue>()
val stripTopStackTrace = coroutineStackFrame.dropWhile {
it.location.isFilterFromTop(preflightFrameLocation).apply {
if (this)
variablesRemovedFromTopRestoredFrame.addAll(it.spilledVariables)
}
}
// @TODO Need to merge variablesRemovedFromTopRestoredFrame into stripTopStackTrace.firstOrNull().spilledVariables
val variablesRemovedFromBottomRestoredFrame = mutableListOf<XNamedValue>()
val restoredFrames = when (preCoroutineTopFrameLocation) {
null -> stripTopStackTrace
else ->
stripTopStackTrace.dropLastWhile {
it.location.isFilterFromBottom(preCoroutineTopFrameLocation)
.apply { variablesRemovedFromBottomRestoredFrame.addAll(it.spilledVariables) }
}
}
return Pair(restoredFrames, variablesRemovedFromBottomRestoredFrame)
}
data class CoroutineFrameItemLists(
val frames: List<CoroutineStackFrameItem>,
val creationFrames: List<CreationCoroutineStackFrameItem>
) {
fun allFrames() =
frames + creationFrames
}
private fun buildRealStackFrameItem(
frame: StackFrameProxyImpl
): RunningCoroutineStackFrameItem? {
val location = frame.location() ?: return null
return if (!location.safeCoroutineExitPointLineNumber())
RunningCoroutineStackFrameItem(safeSkipCoroutineStackFrameProxy(frame), location)
else
null
}
/**
* Used by CoroutineStackFrameInterceptor to check if that frame is 'exit' coroutine frame.
*/
fun coroutineExitFrame(
frame: StackFrameProxyImpl,
suspendContext: SuspendContextImpl
): CoroutinePreflightFrame? {
return suspendContext.invokeInManagerThread {
val sem = frame.location().getSuspendExitMode()
val preflightStackFrame = if (sem.isCoroutineFound()) {
lookupContinuation(suspendContext, frame, sem)
} else
null
preflightStackFrame
}
}
fun lookupContinuation(
suspendContext: SuspendContextImpl,
frame: StackFrameProxyImpl,
mode: SuspendExitMode
): CoroutinePreflightFrame? {
if (!mode.isCoroutineFound())
return null
val theFollowingFrames = theFollowingFrames(frame) ?: emptyList()
if (mode.isSuspendMethodParameter()) {
if (theFollowingFrames.isNotEmpty()) {
// have to check next frame if that's invokeSuspend:-1 before proceed, otherwise skip
lookForTheFollowingFrame(theFollowingFrames) ?: return null
} else
return null
}
if (threadAndContextSupportsEvaluation(suspendContext, frame)) {
val context = suspendContext.executionContext() ?: return null
val continuation = when (mode) {
SuspendExitMode.SUSPEND_LAMBDA -> getThisContinuation(frame)
SuspendExitMode.SUSPEND_METHOD_PARAMETER -> getLVTContinuation(frame)
else -> null
} ?: return null
val continuationHolder = ContinuationHolder.instance(context)
val coroutineInfo = continuationHolder.extractCoroutineInfoData(continuation) ?: return null
return CoroutinePreflightFrame(
coroutineInfo,
frame,
theFollowingFrames,
mode,
coroutineInfo.topFrameVariables
)
}
return null
}
private fun lookForTheFollowingFrame(theFollowingFrames: List<StackFrameProxyImpl>): StackFrameProxyImpl? {
for (i in 0 until min(PRE_FETCH_FRAME_COUNT, theFollowingFrames.size)) { // pre-scan PRE_FETCH_FRAME_COUNT frames
val nextFrame = theFollowingFrames[i]
if (nextFrame.location().getSuspendExitMode() != SuspendExitMode.NONE) {
return nextFrame
}
}
return null
}
private fun getLVTContinuation(frame: StackFrameProxyImpl?) =
frame?.continuationVariableValue()
private fun getThisContinuation(frame: StackFrameProxyImpl?): ObjectReference? =
frame?.thisVariableValue()
private fun theFollowingFrames(frame: StackFrameProxyImpl): List<StackFrameProxyImpl>? {
val frames = frame.threadProxy().frames()
val indexOfCurrentFrame = frames.indexOf(frame)
if (indexOfCurrentFrame >= 0) {
val indexOfGetCoroutineSuspended = hasGetCoroutineSuspended(frames)
// @TODO if found - skip this thread stack
if (indexOfGetCoroutineSuspended < 0 && frames.size > indexOfCurrentFrame + 1)
return frames.drop(indexOfCurrentFrame + 1)
} else {
log.error("Frame isn't found on the thread stack.")
}
return null
}
}
}
| apache-2.0 | 0f9dd261b6f41cd51114fe3df60f67f1 | 46.386139 | 158 | 0.637275 | 6.326504 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/editor/quickDoc/OnMethodUsageWithCodeBlock.kt | 9 | 1205 | /**
* Some documentation.
*
* ```
* Code block
* Second line
*
* Third line
* ```
*
* Text between code blocks.
* ```
* ```
* Text after code block.
*/
fun testMethod() {
}
class C {
}
fun test() {
<caret>testMethod(1, "value")
}
//INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">fun</span> <span style="color:#000000;">testMethod</span>()<span style="">: </span><span style="color:#000000;">Unit</span></pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Some documentation.</p>
//INFO: <pre><code style='font-size:96%;'>
//INFO: <span style=""><span style="">Code block</span></span>
//INFO: <span style="">    <span style="">Second line</span></span>
//INFO:
//INFO: <span style=""><span style="">Third line</span></span>
//INFO: </code></pre><p>Text between code blocks.</p>
//INFO: <pre><code style='font-size:96%;'>
//INFO: </code></pre><p>Text after code block.</p></div><table class='sections'></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/> OnMethodUsageWithCodeBlock.kt<br/></div>
| apache-2.0 | fd939444fe1ceab90c84c5d048f8fbe0 | 33.428571 | 361 | 0.629876 | 3.10567 | false | true | false | false |
cy6erGn0m/kotlin-frontend-plugin | kotlin-frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/util/Runner.kt | 1 | 4944 | package org.jetbrains.kotlin.gradle.frontend.util
import net.rubygrapefruit.platform.*
import org.apache.tools.ant.taskdefs.condition.*
import org.gradle.api.*
import org.jetbrains.kotlin.utils.*
import java.io.*
import java.nio.*
import java.util.concurrent.*
fun ProcessBuilder.startWithRedirectOnFail(project: Project, name: String, exec: Executor = DummyExecutor): java.lang.Process {
require(command().isNotEmpty()) { "No command specified" }
val cmd = command().toList()
val process = Native.get(ProcessLauncher::class.java).let { l ->
addCommandPathToSystemPath()
if (Os.isFamily(Os.FAMILY_WINDOWS) && !cmd[0].endsWith(".exe")) {
command(listOf("cmd.exe", "/c") + cmd)
}
l.start(this)!!
}
val out = if (project.logger.isInfoEnabled) System.out else NullOutputStream
val buffered = OutputStreamWithBuffer(out, 8192)
val rc = try {
ProcessHandler(process, buffered, buffered, exec).startAndWaitFor()
} catch (t: Throwable) {
project.logger.error("Process ${command().first()} failed", t)
process.destroyForcibly()
-1
}
if (rc != 0) {
project.logger.error(buffered.lines().toString(Charsets.UTF_8))
project.logger.debug("Command failed (exit code = $rc): ${command().joinToString(" ")}")
throw GradleException("$name failed (exit code = $rc)")
}
return process
}
private object DummyExecutor : Executor {
override fun execute(command: Runnable) {
Thread(command).start()
}
}
private object NullOutputStream : OutputStream() {
override fun write(b: ByteArray?) {
}
override fun write(b: ByteArray?, off: Int, len: Int) {
}
override fun write(b: Int) {
}
}
internal class OutputStreamWithBuffer(out: OutputStream, sizeLimit: Int) : FilterOutputStream(out) {
private val buffer = ByteBuffer.allocate(sizeLimit)
@Synchronized
override fun write(b: Int) {
if (ensure(1) >= 1) {
buffer.put(b.toByte())
}
out.write(b)
}
override fun write(b: ByteArray) {
write(b, 0, b.size)
}
@Synchronized
override fun write(b: ByteArray, off: Int, len: Int) {
putOrRoll(b, off, len)
out.write(b, off, len)
}
@Synchronized
fun lines(): ByteArray = buffer.duplicate().let { it.flip(); ByteArray(it.remaining()).apply { it.get(this) } }
private fun putOrRoll(b: ByteArray, off: Int, len: Int) {
var pos = off
var rem = len
while (rem > 0) {
val count = ensure(rem)
buffer.put(b, pos, count)
pos += count
rem -= count
}
}
private fun ensure(count: Int): Int {
if (buffer.remaining() < count) {
val space = buffer.remaining()
buffer.flip()
while (buffer.hasRemaining() && buffer.position() + space < count) {
dropLine()
}
buffer.compact()
}
return Math.min(count, buffer.remaining())
}
private fun dropLine() {
while (buffer.hasRemaining()) {
if (buffer.get().toInt() == 0x0d) {
break
}
}
}
}
private class ProcessHandler(val process: java.lang.Process, private val out: OutputStream, private val err: OutputStream, private val exec: Executor) {
private val latch = CountDownLatch(1)
private var exitCode: Int = 0
private var exception: Throwable? = null
fun start() {
StreamForwarder(process.inputStream, out, exec).start()
StreamForwarder(process.errorStream, err, exec).start()
exec.execute {
try {
exitCode = process.waitFor()
} catch (t: Throwable) {
exception = t
} finally {
closeQuietly(process.inputStream)
closeQuietly(process.errorStream)
closeQuietly(process.outputStream)
latch.countDown()
}
}
}
fun waitFor(): Int {
latch.await()
exception?.let { throw it }
return exitCode
}
fun startAndWaitFor(): Int {
start()
return waitFor()
}
}
private class StreamForwarder(val source: InputStream, val destination: OutputStream, val exec: Executor) {
fun start() {
exec.execute {
try {
val buffer = ByteArray(4096)
do {
val rc = source.read(buffer)
if (rc == -1) {
break
}
destination.write(buffer, 0, rc)
if (source.available() == 0) {
destination.flush()
}
} while (true)
} catch (ignore: IOException) {
}
destination.flush()
}
}
} | apache-2.0 | da6ba96b5b22e48d9e50e03edda09ec3 | 26.17033 | 152 | 0.558657 | 4.321678 | false | false | false | false |
team4186/season-2017 | src/main/kotlin/org/usfirst/frc/team4186/extensions/command_builder.kt | 1 | 713 | package org.usfirst.frc.team4186.extensions
import edu.wpi.first.wpilibj.command.Command
import edu.wpi.first.wpilibj.command.CommandGroup
inline fun execute(
name: String,
block: CommandBuilder.() -> Unit
) = CommandBuilder(name).apply {
block()
}.target
class CommandBuilder(name: String) {
val target = CommandGroup(name)
operator fun Command.unaryPlus() = target.addParallel(this)
operator fun Command.unaryMinus() = target.addSequential(this)
operator fun Pair<Command, Double>.unaryPlus() = target.addParallel(first, second)
operator fun Pair<Command, Double>.unaryMinus() = target.addSequential(first, second)
infix fun Command.timeoutIn(timeout: Double) = Pair(this, timeout)
}
| mit | 06b95d4fdbe74ab1fb744a5d274b450f | 31.409091 | 87 | 0.757363 | 3.694301 | false | false | false | false |
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/HttpPageLoader.kt | 1 | 7887 | package eu.kanade.tachiyomi.ui.reader.loader
import eu.kanade.tachiyomi.data.cache.ChapterCache
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import eu.kanade.tachiyomi.util.plusAssign
import rx.Completable
import rx.Observable
import rx.schedulers.Schedulers
import rx.subjects.PublishSubject
import rx.subjects.SerializedSubject
import rx.subscriptions.CompositeSubscription
import timber.log.Timber
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.concurrent.PriorityBlockingQueue
import java.util.concurrent.atomic.AtomicInteger
/**
* Loader used to load chapters from an online source.
*/
class HttpPageLoader(
private val chapter: ReaderChapter,
private val source: HttpSource,
private val chapterCache: ChapterCache = Injekt.get()
) : PageLoader() {
/**
* A queue used to manage requests one by one while allowing priorities.
*/
private val queue = PriorityBlockingQueue<PriorityPage>()
/**
* Current active subscriptions.
*/
private val subscriptions = CompositeSubscription()
init {
subscriptions += Observable.defer { Observable.just(queue.take().page) }
.filter { it.status == Page.QUEUE }
.concatMap { source.fetchImageFromCacheThenNet(it) }
.repeat()
.subscribeOn(Schedulers.io())
.subscribe({
}, { error ->
if (error !is InterruptedException) {
Timber.e(error)
}
})
}
/**
* Recycles this loader and the active subscriptions and queue.
*/
override fun recycle() {
super.recycle()
subscriptions.unsubscribe()
queue.clear()
// Cache current page list progress for online chapters to allow a faster reopen
val pages = chapter.pages
if (pages != null) {
Completable
.fromAction {
// Convert to pages without reader information
val pagesToSave = pages.map { Page(it.index, it.url, it.imageUrl) }
chapterCache.putPageListToCache(chapter.chapter, pagesToSave)
}
.onErrorComplete()
.subscribeOn(Schedulers.io())
.subscribe()
}
}
/**
* Returns an observable with the page list for a chapter. It tries to return the page list from
* the local cache, otherwise fallbacks to network.
*/
override fun getPages(): Observable<List<ReaderPage>> {
return chapterCache
.getPageListFromCache(chapter.chapter)
.onErrorResumeNext { source.fetchPageList(chapter.chapter) }
.map { pages ->
pages.mapIndexed { index, page ->
// Don't trust sources and use our own indexing
ReaderPage(index, page.url, page.imageUrl)
}
}
}
/**
* Returns an observable that loads a page through the queue and listens to its result to
* emit new states. It handles re-enqueueing pages if they were evicted from the cache.
*/
override fun getPage(page: ReaderPage): Observable<Int> {
return Observable.defer {
val imageUrl = page.imageUrl
// Check if the image has been deleted
if (page.status == Page.READY && imageUrl != null && !chapterCache.isImageInCache(imageUrl)) {
page.status = Page.QUEUE
}
// Automatically retry failed pages when subscribed to this page
if (page.status == Page.ERROR) {
page.status = Page.QUEUE
}
val statusSubject = SerializedSubject(PublishSubject.create<Int>())
page.setStatusSubject(statusSubject)
if (page.status == Page.QUEUE) {
queue.offer(PriorityPage(page, 1))
}
preloadNextPages(page, 4)
statusSubject.startWith(page.status)
}
}
/**
* Preloads the given [amount] of pages after the [currentPage] with a lower priority.
*/
private fun preloadNextPages(currentPage: ReaderPage, amount: Int) {
val pageIndex = currentPage.index
val pages = currentPage.chapter.pages ?: return
if (pageIndex == pages.lastIndex) return
val nextPages = pages.subList(pageIndex + 1, Math.min(pageIndex + 1 + amount, pages.size))
for (nextPage in nextPages) {
if (nextPage.status == Page.QUEUE) {
queue.offer(PriorityPage(nextPage, 0))
}
}
}
/**
* Retries a page. This method is only called from user interaction on the viewer.
*/
override fun retryPage(page: ReaderPage) {
if (page.status == Page.ERROR) {
page.status = Page.QUEUE
}
queue.offer(PriorityPage(page, 2))
}
/**
* Data class used to keep ordering of pages in order to maintain priority.
*/
private data class PriorityPage(
val page: ReaderPage,
val priority: Int
) : Comparable<PriorityPage> {
companion object {
private val idGenerator = AtomicInteger()
}
private val identifier = idGenerator.incrementAndGet()
override fun compareTo(other: PriorityPage): Int {
val p = other.priority.compareTo(priority)
return if (p != 0) p else identifier.compareTo(other.identifier)
}
}
/**
* Returns an observable of the page with the downloaded image.
*
* @param page the page whose source image has to be downloaded.
*/
private fun HttpSource.fetchImageFromCacheThenNet(page: ReaderPage): Observable<ReaderPage> {
return if (page.imageUrl.isNullOrEmpty())
getImageUrl(page).flatMap { getCachedImage(it) }
else
getCachedImage(page)
}
private fun HttpSource.getImageUrl(page: ReaderPage): Observable<ReaderPage> {
page.status = Page.LOAD_PAGE
return fetchImageUrl(page)
.doOnError { page.status = Page.ERROR }
.onErrorReturn { null }
.doOnNext { page.imageUrl = it }
.map { page }
}
/**
* Returns an observable of the page that gets the image from the chapter or fallbacks to
* network and copies it to the cache calling [cacheImage].
*
* @param page the page.
*/
private fun HttpSource.getCachedImage(page: ReaderPage): Observable<ReaderPage> {
val imageUrl = page.imageUrl ?: return Observable.just(page)
return Observable.just(page)
.flatMap {
if (!chapterCache.isImageInCache(imageUrl)) {
cacheImage(page)
} else {
Observable.just(page)
}
}
.doOnNext {
page.stream = { chapterCache.getImageFile(imageUrl).inputStream() }
page.status = Page.READY
}
.doOnError { page.status = Page.ERROR }
.onErrorReturn { page }
}
/**
* Returns an observable of the page that downloads the image to [ChapterCache].
*
* @param page the page.
*/
private fun HttpSource.cacheImage(page: ReaderPage): Observable<ReaderPage> {
page.status = Page.DOWNLOAD_IMAGE
return fetchImage(page)
.doOnNext { chapterCache.putImageToCache(page.imageUrl!!, it) }
.map { page }
}
}
| apache-2.0 | ca6d1ebd97888266ecdf299c52ce578d | 33.744493 | 106 | 0.590339 | 4.988615 | false | false | false | false |
sksamuel/ktest | kotest-property/src/commonMain/kotlin/io/kotest/property/config.kt | 1 | 3048 | package io.kotest.property
import io.kotest.mpp.sysprop
import kotlin.math.max
import kotlin.native.concurrent.ThreadLocal
/**
* Global object for containing settings for property testing.
*/
@ThreadLocal
object PropertyTesting {
var maxFilterAttempts: Int = 10
var shouldPrintGeneratedValues: Boolean = sysprop("kotest.proptest.output.generated-values", "false") == "true"
var shouldPrintShrinkSteps: Boolean = sysprop("kotest.proptest.output.shrink-steps", "true") == "true"
var defaultIterationCount: Int = sysprop("kotest.proptest.default.iteration.count", "1000").toInt()
var edgecasesGenerationProbability: Double = sysprop("kotest.proptest.arb.edgecases-generation-probability", "0.02").toDouble()
var edgecasesBindDeterminism: Double = sysprop("kotest.proptest.arb.edgecases-bind-determinism", "0.9").toDouble()
}
/**
* Calculates the default iterations to use for a property test.
* This value is used when a property test does not specify the iteration count.
*
* This is the max of either the [PropertyTesting.defaultIterationCount] or the
* [calculateMinimumIterations] from the supplied gens.
*/
fun computeDefaultIteration(vararg gens: Gen<*>): Int =
max(PropertyTesting.defaultIterationCount, calculateMinimumIterations(*gens))
/**
* Calculates the minimum number of iterations required for the given generators.
*
* The value per generator is calcuated as:
* - for an [Exhaustive] the total number of values is used
* - for an [Arb] the number of edge cases is used
*
* In addition, if all generators are exhaustives, then the cartesian product is used.
*/
fun calculateMinimumIterations(vararg gens: Gen<*>): Int {
return when {
gens.all { it is Exhaustive } -> gens.fold(1) { acc, gen -> gen.minIterations() * acc }
else -> gens.fold(0) { acc, gen -> max(acc, gen.minIterations()) }
}
}
fun EdgeConfig.Companion.default(): EdgeConfig = EdgeConfig(
edgecasesGenerationProbability = PropertyTesting.edgecasesGenerationProbability
)
data class PropTest(
val seed: Long? = null,
val minSuccess: Int = Int.MAX_VALUE,
val maxFailure: Int = 0,
val shrinkingMode: ShrinkingMode = ShrinkingMode.Bounded(1000),
val iterations: Int? = null,
val listeners: List<PropTestListener> = listOf(),
val edgeConfig: EdgeConfig = EdgeConfig.default()
)
fun PropTest.toPropTestConfig() =
PropTestConfig(
seed = seed,
minSuccess = minSuccess,
maxFailure = maxFailure,
iterations = iterations,
shrinkingMode = shrinkingMode,
listeners = listeners,
edgeConfig = edgeConfig
)
data class PropTestConfig(
val seed: Long? = null,
val minSuccess: Int = Int.MAX_VALUE,
val maxFailure: Int = 0,
val shrinkingMode: ShrinkingMode = ShrinkingMode.Bounded(1000),
val iterations: Int? = null,
val listeners: List<PropTestListener> = listOf(),
val edgeConfig: EdgeConfig = EdgeConfig.default()
)
interface PropTestListener {
suspend fun beforeTest(): Unit = Unit
suspend fun afterTest(): Unit = Unit
}
| mit | b588e08d14144ebf6b89dbf255697222 | 35.285714 | 130 | 0.72769 | 4.130081 | false | true | false | false |
DarkToast/JavaDeepDive | src/main/kotlin/deepdive/functional/monads/Option.kt | 1 | 1112 | package deepdive.functional.monads
sealed class Option<T> {
abstract fun <U> map( f: (T) -> U ): Option<U>
abstract fun <U> flatMap( f: (T) -> Option<U> ): Option<U>
abstract fun get(): T?
abstract fun isPresent(): Boolean
abstract fun getOrElse(fallbackValue: T): T
companion object {
fun <T> of(value: T): Option<T> {
return if(value == null) None() else Some(value)
}
}
}
class Some<T> (private val value: T) : Option<T>() {
override fun <U> map( f: (T) -> U ): Option<U> = Option.of( f(value) )
override fun <U> flatMap( f: (T) -> Option<U> ): Option<U> = f(value)
override fun get(): T? = value
override fun isPresent(): Boolean = true
override fun getOrElse(fallbackValue: T): T = value
}
class None<T>: Option<T>() {
override fun <U> map( f: (T) -> U ): Option<U> = this as None<U>
override fun <U> flatMap( f: (T) -> Option<U> ): Option<U> = this as None<U>
override fun get(): T? = null
override fun isPresent(): Boolean = true
override fun getOrElse(fallbackValue: T): T = fallbackValue
} | gpl-3.0 | 7dbe588eaa71caaf00bca94a2e043970 | 23.733333 | 80 | 0.589029 | 3.299703 | false | false | false | false |
aosp-mirror/platform_frameworks_support | paging/common/src/test/java/androidx/paging/Executors.kt | 1 | 1315 | /*
* 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.paging
import org.junit.Assert.fail
import java.util.LinkedList
import java.util.concurrent.Executor
class TestExecutor : Executor {
private val mTasks = LinkedList<Runnable>()
override fun execute(runnable: Runnable) {
mTasks.add(runnable)
}
internal fun executeAll(): Boolean {
val consumed = !mTasks.isEmpty()
var task = mTasks.poll()
while (task != null) {
task.run()
task = mTasks.poll()
}
return consumed
}
}
class FailExecutor(val string: String = "Executor expected to be unused") : Executor {
override fun execute(runnable: Runnable?) {
fail(string)
}
}
| apache-2.0 | 126382b75ab341f92d99d4b31746adcc | 27.586957 | 86 | 0.680608 | 4.201278 | false | false | false | false |
breadwallet/breadwallet-android | app-core/src/main/java/com/breadwallet/tools/manager/BRSharedPrefs.kt | 1 | 23948 | /**
* BreadWallet
*
* Created by Mihail Gutan <[email protected]> on 6/13/16.
* Copyright (c) 2016 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.tools.manager
import android.content.Context
import android.content.SharedPreferences
import android.text.format.DateUtils
import androidx.annotation.VisibleForTesting
import androidx.core.content.edit
import com.breadwallet.app.Conversion
import com.breadwallet.model.PriceAlert
import com.breadwallet.tools.util.Bip39Reader
import com.breadwallet.tools.util.ServerBundlesHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import java.util.Currency
import java.util.Locale
import java.util.UUID
// Suppress warnings about context usage, it remains to support legacy coe.
@Suppress("UNUSED_PARAMETER")
object BRSharedPrefs {
val TAG: String = BRSharedPrefs::class.java.name
const val PREFS_NAME = "MyPrefsFile"
private const val FCM_TOKEN = "fcmToken"
private const val NOTIFICATION_ID = "notificationId"
private const val SCREEN_HEIGHT = "screenHeight"
private const val SCREEN_WIDTH = "screenWidth"
private const val BUNDLE_HASH_PREFIX = "bundleHash_"
private const val SEGWIT = "segwit"
private const val EMAIL_OPT_IN = "emailOptIn"
private const val EMAIL_OPT_IN_DISMISSED = "emailOptInDismissed"
private const val CURRENT_CURRENCY = "currentCurrency"
private const val PAPER_KEY_WRITTEN_DOWN = "phraseWritten"
private const val PREFER_STANDARD_FEE = "favorStandardFee"
private const val FEE_PREFERENCE = "feePreference"
private const val LAST_GIFT_CHECK_TIME = "lastGiftCheckTime"
@VisibleForTesting
const val RECEIVE_ADDRESS = "receive_address"
private const val FEE_RATE = "feeRate"
private const val ECONOMY_FEE_RATE = "economyFeeRate"
private const val BALANCE = "balance"
private const val SECURE_TIME = "secureTime"
private const val LAST_SYNC_TIME_PREFIX = "lastSyncTime_"
private const val LAST_RESCAN_MODE_USED_PREFIX = "lastRescanModeUsed_"
private const val LAST_SEND_TRANSACTION_BLOCK_HEIGHT_PREFIX = "lastSendTransactionBlockheight_"
private const val FEE_TIME_PREFIX = "feeTime_"
private const val ALLOW_SPEND_PREFIX = "allowSpend_"
private const val IS_CRYPTO_PREFERRED = "priceInCrypto"
private const val USE_FINGERPRINT = "useFingerprint"
private const val CURRENT_WALLET_CURRENCY_CODE = "currentWalletIso"
private const val WALLET_REWARD_ID = "walletRewardId"
private const val GEO_PERMISSIONS_REQUESTED = "geoPermissionsRequested"
private const val START_HEIGHT_PREFIX = "startHeight_"
private const val RESCAN_TIME_PREFIX = "rescanTime_"
private const val LAST_BLOCK_HEIGHT_PREFIX = "lastBlockHeight_"
private const val SCAN_RECOMMENDED_PREFIX = "scanRecommended_"
private const val PREFORK_SYNCED = "preforkSynced"
private const val CURRENCY_UNIT = "currencyUnit"
private const val USER_ID = "userId"
private const val SHOW_NOTIFICATION = "showNotification"
private const val SHARE_DATA = "shareData"
private const val NEW_WALLET = "newWallet"
private const val PROMPT_PREFIX = "prompt_"
private const val TRUST_NODE_PREFIX = "trustNode_"
private const val DEBUG_HOST = "debug_host"
private const val DEBUG_SERVER_BUNDLE = "debug_server_bundle"
private const val DEBUG_WEB_PLATFORM_URL = "debug_web_platform_url"
private const val HTTP_SERVER_PORT = "http_server_port"
private const val REWARDS_ANIMATION_SHOWN = "rewardsAnimationShown"
private const val READ_IN_APP_NOTIFICATIONS = "readInAppNotifications"
private const val PRICE_ALERTS = "priceAlerts"
private const val PRICE_ALERTS_INTERVAL = "priceAlertsInterval"
private const val LANGUAGE = "language"
private const val UNLOCK_WITH_FINGERPRINT = "unlock-with-fingerprint"
private const val CONFIRM_SEND_WITH_FINGERPRINT = "confirm-send-with-fingerprint"
private const val TRACKED_TRANSACTIONS = "tracked-transactions"
private const val APP_RATE_PROMPT_DONT_ASK_AGAIN = "app-rate-prompt-dont-ask-again"
private const val APP_RATE_PROMPT_SHOULD_PROMPT = "app-rate-prompt-should-prompt"
private const val APP_RATE_PROMPT_SHOULD_PROMPT_DEBUG = "app-rate-prompt-should-prompt-debug"
const val APP_FOREGROUNDED_COUNT = "appForegroundedCount"
const val APP_RATE_PROMPT_HAS_RATED = "appReviewPromptHasRated"
private val secureTimeFlow = MutableSharedFlow<Long>(replay = 1)
/**
* Call when Application is initialized to setup [brdPrefs].
* This removes the need for a context parameter.
*/
fun initialize(context: Context, applicationScope: CoroutineScope) {
brdPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
applicationScope.launch {
_trackedConversionChanges.value = getTrackedConversions()
secureTimeFlow.tryEmit(getSecureTime())
}
}
private lateinit var brdPrefs: SharedPreferences
private val promptChangeChannel = BroadcastChannel<Unit>(Channel.CONFLATED)
var lastGiftCheckTime: Long
get() = brdPrefs.getLong(LAST_GIFT_CHECK_TIME, 0L)
set(value) {
brdPrefs.edit { putLong(LAST_GIFT_CHECK_TIME, value) }
}
var phraseWroteDown: Boolean
get() = brdPrefs.getBoolean(PAPER_KEY_WRITTEN_DOWN, false)
set(value) {
brdPrefs.edit { putBoolean(PAPER_KEY_WRITTEN_DOWN, value) }
}
@JvmStatic
fun getPreferredFiatIso(): String =
brdPrefs.getString(
CURRENT_CURRENCY, try {
Currency.getInstance(Locale.getDefault()).currencyCode
} catch (e: IllegalArgumentException) {
e.printStackTrace()
Currency.getInstance(Locale.US).currencyCode
}
)!!
fun putPreferredFiatIso(iso: String) =
brdPrefs.edit {
val default = if (iso.equals(Locale.getDefault().isO3Language, ignoreCase = true)) {
null
} else iso
putString(CURRENT_CURRENCY, default)
}
fun getReceiveAddress(iso: String): String? =
brdPrefs.getString(RECEIVE_ADDRESS + iso.toUpperCase(), "")
fun putReceiveAddress(tmpAddr: String, iso: String) =
brdPrefs.edit { putString(RECEIVE_ADDRESS + iso.toUpperCase(), tmpAddr) }
@JvmStatic
fun getSecureTime() =
brdPrefs.getLong(SECURE_TIME, System.currentTimeMillis())
//secure time from the server
fun putSecureTime(date: Long) {
brdPrefs.edit { putLong(SECURE_TIME, date) }
secureTimeFlow.tryEmit(date)
}
fun secureTimeFlow(): Flow<Long> {
return secureTimeFlow
}
fun getLastSyncTime(iso: String) =
brdPrefs.getLong(LAST_SYNC_TIME_PREFIX + iso.toUpperCase(), 0)
fun putLastSyncTime(iso: String, time: Long) =
brdPrefs.edit { putLong(LAST_SYNC_TIME_PREFIX + iso.toUpperCase(), time) }
fun getLastSendTransactionBlockheight(iso: String) =
brdPrefs.getLong(LAST_SEND_TRANSACTION_BLOCK_HEIGHT_PREFIX + iso.toUpperCase(), 0)
fun putLastSendTransactionBlockheight(
iso: String,
blockHeight: Long
) = brdPrefs.edit {
putLong(LAST_SEND_TRANSACTION_BLOCK_HEIGHT_PREFIX + iso.toUpperCase(), blockHeight)
}
//if the user prefers all in crypto units, not fiat currencies
fun isCryptoPreferred(context: Context? = null): Boolean =
brdPrefs.getBoolean(IS_CRYPTO_PREFERRED, false)
//if the user prefers all in crypto units, not fiat currencies
fun setIsCryptoPreferred(b: Boolean) =
brdPrefs.edit { putBoolean(IS_CRYPTO_PREFERRED, b) }
fun getUseFingerprint(): Boolean =
brdPrefs.getBoolean(USE_FINGERPRINT, false)
fun putUseFingerprint(use: Boolean) =
brdPrefs.edit { putBoolean(USE_FINGERPRINT, use) }
fun getFeatureEnabled(feature: String): Boolean =
brdPrefs.getBoolean(feature, false)
fun putFeatureEnabled(enabled: Boolean, feature: String) =
brdPrefs.edit { putBoolean(feature, enabled) }
@JvmStatic
fun getWalletRewardId(): String? =
brdPrefs.getString(WALLET_REWARD_ID, null)
fun putWalletRewardId(id: String) =
brdPrefs.edit { putString(WALLET_REWARD_ID, id) }
fun getGeoPermissionsRequested(): Boolean =
brdPrefs.getBoolean(GEO_PERMISSIONS_REQUESTED, false)
fun putGeoPermissionsRequested(requested: Boolean) =
brdPrefs.edit { putBoolean(GEO_PERMISSIONS_REQUESTED, requested) }
fun getStartHeight(iso: String): Long =
brdPrefs.getLong(START_HEIGHT_PREFIX + iso.toUpperCase(), 0)
fun putStartHeight(iso: String, startHeight: Long) =
brdPrefs.edit { putLong(START_HEIGHT_PREFIX + iso.toUpperCase(), startHeight) }
fun getLastRescanTime(iso: String): Long =
brdPrefs.getLong(RESCAN_TIME_PREFIX + iso.toUpperCase(), 0)
fun putLastRescanTime(iso: String, time: Long) =
brdPrefs.edit { putLong(RESCAN_TIME_PREFIX + iso.toUpperCase(), time) }
fun getLastBlockHeight(iso: String): Int =
brdPrefs.getInt(LAST_BLOCK_HEIGHT_PREFIX + iso.toUpperCase(), 0)
fun putLastBlockHeight(iso: String, lastHeight: Int) =
brdPrefs.edit {
putInt(LAST_BLOCK_HEIGHT_PREFIX + iso.toUpperCase(), lastHeight)
}
fun getScanRecommended(iso: String): Boolean =
brdPrefs.getBoolean(SCAN_RECOMMENDED_PREFIX + iso.toUpperCase(), false)
fun putScanRecommended(iso: String, recommended: Boolean) =
brdPrefs.edit {
putBoolean(SCAN_RECOMMENDED_PREFIX + iso.toUpperCase(), recommended)
}
@JvmStatic
fun getDeviceId(): String =
brdPrefs.run {
if (contains(USER_ID)) {
getString(USER_ID, "")!!
} else {
UUID.randomUUID().toString().also {
edit { putString(USER_ID, it) }
}
}
}
fun getDebugHost(): String? =
brdPrefs.getString(DEBUG_HOST, "")
fun putDebugHost(host: String) =
brdPrefs.edit { putString(DEBUG_HOST, host) }
fun clearAllPrefs() = brdPrefs.edit { clear() }
@JvmStatic
fun getShowNotification(): Boolean =
brdPrefs.getBoolean(SHOW_NOTIFICATION, true)
@JvmStatic
fun putShowNotification(show: Boolean) =
brdPrefs.edit { putBoolean(SHOW_NOTIFICATION, show) }
fun getShareData(): Boolean =
brdPrefs.getBoolean(SHARE_DATA, true)
fun putShareData(show: Boolean) =
brdPrefs.edit { putBoolean(SHARE_DATA, show) }
fun getPromptDismissed(promptName: String): Boolean =
brdPrefs.getBoolean(PROMPT_PREFIX + promptName, false)
fun putPromptDismissed(promptName: String, dismissed: Boolean) =
brdPrefs.edit { putBoolean(PROMPT_PREFIX + promptName, dismissed) }
fun getTrustNode(iso: String): String? =
brdPrefs.getString(TRUST_NODE_PREFIX + iso.toUpperCase(), "")
fun putTrustNode(iso: String, trustNode: String) =
brdPrefs.edit { putString(TRUST_NODE_PREFIX + iso.toUpperCase(), trustNode) }
fun putFCMRegistrationToken(token: String) =
brdPrefs.edit { putString(FCM_TOKEN, token) }
fun getFCMRegistrationToken(): String? =
brdPrefs.getString(FCM_TOKEN, "")
fun putNotificationId(notificationId: Int) =
brdPrefs.edit { putInt(NOTIFICATION_ID, notificationId) }
fun getNotificationId(): Int =
brdPrefs.getInt(NOTIFICATION_ID, 0)
fun putScreenHeight(screenHeight: Int) =
brdPrefs.edit { putInt(SCREEN_HEIGHT, screenHeight) }
@JvmStatic
fun getScreenHeight(): Int =
brdPrefs.getInt(SCREEN_HEIGHT, 0)
fun putScreenWidth(screenWidth: Int) =
brdPrefs.edit { putInt(SCREEN_WIDTH, screenWidth) }
@JvmStatic
fun getScreenWidth(): Int =
brdPrefs.getInt(SCREEN_WIDTH, 0)
@JvmStatic
fun putBundleHash(bundleName: String, bundleHash: String) =
brdPrefs.edit { putString(BUNDLE_HASH_PREFIX + bundleName, bundleHash) }
@JvmStatic
fun getBundleHash(bundleName: String): String? =
brdPrefs.getString(BUNDLE_HASH_PREFIX + bundleName, null)
fun putIsSegwitEnabled(isEnabled: Boolean) =
brdPrefs.edit { putBoolean(SEGWIT, isEnabled) }
fun getIsSegwitEnabled(): Boolean =
brdPrefs.getBoolean(SEGWIT, false)
fun putEmailOptIn(hasOpted: Boolean) =
brdPrefs.edit { putBoolean(EMAIL_OPT_IN, hasOpted) }
fun getEmailOptIn(): Boolean =
brdPrefs.getBoolean(EMAIL_OPT_IN, false)
fun putRewardsAnimationShown(wasShown: Boolean) =
brdPrefs.edit { putBoolean(REWARDS_ANIMATION_SHOWN, wasShown) }
fun getRewardsAnimationShown(): Boolean =
brdPrefs.getBoolean(REWARDS_ANIMATION_SHOWN, false)
fun putEmailOptInDismissed(dismissed: Boolean) =
brdPrefs.edit { putBoolean(EMAIL_OPT_IN_DISMISSED, dismissed) }
fun getEmailOptInDismissed(): Boolean =
brdPrefs.getBoolean(EMAIL_OPT_IN_DISMISSED, false)
/**
* Get the debug bundle from shared preferences or empty if not available.
*
* @param bundleType Bundle type.
* @return Saved debug bundle or empty.
*/
@JvmStatic
fun getDebugBundle(bundleType: ServerBundlesHelper.Type): String? =
brdPrefs.getString(DEBUG_SERVER_BUNDLE + bundleType.name, "")
/**
* Save the bundle to use in debug mode.
*
* @param context Execution context.
* @param bundleType Bundle type.
* @param bundle Debug bundle.
*/
@JvmStatic
fun putDebugBundle(
bundleType: ServerBundlesHelper.Type,
bundle: String
) = brdPrefs.edit { putString(DEBUG_SERVER_BUNDLE + bundleType.name, bundle) }
/**
* Get the web platform debug URL from shared preferences or empty, if not available.
*
* @param context Execution context.
* @return Returns the web platform debug URL or empty.
*/
@JvmStatic
fun getWebPlatformDebugURL(): String =
brdPrefs.getString(DEBUG_WEB_PLATFORM_URL, "")!!
/**
* Saves the web platform debug URL to the shared preferences.
*
* @param context Execution context.
* @param webPlatformDebugURL The web platform debug URL to be persisted.
*/
@JvmStatic
fun putWebPlatformDebugURL(webPlatformDebugURL: String) =
brdPrefs.edit { putString(DEBUG_WEB_PLATFORM_URL, webPlatformDebugURL) }
/**
* Get the port that was used to start the HTTPServer.
*
* @param context Execution context.
* @return The last port used to start the HTTPServer.
*/
@JvmStatic
fun getHttpServerPort(): Int =
brdPrefs.getInt(HTTP_SERVER_PORT, 0)
/**
* Save the port used to start the HTTPServer.
*
* @param context Execution context.
* @param port Port used when starting the HTTPServer
*/
@JvmStatic
fun putHttpServerPort(port: Int) =
brdPrefs.edit { putInt(HTTP_SERVER_PORT, port) }
/**
* Save the given in-app notification id into the collection of read message.
*
* @param context Execution context.
* @param notificationId The id of the message that has been read.
*/
fun putReadInAppNotificationId(notificationId: String) {
val readIds = getReadInAppNotificationIds()
brdPrefs.edit {
if (!readIds.contains(notificationId)) {
putStringSet(READ_IN_APP_NOTIFICATIONS, readIds + notificationId)
}
}
}
/**
* Get the ids of the in-app notification that has been read.
*
* @param context Execution context.
* @return A set with the ids of the messages that has been read.
*/
fun getReadInAppNotificationIds(): Set<String> =
brdPrefs.getStringSet(READ_IN_APP_NOTIFICATIONS, emptySet()) ?: emptySet()
/**
* Save an int with the given key in the shared preferences.
*
* @param context Execution context.
* @param key The name of the preference.
* @param value The new value for the preference.
*/
fun putInt(key: String, value: Int) =
brdPrefs.edit { putInt(key, value) }
/**
* Retrieve an int value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defaultValue Value to return if this preference does not exist.
* @param context Execution context.
* @param key The name of the preference.
* @param defaultValue The default value to return if not present.
* @return Returns the preference value if it exists, or defValue.
*/
fun getInt(key: String, defaultValue: Int): Int =
brdPrefs.getInt(key, defaultValue)
/**
* Save an boolean with the given key in the shared preferences.
*
* @param context Execution context.
* @param key The name of the preference.
* @param value The new value for the preference.
*/
fun putBoolean(key: String, value: Boolean) =
brdPrefs.edit { putBoolean(key, value) }
/**
* Retrieve an boolean value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defaultValue Value to return if this preference does not exist.
* @param context Execution context.
* @param key The name of the preference.
* @param defaultValue The default value to return if not present.
* @return Returns the preference value if it exists, or defValue.
*/
fun getBoolean(key: String, defaultValue: Boolean): Boolean =
brdPrefs.getBoolean(key, defaultValue)
/**
* Gets the set of user defined price alerts.
*/
fun getPriceAlerts(): Set<PriceAlert> = emptySet()
/**
* Save a set of user defined price alerts.
*/
fun putPriceAlerts(priceAlerts: Set<PriceAlert>) = Unit
/**
* Gets the user defined interval in minutes between price
* alert checks.
*/
fun getPriceAlertsInterval() =
brdPrefs.getInt(PRICE_ALERTS_INTERVAL, 15)
/**
* Sets the user defined interval in minutes between price
* alert checks.
*/
fun putPriceAlertsInterval(interval: Int) =
brdPrefs.edit { putInt(PRICE_ALERTS_INTERVAL, interval) }
/** The user's language string as provided by [Locale.getLanguage]. */
var recoveryKeyLanguage: String
get() = brdPrefs.getString(LANGUAGE, Locale.getDefault().language)!!
set(value) {
val isLanguageValid = Bip39Reader.SupportedLanguage.values().any { lang ->
lang.toString() == value
}
brdPrefs.edit {
if (isLanguageValid) {
putString(LANGUAGE, value)
} else {
putString(LANGUAGE, Bip39Reader.SupportedLanguage.EN.toString())
}
}
}
/** Preference to unlock the app using the fingerprint sensor */
var unlockWithFingerprint: Boolean
get() = brdPrefs.getBoolean(UNLOCK_WITH_FINGERPRINT, getUseFingerprint())
set(value) = brdPrefs.edit {
putBoolean(UNLOCK_WITH_FINGERPRINT, value)
}
/** Preference to send money using the fingerprint sensor */
var sendMoneyWithFingerprint: Boolean
get() = brdPrefs.getBoolean(CONFIRM_SEND_WITH_FINGERPRINT, getUseFingerprint())
set(value) = brdPrefs.edit {
putBoolean(CONFIRM_SEND_WITH_FINGERPRINT, value)
}
fun preferredFiatIsoChanges() = callbackFlow<String> {
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == CURRENT_CURRENCY) offer(getPreferredFiatIso())
}
brdPrefs.registerOnSharedPreferenceChangeListener(listener)
awaitClose {
brdPrefs.unregisterOnSharedPreferenceChangeListener(listener)
}
}
private val _trackedConversionChanges = MutableStateFlow<Map<String, List<Conversion>>?>(null)
val trackedConversionChanges: Flow<Map<String, List<Conversion>>>
get() = _trackedConversionChanges
.filterNotNull()
.onStart {
_trackedConversionChanges.value?.let { emit(it) }
}
fun getTrackedConversions(): Map<String, List<Conversion>> =
brdPrefs.getStringSet(TRACKED_TRANSACTIONS, emptySet())!!
.map { Conversion.deserialize(it) }
.groupBy(Conversion::currencyCode)
fun putTrackedConversion(conversion: Conversion) {
brdPrefs.edit {
putStringSet(
TRACKED_TRANSACTIONS,
brdPrefs.getStringSet(TRACKED_TRANSACTIONS, emptySet())!! + conversion.serialize()
)
}
_trackedConversionChanges.value = getTrackedConversions()
}
fun removeTrackedConversion(conversion: Conversion) {
brdPrefs.edit {
val conversionStr = conversion.serialize()
putStringSet(
TRACKED_TRANSACTIONS,
brdPrefs.getStringSet(TRACKED_TRANSACTIONS, emptySet())!! - conversionStr
)
}
_trackedConversionChanges.value = getTrackedConversions()
}
var appRatePromptShouldPrompt: Boolean
get() = brdPrefs.getBoolean(APP_RATE_PROMPT_SHOULD_PROMPT, false)
set(value) = brdPrefs.edit { putBoolean(APP_RATE_PROMPT_SHOULD_PROMPT, value) }
.also { promptChangeChannel.offer(Unit) }
var appRatePromptShouldPromptDebug: Boolean
get() = brdPrefs.getBoolean(APP_RATE_PROMPT_SHOULD_PROMPT_DEBUG, false)
set(value) = brdPrefs.edit { putBoolean(APP_RATE_PROMPT_SHOULD_PROMPT_DEBUG, value) }
.also { promptChangeChannel.offer(Unit) }
var appRatePromptHasRated: Boolean
get() = brdPrefs.getBoolean(APP_RATE_PROMPT_HAS_RATED, false)
set(value) = brdPrefs.edit { putBoolean(APP_RATE_PROMPT_HAS_RATED, value) }
.also { promptChangeChannel.offer(Unit) }
var appRatePromptDontAskAgain: Boolean
get() = brdPrefs.getBoolean(APP_RATE_PROMPT_DONT_ASK_AGAIN, false)
set(value) = brdPrefs.edit { putBoolean(APP_RATE_PROMPT_DONT_ASK_AGAIN, value) }
.also { promptChangeChannel.offer(Unit) }
fun promptChanges(): Flow<Unit> =
promptChangeChannel.asFlow()
.onStart { emit(Unit) }
}
| mit | 0ecffe60809084565d8db9b5887a8b26 | 37.439807 | 99 | 0.676758 | 4.476262 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/notes/book/BookViewModel.kt | 1 | 2852 | package com.orgzly.android.ui.notes.book
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.orgzly.android.App
import com.orgzly.android.data.DataRepository
import com.orgzly.android.db.entity.Book
import com.orgzly.android.db.entity.NoteView
import com.orgzly.android.ui.CommonViewModel
import com.orgzly.android.ui.SingleLiveEvent
import com.orgzly.android.ui.AppBar
import com.orgzly.android.usecase.BookCycleVisibility
import com.orgzly.android.usecase.UseCaseRunner
class BookViewModel(private val dataRepository: DataRepository, val bookId: Long) : CommonViewModel() {
private data class Params(val noteId: Long? = null)
private val params = MutableLiveData<Params>(Params())
enum class FlipperDisplayedChild {
LOADING,
LOADED,
EMPTY,
DOES_NOT_EXIST
}
val flipperDisplayedChild = MutableLiveData(FlipperDisplayedChild.LOADING)
fun setFlipperDisplayedChild(child: FlipperDisplayedChild) {
flipperDisplayedChild.value = child
}
data class Data(val book: Book?, val notes: List<NoteView>?)
val data = Transformations.switchMap(params) { _ ->
MediatorLiveData<Data>().apply {
addSource(dataRepository.getBookLiveData(bookId)) {
value = Data(it, value?.notes)
}
addSource(dataRepository.getVisibleNotesLiveData(bookId)) {
value = Data(value?.book, it)
}
}
}
companion object {
const val APP_BAR_DEFAULT_MODE = 0
const val APP_BAR_SELECTION_MODE = 1
const val APP_BAR_SELECTION_MOVE_MODE = 2
}
val appBar = AppBar(mapOf(
APP_BAR_DEFAULT_MODE to null,
APP_BAR_SELECTION_MODE to APP_BAR_DEFAULT_MODE,
APP_BAR_SELECTION_MOVE_MODE to APP_BAR_SELECTION_MODE))
fun cycleVisibility() {
data.value?.book?.let { book ->
App.EXECUTORS.diskIO().execute {
catchAndPostError {
UseCaseRunner.run(BookCycleVisibility(book))
}
}
}
}
data class NotesToRefile(val selected: Set<Long>, val count: Int)
val refileRequestEvent: SingleLiveEvent<NotesToRefile> = SingleLiveEvent()
fun refile(ids: Set<Long>) {
App.EXECUTORS.diskIO().execute {
val count = dataRepository.getNotesAndSubtreesCount(ids)
refileRequestEvent.postValue(NotesToRefile(ids, count))
}
}
val notesDeleteRequest: SingleLiveEvent<Pair<Set<Long>, Int>> = SingleLiveEvent()
fun requestNotesDelete(ids: Set<Long>) {
App.EXECUTORS.diskIO().execute {
val count = dataRepository.getNotesAndSubtreesCount(ids)
notesDeleteRequest.postValue(Pair(ids, count))
}
}
} | gpl-3.0 | c787f3f191396e0f0cfcad722f740ce3 | 30.7 | 103 | 0.671108 | 4.387692 | false | false | false | false |
SkyA1ex/kotlin-crdt | src/main/kotlin/crdt/cvrdt/set/TwoPhaseSet.kt | 1 | 1320 | package cvrdt.set
/**
* Created by jackqack on 21/05/17.
*/
/**
* Two-phase set.
*/
class TwoPhaseSet<V> : CvRDTSet<V, TwoPhaseSet<V>> {
private val added: GSet<V>
private val tombstone: GSet<V>
constructor() {
added = GSet()
tombstone = GSet()
}
private constructor(added: GSet<V>, tombstone: GSet<V>) {
this.added = added.copy()
this.tombstone = tombstone.copy()
}
override fun add(x: V) {
if (!tombstone.contains(x)) added.add(x)
}
override fun addAll(elements: Collection<V>): Boolean {
val filtered = elements.filter { !tombstone.contains(it) }
return added.addAll(filtered)
}
override fun contains(x: V): Boolean {
return !tombstone.contains(x) && added.contains(x)
}
override fun remove(x: V): Boolean {
if (added.contains(x)) {
tombstone.add(x)
return true
} else return false
}
override fun merge(other: TwoPhaseSet<V>) {
added.merge(other.added)
tombstone.merge(other.tombstone)
}
override fun value(): MutableSet<V> {
val s = added.value()
s.removeAll(tombstone.value())
return s
}
override fun copy(): TwoPhaseSet<V> {
return TwoPhaseSet(added, tombstone)
}
} | mit | f532b5902bc778424ed15fdb086c5361 | 21.016667 | 66 | 0.580303 | 3.804035 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/httpws/service/auth/HttpWsAuthenticationInfo.kt | 1 | 1389 | package org.evomaster.core.problem.httpws.service.auth
import org.evomaster.core.problem.api.service.auth.AuthenticationInfo
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.search.Action
/**
* should be immutable
*
* AuthenticationInfo for http based SUT
*
*/
open class HttpWsAuthenticationInfo(
name: String,
val headers: List<AuthenticationHeader>,
val cookieLogin: CookieLogin?,
val jsonTokenPostLogin: JsonTokenPostLogin?): AuthenticationInfo(name) {
init {
if(name.isBlank()){
throw IllegalArgumentException("Blank name")
}
if(headers.isEmpty() && name != "NoAuth" && cookieLogin==null && jsonTokenPostLogin==null){
throw IllegalArgumentException("Empty headers")
}
if(cookieLogin != null && jsonTokenPostLogin != null){
//TODO maybe in future might want to support both...
throw IllegalArgumentException("Specified both Cookie and Token based login. Choose just one.")
}
}
/**
* @return whether to exclude auth check (401 status code in the response) for the [action]
*/
fun excludeAuthCheck(action: Action) : Boolean{
if (action is RestCallAction && jsonTokenPostLogin != null){
return action.getName() == "POST:${jsonTokenPostLogin.endpoint}"
}
return false
}
} | lgpl-3.0 | c4b899bc32b032387541d042fda28c38 | 32.902439 | 107 | 0.670266 | 4.72449 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/enums/AnimeLanguage.kt | 2 | 543 | package me.proxer.library.enums
import com.serjltt.moshi.adapters.FallbackEnum
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Enum holding the available languages of an anime.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = false)
@FallbackEnum(name = "OTHER")
enum class AnimeLanguage {
@Json(name = "gersub")
GERMAN_SUB,
@Json(name = "gerdub")
GERMAN_DUB,
@Json(name = "engsub")
ENGLISH_SUB,
@Json(name = "engdub")
ENGLISH_DUB,
@Json(name = "misc")
OTHER
}
| gpl-3.0 | 6925ace391db465c9c9d556943965c87 | 17.1 | 52 | 0.67035 | 3.436709 | false | false | false | false |
fluidsonic/jetpack-kotlin | Sources/HalfOpenRange.kt | 1 | 2980 | package com.github.fluidsonic.jetpack
public interface HalfOpenRange<Bound : Comparable<Bound>> {
public val start: Bound
public val endExclusive: Bound
public operator fun contains(value: Bound) =
value >= start && value < endExclusive
public fun isEmpty()
= start >= endExclusive
}
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.flipped() =
endExclusive rangeToBefore start
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.intersection(other: HalfOpenRange<Bound>) =
if (overlaps(other)) {
max(start, other.start) rangeToBefore min(endExclusive, other.endExclusive)
}
else {
null
}
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.contains(other: HalfOpenRange<Bound>) =
contains(other.start) && other.endExclusive <= endExclusive
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.overlaps(other: HalfOpenRange<Bound>) =
contains(other.start) || other.contains(start)
public fun <Bound : Comparable<Bound>, R : Comparable<R>> HalfOpenRange<Bound>.mapBounds(transform: (Bound) -> R) =
transform(start) rangeToBefore transform(endExclusive)
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.subtracting(rangeToSubtract: HalfOpenRange<Bound>): List<HalfOpenRange<Bound>> {
if (rangeToSubtract.start >= endExclusive || rangeToSubtract.endExclusive <= start) {
return listOf(this)
}
val result = mutableListOf<HalfOpenRange<Bound>>()
if (rangeToSubtract.start > start) {
result.add(start rangeToBefore rangeToSubtract.start)
}
if (rangeToSubtract.endExclusive < endExclusive) {
result.add(rangeToSubtract.endExclusive rangeToBefore endExclusive)
}
return result
}
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.toSequence(nextFunction: (Bound) -> Bound?) =
generateSequence(start) {
val next = nextFunction(it)
if (next != null && contains(next)) {
return@generateSequence next
}
else {
return@generateSequence null
}
}
private data class HalfOpenComparableRange<Bound : Comparable<Bound>>(
public override val start: Bound,
public override val endExclusive: Bound
) : HalfOpenRange<Bound> {
init {
require(start <= endExclusive)
}
public override fun toString() = "$start ..< $endExclusive"
}
public data class HalfOpenIntRange(
public override val start: Int,
public override val endExclusive: Int
) : HalfOpenRange<Int>, Iterable<Int> {
public override operator fun contains(value: Int) =
value in start .. (endExclusive - 1)
public override fun isEmpty()
= start >= endExclusive
public override operator fun iterator(): IntIterator {
if (start == endExclusive) {
return emptyRange.iterator()
}
return (start .. (endExclusive - 1)).iterator()
}
}
public infix fun <Bound : Comparable<Bound>> Bound.rangeToBefore(that: Bound): HalfOpenRange<Bound> = HalfOpenComparableRange(this, that)
public infix fun Int.rangeToBefore(that: Int) = HalfOpenIntRange(this, that)
private val emptyRange = 1 .. 0
| mit | 301369a21c34b30ab91eb02ff87246e1 | 25.140351 | 140 | 0.740604 | 3.94702 | false | false | false | false |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/util/Logcat.kt | 1 | 5627 | /*
* 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.util
import android.util.Log
import android.util.Log.DEBUG
import android.util.Log.ERROR
import android.util.Log.INFO
import android.util.Log.VERBOSE
import android.util.Log.WARN
/** Container for Chronicle's loggers. */
object Logcat {
private const val DEFAULT_TAG: String = "Chronicle"
private const val CLIENT_TAG: String = "ChronicleClient"
private const val SERVER_TAG: String = "ChronicleServer"
/**
* [TaggedLogger] intended for use by implementations of the Chronicle interface and as a
* catch-all in situations where it doesn't make sense to implement a new logger.
*/
val default: TaggedLogger = TaggedLogger(DEFAULT_TAG)
/** [TaggedLogger] intended for use by client-side API components. */
val clientSide: TaggedLogger = TaggedLogger(CLIENT_TAG)
/** [TaggedLogger] intended for use by server-side API components. */
val serverSide: TaggedLogger = TaggedLogger(SERVER_TAG)
}
/**
* Helper class to associate a tag with logging calls. Each method simply calls the corresponding
* method in Android's native logger with the given tag.
*/
class TaggedLogger(val tag: String) {
/**
* Send a [VERBOSE] log message.
* @param msg The message you would like logged.
*/
fun v(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, VERBOSE)) {
Log.v(tag, String.format(msg, *args))
}
}
/**
* Send a [VERBOSE] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun v(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, VERBOSE)) {
Log.v(tag, String.format(msg, *args), tr)
}
}
/**
* Send a [DEBUG] log message.
* @param msg The message you would like logged.
*/
fun d(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, DEBUG)) {
Log.d(tag, String.format(msg, *args))
}
}
/**
* Send a [DEBUG] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun d(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, DEBUG)) {
Log.d(tag, String.format(msg, *args), tr)
}
}
/**
* Send an [INFO] log message.
* @param msg The message you would like logged.
*/
fun i(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, INFO)) {
Log.i(tag, String.format(msg, *args))
}
}
/**
* Send a [INFO] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun i(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, INFO)) {
Log.i(tag, String.format(msg, *args), tr)
}
}
/**
* Send a [WARN] log message.
* @param msg The message you would like logged.
*/
fun w(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, WARN)) {
Log.w(tag, String.format(msg, *args))
}
}
/**
* Send a [WARN] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun w(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, WARN)) {
Log.w(tag, String.format(msg, *args), tr)
}
}
/**
* Send a [WARN] log message and log the exception.
* @param tr An exception to log
*/
fun w(tr: Throwable) {
if (Log.isLoggable(tag, WARN)) {
Log.w(tag, tr)
}
}
/**
* Send an [ERROR] log message.
* @param msg The message you would like logged.
*/
fun e(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, ERROR)) {
Log.e(tag, String.format(msg, *args))
}
}
/**
* Send a [ERROR] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun e(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, ERROR)) {
Log.e(tag, String.format(msg, *args), tr)
}
}
/**
* Handy function to get a loggable stack trace from a Throwable
* @param tr An exception to log
*/
fun getStackTraceString(tr: Throwable): String {
return Log.getStackTraceString(tr)
}
/**
* Low-level logging call.
* @param priority The priority/type of this log message
* @param msg The message you would like logged.
* @return The number of bytes written.
*/
fun println(priority: Int, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, priority)) {
Log.println(priority, tag, String.format(msg, *args))
}
}
/**
* Times the duration of the [block] and logs the provided [message] along with the duration at
* [VERBOSE] level.
*/
inline fun <T> timeVerbose(message: String, block: () -> T): T {
val start = System.nanoTime()
return try {
block()
} finally {
val duration = System.nanoTime() - start
v("%s [duration: %.3f ms]", message, duration / 1000000.0)
}
}
}
| apache-2.0 | 2c8baff8f612694bbf00b559ba95cf6d | 27.276382 | 97 | 0.645104 | 3.614001 | false | false | false | false |
jonnyzzz/TeamCity.Node | server/src/main/java/com/jonnyzzz/teamcity/plugins/node/server/NVM.kt | 1 | 4262 | /*
* Copyright 2013-2015 Eugene Petrenko
*
* 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.jonnyzzz.teamcity.plugins.node.server
import jetbrains.buildServer.web.openapi.PluginDescriptor
import com.jonnyzzz.teamcity.plugins.node.common.*
import jetbrains.buildServer.serverSide.PropertiesProcessor
import jetbrains.buildServer.serverSide.InvalidProperty
import jetbrains.buildServer.requirements.Requirement
import jetbrains.buildServer.serverSide.buildDistribution.StartingBuildAgentsFilter
import jetbrains.buildServer.serverSide.buildDistribution.AgentsFilterContext
import jetbrains.buildServer.serverSide.buildDistribution.AgentsFilterResult
import jetbrains.buildServer.serverSide.BuildPromotionManager
import jetbrains.buildServer.requirements.RequirementType
import jetbrains.buildServer.serverSide.BuildPromotion
import jetbrains.buildServer.serverSide.buildDistribution.SimpleWaitReason
/**
* @author Eugene Petrenko ([email protected])
* Date: 16.08.13 21:43
*/
class NVMRunType(val plugin : PluginDescriptor) : RunTypeBase() {
private val bean = NVMBean()
override fun getType(): String = bean.NVMFeatureType
override fun getDisplayName(): String = "Node.js NVM Installer"
override fun getDescription(): String = "Install Node.js of specified version using NVM"
override fun getEditJsp(): String = "node.nvm.edit.jsp"
override fun getViewJsp(): String = "node.nvm.view.jsp"
override fun getRunnerPropertiesProcessor(): PropertiesProcessor
= PropertiesProcessor{ arrayListOf<InvalidProperty>() }
override fun getDefaultRunnerProperties(): MutableMap<String, String>?
= hashMapOf(bean.NVMVersion to "0.10")
override fun describeParameters(parameters: Map<String, String>): String
= "Install Node.js v" + parameters[bean.NVMVersion]
override fun getRunnerSpecificRequirements(runParameters: Map<String, String>): MutableList<Requirement> {
return arrayListOf(Requirement(bean.NVMAvailable, null, RequirementType.EXISTS))
}
}
class NVMBuildStartPrecondition(val promos : BuildPromotionManager) : StartingBuildAgentsFilter {
private val nodeBean = NodeBean()
private val npmBean = NPMBean()
private val nvmBean = NVMBean()
private val runTypes = hashSetOf(nodeBean.runTypeNameNodeJs, npmBean.runTypeName)
override fun filterAgents(context: AgentsFilterContext): AgentsFilterResult {
val result = AgentsFilterResult()
val promo = context.getStartingBuild().getBuildPromotionInfo()
if (promo !is BuildPromotion) return result
val buildType = promo.getBuildType()
if (buildType == null) return result
val runners = buildType.buildRunners.filter { buildType.isEnabled(it.getId()) }
//if nothing found => skip
if (runners.isEmpty()) return result
//if our nodeJS and NPM runners are not used
if (!runners.any { runner -> runTypes.contains(runner.type)}) return result
val version = runners.firstOrNull { it.type == nvmBean.NVMFeatureType }
?.parameters
?.get(nvmBean.NVMVersion)
//skip checks if NVM feature version was specified
if (version != null) return result
//if not, let's filter unwanted agents
val agents = context.agentsForStartingBuild.filter { agent ->
//allow only if there were truly-detected NVM/NPM on the agent
with(agent.configurationParameters) {
get(nodeBean.nodeJSConfigurationParameter) != nvmBean.NVMUsed
&&
get(npmBean.nodeJSNPMConfigurationParameter) != nvmBean.NVMUsed
}
}
if (agents.isEmpty()) {
result.waitReason = SimpleWaitReason("Please add 'Node.js NVM Installer' build runner")
} else {
result.filteredConnectedAgents = agents
}
return result
}
}
| apache-2.0 | f14884f4a8585a760d67e596b2c77f62 | 37.745455 | 108 | 0.756687 | 4.510053 | false | false | false | false |
guyca/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/BackgroundColorAnimator.kt | 1 | 1585 | package com.reactnativenavigation.views.element.animators
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.view.View
import android.view.ViewGroup
import androidx.core.animation.addListener
import androidx.core.animation.doOnStart
import com.facebook.react.views.text.ReactTextView
import com.facebook.react.views.view.ReactViewBackgroundDrawable
import com.reactnativenavigation.parse.SharedElementTransitionOptions
import com.reactnativenavigation.utils.*
class BackgroundColorAnimator(from: View, to: View) : PropertyAnimatorCreator<ViewGroup>(from, to) {
override fun shouldAnimateProperty(fromChild: ViewGroup, toChild: ViewGroup): Boolean {
return fromChild.background is ReactViewBackgroundDrawable &&
toChild.background is ReactViewBackgroundDrawable && (fromChild.background as ReactViewBackgroundDrawable).color != (toChild.background as ReactViewBackgroundDrawable).color
}
override fun excludedViews() = listOf(ReactTextView::class.java)
override fun create(options: SharedElementTransitionOptions): Animator {
val backgroundColorEvaluator = BackgroundColorEvaluator(to.background as ReactViewBackgroundDrawable)
val fromColor = ColorUtils.colorToLAB(ViewUtils.getBackgroundColor(from))
val toColor = ColorUtils.colorToLAB(ViewUtils.getBackgroundColor(to))
backgroundColorEvaluator.evaluate(0f, fromColor, toColor)
return ObjectAnimator.ofObject(backgroundColorEvaluator, fromColor, toColor)
}
} | mit | e80a52c110444188808cd2d38be7e584 | 50.16129 | 189 | 0.813249 | 5.391156 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/ParallelAction.kt | 1 | 4218 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.action
import java.util.concurrent.CopyOnWriteArrayList
class ParallelAction(vararg child: Action) : CompoundAction() {
private var firstChildStarted: Action? = null
/**
* Used by ActionHolder to combine an existing Action into a sequence without restarting it.
* It is generally not advisable for games to use this constructor directly.
*/
constructor(child1: Action, child2: Action, child1Started: Boolean) : this(child1, child2) {
if (child1Started) firstChildStarted = child1
}
/**
* This holds the children that are still active (i.e. those that haven't finished).
* During [act], children that finish are moved from here to [finishedChildren].
* When/if the ParallelAction is restarted, the finishedChildren are added back to
* this list.
*/
override val children = CopyOnWriteArrayList<Action>()
/**
* When adding a new child it is added to this list, their begin method is not called at this time.
* During [act], this each member is then moved to either [finishedChildren] or [chidren]
* depending on the result of their begin.
*/
private val unstartedChildren = mutableListOf<Action>()
/**
* During [act], and [begin], any children that finish are moved from [children] into
* this list.
* This list is then added to [children] if/when the ParallelAction is restarted.
*/
private val finishedChildren = mutableListOf<Action>()
init {
children.addAll(child)
}
override fun begin(): Boolean {
super.begin()
// If we are being restarted (from a ForeverAction, or a RepeatAction), then
// add the finished children back to the active list
if (finishedChildren.isNotEmpty()) {
children.addAll(finishedChildren)
finishedChildren.clear()
}
var finished = true
children.forEach { child ->
val childFinished = if (firstChildStarted == child) false else child.begin()
if (childFinished) {
children.remove(child)
finishedChildren.add(child)
} else {
finished = false // One child isn't finished, so we aren't finished.
}
}
// If we restart, then we don't want to treat the first child special. We need to start all children as normal.
firstChildStarted = null
unstartedChildren.clear()
return finished
}
override fun add(action: Action) {
unstartedChildren.add(action)
super.add(action)
}
override fun remove(action: Action) {
unstartedChildren.remove(action)
super.add(action)
}
override fun act(): Boolean {
if (unstartedChildren.isNotEmpty()) {
unstartedChildren.forEach {
if (it.begin()) {
finishedChildren.add(it)
} else {
children.add(it)
}
}
unstartedChildren.clear()
}
children.forEach { child ->
if (child.act()) {
children.remove(child)
// Remember this child, so that if we are restarted, then the child can be added back to the
// "children" list again.
finishedChildren.add(child)
}
}
return children.isEmpty()
}
override fun and(other: Action): ParallelAction {
add(other)
return this
}
}
| gpl-3.0 | 3d7365d42596aed74981c77e2b192b52 | 31.446154 | 119 | 0.633239 | 4.75 | false | false | false | false |
mizukami2005/StockQiita | app/src/main/kotlin/com/mizukami2005/mizukamitakamasa/qiitaclient/dagger/ClientModule.kt | 1 | 1744 | package com.mizukami2005.mizukamitakamasa.qiitaclient.dagger
import com.google.gson.*
import com.mizukami2005.mizukamitakamasa.qiitaclient.client.ArticleClient
import com.mizukami2005.mizukamitakamasa.qiitaclient.client.QiitaClient
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import io.realm.RealmObject
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
class ClientModule {
@Provides
@Singleton
fun provideGson(): Gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setExclusionStrategies(object : ExclusionStrategy {
override fun shouldSkipField(f: FieldAttributes): Boolean {
return f.declaredClass == RealmObject::class.java
}
override fun shouldSkipClass(clazz: Class<*>): Boolean {
return false
}
})
.create()
@Provides
@Singleton
fun provideRetrofit(gson: Gson): Retrofit = Retrofit.Builder()
.baseUrl("https://qiita.com")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
@Provides
@Singleton
fun provideArticleClient(retrofit: Retrofit): ArticleClient =
retrofit.create(ArticleClient::class.java)
@Provides
@Singleton
fun provideQiitaClient(retrofit: Retrofit): QiitaClient =
retrofit.create(QiitaClient::class.java)
}
| mit | a52a5e1d00d168754ae840bf3db63167 | 31.90566 | 80 | 0.702408 | 4.898876 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/cameraViewer/Camera2BasicFragment.kt | 1 | 22797 | /*
* Copyright 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 com.itachi1706.cheesecakeutilities.modules.cameraViewer
import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.*
import android.hardware.camera2.*
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.util.Size
import android.util.SparseIntArray
import android.view.*
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.itachi1706.cheesecakeutilities.R
import com.itachi1706.helperlib.helpers.LogHelper
import kotlinx.android.synthetic.main.fragment_camera2_basic.*
import java.util.*
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import kotlin.collections.ArrayList
import kotlin.math.max
import kotlin.math.round
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class Camera2BasicFragment : Fragment(), View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {
private val surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) { openCamera(width, height) }
override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) { configureTransform(width, height) }
override fun onSurfaceTextureDestroyed(texture: SurfaceTexture) = true
override fun onSurfaceTextureUpdated(texture: SurfaceTexture) = Unit
}
private lateinit var cameraId: String
private var captureSession: CameraCaptureSession? = null
private var cameraDevice: CameraDevice? = null
private lateinit var previewSize: Size
private lateinit var largest: Size
private val stateCallback = object : CameraDevice.StateCallback() {
override fun onOpened(cameraDevice: CameraDevice) {
cameraOpenCloseLock.release()
[email protected] = cameraDevice
createCameraPreviewSession()
}
override fun onDisconnected(cameraDevice: CameraDevice) {
cameraOpenCloseLock.release()
cameraDevice.close()
[email protected] = null
}
override fun onError(cameraDevice: CameraDevice, error: Int) { onDisconnected(cameraDevice); [email protected]?.finish() }
}
private var backgroundThread: HandlerThread? = null
private var backgroundHandler: Handler? = null
private lateinit var previewRequestBuilder: CaptureRequest.Builder
private lateinit var previewRequest: CaptureRequest
private var state = STATE_PREVIEW
private val cameraOpenCloseLock = Semaphore(1)
private var flashSupported = false
private var sensorOrientation = 0
private val captureCallback = object : CameraCaptureSession.CaptureCallback() {
private fun process() {
when (state) { STATE_PREVIEW -> Unit } // Do nothing when the camera preview is working normally.
}
override fun onCaptureProgressed(session: CameraCaptureSession, request: CaptureRequest, partialResult: CaptureResult) { process() }
override fun onCaptureCompleted(session: CameraCaptureSession, request: CaptureRequest, result: TotalCaptureResult) { process() }
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_camera2_basic, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
flash.setOnClickListener(this)
info.setOnClickListener(this)
switch_cam.setOnClickListener(this)
}
override fun onResume() {
super.onResume()
startBackgroundThread()
if (texture.isAvailable) openCamera(texture.width, texture.height)
else texture.surfaceTextureListener = surfaceTextureListener
}
override fun onPause() {
closeCamera()
stopBackgroundThread()
super.onPause()
}
private fun requestCameraPermission() {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) ConfirmationDialog().show(childFragmentManager, FRAGMENT_DIALOG)
else requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == REQUEST_CAMERA_PERMISSION)
if (grantResults.size != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) ErrorDialog.newInstance(getString(R.string.request_permission)).show(childFragmentManager, FRAGMENT_DIALOG)
else super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private fun setUpCameraOutputs(width: Int, height: Int) {
val manager = activity!!.getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
for (cameraId in manager.cameraIdList) {
if (!setupCam(manager, cameraId, width, height, true)) continue
this.cameraId = cameraId
return // We've found a viable camera and finished setting up member variables so we don't need to iterate through other available cameras.
}
} catch (e: CameraAccessException) {
LogHelper.e(TAG, e.toString())
} catch (e: NullPointerException) {
// Currently an NPE is thrown when the Camera2API is used but not supported on the
// device this code runs.
ErrorDialog.newInstance(getString(R.string.camera_error)).show(childFragmentManager, FRAGMENT_DIALOG)
}
}
private fun setupCam(manager: CameraManager, cameraId: String, width: Int, height: Int, init: Boolean = false): Boolean {
val characteristics = manager.getCameraCharacteristics(cameraId)
// We don't use a front facing camera in this sample.
val cameraDirection = characteristics.get(CameraCharacteristics.LENS_FACING)
if (cameraDirection != null &&
cameraDirection == CameraCharacteristics.LENS_FACING_FRONT && init) {
return false
}
val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) ?: return false
// For still image captures, we use the largest available size.
largest = Collections.max(listOf(*map.getOutputSizes(ImageFormat.JPEG)), CompareSizesByArea())
// Find out if we need to swap dimension to get the preview size relative to sensor coordinate.
val displayRotation = activity!!.windowManager.defaultDisplay.rotation
sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!!
val swappedDimensions = areDimensionsSwapped(displayRotation)
val displaySize = Point()
activity!!.windowManager.defaultDisplay.getSize(displaySize)
val rotatedPreviewWidth = if (swappedDimensions) height else width
val rotatedPreviewHeight = if (swappedDimensions) width else height
var maxPreviewWidth = if (swappedDimensions) displaySize.y else displaySize.x
var maxPreviewHeight = if (swappedDimensions) displaySize.x else displaySize.y
if (maxPreviewWidth > MAX_PREVIEW_WIDTH) maxPreviewWidth = MAX_PREVIEW_WIDTH
if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) maxPreviewHeight = MAX_PREVIEW_HEIGHT
// Danger, W.R.! Attempting to use too large a preview size could exceed the camera
// bus' bandwidth limitation, resulting in gorgeous previews but the storage of
// garbage capture data.
previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture::class.java), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest)
// We fit the aspect ratio of TextureView to the size of preview we picked.
if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
texture.setAspectRatio(previewSize.width, previewSize.height)
} else {
texture.setAspectRatio(previewSize.height, previewSize.width)
}
// Check if the flash is supported.
flashSupported = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true
return true
}
private fun areDimensionsSwapped(displayRotation: Int): Boolean {
var swappedDimensions = false
when (displayRotation) {
Surface.ROTATION_0, Surface.ROTATION_180 -> if (sensorOrientation == 90 || sensorOrientation == 270) swappedDimensions = true
Surface.ROTATION_90, Surface.ROTATION_270 -> if (sensorOrientation == 0 || sensorOrientation == 180) swappedDimensions = true
else -> LogHelper.e(TAG, "Display rotation is invalid: $displayRotation")
}
return swappedDimensions
}
private fun openCamera(width: Int, height: Int, cid: String? = null) {
val permission = ContextCompat.checkSelfPermission(activity!!, Manifest.permission.CAMERA)
if (permission != PackageManager.PERMISSION_GRANTED) {
requestCameraPermission()
return
}
val manager = activity!!.getSystemService(Context.CAMERA_SERVICE) as CameraManager
if (cid.isNullOrEmpty()) setUpCameraOutputs(width, height) else {
setupCam(manager, cid, width, height, false)
this.cameraId = cid
}
flash.isEnabled = flashSupported // If camera has flash
configureTransform(width, height)
try {
// Wait for camera to open - 2.5 seconds is sufficient
if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) throw RuntimeException("Time out waiting to lock camera opening.")
manager.openCamera(cameraId, stateCallback, backgroundHandler)
} catch (e: CameraAccessException) {
LogHelper.e(TAG, e.toString())
} catch (e: InterruptedException) {
throw RuntimeException("Interrupted while trying to lock camera opening.", e)
}
}
private fun closeCamera() {
try {
cameraOpenCloseLock.acquire()
captureSession?.close()
captureSession = null
cameraDevice?.close()
cameraDevice = null
} catch (e: InterruptedException) {
throw RuntimeException("Interrupted while trying to lock camera closing.", e)
} finally {
cameraOpenCloseLock.release()
}
}
private fun startBackgroundThread() {
backgroundThread = HandlerThread("CameraBackground").also { it.start() }
backgroundHandler = Handler(backgroundThread!!.looper)
}
private fun stopBackgroundThread() {
backgroundThread?.quitSafely()
try {
backgroundThread?.join()
backgroundThread = null
backgroundHandler = null
} catch (e: InterruptedException) {
LogHelper.e(TAG, e.toString())
}
}
private fun createCameraPreviewSession() {
try {
val texture = texture.surfaceTexture
texture.setDefaultBufferSize(previewSize.width, previewSize.height) // We configure the size of default buffer to be the size of camera preview we want.
val surface = Surface(texture) // This is the output Surface we need to start preview.
// We set up a CaptureRequest.Builder with the output Surface.
previewRequestBuilder = cameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
previewRequestBuilder.addTarget(surface)
// Here, we create a CameraCaptureSession for camera preview.
cameraDevice?.createCaptureSession(listOf(surface), object : CameraCaptureSession.StateCallback() {
override fun onConfigured(cameraCaptureSession: CameraCaptureSession) {
if (cameraDevice == null) return // The camera is already closed
captureSession = cameraCaptureSession // When the session is ready, we start displaying the preview.
try {
// Auto focus should be continuous for camera preview.
previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
setAutoFlash(previewRequestBuilder) // Flash is automatically enabled when necessary.
// Finally, we start displaying the camera preview.
previewRequest = previewRequestBuilder.build()
captureSession?.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler)
} catch (e: CameraAccessException) {
LogHelper.e(TAG, e.toString())
}
}
override fun onConfigureFailed(session: CameraCaptureSession) { activity!!.runOnUiThread { Toast.makeText(activity, "Failed", Toast.LENGTH_SHORT).show() } } }, null)
} catch (e: CameraAccessException) { LogHelper.e(TAG, e.toString()) }
}
private fun configureTransform(viewWidth: Int, viewHeight: Int) {
activity ?: return
val rotation = activity!!.windowManager.defaultDisplay.rotation
val matrix = Matrix()
val viewRect = RectF(0f, 0f, viewWidth.toFloat(), viewHeight.toFloat())
val bufferRect = RectF(0f, 0f, previewSize.height.toFloat(), previewSize.width.toFloat())
val centerX = viewRect.centerX()
val centerY = viewRect.centerY()
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY())
val scale = max(viewHeight.toFloat() / previewSize.height, viewWidth.toFloat() / previewSize.width)
with(matrix) {
setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL)
postScale(scale, scale, centerX, centerY)
postRotate((90 * (rotation - 2)).toFloat(), centerX, centerY)
}
} else if (Surface.ROTATION_180 == rotation) {
matrix.postRotate(180f, centerX, centerY)
}
texture.setTransform(matrix)
}
private fun toggleFlash() {
if (activity == null) return
LogHelper.d(TAG, "toggleFlash()")
val flashState = previewRequestBuilder.get(CaptureRequest.FLASH_MODE) ?: CaptureRequest.FLASH_MODE_OFF
LogHelper.d(TAG, "Flash State: $flashState")
if (flashState != CaptureRequest.FLASH_MODE_OFF) {
previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF)
setAutoFlash(previewRequestBuilder)
} // On
else {
previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH)
previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON)
} // Off
previewRequest = previewRequestBuilder.build()
captureSession?.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler)
}
private fun getDebugInformation(): String {
if (activity == null) return ""
val manager = activity!!.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val string = StringBuilder()
string.append("Camera Count: ${manager.cameraIdList.size}\n")
string.append("Currently Active Camera: ${this.cameraId}\n")
val c = manager.getCameraCharacteristics(cameraId)
string.append("Is Front Facing: ${c.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT}\n")
string.append("Has Flash: $flashSupported\n")
string.append("Hardware Level Support: ${c.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)} (${getHardwareLevelName(c.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL))})\n")
string.append("Optical Image Stabilization: ${isStateAvailable(CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION, c, CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON)}\n")
string.append("Electronic Image Stabilization: ${isStateAvailable(CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES, c, CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_ON)}\n")
val mp = String.format("%.1f", (largest.width * largest.height) / 1024.0 / 1024.0).toDouble()
val mpRound = round((largest.width * largest.height) / 1024.0 / 1024.0)
string.append("Resolution: ${largest.width}x${largest.height} (${if (mpRound <=0) mp else mpRound} Megapixels)\n")
val aperature = c.get(CameraCharacteristics.LENS_INFO_AVAILABLE_APERTURES)
val aperatureString = aperature?.joinToString(",", "f/", " ") ?: "None"
string.append("Aperature Sizes: $aperatureString")
return string.toString()
}
private fun isStateAvailable(char: CameraCharacteristics.Key<IntArray>, c: CameraCharacteristics, target: Int): Boolean {
val tmp = c.get(char)
tmp?.let { it.forEach { o -> if (o == target) return true } }
return false
}
private fun getHardwareLevelName(level: Int?): String {
return when (level) {
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY -> "Legacy"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL -> "External"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED -> "Limited"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL -> "Full"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3 -> "L3"
else -> "Unknown"
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.flash -> toggleFlash()
R.id.info -> activity?.let { AlertDialog.Builder(it).setTitle("Debug Info").setMessage(getDebugInformation()).setPositiveButton(android.R.string.ok, null).show() }
R.id.switch_cam -> {
val manager = activity!!.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val list = manager.cameraIdList.map { s -> val cameraDirection = manager.getCameraCharacteristics(s.toString()).get(CameraCharacteristics.LENS_FACING)
if (cameraDirection != null && cameraDirection == CameraCharacteristics.LENS_FACING_FRONT) "$s (Front Camera)" else "$s (Rear Camera)" }.toTypedArray()
val selected = manager.cameraIdList.indexOf(cameraId)
// Get front/rear status
AlertDialog.Builder(context).setTitle("Change Camera")
.setSingleChoiceItems(list, selected, null)
.setPositiveButton(android.R.string.ok) { dialog: DialogInterface, _ ->
dialog.dismiss()
val selPos = (dialog as AlertDialog).listView.checkedItemPosition
val selString = manager.cameraIdList[selPos]
LogHelper.d(TAG, "Sel new camera: $selPos ($selString)")
switchCam(selString.toString())
}.setNegativeButton(android.R.string.cancel, null).show()
}
}
}
private fun switchCam(newCam: String) {
LogHelper.i(TAG, "Switching Camera View from ${this.cameraId} to $newCam")
closeCamera()
openCamera(texture.width, texture.height, newCam)
}
private fun setAutoFlash(requestBuilder: CaptureRequest.Builder) {
if (flashSupported) {
requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH)
}
}
companion object {
private val ORIENTATIONS = SparseIntArray()
private const val FRAGMENT_DIALOG = "dialog"
init {
ORIENTATIONS.append(Surface.ROTATION_0, 90)
ORIENTATIONS.append(Surface.ROTATION_90, 0)
ORIENTATIONS.append(Surface.ROTATION_180, 270)
ORIENTATIONS.append(Surface.ROTATION_270, 180)
}
private const val TAG = "Camera2BasicFragment"
private const val STATE_PREVIEW = 0
private const val MAX_PREVIEW_WIDTH = 1920
private const val MAX_PREVIEW_HEIGHT = 1080
@JvmStatic private fun chooseOptimalSize(choices: Array<Size>, textureViewWidth: Int, textureViewHeight: Int, maxWidth: Int, maxHeight: Int, aspectRatio: Size): Size {
// Collect the supported resolutions that are at least as big as the preview Surface
val bigEnough = ArrayList<Size>()
// Collect the supported resolutions that are smaller than the preview Surface
val notBigEnough = ArrayList<Size>()
val w = aspectRatio.width
val h = aspectRatio.height
for (option in choices) {
if (option.width <= maxWidth && option.height <= maxHeight &&
option.height == option.width * h / w) {
if (option.width >= textureViewWidth && option.height >= textureViewHeight) bigEnough.add(option)
else notBigEnough.add(option)
}
}
// Pick the smallest of those big enough. If there is no one big enough, pick the
// largest of those not big enough.
return when {
bigEnough.size > 0 -> Collections.min(bigEnough, CompareSizesByArea())
notBigEnough.size > 0 -> Collections.max(notBigEnough, CompareSizesByArea())
else -> {
LogHelper.e(TAG, "Couldn't find any suitable preview size")
choices[0]
}
}
}
@JvmStatic fun newInstance(): Camera2BasicFragment = Camera2BasicFragment()
}
} | mit | bb84fa3e3e3ce9ce964abc01f07838a3 | 49.105495 | 203 | 0.674255 | 5.12753 | false | false | false | false |
hyst329/OpenFool | core/src/ru/hyst329/openfool/GameScreen.kt | 1 | 41262 | package ru.hyst329.openfool
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.scenes.scene2d.Action
import com.badlogic.gdx.scenes.scene2d.Event
import com.badlogic.gdx.scenes.scene2d.EventListener
import com.badlogic.gdx.scenes.scene2d.Group
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.Touchable
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.utils.viewport.FitViewport
import mu.KotlinLogging
import java.security.SecureRandom
import java.util.ArrayList
import java.util.HashMap
import ru.hyst329.openfool.GameScreen.GameState.BEATEN
import ru.hyst329.openfool.GameScreen.GameState.BEATING
import ru.hyst329.openfool.GameScreen.GameState.DRAWING
import ru.hyst329.openfool.GameScreen.GameState.FINISHED
import ru.hyst329.openfool.GameScreen.GameState.READY
import ru.hyst329.openfool.GameScreen.GameState.THROWING
import ru.hyst329.openfool.GameScreen.GameState.THROWN
import ru.hyst329.openfool.ResultScreen.Result.TEAM_DRAW
import ru.hyst329.openfool.ResultScreen.Result.TEAM_LOST
import ru.hyst329.openfool.ResultScreen.Result.TEAM_PARTNER_LOST
import ru.hyst329.openfool.ResultScreen.Result.TEAM_WON
import ru.hyst329.openfool.ResultScreen.Result.DRAW
import ru.hyst329.openfool.ResultScreen.Result.LOST
import ru.hyst329.openfool.ResultScreen.Result.WON
import kotlin.math.min
/**
* Created by main on 13.03.2017.
* Licensed under MIT License.
*/
private val logger = KotlinLogging.logger {}
class GameScreen(private val game: OpenFoolGame) : Screen, EventListener {
private val background: Texture
private val backgroundColor: Color
private val suitSymbols: Map<Suit, Sprite> = mapOf(
Suit.SPADES to Sprite(game.assetManager.get("suits/spades.png", Texture::class.java)),
Suit.DIAMONDS to Sprite(game.assetManager.get("suits/diamonds.png", Texture::class.java)),
Suit.CLUBS to Sprite(game.assetManager.get("suits/clubs.png", Texture::class.java)),
Suit.HEARTS to Sprite(game.assetManager.get("suits/hearts.png", Texture::class.java))
)
internal enum class GameState {
READY,
DRAWING,
THROWING,
THROWN,
BEATING,
BEATEN,
FINISHED
}
private inner class GameStateChangedAction internal constructor(private val newState: GameState) : Action() {
override fun act(delta: Float): Boolean {
gameState = newState
return true
}
}
private inner class SortAction internal constructor(private val playerIndex: Int) : Action() {
override fun act(delta: Float): Boolean {
if (playerIndex == 0)
sortPlayerCards()
return true
}
}
private val stage: Stage
private val discardPileGroup: Group
private val tableGroup: Group
private val playerGroups: Array<Group>
internal lateinit var trumpSuit: Suit
internal val players: Array<Player>
internal var attackCards = arrayOfNulls<Card>(DEAL_LIMIT)
private set
internal var defenseCards = arrayOfNulls<Card>(DEAL_LIMIT)
private set
private val cardActors = HashMap<Card, CardActor>()
internal var ruleSet = RuleSet(game.preferences)
private set
private val deck = Deck(ruleSet.lowestRank)
private val screenOrientationIsPortrait: Boolean = game.preferences.getBoolean(SettingsScreen.ORIENTATION, false)
private val cardScalePlayer = if (screenOrientationIsPortrait) CARD_SCALE_PLAYER_PORTRAIT else CARD_SCALE_PLAYER_LANDSCAPE
private val cardScaleTable = if (screenOrientationIsPortrait) CARD_SCALE_TABLE_PORTRAIT else CARD_SCALE_TABLE_LANDSCAPE
private val cardScaleAI = if (screenOrientationIsPortrait) CARD_SCALE_AI_PORTRAIT else CARD_SCALE_AI_LANDSCAPE
private val deckPosition = if (screenOrientationIsPortrait) DECK_POSITION_PORTRAIT else DECK_POSITION_LANDSCAPE
private val playerPosition = if (screenOrientationIsPortrait) PLAYER_POSITION_PORTRAIT else PLAYER_POSITION_LANDSCAPE
private val aiPosition = if (screenOrientationIsPortrait) AI_POSITION_PORTRAIT else AI_POSITION_LANDSCAPE
private val tablePosition = if (screenOrientationIsPortrait) TABLE_POSITION_PORTRAIT else TABLE_POSITION_LANDSCAPE
private val discardPilePosition = if (screenOrientationIsPortrait) DISCARD_PILE_POSITION_PORTRAIT else DISCARD_PILE_POSITION_LANDSCAPE
private val playerDelta = if (screenOrientationIsPortrait) PLAYER_DELTA_PORTRAIT else PLAYER_DELTA_LANDSCAPE
private val aiDelta = if (screenOrientationIsPortrait) AI_DELTA_PORTRAIT else AI_DELTA_LANDSCAPE
private val tableDelta = if (screenOrientationIsPortrait) TABLE_DELTA_PORTRAIT else TABLE_DELTA_LANDSCAPE
private val nextLineDelta = if (screenOrientationIsPortrait) NEXT_LINE_DELTA_PORTRAIT else NEXT_LINE_DELTA_LANDSCAPE
private val offset = if (screenOrientationIsPortrait) 384 else 640
private var currentAttackerIndex: Int = 0
private var currentThrowerIndex: Int = 0
private var playersSaidDone: Int = 0
private var isPlayerTaking: Boolean = false
private val random = SecureRandom()
private val outOfPlay: BooleanArray
private val discardPile = ArrayList<Card>()
private var gameState = DRAWING
private var oldGameState = FINISHED
private val sortingMode: Player.SortingMode
private var throwLimit = DEAL_LIMIT
private var playerDoneStatuses: BooleanArray
internal var places = IntArray(DEAL_LIMIT) { 0 }
init {
// Create the stage depending on screen orientation
if (screenOrientationIsPortrait) {
game.orientationHelper.requestOrientation(OrientationHelper.Orientation.PORTRAIT)
} else {
game.orientationHelper.requestOrientation(OrientationHelper.Orientation.LANDSCAPE)
}
stage = Stage(if (screenOrientationIsPortrait) {
FitViewport(480f, 800f)
} else {
FitViewport(800f, 480f)
})
// Initialise the stage
Gdx.input.inputProcessor = stage
// Get background color
backgroundColor = Color(game.preferences.getInteger(SettingsScreen.BACKGROUND_COLOR, 0x33cc4dff))
val backgroundNo = game.preferences.getInteger(SettingsScreen.BACKGROUND, 1)
background = game.assetManager.get("backgrounds/background$backgroundNo.png", Texture::class.java)
background.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat)
// Initialise suit symbols
for ((suit, sprite) in suitSymbols) {
sprite.setCenter(Gdx.graphics.width / 20f, Gdx.graphics.height / 3.2f)
sprite.setScale(0.5f)
}
// Initialise player info
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
outOfPlay = BooleanArray(ruleSet.playerCount)
val deckStyle = game.preferences.getString(SettingsScreen.DECK, "rus")
sortingMode = Player.SortingMode.fromInt(game.preferences.getInteger(SettingsScreen.SORTING_MODE, 0))
// Initialise groups
tableGroup = Group()
stage.addActor(tableGroup)
val deckGroup = Group()
stage.addActor(deckGroup)
discardPileGroup = Group()
stage.addActor(discardPileGroup)
playerGroups = Array(ruleSet.playerCount) { Group() }
for (i in 0 until ruleSet.playerCount) {
playerGroups[i] = Group()
stage.addActor(playerGroups[i])
}
// Add done/take listener
stage.addListener(object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
cardActors.values
.filter { it.x <= x && x <= it.x + it.width * it.scaleX && it.y <= y && y <= it.y + it.height * it.scaleY }
.forEach {
// We're clicked on a card
return true
}
if (currentThrower.index == 0 && attackCards[0] != null) {
currentThrower.sayDone()
return true
}
if (currentDefender.index == 0) {
currentDefender.sayTake()
return true
}
return true
}
})
// Initialise players
// TODO: Replace with settings
val playerNames = arrayOf("South", "West", "North", "East", "Center")
players = Array(ruleSet.playerCount) { i -> Player(ruleSet, playerNames[i], i) }
for (i in 0 until ruleSet.playerCount) {
players[i].addListener(this)
stage.addActor(players[i])
}
// Initialise card actors
val cards = deck.cards
val listener = object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
// don't allow to act while throwing/beating
if (gameState == THROWING || gameState == BEATING) return true
if (event!!.target is CardActor) {
val cardActor = event.target as CardActor
logger.debug("Trying to click ${cardActor.card}\n")
val card = cardActor.card
val user = players[0]
if (!user.hand.contains(card)) {
System.out.printf("$card is not a user's card\n")
return true
}
if (currentThrower === user) {
user.throwCard(card, attackCards, defenseCards, trumpSuit)
return true
}
if (currentDefender === user) {
val nextPlayerHandSize = nextDefender.hand.size
if (user.cardCanBePassed(card, attackCards, defenseCards, nextPlayerHandSize))
user.passWithCard(card, attackCards, defenseCards, nextPlayerHandSize)
else user.beatWithCard(card, attackCards, defenseCards, trumpSuit)
return true
}
return false
}
return super.touchDown(event, x, y, pointer, button)
}
}
for (i in cards!!.indices) {
val c = cards[i]
val cardActor = CardActor(game, c, deckStyle)
cardActors.put(c, cardActor)
cardActor.addListener(this)
cardActor.addListener(listener)
cardActor.touchable = Touchable.enabled
deckGroup.addActor(cardActor)
cardActor.zIndex = i
}
// Starting the game
for (cardActor in cardActors.values) {
cardActor.isFaceUp = false
cardActor.setScale(cardScaleTable)
cardActor.setPosition(deckPosition[0], deckPosition[1])
// cardActor.setDebug(true);
}
// Determine trump
val trumpCard = deck.cards?.get(0)
val trump = cardActors[trumpCard]
trump?.rotation = -90.0f
trump?.isFaceUp = true
trump?.moveBy(90 * cardScaleTable, 0f)
trumpSuit = trumpCard!!.suit
logger.debug("Trump suit is $trumpSuit")
// Draw cards
for (i in 0 until ruleSet.playerCount) {
drawCardsToPlayer(i, DEAL_LIMIT)
}
// TODO: Check for redeal
// Determine the first attacker and thrower
var lowestTrump = Rank.ACE
var lowestTrumpCard = Card(Suit.SPADES, Rank.ACE)
var firstAttacker = 0
for (p in players) {
for (c in p.hand) {
if (c.suit === trumpSuit && (c.rank !== Rank.ACE && c.rank.value < lowestTrump.value || lowestTrump === Rank.ACE)) {
firstAttacker = p.index
lowestTrump = c.rank
lowestTrumpCard = c
}
}
}
if (firstAttacker != 0) {
val showingTrump = cardActors[lowestTrumpCard]
val z = showingTrump?.zIndex ?: 0
showingTrump?.addAction(Actions.sequence(object : Action() {
override fun act(delta: Float): Boolean {
showingTrump.isFaceUp = true
showingTrump.zIndex = 100
return true
}
}, Actions.delay(1.5f), object : Action() {
override fun act(delta: Float): Boolean {
showingTrump.isFaceUp = false
showingTrump.zIndex = z
return true
}
}))
}
logger.debug(players[firstAttacker].name +
" (${players[firstAttacker].index})" +
" has the lowest trump $lowestTrump")
currentAttackerIndex = firstAttacker
currentThrowerIndex = firstAttacker
}
override fun show() {
}
override fun render(delta: Float) {
Gdx.gl.glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
val opponents =
when {
ruleSet.teamPlay -> (if (outOfPlay[currentAttackerIndex]) 0 else 1) + if (outOfPlay[(currentAttackerIndex + 2) % ruleSet.playerCount]) 0 else 1
(outOfPlay.map { if (it) 0 else 1 }.fold(initial = 0) { total, current -> total + current }) > 2 -> 2
else -> 1
}
if (playersSaidDone == opponents && gameState != DRAWING
&& gameState != BEATING && gameState != THROWING) {
logger.debug("Done - all players said done!")
gameState = FINISHED
}
if (oldGameState != gameState) {
logger.debug("Game state is $gameState")
tintCards()
oldGameState = gameState
}
when (gameState) {
READY -> if (currentAttacker.index != 0) {
throwLimit = min((if (ruleSet.loweredFirstDiscardLimit
&& discardPile.isEmpty())
DEAL_LIMIT else DEAL_LIMIT - 1), currentDefender.hand.size)
currentAttacker.startTurn(trumpSuit, cardsRemaining(), players.map { it.hand.size }.toTypedArray())
}
DRAWING -> {
}
THROWING -> {
}
THROWN -> {
if (currentDefender.index != 0) {
if (!isPlayerTaking) {
currentDefender.tryBeat(attackCards, defenseCards, trumpSuit, cardsRemaining(), players.map { it.hand.size }.toTypedArray())
} else {
currentDefender.sayTake()
}
}
if (isPlayerTaking)
gameState = BEATEN
}
BEATING -> {
}
BEATEN -> {
val forcedFinish =
if (currentDefender.hand.size == 0 || attackCards[throwLimit - 1] != null) {
logger.debug("Forced to finish the turn")
gameState = FINISHED
true
} else false
if (currentThrower.index != 0) {
if (!forcedFinish)
currentThrower.throwOrDone(attackCards, defenseCards, trumpSuit, cardsRemaining(), players.map { it.hand.size }.toTypedArray())
else
currentThrower.sayDone()
}
}
FINISHED -> {
val playerTook = isPlayerTaking
val currentDefenderIndex = currentDefender.index
endTurn(if (isPlayerTaking) currentDefender.index else -1)
if (isGameOver) {
logger.debug("GAME OVER")
} else {
currentAttackerIndex += if (playerTook) 2 else 1
currentAttackerIndex %= ruleSet.playerCount
if (!ruleSet.teamPlay)
// Defender who took cannot attack anyway!
while (outOfPlay[currentAttackerIndex] ||
(playerTook && currentAttackerIndex == currentDefenderIndex)) {
currentAttackerIndex++
if (currentAttackerIndex == ruleSet.playerCount)
currentAttackerIndex = 0
if (isGameOver) break
}
currentThrowerIndex = currentAttackerIndex
logger.debug("${currentAttacker.name} (${currentAttacker.index}) -> ${currentDefender.name} (${currentDefender.index})")
}
}
}
// Draw background
game.batch.transformMatrix = stage.viewport.camera.view
game.batch.projectionMatrix = stage.viewport.camera.projection
game.batch.begin()
game.batch.color = backgroundColor
game.batch.draw(background, 0f, 0f, 0, 0, Gdx.graphics.width, Gdx.graphics.height)
game.batch.color = Color(Color.WHITE)
game.batch.end()
// Draw stage
stage.act(delta)
stage.draw()
// Draw player labels
game.batch.transformMatrix = stage.viewport.camera.view
game.batch.projectionMatrix = stage.viewport.camera.projection
game.batch.begin()
for (i in 0 until ruleSet.playerCount) {
val position = (if (i == 0) playerPosition else aiPosition).clone()
if (i > 0 && ruleSet.playerCount > 2)
position[0] += ((i - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
if (screenOrientationIsPortrait) {
if (i > 0) {
position[1] -= 320 * cardScaleAI
} else {
position[1] += 760 * cardScalePlayer
}
} else {
position[1] += 640 * if (i == 0) cardScalePlayer else cardScaleAI
}
var playerFormat = "${players[i].name} (${players[i].hand.size})"
if (playerDoneStatuses[i]) playerFormat += "\n" + game.localeBundle["PlayerDone"]
if (isPlayerTaking && currentDefender.index == i)
playerFormat += "\n" + game.localeBundle["PlayerTakes"]
game.font.draw(game.batch, playerFormat,
position[0], position[1])
}
game.font.draw(game.batch, "${cardsRemaining()}", stage.viewport.worldWidth / 10f, stage.viewport.worldHeight / 3f)
var turnString = "${currentAttacker.name} -> ${currentDefender.name}"
val newLineOrSpaces = if (screenOrientationIsPortrait) " " else "\n"
if (currentAttacker.index == 0)
turnString += newLineOrSpaces + game.localeBundle["YourTurn"]
if (currentDefender.index == 0)
turnString += newLineOrSpaces + game.localeBundle["Defend"]
suitSymbols[trumpSuit]?.draw(game.batch)
if (screenOrientationIsPortrait) {
game.font.draw(game.batch, turnString, stage.viewport.worldWidth / 5f, stage.viewport.worldHeight / 3.2f)
} else {
game.font.draw(game.batch, turnString, stage.viewport.worldWidth / 40f, stage.viewport.worldHeight / 4.8f)
}
game.batch.end()
// Check if the game is over
if (isGameOver) {
var gameResult: ResultScreen.Result = if (outOfPlay[0]) WON else LOST
if (outOfPlay.all { it })
gameResult = DRAW
if (ruleSet.teamPlay) gameResult = if (outOfPlay[0]) TEAM_WON else TEAM_LOST
if (ruleSet.teamPlay && outOfPlay[1] && outOfPlay[3] && gameResult == TEAM_WON)
gameResult = if (outOfPlay[2]) TEAM_DRAW else TEAM_PARTNER_LOST
var position = players.size
val playersPlaces: Map<Int, String> = players.map { (if (places[it.index] == 0) position-- else places[it.index]) to it.name }.toMap()
game.screen = ResultScreen(game, gameResult, playersPlaces)
dispose()
}
}
override fun resize(width: Int, height: Int) {
stage.viewport.update(width, height, true)
stage.viewport.camera.update()
}
override fun pause() {
}
override fun resume() {
}
override fun hide() {
}
override fun dispose() {
}
private fun endTurn(playerIndex: Int) {
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
val tableCards = ArrayList<Card>()
for (i in attackCards.indices) {
if (attackCards[i] != null) {
tableCards.add(attackCards[i] as Card)
//attackCards[i] = null;
}
if (defenseCards[i] != null) {
tableCards.add(defenseCards[i] as Card)
//defenseCards[i] = null;
}
}
attackCards = arrayOfNulls(DEAL_LIMIT)
defenseCards = arrayOfNulls(DEAL_LIMIT)
if (playerIndex < 0) {
for (card in tableCards) {
val cardActor = cardActors[card]
discardPile.add(card)
discardPileGroup.addActor(cardActor)
cardActor?.isFaceUp = false
cardActor?.zIndex = discardPile.size - 1
cardActor?.rotation = random.nextFloat() * 20 - 10
val dx = random.nextFloat() * 20 - 10
val dy = random.nextFloat() * 20 - 10
cardActor?.addAction(
Actions.moveTo(discardPilePosition[0] + dx, discardPilePosition[1] + dy, 0.6f))
}
} else {
val player = players[playerIndex]
for (card in tableCards) {
player.addCard(card)
val cardActor = cardActors[card]
cardActor?.isFaceUp = (playerIndex == 0)
val position = (if (playerIndex == 0) playerPosition else aiPosition).clone()
if (playerIndex > 0 && ruleSet.playerCount > 2)
position[0] += ((playerIndex - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val delta = (if (playerIndex == 0) playerDelta else aiDelta).clone()
val index = player.hand.size - 1
val posX = position[0] + index * delta[0]
val posY = position[1] + index * delta[1]
cardActor?.addAction(Actions.moveTo(posX, posY, 0.4f))
cardActor?.rotation = 0.0f
cardActor?.setScale(if (playerIndex == 0) cardScalePlayer else cardScaleAI)
playerGroups[playerIndex].addActor(cardActor)
cardActor?.zIndex = index
}
player.addAction(Actions.sequence(
Actions.delay(0.39f),
SortAction(playerIndex)
))
}
if (deck.cards?.isEmpty() == false) {
for (i in 0 until ruleSet.playerCount) {
val cardsToDraw = DEAL_LIMIT - players[i].hand.size
if (cardsToDraw > 0) {
drawCardsToPlayer(i, cardsToDraw)
}
if (deck.cards?.isEmpty() != false)
break
}
}
// Check if someone is out of play
if (deck.cards?.isEmpty() != false) {
for (i in 0 until ruleSet.playerCount) {
val oldOutOfPlay = outOfPlay[i]
outOfPlay[i] = players[i].hand.size == 0
if (outOfPlay[i] && !oldOutOfPlay) {
places[i] = outOfPlay.count { it }
}
}
}
isPlayerTaking = false
gameState = READY
}
fun tintCards() {
// Tint the available cards for throwing/beating
for (a in cardActors.values) {
a.untint()
}
when {
currentThrower === players[0] && attackCards[0] != null -> {
for (c in players[0].hand) {
val actor = cardActors[c]
// If the card cannot be thrown, grey it out
if (!players[0].cardCanBeThrown(c, attackCards, defenseCards))
actor?.tint(Color.GRAY)
}
}
currentDefender === players[0] -> {
for (c in players[0].hand) {
val actor = cardActors[c]
// If the card cannot beat, grey it out
if (!players[0].cardCanBeBeaten(c, attackCards, defenseCards, trumpSuit))
actor?.tint(Color.GRAY)
// If the card can be passed, tint it green
if (players[0].cardCanBePassed(c, attackCards, defenseCards, nextDefender.hand.size))
actor?.tint(Color.GREEN)
}
}
else -> {
}
}
}
private // TODO: Generalise
val isGameOver: Boolean
get() {
if (ruleSet.teamPlay)
return outOfPlay[0] && outOfPlay[2] || outOfPlay[1] && outOfPlay[3]
else {
// Simply check if only one player remains
return (outOfPlay.map { if (it) 0 else 1 }.fold(initial = 0) { total, current -> total + current }) <= 1
}
}
val areAllCardsBeaten: Boolean
get() {
return (0 until DEAL_LIMIT).map { (attackCards[it] != null) == (defenseCards[it] != null) }
.fold(initial = true) { total, current -> total && current }
}
internal fun cardsRemaining(): Int {
return deck.cards?.size ?: 0
}
override fun handle(event: Event): Boolean {
if (event is Player.CardThrownEvent) {
// Handle when card is thrown
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
var throwIndex = 0
while (attackCards[throwIndex] != null) throwIndex++
val throwCard = event.card
attackCards[throwIndex] = throwCard
val throwCardActor = cardActors[throwCard]
throwCardActor?.isFaceUp = true
tableGroup.addActor(throwCardActor)
throwCardActor?.zIndex = 2 * throwIndex
throwCardActor?.setScale(cardScaleTable)
val throwPos = tablePosition.clone()
throwPos[0] += (90 * throwIndex).toFloat()
if (throwIndex >= 3) {
throwPos[0] += nextLineDelta[0]
throwPos[1] += nextLineDelta[1]
}
throwCardActor?.addAction(Actions.sequence(
GameStateChangedAction(GameState.THROWING),
Actions.moveTo(throwPos[0], throwPos[1], 0.4f),
Actions.delay(0.2f),
GameStateChangedAction(GameState.THROWN)))
val thrower = event.getTarget() as Player
logger.debug("${thrower.name} (${thrower.index}) throws $throwCard")
for (i in 0 until thrower.hand.size) {
val cardActor = cardActors[thrower.hand[i]]
val position = (if (thrower.index == 0) playerPosition else aiPosition).clone()
val delta = (if (thrower.index == 0) playerDelta else aiDelta).clone()
if (thrower.index > 0 && ruleSet.playerCount > 2)
position[0] += ((thrower.index - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val posX = position[0] + i * delta[0]
val posY = position[1] + i * delta[1]
//cardActor.addAction(Actions.moveTo(posX, posY, 0.1f));
cardActor?.setPosition(posX, posY)
cardActor?.rotation = 0.0f
cardActor?.setScale(if (thrower.index == 0) cardScalePlayer else cardScaleAI)
cardActor?.zIndex = i
}
return true
}
if (event is Player.CardBeatenEvent) {
// Handle when card is beaten
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
var beatIndex = 0
while (defenseCards[beatIndex] != null) beatIndex++
val beatCard = event.card
defenseCards[beatIndex] = beatCard
val beatCardActor = cardActors[beatCard]
beatCardActor?.isFaceUp = true
tableGroup.addActor(beatCardActor)
beatCardActor?.zIndex = 2 * beatIndex + 1
beatCardActor?.setScale(cardScaleTable)
val beatPos = tablePosition.clone()
beatPos[0] += (90 * beatIndex).toFloat()
if (beatIndex >= 3) {
beatPos[0] += nextLineDelta[0]
beatPos[1] += nextLineDelta[1]
}
beatCardActor?.addAction(Actions.sequence(
GameStateChangedAction(BEATING),
Actions.moveTo(beatPos[0] + tableDelta[0], beatPos[1] + tableDelta[1], 0.4f),
Actions.delay(0.2f),
GameStateChangedAction(if (areAllCardsBeaten) BEATEN else THROWN)))
val beater = event.getTarget() as Player
logger.debug("${beater.name} (${beater.index}) beats with $beatCard\n")
for (i in 0 until beater.hand.size) {
val cardActor = cardActors[beater.hand[i]]
val position = (if (beater.index == 0) playerPosition else aiPosition).clone()
val delta = (if (beater.index == 0) playerDelta else aiDelta).clone()
if (beater.index > 0 && ruleSet.playerCount > 2)
position[0] += ((beater.index - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val posX = position[0] + i * delta[0]
val posY = position[1] + i * delta[1]
//cardActor.addAction(Actions.moveTo(posX, posY, 0.1f));
cardActor?.setPosition(posX, posY)
cardActor?.rotation = 0.0f
cardActor?.setScale(if (beater.index == 0) cardScalePlayer else cardScaleAI)
cardActor?.zIndex = i
}
return true
}
if (event is Player.CardPassedEvent) {
// Handle when player passes
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
var passIndex = 0
while (attackCards[passIndex] != null) passIndex++
val passCard = event.card
attackCards[passIndex] = passCard
val passCardActor = cardActors[passCard]
passCardActor?.isFaceUp = true
tableGroup.addActor(passCardActor)
passCardActor?.zIndex = 2 * passIndex
passCardActor?.setScale(cardScaleTable)
val passPos = tablePosition.clone()
passPos[0] += (90 * passIndex).toFloat()
if (passIndex >= 3) {
passPos[0] += nextLineDelta[0]
passPos[1] += nextLineDelta[1]
}
passCardActor?.addAction(Actions.sequence(
GameStateChangedAction(GameState.THROWING),
Actions.moveTo(passPos[0], passPos[1], 0.4f),
Actions.delay(0.2f),
GameStateChangedAction(GameState.THROWN)))
val thrower = event.getTarget() as Player
logger.debug("${thrower.name} (${thrower.index}) passes with $passCard\n")
for (i in 0 until thrower.hand.size) {
val cardActor = cardActors[thrower.hand[i]]
val position = (if (thrower.index == 0) playerPosition else aiPosition).clone()
val delta = (if (thrower.index == 0) playerDelta else aiDelta).clone()
if (thrower.index > 0 && ruleSet.playerCount > 2)
position[0] += ((thrower.index - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val posX = position[0] + i * delta[0]
val posY = position[1] + i * delta[1]
//cardActor.addAction(Actions.moveTo(posX, posY, 0.1f));
cardActor?.setPosition(posX, posY)
cardActor?.rotation = 0.0f
cardActor?.setScale(if (thrower.index == 0) cardScalePlayer else cardScaleAI)
cardActor?.zIndex = i
}
do {
currentAttackerIndex++
if (currentAttackerIndex == players.size) currentAttackerIndex = 0
} while (outOfPlay[currentAttackerIndex])
currentThrowerIndex = currentAttackerIndex
logger.debug("Passed to: ${currentAttacker.name} -> ${currentDefender.name}")
}
if (event is Player.TakeEvent) {
// Handle when player takes
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
isPlayerTaking = true
val player = event.getTarget() as Player
logger.debug("${player.name} (${player.index}) decides to take")
return true
}
if (event is Player.DoneEvent) {
// Handle when player says done
playersSaidDone++
currentThrowerIndex += 2
currentThrowerIndex %= ruleSet.playerCount
val player = event.getTarget() as Player
playerDoneStatuses[player.index] = true
logger.debug("${player.name} (${player.index}) says done\n")
return true
}
return false
}
private fun drawCardsToPlayer(playerIndex: Int, cardCount: Int) {
val player = players[playerIndex]
if (!deck.cards!!.isEmpty()) {
player.addAction(Actions.sequence(
GameStateChangedAction(GameState.DRAWING),
Actions.delay(0.39f),
GameStateChangedAction(READY),
SortAction(playerIndex)
))
}
for (i in 0 until cardCount) {
if (deck.cards!!.isEmpty())
break
val card = deck.draw() as Card
player.addCard(card)
val cardActor = cardActors[card]
cardActor?.isFaceUp = (playerIndex == 0)
val position = (if (playerIndex == 0) playerPosition else aiPosition).clone()
if (playerIndex > 0 && ruleSet.playerCount > 2)
position[0] += ((playerIndex - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val delta = (if (playerIndex == 0) playerDelta else aiDelta).clone()
val index = player.hand.size - 1
val posX = position[0] + index * delta[0]
val posY = position[1] + index * delta[1]
cardActor?.addAction(Actions.moveTo(posX, posY, 0.4f))
cardActor?.rotation = 0.0f
cardActor?.setScale(if (playerIndex == 0) cardScalePlayer else cardScaleAI)
playerGroups[playerIndex].addActor(cardActor)
cardActor?.zIndex = index
}
}
private val currentAttacker: Player
get() {
if (outOfPlay[currentAttackerIndex]) {
return players[(currentAttackerIndex + 2) % ruleSet.playerCount]
}
return players[currentAttackerIndex]
}
private val currentDefender: Player
get() {
var currentDefenderIndex = (currentAttackerIndex + 1) % ruleSet.playerCount
if (!ruleSet.teamPlay)
while (outOfPlay[currentDefenderIndex]) {
currentDefenderIndex++
if (currentDefenderIndex == ruleSet.playerCount)
currentDefenderIndex = 0
}
else if (outOfPlay[currentDefenderIndex]) {
return players[(currentDefenderIndex + 2) % ruleSet.playerCount]
}
return players[currentDefenderIndex]
}
private val nextDefender: Player
get() {
var nextDefenderIndex = (currentDefender.index + 1) % ruleSet.playerCount
if (!ruleSet.teamPlay)
while (outOfPlay[nextDefenderIndex]) {
nextDefenderIndex++
if (nextDefenderIndex == ruleSet.playerCount)
nextDefenderIndex = 0
}
else if (outOfPlay[nextDefenderIndex]) {
return players[(nextDefenderIndex + 2) % ruleSet.playerCount]
}
return players[nextDefenderIndex]
}
private val currentThrower: Player
get() {
if (outOfPlay[currentThrowerIndex]) {
return players[(currentThrowerIndex + 2) % ruleSet.playerCount]
}
return players[currentThrowerIndex]
}
private fun sortPlayerCards() {
// TODO: Generalise to other players
val player = players[0]
player.sortCards(sortingMode, trumpSuit)
// Reposition all cards
for (i in 0 until player.hand.size) {
val cardActor = cardActors[player.hand[i]]
val position = (if (player.index == 0) playerPosition else aiPosition).clone()
val delta = (if (player.index == 0) playerDelta else aiDelta).clone()
if (player.index > 0)
position[0] += ((player.index - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val posX = position[0] + i * delta[0]
val posY = position[1] + i * delta[1]
cardActor?.setPosition(posX, posY)
cardActor?.rotation = 0.0f
cardActor?.setScale(if (player.index == 0) cardScalePlayer else cardScaleAI)
cardActor?.zIndex = i
}
}
companion object {
private const val DEAL_LIMIT = 6
private const val CARD_SCALE_TABLE_LANDSCAPE = 0.24f
private const val CARD_SCALE_AI_LANDSCAPE = 0.18f
private const val CARD_SCALE_PLAYER_LANDSCAPE = 0.28f
// Half-widths and half-heights
private const val HW_TABLE_LANDSCAPE = CARD_SCALE_TABLE_LANDSCAPE * 180
private const val HW_AI_LANDSCAPE = CARD_SCALE_AI_LANDSCAPE * 180
private const val HW_PLAYER_LANDSCAPE = CARD_SCALE_PLAYER_LANDSCAPE * 180
private const val HH_TABLE_LANDSCAPE = CARD_SCALE_TABLE_LANDSCAPE * 270
private const val HH_AI_LANDSCAPE = CARD_SCALE_AI_LANDSCAPE * 270
private const val HH_PLAYER_LANDSCAPE = CARD_SCALE_PLAYER_LANDSCAPE * 270
private val DECK_POSITION_LANDSCAPE = floatArrayOf(60 - HW_TABLE_LANDSCAPE, 240 - HH_TABLE_LANDSCAPE)
private val DISCARD_PILE_POSITION_LANDSCAPE = floatArrayOf(680 - HW_TABLE_LANDSCAPE, 180 - HH_TABLE_LANDSCAPE)
private val PLAYER_POSITION_LANDSCAPE = floatArrayOf(240 - HW_PLAYER_LANDSCAPE, 80 - HH_PLAYER_LANDSCAPE)
private val AI_POSITION_LANDSCAPE = floatArrayOf(60 - HW_AI_LANDSCAPE, 400 - HH_AI_LANDSCAPE)
private val TABLE_POSITION_LANDSCAPE = floatArrayOf(200 - HW_TABLE_LANDSCAPE, 280 - HH_TABLE_LANDSCAPE)
private val TABLE_DELTA_LANDSCAPE = floatArrayOf(10f, -10f)
private val PLAYER_DELTA_LANDSCAPE = floatArrayOf(40f, 0f)
private val AI_DELTA_LANDSCAPE = floatArrayOf(5f, -5f)
private val NEXT_LINE_DELTA_LANDSCAPE = floatArrayOf(0f, 0f)
private const val CARD_SCALE_TABLE_PORTRAIT = 0.20f
private const val CARD_SCALE_AI_PORTRAIT = 0.10f
private const val CARD_SCALE_PLAYER_PORTRAIT = 0.36f
// Half-widths and half-heights
private const val HW_TABLE_PORTRAIT = CARD_SCALE_TABLE_PORTRAIT * 180
private const val HW_AI_PORTRAIT = CARD_SCALE_AI_PORTRAIT * 180
private const val HW_PLAYER_PORTRAIT = CARD_SCALE_PLAYER_PORTRAIT * 180
private const val HH_TABLE_PORTRAIT = CARD_SCALE_TABLE_PORTRAIT * 270
private const val HH_AI_PORTRAIT = CARD_SCALE_AI_PORTRAIT * 270
private const val HH_PLAYER_PORTRAIT = CARD_SCALE_PLAYER_PORTRAIT * 270
private val DECK_POSITION_PORTRAIT = floatArrayOf(40 - HW_TABLE_PORTRAIT, 440 - HH_TABLE_PORTRAIT)
private val DISCARD_PILE_POSITION_PORTRAIT = floatArrayOf(440 - HW_TABLE_PORTRAIT, 440 - HH_TABLE_PORTRAIT)
private val PLAYER_POSITION_PORTRAIT = floatArrayOf(120 - HW_PLAYER_PORTRAIT, 120 - HH_PLAYER_PORTRAIT)
private val AI_POSITION_PORTRAIT = floatArrayOf(20 - HW_AI_PORTRAIT, 760 - HH_AI_PORTRAIT)
private val TABLE_POSITION_PORTRAIT = floatArrayOf(160 - HW_TABLE_PORTRAIT, 480 - HH_TABLE_PORTRAIT)
private val TABLE_DELTA_PORTRAIT = floatArrayOf(10f, -10f)
private val PLAYER_DELTA_PORTRAIT = floatArrayOf(40f, 0f)
private val AI_DELTA_PORTRAIT = floatArrayOf(5f, -5f)
private val NEXT_LINE_DELTA_PORTRAIT = floatArrayOf(-270f, -120f)
}
}
| gpl-3.0 | 52103627f777c232b12192472a3b994f | 45.051339 | 163 | 0.580655 | 4.844095 | false | false | false | false |
ElectroWeak1/libGDX_Jam | core/src/com/electroweak/game/entity/Bullet.kt | 1 | 2366 | package com.electroweak.game.entity
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.math.Vector2
import com.electroweak.game.asset.Assets
import com.electroweak.game.core.Globals
import com.electroweak.game.entity.component.*
import com.electroweak.game.entity.system.Mappers
class Bullet(val bulletDamage: BulletDamage) : Entity() {
enum class BulletDamage(val damage: Float) {
WEAK(10f),
NORMAL(20f),
STRONG(30f)
}
init {
val textureComponent = TextureComponent()
val positionComponent = PositionComponent()
val sizeComponent = SizeComponent()
val rotationComponent = RotationComponent()
val bulletComponent = BulletComponent()
val velocityComponent = VelocityComponent()
val collisionComponent = CollisionComponent()
textureComponent.textureRegion = Assets.getAtlasRegion(Assets.Resource.BULLET)
positionComponent.position = Globals.SCREEN_CENTER.cpy()
sizeComponent.width = textureComponent.textureRegion.regionWidth.toFloat()
sizeComponent.height = textureComponent.textureRegion.regionHeight.toFloat()
bulletComponent.damage = bulletDamage.damage
collisionComponent.collisionHandler = object : CollisionHandler {
override fun collision(owner: Entity, entity: Entity) {
}
}
add(textureComponent)
add(positionComponent)
add(sizeComponent)
add(rotationComponent)
add(bulletComponent)
add(velocityComponent)
add(collisionComponent)
}
fun setPosition(position: Vector2) {
val positionComponent = Mappers.POSITION_MAPPER.get(this)
positionComponent.position = position
}
fun setScale(scale: Float) {
val sizeComponent = Mappers.SIZE_MAPPER.get(this)
sizeComponent.scaleX = scale
sizeComponent.scaleY = scale
}
fun setVelocity(velocity: Vector2) {
Mappers.VELOCITY_MAPPER.get(this).velocity = velocity
}
fun setRotation(rotation: Float) {
Mappers.ROTATION_MAPPER.get(this).rotation = rotation
}
fun getPosition() : Vector2 = Mappers.POSITION_MAPPER.get(this).position!!.cpy()
fun getWidth() : Float = Mappers.SIZE_MAPPER.get(this).width
fun getHeight() : Float = Mappers.SIZE_MAPPER.get(this).height
} | mit | 7ef33c9e34b9c27eb3bcff486f4b0c92 | 30.144737 | 86 | 0.691885 | 4.666667 | false | false | false | false |
KameLong/AOdia | app/src/main/java/com/kamelong/aodia/TimeTable/OpenLineFileSelector.kt | 1 | 1205 | package com.kamelong.aodia.TimeTable
import android.app.Dialog
import android.widget.Button
import android.widget.LinearLayout
import com.kamelong.OuDia.Train
import com.kamelong.aodia.MainActivity
class OpenLineFileSelector(activity:MainActivity,listener:OnLineFileOpenSelect):Dialog(activity){
init{
val layout=LinearLayout(activity)
layout.orientation=LinearLayout.VERTICAL
setContentView(layout)
val openNormal=Button(context)
openNormal.setText("新しい路線として開く")
openNormal.setOnClickListener { listener.openAsNewLine();this.dismiss() }
val appendDown=Button(context)
appendDown.setText("下り方向に挿入する")
appendDown.setOnClickListener { listener.openAsIncludeLine(Train.DOWN);this.dismiss() }
val appendUp=Button(context)
appendUp.setText("上り方向に挿入する")
appendUp.setOnClickListener { listener.openAsIncludeLine(Train.UP);this.dismiss() }
layout.addView(openNormal)
layout.addView(appendDown)
layout.addView(appendUp)
}
}
interface OnLineFileOpenSelect{
fun openAsNewLine();
fun openAsIncludeLine(direction:Int);
}
| gpl-3.0 | 5d3c128da897445af2e9c8be6783417e | 32.794118 | 97 | 0.737163 | 3.868687 | false | false | false | false |
Nagarajj/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/Executions.kt | 1 | 3567 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.pipeline.model.Task
/**
* @return the initial stages of the execution.
*/
fun Execution<*>.initialStages() =
getStages()
.filter { it.isInitial() }
/**
* @return the stage's first before stage or `null` if there are none.
*/
fun Stage<out Execution<*>>.firstBeforeStages() =
getExecution()
.getStages()
.filter {
it.getParentStageId() == getId() && it.getSyntheticStageOwner() == STAGE_BEFORE && it.getRequisiteStageRefIds().isEmpty()
}
/**
* @return the stage's first after stage or `null` if there are none.
*/
fun Stage<out Execution<*>>.firstAfterStages() =
getExecution()
.getStages()
.filter {
it.getParentStageId() == getId() && it.getSyntheticStageOwner() == STAGE_AFTER && it.getRequisiteStageRefIds().isEmpty()
}
fun Stage<*>.isInitial() =
getRequisiteStageRefIds() == null || getRequisiteStageRefIds().isEmpty()
/**
* @return the stage's first task or `null` if there are none.
*/
fun Stage<out Execution<*>>.firstTask() = getTasks().firstOrNull()
/**
* @return the stage's parent stage.
* @throws IllegalStateException if the stage is not synthetic.
*/
fun Stage<out Execution<*>>.parent() =
getExecution()
.getStages()
.find { it.getId() == getParentStageId() } ?: throw IllegalStateException("Not a synthetic stage")
/**
* @return the task that follows [task] or `null` if [task] is the end of the
* stage.
*/
fun Stage<out Execution<*>>.nextTask(task: Task) =
if (task.isStageEnd) {
null
} else {
val index = getTasks().indexOf(task)
getTasks()[index + 1]
}
/**
* @return the stage with the specified [refId].
* @throws IllegalArgumentException if there is no such stage.
*/
fun <T : Execution<T>> Execution<T>.stageByRef(refId: String) =
stages.find { it.refId == refId } ?: throw IllegalArgumentException("No such stage")
/**
* @return all upstream stages of this stage.
*/
fun Stage<*>.upstreamStages(): List<Stage<*>> =
getExecution().getStages().filter { it.getRefId() in getRequisiteStageRefIds().orEmpty() }
/**
* @return `true` if all upstream stages of this stage were run successfully.
*/
fun Stage<*>.allUpstreamStagesComplete(): Boolean =
upstreamStages().all { it.getStatus() in listOf(SUCCEEDED, FAILED_CONTINUE, SKIPPED) }
fun Stage<*>.beforeStages(): List<Stage<*>> =
getExecution().getStages().filter { it.getParentStageId() == getId() && it.getSyntheticStageOwner() == STAGE_BEFORE }
fun Stage<*>.allBeforeStagesComplete(): Boolean =
beforeStages().all { it.getStatus() in listOf(SUCCEEDED, FAILED_CONTINUE, SKIPPED) }
| apache-2.0 | aa16f8ff3f6cc370efe8b8dfa7ae19ea | 32.971429 | 127 | 0.707037 | 4.071918 | false | false | false | false |
eugeis/ee | ee-lang_fx/src/main/kotlin/ee/lang/fx/view/ConsoleInputView.kt | 1 | 1908 | package ee.lang.fx.view
import javafx.application.Platform
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import tornadofx.borderpane
import tornadofx.bottom
import tornadofx.center
import tornadofx.textfield
import java.util.*
import java.util.function.Consumer
class ConsoleInputView : ConsoleView("ConsoleInputView") {
private val history: MutableList<String> = ArrayList()
private var historyPointer = 0
private var onMessageReceivedHandler: Consumer<String>? = null
private val input = textfield {
addEventHandler(KeyEvent.KEY_RELEASED) { keyEvent ->
when (keyEvent.code) {
KeyCode.ENTER -> {
val text = text
out.appendText(text + System.lineSeparator())
history.add(text)
historyPointer++
if (onMessageReceivedHandler != null) {
onMessageReceivedHandler!!.accept(text)
}
clear()
}
KeyCode.UP -> {
if (historyPointer > 0) {
historyPointer--
Platform.runLater {
text = history[historyPointer]
selectAll()
}
}
}
KeyCode.DOWN -> {
if (historyPointer < history.size - 1) {
historyPointer++
Platform.runLater {
text = history[historyPointer]
selectAll()
}
}
}
else -> {
}
}
}
}
override val root = borderpane {
center { add(out) }
bottom { add(input) }
}
}
| apache-2.0 | 32e5cecb150c47748759c0867730f74a | 31.338983 | 66 | 0.47065 | 5.852761 | false | false | false | false |
roadmaptravel/Rome2RioAndroid | library/src/main/java/com/getroadmap/r2rlib/models/Alternative.kt | 1 | 1433 | package com.getroadmap.r2rlib.models
import android.os.Parcel
import android.os.Parcelable
/**
* Created by jan on 11/07/16.
*
* https://www.rome2rio.com/documentation/search#Alternative
*/
open class Alternative() : Parcelable {
/**
* firstSegment integer First segment to replace (index into segments array) [1]
* lastSegment integer Last segment to replace (index into segments array) [1]
* route Route Alternative route
*/
private var firstSegment: Int? = null
private var lastSegment: Int? = null
private var route: Route? = null
constructor(parcel: Parcel) : this() {
firstSegment = parcel.readValue(Int::class.java.classLoader) as? Int
lastSegment = parcel.readValue(Int::class.java.classLoader) as? Int
route = parcel.readParcelable(Route::class.java.classLoader)
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeValue(firstSegment)
parcel.writeValue(lastSegment)
parcel.writeParcelable(route, flags)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Alternative> {
override fun createFromParcel(parcel: Parcel): Alternative {
return Alternative(parcel)
}
override fun newArray(size: Int): Array<Alternative?> {
return arrayOfNulls(size)
}
}
} | apache-2.0 | 01e631c60eb54606bc82da9bfe48d9a1 | 28.265306 | 86 | 0.661549 | 4.382263 | false | false | false | false |
kotlintest/kotlintest | kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/MultipleTestTimeoutTest.kt | 1 | 1434 | package com.sksamuel.kotest
import io.kotest.core.spec.style.FreeSpec
import kotlin.time.ExperimentalTime
import kotlin.time.milliseconds
@UseExperimental(ExperimentalTime::class)
@Suppress("BlockingMethodInNonBlockingContext")
class MultipleTestTimeoutTest : FreeSpec() {
// The test executor was failing because as it reutilizes some threads from a thread pool.
// When using that thread pool, a task to cancel the thread is created, so that the engine can interrupt
// a test that is going forever.
// However, if the task is not cancelled, it will eventually interrupt the thread when it's running another task
// in the thread pool, interrupting a test that hasn't timed out yet, which is undesired.
init {
// 100 millis sleep will "accumulate" between tests. If the context is still shared, one of them will fail
// due to timeout.
"Test 1".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 2".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 3".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 4".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 5".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 6".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 7".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
}
}
| apache-2.0 | b0415adcd60b392fd504030280f20720 | 28.875 | 114 | 0.692469 | 4.039437 | false | true | false | false |
StefanOltmann/Kaesekaestchen | app/src/main/java/de/stefan_oltmann/kaesekaestchen/ui/activities/MainActivity.kt | 1 | 2807 | /*
* Kaesekaestchen
* A simple Dots'n'Boxes Game for Android
*
* Copyright (C) Stefan Oltmann
*
* Contact : [email protected]
* Homepage: https://github.com/StefanOltmann/Kaesekaestchen
*
* This file is part of Kaesekaestchen.
*
* Kaesekaestchen 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.
*
* Kaesekaestchen 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 Kaesekaestchen. If not, see <http://www.gnu.org/licenses/>.
*/
package de.stefan_oltmann.kaesekaestchen.ui.activities
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.drawerlayout.widget.DrawerLayout.LOCK_MODE_LOCKED_CLOSED
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.navigation.NavigationView
import de.stefan_oltmann.kaesekaestchen.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
/* Es wird keine Seitennavigation benutzt. Daher dauerhaft deaktiviert. */
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
drawerLayout.setDrawerLockMode(LOCK_MODE_LOCKED_CLOSED)
val navView: NavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)
navView.setupWithNavController(navController)
}
/**
* Diese Methode muss überschrieben werden, wenn ein Menü angezeigt werden
* soll. Die App benutzt dieses um ein Beenden-Menü anzubieten.
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.menu, menu)
return true
}
/**
* Wurde in der Menüleiste eine Option gewählt, wird diese Methode
* aufgerufen.
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.app_beenden)
finish()
return super.onOptionsItemSelected(item)
}
}
| gpl-3.0 | 7191514d732457af21afa3c0ff93f869 | 32.357143 | 82 | 0.738758 | 4.277863 | false | false | false | false |
SimonMarquis/FCM-toolbox | app/src/main/java/fr/smarquis/fcm/viewmodel/PresenceLiveData.kt | 1 | 2716 | package fr.smarquis.fcm.viewmodel
import android.app.Application
import android.os.Build.MANUFACTURER
import android.os.Build.MODEL
import androidx.lifecycle.LiveData
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ServerValue
import com.google.firebase.database.ValueEventListener
import fr.smarquis.fcm.BuildConfig
import fr.smarquis.fcm.data.model.Presence
import fr.smarquis.fcm.data.model.Presence.*
import fr.smarquis.fcm.data.model.Token
import fr.smarquis.fcm.usecase.GetTokenUseCase
import fr.smarquis.fcm.utils.uuid
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
class PresenceLiveData(
application: Application,
database: FirebaseDatabase,
getTokenUseCase: GetTokenUseCase,
scope: CoroutineScope,
) : LiveData<Presence>(Offline), ValueEventListener, CoroutineScope by scope {
private var token: Token? = null
private val presenceRef: DatabaseReference = database.getReference(".info/connected")
private val connectionRef: DatabaseReference = database.getReference("devices/${uuid(application)}").apply {
onDisconnect().removeValue()
}
init {
launch {
getTokenUseCase().collectLatest {
token = it
updateMetadata()
}
}
}
override fun onActive() {
presenceRef.addValueEventListener(this)
DatabaseReference.goOnline()
updateMetadata()
}
override fun onInactive() {
clearMetadata()
DatabaseReference.goOffline()
presenceRef.removeEventListener(this)
value = Offline
}
override fun onCancelled(error: DatabaseError) {
value = Error(error)
}
override fun onDataChange(snapshot: DataSnapshot) {
value = when (snapshot.getValue(Boolean::class.java)) {
true -> Online
false, null -> Offline
}
updateMetadata()
}
private fun updateMetadata() = connectionRef.setValue(metadata(token))
private fun clearMetadata() = connectionRef.removeValue()
private fun metadata(token: Token?) = mapOf(
"name" to if (MODEL.lowercase().startsWith(MANUFACTURER.lowercase())) MODEL else MANUFACTURER.lowercase() + " " + MODEL,
"token" to when (token) {
is Token.Success -> token.value
Token.Loading, is Token.Failure, null -> null
},
"version" to BuildConfig.VERSION_CODE,
"timestamp" to ServerValue.TIMESTAMP
)
} | apache-2.0 | 210f803f82d030b5732806515f413430 | 31.345238 | 128 | 0.70324 | 4.78169 | false | false | false | false |
jitsi/jitsi-videobridge | rtp/src/main/kotlin/org/jitsi/rtp/rtp/header_extensions/SdesHeaderExtension.kt | 1 | 2640 | /*
* Copyright @ 2021 - present 8x8, 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 org.jitsi.rtp.rtp.header_extensions
import org.jitsi.rtp.rtp.RtpPacket
import org.jitsi.rtp.rtp.header_extensions.HeaderExtensionHelpers.Companion.getDataLengthBytes
import java.nio.charset.StandardCharsets
/**
* https://datatracker.ietf.org/doc/html/rfc7941#section-4.1.1
* Note: this is only the One-Byte Format, because we don't support Two-Byte yet.
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ID | len | SDES item text value ... |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
class SdesHeaderExtension {
companion object {
const val DATA_OFFSET = 1
fun getTextValue(ext: RtpPacket.HeaderExtension): String =
getTextValue(ext.currExtBuffer, ext.currExtOffset)
fun setTextValue(ext: RtpPacket.HeaderExtension, sdesValue: String) =
setTextValue(ext.currExtBuffer, ext.currExtOffset, sdesValue)
private fun getTextValue(buf: ByteArray, offset: Int): String {
val dataLength = getDataLengthBytes(buf, offset)
/* RFC 7941 says the value in RTP is UTF-8. But we use this for MID and RID values
* which are define for SDP in RFC 5888 and RFC 4566 as ASCII only. Thus we don't
* support UTF-8 to keep things simpler. */
return String(buf, offset + SdesHeaderExtension.DATA_OFFSET, dataLength, StandardCharsets.US_ASCII)
}
private fun setTextValue(buf: ByteArray, offset: Int, sdesValue: String) {
val dataLength = getDataLengthBytes(buf, offset)
assert(dataLength == sdesValue.length) { "buffer size doesn't match SDES value length" }
System.arraycopy(
sdesValue.toByteArray(StandardCharsets.US_ASCII), 0, buf,
offset + SdesHeaderExtension.DATA_OFFSET, sdesValue.length
)
}
}
}
| apache-2.0 | 43a698abace16a769f4e306a1657e015 | 45.315789 | 111 | 0.626136 | 4.251208 | false | false | false | false |
Bombe/Sone | src/test/kotlin/net/pterodactylus/sone/core/ImageInserterTest.kt | 1 | 2321 | package net.pterodactylus.sone.core
import net.pterodactylus.sone.core.FreenetInterface.InsertToken
import net.pterodactylus.sone.core.FreenetInterface.InsertTokenSupplier
import net.pterodactylus.sone.data.TemporaryImage
import net.pterodactylus.sone.data.impl.*
import net.pterodactylus.sone.test.getInstance
import net.pterodactylus.sone.test.mock
import net.pterodactylus.sone.test.whenever
import net.pterodactylus.sone.web.baseInjector
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.notNullValue
import org.junit.Test
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mockito.doThrow
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
/**
* Unit test for [ImageInserter].
*/
class ImageInserterTest {
private val temporaryImage = mock<TemporaryImage>().apply { whenever(id).thenReturn("image-id") }
private val image = ImageImpl("image-id")
private val freenetInterface = mock<FreenetInterface>()
private val insertToken = mock<InsertToken>()
private val insertTokenSupplier: InsertTokenSupplier = mock<InsertTokenSupplier>().apply { whenever(apply(any())).thenReturn(insertToken) }
private val imageInserter = ImageInserter(freenetInterface, insertTokenSupplier)
@Test
fun `inserter inserts image`() {
imageInserter.insertImage(temporaryImage, image)
verify(freenetInterface).insertImage(eq(temporaryImage), eq(image), any(InsertToken::class.java))
}
@Test
fun `exception when inserting image is ignored`() {
doThrow(SoneException::class.java).whenever(freenetInterface).insertImage(eq(temporaryImage), eq(image), any(InsertToken::class.java))
imageInserter.insertImage(temporaryImage, image)
verify(freenetInterface).insertImage(eq(temporaryImage), eq(image), any(InsertToken::class.java))
}
@Test
fun `cancelling image insert that is not running does nothing`() {
imageInserter.cancelImageInsert(image)
verify(insertToken, never()).cancel()
}
@Test
fun `cancelling image cancels the insert token`() {
imageInserter.insertImage(temporaryImage, image)
imageInserter.cancelImageInsert(image)
verify(insertToken).cancel()
}
@Test
fun `image inserter can be created by dependency injection`() {
assertThat(baseInjector.getInstance<ImageInserter>(), notNullValue())
}
}
| gpl-3.0 | ce8db24aab840dde1ad4d55a410ebd30 | 35.84127 | 140 | 0.79707 | 4.036522 | false | true | false | false |
PhilGlass/auto-moshi | processor/src/main/kotlin/glass/phil/auto/moshi/Elements.kt | 1 | 1101 | package glass.phil.auto.moshi
import com.google.auto.common.MoreElements.getPackage
import com.google.auto.common.MoreElements.isType
import com.google.auto.common.Visibility
import javax.lang.model.element.Element
import javax.lang.model.element.Modifier.STATIC
val Element.packageName get() = getPackage(this).qualifiedName.toString()
fun Element.hasAnnotation(simpleName: String) = annotationMirrors
.map { it.annotationType.asElement().simpleName }.any { it.contentEquals(simpleName) }
fun Element.isVisibleTo(other: Element) = getPackage(this) == getPackage(other) ||
Visibility.effectiveVisibilityOfElement(this) == Visibility.PUBLIC
fun Element.isEffectivelyStatic(): Boolean {
if (enclosingElement == null || !isType(enclosingElement)) {
return true
}
return modifiers.contains(STATIC) && enclosingElement.isEffectivelyStatic()
}
fun Element.generatedName(name: String = simpleName.toString()): String {
if (enclosingElement == null || !isType(enclosingElement)) {
return name
}
return enclosingElement.generatedName("${enclosingElement.simpleName}_$name")
}
| apache-2.0 | e07417c9214f6ea42b743333676903ac | 36.965517 | 90 | 0.777475 | 4.369048 | false | false | false | false |
wireapp/wire-android | storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/clients/ClientsTable127to128MigrationTest.kt | 1 | 1112 | package com.waz.zclient.storage.userdatabase.clients
import com.waz.zclient.storage.db.users.migration.USER_DATABASE_MIGRATION_127_TO_128
import com.waz.zclient.storage.userdatabase.UserDatabaseMigrationTest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
@ExperimentalCoroutinesApi
class ClientsTable127to128MigrationTest : UserDatabaseMigrationTest(127, 128) {
@Test
fun givenClientIntoClientsTableVersion127_whenMigratedToVersion128_thenAssertDataIsStillIntact() {
val id = "testId"
val data = "testData"
ClientsTableTestHelper.insertClient(
id = id,
data = data,
openHelper = testOpenHelper
)
validateMigration(USER_DATABASE_MIGRATION_127_TO_128)
runBlocking {
with(allClients()[0]) {
assertEquals(this.id, id)
assertEquals(this.data, data)
}
}
}
private suspend fun allClients() =
getDatabase().userClientDao().allClients()
}
| gpl-3.0 | 2c2fc9c22dd43901448a7e87367669ec | 29.054054 | 102 | 0.696043 | 4.557377 | false | true | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/actions/RustfmtFileAction.kt | 2 | 1958 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.execution.ExecutionException
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.toolchain.RustToolchain
import org.rust.ide.notifications.showBalloon
import org.rust.lang.core.psi.isRustFile
class RustfmtFileAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabled = getContext(e) != null
}
override fun actionPerformed(e: AnActionEvent) {
val (project, toolchain, file) = getContext(e) ?: return
val cargo = toolchain.rawCargo()
try {
cargo.reformatFile(project, file)
} catch (e: ExecutionException) {
val message = e.message ?: ""
// #1131 - Check if we get a `no such subcommand: fmt` and let the user know to install fmt
if ("no such subcommand: fmt" in message) {
project.showBalloon("Install rustfmt: https://github.com/rust-lang-nursery/rustfmt", NotificationType.ERROR)
} else {
project.showBalloon(message, NotificationType.ERROR)
}
}
}
private fun getContext(e: AnActionEvent): Triple<Project, RustToolchain, VirtualFile>? {
val project = e.project ?: return null
val toolchain = project.toolchain ?: return null
val file = e.getData(CommonDataKeys.VIRTUAL_FILE) ?: return null
if (!(file.isInLocalFileSystem && file.isRustFile)) return null
return Triple(project, toolchain, file)
}
}
| mit | bd2cc76e84da6e94e8a371f6d67da054 | 37.392157 | 124 | 0.695097 | 4.439909 | false | false | false | false |
moezbhatti/qksms | presentation/src/withAnalytics/java/com/moez/QKSMS/common/util/BillingManagerImpl.kt | 3 | 7075 | /*
* Copyright (C) 2020 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.app.Activity
import android.content.Context
import com.android.billingclient.api.AcknowledgePurchaseParams
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.SkuDetails
import com.android.billingclient.api.SkuDetailsParams
import com.android.billingclient.api.acknowledgePurchase
import com.android.billingclient.api.queryPurchaseHistory
import com.android.billingclient.api.querySkuDetails
import com.moez.QKSMS.manager.AnalyticsManager
import com.moez.QKSMS.manager.BillingManager
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class BillingManagerImpl @Inject constructor(
context: Context,
private val analyticsManager: AnalyticsManager
) : BillingManager, BillingClientStateListener, PurchasesUpdatedListener {
private val productsSubject: Subject<List<SkuDetails>> = BehaviorSubject.create()
override val products: Observable<List<BillingManager.Product>> = productsSubject
.map { skuDetailsList ->
skuDetailsList.map { skuDetails ->
BillingManager.Product(skuDetails.sku, skuDetails.price, skuDetails.priceCurrencyCode)
}
}
private val purchaseListSubject = BehaviorSubject.create<List<Purchase>>()
override val upgradeStatus: Observable<Boolean> = purchaseListSubject
.map { purchases ->
purchases
.filter { it.purchaseState == Purchase.PurchaseState.PURCHASED }
.any { it.sku in skus }
}
.distinctUntilChanged()
.doOnNext { upgraded -> analyticsManager.setUserProperty("Upgraded", upgraded) }
private val skus = listOf(BillingManager.SKU_PLUS, BillingManager.SKU_PLUS_DONATE)
private val billingClient: BillingClient = BillingClient.newBuilder(context)
.setListener(this)
.enablePendingPurchases()
.build()
private val billingClientState = MutableSharedFlow<Int>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
init {
billingClientState.tryEmit(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
}
override suspend fun checkForPurchases() = executeServiceRequest {
// Load the cached data
queryPurchases()
// On a fresh device, the purchase might not be cached, and so we'll need to force a refresh
billingClient.queryPurchaseHistory(BillingClient.SkuType.INAPP)
queryPurchases()
}
override suspend fun queryProducts() = executeServiceRequest {
val params = SkuDetailsParams.newBuilder()
.setSkusList(skus)
.setType(BillingClient.SkuType.INAPP)
val (billingResult, skuDetailsList) = billingClient.querySkuDetails(params.build())
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
productsSubject.onNext(skuDetailsList.orEmpty())
}
}
override suspend fun initiatePurchaseFlow(activity: Activity, sku: String) = executeServiceRequest {
val skuDetails = withContext(Dispatchers.IO) {
val params = SkuDetailsParams.newBuilder()
.setType(BillingClient.SkuType.INAPP)
.setSkusList(listOf(sku))
.build()
billingClient.querySkuDetails(params).skuDetailsList?.firstOrNull()!!
}
val params = BillingFlowParams.newBuilder().setSkuDetails(skuDetails)
billingClient.launchBillingFlow(activity, params.build())
}
override fun onPurchasesUpdated(result: BillingResult, purchases: MutableList<Purchase>?) {
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
GlobalScope.launch(Dispatchers.IO) {
handlePurchases(purchases.orEmpty())
}
}
}
private suspend fun queryPurchases() {
val result = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
handlePurchases(result.purchasesList.orEmpty())
}
}
private suspend fun handlePurchases(purchases: List<Purchase>) = executeServiceRequest {
purchases.forEach { purchase ->
if (!purchase.isAcknowledged) {
val params = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
.build()
Timber.i("Acknowledging purchase ${purchase.orderId}")
val result = billingClient.acknowledgePurchase(params)
Timber.i("Acknowledgement result: ${result.responseCode}, ${result.debugMessage}")
}
}
purchaseListSubject.onNext(purchases)
}
private suspend fun executeServiceRequest(runnable: suspend () -> Unit) {
if (billingClientState.first() != BillingClient.BillingResponseCode.OK) {
Timber.i("Starting billing service")
billingClient.startConnection(this)
}
billingClientState.first { state -> state == BillingClient.BillingResponseCode.OK }
runnable()
}
override fun onBillingSetupFinished(result: BillingResult) {
Timber.i("Billing response: ${result.responseCode}")
billingClientState.tryEmit(result.responseCode)
}
override fun onBillingServiceDisconnected() {
Timber.i("Billing service disconnected")
billingClientState.tryEmit(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
}
}
| gpl-3.0 | d9ebf21adc180eb647ab9b92760d496d | 39.198864 | 106 | 0.705583 | 5.179356 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2018/AocVm.kt | 1 | 5962 | package com.s13g.aoc.aoc2018
class AocVm(private val ipIdx: Int, private val program: List<Instruction>) {
private var ip = 0
private val reg = intArrayOf(0, 0, 0, 0, 0, 0)
private val ops = createOperations()
fun runUntilHalt() {
while (true) {
if (!next()) break
}
}
fun runUntilIp(ipHalt: Int) {
do {
if (!next()) break
} while (ip != ipHalt)
}
/** Returns false, if the program execution halted */
private fun next(): Boolean {
if (program.size <= ip) return false
val instr = program[ip]
// val preDbgStr = "ip=$ip [${reg.joinToString(", ")}] $instr"
reg[ipIdx] = ip
ops[instr.op]!!(instr.params, reg)
ip = reg[ipIdx]
ip++
// println("$preDbgStr [${reg.joinToString(", ")}]")
return true
}
fun getReg(i: Int) = reg[i]
}
fun parseInstructions(program: List<String>): List<Instruction> {
val result = arrayListOf<Instruction>()
for (line in program) {
if (line.startsWith("#")) continue
val split = line.split(" ")
assert(split.size == 4) { println("Invalid instruction: '$line'") }
result.add(Instruction(split[0],
Params(split[1].toInt(), split[2].toInt(), split[3].toInt())))
}
return result
}
data class Instruction(val op: String, val params: Params) {
override fun toString() = "$op $params"
}
data class Params(val a: Int, val b: Int, val c: Int) {
override fun toString() = "$a $b $c"
}
typealias Operation = (Params, IntArray) -> Unit
private fun createOperations(): HashMap<String, Operation> {
return hashMapOf(
Pair("addr", ::addr),
Pair("addi", ::addi),
Pair("mulr", ::mulr),
Pair("muli", ::muli),
Pair("banr", ::banr),
Pair("bani", ::bani),
Pair("borr", ::borr),
Pair("bori", ::bori),
Pair("setr", ::setr),
Pair("seti", ::seti),
Pair("gtir", ::gtir),
Pair("gtri", ::gtri),
Pair("gtrr", ::gtrr),
Pair("eqir", ::eqir),
Pair("eqri", ::eqri),
Pair("eqrr", ::eqrr))
}
private fun addr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] + reg[param.b]
}
private fun addi(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] + param.b
}
private fun mulr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] * reg[param.b]
}
private fun muli(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] * param.b
}
private fun banr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] and reg[param.b]
}
private fun bani(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] and param.b
}
private fun borr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] or reg[param.b]
}
private fun bori(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] or param.b
}
private fun setr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a]
}
private fun seti(param: Params, reg: IntArray) {
reg[param.c] = param.a
}
private fun gtir(param: Params, reg: IntArray) {
reg[param.c] = if (param.a > reg[param.b]) 1 else 0
}
private fun gtri(param: Params, reg: IntArray) {
reg[param.c] = if (reg[param.a] > param.b) 1 else 0
}
private fun gtrr(param: Params, reg: IntArray) {
reg[param.c] = if (reg[param.a] > reg[param.b]) 1 else 0
}
private fun eqir(param: Params, reg: IntArray) {
reg[param.c] = if (param.a == reg[param.b]) 1 else 0
}
private fun eqri(param: Params, reg: IntArray) {
reg[param.c] = if (reg[param.a] == param.b) 1 else 0
}
private fun eqrr(param: Params, reg: IntArray) {
reg[param.c] = if (reg[param.a] == reg[param.b]) 1 else 0
}
/** A way to understand the program better. */
class Decompiler(val ipIndex: Int) {
fun decompileProgram(program: List<Instruction>) {
for ((n, instr) in program.withIndex()) {
print("${n.toString().padStart(2, '0')} ")
when (instr.op) {
"addr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} + ${reg(instr.params.b)}")
}
"addi" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} + ${instr.params.b}")
}
"mulr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} * ${reg(instr.params.b)}")
}
"muli" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} * ${instr.params.b}")
}
"banr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} & ${reg(instr.params.b)}")
}
"bani" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} & ${instr.params.b}")
}
"borr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} | ${reg(instr.params.b)}")
}
"bori" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} | ${instr.params.b}")
}
"setr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)}")
}
"seti" -> {
println("${reg(instr.params.c)} = ${instr.params.a}")
}
"gtir" -> {
println("${reg(instr.params.c)} = boolToInt(${instr.params.a} > ${reg(instr.params.b)})")
}
"gtri" -> {
println("${reg(instr.params.c)} = boolToInt(${reg(instr.params.a)} > ${instr.params.b})")
}
"gtrr" -> {
println("${reg(instr.params.c)} = boolToInt(${reg(instr.params.a)} > ${reg(instr.params.b)})")
}
"eqir" -> {
println("${reg(instr.params.c)} = boolToInt(${instr.params.a} == ${reg(instr.params.b)})")
}
"eqri" -> {
println("${reg(instr.params.c)} = boolToInt(${reg(instr.params.a)} == ${instr.params.b})")
}
"eqrr" -> {
println("${reg(instr.params.c)} = boolToInt(${reg(instr.params.a)} == ${reg(instr.params.b)})")
}
else -> {
println("[MISSING: '${instr.op}']")
}
}
}
}
private fun reg(reg: Int) = if (reg == ipIndex) "ip" else "reg[$reg]"
}
| apache-2.0 | 16971e64527a9bfc2021291dc5092998 | 27.941748 | 105 | 0.555183 | 3.059005 | false | false | false | false |
domaframework/doma | integration-test-kotlin/src/test/kotlin/org/seasar/doma/it/criteria/KNativeSqlInsertTest.kt | 1 | 2626 | package org.seasar.doma.it.criteria
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.seasar.doma.it.IntegrationTestEnvironment
import org.seasar.doma.jdbc.Config
import org.seasar.doma.jdbc.SqlLogType
import org.seasar.doma.kotlin.jdbc.criteria.KNativeSql
@ExtendWith(IntegrationTestEnvironment::class)
class KNativeSqlInsertTest(config: Config) {
private val nativeSql = KNativeSql(config)
@Test
fun settings() {
val d = Department_()
val count = nativeSql
.insert(
d
) {
comment = "insert department"
queryTimeout = 1000
sqlLogType = SqlLogType.RAW
batchSize = 20
}
.values {
value(d.departmentId, 99)
value(d.departmentNo, 99)
value(d.departmentName, "aaa")
value(d.location, "bbb")
value(d.version, 1)
}
.execute()
assertEquals(1, count)
}
@Test
fun insert() {
val d = Department_()
val count = nativeSql
.insert(d)
.values {
value(d.departmentId, 99)
value(d.departmentNo, 99)
value(d.departmentName, "aaa")
value(d.location, "bbb")
value(d.version, 1)
}
.execute()
assertEquals(1, count)
}
@Test
fun insert_select_entity() {
val da = DepartmentArchive_()
val d = Department_()
val count = nativeSql
.insert(da)
.select { from(d).where { `in`(d.departmentId, listOf(1, 2)) } }
.execute()
assertEquals(2, count)
}
@Test
fun insert_select_properties() {
val da = DepartmentArchive_()
val d = Department_()
val count = nativeSql
.insert(da)
.select {
from(d).where { `in`(d.departmentId, listOf(1, 2)) }.select(
d.departmentId,
d.departmentNo,
d.departmentName,
d.location,
d.version
)
}
.execute()
assertEquals(2, count)
}
@Test
fun insert_select_using_same_entityMetamodel() {
val da = Department_("DEPARTMENT_ARCHIVE")
val d = Department_()
val count = nativeSql.insert(da).select { from(d) }.execute()
assertEquals(4, count)
}
}
| apache-2.0 | 34ad8e600ca2b017852f29e39d3c53ca | 27.543478 | 76 | 0.518279 | 4.473595 | false | true | false | false |
google/horologist | base-ui/src/main/java/com/google/android/horologist/base/ui/components/Title.kt | 1 | 1982 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.base.ui.components
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import com.google.android.horologist.base.ui.ExperimentalHorologistBaseUiApi
/**
* An alternative function to [Title] that allows a string resource id to be passed as text.
*/
@ExperimentalHorologistBaseUiApi
@Composable
public fun Title(
@StringRes textId: Int,
modifier: Modifier = Modifier
) {
Title(
text = stringResource(id = textId),
modifier = modifier
)
}
/**
* This composable fulfils the redlines of the following components:
* - Primary title;
*/
@ExperimentalHorologistBaseUiApi
@Composable
public fun Title(
text: String,
modifier: Modifier = Modifier
) {
Text(
text = text,
modifier = modifier.semantics { heading() },
textAlign = TextAlign.Center,
overflow = TextOverflow.Ellipsis,
maxLines = 3,
style = MaterialTheme.typography.title3
)
}
| apache-2.0 | 5fef3267ee15d84fb3d39860e1d0b3a1 | 29.96875 | 92 | 0.744702 | 4.33698 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/language/MdStripTrailingSpacesCoreExtension.kt | 1 | 3168 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.language
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.vladsch.md.nav.language.api.MdStripTrailingSpacesDocumentFilter
import com.vladsch.md.nav.language.api.MdStripTrailingSpacesExtension
import com.vladsch.md.nav.psi.element.*
import com.vladsch.md.nav.psi.util.MdTokenSets
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.md.nav.psi.util.MdVisitHandler
import com.vladsch.plugin.util.psi.isIn
import com.vladsch.plugin.util.psi.isTypeIn
// NOTE: this should be the first extension used, the rest can override its handlers
// so it is not registered but hard-coded in com.vladsch.md.nav.language.MdStripTrailingSpacesSmartFilter
class MdStripTrailingSpacesCoreExtension : MdStripTrailingSpacesExtension {
override fun setStripTrailingSpacesFilters(filter: MdStripTrailingSpacesDocumentFilter) {
val keepTrailingLineBreak = filter.codeStyleSettings.isKeepLineBreakSpaces
val keepCodeTrailingSpaces = filter.codeStyleSettings.keepVerbatimTrailingSpaces
val handler = CoreStripSpacedHandler(filter, keepTrailingLineBreak, keepCodeTrailingSpaces)
filter.addHandlers(
MdVisitHandler(MdOrderedListItem::class.java, handler::visit),
MdVisitHandler(MdUnorderedListItem::class.java, handler::visit),
MdVisitHandler(MdTextBlock::class.java, handler::visit),
MdVisitHandler(MdVerbatim::class.java, handler::visit),
MdVisitHandler(MdBlankLine::class.java, handler::visit)
)
}
private class CoreStripSpacedHandler internal constructor(
val filter: MdStripTrailingSpacesDocumentFilter,
val keepTrailingLineBreak: Boolean,
val keepCodeTrailingSpaces: Boolean
) {
fun visit(it: MdVerbatim) {
if (keepCodeTrailingSpaces) {
filter.disableOffsetRange(it.getContentRange(true), false)
filter.visitChildren(it);
}
}
fun visit(it: MdBlankLine) {
if (keepCodeTrailingSpaces) {
filter.disableOffsetRange(it.textRange, true)
}
}
fun visit(it: MdTextBlock) {
if (keepTrailingLineBreak) {
filter.disableOffsetRange(it.node.textRange, true)
}
}
fun visit(it: MdListItem) {
if (keepTrailingLineBreak) {
val firstChild = it.firstChild
var nextChild = firstChild?.nextSibling ?: firstChild
if (nextChild is LeafPsiElement && nextChild.isTypeIn(MdTokenSets.TASK_LIST_ITEM_MARKERS)) {
nextChild = nextChild.nextSibling
}
if (nextChild.isIn(MdTypes.EOL) || nextChild is LeafPsiElement && nextChild.isTypeIn(MdTokenSets.LIST_ITEM_MARKER_SET)) {
filter.disableOffsetRange(it.node.textRange, true)
}
}
filter.visitChildren(it);
}
}
}
| apache-2.0 | 84fbfdeb9a043c58c603867623c6481d | 41.810811 | 177 | 0.684659 | 4.821918 | false | false | false | false |
VerachadW/FireRedux | app/src/main/java/me/lazmaid/fireredux/view/home/HomeActivity.kt | 1 | 2140 | package me.lazmaid.fireredux.view.home
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.ViewGroup
import com.github.kittinunf.reactiveandroid.support.v7.widget.rx_itemsWith
import com.github.kittinunf.reactiveandroid.view.rx_click
import kotlinx.android.synthetic.main.activity_home.*
import me.lazmaid.fireredux.R
import me.lazmaid.fireredux.model.Note
import me.lazmaid.fireredux.navigation.StoreNavigator
import me.lazmaid.fireredux.presentation.HomeViewModelStore
import me.lazmaid.fireredux.presentation.HomeViewModelStore.Action
import me.lazmaid.fireredux.repository.NoteRepositoryImpl
import me.lazmaid.fireredux.view.BaseActivity
import rx.Observable
class HomeActivity : BaseActivity<HomeViewModelStore>() {
override val viewModelStore: HomeViewModelStore by lazy {
HomeViewModelStore(StoreNavigator(this), NoteRepositoryImpl())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
setSupportActionBar(tbHome)
rvNotes.apply {
layoutManager = LinearLayoutManager(this@HomeActivity)
}
fabCreate.rx_click().subscribe {
viewModelStore.dispatch(Action.CreateNewNoteAction())
}
}
override fun onStart() {
super.onStart()
val stateObservable = viewModelStore.stateChanged.share()
val notesObservable = stateObservable.map { it.items }.bindUntilDestroyed()
rvNotes.rx_itemsWith(notesObservable, onCreateViewHolder = { parent: ViewGroup?, viewType: Int ->
val view = layoutInflater.inflate(R.layout.item_note, parent, false)
HomeNoteItemViewHolder(view)
}, onBindViewHolder = { holder: HomeNoteItemViewHolder, position: Int, item: Note ->
holder.bindView(item)
holder.itemView.rx_click().bindUntilDestroyed().subscribe {
viewModelStore.dispatch(Action.OpenNoteDetailAction(item))
}
})
viewModelStore.dispatch(Action.GetNotesAction())
}
}
| mit | b1e00b4b0736ec921c16e3f7313b78f9 | 37.909091 | 105 | 0.734112 | 4.703297 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/update/UpdateComponent.kt | 1 | 4033 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.update
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PermanentInstallationID
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.components.ApplicationComponent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.EditorFactoryAdapter
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.io.HttpRequests
import org.jdom.JDOMException
import org.rust.lang.core.psi.isRustFile
import java.io.IOException
import java.net.URLEncoder
import java.net.UnknownHostException
import java.util.concurrent.TimeUnit
class UpdateComponent : ApplicationComponent, Disposable {
override fun getComponentName(): String = javaClass.name
override fun initComponent() {
if (!ApplicationManager.getApplication().isUnitTestMode) {
EditorFactory.getInstance().addEditorFactoryListener(EDITOR_LISTENER, this)
}
}
override fun disposeComponent() {
// NOP
}
override fun dispose() = disposeComponent()
object EDITOR_LISTENER : EditorFactoryAdapter() {
override fun editorCreated(event: EditorFactoryEvent) {
val document = event.editor.document
val file = FileDocumentManager.getInstance().getFile(document)
if (file != null && file.isRustFile) {
update()
}
}
}
companion object {
private val LAST_UPDATE: String = "org.rust.LAST_UPDATE"
private val PLUGIN_ID: String = "org.rust.lang"
private val LOG = Logger.getInstance(UpdateComponent::class.java)
fun update() {
val properties = PropertiesComponent.getInstance()
val lastUpdate = properties.getOrInitLong(LAST_UPDATE, 0L)
val shouldUpdate = lastUpdate == 0L || System.currentTimeMillis() - lastUpdate > TimeUnit.DAYS.toMillis(1)
if (shouldUpdate) {
properties.setValue(LAST_UPDATE, System.currentTimeMillis().toString())
val url = updateUrl
ApplicationManager.getApplication().executeOnPooledThread {
try {
HttpRequests.request(url).connect {
try {
JDOMUtil.load(it.reader)
} catch (e: JDOMException) {
LOG.warn(e)
}
LOG.info("updated: $url")
}
} catch (ignored: UnknownHostException) {
// No internet connections, no need to log anything
} catch (e: IOException) {
LOG.warn(e)
}
}
}
}
private val updateUrl: String get() {
val applicationInfo = ApplicationInfoEx.getInstanceEx()
val buildNumber = applicationInfo.build.asString()
val plugin = PluginManager.getPlugin(PluginId.getId(PLUGIN_ID))!!
val pluginId = plugin.pluginId.idString
val os = URLEncoder.encode("${SystemInfo.OS_NAME} ${SystemInfo.OS_VERSION}", Charsets.UTF_8.name())
val uid = PermanentInstallationID.get()
val baseUrl = "https://plugins.jetbrains.com/plugins/list"
return "$baseUrl?pluginId=$pluginId&build=$buildNumber&pluginVersion=${plugin.version}&os=$os&uuid=$uid"
}
}
}
| mit | bdaf8db5c544e11c2083c9a1dee9df10 | 38.930693 | 118 | 0.643442 | 5.157289 | false | false | false | false |
xiaopansky/Sketch | sample/src/main/java/me/panpf/sketch/sample/item/AppScanningItemFactory.kt | 1 | 1719 | package me.panpf.sketch.sample.item
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import me.panpf.adapter.AssemblyItem
import me.panpf.adapter.AssemblyItemFactory
import me.panpf.adapter.ktx.bindView
import me.panpf.sketch.sample.R
import me.panpf.sketch.sample.bean.AppScanning
class AppScanningItemFactory : AssemblyItemFactory<AppScanning>() {
override fun match(o: Any?): Boolean {
return o is AppScanning
}
override fun createAssemblyItem(viewGroup: ViewGroup): AppListHeaderItem {
return AppListHeaderItem(R.layout.list_item_app_scanning, viewGroup)
}
inner class AppListHeaderItem(itemLayoutId: Int, parent: ViewGroup) : AssemblyItem<AppScanning>(itemLayoutId, parent) {
private val textView: TextView by bindView(R.id.text_appScanningItem)
private val progressBar: ProgressBar by bindView(R.id.progress_appScanningItem)
override fun onConfigViews(context: Context) {
}
override fun onSetData(i: Int, scanning: AppScanning?) {
scanning ?: return
if (scanning.running) {
val progress = if (scanning.totalLength > 0) (scanning.completedLength.toFloat() / scanning.totalLength * 100).toInt() else 0
textView.text = String.format("已发现%d个安装包, %d%%", scanning.count, progress)
progressBar.visibility = View.VISIBLE
} else {
textView.text = String.format("共发现%d个安装包,用时%d秒", scanning.count, scanning.time / 1000)
progressBar.visibility = View.GONE
}
}
}
}
| apache-2.0 | 618ac6208e2ef65142ec7f474d165344 | 38.139535 | 141 | 0.695187 | 4.197007 | false | false | false | false |
OdysseusLevy/kale | src/main/kotlin/org/kale/mail/StoreWrapper.kt | 1 | 8246 | package org.kale.mail
import com.sun.mail.imap.IMAPFolder
import com.sun.mail.imap.IMAPStore
import org.apache.logging.log4j.LogManager
import java.time.Instant
import java.util.*
import javax.mail.*
import javax.mail.internet.MimeMessage
import javax.mail.search.ComparisonTerm
import javax.mail.search.ReceivedDateTerm
/**
*
*/
class StoreWrapper(val account: EmailAccountConfig,
val store: IMAPStore = createStore("imaps"), // default to ssl connection
val dryRun: Boolean = false
) {
//
// Public
//
val expunge = (dryRun == false)
fun scanFolder(folderName: String, callback: MailCallback, startUID: Long = -1, doFirstRead: Boolean = true): Unit {
checkStore()
ImapFolderScanner(this, folderName, callback, startUID, doFirstRead).startScanning()
}
fun getMessages(folderName: String, limit: Int = 0): List<MessageHelper>
{
return getMessages(folderName, { folder ->
val start = if (limit <= 0 || limit >= folder.getMessageCount()) 1 else folder.getMessageCount() - limit + 1
val count = folder.getMessageCount()
folder.getMessages(start, count)
})
}
fun getMessagesAfterUID(folderName: String, start: Long) =
getMessagesByUIDRange(folderName, start + 1)
fun getMessagesByUIDRange(folderName: String, startUID: Long,
endUID: Long = UIDFolder.LASTUID): List<MessageHelper>
{
return getMessages(folderName, {folder ->
if (folder !is IMAPFolder)
throw imapError(folder)
folder.getMessagesByUID(startUID, endUID)
})
}
fun getEmailsBeforeDate(folderName: String, date: Instant) =
getEmailsBeforeDate(folderName, Date.from(date))
fun getEmailsBeforeDate(folderName: String, date: Date): List<MessageHelper> {
val olderThan = ReceivedDateTerm(ComparisonTerm.LT, date)
return getMessages(folderName, { folder ->
fetch(folder.search(olderThan), folder)
})
}
fun getEmailsAfterDate(folderName: String, instant: Instant) =
getEmailsAfterDate(folderName,Date.from(instant))
fun getEmailsAfterDate(folderName: String, date: Date): List<MessageHelper> {
val newerThan = ReceivedDateTerm(ComparisonTerm.GT, date)
return getMessages(folderName, { folder ->
fetch(folder.search(newerThan), folder)
})
}
fun getEmailsByUID(folderName: String, ids: List<Long>): List<MessageHelper> {
return getMessages(folderName, { folder ->
if (folder !is IMAPFolder)
throw imapError(folder)
folder.getMessagesByUID(ids.toLongArray())
})
}
fun moveTo(toFolderName: String, m: MessageHelper) {
if (dryRun) {
logger.info("DRY RUN -- moving message from: ${m.from} subject: ${m.subject} to folder: $toFolderName")
return
}
val fromFolder = getFolder(m.folderName)
val toFolder = getFolder(toFolderName)
try {
if (!toFolder.exists()){
logger.warn("ignoring request to move message to folder that does not exist: $toFolderName")
return
}
val message = getMessageByUID(fromFolder, m.uid)
val newMessage = MimeMessage(message)
newMessage.removeHeader(MoveHeader)
newMessage.addHeader(MoveHeader, toFolderName)
val messageArray = arrayOf(newMessage)
logger.info("moving mail from: ${m.from} subject: ${m.subject} " +
"from folder: ${m.folderName} to folder: $toFolderName")
toFolder.appendMessages(messageArray)
message.setFlag(Flags.Flag.DELETED, true)
} catch (e: Exception){
logger.warn("failed moving message to folder: $toFolderName", e)
} finally {
closeFolder(fromFolder)
closeFolder(toFolder)
}
}
fun delete(permanent: Boolean, m: MessageHelper): Unit {
if (dryRun) {
logger.info("DRY RUN -- deleting message from: ${m.from} subject: ${m.subject}")
return
}
if (permanent)
permanentDelete(m)
else
moveTo(MailUtils.trashFolder(account), m)
}
fun permanentDelete(m: MessageHelper) {
val folder = getFolder(m.folderName)
try {
val message = getMessageByUID(folder,m.uid)
message.setFlag(Flags.Flag.DELETED, true)
} finally {
closeFolder(folder)
}
}
fun getFolders(): List<FolderWrapper> {
checkStore()
return store.getDefaultFolder().list("*").map{f -> FolderWrapper.create(f, this)}
}
fun hasFolder(name: String): Boolean {
return getFolder(name).exists()
}
//
// Internal
//
internal fun getMessageByUID(folder: Folder, uid: Long): MimeMessage {
if (folder !is IMAPFolder)
throw imapError(folder)
return folder.getMessageByUID(uid) as MimeMessage
}
internal fun <T>doWithFolder(folderName: String, lambda: (Folder) -> T): T {
val folder = getFolder(folderName)
try {
return lambda(folder)
} finally {
closeFolder(folder)
}
}
fun getMessages(folderName: String, lambda: (Folder) -> Array<Message>): List<MessageHelper>
{
return doWithFolder(folderName, { folder ->
val messages = lambda(folder)
fetch(messages, folder)
messages.map{MessageHelper.create(it, this)}
})
}
internal fun getFolder(folderName: String): Folder {
checkStore()
val folder = store.getFolder(folderName)
folder.open(getPermission())
return folder
}
internal fun closeFolder(folder: Folder?) {
if (folder != null && folder.isOpen()) {
try {
folder.close(expunge)
} catch (e: Exception) {
logger.info(e)
}
}
}
private fun imapError(folder: Folder): Exception {
return RuntimeException("folder: ${folder.name} for: ${account.user} does not support UID's")
}
private fun fetchMessages(messages: Array<Message>) = messages.map {
MessageHelper.create(it as MimeMessage, this)}
private fun getPermission() = if (dryRun) Folder.READ_ONLY else Folder.READ_WRITE
private fun getEmails(messages: Array<Message>, folder: Folder): List<MessageHelper> {
fetch(messages, folder)
return messages.map { m: Message -> MessageHelper.create(m as MimeMessage, this) }
}
fun checkStore(): Boolean {
if (!store.isConnected) {
logger.info("store connecting to account: ${account.imapHost} user: ${account.user}")
store.connect(account.imapHost, account.user, account.password)
return true
} else {
return false
}
}
companion object {
val logger = LogManager.getLogger(StoreWrapper::class.java.name)
val defaultFetchProfile = createDefaultFetchProfile()
val MoveHeader = "Mailscript-Move"
private fun fetch(messages: Array<Message>, folder: Folder): Array<Message> {
logger.debug("fetching ${messages.count()} email(s) from ${folder.name}")
folder.fetch(messages, defaultFetchProfile)
logger.debug("finishing fetch for ${folder.getName()}")
return messages
}
fun createStore(storeName: String,
session: Session = Session.getDefaultInstance(Properties(), null)): IMAPStore {
return session.getStore(storeName) as IMAPStore
}
fun createDefaultFetchProfile(): FetchProfile {
val fp = FetchProfile()
fp.add(FetchProfile.Item.ENVELOPE)
fp.add(FetchProfile.Item.FLAGS)
fp.add(FetchProfile.Item.SIZE)
fp.add(UIDFolder.FetchProfileItem.UID)
fp.add(IMAPFolder.FetchProfileItem.HEADERS) //load all headers
return fp
}
}
}
| apache-2.0 | 5ace9f35df9a0bbd470e585ab5e801dc | 30.116981 | 120 | 0.606718 | 4.619608 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/upload/UploadController.kt | 1 | 2233 | package de.westnordost.streetcomplete.data.upload
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import javax.inject.Inject
import javax.inject.Singleton
/** Controls uploading */
@Singleton class UploadController @Inject constructor(
private val context: Context
): UploadProgressSource {
private var uploadServiceIsBound = false
private var uploadService: UploadService.Interface? = null
private val uploadServiceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
uploadService = service as UploadService.Interface
uploadService?.setProgressListener(uploadProgressRelay)
}
override fun onServiceDisconnected(className: ComponentName) {
uploadService = null
}
}
private val uploadProgressRelay = UploadProgressRelay()
/** @return true if an upload is running */
override val isUploadInProgress: Boolean get() =
uploadService?.isUploadInProgress == true
var showNotification: Boolean
get() = uploadService?.showUploadNotification == true
set(value) { uploadService?.showUploadNotification = value }
init {
bindServices()
}
/** Collect and upload all changes made by the user */
fun upload() {
if (uploadService == null) return
context.startService(UploadService.createIntent(context))
}
private fun bindServices() {
uploadServiceIsBound = context.bindService(
Intent(context, UploadService::class.java),
uploadServiceConnection, Context.BIND_AUTO_CREATE
)
}
private fun unbindServices() {
if (uploadServiceIsBound) context.unbindService(uploadServiceConnection)
uploadServiceIsBound = false
}
override fun addUploadProgressListener(listener: UploadProgressListener) {
uploadProgressRelay.addListener(listener)
}
override fun removeUploadProgressListener(listener: UploadProgressListener) {
uploadProgressRelay.removeListener(listener)
}
}
| gpl-3.0 | 6fe18a285f7e6b06efc957b3131857f1 | 32.833333 | 89 | 0.720107 | 5.710997 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/androidTest/java/org/wordpress/android/fluxc/release/ReleaseStack_EncryptedLogTest.kt | 2 | 4926 | package org.wordpress.android.fluxc.release
import org.greenrobot.eventbus.Subscribe
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.hasItem
import org.junit.Assert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Ignore
import org.junit.Test
import org.wordpress.android.fluxc.TestUtils
import org.wordpress.android.fluxc.generated.EncryptedLogActionBuilder
import org.wordpress.android.fluxc.release.ReleaseStack_EncryptedLogTest.TestEvents.ENCRYPTED_LOG_UPLOADED_SUCCESSFULLY
import org.wordpress.android.fluxc.release.ReleaseStack_EncryptedLogTest.TestEvents.ENCRYPTED_LOG_UPLOAD_FAILED_WITH_INVALID_UUID
import org.wordpress.android.fluxc.store.EncryptedLogStore
import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded
import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded.EncryptedLogFailedToUpload
import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded.EncryptedLogUploadedSuccessfully
import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.InvalidRequest
import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.TooManyRequests
import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogPayload
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import javax.inject.Inject
private const val NUMBER_OF_LOGS_TO_UPLOAD = 2
private const val TEST_UUID_PREFIX = "TEST-UUID-"
private const val INVALID_UUID = "INVALID_UUID" // Underscore is not allowed
@Ignore("Temporarily disabled: Tests are only failing in CircleCI and will be debugged next week")
class ReleaseStack_EncryptedLogTest : ReleaseStack_Base() {
@Inject lateinit var encryptedLogStore: EncryptedLogStore
private var nextEvent: TestEvents? = null
private enum class TestEvents {
NONE,
ENCRYPTED_LOG_UPLOADED_SUCCESSFULLY,
ENCRYPTED_LOG_UPLOAD_FAILED_WITH_INVALID_UUID
}
@Throws(Exception::class)
override fun setUp() {
super.setUp()
mReleaseStackAppComponent.inject(this)
init()
nextEvent = TestEvents.NONE
}
@Test
fun testQueueForUpload() {
nextEvent = ENCRYPTED_LOG_UPLOADED_SUCCESSFULLY
val testIds = testIds()
mCountDownLatch = CountDownLatch(testIds.size)
testIds.forEach { uuid ->
val payload = UploadEncryptedLogPayload(
uuid = uuid,
file = createTempFileWithContent(suffix = uuid, content = "Testing FluxC log upload for $uuid"),
shouldStartUploadImmediately = true
)
mDispatcher.dispatch(EncryptedLogActionBuilder.newUploadLogAction(payload))
}
assertTrue(mCountDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS))
}
@Test
fun testQueueForUploadForInvalidUuid() {
nextEvent = ENCRYPTED_LOG_UPLOAD_FAILED_WITH_INVALID_UUID
mCountDownLatch = CountDownLatch(1)
val payload = UploadEncryptedLogPayload(
uuid = INVALID_UUID,
file = createTempFile(suffix = INVALID_UUID),
shouldStartUploadImmediately = true
)
mDispatcher.dispatch(EncryptedLogActionBuilder.newUploadLogAction(payload))
assertTrue(mCountDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS))
}
@Suppress("unused")
@Subscribe
fun onEncryptedLogUploaded(event: OnEncryptedLogUploaded) {
when (event) {
is EncryptedLogUploadedSuccessfully -> {
assertThat(nextEvent, `is`(ENCRYPTED_LOG_UPLOADED_SUCCESSFULLY))
assertThat(testIds(), hasItem(event.uuid))
}
is EncryptedLogFailedToUpload -> {
when (event.error) {
is TooManyRequests -> {
// If we are hitting too many requests, we just ignore the test as restarting it will not help
assertThat(event.willRetry, `is`(true))
}
is InvalidRequest -> {
assertThat(nextEvent, `is`(ENCRYPTED_LOG_UPLOAD_FAILED_WITH_INVALID_UUID))
assertThat(event.willRetry, `is`(false))
}
else -> {
throw AssertionError("Unexpected error occurred in onEncryptedLogUploaded: ${event.error}")
}
}
}
}
mCountDownLatch.countDown()
}
private fun testIds() = (1..NUMBER_OF_LOGS_TO_UPLOAD).map { i ->
"$TEST_UUID_PREFIX$i"
}
private fun createTempFileWithContent(suffix: String, content: String): File {
val file = createTempFile(suffix = suffix)
file.writeText(content)
return file
}
}
| gpl-2.0 | 56ee7c18b6963692075c3b4a775e27da | 41.102564 | 129 | 0.689809 | 5.001015 | false | true | false | false |
BasinMC/Basin | faucet/src/main/kotlin/org/basinmc/faucet/event/extension/ExtensionRunEvent.kt | 1 | 1807 | /*
* Copyright 2019 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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.basinmc.faucet.event.extension
import org.basinmc.faucet.event.StatelessEvent
import org.basinmc.faucet.extension.Extension
import org.basinmc.faucet.extension.Extension.Phase
import org.basinmc.faucet.util.BitMask
/**
* @author [Johannes Donath](mailto:[email protected])
*/
interface ExtensionRunEvent<S> : ExtensionPhaseEvent<S> {
/**
* {@inheritDoc}
*/
override val currentPhase: Phase
get() = Phase.LOADED
/**
* {@inheritDoc}
*/
override val targetPhase: Phase
get() = Phase.RUNNING
class Pre @JvmOverloads constructor(extension: Extension, state: State = State.RUN) :
AbstractStatefulExtensionEvent<State>(extension, state), ExtensionRunEvent<State>
class Post(extension: Extension) : AbstractExtensionEvent<Unit>(extension),
ExtensionRunEvent<Unit>, StatelessEvent
class State(mask: Int) : BitMask<State>(mask) {
override val definition = Companion
companion object : Definition<State> {
val RUN = State(1)
override val values = listOf(RUN)
override fun newInstance(mask: Int) = State(mask)
}
}
}
| apache-2.0 | 3435fbffecbf17f0a288bfd4834c7974 | 29.627119 | 87 | 0.727726 | 4.125571 | false | false | false | false |
ChrisZhong/organization-model | chazm-model/src/main/kotlin/runtimemodels/chazm/model/relation/NeedsEvent.kt | 2 | 1586 | package runtimemodels.chazm.model.relation
import runtimemodels.chazm.api.entity.Attribute
import runtimemodels.chazm.api.entity.AttributeId
import runtimemodels.chazm.api.entity.Role
import runtimemodels.chazm.api.entity.RoleId
import runtimemodels.chazm.api.id.UniqueId
import runtimemodels.chazm.api.relation.Needs
import runtimemodels.chazm.model.event.AbstractEvent
import runtimemodels.chazm.model.event.EventType
import runtimemodels.chazm.model.message.M
import java.util.*
import javax.inject.Inject
/**
* The [NeedsEvent] class indicates that there is an update about a [Needs] relation.
*
* @author Christopher Zhong
* @since 7.0.0
*/
open class NeedsEvent @Inject internal constructor(
category: EventType,
needs: Needs
) : AbstractEvent(category) {
/**
* Returns a [UniqueId] that represents a [Role].
*
* @return a [UniqueId].
*/
val roleId: RoleId = needs.role.id
/**
* Returns a [UniqueId] that represents a [Attribute].
*
* @return a [UniqueId].
*/
val attributeId: AttributeId = needs.attribute.id
override fun equals(other: Any?): Boolean {
if (other is NeedsEvent) {
return super.equals(other) && roleId == other.roleId && attributeId == other.attributeId
}
return false
}
override fun hashCode(): Int = Objects.hash(category, roleId, attributeId)
override fun toString(): String = M.EVENT_WITH_2_IDS[super.toString(), roleId, attributeId]
companion object {
private const val serialVersionUID = -2368504360543452399L
}
}
| apache-2.0 | d65a557e926d32d693c6c3603c2d7342 | 28.924528 | 100 | 0.70681 | 4.108808 | false | false | false | false |
raatiniemi/worker | app/src/main/java/me/raatiniemi/worker/data/projects/TimeIntervalEntity.kt | 1 | 2217 | /*
* Copyright (C) 2018 Tobias Raatiniemi
*
* 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, version 2 of the License.
*
* 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 me.raatiniemi.worker.data.projects
import androidx.room.*
import androidx.room.ForeignKey.CASCADE
import me.raatiniemi.worker.domain.model.TimeInterval
@Entity(
tableName = "time_intervals",
foreignKeys = [
ForeignKey(
entity = ProjectEntity::class,
parentColumns = ["_id"],
childColumns = ["project_id"],
onDelete = CASCADE
)
],
indices = [
Index(name = "index_project_id", value = ["project_id"])
]
)
data class TimeIntervalEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "_id")
val id: Long = 0,
@ColumnInfo(name = "project_id")
val projectId: Long,
@ColumnInfo(name = "start_in_milliseconds")
val startInMilliseconds: Long,
@ColumnInfo(name = "stop_in_milliseconds")
val stopInMilliseconds: Long = 0,
val registered: Long = 0
) {
internal fun toTimeInterval() = TimeInterval(
id = id,
projectId = projectId,
startInMilliseconds = startInMilliseconds,
stopInMilliseconds = stopInMilliseconds,
isRegistered = registered == 1L
)
}
internal fun TimeInterval.toEntity() = TimeIntervalEntity(
id = id ?: 0,
projectId = projectId,
startInMilliseconds = startInMilliseconds,
stopInMilliseconds = stopInMilliseconds,
registered = if (isRegistered) {
1
} else {
0
}
)
| gpl-2.0 | 5d04184b16f79f39537619cade27d742 | 31.602941 | 72 | 0.618854 | 4.830065 | false | false | false | false |
googlecodelabs/watchnext-for-movie-tv-episodes | step_4_completed/src/main/java/com/android/tv/reference/shared/watchprogress/WatchProgress.kt | 9 | 1758 | /*
* 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.android.tv.reference.shared.watchprogress
import androidx.lifecycle.LiveData
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
/**
* Room class and interface for tracking watch progress of videos.
*
* This is basically how much of a video the user has watched according to ExoPlayer, which allows
* users to resume from where they were watching the video previously.
*/
@Entity(tableName = "watch_progress")
data class WatchProgress(
// A unique identifier for the video
@PrimaryKey
@ColumnInfo(name = "video_id") var videoId: String,
@ColumnInfo(name = "start_position") var startPosition: Long
)
@Dao
interface WatchProgressDao {
@Query("SELECT * FROM watch_progress WHERE video_id = :videoId LIMIT 1")
fun getWatchProgressByVideoId(videoId: String): LiveData<WatchProgress>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(watchProgress: WatchProgress)
@Query("DELETE FROM watch_progress")
suspend fun deleteAll()
}
| apache-2.0 | 08ac3766c03269fd729512a4f57d8de5 | 32.807692 | 98 | 0.758248 | 4.277372 | false | false | false | false |
cempo/SimpleTodoList | app/src/main/java/com/makeevapps/simpletodolist/ui/activity/MainActivity.kt | 1 | 6122 | package com.makeevapps.simpletodolist.ui.activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.Toolbar
import android.view.LayoutInflater
import com.makeevapps.simpletodolist.R
import com.makeevapps.simpletodolist.databinding.ActivityMainBinding
import com.makeevapps.simpletodolist.databinding.ViewMenuHeaderBinding
import com.makeevapps.simpletodolist.enums.MainMenuItemType
import com.makeevapps.simpletodolist.ui.fragment.CalendarFragment
import com.makeevapps.simpletodolist.ui.fragment.TodayFragment
import com.makeevapps.simpletodolist.utils.DateUtils
import com.makeevapps.simpletodolist.utils.UIUtils
import com.makeevapps.simpletodolist.viewmodel.MainViewModel
import com.mikepenz.materialdrawer.Drawer
import com.mikepenz.materialdrawer.DrawerBuilder
import com.mikepenz.materialdrawer.holder.DimenHolder
import com.mikepenz.materialdrawer.holder.StringHolder
import com.mikepenz.materialdrawer.model.DividerDrawerItem
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem
class MainActivity : BaseActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var drawer: Drawer
companion object {
fun getActivityIntent(context: Context, clearFlag: Boolean = true): Intent {
val intent = Intent(context, MainActivity::class.java)
if (clearFlag) intent.addFlags(UIUtils.getClearFlags())
return intent
}
}
val model: MainViewModel by lazy {
ViewModelProviders.of(this).get(MainViewModel::class.java)
}
val binding: ActivityMainBinding by lazy {
DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.controller = this
binding.model = model
model.preferenceManager.getSharedPreferences().registerOnSharedPreferenceChangeListener(this)
val headerBinding = DataBindingUtil.inflate<ViewMenuHeaderBinding>(LayoutInflater.from(this), R.layout
.view_menu_header, null, false)
headerBinding.controller = this
headerBinding.date = DateUtils.currentTime()
drawer = DrawerBuilder()
.withActivity(this)
.withHeader(headerBinding.root)
.withHeaderHeight(DimenHolder.fromDp(200))
.withTranslucentStatusBar(false)
.withHasStableIds(true)
.withSavedInstance(savedInstanceState)
.addDrawerItems(
createMenuItemByType(MainMenuItemType.TODAY, true),
createMenuItemByType(MainMenuItemType.CALENDAR, true),
DividerDrawerItem(),
createMenuItemByType(MainMenuItemType.SETTINGS, false)
)
.withSelectedItem(1)
.withOnDrawerItemClickListener { _, _, drawerItem ->
if (drawerItem != null) {
val menuItem = MainMenuItemType.getItemById(drawerItem.identifier)
selectMenuItem(menuItem)
}
false
}
.build()
if (savedInstanceState == null) {
selectMenuItem(MainMenuItemType.TODAY)
}
observeTaskData()
}
private fun createMenuItemByType(type: MainMenuItemType, selectable: Boolean): PrimaryDrawerItem {
return PrimaryDrawerItem()
.withIdentifier(type.id)
.withName(type.textResId)
.withIcon(type.imageResId)
.withSelectable(selectable)
.withIconTintingEnabled(true)
}
private fun observeTaskData() {
model.getTasksCount().observe(this, Observer<Int> { tasksCount ->
if (tasksCount != null) {
drawer.updateBadge(1, StringHolder("$tasksCount"))
}
})
}
private fun selectMenuItem(menuItem: MainMenuItemType) {
when (menuItem) {
MainMenuItemType.TODAY -> {
showFragment(TodayFragment.newInstance())
}
MainMenuItemType.CALENDAR -> {
showFragment(CalendarFragment.newInstance())
}
MainMenuItemType.SETTINGS -> {
startActivity(SettingsActivity.getActivityIntent(this))
}
}
}
private fun showFragment(fragment: Fragment) {
//val lastFragment = supportFragmentManager.findFragmentById(R.id.container)
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commitNowAllowingStateLoss()
}
fun setToolbar(toolbar: Toolbar, homeAsUp: Boolean, homeEnabled: Boolean, title: String?) {
setSupportActionBar(toolbar, homeAsUp, homeEnabled, title)
drawer.setToolbar(this, toolbar, true)
//drawer.drawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(this, R.color.status_bar))
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (!key.isNullOrEmpty() && key == getString(R.string.is24HourFormat)) {
selectMenuItem(MainMenuItemType.getItemById(drawer.currentSelection))
}
}
override fun onSaveInstanceState(outState: Bundle?) {
val newOutState = drawer.saveInstanceState(outState)
super.onSaveInstanceState(newOutState)
}
override fun onBackPressed() {
if (drawer.isDrawerOpen) {
drawer.closeDrawer()
} else {
super.onBackPressed()
}
}
override fun onDestroy() {
model.preferenceManager.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this)
super.onDestroy()
}
}
| mit | f0fa741f1b2bc7b2fc970e2b89ab27d9 | 37.2625 | 110 | 0.672983 | 5.590868 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/FilterParser.kt | 1 | 4274 | package com.pr0gramm.app.ui
import android.net.Uri
import com.google.code.regexp.Pattern
import com.pr0gramm.app.Instant
import com.pr0gramm.app.feed.FeedFilter
import com.pr0gramm.app.feed.FeedType
import com.pr0gramm.app.ui.fragments.CommentRef
import java.util.*
object FilterParser {
fun parse(uri: Uri, notificationTime: Instant? = null): FeedFilterWithStart? {
val uriPath = uri.encodedPath ?: "/"
val commentId = extractCommentId(uriPath)
// get the path without optional comment link
val path = uriPath.replaceFirst(reCommentSuffix, "")
for (pattern in patterns) {
val matcher = pattern.matcher(path)
if (!matcher.matches()) {
continue
}
val encodedGroups = matcher.namedGroups().firstOrNull()?.toMap() ?: continue
val values = encodedGroups.mapValues { decodeUrlComponent(it.value) }
var filter = FeedFilter().withFeedType(FeedType.NEW)
if (values["type"] == "top") {
filter = filter.withFeedType(FeedType.PROMOTED)
}
if (values["type"] == "stalk") {
filter = filter.withFeedType(FeedType.STALK)
}
val tag = values["tag"]
val user = values["user"]
if (!user.isNullOrBlank()) {
when (val subcategory = values["subcategory"]) {
null, "uploads" -> {
filter = filter
.withFeedType(FeedType.NEW)
.basicWithUser(user)
.withTagsNoReset(tag)
}
else -> {
val collectionTitle = subcategory.replaceFirstChar { ch ->
if (ch.isLowerCase()) ch.titlecase(Locale.getDefault()) else ch.toString()
}
filter = filter
.withFeedType(FeedType.NEW)
.basicWithCollection(user, subcategory, collectionTitle)
}
}
}
if (filter.tags == null && !tag.isNullOrBlank()) {
filter = filter.withTagsNoReset(tag)
}
val itemId = values["id"]?.toLongOrNull()
return FeedFilterWithStart(filter, itemId, commentId, notificationTime)
}
return null
}
private fun decodeUrlComponent(value: String): String {
return Uri.decode(value)
}
/**
* Returns the comment id from the path or null, if no comment id
* is provided.
*/
private fun extractCommentId(path: String): Long? {
val matcher = Pattern.compile(":comment([0-9]+)$").matcher(path)
return if (matcher.find()) matcher.group(1).toLongOrNull() else null
}
private val reCommentSuffix = ":comment[0-9]+$".toRegex()
private val pFeed = Pattern.compile("^/(?<type>new|top|stalk)$")
private val pFeedId = Pattern.compile("^/(?<type>new|top|stalk)/(?<id>[0-9]+)$")
private val pUser = Pattern.compile("^/user/(?<user>[^/]+)/?$")
private val pUserUploads = Pattern.compile("^/user/(?<user>[^/]+)/(?<subcategory>uploads|[^/]+)/?$")
private val pUserUploadsId = Pattern.compile("^/user/(?<user>[^/]+)/(?<subcategory>uploads|[^/]+)/(?<id>[0-9]+)$")
private val pUserUploadsWithTag = Pattern.compile("^/user/(?<user>[^/]+)/(?<subcategory>uploads)/(?<tag>[^/]+)$")
private val pUserUploadsWithTagId =
Pattern.compile("^/user/(?<user>[^/]+)/(?<subcategory>uploads|[^/]+)/(?<tag>[^/]+)/(?<id>[0-9]+)$")
private val pTag = Pattern.compile("^/(?<type>new|top)/(?<tag>[^/]+)$")
private val pTagId = Pattern.compile("^/(?<type>new|top)/(?<tag>[^/]+)/(?<id>[0-9]+)$")
private val patterns = listOf(
pFeed,
pFeedId,
pUser,
pUserUploads,
pUserUploadsId,
pUserUploadsWithTag,
pUserUploadsWithTagId,
pTag,
pTagId,
)
}
class FeedFilterWithStart(
val filter: FeedFilter, start: Long?, commentId: Long?,
notificationTime: Instant?
) {
val start: CommentRef? = if (start != null) CommentRef(start, commentId, notificationTime) else null
}
| mit | 51d907f42b9a432a014057c168d80819 | 35.220339 | 118 | 0.55592 | 4.676149 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/builder/lookup/GivenServerInfoErrorXml/WhenParsingTheServerInfo.kt | 2 | 1637 | package com.lasthopesoftware.bluewater.client.connection.builder.lookup.GivenServerInfoErrorXml
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.RequestServerInfoXml
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.ServerDiscoveryException
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.ServerLookup
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
import xmlwise.Xmlwise
import java.util.concurrent.ExecutionException
class WhenParsingTheServerInfo {
companion object {
private var exception: ServerDiscoveryException? = null
@BeforeClass
@JvmStatic
fun before() {
val serverInfoXml = mockk<RequestServerInfoXml>()
every { serverInfoXml.promiseServerInfoXml(any()) } returns Promise(
Xmlwise.createXml(
"""<?xml version="1.0" encoding="UTF-8"?>
<Response Status="Error">
<msg>Keyid gooPc not found.</msg></Response>"""
)
)
val serverLookup = ServerLookup(serverInfoXml)
try {
serverLookup.promiseServerInformation(LibraryId(14)).toFuture().get()
} catch (e: ExecutionException) {
exception = e.cause as? ServerDiscoveryException ?: throw e
}
}
}
@Test
fun thenAServerDiscoveryExceptionIsThrownWithTheCorrectMessage() {
assertThat(exception?.message).contains("Keyid gooPc not found.")
}
}
| lgpl-3.0 | 31197a6d5f27a42a074173bf03d53b25 | 33.829787 | 95 | 0.793525 | 4.041975 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/view/nowplaying/menu/NowPlayingFileListItemMenuBuilder.kt | 2 | 4018 | package com.lasthopesoftware.bluewater.client.playback.view.nowplaying.menu
import android.widget.ImageButton
import androidx.recyclerview.widget.RecyclerView
import com.lasthopesoftware.bluewater.R
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.details.ViewFileDetailsClickListener
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.AbstractFileListItemMenuBuilder
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.FileListItemContainer
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.FileListItemNowPlayingRegistrar
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.FileNameTextViewSetter
import com.lasthopesoftware.bluewater.client.browsing.items.menu.LongClickViewAnimatorListener
import com.lasthopesoftware.bluewater.client.playback.file.PositionedFile
import com.lasthopesoftware.bluewater.client.playback.service.broadcasters.PlaylistEvents
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.menu.listeners.FileSeekToClickListener
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.menu.listeners.RemovePlaylistFileClickListener
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.INowPlayingRepository
import com.lasthopesoftware.bluewater.shared.android.view.LazyViewFinder
import com.lasthopesoftware.bluewater.shared.android.view.ViewUtils
import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise
class NowPlayingFileListItemMenuBuilder(private val nowPlayingRepository: INowPlayingRepository, private val fileListItemNowPlayingRegistrar: FileListItemNowPlayingRegistrar)
: AbstractFileListItemMenuBuilder<NowPlayingFileListItemMenuBuilder.ViewHolder>(R.layout.layout_now_playing_file_item_menu) {
override fun newViewHolder(fileItemMenu: FileListItemContainer) = ViewHolder(fileItemMenu)
inner class ViewHolder internal constructor(private val fileListItemContainer: FileListItemContainer)
: RecyclerView.ViewHolder(fileListItemContainer.viewAnimator) {
private val viewFileDetailsButtonFinder = LazyViewFinder<ImageButton>(itemView, R.id.btnViewFileDetails)
private val playButtonFinder = LazyViewFinder<ImageButton>(itemView, R.id.btnPlaySong)
private val removeButtonFinder = LazyViewFinder<ImageButton>(itemView, R.id.btnRemoveFromPlaylist)
private val fileNameTextViewSetter = FileNameTextViewSetter(fileListItemContainer.findTextView())
var fileListItemNowPlayingHandler: AutoCloseable? = null
fun update(positionedFile: PositionedFile) {
val fileListItem = fileListItemContainer
val textView = fileListItem.findTextView()
val serviceFile = positionedFile.serviceFile
fileNameTextViewSetter.promiseTextViewUpdate(serviceFile)
val position = positionedFile.playlistPosition
val viewFlipper = fileListItem.viewAnimator
nowPlayingRepository
.nowPlaying
.eventually(LoopedInPromise.response({ np ->
textView.setTypeface(null, ViewUtils.getActiveListItemTextViewStyle(position == np.playlistPosition))
viewFlipper.isSelected = position == np.playlistPosition
}, textView.context))
fileListItemNowPlayingHandler?.close()
fileListItemNowPlayingHandler = fileListItemNowPlayingRegistrar.registerNewHandler(fileListItem) { _, intent ->
val playlistPosition = intent.getIntExtra(PlaylistEvents.PlaylistParameters.playlistPosition, -1)
textView.setTypeface(null, ViewUtils.getActiveListItemTextViewStyle(position == playlistPosition))
viewFlipper.isSelected = position == playlistPosition
}
LongClickViewAnimatorListener.tryFlipToPreviousView(viewFlipper)
playButtonFinder.findView().setOnClickListener(FileSeekToClickListener(viewFlipper, position))
viewFileDetailsButtonFinder.findView().setOnClickListener(ViewFileDetailsClickListener(viewFlipper, serviceFile))
removeButtonFinder.findView().setOnClickListener(RemovePlaylistFileClickListener(viewFlipper, position))
}
}
}
| lgpl-3.0 | f3525c317fcffa6042c9ee2ef9d88350 | 57.231884 | 174 | 0.854903 | 5.003736 | false | false | false | false |
RanKKI/PSNine | app/src/main/java/xyz/rankki/psnine/ui/topics/TopicsFragment.kt | 1 | 3696 | package xyz.rankki.psnine.ui.topics
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.blankj.utilcode.util.ActivityUtils
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.support.v4.UI
import org.jetbrains.anko.support.v4.find
import org.jetbrains.anko.support.v4.onRefresh
import org.jetbrains.anko.support.v4.swipeRefreshLayout
import xyz.rankki.psnine.base.BaseFragment
import xyz.rankki.psnine.base.BaseTopicsModel
import xyz.rankki.psnine.common.config.RefreshColors
import xyz.rankki.psnine.common.listener.RecyclerViewScrollListener
import xyz.rankki.psnine.data.http.HttpManager
import xyz.rankki.psnine.ui.topic.TopicActivity
class TopicsFragment<K> : BaseFragment(), RecyclerViewScrollListener.LoadingListener {
private lateinit var mAdapter: TopicsAdapter<K>
private lateinit var clz: Class<*>
private var page: Int = 1
companion object {
const val ID_SwipeRefreshLayout: Int = 1
const val ID_RecyclerView: Int = 2
fun <T, K> newInstance(clz: Class<T>, clazz: Class<K>): TopicsFragment<K> {
val topicsModel: BaseTopicsModel<*> = clz.newInstance() as BaseTopicsModel<*>
val args = Bundle()
val fragment: TopicsFragment<K> = TopicsFragment()
args.putString("clz", clz.name)
args.putString("path", topicsModel.getPath())
args.putString("name", topicsModel.getName())
fragment.arguments = args
return fragment
}
}
override fun initView(): View {
mAdapter = TopicsAdapter(mContext)
mAdapter.clickListener = View.OnClickListener {
val position: Int = find<RecyclerView>(ID_RecyclerView).getChildAdapterPosition(it)
if (position != RecyclerView.NO_POSITION) {
val extras = Bundle()
extras.putString("url", mAdapter.getData(position).getTopicUrl())
ActivityUtils.startActivity(extras, TopicActivity::class.java)
}
}
clz = Class.forName(arguments?.getString("clz")) as Class<*>
return UI {
swipeRefreshLayout {
id = ID_SwipeRefreshLayout
setColorSchemeColors(RefreshColors.ColorA, RefreshColors.ColorB, RefreshColors.ColorC)
onRefresh {
initData()
}
recyclerView {
id = ID_RecyclerView
layoutManager = LinearLayoutManager(mContext)
adapter = mAdapter
addItemDecoration(DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL))
val scrollListener = RecyclerViewScrollListener(mContext, this@TopicsFragment)
addOnScrollListener(scrollListener)
}
}
}.view
}
override fun initData() {
setRefreshing(true)
HttpManager.get()
.getTopics("${arguments!!.getString("path")}?page=$page", clz)
.subscribe {
mAdapter.updateData(it)
setRefreshing(false)
}
}
private fun setRefreshing(isRefreshing: Boolean) {
find<SwipeRefreshLayout>(ID_SwipeRefreshLayout).isRefreshing = isRefreshing
}
override fun loadMore() {
page += 1
initData()
}
override fun isLoading(): Boolean = find<SwipeRefreshLayout>(ID_SwipeRefreshLayout).isRefreshing
} | apache-2.0 | 9ce56549211ef07c69ae0d284e91a80e | 36.343434 | 102 | 0.651786 | 4.994595 | false | false | false | false |
WonderBeat/suchmarines | src/main/kotlin/org/wow/logger/GameLogger.kt | 1 | 2060 | package org.wow.logger
import com.epam.starwors.bot.Logic
import com.epam.starwors.galaxy.Planet
import com.epam.starwors.galaxy.Move
import com.epam.starwors.galaxy.PlanetType
import com.fasterxml.jackson.databind.ObjectMapper
import org.wow.http.GameClient
data class SerializedGameTurn(val planets: List<SerializedPlanet> = arrayListOf(),
var moves: List<PlayerMove> = arrayListOf())
data class SerializedPlanet(val id: String = "",
val owner: String = "",
val units: Int = 0,
val `type`: PlanetType = PlanetType.TYPE_A,
val neighbours: List<String> = listOf())
data class PlayerActionsResponse(val actions: List<PlayerMove> = listOf())
data class GameTurnResponse(val turnNumber: Int = 0, val playersActions: PlayerActionsResponse = PlayerActionsResponse())
public class GameLogger(val serializer: ObjectMapper,
val gameId: String,
val client: GameClient): Logic {
var states: List<GameTurn> = arrayListOf()
/**
* Game turn contains world + moves.
* But moves could be requested only after this game turn
*/
var lastWorld: Collection<Planet>? = null
override fun step(world: Collection<Planet>?): MutableCollection<Move>? {
if(world!!.empty) { // end of the game
return arrayListOf()
}
if(lastWorld != null) {
states = states.plus(GameTurn(lastWorld!!, client.getMovesForPreviousTurn(gameId)))
}
lastWorld = world
return arrayListOf()
}
private fun serializePlanet(planet: Planet): SerializedPlanet = SerializedPlanet(planet.getId()!!,
planet.getOwner()!!,
planet.getUnits(), planet.getType()!!,
planet.getNeighbours()!!.map { it.getId()!! })
fun dump(): ByteArray = serializer.writeValueAsBytes(states.
map { SerializedGameTurn(it.planets.map { serializePlanet(it) }, it.moves) })!!
}
| mit | bfc6f99428288d49f6fe83d0bb6526ce | 36.454545 | 121 | 0.62767 | 4.507659 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/files/FileHelper.kt | 1 | 9454 | package org.tasks.files
import android.annotation.TargetApi
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import androidx.documentfile.provider.DocumentFile
import androidx.fragment.app.Fragment
import com.google.common.collect.Iterables
import com.google.common.io.ByteStreams
import com.google.common.io.Files
import com.todoroo.astrid.utility.Constants
import org.tasks.Strings.isNullOrEmpty
import org.tasks.extensions.Context.safeStartActivity
import timber.log.Timber
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.util.*
object FileHelper {
fun newFilePickerIntent(activity: Activity?, initial: Uri?, vararg mimeTypes: String?): Intent =
Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
putExtra("android.content.extra.SHOW_ADVANCED", true)
putExtra("android.content.extra.FANCY", true)
putExtra("android.content.extra.SHOW_FILESIZE", true)
addCategory(Intent.CATEGORY_OPENABLE)
setInitialUri(activity, this, initial)
if (mimeTypes.size == 1) {
type = mimeTypes[0]
} else {
type = "*/*"
if (mimeTypes.size > 1) {
putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
}
}
}
fun newDirectoryPicker(fragment: Fragment, rc: Int, initial: Uri?) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
addFlags(
Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
or Intent.FLAG_GRANT_READ_URI_PERMISSION
or Intent.FLAG_GRANT_PREFIX_URI_PERMISSION)
putExtra("android.content.extra.SHOW_ADVANCED", true)
putExtra("android.content.extra.FANCY", true)
putExtra("android.content.extra.SHOW_FILESIZE", true)
setInitialUri(fragment.context, this, initial)
}
fragment.startActivityForResult(intent, rc)
}
@TargetApi(Build.VERSION_CODES.O)
private fun setInitialUri(context: Context?, intent: Intent, uri: Uri?) {
if (uri == null || uri.scheme != ContentResolver.SCHEME_CONTENT) {
return
}
try {
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, DocumentFile.fromTreeUri(context!!, uri)!!.uri)
} catch (e: Exception) {
Timber.e(e)
}
}
fun delete(context: Context?, uri: Uri?) {
if (uri == null) {
return
}
when (uri.scheme) {
"content" -> {
val documentFile = DocumentFile.fromSingleUri(context!!, uri)
documentFile!!.delete()
}
"file" -> delete(File(uri.path))
}
}
private fun delete(vararg files: File) {
for (file in files) {
if (file.isDirectory) {
file.listFiles()?.let { delete(*it) }
} else {
file.delete()
}
}
}
fun getFilename(context: Context, uri: Uri): String? {
when (uri.scheme) {
ContentResolver.SCHEME_FILE -> return uri.lastPathSegment
ContentResolver.SCHEME_CONTENT -> {
val cursor = context.contentResolver.query(uri, null, null, null, null)
if (cursor != null && cursor.moveToFirst()) {
return try {
cursor.getString(cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
} finally {
cursor.close()
}
}
}
}
return null
}
fun getExtension(context: Context, uri: Uri): String? {
if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
val mimeType = context.contentResolver.getType(uri)
val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)
if (!isNullOrEmpty(extension)) {
return extension
}
}
val extension = MimeTypeMap.getFileExtensionFromUrl(uri.path)
return if (!isNullOrEmpty(extension))
extension
else
Files.getFileExtension(getFilename(context, uri)!!)
}
fun getMimeType(context: Context, uri: Uri): String? {
val mimeType = context.contentResolver.getType(uri)
if (!isNullOrEmpty(mimeType)) {
return mimeType
}
val extension = getExtension(context, uri)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
}
fun startActionView(context: Activity, uri: Uri?) {
var uri = uri ?: return
val mimeType = getMimeType(context, uri)
val intent = Intent(Intent.ACTION_VIEW)
if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
uri = copyToUri(context, Uri.fromFile(context.externalCacheDir), uri)
}
val share = FileProvider.getUriForFile(context, Constants.FILE_PROVIDER_AUTHORITY, File(uri.path))
intent.setDataAndType(share, mimeType)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.safeStartActivity(intent)
}
@JvmStatic
@Throws(IOException::class)
fun newFile(
context: Context, destination: Uri, mimeType: String?, baseName: String, extension: String?): Uri {
val filename = getNonCollidingFileName(context, destination, baseName, extension)
return when (destination.scheme) {
"content" -> {
val tree = DocumentFile.fromTreeUri(context, destination)
val f1 = tree!!.createFile(mimeType!!, filename)
?: throw FileNotFoundException("Failed to create $filename")
f1.uri
}
"file" -> {
val dir = File(destination.path)
if (!dir.exists() && !dir.mkdirs()) {
throw IOException("Failed to create %s" + dir.absolutePath)
}
val f2 = File(dir.absolutePath + File.separator + filename)
if (f2.createNewFile()) {
return Uri.fromFile(f2)
}
throw FileNotFoundException("Failed to create $filename")
}
else -> throw IllegalArgumentException("Unknown URI scheme: " + destination.scheme)
}
}
fun copyToUri(context: Context, destination: Uri, input: Uri): Uri {
val filename = getFilename(context, input)
val basename = Files.getNameWithoutExtension(filename!!)
try {
val output = newFile(
context,
destination,
getMimeType(context, input),
basename,
getExtension(context, input)
)
copyStream(context, input, output)
return output
} catch (e: IOException) {
throw IllegalStateException(e)
}
}
fun copyStream(context: Context, input: Uri?, output: Uri?) {
val contentResolver = context.contentResolver
try {
val inputStream = contentResolver.openInputStream(input!!)
val outputStream = contentResolver.openOutputStream(output!!)
ByteStreams.copy(inputStream!!, outputStream!!)
inputStream.close()
outputStream.close()
} catch (e: IOException) {
throw IllegalStateException(e)
}
}
private fun getNonCollidingFileName(
context: Context, uri: Uri, baseName: String, extension: String?): String {
var extension = extension
var tries = 1
if (!extension!!.startsWith(".")) {
extension = ".$extension"
}
var tempName = baseName
when (uri.scheme) {
ContentResolver.SCHEME_CONTENT -> {
val dir = DocumentFile.fromTreeUri(context, uri)
val documentFiles = Arrays.asList(*dir!!.listFiles())
while (true) {
val result = tempName + extension
if (Iterables.any(documentFiles) { f: DocumentFile? -> f!!.name == result }) {
tempName = "$baseName-$tries"
tries++
} else {
break
}
}
}
ContentResolver.SCHEME_FILE -> {
var f = File(uri.path, baseName + extension)
while (f.exists()) {
tempName = "$baseName-$tries" // $NON-NLS-1$
f = File(uri.path, tempName + extension)
tries++
}
}
}
return tempName + extension
}
fun uri2String(uri: Uri?): String {
if (uri == null) {
return ""
}
return if (uri.scheme == ContentResolver.SCHEME_FILE)
File(uri.path).absolutePath
else
uri.toString()
}
} | gpl-3.0 | 1fc28775cbe2555b1543bf09f0fc6316 | 36.519841 | 112 | 0.565792 | 5.015385 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb-api/jvb-api-client/src/test/kotlin/org/jitsi/videobridge/api/util/WebSocketClientTest.kt | 1 | 3823 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.videobridge.api.util
import io.kotest.assertions.timing.eventually
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.shouldBeInstanceOf
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.features.websocket.WebSockets
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import io.ktor.server.engine.embeddedServer
import io.ktor.server.jetty.Jetty
import org.jitsi.utils.logging2.LoggerImpl
import kotlin.random.Random
import kotlin.time.ExperimentalTime
import kotlin.time.seconds
@ExperimentalTime
class WebSocketClientTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
private val wsPort = Random.nextInt(49152, 65535).also {
println("Server running on port $it")
}
private val client = HttpClient(CIO) {
install(WebSockets)
}
private val wsServer = TestWsServer()
private val server = embeddedServer(Jetty, port = wsPort) {
wsServer.app(this)
}
private val receivedMessages = mutableListOf<Frame>()
private fun incomingMessageHandler(frame: Frame) {
receivedMessages.add(frame)
}
private val testLogger = LoggerImpl("test")
init {
server.start()
context("sendString") {
context("when no reply is expected") {
val ws = WebSocketClient(
client,
"localhost",
wsPort,
"/ws/blackhole",
testLogger,
::incomingMessageHandler
)
ws.run()
ws.sendString("hello")
should("send a message") {
eventually(5.seconds) {
wsServer.receivedMessages shouldHaveSize 1
}
wsServer.receivedMessages.first().shouldBeInstanceOf<Frame.Text>()
(wsServer.receivedMessages.first() as Frame.Text).readText() shouldBe "hello"
}
}
context("when a reply is expected") {
val ws = WebSocketClient(client, "localhost", wsPort, "/ws/echo", testLogger, ::incomingMessageHandler)
ws.run()
ws.sendString("hello")
should("invoke the incoming message handler") {
eventually(5.seconds) {
receivedMessages shouldHaveSize 1
}
receivedMessages.first().shouldBeInstanceOf<Frame.Text>()
(receivedMessages.first() as Frame.Text).readText() shouldBe "hello"
}
}
context("stop") {
val ws = WebSocketClient(client, "localhost", wsPort, "/ws/echo", testLogger, ::incomingMessageHandler)
ws.run()
ws.sendString("hello")
should("clean things up correctly") {
ws.stop()
}
}
}
}
}
| apache-2.0 | ce1869328237694e94db158676e14c87 | 34.398148 | 119 | 0.614177 | 4.845374 | false | true | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/table/query/handlers/PlayerRaisedEventHandler.kt | 1 | 2809 | package com.flexpoker.table.query.handlers
import com.flexpoker.chat.service.ChatService
import com.flexpoker.framework.event.EventHandler
import com.flexpoker.framework.pushnotifier.PushNotificationPublisher
import com.flexpoker.login.repository.LoginRepository
import com.flexpoker.pushnotifications.TableUpdatedPushNotification
import com.flexpoker.table.command.events.PlayerRaisedEvent
import com.flexpoker.table.query.repository.TableRepository
import org.springframework.stereotype.Component
import javax.inject.Inject
@Component
class PlayerRaisedEventHandler @Inject constructor(
private val loginRepository: LoginRepository,
private val tableRepository: TableRepository,
private val pushNotificationPublisher: PushNotificationPublisher,
private val chatService: ChatService
) : EventHandler<PlayerRaisedEvent> {
override fun handle(event: PlayerRaisedEvent) {
handleUpdatingTable(event)
handlePushNotifications(event)
handleChat(event)
}
private fun handleUpdatingTable(event: PlayerRaisedEvent) {
val tableDTO = tableRepository.fetchById(event.aggregateId)
val username = loginRepository.fetchUsernameByAggregateId(event.playerId)
val raiseToAmount = event.raiseToAmount
val updatedSeats = tableDTO.seats!!
.map {
val amountOverChipsInFront = raiseToAmount - it.chipsInFront
if (it.name == username) {
val updatedChipsInBack = it.chipsInBack - amountOverChipsInFront
it.copy(chipsInBack = updatedChipsInBack, chipsInFront = raiseToAmount,
raiseTo = 0, callAmount = 0, isActionOn = false)
} else {
it.copy(raiseTo = minOf(raiseToAmount * 2, it.chipsInFront + it.chipsInBack),
callAmount = amountOverChipsInFront)
}
}
val previousChipsInFront = tableDTO.seats.first { it.name == username }.chipsInFront
val totalPotIncrease = raiseToAmount - previousChipsInFront
val updatedTable = tableDTO.copy(version = event.version, seats = updatedSeats,
totalPot = tableDTO.totalPot + totalPotIncrease)
tableRepository.save(updatedTable)
}
private fun handlePushNotifications(event: PlayerRaisedEvent) {
val pushNotification = TableUpdatedPushNotification(event.gameId, event.aggregateId)
pushNotificationPublisher.publish(pushNotification)
}
private fun handleChat(event: PlayerRaisedEvent) {
val username = loginRepository.fetchUsernameByAggregateId(event.playerId)
val message = username + " raises to " + event.raiseToAmount
chatService.saveAndPushSystemTableChatMessage(event.gameId, event.aggregateId, message)
}
} | gpl-2.0 | 15e8b763c241e1b49e1934e5d1833770 | 45.065574 | 97 | 0.724101 | 5.454369 | false | false | false | false |
nemerosa/ontrack | ontrack-service/src/main/java/net/nemerosa/ontrack/service/support/StorageServiceImpl.kt | 1 | 3706 | package net.nemerosa.ontrack.service.support
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.common.asOptional
import net.nemerosa.ontrack.json.JsonUtils
import net.nemerosa.ontrack.json.parseInto
import net.nemerosa.ontrack.model.support.StorageService
import net.nemerosa.ontrack.repository.StorageRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*
import kotlin.reflect.KClass
@Service
@Transactional
class StorageServiceImpl(
private val repository: StorageRepository,
) : StorageService {
override fun storeJson(store: String, key: String, node: JsonNode?) {
if (node != null) {
repository.storeJson(store, key, node)
} else {
repository.delete(store, key)
}
}
override fun retrieveJson(store: String, key: String): Optional<JsonNode> =
findJson(store, key).asOptional()
override fun findJson(store: String, key: String): JsonNode? = repository.retrieveJson(store, key)
override fun getKeys(store: String): List<String> = repository.getKeys(store)
override fun getData(store: String): Map<String, JsonNode> = repository.getData(store)
override fun delete(store: String, key: String) {
repository.delete(store, key)
}
override fun clear(store: String) {
repository.clear(store)
}
override fun exists(store: String, key: String): Boolean = repository.exists(store, key)
override fun <T> findByJson(store: String, query: String, variables: Map<String, *>, type: Class<T>): List<T> {
return repository.filter(
store = store,
offset = 0,
size = Int.MAX_VALUE,
query = query,
queryVariables = variables,
).map {
JsonUtils.parse(it, type)
}
}
override fun count(store: String, context: String, query: String?, queryVariables: Map<String, *>?): Int =
repository.count(store, context, query, queryVariables)
override fun <T : Any> filter(
store: String,
type: KClass<T>,
offset: Int,
size: Int,
context: String,
query: String?,
queryVariables: Map<String, *>?,
orderQuery: String?,
): List<T> =
repository.filter(
store = store,
offset = offset,
size = size,
context = context,
query = query,
queryVariables = queryVariables,
orderQuery = orderQuery
).map {
it.parseInto(type)
}
override fun <T : Any> filterRecords(
store: String,
type: KClass<T>,
offset: Int,
size: Int,
context: String,
query: String?,
queryVariables: Map<String, *>?,
orderQuery: String?,
): Map<String, T> =
repository.filterRecords(store, offset, size, context, query, queryVariables, orderQuery)
.mapValues { (_, data) ->
data.parseInto(type)
}
override fun <T : Any> forEach(
store: String,
type: KClass<T>,
context: String,
query: String?,
queryVariables: Map<String, *>?,
orderQuery: String?,
code: (key: String, item: T) -> Unit,
) {
repository.forEach(store, context, query, queryVariables, orderQuery) { key, node ->
val item = node.parseInto(type)
code(key, item)
}
}
override fun deleteWithFilter(store: String, query: String?, queryVariables: Map<String, *>?): Int =
repository.deleteWithFilter(store, query, queryVariables)
}
| mit | 43adaf0c1dd0964dabadaab98176c844 | 30.948276 | 115 | 0.616568 | 4.385799 | false | false | false | false |
dykstrom/jcc | src/test/kotlin/se/dykstrom/jcc/basic/compiler/BasicCodeGeneratorArrayTests.kt | 1 | 20491 | /*
* Copyright (C) 2019 Johan Dykstrom
*
* 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 se.dykstrom.jcc.basic.compiler
import org.junit.Test
import se.dykstrom.jcc.basic.ast.PrintStatement
import se.dykstrom.jcc.basic.ast.SwapStatement
import se.dykstrom.jcc.common.assembly.base.Line
import se.dykstrom.jcc.common.assembly.instruction.*
import se.dykstrom.jcc.common.assembly.instruction.floating.ConvertIntRegToFloatReg
import se.dykstrom.jcc.common.assembly.instruction.floating.MoveFloatRegToMem
import se.dykstrom.jcc.common.assembly.instruction.floating.MoveMemToFloatReg
import se.dykstrom.jcc.common.assembly.instruction.floating.RoundFloatRegToIntReg
import se.dykstrom.jcc.common.assembly.other.DataDefinition
import se.dykstrom.jcc.common.ast.*
import se.dykstrom.jcc.common.types.Arr
import se.dykstrom.jcc.common.types.F64
import se.dykstrom.jcc.common.types.I64
import se.dykstrom.jcc.common.types.Str
import kotlin.test.assertEquals
/**
* Tests features related to arrays in code generation.
*
* @author Johan Dykstrom
*/
class BasicCodeGeneratorArrayTests : AbstractBasicCodeGeneratorTest() {
@Test
fun shouldDefineSimpleIntegerArray() {
// dim a%(3) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_3)))
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable a% should be defined and be an array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == I64.INSTANCE }
.filter { it.identifier().mappedName == IDENT_ARR_I64_A.mappedName + "_arr" }
.filter { it.value() == "3 dup " + I64.INSTANCE.defaultValue }
.count())
}
@Test
fun shouldDefineMultiDimensionalIntegerArray() {
// dim a%(2, 4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_2, listOf(IL_2, IL_4)))
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable a% should be defined and be a two-dimensional array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == I64.INSTANCE }
.filter { it.identifier().mappedName == IDENT_ARR_I64_A.mappedName + "_arr" }
.filter { it.value() == "8 dup " + I64.INSTANCE.defaultValue }
.count())
// There should be two dimensions
assertEquals(2, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_num_dims"))
// Of size two
assertEquals(2, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_dim_0"))
// And four
assertEquals(4, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_dim_1"))
}
@Test
fun shouldDefineSimpleFloatArray() {
// dim d(2) as double
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_F64_D.name(), TYPE_ARR_F64_1, listOf(IL_2)))
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable d should be defined and be an array of floats
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == F64.INSTANCE }
.filter { it.identifier().mappedName == IDENT_ARR_F64_D.mappedName + "_arr" }
.filter { it.value() == "2 dup " + F64.INSTANCE.defaultValue }
.count())
// There should be one dimension
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_F64_D.mappedName + "_num_dims"))
// Of size two
assertEquals(2, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_F64_D.mappedName + "_dim_0"))
}
@Test
fun shouldDefineSimpleStringArray() {
// dim s$(1) as string
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_STR_S.name(), TYPE_ARR_STR_1, listOf(IL_1)))
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable s$ should be defined and be an array of strings
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == Str.INSTANCE }
.filter { it.identifier().mappedName == IDENT_STR_S.mappedName + "_arr" }
.filter { it.value() == "1 dup " + Str.INSTANCE.defaultValue }
.count())
// There should be one dimension
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_STR_S.mappedName + "_num_dims"))
// Of size one
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_STR_S.mappedName + "_dim_0"))
}
@Test
fun shouldDefineTwoArrays() {
// dim s$(1) as string
// dim a%(4, 4) as integer
val declarations = listOf(
ArrayDeclaration(0, 0, IDENT_ARR_STR_S.name(), TYPE_ARR_STR_1, listOf(IL_1)),
ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_2, listOf(IL_4, IL_4))
)
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable s$ should be defined and be an array of strings
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == Str.INSTANCE }
.filter { it.identifier().mappedName == IDENT_STR_S.mappedName + "_arr" }
.filter { it.value() == "1 dup " + Str.INSTANCE.defaultValue }
.count())
// There should be one dimension
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_STR_S.mappedName + "_num_dims"))
// Of size one
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_STR_S.mappedName + "_dim_0"))
// Variable a% should be defined and be an array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == I64.INSTANCE }
.filter { it.identifier().mappedName == IDENT_ARR_I64_A.mappedName + "_arr" }
.filter { it.value() == "16 dup " + I64.INSTANCE.defaultValue }
.count())
// There should be two dimensions
assertEquals(2, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_num_dims"))
// Of size four
assertEquals(4, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_dim_0"))
// And four
assertEquals(4, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_dim_1"))
}
@Test
fun shouldAccessElementInOneDimensionalArray() {
// dim a%(4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(2)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_A, listOf(IL_2))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Move literal value subscript
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveImmToReg::class.java)
.count { it.source == "2" })
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_A.mappedName + "_arr") })
}
@Test
fun shouldAccessElementInTwoDimensionalArray() {
// dim a%(3, 2) as integer
val declarations = listOf(ArrayDeclaration(0, 0,
IDENT_ARR_I64_B.name(), Arr.from(2, I64.INSTANCE), listOf(IL_3, IL_2)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(2, 0)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_B, listOf(IL_2, IL_0))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Move array dimension 1
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_B.mappedName + "_dim_1") })
// Multiply accumulator with dimension 1
assertEquals(1, lines.asSequence()
.filterIsInstance(IMulRegWithReg::class.java)
.count())
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_B.mappedName + "_arr") })
}
@Test
fun shouldAccessElementInThreeDimensionalArray() {
// dim a%(4, 2, 3) as integer
val declarations = listOf(ArrayDeclaration(0, 0,
IDENT_ARR_I64_C.name(), Arr.from(3, I64.INSTANCE), listOf(IL_4, IL_2, IL_3)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(2, 0, 2)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_C, listOf(IL_2, IL_0, IL_2))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Move array dimension 1
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_C.mappedName + "_dim_1") })
// Move array dimension 2
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_C.mappedName + "_dim_2") })
// Multiply accumulator with dimension 1 and 2
assertEquals(2, lines.asSequence()
.filterIsInstance(IMulRegWithReg::class.java)
.count())
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_C.mappedName + "_arr") })
}
@Test
fun shouldAccessElementInFloatArray() {
// dim a%(4) as float
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_F64_D.name(), TYPE_ARR_F64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(2)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_F64_D, listOf(IL_2))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Move literal value subscript
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveImmToReg::class.java)
.count { it.source == "2" })
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToFloatReg::class.java)
.count { it.source.contains(IDENT_ARR_F64_D.mappedName + "_arr") })
}
@Test
fun shouldAccessElementWithSubscriptExpression() {
// dim a%(4) as float
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_F64_D.name(), TYPE_ARR_F64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(1 + 2)
val addExpression = AddExpression(0, 0, IL_1, IL_2)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_F64_D, listOf(addExpression))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Add registers containing 1 and 2
assertEquals(1, lines.asSequence()
.filterIsInstance(AddRegToReg::class.java)
.count())
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToFloatReg::class.java)
.count { it.source.contains(IDENT_ARR_F64_D.mappedName + "_arr") })
}
@Test
fun shouldSetElementInOneDimensionalArray() {
// dim a%(4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// a%(2) = 4
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_A, listOf(IL_2))
val assignStatement = AssignStatement(0, 0, arrayAccessExpression, IL_4)
val result = assembleProgram(listOf(declarationStatement, assignStatement))
val lines = result.lines()
// Move literal value subscript
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveImmToReg::class.java)
.count { it.source == "2" })
// Move literal value to assign
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveImmToReg::class.java)
.count { it.source == "4" })
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveRegToMem::class.java)
.count { it.destination.contains(IDENT_ARR_I64_A.mappedName + "_arr") })
}
@Test
fun shouldSwapIntegerAndArrayElement() {
// dim a%(4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_A, listOf(IL_2))
val swapStatement = SwapStatement(0, 0, arrayAccessExpression, NAME_H)
val result = assembleProgram(listOf(declarationStatement, swapStatement))
val lines = result.lines()
// Variable a% should be defined and be an array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == I64.INSTANCE && it.mappedName == IDENT_ARR_I64_A.mappedName + "_arr" })
// Variable h% should be defined and be an integer
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == I64.INSTANCE && it.mappedName == IDENT_I64_H.mappedName })
// Moving the variable contents to registers
assertEquals(2, countInstances(MoveMemToReg::class.java, lines))
// Moving the register contents to variables
assertEquals(2, countInstances(MoveRegToMem::class.java, lines))
}
@Test
fun shouldSwapStringAndArrayElement() {
// dim a%(4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_STR_S.name(), TYPE_ARR_STR_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_STR_S, listOf(IL_2))
val swapStatement = SwapStatement(0, 0, arrayAccessExpression, NAME_B)
val result = assembleProgram(listOf(declarationStatement, swapStatement))
val lines = result.lines()
// Variable s$ should be defined and be an array of strings
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == Str.INSTANCE && it.mappedName == IDENT_ARR_STR_S.mappedName + "_arr" })
// Variable b$ should be defined and be a string
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == Str.INSTANCE && it.mappedName == IDENT_STR_B.mappedName })
// Moving the variable contents (and variable type pointers) to registers
assertEquals(4, countInstances(MoveMemToReg::class.java, lines))
// Moving the register contents to variables (and variable type pointers)
assertEquals(4, countInstances(MoveRegToMem::class.java, lines))
}
@Test
fun shouldSwapIntegerArrayElementAndFloatArrayElement() {
// dim a%(4) as integer
// dim d#(2) as double
val declarations = listOf(
ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_4)),
ArrayDeclaration(0, 0, IDENT_ARR_F64_D.name(), TYPE_ARR_F64_1, listOf(IL_2))
)
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
val integerArrayAccess = ArrayAccessExpression(0, 0, IDENT_ARR_I64_A, listOf(IL_2))
val floatArrayAccess = ArrayAccessExpression(0, 0, IDENT_ARR_F64_D, listOf(IL_0))
val swapStatement = SwapStatement(0, 0, integerArrayAccess, floatArrayAccess)
val result = assembleProgram(listOf(declarationStatement, swapStatement))
val lines = result.lines()
// Variable a% should be defined and be an array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == I64.INSTANCE && it.mappedName == IDENT_ARR_I64_A.mappedName + "_arr" })
// Variable d# should be defined and be an array of floats
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == F64.INSTANCE && it.mappedName == IDENT_ARR_F64_D.mappedName + "_arr" })
// Move contents of integer array element to register
assertEquals(1, countInstances(MoveMemToReg::class.java, lines))
// Move register contents to integer array element
assertEquals(1, countInstances(MoveRegToMem::class.java, lines))
// Move contents of float array element to register
assertEquals(1, countInstances(MoveMemToFloatReg::class.java, lines))
// Move register contents to float array element
assertEquals(1, countInstances(MoveFloatRegToMem::class.java, lines))
// Convert integer to float
assertEquals(1, countInstances(ConvertIntRegToFloatReg::class.java, lines))
// Convert float to integer
assertEquals(1, countInstances(RoundFloatRegToIntReg::class.java, lines))
}
/**
* Extracts the value of the data definition with the given mapped name as an Int.
* This method expects to find exactly one such data definition, and that the value
* is actually an integer.
*/
private fun getValueOfDataDefinitionAsInt(lines: List<Line>, mappedName: String): Int {
val values = lines
.filterIsInstance<DataDefinition>()
.filter { it.identifier().mappedName == mappedName }
.map { it.value().toInt() }
assertEquals(1, values.size)
return values.first()
}
}
| gpl-3.0 | bda756a4f57dc0ef9613ef6237e4e299 | 45.89016 | 117 | 0.649212 | 4.326647 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-jenkins/src/main/java/net/nemerosa/ontrack/extension/jenkins/client/DefaultJenkinsClient.kt | 1 | 4656 | package net.nemerosa.ontrack.extension.jenkins.client
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import net.nemerosa.ontrack.common.untilTimeout
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.util.LinkedMultiValueMap
import org.springframework.web.client.RestTemplate
import java.net.URI
import java.time.Duration
class DefaultJenkinsClient(
private val url: String,
private val client: RestTemplate,
) : JenkinsClient {
private val logger: Logger = LoggerFactory.getLogger(DefaultJenkinsClient::class.java)
private val crumbs: JenkinsCrumbs by lazy {
runBlocking {
untilTimeout("Getting Jenkins authentication crumbs") {
client.getForObject("/crumbIssuer/api/json", JenkinsCrumbs::class.java)
}
}
}
override fun getJob(job: String): JenkinsJob {
val jobPath = getJobPath(job)
val jobUrl = "$url$jobPath"
val jobName = jobPath.substringAfterLast("/")
return JenkinsJob(
jobName,
jobUrl
)
}
override val info: JenkinsInfo
get() =
client.getForObject("/api/json", JenkinsInfo::class.java) ?: error("Cannot get Jenkins info")
override fun runJob(
job: String,
parameters: Map<String, String>,
retries: Int,
retriesDelaySeconds: Int,
): JenkinsBuild {
val retriesDelay = Duration.ofSeconds(retriesDelaySeconds.toLong())
val path = getJobPath(job)
logger.debug("run,job=$job,path=$path,parameters=$parameters")
return runBlocking {
// Query
val map = LinkedMultiValueMap<String, Any>()
parameters.forEach { (key, value) ->
map.add(key, value)
}
// Headers (form)
val headers = createCSRFHeaders()
headers.contentType = MediaType.MULTIPART_FORM_DATA
// Request to send
val requestEntity = HttpEntity(map, headers)
// Launches the job with parameters and get the queue item
val queueItemURI: URI? = withContext(Dispatchers.IO) {
client.postForLocation(
"$path/buildWithParameters",
requestEntity
)
}
if (queueItemURI == null) {
error("Cannot fire job $path")
} else {
// We must now monitor the state of the queue item
// Until `cancelled` is true, or `executable` contains a valid link
val executable: JenkinsBuildId =
untilTimeout("Waiting for $queueItemURI to be scheduled", retries, retriesDelay) {
logger.debug("queued=$queueItemURI,job=$job,path=$path,parameters=$parameters")
getQueueStatus(queueItemURI)
}
// Waits for its completion
untilTimeout("Waiting for build completion at ${executable.url(path)}", retries, retriesDelay) {
logger.debug("build=${executable.number},job=$job,path=$path,parameters=$parameters")
getBuildStatus(path, executable)
}
}
}
}
private fun getJobPath(job: String): String {
val path = job.replace("/job/".toRegex(), "/").replace("/".toRegex(), "/job/")
return "/job/$path"
}
private fun createCSRFHeaders(): HttpHeaders {
val headers = HttpHeaders()
headers.add(crumbs.crumbRequestField, crumbs.crumb)
return headers
}
private fun getQueueStatus(queueItemURI: URI): JenkinsBuildId? {
val queueItem: JenkinsQueueItem? = client.getForObject("$queueItemURI/api/json", JenkinsQueueItem::class.java)
return if (queueItem != null) {
when {
queueItem.cancelled != null && queueItem.cancelled -> throw JenkinsJobCancelledException(queueItemURI.toString())
queueItem.executable != null -> queueItem.executable
else -> null
}
} else {
null
}
}
private fun getBuildStatus(job: String, buildId: JenkinsBuildId): JenkinsBuild? {
val buildInfoUrl = "${buildId.url(job)}/api/json"
val build: JenkinsBuild? = client.getForObject(buildInfoUrl, JenkinsBuild::class.java)
return build?.takeIf { !build.building }
}
} | mit | 418ecff2993f0b2d2dddf93dff7ee90b | 35.669291 | 129 | 0.613187 | 5.001074 | false | false | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/custom/LagouHomePanelLayout.kt | 1 | 4867 | package com.hewking.custom
import android.content.Context
import androidx.core.view.GestureDetectorCompat
import android.util.AttributeSet
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.OverScroller
/**
* 类的描述:
* 创建人员:hewking
* 创建时间:2018/6/25
* 修改人员:hewking
* 修改时间:2018/6/25
* 修改备注:
* Version: 1.0.0
*/
class LagouHomePanelLayout(ctx: Context, attrs: AttributeSet) : ViewGroup(ctx, attrs) {
private val TAG = "LagouHomePanelLayout"
private var mTopView: View? = null
private var mContentView: View? = null
private var mTopHeight = 0
private var parallRate = 0.6f
private var mCurOffset = 0f
private val mScroller : OverScroller by lazy {
OverScroller(ctx)
}
private fun ensureTargetView() {
if (childCount > 1) {
if (mTopView == null) {
mTopView = getChildAt(0)
}
if (mContentView == null) {
mContentView = getChildAt(1)
}
} else {
throw IllegalArgumentException("must have two child view!!")
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
ensureTargetView()
measureChildren(widthMeasureSpec, heightMeasureSpec)
mTopHeight = mTopView?.measuredHeight?:0
val height = (mTopView?.measuredHeight ?: 0) + (mContentView?.measuredHeight!! ?: 0)
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY))
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
ensureTargetView()
mTopView?.layout(l,t,r,t + mTopHeight)
mContentView?.layout(l,t + mTopHeight,r,mTopHeight + mContentView?.measuredHeight!!)
}
private val mGestenerDetector : GestureDetectorCompat = GestureDetectorCompat(context,object : GestureDetector.SimpleOnGestureListener() {
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {
Log.i(TAG,"e1 y : ${e1?.y} e2 y : ${e2?.y} distanceY : ${distanceY}")
refreshLayout(distanceY)
postInvalidate()
return true
}
override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
mScroller.fling(0,mCurOffset.toInt(),0,velocityY.toInt() / 2,0,0,-mTopHeight,0)
postInvalidate()
return true
}
})
private fun refreshLayout(distanceY: Float) {
val offset = mCurOffset - distanceY
if (offset != mCurOffset) {
mCurOffset = offset
val l = mTopView?.left?:0
val t = mTopView?.top?:0
val r = mTopView?.right?:0
// mCurOffset 上限 -mTopHeight 下限 0
val offsetLimit = Math.min(0,Math.max(mCurOffset?.toInt(),-mTopHeight))
val topLimit = mTopHeight + offsetLimit?.toInt()?:0
val topT = (parallRate * offsetLimit).toInt()
mTopView?.layout(l,topT,r,topT + mTopHeight)
mContentView?.layout(l,topLimit,r,topLimit + mTopHeight + mContentView?.measuredHeight!!)
}
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
// 需要拦截的时候返回 true
ev?:return false
if (mCurOffset <= - mTopHeight && ev.actionMasked != MotionEvent.ACTION_DOWN) {
// val downEv = MotionEvent.obtain(ev)
// downEv.action = MotionEvent.ACTION_DOWN
// mContentView?.onTouchEvent(downEv)
return false
}
return mGestenerDetector.onTouchEvent(ev)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
mGestenerDetector.onTouchEvent(event)
return true
}
/**
* 动态展开
*/
fun expand(){
mScroller.startScroll(0,0,0,mTopHeight)
invalidate()
}
/**
* 折叠起来
*/
fun collapsing(){
mScroller.startScroll(0,mCurOffset?.toInt(),0,-mTopHeight)
invalidate()
}
private var lastScrollY = -1f
override fun computeScroll() {
if (mScroller.computeScrollOffset()) {
var dy = mScroller.currY?.toFloat() - lastScrollY
if (lastScrollY == -1f) {
dy = 0f
}
lastScrollY = mScroller.currY?.toFloat()
Log.i(TAG,"computeScroll currY : ${mScroller.currY?.toFloat()} dy : $dy")
refreshLayout(-dy)
postInvalidate()
}
}
} | mit | 7715579d5a58b5c3615d2d9b70206f6e | 29.993289 | 142 | 0.593494 | 4.491046 | false | false | false | false |
yukuku/androidbible | Alkitab/src/main/java/yuku/alkitab/datatransfer/process/ImportProcess.kt | 1 | 8698 | package yuku.alkitab.datatransfer.process
import java.util.Date
import kotlinx.serialization.decodeFromString
import yuku.alkitab.base.util.History
import yuku.alkitab.base.util.Sqlitil
import yuku.alkitab.datatransfer.model.Gid
import yuku.alkitab.datatransfer.model.HistoryEntity
import yuku.alkitab.datatransfer.model.LabelEntity
import yuku.alkitab.datatransfer.model.MabelEntity
import yuku.alkitab.datatransfer.model.MarkerEntity
import yuku.alkitab.datatransfer.model.MarkerLabelEntity
import yuku.alkitab.datatransfer.model.Pin
import yuku.alkitab.datatransfer.model.PinsEntity
import yuku.alkitab.datatransfer.model.Root
import yuku.alkitab.datatransfer.model.Rpp
import yuku.alkitab.datatransfer.model.RppEntity
import yuku.alkitab.datatransfer.model.Snapshot
import yuku.alkitab.model.Label
import yuku.alkitab.model.Marker
import yuku.alkitab.model.Marker_Label
import yuku.alkitab.model.ProgressMark
class ImportProcess(
private val storage: ReadWriteStorageInterface,
private val log: LogInterface,
) {
data class Options(
val importHistory: Boolean,
val importMabel: Boolean,
val importPins: Boolean,
val importRpp: Boolean,
val actualRun: Boolean,
)
fun import(json: String, options: Options) {
log.log("Decoding from JSON")
val root = Serializer.importJson.decodeFromString<Root>(json)
log.log("JSON was read successfully")
if (options.actualRun) {
log.log("Proceeding with actual import unless error happens")
} else {
log.log("Simulating import")
}
storage.transact { handle ->
if (options.importHistory) {
history(root.snapshots.history)
}
if (options.importMabel) {
mabel(root.snapshots.mabel)
}
if (options.importPins) {
pins(root.snapshots.pins)
}
if (options.importRpp) {
rpp(root.snapshots.rp)
}
if (options.actualRun) {
log.log("Everything works without error, committing the change")
handle.commit()
}
}
log.log("All succeeded")
}
/**
* For history, there is no merging done locally, local will be replaced completely.
*/
private fun history(history: Snapshot<HistoryEntity>) {
val logger = log.logger("History")
val old = storage.history()
val new = history.entities.map { entity ->
History.Entry(entity.gid, entity.content.ari, entity.content.timestamp, entity.creator_id)
}
logger("${old.size} entries will be replaced by incoming ${new.size} entries")
storage.replaceHistory(new)
logger("replace succeeded")
}
/**
* For mabel, if the gid matches, they will be replaced. Otherwise, inserted.
*/
private fun mabel(mabel: Snapshot<MabelEntity>) {
val logger = log.logger("Markers and labels")
val oldMarkers = storage.markers()
val oldLabels = storage.labels()
val oldMarkerLabels = storage.markerLabels()
logger("there are currently ${oldMarkers.size} markers")
logger("- ${oldMarkers.count { it.kind == Marker.Kind.bookmark }} bookmarks")
logger("- ${oldMarkers.count { it.kind == Marker.Kind.note }} notes")
logger("- ${oldMarkers.count { it.kind == Marker.Kind.highlight }} highlights")
logger("there are currently ${oldLabels.size} labels")
val markerGids = oldMarkers.associateBy { it.gid }
val labelGids = oldLabels.associateBy { it.gid }
val markerLabelGids = oldMarkerLabels.associateBy { it.gid }
// do the counting first
logger("incoming markers will replace ${
mabel.entities.count { it is MarkerEntity && markerGids.containsKey(it.gid) }
} existing ones")
logger("incoming labels will replace ${
mabel.entities.count { it is LabelEntity && labelGids.containsKey(it.gid) }
} existing ones")
var markerNewCount = 0
var markerEditCount = 0
var labelNewCount = 0
var labelEditCount = 0
var markerLabelNewCount = 0
var markerLabelEditCount = 0
for (entity in mabel.entities) {
when (entity) {
is MarkerEntity -> {
val oldMarker = markerGids[entity.gid]
if (oldMarker == null) markerNewCount++ else markerEditCount++
val newMarker = (oldMarker ?: Marker.createEmptyMarker()).apply {
// _id will be nonzero if oldMarker is non-null
gid = entity.gid
ari = entity.content.ari
kind = Marker.Kind.fromCode(entity.content.kind)
caption = entity.content.caption
verseCount = entity.content.verseCount
createTime = Sqlitil.toDate(entity.content.createTime)
modifyTime = Sqlitil.toDate(entity.content.modifyTime)
}
storage.replaceMarker(newMarker)
}
is LabelEntity -> {
val oldLabel = labelGids[entity.gid]
if (oldLabel == null) labelNewCount++ else labelEditCount++
val newLabel = (oldLabel ?: Label.createEmptyLabel()).apply {
// _id will be nonzero if oldLabel is non-null
gid = entity.gid
title = entity.content.title
ordering = entity.content.ordering
backgroundColor = entity.content.backgroundColor
}
storage.replaceLabel(newLabel)
}
is MarkerLabelEntity -> {
// check validity of marker gid and label gid
val oldMarkerLabel = markerLabelGids[entity.gid]
if (oldMarkerLabel == null) markerLabelNewCount++ else markerLabelEditCount++
val newMarkerLabel = (oldMarkerLabel ?: Marker_Label.createEmptyMarker_Label()).apply {
// _id will be nonzero if oldMarkerLabel is non-null
gid = entity.gid
marker_gid = entity.content.marker_gid
label_gid = entity.content.label_gid
}
storage.replaceMarkerLabel(newMarkerLabel)
}
}
}
logger("added $markerNewCount markers, edited existing $markerEditCount markers")
logger("added $labelNewCount labels, edited existing $labelEditCount labels")
logger("added $markerLabelNewCount label-assignments, edited existing $markerLabelEditCount label-assignments")
}
private fun pins(pins: Snapshot<PinsEntity>) {
val logger = log.logger("Pins")
val old = storage.pins()
val new = pins.entities.firstOrNull()?.content?.pins.orEmpty()
logger("there are currently ${old.size} pins, incoming ${new.size} pins")
fun ProgressMark.display(): String {
val caption = caption
return if (caption == null) "Pin ${preset_id + 1}" else "Pin ${preset_id + 1} ($caption)"
}
fun Pin.display(): String {
val caption = caption
return if (caption == null) "Pin ${preset_id + 1}" else "Pin ${preset_id + 1} ($caption)"
}
for (newPin in new) {
val oldPin = old.find { it.preset_id == newPin.preset_id }
if (oldPin != null) {
logger("current ${oldPin.display()} will be replaced by an incoming ${newPin.display()}")
}
storage.replacePin(newPin)
logger("replace pin ${newPin.preset_id + 1} succeeded")
}
}
private fun rpp(rpp: Snapshot<RppEntity>) {
val logger = log.logger("Reading plan progress")
val old = storage.rpps()
val new = rpp.entities.map { entity ->
Rpp(Gid(entity.gid), entity.content.startTime, entity.content.done.toList())
}
logger("there are currently ${old.size} progresses, incoming ${new.size} progresses")
for (newRpp in new) {
val oldRpp = old.find { it.gid == newRpp.gid }
if (oldRpp != null) {
logger("current progress ${oldRpp.gid} will be replaced by an incoming progress")
}
storage.replaceRpp(newRpp)
logger("replace progress ${newRpp.gid} succeeded")
}
}
}
| apache-2.0 | 5686242f5c7c32b0b9d23091f61371d9 | 39.082949 | 119 | 0.592665 | 4.704164 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/models/Post.kt | 1 | 6942 | package com.emogoth.android.phone.mimi.db.models
import androidx.room.*
import com.emogoth.android.phone.mimi.db.MimiDatabase
import com.mimireader.chanlib.interfaces.PostConverter
import com.mimireader.chanlib.models.ChanPost
@Entity(tableName = MimiDatabase.POSTS_TABLE,
indices = [Index(Post.ID, unique = true), Index(Post.POST_ID), Index(Post.THREAD_ID), Index(Post.BOARD_NAME)])
class Post() : PostConverter {
constructor(boardName: String, threadId: Long, other: ChanPost): this() {
this.boardName = boardName
this.threadId = threadId
postId = other.no
closed = if (other.isClosed) 1 else 0
sticky = if (other.isSticky) 1 else 0
readableTime = other.now
author = other.name
comment = other.com
subject = other.sub
oldFilename = other.filename
newFilename = other.tim
fileExt = other.ext
fileWidth = other.width
fileHeight = other.height
thumbnailWidth = other.thumbnailWidth
thumbnailHeight = other.thumbnailHeight
epoch = other.time
md5 = other.md5
fileSize = other.fsize
resto = other.resto
bumplimit = other.bumplimit
imagelimit = other.imagelimit
semanticUrl = other.semanticUrl
replyCount = other.replies
imageCount = other.images
omittedPosts = other.omittedPosts
omittedImages = other.omittedImages
email = other.email
tripcode = other.trip
authorId = other.id
capcode = other.capcode
country = other.country
countryName = other.countryName
trollCountry = other.trollCountry
spoiler = other.spoiler
customSpoiler = other.customSpoiler
}
companion object {
const val ID = "id"
const val THREAD_ID = "thread_id"
const val BOARD_NAME = "board_name"
const val POST_ID = "post_id"
const val CLOSED = "closed"
const val STICKY = "sticky"
const val READABLE_TIME = "readable_time"
const val AUTHOR = "author"
const val COMMENT = "comment"
const val SUBJECT = "subject"
const val OLD_FILENAME = "old_filename"
const val NEW_FILENAME = "new_filename"
const val FILE_SIZE = "file_size"
const val FILE_EXT = "file_ext"
const val FILE_WIDTH = "file_width"
const val FILE_HEIGHT = "file_height"
const val THUMB_WIDTH = "thumb_width"
const val THUMB_HEIGHT = "thumb_height"
const val EPOCH = "epoch"
const val MD5 = "md5"
const val RESTO = "resto"
const val BUMP_LIMIT = "bump_limit"
const val IMAGE_LIMIT = "image_limit"
const val SEMANTIC_URL = "semantic_url"
const val REPLY_COUNT = "reply_count"
const val IMAGE_COUNT = "image_count"
const val OMITTED_POSTS = "omitted_posts"
const val OMITTED_IMAGE = "omitted_image"
const val EMAIL = "email"
const val TRIPCODE = "tripcode"
const val AUTHOR_ID = "author_id"
const val CAPCODE = "capcode"
const val COUNTRY = "country"
const val COUNTRY_NAME = "country_name"
const val TROLL_COUNTRY = "troll_country"
const val SPOILER = "spoiler"
const val CUSTOM_SPOILER = "custom_spoiler"
}
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ID)
var id: Int? = null
@ColumnInfo(name = THREAD_ID)
var threadId: Long = 0L
@ColumnInfo(name = BOARD_NAME)
var boardName: String = ""
@ColumnInfo(name = POST_ID)
var postId: Long = 0
@ColumnInfo(name = CLOSED)
var closed: Int = 0
@ColumnInfo(name = STICKY)
var sticky: Int = 0
@ColumnInfo(name = READABLE_TIME)
var readableTime: String? = null
@ColumnInfo(name = AUTHOR)
var author: String? = null
@ColumnInfo(name = COMMENT)
var comment: String? = null
@ColumnInfo(name = SUBJECT)
var subject: String? = null
@ColumnInfo(name = OLD_FILENAME)
var oldFilename: String? = null
@ColumnInfo(name = NEW_FILENAME)
var newFilename: String? = null
@ColumnInfo(name = FILE_EXT)
var fileExt: String? = null
@ColumnInfo(name = FILE_WIDTH)
var fileWidth: Int = 0
@ColumnInfo(name = FILE_HEIGHT)
var fileHeight: Int = 0
@ColumnInfo(name = THUMB_WIDTH)
var thumbnailWidth: Int = 0
@ColumnInfo(name = THUMB_HEIGHT)
var thumbnailHeight: Int = 0
@ColumnInfo(name = EPOCH)
var epoch: Long = 0
@ColumnInfo(name = MD5)
var md5: String? = null
@ColumnInfo(name = FILE_SIZE)
var fileSize: Int = 0
@ColumnInfo(name = RESTO)
var resto: Int = 0
@ColumnInfo(name = BUMP_LIMIT)
var bumplimit: Int = 0
@ColumnInfo(name = IMAGE_LIMIT)
var imagelimit: Int = 0
@ColumnInfo(name = SEMANTIC_URL)
var semanticUrl: String? = null
@ColumnInfo(name = REPLY_COUNT)
var replyCount: Int = 0
@ColumnInfo(name = IMAGE_COUNT)
var imageCount: Int = 0
@ColumnInfo(name = OMITTED_POSTS)
var omittedPosts: Int = 0
@ColumnInfo(name = OMITTED_IMAGE)
var omittedImages: Int = 0
@ColumnInfo(name = EMAIL)
var email: String? = null
@ColumnInfo(name = TRIPCODE)
var tripcode: String? = null
@ColumnInfo(name = AUTHOR_ID)
var authorId: String? = null
@ColumnInfo(name = CAPCODE)
var capcode: String? = null
@ColumnInfo(name = COUNTRY)
var country: String? = null
@ColumnInfo(name = COUNTRY_NAME)
var countryName: String? = null
@ColumnInfo(name = TROLL_COUNTRY)
var trollCountry: String? = null
@ColumnInfo(name = SPOILER)
var spoiler: Int = 0
@ColumnInfo(name = CUSTOM_SPOILER)
var customSpoiler: Int = 0
override fun toPost(): ChanPost {
val post = ChanPost()
post.no = postId
post.isClosed = closed == 1
post.isSticky = sticky == 1
post.bumplimit = bumplimit
post.com = comment
post.sub = subject
post.name = author
post.ext = fileExt
post.filename = oldFilename
post.fsize = fileSize
post.height = fileHeight
post.width = fileWidth
post.thumbnailHeight = thumbnailHeight
post.thumbnailWidth = thumbnailWidth
post.imagelimit = imagelimit
post.images = imageCount
post.replies = replyCount
post.resto = resto
post.omittedImages = omittedImages
post.omittedPosts = omittedPosts
post.semanticUrl = semanticUrl
post.md5 = md5
post.tim = newFilename
post.time = epoch
post.email = email
post.trip = tripcode
post.id = authorId
post.capcode = capcode
post.country = country
post.countryName = countryName
post.trollCountry = trollCountry
post.spoiler = spoiler
post.customSpoiler = customSpoiler
return post
}
} | apache-2.0 | 94851a155000f6e7aec992c95e27924c | 32.868293 | 118 | 0.624172 | 4.022016 | false | false | false | false |
jitsi/jicofo | jicofo-common/src/main/kotlin/org/jitsi/jicofo/xmpp/jingle/JingleStats.kt | 1 | 2168 | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2015-Present 8x8, 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 org.jitsi.jicofo.xmpp.jingle
import org.jitsi.jicofo.metrics.JicofoMetricsContainer
import org.jitsi.metrics.CounterMetric
import org.jitsi.xmpp.extensions.jingle.JingleAction
import org.json.simple.JSONObject
import java.util.concurrent.ConcurrentHashMap
class JingleStats {
companion object {
private val stanzasReceivedByAction: MutableMap<JingleAction, CounterMetric> = ConcurrentHashMap()
private val stanzasSentByAction: MutableMap<JingleAction, CounterMetric> = ConcurrentHashMap()
@JvmStatic
fun stanzaReceived(action: JingleAction) {
stanzasReceivedByAction.computeIfAbsent(action) {
JicofoMetricsContainer.instance.registerCounter(
"jingle_${action.name.lowercase()}_received",
"Number of ${action.name} stanzas received"
)
}.inc()
}
@JvmStatic
fun stanzaSent(action: JingleAction) {
stanzasSentByAction.computeIfAbsent(action) {
JicofoMetricsContainer.instance.registerCounter(
"jingle_${action.name.lowercase()}_sent",
"Number of ${action.name} stanzas sent."
)
}.inc()
}
@JvmStatic
fun toJson() = JSONObject().apply {
this["sent"] = stanzasSentByAction.map { it.key to it.value.get() }.toMap()
this["received"] = stanzasReceivedByAction.map { it.key to it.value.get() }.toMap()
}
}
}
| apache-2.0 | 337bd7b5eac4d7bd4eba73662459af19 | 36.37931 | 106 | 0.660055 | 4.652361 | false | false | false | false |
Jire/Abendigo | src/main/kotlin/org/abendigo/plugin/csgo/RCSPlugin.kt | 1 | 1726 | package org.abendigo.plugin.csgo
import org.abendigo.DEBUG
import org.abendigo.csgo.Engine.clientState
import org.abendigo.csgo.Me
import org.abendigo.csgo.Vector
import org.abendigo.csgo.normalizeAngle
import org.abendigo.util.randomFloat
import org.jire.arrowhead.keyReleased
object RCSPlugin : InGamePlugin("RCS", duration = 32) {
// 0F = no correction, 2F = 100% correction
private const val RANDOM_MIN = 1.86F
private const val RANDOM_MAX = 1.97F
private var prevFired = 0
private val lastPunch = FloatArray(2)
override fun cycle() {
val shotsFired = +Me().shotsFired
val weapon = +Me().weapon
try {
if (!weapon.type!!.automatic) {
reset()
return
}
} catch (t: Throwable) {
if (DEBUG) t.printStackTrace()
}
val bulletsLeft = +weapon.bullets
if (shotsFired <= 2 || shotsFired < prevFired || bulletsLeft <= 0 || +Me().dead) {
if (keyReleased(1)) { // prevent aim flick down cheaphax
reset()
return
}
}
val punch = +Me().punch
punch.x *= randomFloat(RANDOM_MIN, RANDOM_MAX)
punch.y *= randomFloat(RANDOM_MIN, RANDOM_MAX)
punch.z = 0F
normalizeAngle(punch)
var view = clientState(1024).angle()
if (view.x == 0F || view.y == 0F || view.z == 0F) view = clientState(1024).angle()
val newView = Vector(punch.x, punch.y, punch.z)
newView.x -= lastPunch[0]
newView.y -= lastPunch[1]
newView.z = 0F
normalizeAngle(newView)
view.x -= newView.x
view.y -= newView.y
view.z = 0F
normalizeAngle(view)
clientState(1024).angle(view)
lastPunch[0] = punch.x
lastPunch[1] = punch.y
prevFired = shotsFired
}
private fun reset() {
prevFired = 0
lastPunch[0] = 0F
lastPunch[1] = 0F
}
override fun disable() {
reset()
}
} | gpl-3.0 | ca43bfd90355cf34d199b717676dfa97 | 20.320988 | 84 | 0.670915 | 2.981002 | false | false | false | false |
bbqapp/bbqapp-android | app/src/test/kotlin/org/bbqaap/android/extension/LocationUtilsTest.kt | 1 | 2459 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 bbqapp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.bbqaap.android.extension
import android.location.Address
import android.location.Location
import org.bbqapp.android.extension.getLatLng
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.bbqapp.android.api.model.Location as ApiLocation
class LocationUtilsTest {
@Test fun testLocationToLatLng() {
val location = mock(Location::class.java)
`when`(location.latitude).thenReturn(12.65)
`when`(location.longitude).thenReturn(98.12)
val latLng = location.getLatLng()
assertEquals(latLng.latitude, 12.65, 0.001)
assertEquals(latLng.longitude, 98.12, 0.001)
}
@Test fun testApiLocationToLatLng() {
var location = ApiLocation(listOf(95.23, 12.54), "Point")
var latLng = location.getLatLng()
assertEquals(latLng.latitude, 12.54, 0.001)
assertEquals(latLng.longitude, 95.23, 0.001)
}
@Test fun testAddressToLatLng() {
var address = mock(Address::class.java)
`when`(address.latitude).thenReturn(14.98)
`when`(address.longitude).thenReturn(89.21)
var latLng = address.getLatLng()
assertEquals(latLng.latitude, 14.98, 0.001)
assertEquals(latLng.longitude, 89.21, 0.001)
}
} | mit | dc487e053fb455de8184ab0c6a4e441d | 35.716418 | 81 | 0.721431 | 4.057756 | false | true | false | false |
matejdro/WearMusicCenter | mobile/src/main/java/com/matejdro/wearmusiccenter/actions/playback/ReverseThirtySecondsAction.kt | 1 | 2268 | package com.matejdro.wearmusiccenter.actions.playback
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.PersistableBundle
import androidx.appcompat.content.res.AppCompatResources
import com.matejdro.wearmusiccenter.R
import com.matejdro.wearmusiccenter.actions.ActionHandler
import com.matejdro.wearmusiccenter.actions.PhoneAction
import com.matejdro.wearmusiccenter.actions.SelectableAction
import com.matejdro.wearmusiccenter.music.MusicService
import com.matejdro.wearmusiccenter.view.actionconfigs.ActionConfigFragment
import com.matejdro.wearmusiccenter.view.actionconfigs.ReverseSecondsConfigFragment
import javax.inject.Inject
/**
* Class name needs to be kept at "thirty seconds" for backwards compatibility
*/
class ReverseThirtySecondsAction : SelectableAction {
constructor(context: Context) : super(context)
constructor(context: Context, bundle: PersistableBundle) : super(context, bundle) {
secondsToReverse = bundle.getInt(KEY_SECONDS_TO_REVERSE, DEFAULT_SECONDS_TO_REVERSE)
}
var secondsToReverse: Int = DEFAULT_SECONDS_TO_REVERSE
override fun retrieveTitle(): String = context.getString(R.string.action_reverse_seconds, secondsToReverse)
override val defaultIcon: Drawable
get() = AppCompatResources.getDrawable(context, R.drawable.action_reverse_30_seconds)!!
override val configFragment: Class<out ActionConfigFragment<out PhoneAction>>
get() = ReverseSecondsConfigFragment::class.java
override fun writeToBundle(bundle: PersistableBundle) {
super.writeToBundle(bundle)
bundle.putInt(KEY_SECONDS_TO_REVERSE, secondsToReverse)
}
class Handler @Inject constructor(private val service: MusicService) : ActionHandler<ReverseThirtySecondsAction> {
override suspend fun handleAction(action: ReverseThirtySecondsAction) {
val currentPos = service.currentMediaController?.playbackState?.position ?: return
service.currentMediaController?.transportControls?.seekTo(
(currentPos - action.secondsToReverse * 1_000).coerceAtLeast(0)
)
}
}
}
private const val KEY_SECONDS_TO_REVERSE = "SECONDS_TO_REVERSE"
private const val DEFAULT_SECONDS_TO_REVERSE = 30
| gpl-3.0 | 260cde24fdc32b5bc6107d7c792f2912 | 44.36 | 118 | 0.777778 | 4.898488 | false | true | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/store/SuspiciousEventStore.kt | 1 | 1820 | package au.com.codeka.warworlds.server.store
import au.com.codeka.warworlds.server.proto.SuspiciousEvent
import au.com.codeka.warworlds.server.store.base.BaseStore
import java.util.*
/**
* Store for keep track of suspicious events.
*/
class SuspiciousEventStore(fileName: String) : BaseStore(fileName) {
fun add(events: Collection<SuspiciousEvent>) {
newTransaction().use { t ->
val writer = newWriter(t)
.stmt("INSERT INTO suspicious_events (" +
"timestamp, day, empire_id, event) " +
"VALUES (?, ?, ?, ?)")
for (event in events) {
writer
.param(0, event.timestamp)
.param(1, StatsHelper.timestampToDay(event.timestamp))
.param(2, event.modification.empire_id)
.param(3, event.encode())
.execute()
}
t.commit()
}
}
fun query( /* TODO: search? */): Collection<SuspiciousEvent> {
newReader()
.stmt("SELECT event FROM suspicious_events ORDER BY timestamp DESC")
.query().use { res ->
val events: ArrayList<SuspiciousEvent> = ArrayList<SuspiciousEvent>()
while (res.next()) {
events.add(SuspiciousEvent.ADAPTER.decode(res.getBytes(0)))
}
return events
}
}
override fun onOpen(diskVersion: Int): Int {
var version = diskVersion
if (version == 0) {
newWriter()
.stmt(
"CREATE TABLE suspicious_events (" +
" timestamp INTEGER," +
" day INTEGER," +
" empire_id INTEGER," +
" event BLOB)")
.execute()
newWriter()
.stmt("CREATE INDEX IX_suspicious_events_day ON suspicious_events (day)")
.execute()
version++
}
return version
}
} | mit | 51c32d037f8620d7bfdbf6cd2de46de7 | 29.864407 | 83 | 0.567033 | 4.282353 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/templating/RandTemplate.kt | 1 | 1945 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.templating
import kotlin.math.max
import kotlin.math.min
object RandTemplate : Template("rand") {
private const val dashPatternString = "\\s*[-]\\s*"
private val dashPattern = dashPatternString.toRegex()
override fun invoke(arguments: String): String {
if (arguments.isBlank()) {
return arguments
}
val split = arguments.split(dashPattern).mapNotNull { it.trim() }.filter(String::isNotEmpty)
val first = split[0].toIntOrNull() ?: return arguments
val second = split[1].toIntOrNull() ?: return arguments
val minVal = min(first, second)
val maxVal = max(first, second)
return (minVal..maxVal).random().toString()
}
}
| mit | 378b0cf344fbea1a3fd399257a7b65d0 | 45.309524 | 105 | 0.723907 | 4.481567 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/mosaic/src/main/kotlin/com/teamwizardry/librarianlib/mosaic/PinnedWrapper.kt | 1 | 2027 | package com.teamwizardry.librarianlib.mosaic
import com.teamwizardry.librarianlib.math.Matrix4d
import net.minecraft.client.render.RenderLayer
import net.minecraft.util.Identifier
import java.awt.Color
public class PinnedWrapper(
public val wrapped: Sprite,
override val pinTop: Boolean,
override val pinBottom: Boolean,
override val pinLeft: Boolean,
override val pinRight: Boolean
): Sprite {
override fun minU(animFrames: Int): Float = wrapped.minU(animFrames)
override fun minU(): Float = wrapped.minU()
override fun minV(animFrames: Int): Float = wrapped.minV(animFrames)
override fun minV(): Float = wrapped.minV()
override fun maxU(animFrames: Int): Float = wrapped.maxU(animFrames)
override fun maxU(): Float = wrapped.maxU()
override fun maxV(animFrames: Int): Float = wrapped.maxV(animFrames)
override fun maxV(): Float = wrapped.maxV()
override fun draw(matrix: Matrix4d, x: Float, y: Float, animTicks: Int, tint: Color) {
wrapped.draw(matrix, x, y, animTicks, tint)
}
override fun draw(matrix: Matrix4d, x: Float, y: Float, width: Float, height: Float, animTicks: Int, tint: Color) {
wrapped.draw(matrix, x, y, width, height, animTicks, tint)
}
override fun pinnedWrapper(top: Boolean, bottom: Boolean, left: Boolean, right: Boolean): Sprite {
return wrapped.pinnedWrapper(top, bottom, left, right)
}
override val texture: Identifier get() = wrapped.texture
override val width: Int get() = wrapped.width
override val height: Int get() = wrapped.height
override val uSize: Float get() = wrapped.uSize
override val vSize: Float get() = wrapped.vSize
override val frameCount: Int get() = wrapped.frameCount
override val minUCap: Float get() = wrapped.minUCap
override val minVCap: Float get() = wrapped.minVCap
override val maxUCap: Float get() = wrapped.maxUCap
override val maxVCap: Float get() = wrapped.maxVCap
override val rotation: Int get() = wrapped.rotation
} | lgpl-3.0 | bfaff2592f92dd357054d29d78ade720 | 42.148936 | 119 | 0.710903 | 4.037849 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/actions/RefreshCargoProjectsAction.kt | 3 | 1238 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import org.rust.cargo.project.model.CargoProjectActionBase
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.model.guessAndSetupRustProject
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.runconfig.hasCargoProject
import org.rust.ide.notifications.confirmLoadingUntrustedProject
import org.rust.openapiext.saveAllDocuments
class RefreshCargoProjectsAction : CargoProjectActionBase() {
override fun update(e: AnActionEvent) {
val project = e.project
e.presentation.isEnabled = project != null && project.toolchain != null && project.hasCargoProject
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (!project.confirmLoadingUntrustedProject()) return
saveAllDocuments()
if (project.toolchain == null || !project.hasCargoProject) {
guessAndSetupRustProject(project, explicitRequest = true)
} else {
project.cargoProjects.refreshAllProjects()
}
}
}
| mit | a19663fb1adf9e9c9ae5a3a4d9f1ec14 | 33.388889 | 106 | 0.739903 | 4.585185 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/lang/parser/IdentifierParser.kt | 1 | 1299 | package org.jetbrains.fortran.lang.parser
import com.intellij.lang.PsiBuilder
import org.jetbrains.fortran.lang.FortranTypes.IDENTIFIER
import org.jetbrains.fortran.lang.parser.FortranParserUtil.consumeToken
import org.jetbrains.fortran.lang.parser.FortranParserUtil.enter_section_
import org.jetbrains.fortran.lang.parser.FortranParserUtil.exit_section_
import org.jetbrains.fortran.lang.parser.FortranParserUtil.recursion_guard_
import org.jetbrains.fortran.lang.psi.FortranTokenSets
import org.jetbrains.fortran.lang.psi.FortranTokenType
class IdentifierParser : FortranParserUtil.Parser {
override fun parse(builder: PsiBuilder, level: Int): Boolean {
if (!recursion_guard_(builder, level, "Identifier")) return false
var result: Boolean
val marker = enter_section_(builder)
result = consumeToken(builder, IDENTIFIER)
if (!result) {
val tokenType = builder.tokenType
if (tokenType === FortranTokenType.WORD || FortranTokenSets.KEYWORDS.contains(tokenType)) {
builder.remapCurrentToken(FortranParserUtil.cloneTTwithBase(tokenType, IDENTIFIER))
result = consumeToken(builder, IDENTIFIER)
}
}
exit_section_(builder, marker, null, result)
return result
}
}
| apache-2.0 | 2747f55d69d1b87921b56a01c3b45ea7 | 45.392857 | 103 | 0.735181 | 4.639286 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/screens/LayerTransformTestScreen.kt | 1 | 1244 | package com.teamwizardry.librarianlib.facade.test.screens
import com.teamwizardry.librarianlib.facade.FacadeScreen
import com.teamwizardry.librarianlib.facade.layer.GuiLayerEvents
import com.teamwizardry.librarianlib.facade.layers.SpriteLayer
import com.teamwizardry.librarianlib.core.util.vec
import com.teamwizardry.librarianlib.mosaic.Mosaic
import net.minecraft.text.Text
import net.minecraft.util.Identifier
class LayerTransformTestScreen(title: Text): FacadeScreen(title) {
init {
val dirt = Mosaic(Identifier("minecraft:textures/block/dirt.png"), 16, 16).getSprite("")
val stone = Mosaic(Identifier("minecraft:textures/block/stone.png"), 16, 16).getSprite("")
val layer = SpriteLayer(dirt)
layer.pos = vec(32, 32)
layer.rotation = Math.toRadians(15.0)
val layer2 = SpriteLayer(dirt)
layer2.pos = vec(32, 32)
layer2.rotation = Math.toRadians(-15.0)
layer.add(layer2)
layer.BUS.hook<GuiLayerEvents.MouseMove> {
layer.sprite = if (layer.mouseOver) stone else dirt
}
layer2.BUS.hook<GuiLayerEvents.MouseMove> {
layer2.sprite = if (layer2.mouseOver) stone else dirt
}
facade.root.add(layer)
}
} | lgpl-3.0 | 73d41936ec4210c83bcebc7fe158d8f7 | 37.90625 | 98 | 0.70418 | 3.949206 | false | true | false | false |
OpenConference/DroidconBerlin2017 | app/src/main/java/de/droidcon/berlin2018/ui/speakerdetail/SpeakerDetailsViewHolder.kt | 1 | 749 | package com.openconference.speakerdetails
import android.support.annotation.DrawableRes
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import de.droidcon.berlin2018.R
/**
* ViewHolder for icon text combination
*
* @author Hannes Dorfmann
*/
open class SpeakerDetailsViewHolder(v: View) : RecyclerView.ViewHolder(v) {
val icon = v.findViewById<ImageView>(R.id.icon)
val text = v.findViewById<TextView>(R.id.text)
inline fun bind(@DrawableRes iconRes: Int?, t: String) {
if (iconRes == null) {
icon.visibility = View.INVISIBLE
} else {
icon.setImageDrawable(itemView.resources.getDrawable(iconRes))
}
text.text = t
}
}
| apache-2.0 | c056443909efbc811c848e9a8e881696 | 24.827586 | 75 | 0.740988 | 3.921466 | false | false | false | false |
androidx/androidx | compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/Effects.kt | 3 | 20050 | /*
* 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.runtime
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlin.coroutines.EmptyCoroutineContext
/**
* Schedule [effect] to run when the current composition completes successfully and applies
* changes. [SideEffect] can be used to apply side effects to objects managed by the
* composition that are not backed by [snapshots][androidx.compose.runtime.snapshots.Snapshot] so
* as not to leave those objects in an inconsistent state if the current composition operation
* fails.
*
* [effect] will always be run on the composition's apply dispatcher and appliers are never run
* concurrent with themselves, one another, applying changes to the composition tree, or running
* [RememberObserver] event callbacks. [SideEffect]s are always run after [RememberObserver]
* event callbacks.
*
* A [SideEffect] runs after **every** recomposition. To launch an ongoing task spanning
* potentially many recompositions, see [LaunchedEffect]. To manage an event subscription or other
* object lifecycle, see [DisposableEffect].
*/
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun SideEffect(
effect: () -> Unit
) {
currentComposer.recordSideEffect(effect)
}
/**
* Receiver scope for [DisposableEffect] that offers the [onDispose] clause that should be
* the last statement in any call to [DisposableEffect].
*/
class DisposableEffectScope {
/**
* Provide [onDisposeEffect] to the [DisposableEffect] to run when it leaves the composition
* or its key changes.
*/
inline fun onDispose(
crossinline onDisposeEffect: () -> Unit
): DisposableEffectResult = object : DisposableEffectResult {
override fun dispose() {
onDisposeEffect()
}
}
}
interface DisposableEffectResult {
fun dispose()
}
private val InternalDisposableEffectScope = DisposableEffectScope()
private class DisposableEffectImpl(
private val effect: DisposableEffectScope.() -> DisposableEffectResult
) : RememberObserver {
private var onDispose: DisposableEffectResult? = null
override fun onRemembered() {
onDispose = InternalDisposableEffectScope.effect()
}
override fun onForgotten() {
onDispose?.dispose()
onDispose = null
}
override fun onAbandoned() {
// Nothing to do as [onRemembered] was not called.
}
}
private const val DisposableEffectNoParamError =
"DisposableEffect must provide one or more 'key' parameters that define the identity of " +
"the DisposableEffect and determine when its previous effect should be disposed and " +
"a new effect started for the new key."
private const val LaunchedEffectNoParamError =
"LaunchedEffect must provide one or more 'key' parameters that define the identity of " +
"the LaunchedEffect and determine when its previous effect coroutine should be cancelled " +
"and a new effect launched for the new key."
/**
* A side effect of composition that must be reversed or cleaned up if the [DisposableEffect]
* leaves the composition.
*
* It is an error to call [DisposableEffect] without at least one `key` parameter.
*/
// This deprecated-error function shadows the varargs overload so that the varargs version
// is not used without key parameters.
@Composable
@NonRestartableComposable
@Suppress("DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER")
@Deprecated(DisposableEffectNoParamError, level = DeprecationLevel.ERROR)
fun DisposableEffect(
effect: DisposableEffectScope.() -> DisposableEffectResult
): Unit = error(DisposableEffectNoParamError)
/**
* A side effect of composition that must run for any new unique value of [key1] and must be
* reversed or cleaned up if [key1] changes or if the [DisposableEffect] leaves the composition.
*
* A [DisposableEffect]'s _key_ is a value that defines the identity of the
* [DisposableEffect]. If a key changes, the [DisposableEffect] must
* [dispose][DisposableEffectScope.onDispose] its current [effect] and reset by calling [effect]
* again. Examples of keys include:
*
* * Observable objects that the effect subscribes to
* * Unique request parameters to an operation that must cancel and retry if those parameters change
*
* [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize
* when a different key is provided, performing cleanup for the old operation before
* initializing the new. For example:
*
* @sample androidx.compose.runtime.samples.disposableEffectSample
*
* A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause
* as the final statement in its [effect] block. If your operation does not require disposal
* it might be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should
* be managed by the composition.
*
* There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call
* to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run
* on the composition's apply dispatcher and appliers are never run concurrent with themselves,
* one another, applying changes to the composition tree, or running [RememberObserver] event
* callbacks.
*/
@Composable
@NonRestartableComposable
fun DisposableEffect(
key1: Any?,
effect: DisposableEffectScope.() -> DisposableEffectResult
) {
remember(key1) { DisposableEffectImpl(effect) }
}
/**
* A side effect of composition that must run for any new unique value of [key1] or [key2]
* and must be reversed or cleaned up if [key1] or [key2] changes, or if the
* [DisposableEffect] leaves the composition.
*
* A [DisposableEffect]'s _key_ is a value that defines the identity of the
* [DisposableEffect]. If a key changes, the [DisposableEffect] must
* [dispose][DisposableEffectScope.onDispose] its current [effect] and reset by calling [effect]
* again. Examples of keys include:
*
* * Observable objects that the effect subscribes to
* * Unique request parameters to an operation that must cancel and retry if those parameters change
*
* [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize
* when a different key is provided, performing cleanup for the old operation before
* initializing the new. For example:
*
* @sample androidx.compose.runtime.samples.disposableEffectSample
*
* A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause
* as the final statement in its [effect] block. If your operation does not require disposal
* it might be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should
* be managed by the composition.
*
* There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call
* to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run
* on the composition's apply dispatcher and appliers are never run concurrent with themselves,
* one another, applying changes to the composition tree, or running [RememberObserver]
* event callbacks.
*/
@Composable
@NonRestartableComposable
fun DisposableEffect(
key1: Any?,
key2: Any?,
effect: DisposableEffectScope.() -> DisposableEffectResult
) {
remember(key1, key2) { DisposableEffectImpl(effect) }
}
/**
* A side effect of composition that must run for any new unique value of [key1], [key2]
* or [key3] and must be reversed or cleaned up if [key1], [key2] or [key3]
* changes, or if the [DisposableEffect] leaves the composition.
*
* A [DisposableEffect]'s _key_ is a value that defines the identity of the
* [DisposableEffect]. If a key changes, the [DisposableEffect] must
* [dispose][DisposableEffectScope.onDispose] its current [effect] and reset by calling [effect]
* again. Examples of keys include:
*
* * Observable objects that the effect subscribes to
* * Unique request parameters to an operation that must cancel and retry if those parameters change
*
* [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize
* when a different key is provided, performing cleanup for the old operation before
* initializing the new. For example:
*
* @sample androidx.compose.runtime.samples.disposableEffectSample
*
* A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause
* as the final statement in its [effect] block. If your operation does not require disposal
* it might be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should
* be managed by the composition.
*
* There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call
* to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run
* on the composition's apply dispatcher and appliers are never run concurrent with themselves,
* one another, applying changes to the composition tree, or running [RememberObserver] event
* callbacks.
*/
@Composable
@NonRestartableComposable
fun DisposableEffect(
key1: Any?,
key2: Any?,
key3: Any?,
effect: DisposableEffectScope.() -> DisposableEffectResult
) {
remember(key1, key2, key3) { DisposableEffectImpl(effect) }
}
/**
* A side effect of composition that must run for any new unique value of [keys] and must
* be reversed or cleaned up if any [keys] change or if the [DisposableEffect] leaves the
* composition.
*
* A [DisposableEffect]'s _key_ is a value that defines the identity of the
* [DisposableEffect]. If a key changes, the [DisposableEffect] must
* [dispose][DisposableEffectScope.onDispose] its current [effect] and reset by calling [effect]
* again. Examples of keys include:
*
* * Observable objects that the effect subscribes to
* * Unique request parameters to an operation that must cancel and retry if those parameters change
*
* [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize
* when a different key is provided, performing cleanup for the old operation before
* initializing the new. For example:
*
* @sample androidx.compose.runtime.samples.disposableEffectSample
*
* A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause
* as the final statement in its [effect] block. If your operation does not require disposal
* it might be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should
* be managed by the composition.
*
* There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call
* to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run
* on the composition's apply dispatcher and appliers are never run concurrent with themselves,
* one another, applying changes to the composition tree, or running [RememberObserver] event
* callbacks.
*/
@Composable
@NonRestartableComposable
@Suppress("ArrayReturn")
fun DisposableEffect(
vararg keys: Any?,
effect: DisposableEffectScope.() -> DisposableEffectResult
) {
remember(*keys) { DisposableEffectImpl(effect) }
}
internal class LaunchedEffectImpl(
parentCoroutineContext: CoroutineContext,
private val task: suspend CoroutineScope.() -> Unit
) : RememberObserver {
private val scope = CoroutineScope(parentCoroutineContext)
private var job: Job? = null
override fun onRemembered() {
job?.cancel("Old job was still running!")
job = scope.launch(block = task)
}
override fun onForgotten() {
job?.cancel()
job = null
}
override fun onAbandoned() {
job?.cancel()
job = null
}
}
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] when the [LaunchedEffect]
* leaves the composition.
*
* It is an error to call [LaunchedEffect] without at least one `key` parameter.
*/
// This deprecated-error function shadows the varargs overload so that the varargs version
// is not used without key parameters.
@Deprecated(LaunchedEffectNoParamError, level = DeprecationLevel.ERROR)
@Suppress("DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER")
@Composable
fun LaunchedEffect(
block: suspend CoroutineScope.() -> Unit
): Unit = error(LaunchedEffectNoParamError)
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when
* [LaunchedEffect] is recomposed with a different [key1]. The coroutine will be
* [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition.
*
* This function should **not** be used to (re-)launch ongoing tasks in response to callback
* events by way of storing callback data in [MutableState] passed to [key1]. Instead, see
* [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs
* scoped to the composition in response to event callbacks.
*/
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
key1: Any?,
block: suspend CoroutineScope.() -> Unit
) {
val applyContext = currentComposer.applyCoroutineContext
remember(key1) { LaunchedEffectImpl(applyContext, block) }
}
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when
* [LaunchedEffect] is recomposed with a different [key1] or [key2]. The coroutine will be
* [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition.
*
* This function should **not** be used to (re-)launch ongoing tasks in response to callback
* events by way of storing callback data in [MutableState] passed to [key]. Instead, see
* [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs
* scoped to the composition in response to event callbacks.
*/
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
key1: Any?,
key2: Any?,
block: suspend CoroutineScope.() -> Unit
) {
val applyContext = currentComposer.applyCoroutineContext
remember(key1, key2) { LaunchedEffectImpl(applyContext, block) }
}
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when
* [LaunchedEffect] is recomposed with a different [key1], [key2] or [key3].
* The coroutine will be [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition.
*
* This function should **not** be used to (re-)launch ongoing tasks in response to callback
* events by way of storing callback data in [MutableState] passed to [key]. Instead, see
* [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs
* scoped to the composition in response to event callbacks.
*/
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
key1: Any?,
key2: Any?,
key3: Any?,
block: suspend CoroutineScope.() -> Unit
) {
val applyContext = currentComposer.applyCoroutineContext
remember(key1, key2, key3) { LaunchedEffectImpl(applyContext, block) }
}
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when
* [LaunchedEffect] is recomposed with any different [keys]. The coroutine will be
* [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition.
*
* This function should **not** be used to (re-)launch ongoing tasks in response to callback
* events by way of storing callback data in [MutableState] passed to [key]. Instead, see
* [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs
* scoped to the composition in response to event callbacks.
*/
@Composable
@NonRestartableComposable
@Suppress("ArrayReturn")
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
vararg keys: Any?,
block: suspend CoroutineScope.() -> Unit
) {
val applyContext = currentComposer.applyCoroutineContext
remember(*keys) { LaunchedEffectImpl(applyContext, block) }
}
@PublishedApi
internal class CompositionScopedCoroutineScopeCanceller(
val coroutineScope: CoroutineScope
) : RememberObserver {
override fun onRemembered() {
// Nothing to do
}
override fun onForgotten() {
coroutineScope.cancel()
}
override fun onAbandoned() {
coroutineScope.cancel()
}
}
@PublishedApi
@OptIn(InternalComposeApi::class)
internal fun createCompositionCoroutineScope(
coroutineContext: CoroutineContext,
composer: Composer
) = if (coroutineContext[Job] != null) {
CoroutineScope(
Job().apply {
completeExceptionally(
IllegalArgumentException(
"CoroutineContext supplied to " +
"rememberCoroutineScope may not include a parent job"
)
)
}
)
} else {
val applyContext = composer.applyCoroutineContext
CoroutineScope(applyContext + Job(applyContext[Job]) + coroutineContext)
}
/**
* Return a [CoroutineScope] bound to this point in the composition using the optional
* [CoroutineContext] provided by [getContext]. [getContext] will only be called once and the same
* [CoroutineScope] instance will be returned across recompositions.
*
* This scope will be [cancelled][CoroutineScope.cancel] when this call leaves the composition.
* The [CoroutineContext] returned by [getContext] may not contain a [Job] as this scope is
* considered to be a child of the composition.
*
* The default dispatcher of this scope if one is not provided by the context returned by
* [getContext] will be the applying dispatcher of the composition's [Recomposer].
*
* Use this scope to launch jobs in response to callback events such as clicks or other user
* interaction where the response to that event needs to unfold over time and be cancelled if the
* composable managing that process leaves the composition. Jobs should never be launched into
* **any** coroutine scope as a side effect of composition itself. For scoped ongoing jobs
* initiated by composition, see [LaunchedEffect].
*
* This function will not throw if preconditions are not met, as composable functions do not yet
* fully support exceptions. Instead the returned scope's [CoroutineScope.coroutineContext] will
* contain a failed [Job] with the associated exception and will not be capable of launching
* child jobs.
*/
@Composable
inline fun rememberCoroutineScope(
crossinline getContext: @DisallowComposableCalls () -> CoroutineContext =
{ EmptyCoroutineContext }
): CoroutineScope {
val composer = currentComposer
val wrapper = remember {
CompositionScopedCoroutineScopeCanceller(
createCompositionCoroutineScope(getContext(), composer)
)
}
return wrapper.coroutineScope
}
| apache-2.0 | 1164d3d5b2498d66f6544d1e5a0f185a | 40.511387 | 100 | 0.745337 | 4.701055 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/message/MessengerViewModel.kt | 1 | 5131 | package me.proxer.app.chat.prv.message
import androidx.lifecycle.MediatorLiveData
import com.gojuno.koptional.rxjava2.filterSome
import com.gojuno.koptional.toOptional
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.schedulers.Schedulers
import me.proxer.app.base.PagedViewModel
import me.proxer.app.chat.prv.LocalConference
import me.proxer.app.chat.prv.LocalMessage
import me.proxer.app.chat.prv.sync.MessengerDao
import me.proxer.app.chat.prv.sync.MessengerErrorEvent
import me.proxer.app.chat.prv.sync.MessengerWorker
import me.proxer.app.exception.ChatMessageException
import me.proxer.app.util.ErrorUtils
import me.proxer.app.util.data.ResettingMutableLiveData
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.subscribeAndLogErrors
/**
* @author Ruben Gees
*/
class MessengerViewModel(initialConference: LocalConference) : PagedViewModel<LocalMessage>() {
override val isLoginRequired = true
override val itemsOnPage = MessengerWorker.MESSAGES_ON_PAGE
@Suppress("UNUSED_PARAMETER")
override var hasReachedEnd
get() = safeConference.isFullyLoaded
set(value) = Unit
override val data = MediatorLiveData<List<LocalMessage>>()
val conference = MediatorLiveData<LocalConference>()
val draft = ResettingMutableLiveData<String?>()
override val dataSingle: Single<List<LocalMessage>>
get() = Single.fromCallable { validators.validateLogin() }
.flatMap {
when (page) {
0 -> messengerDao.markConferenceAsRead(safeConference.id)
else -> if (!hasReachedEnd) MessengerWorker.enqueueMessageLoad(safeConference.id)
}
Single.never()
}
private val dataSource: (List<LocalMessage>?) -> Unit = {
if (it != null && storageHelper.isLoggedIn) {
if (it.isEmpty()) {
if (!hasReachedEnd) {
MessengerWorker.enqueueMessageLoad(safeConference.id)
}
} else {
if (error.value == null) {
dataDisposable?.dispose()
page = it.size / itemsOnPage
isLoading.value = false
error.value = null
data.value = it
Completable.fromAction { messengerDao.markConferenceAsRead(safeConference.id) }
.subscribeOn(Schedulers.io())
.subscribeAndLogErrors()
}
}
}
}
private val conferenceSource: (LocalConference?) -> Unit = {
if (it != null) conference.value = it
}
private val messengerDao by safeInject<MessengerDao>()
private val safeConference: LocalConference
get() = requireNotNull(conference.value)
private var draftDisposable: Disposable? = null
init {
conference.value = initialConference
data.addSource(messengerDao.getMessagesLiveDataForConference(initialConference.id), dataSource)
conference.addSource(messengerDao.getConferenceLiveData(initialConference.id), conferenceSource)
disposables += bus.register(MessengerErrorEvent::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { event: MessengerErrorEvent ->
if (event.error is ChatMessageException) {
dataDisposable?.dispose()
isLoading.value = false
error.value = ErrorUtils.handle(event.error)
}
}
}
override fun onCleared() {
draftDisposable?.dispose()
draftDisposable = null
super.onCleared()
}
fun loadDraft() {
draftDisposable?.dispose()
draftDisposable = Single
.fromCallable { storageHelper.getMessageDraft(safeConference.id.toString()).toOptional() }
.filterSome()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { draft.value = it }
}
fun updateDraft(draft: String) {
draftDisposable?.dispose()
draftDisposable = Single
.fromCallable {
if (draft.isBlank()) {
storageHelper.deleteMessageDraft(safeConference.id.toString())
} else {
storageHelper.putMessageDraft(safeConference.id.toString(), draft)
}
}
.subscribeOn(Schedulers.io())
.subscribe()
}
fun sendMessage(text: String) {
val safeUser = requireNotNull(storageHelper.user)
disposables += Single
.fromCallable { messengerDao.insertMessageToSend(safeUser, text, safeConference.id) }
.doOnSuccess { if (!MessengerWorker.isRunning) MessengerWorker.enqueueSynchronization() }
.subscribeOn(Schedulers.io())
.subscribeAndLogErrors()
}
}
| gpl-3.0 | 92bbbced0435231a2588bf8da7bb472e | 34.386207 | 104 | 0.638667 | 5.141283 | false | false | false | false |
nitrico/LastAdapter | app/src/main/java/com/github/nitrico/lastadapter_sample/ui/MainActivity.kt | 1 | 2278 | package com.github.nitrico.lastadapter_sample.ui
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.view.Menu
import android.view.MenuItem
import com.github.nitrico.lastadapter_sample.data.Data
import com.github.nitrico.lastadapter_sample.R
import com.github.nitrico.lastadapter_sample.data.Header
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
private val random = Random()
private var randomPosition: Int = 0
get() = random.nextInt(Data.items.size-1)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
pager.adapter = ViewPagerAdapter(supportFragmentManager)
tabs.setupWithViewPager(pager)
}
override fun onCreateOptionsMenu(menu: Menu) = consume { menuInflater.inflate(R.menu.main, menu) }
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.addFirst -> consume {
Data.items.add(0, Header("New Header"))
}
R.id.addLast -> consume {
Data.items.add(Data.items.size, Header("New header"))
}
R.id.addRandom -> consume {
Data.items.add(randomPosition, Header("New Header"))
}
R.id.removeFirst -> consume {
if (Data.items.isNotEmpty()) Data.items.removeAt(0)
}
R.id.removeLast -> consume {
if (Data.items.isNotEmpty()) Data.items.removeAt(Data.items.size-1)
}
R.id.removeRandom -> consume {
if (Data.items.isNotEmpty()) Data.items.removeAt(randomPosition)
}
else -> super.onOptionsItemSelected(item)
}
private fun consume(f: () -> Unit): Boolean {
f()
return true
}
class ViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getCount() = 2
override fun getItem(i: Int) = if (i == 0) KotlinListFragment() else JavaListFragment()
override fun getPageTitle(i: Int) = if (i == 0) "Kotlin" else "Java"
}
}
| apache-2.0 | 584beeaed5b3ed9b758340b1839c6a52 | 34.046154 | 102 | 0.66813 | 4.1875 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/psi/shadow/XpmShadowPsiElementFactory.kt | 1 | 3395 | /*
* Copyright (C) 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.xpm.psi.shadow
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiElement
import com.intellij.psi.xml.XmlAttribute
import com.intellij.psi.xml.XmlTag
import org.jetbrains.annotations.TestOnly
import uk.co.reecedunn.intellij.plugin.core.extensions.PluginDescriptorProvider
import uk.co.reecedunn.intellij.plugin.core.extensions.registerExtension
import uk.co.reecedunn.intellij.plugin.core.extensions.registerExtensionPointBean
import uk.co.reecedunn.intellij.plugin.core.xml.psi.qname
import javax.xml.namespace.QName
interface XpmShadowPsiElementFactory {
companion object {
val EP_NAME: ExtensionPointName<XpmShadowPsiElementFactoryBean> = ExtensionPointName.create(
"uk.co.reecedunn.intellij.shadowPsiElementFactory"
)
private val factories: Sequence<XpmShadowPsiElementFactoryBean>
get() = EP_NAME.extensionList.asSequence()
private val SHADOW_PSI_ELEMENT: Key<Pair<QName?, XpmShadowPsiElement>> = Key.create("SHADOW_PSI_ELEMENT")
fun create(element: PsiElement): XpmShadowPsiElement? {
val name = (element as? XmlTag)?.qname() ?: (element as? XmlAttribute)?.qname()
element.getUserData(SHADOW_PSI_ELEMENT)?.let {
if (it.first == name && it.second.isValid) {
return it.second
}
}
factories.map { it.getInstance().create(element, name) }.firstOrNull()?.let {
element.putUserData(SHADOW_PSI_ELEMENT, name to it)
return it
}
return factories.map { it.getInstance().createDefault(element) }.firstOrNull()?.let {
element.putUserData(SHADOW_PSI_ELEMENT, name to it)
return it
}
}
@TestOnly
@Suppress("UsePropertyAccessSyntax")
fun register(
plugin: PluginDescriptorProvider,
factory: XpmShadowPsiElementFactory,
fieldName: String = "INSTANCE"
) {
val bean = XpmShadowPsiElementFactoryBean()
bean.implementationClass = factory.javaClass.name
bean.fieldName = fieldName
bean.setPluginDescriptor(plugin.pluginDescriptor)
val app = ApplicationManager.getApplication()
app.registerExtensionPointBean(EP_NAME, XpmShadowPsiElementFactoryBean::class.java, plugin.pluginDisposable)
app.registerExtension(EP_NAME, bean, plugin.pluginDisposable)
}
}
fun create(element: PsiElement, name: QName?): XpmShadowPsiElement?
fun createDefault(element: PsiElement): XpmShadowPsiElement?
}
| apache-2.0 | 5a8367ceb208159528a69268f3c81577 | 39.903614 | 120 | 0.693962 | 4.78169 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/course_revenue/analytic/CourseBenefitClickedEvent.kt | 2 | 960 | package org.stepik.android.domain.course_revenue.analytic
import org.stepik.android.domain.base.analytic.AnalyticEvent
import org.stepik.android.domain.course_revenue.model.CourseBenefit
import java.util.Locale
class CourseBenefitClickedEvent(
benefitId: Long,
benefitStatus: CourseBenefit.Status,
courseId: Long,
courseTitle: String?
) : AnalyticEvent {
companion object {
private const val PARAM_BENEFIT = "benefit"
private const val PARAM_STATUS = "status"
private const val PARAM_COURSE = "course"
private const val PARAM_COURSE_TITLE = "course_title"
}
override val name: String =
"Course benefit clicked"
override val params: Map<String, Any> =
mapOf(
PARAM_BENEFIT to benefitId,
PARAM_STATUS to benefitStatus.name.toLowerCase(Locale.ROOT),
PARAM_COURSE to courseId,
PARAM_COURSE_TITLE to courseTitle.orEmpty()
)
} | apache-2.0 | 280adb733f62b8d8f3a95ea9abfedfd0 | 31.033333 | 72 | 0.6875 | 4.324324 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/data/download/repository/DownloadRepositoryImpl.kt | 1 | 3639 | package org.stepik.android.data.download.repository
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles
import io.reactivex.rxkotlin.toObservable
import org.stepic.droid.persistence.downloads.progress.mapper.DownloadProgressStatusMapper
import org.stepic.droid.persistence.model.DownloadItem
import org.stepic.droid.persistence.model.DownloadProgress
import org.stepic.droid.persistence.model.PersistentItem
import org.stepic.droid.persistence.model.PersistentState
import org.stepic.droid.persistence.model.Structure
import org.stepic.droid.persistence.model.SystemDownloadRecord
import org.stepic.droid.persistence.storage.dao.PersistentItemDao
import org.stepic.droid.persistence.storage.dao.SystemDownloadsDao
import ru.nobird.android.core.model.mapToLongArray
import org.stepic.droid.util.plus
import org.stepik.android.data.download.source.DownloadCacheDataSource
import org.stepik.android.domain.course.repository.CourseRepository
import org.stepik.android.domain.download.repository.DownloadRepository
import org.stepik.android.model.Course
import org.stepik.android.view.injection.download.DownloadsProgressStatusMapper
import javax.inject.Inject
class DownloadRepositoryImpl
@Inject
constructor(
private val updatesObservable: Observable<Structure>,
private val intervalUpdatesObservable: Observable<Unit>,
private val systemDownloadsDao: SystemDownloadsDao,
private val persistentItemDao: PersistentItemDao,
private val courseRepository: CourseRepository,
@DownloadsProgressStatusMapper
private val downloadProgressStatusMapper: DownloadProgressStatusMapper,
private val downloadCacheDataSource: DownloadCacheDataSource
) : DownloadRepository {
override fun getDownloads(): Observable<DownloadItem> =
Observable
.merge(
downloadCacheDataSource
.getDownloadedCoursesIds()
.flatMapObservable { it.toObservable() },
updatesObservable
.map { it.course }
)
.flatMapSingle { courseId -> persistentItemDao.getItemsByCourse(courseId).map { courseId to it } }
.flatMap { (courseId, items) -> getDownloadItem(courseId, items) }
private fun getDownloadItem(courseId: Long, items: List<PersistentItem>): Observable<DownloadItem> =
(resolveCourse(courseId, items).toObservable() +
intervalUpdatesObservable
.switchMapSingle { persistentItemDao.getItemsByCourse(courseId) }
.switchMapSingle { resolveCourse(courseId, it) }
)
.takeUntil { it.status !is DownloadProgress.Status.InProgress }
private fun resolveCourse(courseId: Long, items: List<PersistentItem>): Single<DownloadItem> =
Singles.zip(
courseRepository.getCourse(courseId).toSingle(),
getStorageRecords(items)
) { course, records ->
resolveDownloadItem(course, items, records)
}
private fun getStorageRecords(items: List<PersistentItem>): Single<List<SystemDownloadRecord>> =
Single
.fromCallable { items.filter { it.status == PersistentItem.Status.IN_PROGRESS || it.status == PersistentItem.Status.FILE_TRANSFER } }
.flatMap { systemDownloadsDao.get(*it.mapToLongArray(PersistentItem::downloadId)) }
private fun resolveDownloadItem(course: Course, items: List<PersistentItem>, records: List<SystemDownloadRecord>): DownloadItem =
DownloadItem(course, downloadProgressStatusMapper.countItemProgress(items, records, PersistentState.State.CACHED))
} | apache-2.0 | a87f163a41049d0d7e150cbb0a42cfdb | 48.863014 | 145 | 0.751305 | 5.075314 | false | false | false | false |
android/performance-samples | MacrobenchmarkSample/app/src/main/java/com/example/macrobenchmark/target/util/ClickTrace.kt | 1 | 2840 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark.target.util
import android.os.Looper
import android.view.MotionEvent
import androidx.tracing.Trace
import curtains.Curtains
import curtains.OnRootViewAddedListener
import curtains.OnTouchEventListener
import curtains.phoneWindow
import curtains.touchEventInterceptors
import curtains.windowAttachCount
/**
* Logs async trace sections that track the duration of click handling in the app, i.e. the
* duration from MotionEvent.ACTION_UP to OnClick callbacks.
*/
object ClickTrace {
private const val SECTION_NAME = "ClickTrace"
private var clickInProgress = false
private val isMainThread: Boolean get() = Looper.getMainLooper().thread === Thread.currentThread()
/**
* Ends a trace started when a ACTION_UP motion event was received.
*/
fun onClickPerformed() {
Trace.endAsyncSection(SECTION_NAME, 0)
checkMainThread()
clickInProgress = false
}
/**
* Leverages the [Curtains] library to intercept all ACTION_UP motion events sent to all
* windows in the app, starting an async trace that will end when [onClickPerformed] is called.
*/
fun install() {
checkMainThread()
// Listen to every new attached root view.
Curtains.onRootViewsChangedListeners += OnRootViewAddedListener { rootView ->
// If a root is attached, detached and reattached we don't want to do this again.
if (rootView.windowAttachCount == 0) {
// Not all root views have a window associated to them.
rootView.phoneWindow?.let { window ->
// Adds a touch event interceptor to the window callback
window.touchEventInterceptors += OnTouchEventListener { event ->
if (event.action == MotionEvent.ACTION_UP) {
Trace.beginAsyncSection(SECTION_NAME, 0)
clickInProgress = true
}
}
}
}
}
}
private fun checkMainThread() {
check(isMainThread) {
"Should be called from the main thread, not ${Thread.currentThread()}"
}
}
} | apache-2.0 | d4f1d77f467925847c084ef36f5e2671 | 34.962025 | 102 | 0.660563 | 4.913495 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt | 1 | 877 | package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
@Database(
entities = [HistoryRecordEntity::class],
exportSchema = false,
version = DashHistoryDatabase.VERSION
)
@TypeConverters(Converters::class)
abstract class DashHistoryDatabase : RoomDatabase() {
abstract fun historyRecordDao(): HistoryRecordDao
companion object {
const val VERSION = 3
fun build(context: Context) =
Room.databaseBuilder(
context.applicationContext,
DashHistoryDatabase::class.java,
"omnipod_dash_history_database.db",
)
.fallbackToDestructiveMigration()
.build()
}
}
| agpl-3.0 | 866ac115d1ea252f05d246c1a128658e | 26.40625 | 77 | 0.68301 | 5.04023 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/permissions/requesters/SimpleRequester.kt | 2 | 1981 | package abi42_0_0.expo.modules.permissions.requesters
import android.os.Bundle
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.CAN_ASK_AGAIN_KEY
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.EXPIRES_KEY
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.GRANTED_KEY
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.PERMISSION_EXPIRES_NEVER
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.STATUS_KEY
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsStatus
/**
* Used for representing CAMERA, CONTACTS, AUDIO_RECORDING, SMS
*/
class SimpleRequester(vararg val permission: String) : PermissionRequester {
override fun getAndroidPermissions(): List<String> = permission.toList()
override fun parseAndroidPermissions(permissionsResponse: Map<String, PermissionsResponse>): Bundle {
return Bundle().apply {
// combined status is equal:
// granted when all needed permissions have been granted
// denied when all needed permissions have been denied
// undetermined if exist permission with undetermined status
val permissionsStatus = when {
getAndroidPermissions().all { permissionsResponse.getValue(it).status == PermissionsStatus.GRANTED } -> PermissionsStatus.GRANTED
getAndroidPermissions().all { permissionsResponse.getValue(it).status == PermissionsStatus.DENIED } -> PermissionsStatus.DENIED
else -> PermissionsStatus.UNDETERMINED
}
putString(STATUS_KEY, permissionsStatus.status)
putString(EXPIRES_KEY, PERMISSION_EXPIRES_NEVER)
putBoolean(CAN_ASK_AGAIN_KEY, getAndroidPermissions().all { permissionsResponse.getValue(it).canAskAgain })
putBoolean(GRANTED_KEY, permissionsStatus == PermissionsStatus.GRANTED)
}
}
}
| bsd-3-clause | d9b79a4a23c993d3e0728f5761c52ff6 | 54.027778 | 137 | 0.787986 | 4.79661 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt | 1 | 4362 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.content.Context
import android.graphics.Typeface
import android.text.format.DateFormat
import android.view.ContextThemeWrapper
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.timepicker.MaterialTimePicker
import com.google.android.material.timepicker.TimeFormat
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.interfaces.ResourceHelper
import java.util.*
class InputDateTime(private val rh: ResourceHelper, private val dateUtil: DateUtil, var value: Long = dateUtil.now()) : Element() {
override fun addToLayout(root: LinearLayout) {
val px = rh.dpToPx(10)
root.addView(
LinearLayout(root.context).apply {
orientation = LinearLayout.HORIZONTAL
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
addView(
TextView(root.context).apply {
text = rh.gs(R.string.atspecifiedtime, "")
setTypeface(typeface, Typeface.BOLD)
setPadding(px, px, px, px)
})
addView(
TextView(root.context).apply {
text = dateUtil.dateString(value)
setPadding(px, px, px, px)
setOnClickListener {
getFragmentManager(root.context)?.let { fm ->
MaterialDatePicker.Builder.datePicker()
.setTheme(R.style.DatePicker)
.setSelection(dateUtil.timeStampToUtcDateMillis(value))
.build()
.apply {
addOnPositiveButtonClickListener { selection ->
value = dateUtil.mergeUtcDateToTimestamp(value, selection)
text = dateUtil.dateString(value)
}
}
.show(fm, "input_date_picker")
}
}
})
addView(
TextView(root.context).apply {
text = dateUtil.timeString(value)
setPadding(px, px, px, px)
setOnClickListener {
getFragmentManager(root.context)?.let { fm ->
val cal = Calendar.getInstance().apply { timeInMillis = value }
val clockFormat = if (DateFormat.is24HourFormat(context)) TimeFormat.CLOCK_24H else TimeFormat.CLOCK_12H
val timePicker = MaterialTimePicker.Builder()
.setTheme(R.style.TimePicker)
.setTimeFormat(clockFormat)
.setHour(cal.get(Calendar.HOUR_OF_DAY))
.setMinute(cal.get(Calendar.MINUTE))
.build()
timePicker.addOnPositiveButtonClickListener {
value = dateUtil.mergeHourMinuteToTimestamp(value, timePicker.hour, timePicker.minute)
text = dateUtil.timeString(value)
}
timePicker.show(fm, "input_time_picker")
}
}
}
)
})
}
private fun getFragmentManager(context: Context?): FragmentManager? {
return when (context) {
is AppCompatActivity -> context.supportFragmentManager
is ContextThemeWrapper -> getFragmentManager(context.baseContext)
else -> null
}
}
}
| agpl-3.0 | 3ba9fdb983e8415bff469eaec0b02da0 | 48.568182 | 136 | 0.519486 | 6.196023 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/showcase/queries/ProductDatabase.kt | 1 | 824 | package arcs.showcase.queries
import arcs.jvm.host.TargetHost
typealias Product = AbstractProductDatabase.Product
/**
* This particle generates dummy data that is used in testing queries.
* @see ProductClassifier
*/
@TargetHost(arcs.android.integration.IntegrationHost::class)
class ProductDatabase : AbstractProductDatabase() {
override fun onFirstStart() {
handles.products.storeAll(
listOf(
Product(name = "Pencil", price = 2.5),
Product(name = "Ice cream", price = 3.0),
Product(name = "Chocolate", price = 3.0),
Product(name = "Blueberries", price = 4.0),
Product(name = "Sandwich", price = 4.50),
Product(name = "Scarf", price = 20.0),
Product(name = "Hat", price = 25.0),
Product(name = "Stop sign", price = 100.0)
)
)
}
}
| bsd-3-clause | d9cb2e9ea5cd57dd41f2fa49e72e67b3 | 29.518519 | 70 | 0.64199 | 3.695067 | false | false | false | false |
laminr/aeroknow | app/src/main/java/biz/eventually/atpl/di/module/DatabaseModule.kt | 1 | 2136 | package biz.eventually.atpl.di.module
import android.arch.persistence.room.Room
import android.content.Context
import android.os.Debug
import biz.eventually.atpl.data.DataProvider
import biz.eventually.atpl.data.dao.*
import biz.eventually.atpl.ui.questions.QuestionRepository
import biz.eventually.atpl.ui.source.SourceRepository
import biz.eventually.atpl.ui.subject.SubjectRepository
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* Created by Thibault de Lambilly on 17/10/17.
*/
@Module
class DatabaseModule {
@Singleton
@Provides
fun provideDatabase(context: Context) : AppDatabase {
val builder = Room.databaseBuilder(context, AppDatabase::class.java, "aeroknow.db").fallbackToDestructiveMigration()
// if (Debug.isDebuggerConnected()) {
// builder.allowMainThreadQueries()
// }
return builder.build()
}
/**
* Dao
*/
@Singleton
@Provides
fun provideSourceDao(db: AppDatabase) : SourceDao = db.sourceDao()
@Singleton
@Provides
fun provideSubjectDao(db: AppDatabase) : SubjectDao = db.subjectDao()
@Singleton
@Provides
fun provideTopicDao(db: AppDatabase) : TopicDao = db.topicDao()
@Singleton
@Provides
fun provideQuestionDao(db: AppDatabase) : QuestionDao = db.questionDao()
@Singleton
@Provides
fun provideLastCallDao(db: AppDatabase) : LastCallDao = db.lastCallDao()
/**
* Repositories
*/
@Singleton
@Provides
fun provideSourceRepository(dataProvider: DataProvider, dao: SourceDao, lastDao: LastCallDao): SourceRepository =
SourceRepository(dataProvider, dao, lastDao)
@Singleton
@Provides
fun provideSubjectRepository(dataProvider: DataProvider, dao: SubjectDao,tDao: TopicDao, lastDao: LastCallDao): SubjectRepository =
SubjectRepository(dataProvider, dao, tDao, lastDao)
@Singleton
@Provides
fun provideQuestionRepository(dataProvider: DataProvider, dao: QuestionDao, lastDao: LastCallDao): QuestionRepository =
QuestionRepository(dataProvider, dao, lastDao)
} | mit | 831d05a1fa8049e545de66e9c0a8b849 | 28.273973 | 135 | 0.720037 | 4.496842 | false | false | false | false |
Maccimo/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/highlighter/GroovyColorSettingsPage.kt | 3 | 9104 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.highlighter
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import icons.JetgroovyIcons
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.highlighter.GroovySyntaxHighlighter.*
import javax.swing.Icon
class GroovyColorSettingsPage : ColorSettingsPage {
private companion object {
val attributes = mapOf(
"Annotations//Annotation attribute name" to ANNOTATION_ATTRIBUTE_NAME,
"Annotations//Annotation name" to ANNOTATION,
"Braces and Operators//Braces" to BRACES,
"Braces and Operators//Closure expression braces and arrow" to CLOSURE_ARROW_AND_BRACES,
"Braces and Operators//Lambda expression braces and arrow " to LAMBDA_ARROW_AND_BRACES,
"Braces and Operators//Brackets" to BRACKETS,
"Braces and Operators//Parentheses" to PARENTHESES,
"Braces and Operators//Operator sign" to OPERATION_SIGN,
"Comments//Line comment" to LINE_COMMENT,
"Comments//Block comment" to BLOCK_COMMENT,
"Comments//Groovydoc//Text" to DOC_COMMENT_CONTENT,
"Comments//Groovydoc//Tag" to DOC_COMMENT_TAG,
"Classes and Interfaces//Class" to CLASS_REFERENCE,
"Classes and Interfaces//Abstract class" to ABSTRACT_CLASS_NAME,
"Classes and Interfaces//Anonymous class" to ANONYMOUS_CLASS_NAME,
"Classes and Interfaces//Interface" to INTERFACE_NAME,
"Classes and Interfaces//Trait" to TRAIT_NAME,
"Classes and Interfaces//Enum" to ENUM_NAME,
"Classes and Interfaces//Type parameter" to TYPE_PARAMETER,
"Methods//Method declaration" to METHOD_DECLARATION,
"Methods//Constructor declaration" to CONSTRUCTOR_DECLARATION,
"Methods//Instance method call" to METHOD_CALL,
"Methods//Static method call" to STATIC_METHOD_ACCESS,
"Methods//Constructor call" to CONSTRUCTOR_CALL,
"Fields//Instance field" to INSTANCE_FIELD,
"Fields//Static field" to STATIC_FIELD,
"Variables and Parameters//Local variable" to LOCAL_VARIABLE,
"Variables and Parameters//Reassigned local variable" to REASSIGNED_LOCAL_VARIABLE,
"Variables and Parameters//Parameter" to PARAMETER,
"Variables and Parameters//Reassigned parameter" to REASSIGNED_PARAMETER,
"References//Instance property reference" to INSTANCE_PROPERTY_REFERENCE,
"References//Static property reference" to STATIC_PROPERTY_REFERENCE,
"References//Unresolved reference" to UNRESOLVED_ACCESS,
"Strings//String" to STRING,
"Strings//GString" to GSTRING,
"Strings//Valid string escape" to VALID_STRING_ESCAPE,
"Strings//Invalid string escape" to INVALID_STRING_ESCAPE,
"Keyword" to KEYWORD,
"Number" to NUMBER,
"Bad character" to BAD_CHARACTER,
"List/map to object conversion" to LITERAL_CONVERSION,
"Map key/Named argument" to MAP_KEY,
"Label" to LABEL
).map { AttributesDescriptor(it.key, it.value) }.toTypedArray()
val additionalTags = mapOf(
"annotation" to ANNOTATION,
"annotationAttribute" to ANNOTATION_ATTRIBUTE_NAME,
"groovydoc" to DOC_COMMENT_CONTENT,
"groovydocTag" to DOC_COMMENT_TAG,
"class" to CLASS_REFERENCE,
"abstractClass" to ABSTRACT_CLASS_NAME,
"anonymousClass" to ANONYMOUS_CLASS_NAME,
"interface" to INTERFACE_NAME,
"trait" to TRAIT_NAME,
"enum" to ENUM_NAME,
"typeParameter" to TYPE_PARAMETER,
"method" to METHOD_DECLARATION,
"constructor" to CONSTRUCTOR_DECLARATION,
"instanceMethodCall" to METHOD_CALL,
"staticMethodCall" to STATIC_METHOD_ACCESS,
"constructorCall" to CONSTRUCTOR_CALL,
"instanceField" to INSTANCE_FIELD,
"staticField" to STATIC_FIELD,
"localVariable" to LOCAL_VARIABLE,
"reassignedVariable" to REASSIGNED_LOCAL_VARIABLE,
"parameter" to PARAMETER,
"reassignedParameter" to REASSIGNED_PARAMETER,
"instanceProperty" to INSTANCE_PROPERTY_REFERENCE,
"staticProperty" to STATIC_PROPERTY_REFERENCE,
"unresolved" to UNRESOLVED_ACCESS,
"keyword" to KEYWORD,
"literalConstructor" to LITERAL_CONVERSION,
"mapKey" to MAP_KEY,
"label" to LABEL,
"validEscape" to VALID_STRING_ESCAPE,
"invalidEscape" to INVALID_STRING_ESCAPE,
"closureBraces" to CLOSURE_ARROW_AND_BRACES,
"lambdaBraces" to LAMBDA_ARROW_AND_BRACES
)
}
override fun getDisplayName(): String = GroovyBundle.message("language.groovy")
override fun getIcon(): Icon = JetgroovyIcons.Groovy.Groovy_16x16
override fun getAttributeDescriptors(): Array<AttributesDescriptor> = attributes
override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter(): GroovySyntaxHighlighter = GroovySyntaxHighlighter()
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey> = additionalTags
@NonNls
override fun getDemoText(): String = """<keyword>package</keyword> highlighting
###
<groovydoc>/**
* This is Groovydoc comment
* <groovydocTag>@see</groovydocTag> java.lang.String#equals
*/</groovydoc>
<annotation>@Annotation</annotation>(<annotationAttribute>parameter</annotationAttribute> = 'value')
<keyword>class</keyword> <class>C</class> {
<keyword>def</keyword> <instanceField>property</instanceField> = <keyword>new</keyword> <anonymousClass>I</anonymousClass>() {}
<keyword>static</keyword> <keyword>def</keyword> <staticField>staticProperty</staticField> = []
<constructor>C</constructor>() {}
<keyword>def</keyword> <<typeParameter>T</typeParameter>> <typeParameter>T</typeParameter> <method>instanceMethod</method>(T <parameter>parameter</parameter>, <reassignedParameter>reassignedParameter</reassignedParameter>) {
<reassignedParameter>reassignedParameter</reassignedParameter> = 1
//This is a line comment
<keyword>return</keyword> <parameter>parameter</parameter>
}
<keyword>def</keyword> <method>getStuff</method>() { 42 }
<keyword>static</keyword> <keyword>boolean</keyword> <method>isStaticStuff</method>() { true }
<keyword>static</keyword> <keyword>def</keyword> <method>staticMethod</method>(<keyword>int</keyword> <parameter>i</parameter>) {
/* This is a block comment */
<interface>Map</interface> <localVariable>map</localVariable> = [<mapKey>key1</mapKey>: 1, <mapKey>key2</mapKey>: 2, (22): 33]
<keyword>def</keyword> <localVariable>cl</localVariable> = <closureBraces>{</closureBraces> <parameter>a</parameter> <closureBraces>-></closureBraces> <parameter>a</parameter> <closureBraces>}</closureBraces>
<keyword>def</keyword> <localVariable>lambda</localVariable> = <parameter>b</parameter> <lambdaBraces>-></lambdaBraces> <lambdaBraces>{</lambdaBraces> <parameter>b</parameter> <lambdaBraces>}</lambdaBraces>
<class>File</class> <localVariable>f</localVariable> = <literalConstructor>[</literalConstructor>'path'<literalConstructor>]</literalConstructor>
<keyword>def</keyword> <reassignedVariable>a</reassignedVariable> = 'JetBrains'.<instanceMethodCall>matches</instanceMethodCall>(/Jw+Bw+/)
<label>label</label>:
<keyword>for</keyword> (<localVariable>entry</localVariable> <keyword>in</keyword> <localVariable>map</localVariable>) {
<keyword>if</keyword> (<localVariable>entry</localVariable>.value > 1 && <parameter>i</parameter> < 2) {
<reassignedVariable>a</reassignedVariable> = <unresolved>unresolvedReference</unresolved>
<keyword>continue</keyword> label
} <keyword>else</keyword> {
<reassignedVariable>a</reassignedVariable> = <localVariable>entry</localVariable>
}
}
<instanceMethodCall>print</instanceMethodCall> <localVariable>map</localVariable>.<mapKey>key1</mapKey>
}
}
<keyword>def</keyword> <localVariable>c</localVariable> = <keyword>new</keyword> <constructorCall>C</constructorCall>()
<localVariable>c</localVariable>.<instanceMethodCall>instanceMethod</instanceMethodCall>("Hello<validEscape>\n</validEscape>", 'world<invalidEscape>\x</invalidEscape>')
<instanceMethodCall>println</instanceMethodCall> <localVariable>c</localVariable>.<instanceProperty>stuff</instanceProperty>
<class>C</class>.<staticMethodCall>staticMethod</staticMethodCall>(<mapKey>namedArg</mapKey>: 1)
<class>C</class>.<staticProperty>staticStuff</staticProperty>
<keyword>abstract</keyword> <keyword>class</keyword> <abstractClass>AbstractClass</abstractClass> {}
<keyword>interface</keyword> <interface>I</interface> {}
<keyword>trait</keyword> <trait>T</trait> {}
<keyword>enum</keyword> <enum>E</enum> {}
@<keyword>interface</keyword> <annotation>Annotation</annotation> {
<class>String</class> <method>parameter</method>()
}
"""
}
| apache-2.0 | 32feddbcaf47b391ab30e17f31a99834 | 45.927835 | 226 | 0.733084 | 4.34766 | false | false | false | false |
JohnnyShieh/Gank | app/src/main/kotlin/com/johnny/gank/main/MainActivity.kt | 1 | 5921 | package com.johnny.gank.main
/*
* Copyright (C) 2016 Johnny Shieh 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.
*/
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import com.alibaba.sdk.android.feedback.impl.FeedbackAPI
import com.google.android.material.navigation.NavigationView
import com.johnny.gank.R
import com.johnny.gank.about.AboutActivity
import com.johnny.gank.search.SearchActivity
import com.umeng.analytics.MobclickAgent
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.app_bar_main.*
import org.jetbrains.anko.startActivity
/**
* @author Johnny Shieh
* @version 1.0
*/
class MainActivity : AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener
{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
replaceFragment(R.id.fragment_container, TodayGankFragment(), TodayGankFragment.TAG)
}
override fun onResume() {
super.onResume()
MobclickAgent.onResume(this)
}
override fun onPause() {
super.onPause()
MobclickAgent.onPause(this)
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_search) {
startActivity(SearchActivity.newIntent(this))
return true
}
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when(item.itemId) {
R.id.nav_today -> {
if(null == supportFragmentManager.findFragmentByTag(TodayGankFragment.TAG)) {
replaceFragment(R.id.fragment_container, TodayGankFragment(), TodayGankFragment.TAG)
setTitle(R.string.app_name)
}
}
R.id.nav_welfare -> {
if(null == supportFragmentManager.findFragmentByTag(WelfareFragment.TAG)) {
replaceFragment(R.id.fragment_container, WelfareFragment(), WelfareFragment.TAG)
setTitle(R.string.nav_welfare)
}
}
R.id.nav_android -> {
if(null == supportFragmentManager.findFragmentByTag(AndroidFragment.TAG)) {
replaceFragment(R.id.fragment_container, AndroidFragment(), AndroidFragment.TAG)
setTitle(R.string.nav_android)
}
}
R.id.nav_ios -> {
if(null == supportFragmentManager.findFragmentByTag(IOSFragment.TAG)) {
replaceFragment(R.id.fragment_container, IOSFragment(), IOSFragment.TAG)
setTitle(R.string.nav_ios)
}
}
R.id.nav_front_end -> {
if(null == supportFragmentManager.findFragmentByTag(FrontEndFragment.TAG)) {
replaceFragment(R.id.fragment_container, FrontEndFragment(), FrontEndFragment.TAG)
setTitle(R.string.nav_front_end)
}
}
R.id.nav_video -> {
if(null == supportFragmentManager.findFragmentByTag(VideoFragment.TAG)) {
replaceFragment(R.id.fragment_container, VideoFragment(), VideoFragment.TAG)
setTitle(R.string.nav_video)
}
}
R.id.nav_about -> {
startActivity<AboutActivity>()
}
R.id.nav_feedback -> {
startFeedbackActivity()
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
private fun replaceFragment(containerViewId: Int, fragment: Fragment, tag: String) {
if (null == supportFragmentManager.findFragmentByTag(tag)) {
supportFragmentManager.beginTransaction()
.replace(containerViewId, fragment, tag)
.commit()
}
}
private fun startFeedbackActivity() {
val uiCustomInfoMap = mutableMapOf<String, String>()
uiCustomInfoMap.plus("enableAudio" to "0")
uiCustomInfoMap.plus("themeColor" to "#00acc1")
uiCustomInfoMap.plus("hideLoginSuccess" to "true")
uiCustomInfoMap.plus("pageTitle" to getString(R.string.nav_feedback))
FeedbackAPI.setUICustomInfo(uiCustomInfoMap)
FeedbackAPI.setCustomContact("Contact", true)
FeedbackAPI.openFeedbackActivity(this)
}
}
| apache-2.0 | b70e8d1ab4f769f2c1b1e8ba08151c7c | 36.955128 | 104 | 0.642459 | 4.790453 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day05.kt | 1 | 1369 | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.head
import java.util.*
class Day05 : Day(title = "Alchemical Reduction") {
override fun first(input: Sequence<String>): Any =
input.head
.run { collapsed(initialStackSize = length) }
.size
override fun second(input: Sequence<String>): Any = input.head
.collapsed()
.joinToString("")
.let { newPolymer ->
('a'..'z')
.asSequence()
.filter { it in newPolymer || it.toUpperCase() in newPolymer }
.map { c -> newPolymer.collapsed(c, newPolymer.length).size }
.min() ?: throw IllegalStateException()
}
private fun Char.oppositeOf(other: Char?): Boolean =
other?.minus(this) == 32 || other?.minus(this) == -32
private fun String.collapsed(lowerCaseBadChar: Char? = null, initialStackSize: Int = 10000) =
this.fold(ArrayDeque<Char>(initialStackSize)) { stack, current ->
when {
lowerCaseBadChar != null && current.toLowerCase() == lowerCaseBadChar -> Unit
current.oppositeOf(stack.peek()) -> stack.removeFirst()
else -> stack.addFirst(current)
}
stack
}
}
| mit | 46a2485beb6f4be2b1fbe17edd75fb11 | 36 | 97 | 0.591673 | 4.473856 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/listener/AppCodeTemplates.kt | 1 | 4567 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.listener
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionResult
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.Key
import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.motion.select.SelectToggleVisualMode
import com.maddyhome.idea.vim.group.visual.VimVisualTimer
import com.maddyhome.idea.vim.helper.fileSize
import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.newapi.vim
/**
* A collection of hacks to improve the interaction with fancy AppCode templates
*/
object AppCodeTemplates {
private val facedAppCodeTemplate = Key.create<IntRange>("FacedAppCodeTemplate")
private const val TEMPLATE_START = "<#T##"
private const val TEMPLATE_END = "#>"
class ActionListener : AnActionListener {
private var editor: Editor? = null
override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) {
if (!VimPlugin.isEnabled()) return
val hostEditor = event.dataContext.getData(CommonDataKeys.HOST_EDITOR)
if (hostEditor != null) {
editor = hostEditor
}
}
override fun afterActionPerformed(action: AnAction, event: AnActionEvent, result: AnActionResult) {
if (!VimPlugin.isEnabled()) return
if (ActionManager.getInstance().getId(action) == IdeActions.ACTION_CHOOSE_LOOKUP_ITEM) {
val myEditor = editor
if (myEditor != null) {
VimVisualTimer.doNow()
if (myEditor.inVisualMode) {
SelectToggleVisualMode.toggleMode(myEditor.vim)
KeyHandler.getInstance().partialReset(myEditor.vim)
}
}
}
}
}
@JvmStatic
fun onMovement(
editor: Editor,
caret: Caret,
toRight: Boolean,
) {
val offset = caret.offset
val offsetRightEnd = offset + TEMPLATE_START.length
val offsetLeftEnd = offset - 1
val templateRange = caret.getUserData(facedAppCodeTemplate)
if (templateRange == null) {
if (offsetRightEnd < editor.fileSize &&
editor.document.charsSequence.subSequence(offset, offsetRightEnd).toString() == TEMPLATE_START
) {
caret.shake()
val templateEnd = editor.findTemplateEnd(offset) ?: return
caret.putUserData(facedAppCodeTemplate, offset..templateEnd)
}
if (offsetLeftEnd >= 0 &&
offset + 1 <= editor.fileSize &&
editor.document.charsSequence.subSequence(offsetLeftEnd, offset + 1).toString() == TEMPLATE_END
) {
caret.shake()
val templateStart = editor.findTemplateStart(offsetLeftEnd) ?: return
caret.putUserData(facedAppCodeTemplate, templateStart..offset)
}
} else {
if (offset in templateRange) {
if (toRight) {
caret.moveToOffset(templateRange.last + 1)
} else {
caret.moveToOffset(templateRange.first)
}
}
caret.putUserData(facedAppCodeTemplate, null)
caret.shake()
}
}
fun Editor.appCodeTemplateCaptured(): Boolean {
return this.caretModel.allCarets.any { it.getUserData(facedAppCodeTemplate) != null }
}
private fun Caret.shake() {
moveCaretRelatively(1, 0, false, false)
moveCaretRelatively(-1, 0, false, false)
}
private fun Editor.findTemplateEnd(start: Int): Int? {
val charSequence = this.document.charsSequence
val length = charSequence.length
for (i in start until length - 1) {
if (charSequence[i] == TEMPLATE_END[0] && charSequence[i + 1] == TEMPLATE_END[1]) {
return i + 1
}
}
return null
}
private fun Editor.findTemplateStart(start: Int): Int? {
val charSequence = this.document.charsSequence
val templateLastIndex = TEMPLATE_START.length
for (i in start downTo templateLastIndex) {
if (charSequence.subSequence(i - templateLastIndex, i).toString() == TEMPLATE_START) {
return i - templateLastIndex
}
}
return null
}
}
| mit | d956febdda159318b5c7a741b5c6685c | 31.621429 | 103 | 0.699584 | 4.324811 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/functionalities/initializers/GlorotInitializer.kt | 1 | 2582 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.functionalities.initializers
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.activations.ReLU
import com.kotlinnlp.simplednn.core.functionalities.activations.Sigmoid
import com.kotlinnlp.simplednn.core.functionalities.randomgenerators.FixedRangeRandom
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import java.util.*
/**
* An initializer of dense arrays with the 'Glorot Initialization', as explained by Xavier Glorot.
*
* References:
* [Understanding the difficulty of training deep feedforward neural networks]
* (http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf)
*
* @param gain the gain that determines the scale of the generated values (default = 1.0)
* @param enablePseudoRandom if true use pseudo-random with a seed (default = true)
* @param seed seed used for the pseudo-random (default = 743)
*/
class GlorotInitializer(
private val gain: Double = 1.0,
private val enablePseudoRandom: Boolean = true,
private val seed: Long = 743
) : Initializer {
companion object {
/**
* Private val used to serialize the class (needed by Serializable).
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
/**
* @param activationFunction the activation function of a layer (can be null)
*
* @return the gain to apply to a [GlorotInitializer] in relation to the given [activationFunction]
*/
fun getGain(activationFunction: ActivationFunction?): Double = when (activationFunction) {
is ReLU -> 0.5
is Sigmoid -> 4.0
else -> 1.0
}
}
/**
* The random generator of seeds for the pseudo-random initialization.
*/
private val seedGenerator = Random(this.seed)
/**
* Initialize the values of the given [array].
*
* @param array a dense array
*/
override fun initialize(array: DenseNDArray) {
val randomGenerator = FixedRangeRandom(
radius = this.gain * Math.sqrt(6.0 / (array.rows + array.columns)),
enablePseudoRandom = this.enablePseudoRandom,
seed = this.seedGenerator.nextLong())
array.randomize(randomGenerator)
}
}
| mpl-2.0 | e175e5e29a458a78e3b1514636316107 | 34.369863 | 103 | 0.706429 | 4.184765 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/ui/fragments/devdb/device/posts/PostsFragment.kt | 1 | 1990 | package forpdateam.ru.forpda.ui.fragments.devdb.device.posts
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import java.util.ArrayList
import forpdateam.ru.forpda.App
import forpdateam.ru.forpda.R
import forpdateam.ru.forpda.entity.remote.devdb.Device
import forpdateam.ru.forpda.ui.fragments.devdb.brand.DevicesFragment
import forpdateam.ru.forpda.ui.fragments.devdb.device.SubDeviceFragment
/**
* Created by radiationx on 09.08.17.
*/
class PostsFragment : SubDeviceFragment() {
private var source = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.device_fragment_specs, container, false)
//view.setBackgroundColor(App.getColorFromAttr(getContext(), R.attr.background_for_lists));
val recyclerView = view.findViewById<View>(R.id.base_list) as androidx.recyclerview.widget.RecyclerView
recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(recyclerView.context)
val adapter = PostsAdapter { item -> presenter.onPostClick(item, source) }
adapter.setSource(source)
adapter.addAll(getList())
recyclerView.adapter = adapter
recyclerView.addItemDecoration(DevicesFragment.SpacingItemDecoration(App.px8, true))
return view
}
private fun getList(): List<Device.PostItem> = when (source) {
SRC_DISCUSSIONS -> device.discussions
SRC_FIRMWARES -> device.firmwares
SRC_NEWS -> device.news
else -> emptyList()
}
fun setSource(source: Int): SubDeviceFragment {
this.source = source
return this
}
companion object {
const val SRC_DISCUSSIONS = 1
const val SRC_FIRMWARES = 2
const val SRC_NEWS = 3
}
}
| gpl-3.0 | 6c744d395582b183da70ff0fdaf66cce | 33.912281 | 116 | 0.730151 | 4.344978 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.