repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
JetBrains/intellij-community
plugins/git4idea/src/git4idea/checkin/GitCommitOptions.kt
1
10005
// 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 git4idea.checkin import com.intellij.openapi.Disposable import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil.escapeXmlEntities import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.LocalChangeList import com.intellij.openapi.vcs.changes.author import com.intellij.openapi.vcs.changes.authorDate import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBLabel import com.intellij.util.ui.GridBag import com.intellij.util.ui.JBUI import com.intellij.vcs.commit.* import com.intellij.vcs.commit.CommitSessionCounterUsagesCollector.CommitOption import com.intellij.vcs.log.VcsUser import com.intellij.vcs.log.VcsUserEditor import com.intellij.vcs.log.VcsUserEditor.Companion.getAllUsers import com.intellij.vcs.log.util.VcsUserUtil import com.intellij.vcs.log.util.VcsUserUtil.isSamePerson import com.intellij.xml.util.XmlStringUtil import git4idea.GitUserRegistry import git4idea.GitUtil.getRepositoryManager import git4idea.checkin.GitCheckinEnvironment.collectActiveMovementProviders import git4idea.config.GitVcsSettings import git4idea.i18n.GitBundle import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.Point import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import java.awt.event.HierarchyEvent import java.awt.event.HierarchyListener import java.util.* import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel import javax.swing.UIManager private val COMMIT_AUTHOR_KEY = Key.create<VcsUser>("Git.Commit.Author") private val COMMIT_AUTHOR_DATE_KEY = Key.create<Date>("Git.Commit.AuthorDate") private val IS_SIGN_OFF_COMMIT_KEY = Key.create<Boolean>("Git.Commit.IsSignOff") private val IS_COMMIT_RENAMES_SEPARATELY_KEY = Key.create<Boolean>("Git.Commit.IsCommitRenamesSeparately") internal var CommitContext.commitAuthor: VcsUser? by commitProperty(COMMIT_AUTHOR_KEY, null) internal var CommitContext.commitAuthorDate: Date? by commitProperty(COMMIT_AUTHOR_DATE_KEY, null) internal var CommitContext.isSignOffCommit: Boolean by commitProperty(IS_SIGN_OFF_COMMIT_KEY) internal var CommitContext.isCommitRenamesSeparately: Boolean by commitProperty(IS_COMMIT_RENAMES_SEPARATELY_KEY) private val HierarchyEvent.isShowingChanged get() = (changeFlags and HierarchyEvent.SHOWING_CHANGED.toLong()) != 0L private val HierarchyEvent.isParentChanged get() = (changeFlags and HierarchyEvent.PARENT_CHANGED.toLong()) != 0L private val CheckinProjectPanel.commitAuthorTracker: CommitAuthorTracker? get() = commitWorkflowHandler.commitAuthorTracker class GitCommitOptionsUi( private val commitPanel: CheckinProjectPanel, private val commitContext: CommitContext, private val showAmendOption: Boolean ) : RefreshableOnComponent, CheckinChangeListSpecificComponent, AmendCommitModeListener, CommitAuthorListener, Disposable { private val project get() = commitPanel.project private val settings = GitVcsSettings.getInstance(project) private val userRegistry = GitUserRegistry.getInstance(project) val amendHandler: AmendCommitHandler get() = commitPanel.commitWorkflowHandler.amendCommitHandler private var authorDate: Date? = null private val panel = JPanel(GridBagLayout()) private val authorField = VcsUserEditor(project, getKnownCommitAuthors()) private val signOffCommit = JBCheckBox(GitBundle.message("commit.options.sign.off.commit.checkbox"), settings.shouldSignOffCommit()).apply { val user = commitPanel.roots.mapNotNull { userRegistry.getUser(it) }.firstOrNull() val signature = user?.let { escapeXmlEntities(VcsUserUtil.toExactString(it)) }.orEmpty() toolTipText = XmlStringUtil.wrapInHtml(GitBundle.message("commit.options.sign.off.commit.message.line", signature)) addActionListener { CommitSessionCollector.getInstance(project).logCommitOptionToggled(CommitOption.SIGN_OFF, isSelected) } } private val commitRenamesSeparately = JBCheckBox( GitBundle.message("commit.options.create.extra.commit.with.file.movements"), settings.isCommitRenamesSeparately ) private var authorWarning: Balloon? = null init { authorField.addFocusListener(object : FocusAdapter() { override fun focusLost(e: FocusEvent) { updateCurrentCommitAuthor() clearAuthorWarning() } }) authorField.addHierarchyListener(object : HierarchyListener { override fun hierarchyChanged(e: HierarchyEvent) { if (e.isShowingChanged && authorField.isShowing && authorField.user != null) { showAuthorWarning() authorField.removeHierarchyListener(this) } } }) if (commitPanel.isNonModalCommit) { commitPanel.commitAuthorTracker?.addCommitAuthorListener(this, this) panel.addHierarchyListener { e -> if (e.isParentChanged && panel == e.changed && panel.parent != null) beforeShow() } } buildLayout() amendHandler.addAmendCommitModeListener(this, this) } private fun buildLayout() = panel.apply { val gb = GridBag().setDefaultAnchor(GridBagConstraints.WEST).setDefaultInsets(JBUI.insets(2)) val authorLabel = JBLabel(GitBundle.message("commit.author")).apply { labelFor = authorField } add(authorLabel, gb.nextLine().next()) add(authorField, gb.next().fillCellHorizontally().weightx(1.0)) val amendOption = if (showAmendOption) ToggleAmendCommitOption(commitPanel, this@GitCommitOptionsUi) else null amendOption?.let { add(it, gb.nextLine().next().coverLine()) } add(signOffCommit, gb.nextLine().next().coverLine()) add(commitRenamesSeparately, gb.nextLine().next().coverLine()) } // called before popup size calculation => changing preferred size here will be correctly reflected by popup private fun beforeShow() = updateRenamesCheckboxState() override fun amendCommitModeToggled() = updateRenamesCheckboxState() override fun dispose() = Unit override fun getComponent(): JComponent = panel override fun restoreState() { updateRenamesCheckboxState() clearAuthorWarning() commitAuthorChanged() commitAuthorDateChanged() } override fun saveState() { if (commitPanel.isNonModalCommit) updateRenamesCheckboxState() val author = getAuthor() commitContext.commitAuthor = author commitContext.commitAuthorDate = authorDate commitContext.isSignOffCommit = signOffCommit.isSelected commitContext.isCommitRenamesSeparately = commitRenamesSeparately.run { isEnabled && isSelected } author?.let { settings.saveCommitAuthor(it) } settings.setSignOffCommit(signOffCommit.isSelected) settings.isCommitRenamesSeparately = commitRenamesSeparately.isSelected } override fun onChangeListSelected(list: LocalChangeList) { updateRenamesCheckboxState() clearAuthorWarning() setAuthor(list.author) authorDate = list.authorDate panel.revalidate() panel.repaint() } fun getAuthor(): VcsUser? = authorField.user private fun setAuthor(author: VcsUser?) { val isAuthorNullOrDefault = author == null || isDefaultAuthor(author) authorField.user = author.takeUnless { isAuthorNullOrDefault } if (!isAuthorNullOrDefault) { authorField.putClientProperty("JComponent.outline", "warning") // NON-NLS if (authorField.isShowing) showAuthorWarning() } } private fun updateCurrentCommitAuthor() { commitPanel.commitAuthorTracker?.commitAuthor = getAuthor() } override fun commitAuthorChanged() { val newAuthor = commitPanel.commitAuthorTracker?.commitAuthor if (getAuthor() != newAuthor) setAuthor(newAuthor) } override fun commitAuthorDateChanged() { authorDate = commitPanel.commitAuthorTracker?.commitAuthorDate } private fun updateRenamesCheckboxState() { val providers = collectActiveMovementProviders(project) commitRenamesSeparately.apply { text = providers.singleOrNull()?.description ?: GitBundle.message("commit.options.create.extra.commit.with.file.movements") isVisible = providers.isNotEmpty() isEnabled = isVisible && !amendHandler.isAmendCommitMode } } private fun showAuthorWarning() { if (authorWarning?.isDisposed == false) return val builder = JBPopupFactory.getInstance() .createBalloonBuilder(JLabel(GitBundle.message("commit.author.diffs"))) .setBorderInsets(UIManager.getInsets("Balloon.error.textInsets")) // NON-NLS .setBorderColor(JBUI.CurrentTheme.Validator.warningBorderColor()) .setFillColor(JBUI.CurrentTheme.Validator.warningBackgroundColor()) .setHideOnClickOutside(true) .setHideOnFrameResize(false) authorWarning = builder.createBalloon() authorWarning?.show(RelativePoint(authorField, Point(authorField.width / 2, authorField.height)), Balloon.Position.below) } private fun clearAuthorWarning() { authorField.putClientProperty("JComponent.outline", null) // NON-NLS authorWarning?.hide() authorWarning = null } private fun getKnownCommitAuthors(): List<String> = (getAllUsers(project) + settings.commitAuthors).distinct().sorted() private fun isDefaultAuthor(author: VcsUser): Boolean { val repositoryManager = getRepositoryManager(project) val affectedRoots = commitPanel.roots.filter { repositoryManager.getRepositoryForRootQuick(it) != null } return affectedRoots.isNotEmpty() && affectedRoots.map { userRegistry.getUser(it) }.all { it != null && isSamePerson(author, it) } } }
apache-2.0
0d21ec0a7ec681091ee4b2fc0ce208e4
39.674797
140
0.771814
4.426991
false
false
false
false
asimarslan/hazelcast-tools
src/main/kotlin/com/hazelcast/idea/plugins/tools/GenerateDialog.kt
1
1902
package com.hazelcast.idea.plugins.tools import com.intellij.ide.util.DefaultPsiElementCellRenderer import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.LabeledComponent import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.ui.CollectionListModel import com.intellij.ui.ToolbarDecorator import com.intellij.ui.components.JBList import java.util.* import javax.swing.JComponent import javax.swing.JPanel class GenerateDialog(psiClass: PsiClass, dialogTitle: String) : DialogWrapper(psiClass.project) { private val myComponent: LabeledComponent<JPanel> private val fieldList: JBList init { title = dialogTitle val myFields = CollectionListModel(*psiClass.allFields) fieldList = JBList(myFields) fieldList.cellRenderer = DefaultPsiElementCellRenderer() val decorator = ToolbarDecorator.createDecorator(fieldList) decorator.disableAddAction() val panel = decorator.createPanel() myComponent = LabeledComponent.create(panel, dialogTitle + " (Warning: existing method(s) will be replaced):") init() } override fun createCenterPanel(): JComponent? { return myComponent } val fields: List<PsiField> get() = selectedValuesList val selectedValuesList: List<PsiField> get() { val sm = fieldList.selectionModel val dm = fieldList.model val iMin = sm.minSelectionIndex val iMax = sm.maxSelectionIndex if (iMin < 0 || iMax < 0) { return emptyList() } val selectedItems = ArrayList<PsiField>() for (i in iMin..iMax) { if (sm.isSelectedIndex(i)) { selectedItems.add(dm.getElementAt(i) as PsiField) } } return selectedItems } }
apache-2.0
e3f2d315158993fd701bac58ec0a5443
29.693548
118
0.664038
4.839695
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/model/openshift/ImageStreamImport.kt
1
888
package no.skatteetaten.aurora.boober.model.openshift import io.fabric8.openshift.api.model.ImageStreamImport import io.fabric8.openshift.api.model.NamedTagEventList fun ImageStreamImport.findErrorMessage(): String? { val errorStatuses = listOf("false", "failure") val tag = this.findImportStatusTag() return tag?.conditions ?.firstOrNull { errorStatuses.contains(it.status.lowercase()) } ?.message } fun ImageStreamImport.isDifferentImage(imageHash: String?): Boolean { val tag = this.findImportStatusTag() val image = tag?.items?.firstOrNull()?.image return image?.let { return it != imageHash } ?: true } fun ImageStreamImport.findImportStatusTag(): NamedTagEventList? { val tagName = this.spec.images.first().to.name return this.status ?.import ?.status ?.tags ?.firstOrNull { it.tag == tagName } }
apache-2.0
5544544d6e5e8b67d4e0c2a032725e2d
30.714286
71
0.703829
4.149533
false
false
false
false
allotria/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/right/PackagesChosenPlatformsView.kt
1
1562
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.right import com.intellij.util.ui.JBUI import com.jetbrains.packagesearch.intellij.plugin.asListOfTags import com.jetbrains.packagesearch.intellij.plugin.ui.RiderUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageSearchDependency import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint import java.awt.Component import javax.swing.Box import javax.swing.BoxLayout class PackagesChosenPlatformsView { private val panelHeight = 26 private val platformsPanel = RiderUI.boxPanel { layout = BoxLayout(this, BoxLayout.X_AXIS) alignmentX = Component.LEFT_ALIGNMENT alignmentY = Component.TOP_ALIGNMENT } val panel = RiderUI.borderPanel { RiderUI.setHeight(this, panelHeight, true) border = JBUI.Borders.empty(-8, 6, 0, 6) addToCenter(platformsPanel) } fun refreshUI(meta: PackageSearchDependency?) { platformsPanel.removeAll() if (meta?.remoteInfo?.mpp == null) { hide() } else { @Suppress("MagicNumber") // Gotta love Swing APIs meta.remoteInfo?.platforms?.asListOfTags()?.forEach { tag -> platformsPanel.add(RiderUI.createPlatformTag(tag)) platformsPanel.add(Box.createHorizontalStrut(6)) } } panel.updateAndRepaint() } fun show() { panel.isVisible = true } fun hide() { panel.isVisible = false } }
apache-2.0
4fc83a2b72eb134e216996de47877af7
29.627451
95
0.683099
4.424929
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultKeymap.kt
2
5949
// 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.keymap.impl import com.intellij.configurationStore.SchemeDataHolder import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtilRt import org.jdom.Element import java.util.function.BiConsumer private val LOG = logger<DefaultKeymap>() open class DefaultKeymap { internal val keymaps = ArrayList<Keymap>() private val nameToScheme = HashMap<String, Keymap>() companion object { @JvmStatic val instance: DefaultKeymap get() = service() @JvmStatic fun isBundledKeymapHidden(keymapName: String?): Boolean { return ((SystemInfoRt.isWindows || SystemInfoRt.isMac) && isKnownLinuxKeymap(keymapName)) || (!SystemInfoRt.isMac && isKnownMacOSKeymap(keymapName)) } } init { val filterKeymaps = !ApplicationManager.getApplication().isHeadlessEnvironment && System.getProperty("keymap.current.os.only", "true").toBoolean() val filteredBeans = mutableListOf<Pair<BundledKeymapBean, PluginDescriptor>>() var macosParentKeymapFound = false val macosBeans = if (SystemInfoRt.isMac) null else mutableListOf<Pair<BundledKeymapBean, PluginDescriptor>>() BundledKeymapBean.EP_NAME.processWithPluginDescriptor(BiConsumer { bean, pluginDescriptor -> val keymapName = bean.keymapName // filter out bundled keymaps for other systems, but allow them via non-bundled plugins // on non-macOS add non-bundled known macOS keymaps if the default macOS keymap is present if (filterKeymaps && pluginDescriptor.isBundled && isBundledKeymapHidden(keymapName)) { return@BiConsumer } if (filterKeymaps && macosBeans != null && !pluginDescriptor.isBundled && isKnownMacOSKeymap(keymapName)) { macosParentKeymapFound = macosParentKeymapFound || keymapName == KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP macosBeans.add(Pair(bean, pluginDescriptor)) } else { filteredBeans.add(Pair(bean, pluginDescriptor)) } }) if (macosParentKeymapFound && macosBeans != null) { filteredBeans.addAll(macosBeans) } for ((bean, pluginDescriptor) in filteredBeans) { LOG.runAndLogException { loadKeymap(bean.keymapName, object : SchemeDataHolder<KeymapImpl> { override fun read(): Element { return pluginDescriptor.pluginClassLoader.getResourceAsStream(bean.effectiveFile).use { JDOMUtil.load(it) } } }, pluginDescriptor) } } } internal fun loadKeymap(keymapName: String, dataHolder: SchemeDataHolder<KeymapImpl>, plugin: PluginDescriptor): DefaultKeymapImpl { val keymap = when { keymapName.startsWith(KeymapManager.MAC_OS_X_KEYMAP) -> MacOSDefaultKeymap(dataHolder, this, plugin) else -> DefaultKeymapImpl(dataHolder, this, plugin) } keymap.name = keymapName addKeymap(keymap) return keymap } private fun addKeymap(keymap: DefaultKeymapImpl) { keymaps.add(keymap) nameToScheme[keymap.name] = keymap } internal fun removeKeymap(keymapName: String) { val removed = nameToScheme.remove(keymapName) keymaps.remove(removed) } internal fun findScheme(name: String) = nameToScheme[name] open val defaultKeymapName: String get() = when { SystemInfoRt.isMac -> KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP SystemInfo.isGNOME -> KeymapManager.GNOME_KEYMAP SystemInfo.isKDE -> KeymapManager.KDE_KEYMAP SystemInfo.isXWindow -> KeymapManager.X_WINDOW_KEYMAP else -> KeymapManager.DEFAULT_IDEA_KEYMAP } open fun getKeymapPresentableName(keymap: KeymapImpl): String { return when (val name = keymap.name) { KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP -> "macOS" KeymapManager.DEFAULT_IDEA_KEYMAP -> "Windows" KeymapManager.GNOME_KEYMAP -> "GNOME" KeymapManager.KDE_KEYMAP -> "KDE" KeymapManager.X_WINDOW_KEYMAP -> "XWin" KeymapManager.MAC_OS_X_KEYMAP -> "IntelliJ IDEA Classic" + (if (SystemInfoRt.isMac) "" else " (macOS)") "NetBeans 6.5" -> "NetBeans" else -> { val newName = name .removeSuffix(" (Mac OS X)") .removeSuffix(" OSX") when { newName === name -> name else -> "$newName (macOS)" } .removePrefix("${osName()}/") } } } } internal val BundledKeymapBean.effectiveFile: String get() = "keymaps/${file.replace("\$OS\$", osName())}" internal val BundledKeymapBean.keymapName: String get() = FileUtilRt.getNameWithoutExtension(file).removePrefix("\$OS\$/") private fun osName(): String = when { SystemInfo.isMac -> "macos" SystemInfo.isWindows -> "windows" SystemInfo.isLinux -> "linux" else -> "other" } private fun isKnownLinuxKeymap(keymapName: String?) = when (keymapName) { KeymapManager.X_WINDOW_KEYMAP, KeymapManager.GNOME_KEYMAP, KeymapManager.KDE_KEYMAP -> true else -> false } private fun isKnownMacOSKeymap(keymapName: String?) = when (keymapName) { KeymapManager.MAC_OS_X_KEYMAP, KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP, "macOS System Shortcuts", "Eclipse (Mac OS X)", "Sublime Text (Mac OS X)", "Xcode", "ReSharper OSX", "Visual Studio OSX", "Visual Assist OSX", "Visual Studio for Mac", "VSCode OSX", "QtCreator (Mac OS X)" -> true else -> false }
apache-2.0
0bd3c4bb3d6ea06300084af93608cf98
37.141026
154
0.700454
4.383935
false
false
false
false
zdary/intellij-community
plugins/dependency-updater/src/com/intellij/buildsystem/model/unified/UnifiedDependencyRepository.kt
1
683
package com.intellij.buildsystem.model.unified import com.intellij.buildsystem.model.BuildDependencyRepository data class UnifiedDependencyRepository( val id: String?, val name: String?, val url: String? ) : BuildDependencyRepository { val displayName: String = buildString { append('[') if (!name.isNullOrBlank()) append("name='$name'") if (!id.isNullOrBlank()) { if (count() > 1) append(", ") append("id='") append(id) append("'") } if (!url.isNullOrBlank()) { if (count() > 1) append(", ") append("url='") append(url) append("'") } if (count() == 1) append("#NO_DATA#") append(']') } }
apache-2.0
7af7ba857c0d5ef5ce5f9ffd8cc081b1
21.766667
63
0.587116
3.994152
false
false
false
false
blokadaorg/blokada
android5/app/src/main/java/ui/settings/leases/LeasesFragment.kt
1
2336
/* * This file is part of Blokada. * * 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 https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package ui.settings.leases import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import model.Lease import org.blokada.R import ui.AccountViewModel import ui.TunnelViewModel import ui.app class LeasesFragment : Fragment() { private lateinit var vm: LeasesViewModel private lateinit var accountVM: AccountViewModel private lateinit var tunnelVM: TunnelViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { activity?.let { vm = ViewModelProvider(it).get(LeasesViewModel::class.java) accountVM = ViewModelProvider(it.app()).get(AccountViewModel::class.java) tunnelVM = ViewModelProvider(it.app()).get(TunnelViewModel::class.java) } val root = inflater.inflate(R.layout.fragment_leases, container, false) val recycler: RecyclerView = root.findViewById(R.id.recyclerview) recycler.layoutManager = LinearLayoutManager(context) accountVM.account.observe(viewLifecycleOwner, Observer { account -> val adapter = LeasesAdapter(interaction = object : LeasesAdapter.Interaction { override fun onDelete(lease: Lease) { vm.delete(account.id, lease) } override fun isThisDevice(lease: Lease): Boolean { return tunnelVM.isMe(lease.public_key) } }) recycler.adapter = adapter vm.leases.observe(viewLifecycleOwner, Observer { adapter.swapData(it) }) vm.fetch(account.id) }) return root } }
mpl-2.0
d20c4abaa077d91c0714fe62f36339ef
31
90
0.67152
4.623762
false
false
false
false
afollestad/photo-affix
utilities/src/main/java/com/afollestad/photoaffix/utilities/IoManager.kt
1
2363
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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.afollestad.photoaffix.utilities import android.app.Application import android.net.Uri import android.os.Environment import com.afollestad.photoaffix.utilities.ext.closeQuietely import com.afollestad.photoaffix.utilities.qualifiers.AppName import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import javax.inject.Inject /** @author Aidan Follestad (afollestad) */ interface IoManager { fun makeTempFile(extension: String): File fun openStream(uri: Uri): InputStream? fun copyUriToFile( uri: Uri, file: File ) } /** @author Aidan Follestad (afollestad) */ class RealIoManager @Inject constructor( private val app: Application, @AppName private val appName: String ) : IoManager { override fun makeTempFile(extension: String): File { val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) val parent = File(Environment.getExternalStorageDirectory(), appName) parent.mkdirs() return File(parent, "AFFIX_$timeStamp$extension") } override fun openStream(uri: Uri): InputStream? { val scheme = uri.scheme ?: "" return if (scheme.equals("file", ignoreCase = true)) { FileInputStream(uri.path!!) } else { app.contentResolver.openInputStream(uri) } } override fun copyUriToFile( uri: Uri, file: File ) { var input: InputStream? = null var output: FileOutputStream? = null try { input = openStream(uri) output = FileOutputStream(file) input!!.copyTo(output) } finally { input.closeQuietely() output.closeQuietely() } } }
apache-2.0
da264a3c716c4a2a5f84cb4d746d5a35
27.46988
91
0.723656
4.174912
false
false
false
false
hannesa2/owncloud-android
owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/security/PatternViewModelTest.kt
2
3574
/** * ownCloud Android client application * * @author Juan Carlos Garrote Gascón * * Copyright (C) 2021 ownCloud GmbH. * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.presentation.viewmodels.security import com.owncloud.android.data.preferences.datasources.SharedPreferencesProvider import com.owncloud.android.presentation.ui.security.PatternActivity import com.owncloud.android.presentation.viewmodels.ViewModelTest import io.mockk.every import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @ExperimentalCoroutinesApi class PatternViewModelTest : ViewModelTest() { private lateinit var patternViewModel: PatternViewModel private lateinit var preferencesProvider: SharedPreferencesProvider private val pattern = "1234" @Before fun setUp() { preferencesProvider = mockk(relaxUnitFun = true) patternViewModel = PatternViewModel(preferencesProvider) } @Test fun `set pattern - ok`() { patternViewModel.setPattern(pattern) verify(exactly = 1) { preferencesProvider.putString(PatternActivity.PREFERENCE_PATTERN, pattern) preferencesProvider.putBoolean(PatternActivity.PREFERENCE_SET_PATTERN, true) } } @Test fun `remove pattern - ok`() { patternViewModel.removePattern() verify(exactly = 1) { preferencesProvider.removePreference(PatternActivity.PREFERENCE_PATTERN) preferencesProvider.putBoolean(PatternActivity.PREFERENCE_SET_PATTERN, false) } } @Test fun `check pattern is valid - ok`() { every { preferencesProvider.getString(any(), any()) } returns pattern val patternValue = "1234" val patternCheckResult = patternViewModel.checkPatternIsValid(patternValue) assertTrue(patternCheckResult) verify(exactly = 1) { preferencesProvider.getString(PatternActivity.PREFERENCE_PATTERN, null) } } @Test fun `check pattern is valid - ko - saved pattern is null`() { every { preferencesProvider.getString(any(), any()) } returns null val patternValue = "1234" val patternCheckResult = patternViewModel.checkPatternIsValid(patternValue) assertFalse(patternCheckResult) verify(exactly = 1) { preferencesProvider.getString(PatternActivity.PREFERENCE_PATTERN, null) } } @Test fun `check pattern is valid - ko - different pattern`() { every { preferencesProvider.getString(any(), any()) } returns pattern val patternValue = "1235" val patternCheckResult = patternViewModel.checkPatternIsValid(patternValue) assertFalse(patternCheckResult) verify(exactly = 1) { preferencesProvider.getString(PatternActivity.PREFERENCE_PATTERN, null) } } }
gpl-2.0
7c236f12ba0947430f4305ff15e69e5e
30.619469
89
0.710607
4.719947
false
true
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt
1
16806
package info.nightscout.androidaps.plugins.pump.virtual import android.os.SystemClock import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreference import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.db.ExtendedBolus import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.InstanceId.instanceId import info.nightscout.androidaps.utils.TimeChangeType import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import org.json.JSONException import org.json.JSONObject import javax.inject.Inject import javax.inject.Singleton import kotlin.math.min @Singleton class VirtualPumpPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, private val rxBus: RxBusWrapper, private var fabricPrivacy: FabricPrivacy, resourceHelper: ResourceHelper, private val sp: SP, private val profileFunction: ProfileFunction, private val treatmentsPlugin: TreatmentsPlugin, commandQueue: CommandQueueProvider, private val config: Config, private val dateUtil: DateUtil ) : PumpPluginBase(PluginDescription() .mainType(PluginType.PUMP) .fragmentClass(VirtualPumpFragment::class.java.name) .pluginIcon(R.drawable.ic_virtual_pump) .pluginName(R.string.virtualpump) .shortName(R.string.virtualpump_shortname) .preferencesId(R.xml.pref_virtualpump) .description(R.string.description_pump_virtual) .setDefault(), injector, aapsLogger, resourceHelper, commandQueue ), PumpInterface { private val disposable = CompositeDisposable() var batteryPercent = 50 var reservoirInUnits = 50 var pumpType: PumpType? = null private set private var lastDataTime: Long = 0 private val pumpDescription = PumpDescription() init { pumpDescription.isBolusCapable = true pumpDescription.bolusStep = 0.1 pumpDescription.isExtendedBolusCapable = true pumpDescription.extendedBolusStep = 0.05 pumpDescription.extendedBolusDurationStep = 30.0 pumpDescription.extendedBolusMaxDuration = 8 * 60.toDouble() pumpDescription.isTempBasalCapable = true pumpDescription.tempBasalStyle = PumpDescription.PERCENT or PumpDescription.ABSOLUTE pumpDescription.maxTempPercent = 500 pumpDescription.tempPercentStep = 10 pumpDescription.tempDurationStep = 30 pumpDescription.tempDurationStep15mAllowed = true pumpDescription.tempDurationStep30mAllowed = true pumpDescription.tempMaxDuration = 24 * 60 pumpDescription.isSetBasalProfileCapable = true pumpDescription.basalStep = 0.01 pumpDescription.basalMinimumRate = 0.01 pumpDescription.isRefillingCapable = true pumpDescription.storesCarbInfo = false pumpDescription.is30minBasalRatesCapable = true } fun getFakingStatus(): Boolean { return sp.getBoolean(R.string.key_fromNSAreCommingFakedExtendedBoluses, false) } fun setFakingStatus(newStatus: Boolean) { sp.putBoolean(R.string.key_fromNSAreCommingFakedExtendedBoluses, newStatus) } override fun onStart() { super.onStart() disposable += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(Schedulers.io()) .subscribe({ event: EventPreferenceChange -> if (event.isChanged(resourceHelper, R.string.key_virtualpump_type)) refreshConfiguration() }) { fabricPrivacy.logException(it) } refreshConfiguration() } override fun onStop() { disposable.clear() super.onStop() } override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) val uploadStatus = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_virtualpump_uploadstatus)) as SwitchPreference? ?: return uploadStatus.isVisible = !config.NSCLIENT } override fun isFakingTempsByExtendedBoluses(): Boolean { return config.NSCLIENT && getFakingStatus() } override fun loadTDDs(): PumpEnactResult { //no result, could read DB in the future? return PumpEnactResult(injector) } override fun getCustomActions(): List<CustomAction>? { return null } override fun executeCustomAction(customActionType: CustomActionType) {} override fun executeCustomCommand(customCommand: CustomCommand?): PumpEnactResult? { return null } override fun isInitialized(): Boolean { return true } override fun isSuspended(): Boolean { return false } override fun isBusy(): Boolean { return false } override fun isConnected(): Boolean { return true } override fun isConnecting(): Boolean { return false } override fun isHandshakeInProgress(): Boolean { return false } override fun finishHandshaking() {} override fun connect(reason: String) { //if (!Config.NSCLIENT) NSUpload.uploadDeviceStatus() lastDataTime = System.currentTimeMillis() } override fun disconnect(reason: String) {} override fun stopConnecting() {} override fun getPumpStatus(reason: String?) { lastDataTime = System.currentTimeMillis() } override fun setNewBasalProfile(profile: Profile): PumpEnactResult { lastDataTime = System.currentTimeMillis() // Do nothing here. we are using ConfigBuilderPlugin.getPlugin().getActiveProfile().getProfile(); val result = PumpEnactResult(injector) result.success = true val notification = Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60) rxBus.send(EventNewNotification(notification)) return result } override fun isThisProfileSet(profile: Profile): Boolean { return true } override fun lastDataTime(): Long { return lastDataTime } override fun getBaseBasalRate(): Double { return profileFunction.getProfile()?.basal ?: 0.0 } override fun getReservoirLevel(): Double { return reservoirInUnits.toDouble() } override fun getBatteryLevel(): Int { return batteryPercent } override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { val result = PumpEnactResult(injector) result.success = true result.bolusDelivered = detailedBolusInfo.insulin result.carbsDelivered = detailedBolusInfo.carbs result.enacted = result.bolusDelivered > 0 || result.carbsDelivered > 0 result.comment = resourceHelper.gs(R.string.virtualpump_resultok) var delivering = 0.0 while (delivering < detailedBolusInfo.insulin) { SystemClock.sleep(200) val bolusingEvent = EventOverviewBolusProgress bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivering, delivering) bolusingEvent.percent = min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100) rxBus.send(bolusingEvent) delivering += 0.1 } SystemClock.sleep(200) val bolusingEvent = EventOverviewBolusProgress bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivered, detailedBolusInfo.insulin) bolusingEvent.percent = 100 rxBus.send(bolusingEvent) SystemClock.sleep(1000) aapsLogger.debug(LTag.PUMP, "Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result) rxBus.send(EventVirtualPumpUpdateGui()) lastDataTime = System.currentTimeMillis() treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false) return result } override fun stopBolusDelivering() {} override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult { val tempBasal = TemporaryBasal(injector) .date(System.currentTimeMillis()) .absolute(absoluteRate) .duration(durationInMinutes) .source(Source.USER) val result = PumpEnactResult(injector) result.success = true result.enacted = true result.isTempCancel = false result.absolute = absoluteRate result.duration = durationInMinutes result.comment = resourceHelper.gs(R.string.virtualpump_resultok) treatmentsPlugin.addToHistoryTempBasal(tempBasal) aapsLogger.debug(LTag.PUMP, "Setting temp basal absolute: $result") rxBus.send(EventVirtualPumpUpdateGui()) lastDataTime = System.currentTimeMillis() return result } override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult { val tempBasal = TemporaryBasal(injector) .date(System.currentTimeMillis()) .percent(percent) .duration(durationInMinutes) .source(Source.USER) val result = PumpEnactResult(injector) result.success = true result.enacted = true result.percent = percent result.isPercent = true result.isTempCancel = false result.duration = durationInMinutes result.comment = resourceHelper.gs(R.string.virtualpump_resultok) treatmentsPlugin.addToHistoryTempBasal(tempBasal) aapsLogger.debug(LTag.PUMP, "Settings temp basal percent: $result") rxBus.send(EventVirtualPumpUpdateGui()) lastDataTime = System.currentTimeMillis() return result } override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { val result = cancelExtendedBolus() if (!result.success) return result val extendedBolus = ExtendedBolus(injector) .date(System.currentTimeMillis()) .insulin(insulin) .durationInMinutes(durationInMinutes) .source(Source.USER) result.success = true result.enacted = true result.bolusDelivered = insulin result.isTempCancel = false result.duration = durationInMinutes result.comment = resourceHelper.gs(R.string.virtualpump_resultok) treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus) aapsLogger.debug(LTag.PUMP, "Setting extended bolus: $result") rxBus.send(EventVirtualPumpUpdateGui()) lastDataTime = System.currentTimeMillis() return result } override fun cancelTempBasal(force: Boolean): PumpEnactResult { val result = PumpEnactResult(injector) result.success = true result.isTempCancel = true result.comment = resourceHelper.gs(R.string.virtualpump_resultok) if (treatmentsPlugin.isTempBasalInProgress) { result.enacted = true val tempStop = TemporaryBasal(injector).date(System.currentTimeMillis()).source(Source.USER) treatmentsPlugin.addToHistoryTempBasal(tempStop) //tempBasal = null; aapsLogger.debug(LTag.PUMP, "Canceling temp basal: $result") rxBus.send(EventVirtualPumpUpdateGui()) } lastDataTime = System.currentTimeMillis() return result } override fun cancelExtendedBolus(): PumpEnactResult { val result = PumpEnactResult(injector) if (treatmentsPlugin.isInHistoryExtendedBoluslInProgress) { val exStop = ExtendedBolus(injector, System.currentTimeMillis()) exStop.source = Source.USER treatmentsPlugin.addToHistoryExtendedBolus(exStop) } result.success = true result.enacted = true result.isTempCancel = true result.comment = resourceHelper.gs(R.string.virtualpump_resultok) aapsLogger.debug(LTag.PUMP, "Canceling extended bolus: $result") rxBus.send(EventVirtualPumpUpdateGui()) lastDataTime = System.currentTimeMillis() return result } override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject { val now = System.currentTimeMillis() if (!sp.getBoolean(R.string.key_virtualpump_uploadstatus, false)) { return JSONObject() } val pump = JSONObject() val battery = JSONObject() val status = JSONObject() val extended = JSONObject() try { battery.put("percent", batteryPercent) status.put("status", "normal") extended.put("Version", version) try { extended.put("ActiveProfile", profileName) } catch (ignored: Exception) { } val tb = treatmentsPlugin.getTempBasalFromHistory(now) if (tb != null) { extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile)) extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.date)) extended.put("TempBasalRemaining", tb.plannedRemainingMinutes) } val eb = treatmentsPlugin.getExtendedBolusFromHistory(now) if (eb != null) { extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate()) extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.date)) extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes) } status.put("timestamp", DateUtil.toISOString(now)) pump.put("battery", battery) pump.put("status", status) pump.put("extended", extended) pump.put("reservoir", reservoirInUnits) pump.put("clock", DateUtil.toISOString(now)) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) } return pump } override fun manufacturer(): ManufacturerType { return pumpDescription.pumpType.manufacturer } override fun model(): PumpType { return pumpDescription.pumpType } override fun serialNumber(): String { return instanceId() } override fun getPumpDescription(): PumpDescription { return pumpDescription } override fun shortStatus(veryShort: Boolean): String { return "Virtual Pump" } override fun canHandleDST(): Boolean { return true } fun refreshConfiguration() { val pumptype = sp.getString(R.string.key_virtualpump_type, PumpType.GenericAAPS.description) val pumpTypeNew = PumpType.getByDescription(pumptype) aapsLogger.debug(LTag.PUMP, "Pump in configuration: $pumptype, PumpType object: $pumpTypeNew") if (pumpType == pumpTypeNew) return aapsLogger.debug(LTag.PUMP, "New pump configuration found ($pumpTypeNew), changing from previous ($pumpType)") pumpDescription.setPumpDescription(pumpTypeNew) pumpType = pumpTypeNew } override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType?) {} }
agpl-3.0
edacf007679e3f0b83ac2476944b2ac5
39.109785
185
0.703558
5.012228
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/models/RewardsItemTest.kt
1
2292
package com.kickstarter.models import com.kickstarter.mock.factories.ItemFactory import com.kickstarter.mock.factories.RewardsItemFactory import junit.framework.TestCase class RewardsItemTest : TestCase() { fun testEquals_whenSecondNull_returnFalse() { val rwItem = RewardsItemFactory.rewardsItem() val rwItem1 = RewardsItem.builder() .id(9L) .itemId(3L) .quantity(1) .rewardId(3) .build() assertFalse(rwItem == rwItem1) } fun testEquals_whenSecondEqual_returnTrue() { val rwItem = RewardsItemFactory.rewardsItem() val rwItem1 = rwItem assertTrue(rwItem == rwItem1) } fun testEquals_whenSecondNotEqualEqual_itemId() { val rwItem = RewardsItemFactory.rewardsItem() val rwItem1 = rwItem.toBuilder() .itemId(3) .build() assertFalse(rwItem == rwItem1) val rwItem3 = rwItem1.toBuilder() .itemId(rwItem.itemId()) .build() assertTrue(rwItem == rwItem3) } fun testEquals_whenSecondNotEqualEqual_item() { val rwItem = RewardsItemFactory.rewardsItem() val rwItem1 = rwItem.toBuilder() .item(ItemFactory.item().toBuilder().amount(3.0f).build()) .build() assertFalse(rwItem == rwItem1) val rwItem3 = rwItem1.toBuilder() .item(rwItem.item()) .build() assertTrue(rwItem == rwItem3) } fun testEquals_whenSecondNotEqualEqual_hasBackers() { val rwItem = RewardsItemFactory.rewardsItem() val rwItem1 = rwItem.toBuilder() .hasBackers(true) .build() assertFalse(rwItem == rwItem1) val rwItem3 = rwItem1.toBuilder() .hasBackers(rwItem.hasBackers()) .build() assertTrue(rwItem == rwItem3) } fun testEquals_whenSecondNotEqualEqual_rewardId() { val rwItem = RewardsItemFactory.rewardsItem() val rwItem1 = rwItem.toBuilder() .rewardId(null) .build() assertFalse(rwItem == rwItem1) val rwItem3 = rwItem1.toBuilder() .rewardId(rwItem.rewardId()) .build() assertTrue(rwItem == rwItem3) } }
apache-2.0
7b580178650c16fff9324130527a520b
25.344828
70
0.596422
4.122302
false
true
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/ShippingRuleViewHolderViewModel.kt
1
1689
package com.kickstarter.viewmodels import android.util.Pair import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.models.Project import com.kickstarter.models.ShippingRule import com.kickstarter.ui.viewholders.ShippingRuleViewHolder import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface ShippingRuleViewHolderViewModel { interface Inputs { /** Call with a shipping rule and project when data is bound to the view. */ fun configureWith(shippingRule: ShippingRule, project: Project) } interface Outputs { /** Returns the Shipping Rule text. */ fun shippingRuleText(): Observable<String> } class ViewModel(val environment: Environment) : ActivityViewModel<ShippingRuleViewHolder>(environment), Inputs, Outputs { private val shippingRuleAndProject = PublishSubject.create<Pair<ShippingRule, Project>>() private val shippingRuleText = BehaviorSubject.create<String>() val inputs: Inputs = this val outputs: Outputs = this init { this.shippingRuleAndProject .filter { ObjectUtils.isNotNull(it.first) } .map { it.first.location()?.displayableName() } .compose(bindToLifecycle()) .subscribe(this.shippingRuleText) } override fun configureWith(shippingRule: ShippingRule, project: Project) = this.shippingRuleAndProject.onNext(Pair.create(shippingRule, project)) override fun shippingRuleText(): Observable<String> = this.shippingRuleText } }
apache-2.0
9cc9b7ca109ceb081c5614ae0e1a9560
34.93617
153
0.720545
5.245342
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedUnaryOperatorInspection.kt
1
3013
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPrefixExpression import org.jetbrains.kotlin.psi.prefixExpressionVisitor import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class UnusedUnaryOperatorInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = prefixExpressionVisitor(fun(prefix) { if (prefix.baseExpression == null) return val operationToken = prefix.operationToken if (operationToken != KtTokens.PLUS && operationToken != KtTokens.MINUS) return // hack to fix KTIJ-196 (unstable `USED_AS_EXPRESSION` marker for KtAnnotationEntry) if (prefix.isInAnnotationEntry) return val context = prefix.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL_WITH_CFA) if (context == BindingContext.EMPTY || prefix.isUsedAsExpression(context)) return val operatorDescriptor = prefix.operationReference.getResolvedCall(context)?.resultingDescriptor as? DeclarationDescriptor ?: return if (!KotlinBuiltIns.isUnderKotlinPackage(operatorDescriptor)) return holder.registerProblem(prefix, KotlinBundle.message("unused.unary.operator"), RemoveUnaryOperatorFix()) }) private class RemoveUnaryOperatorFix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.unary.operator.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val prefixExpression = descriptor.psiElement as? KtPrefixExpression ?: return val baseExpression = prefixExpression.baseExpression ?: return prefixExpression.replace(baseExpression) } } } private val KtPrefixExpression.isInAnnotationEntry: Boolean get() = parentsWithSelf.takeWhile { it is KtExpression }.last().parent?.parent?.parent is KtAnnotationEntry
apache-2.0
4a192cfddcc6bd7f44c2da2d2bacf3d5
52.803571
158
0.795553
5.185886
false
false
false
false
DanielGrech/anko
dsl/src/org/jetbrains/android/anko/config/AnkoFile.kt
3
1803
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.config import kotlin.properties.Delegates public enum class AnkoFile : ConfigurationOption { ASYNC, CONTEXT_UTILS, CUSTOM, DATABASE, DIALOGS, HELPERS, INTERFACE_WORKAROUNDS_JAVA, INTERNALS, LAYOUTS, LISTENERS, LOGGER, OTHER, OTHER_WIDGETS, PROPERTIES, SERVICES, SQL_PARSER_HELPERS, SQL_PARSERS, SUPPORT, VIEWS; public val filename: String by Delegates.lazy { val name = name() val extension = if (name.endsWith("_JAVA")) ".java" else ".kt" name.substringBeforeLast("_JAVA").toCamelCase() + extension } private companion object { private fun String.toCamelCase(): String { val builder = StringBuilder() var capitalFlag = true for (c in this) { when (c) { '_' -> capitalFlag = true else -> { builder.append(if (capitalFlag) Character.toUpperCase(c) else Character.toLowerCase(c)) capitalFlag = false } } } return builder.toString() } } }
apache-2.0
908d72dacd69c4012368a1875f532579
27.1875
111
0.608985
4.564557
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/platform/AttachProjectAction.kt
1
2406
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.platform import com.intellij.ide.GeneralSettings import com.intellij.ide.actions.OpenProjectFileChooserDescriptor import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.project.isProjectDirectoryExistsUsingIo import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.projectImport.ProjectAttachProcessor import java.nio.file.Paths /** * This action is enabled when confirmOpenNewProject option is set in settings to either OPEN_PROJECT_NEW_WINDOW or * OPEN_PROJECT_SAME_WINDOW, so there is no dialog shown on open directory action, which makes attaching a new project impossible. * This action provides a way to do that in this case. * * @author traff */ internal class AttachProjectAction : AnAction("Attach project..."), DumbAware { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = ProjectAttachProcessor.canAttachToProject() && GeneralSettings.getInstance().confirmOpenNewProject != GeneralSettings.OPEN_PROJECT_ASK } override fun actionPerformed(e: AnActionEvent) { val descriptor = OpenProjectFileChooserDescriptor(true) val project = e.getData(CommonDataKeys.PROJECT) ?: return FileChooser.chooseFiles(descriptor, project, null) { attachProject(it[0], project) } } } private fun attachProject(virtualFile: VirtualFile, project: Project) { var baseDir: VirtualFile? = virtualFile if (!virtualFile.isDirectory) { baseDir = virtualFile.parent while (baseDir != null) { if (isProjectDirectoryExistsUsingIo(baseDir)) { break } baseDir = baseDir.parent } } if (baseDir == null) { Messages.showErrorDialog("Project not found in ${virtualFile.path}", "Can't Attach Project") } else { PlatformProjectOpenProcessor.attachToProject(project, Paths.get(FileUtil.toSystemDependentName(baseDir.path)), null) } }
apache-2.0
37f6afb31903c3a207614998ebfdccd6
39.116667
140
0.766002
4.609195
false
false
false
false
danielgindi/android-helpers
Helpers/src/main/java/com/dg/helpers/FontHelper.kt
1
2853
package com.dg.helpers import android.content.Context import android.graphics.Typeface import android.util.Log import java.util.HashMap /** * This loads the specified font from the assets folder. * If the path specified does not contain path and extension * - it will search for assets/fonts/<fontname>.[ttf|otf] */ @Suppress("unused") class FontHelper private constructor() { companion object { private val sFontCache = HashMap<String, Typeface>() fun clearCache() { sFontCache.clear() } fun cacheSize(): Int { return sFontCache.size } /** * Loads the font with possible use of the static cache * @param context * @param fontFamily * @param loadFromCache Should the font be loaded from cache? * @param saveToCache Should the font be saved to cache? * @return The loaded Typeface or null if failed. */ fun getFont(context: Context, fontFamily: String, loadFromCache: Boolean = true, saveToCache: Boolean = true): Typeface? { var typeface: Typeface? = if (loadFromCache) sFontCache[fontFamily] else null if (typeface == null) { typeface = loadFontFromAssets(context, fontFamily) if (saveToCache && typeface != null) { sFontCache[fontFamily] = typeface } } return typeface } /** * Loads the font directly from the Assets. No caching done here. * @param context * @param fontFamily * @return The loaded Typeface or null if failed. */ private fun loadFontFromAssets(context: Context, fontFamily: String): Typeface? { if (!fontFamily.contains(".") && !fontFamily.contains("/")) { val ttfFontFamily = "fonts/$fontFamily.ttf" try { return Typeface.createFromAsset(context.resources.assets, ttfFontFamily) } catch (ignored: Exception) { } val otfFontFamily = "fonts/$fontFamily.otf" try { return Typeface.createFromAsset(context.resources.assets, otfFontFamily) } catch (ignored: Exception) { } } try { return Typeface.createFromAsset(context.resources.assets, fontFamily) } catch (e: Exception) { Log.e("FontHelper", e.message) return null } } } }
mit
bdbe75a577471065e6d367d1bc0f2e72
27.54
92
0.513495
5.283333
false
false
false
false
jwren/intellij-community
java/java-tests/testSrc/com/intellij/java/refactoring/ExtractMethodAndDuplicatesInplaceTest.kt
1
7861
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.codeInsight.template.impl.TemplateState import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.TextRange import com.intellij.pom.java.LanguageLevel import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.extractMethod.newImpl.MethodExtractor import com.intellij.refactoring.extractMethod.newImpl.inplace.DuplicatesMethodExtractor import com.intellij.refactoring.listeners.RefactoringEventData import com.intellij.refactoring.listeners.RefactoringEventListener import com.intellij.refactoring.util.CommonRefactoringUtil.RefactoringErrorHintException import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.LightJavaCodeInsightTestCase import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.NonNls class ExtractMethodAndDuplicatesInplaceTest: LightJavaCodeInsightTestCase() { private val BASE_PATH: @NonNls String = "/refactoring/extractMethodAndDuplicatesInplace" fun testStatement(){ doTest() } fun testConflictedNamesFiltered(){ doTest() } fun testVariableGetterSuggested(){ doTest() } fun testExactDuplicates(){ doTest() } fun testInvalidRename(){ doTest(changedName = "invalid! name", checkResults = false) require(getActiveTemplate() != null) } fun testConflictRename(){ doTest(changedName = "conflict", checkResults = false) require(getActiveTemplate() != null) } fun testValidRename(){ doTest(changedName = "valid") require(getActiveTemplate() == null) } fun testGeneratedDefault(){ doTest() } fun testRenamedExactDuplicate(){ doTest(changedName = "renamed") } fun testRenamedParametrizedDuplicate(){ doTest(changedName = "average") } fun testStaticMustBePlaced(){ doTest() } fun testShortenClassReferences(){ IdeaTestUtil.withLevel(module, LanguageLevel.JDK_11) { doTest() } } fun testThreeDuplicates(){ doTest(changedName = "sayHello") } fun testParameterGrouping(){ doTest() } fun testConditionalExitPoint(){ doTest() } fun testRuntimeCatchMayChangeSemantic1(){ assertThrows(RefactoringErrorHintException::class.java, JavaRefactoringBundle.message("extract.method.error.many.exits")) { doTest() } } fun testRuntimeCatchMayChangeSemantic2(){ assertThrows(RefactoringErrorHintException::class.java, JavaRefactoringBundle.message("extract.method.error.many.exits")) { doTest() } } fun testRuntimeCatchWithLastAssignment(){ doTest() } fun testSpecificCatch(){ doTest() } fun testExpressionDuplicates(){ doTest() } fun testArrayFoldingWithDuplicate(){ doTest() } fun testFoldReturnExpression(){ doTest() } fun testOverlappingRanges(){ doTest() } fun testConditionalYield(){ doTest() } fun testYieldWithDuplicate(){ doTest() } fun testDisabledOnSwitchRules(){ assertThrows(RefactoringErrorHintException::class.java, RefactoringBundle.message("selected.block.should.represent.a.set.of.statements.or.an.expression")) { doTest() } } fun testNormalizedOnSwitchRule(){ doTest() } fun testExpressionStatementInSwitchExpression(){ doTest() } fun testExpressionStatementInSwitchStatement(){ doTest() } fun testIDEA278872(){ doTest() } fun testLocalAssignmentDuplicates(){ doTest() } fun testWrongLocalAssignmentDuplicates(){ doTest() } fun testDuplicateWithLocalMethodReference(){ doTest() } fun testDuplicateWithAnonymousMethodReference(){ doTest() } fun testDuplicateWithAnonymousFieldReference(){ doTest() } fun testDuplicateWithLocalReferenceInLambda(){ doTest() } fun testAvoidChangeSignatureForLocalRefsInPattern(){ doTest() } fun testAvoidChangeSignatureForLocalRefsInCandidate(){ doTest() } fun testDiamondTypesConsideredAsEqual(){ doTest() } fun testDuplicatedExpressionAndChangeSignature(){ doTest() } fun testChangedVariableDeclaredOnce(){ doTest() } fun testDuplicatedWithDeclinedChangeSignature(){ val default = DuplicatesMethodExtractor.changeSignatureDefault try { DuplicatesMethodExtractor.changeSignatureDefault = false doTest() } finally { DuplicatesMethodExtractor.changeSignatureDefault = default } } fun testDuplicatedButDeclined(){ val default = DuplicatesMethodExtractor.replaceDuplicatesDefault try { DuplicatesMethodExtractor.replaceDuplicatesDefault = false doTest() } finally { DuplicatesMethodExtractor.replaceDuplicatesDefault = default } } fun testTemplateRenamesInsertedCallOnly(){ doTest(changedName = "renamed") } fun testRefactoringListener(){ templateTest { configureByFile("$BASE_PATH/${getTestName(false)}.java") var startReceived = false var doneReceived = false val connection = project.messageBus.connect() Disposer.register(testRootDisposable, connection) connection.subscribe(RefactoringEventListener.REFACTORING_EVENT_TOPIC, object : RefactoringEventListener { override fun refactoringStarted(refactoringId: String, beforeData: RefactoringEventData?) { startReceived = true } override fun refactoringDone(refactoringId: String, afterData: RefactoringEventData?) { doneReceived = true } override fun conflictsDetected(refactoringId: String, conflictsData: RefactoringEventData) = Unit override fun undoRefactoring(refactoringId: String) = Unit }) val template = startRefactoring(editor) require(startReceived) finishTemplate(template) require(doneReceived) } } private fun doTest(checkResults: Boolean = true, changedName: String? = null){ templateTest { configureByFile("$BASE_PATH/${getTestName(false)}.java") val template = startRefactoring(editor) if (changedName != null) { renameTemplate(template, changedName) } finishTemplate(template) if (checkResults) { checkResultByFile("$BASE_PATH/${getTestName(false)}_after.java") } } } private fun startRefactoring(editor: Editor): TemplateState { val selection = with(editor.selectionModel) { TextRange(selectionStart, selectionEnd) } MethodExtractor().doExtract(file, selection) val templateState = getActiveTemplate() require(templateState != null) { "Failed to start refactoring" } return templateState } private fun getActiveTemplate() = TemplateManagerImpl.getTemplateState(editor) private fun finishTemplate(templateState: TemplateState){ try { templateState.gotoEnd(false) UIUtil.dispatchAllInvocationEvents() } catch (ignore: RefactoringErrorHintException) { } } private fun renameTemplate(templateState: TemplateState, name: String) { WriteCommandAction.runWriteCommandAction(project) { val range = templateState.currentVariableRange!! editor.document.replaceString(range.startOffset, range.endOffset, name) } } private inline fun templateTest(test: () -> Unit) { val disposable = Disposer.newDisposable() try { TemplateManagerImpl.setTemplateTesting(disposable) test() } finally { Disposer.dispose(disposable) } } override fun tearDown() { val template = getActiveTemplate() if (template != null) Disposer.dispose(template) super.tearDown() } }
apache-2.0
fe32714d8df2bebf69527e0842d46a4b
24.777049
160
0.726116
4.937814
false
true
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt
1
19756
// 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.refactoring.move.moveDeclarations import com.intellij.ide.IdeDeprecatedMessagesBundle import com.intellij.ide.highlighter.JavaFileType import com.intellij.ide.util.EditorHelper import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler import com.intellij.refactoring.rename.RenameUtil import com.intellij.refactoring.util.NonCodeUsageInfo import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.refactoring.util.TextOccurrencesUtil import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewDescriptor import com.intellij.usageView.UsageViewUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.HashingStrategy import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration import org.jetbrains.kotlin.asJava.findFacadeClass import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests import org.jetbrains.kotlin.idea.core.deleteSingle import org.jetbrains.kotlin.idea.core.quoteIfNeeded import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit import org.jetbrains.kotlin.idea.refactoring.move.* import org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories.MoveKotlinClassHandler import org.jetbrains.kotlin.idea.search.projectScope import org.jetbrains.kotlin.idea.search.restrictByFileType import org.jetbrains.kotlin.idea.util.projectStructure.module import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.utils.ifEmpty import org.jetbrains.kotlin.utils.keysToMap import kotlin.math.max import kotlin.math.min interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration { object Default : Mover { override fun invoke(originalElement: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration { return when (targetContainer) { is KtFile -> { val declarationContainer: KtElement = if (targetContainer.isScript()) targetContainer.script!!.blockExpression else targetContainer declarationContainer.add(originalElement) as KtNamedDeclaration } is KtClassOrObject -> targetContainer.addDeclaration(originalElement) else -> error("Unexpected element: ${targetContainer.getElementTextWithContext()}") }.apply { val container = originalElement.containingClassOrObject if (container is KtObjectDeclaration && container.isCompanion() && container.declarations.singleOrNull() == originalElement && KotlinFindUsagesHandlerFactory(container.project).createFindUsagesHandler(container, false) .findReferencesToHighlight(container, LocalSearchScope(container.containingFile)).isEmpty() ) { container.deleteSingle() } else { originalElement.deleteSingle() } } } } } sealed class MoveSource { abstract val elementsToMove: Collection<KtNamedDeclaration> class Elements(override val elementsToMove: Collection<KtNamedDeclaration>) : MoveSource() class File(val file: KtFile) : MoveSource() { override val elementsToMove: Collection<KtNamedDeclaration> get() = file.declarations.filterIsInstance<KtNamedDeclaration>() } } fun MoveSource(declaration: KtNamedDeclaration) = MoveSource.Elements(listOf(declaration)) fun MoveSource(declarations: Collection<KtNamedDeclaration>) = MoveSource.Elements(declarations) fun MoveSource(file: KtFile) = MoveSource.File(file) class MoveDeclarationsDescriptor @JvmOverloads constructor( val project: Project, val moveSource: MoveSource, val moveTarget: KotlinMoveTarget, val delegate: MoveDeclarationsDelegate, val searchInCommentsAndStrings: Boolean = true, val searchInNonCode: Boolean = true, val deleteSourceFiles: Boolean = false, val moveCallback: MoveCallback? = null, val openInEditor: Boolean = false, val allElementsToMove: List<PsiElement>? = null, val analyzeConflicts: Boolean = true, val searchReferences: Boolean = true ) class ConflictUsageInfo(element: PsiElement, val messages: Collection<String>) : UsageInfo(element) private object ElementHashingStrategy : HashingStrategy<PsiElement> { override fun equals(e1: PsiElement?, e2: PsiElement?): Boolean { if (e1 === e2) return true // Name should be enough to distinguish different light elements based on the same original declaration if (e1 is KtLightDeclaration<*, *> && e2 is KtLightDeclaration<*, *>) { return e1.kotlinOrigin == e2.kotlinOrigin && e1.name == e2.name } return false } override fun hashCode(e: PsiElement?): Int { return when (e) { null -> 0 is KtLightDeclaration<*, *> -> (e.kotlinOrigin?.hashCode() ?: 0) * 31 + (e.name?.hashCode() ?: 0) else -> e.hashCode() } } } class MoveKotlinDeclarationsProcessor( val descriptor: MoveDeclarationsDescriptor, val mover: Mover = Mover.Default, private val throwOnConflicts: Boolean = false ) : BaseRefactoringProcessor(descriptor.project) { companion object { const val REFACTORING_ID = "move.kotlin.declarations" } val project get() = descriptor.project private var nonCodeUsages: Array<NonCodeUsageInfo>? = null private val moveEntireFile = descriptor.moveSource is MoveSource.File private val elementsToMove = descriptor.moveSource.elementsToMove.filter { e -> e.parent != descriptor.moveTarget.getTargetPsiIfExists(e) } private val kotlinToLightElementsBySourceFile = elementsToMove .groupBy { it.containingKtFile } .mapValues { it.value.keysToMap { declaration -> declaration.toLightElements().ifEmpty { listOf(declaration) } } } private val conflicts = MultiMap<PsiElement, String>() override fun getRefactoringId() = REFACTORING_ID override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor { val targetContainerFqName = descriptor.moveTarget.targetContainerFqName?.let { if (it.isRoot) IdeDeprecatedMessagesBundle.message("default.package.presentable.name") else it.asString() } ?: IdeDeprecatedMessagesBundle.message("default.package.presentable.name") return MoveMultipleElementsViewDescriptor(elementsToMove.toTypedArray(), targetContainerFqName) } fun getConflictsAsUsages(): List<UsageInfo> = conflicts.entrySet().map { ConflictUsageInfo(it.key, it.value) } public override fun findUsages(): Array<UsageInfo> { if (!descriptor.searchReferences || elementsToMove.isEmpty()) return UsageInfo.EMPTY_ARRAY val newContainerName = descriptor.moveTarget.targetContainerFqName?.asString() ?: "" fun getSearchScope(element: PsiElement): GlobalSearchScope? { val projectScope = project.projectScope() val ktDeclaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return projectScope if (ktDeclaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) return projectScope val moveTarget = descriptor.moveTarget val (oldContainer, newContainer) = descriptor.delegate.getContainerChangeInfo(ktDeclaration, moveTarget) val targetModule = moveTarget.getTargetModule(project) ?: return projectScope if (oldContainer != newContainer || ktDeclaration.module != targetModule) return projectScope // Check if facade class may change if (newContainer is ContainerInfo.Package) { val javaScope = projectScope.restrictByFileType(JavaFileType.INSTANCE) val currentFile = ktDeclaration.containingKtFile val newFile = when (moveTarget) { is KotlinMoveTargetForExistingElement -> moveTarget.targetElement as? KtFile ?: return null is KotlinMoveTargetForDeferredFile -> return javaScope else -> return null } val currentFacade = currentFile.findFacadeClass() val newFacade = newFile.findFacadeClass() return if (currentFacade?.qualifiedName != newFacade?.qualifiedName) javaScope else null } return null } fun UsageInfo.intersectsWith(usage: UsageInfo): Boolean { if (element?.containingFile != usage.element?.containingFile) return false val firstSegment = segment ?: return false val secondSegment = usage.segment ?: return false return max(firstSegment.startOffset, secondSegment.startOffset) <= min(firstSegment.endOffset, secondSegment.endOffset) } fun collectUsages(kotlinToLightElements: Map<KtNamedDeclaration, List<PsiNamedElement>>, result: MutableCollection<UsageInfo>) { kotlinToLightElements.values.flatten().flatMapTo(result) { lightElement -> val searchScope = getSearchScope(lightElement) ?: return@flatMapTo emptyList() val elementName = lightElement.name ?: return@flatMapTo emptyList() val newFqName = StringUtil.getQualifiedName(newContainerName, elementName) val foundReferences = HashSet<PsiReference>() val results = ReferencesSearch .search(lightElement, searchScope) .mapNotNullTo(ArrayList()) { ref -> if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element) }) { createMoveUsageInfoIfPossible(ref, lightElement, addImportToOriginalFile = true, isInternal = false) } else null } val name = lightElement.getKotlinFqName()?.quoteIfNeeded()?.asString() if (name != null) { fun searchForKotlinNameUsages(results: ArrayList<UsageInfo>) { TextOccurrencesUtil.findNonCodeUsages( lightElement, searchScope, name, descriptor.searchInCommentsAndStrings, descriptor.searchInNonCode, FqName(newFqName).quoteIfNeeded().asString(), results ) } val facadeContainer = lightElement.parent as? KtLightClassForFacade if (facadeContainer != null) { val oldFqNameWithFacade = StringUtil.getQualifiedName(facadeContainer.qualifiedName, elementName) val newFqNameWithFacade = StringUtil.getQualifiedName( StringUtil.getQualifiedName(newContainerName, facadeContainer.name), elementName ) TextOccurrencesUtil.findNonCodeUsages( lightElement, searchScope, oldFqNameWithFacade, descriptor.searchInCommentsAndStrings, descriptor.searchInNonCode, FqName(newFqNameWithFacade).quoteIfNeeded().asString(), results ) ArrayList<UsageInfo>().also { searchForKotlinNameUsages(it) }.forEach { kotlinNonCodeUsage -> if (results.none { it.intersectsWith(kotlinNonCodeUsage) }) { results.add(kotlinNonCodeUsage) } } } else { searchForKotlinNameUsages(results) } } MoveClassHandler.EP_NAME.extensions.filter { it !is MoveKotlinClassHandler }.forEach { handler -> handler.preprocessUsages(results) } results } } val usages = ArrayList<UsageInfo>() val conflictChecker = MoveConflictChecker( project, elementsToMove, descriptor.moveTarget, elementsToMove.first(), allElementsToMove = descriptor.allElementsToMove ) for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) { val internalUsages = LinkedHashSet<UsageInfo>() val externalUsages = LinkedHashSet<UsageInfo>() if (moveEntireFile) { val changeInfo = ContainerChangeInfo( ContainerInfo.Package(sourceFile.packageFqName), descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage ) internalUsages += sourceFile.getInternalReferencesToUpdateOnPackageNameChange(changeInfo) } else { kotlinToLightElements.keys.forEach { val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget) internalUsages += it.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo) } } internalUsages += descriptor.delegate.findInternalUsages(descriptor) collectUsages(kotlinToLightElements, externalUsages) if (descriptor.analyzeConflicts) { conflictChecker.checkAllConflicts(externalUsages, internalUsages, conflicts) descriptor.delegate.collectConflicts(descriptor, internalUsages, conflicts) } usages += internalUsages usages += externalUsages } return UsageViewUtil.removeDuplicatedUsages(usages.toTypedArray()) } override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean { return showConflicts(conflicts, refUsages.get()) } override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean { if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException() return super.showConflicts(conflicts, usages) } override fun performRefactoring(usages: Array<out UsageInfo>) = doPerformRefactoring(usages.toList()) internal fun doPerformRefactoring(usages: List<UsageInfo>) { fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration { val targetContainer = moveTarget.getOrCreateTargetPsi(declaration) descriptor.delegate.preprocessDeclaration(descriptor, declaration) if (moveEntireFile) return declaration return mover(declaration, targetContainer).apply { addToBeShortenedDescendantsToWaitingSet() } } val (oldInternalUsages, externalUsages) = usages.partition { it is KotlinMoveUsage && it.isInternal } val newInternalUsages = ArrayList<UsageInfo>() markInternalUsages(oldInternalUsages) val usagesToProcess = ArrayList(externalUsages) try { descriptor.delegate.preprocessUsages(descriptor, usages) val oldToNewElementsMapping = CollectionFactory.createCustomHashingStrategyMap<PsiElement, PsiElement>(ElementHashingStrategy) val newDeclarations = ArrayList<KtNamedDeclaration>() for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) { for ((oldDeclaration, oldLightElements) in kotlinToLightElements) { val elementListener = transaction?.getElementListener(oldDeclaration) val newDeclaration = moveDeclaration(oldDeclaration, descriptor.moveTarget) newDeclarations += newDeclaration oldToNewElementsMapping[oldDeclaration] = newDeclaration oldToNewElementsMapping[sourceFile] = newDeclaration.containingKtFile elementListener?.elementMoved(newDeclaration) for ((oldElement, newElement) in oldLightElements.asSequence().zip(newDeclaration.toLightElements().asSequence())) { oldToNewElementsMapping[oldElement] = newElement } if (descriptor.openInEditor) { EditorHelper.openInEditor(newDeclaration) } } if (descriptor.deleteSourceFiles && sourceFile.declarations.isEmpty()) { sourceFile.delete() } } val internalUsageScopes: List<KtElement> = if (moveEntireFile) { newDeclarations.asSequence().map { it.containingKtFile }.distinct().toList() } else { newDeclarations } internalUsageScopes.forEach { newInternalUsages += restoreInternalUsages(it, oldToNewElementsMapping) } usagesToProcess += newInternalUsages nonCodeUsages = postProcessMoveUsages(usagesToProcess, oldToNewElementsMapping).toTypedArray() performDelayedRefactoringRequests(project) } catch (e: IncorrectOperationException) { nonCodeUsages = null RefactoringUIUtil.processIncorrectOperation(myProject, e) } finally { cleanUpInternalUsages(newInternalUsages + oldInternalUsages) } } override fun performPsiSpoilingRefactoring() { nonCodeUsages?.let { nonCodeUsages -> RenameUtil.renameNonCodeUsages(myProject, nonCodeUsages) } descriptor.moveCallback?.refactoringCompleted() } fun execute(usages: List<UsageInfo>) { execute(usages.toTypedArray()) } override fun doRun() { try { super.doRun() } finally { broadcastRefactoringExit(myProject, refactoringId) } } override fun getCommandName(): String = KotlinBundle.message("command.move.declarations") }
apache-2.0
d5e0500b935540fd6129a3da8ee200a8
47.303178
138
0.673112
5.872771
false
false
false
false
JetBrains/kotlin-native
tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/konan/KonanCompileConfig.kt
1
7325
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.gradle.plugin.konan import groovy.lang.Closure import org.gradle.api.Task import org.gradle.api.file.FileCollection import org.gradle.api.internal.project.ProjectInternal import org.jetbrains.kotlin.gradle.plugin.tasks.* import org.jetbrains.kotlin.konan.target.Family import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.konan.target.KonanTarget.WASM32 import java.io.File abstract class KonanCompileConfig<T: KonanCompileTask>(name: String, type: Class<T>, project: ProjectInternal, targets: Iterable<String>) : KonanBuildingConfig<T>(name, type, project, targets), KonanCompileSpec { protected abstract val typeForDescription: String override fun generateTaskDescription(task: T) = "Build the Kotlin/Native $typeForDescription '${task.name}' for target '${task.konanTarget}'" override fun generateAggregateTaskDescription(task: Task) = "Build the Kotlin/Native $typeForDescription '${task.name}' for all supported and declared targets" override fun generateTargetAliasTaskDescription(task: Task, targetName: String) = "Build the Kotlin/Native $typeForDescription '${task.name}' for target '$targetName'" override fun srcDir(dir: Any) = tasks().forEach { it.configure { t -> t.srcDir(dir) } } override fun srcFiles(vararg files: Any) = tasks().forEach { it.configure { t -> t.srcFiles(*files) } } override fun srcFiles(files: Collection<Any>) = tasks().forEach { it.configure { t -> t.srcFiles(files) } } override fun nativeLibrary(lib: Any) = tasks().forEach { it.configure { t -> t.nativeLibrary(lib) } } override fun nativeLibraries(vararg libs: Any) = tasks().forEach { it.configure { t -> t.nativeLibraries(*libs) } } override fun nativeLibraries(libs: FileCollection) = tasks().forEach { it.configure { t -> t.nativeLibraries(libs) } } @Deprecated("Use commonSourceSets instead", ReplaceWith("commonSourceSets(sourceSetName)")) override fun commonSourceSet(sourceSetName: String) = tasks().forEach { it.configure { t -> t.commonSourceSets(sourceSetName) } } override fun commonSourceSets(vararg sourceSetNames: String) = tasks().forEach { it.configure { t -> t.commonSourceSets(*sourceSetNames) } } override fun enableMultiplatform(flag: Boolean) = tasks().forEach { it.configure { t -> t.enableMultiplatform(flag) } } override fun linkerOpts(values: List<String>) = tasks().forEach { it.configure { t -> t.linkerOpts(values) } } override fun linkerOpts(vararg values: String) = tasks().forEach { it.configure { t -> t.linkerOpts(*values) } } override fun enableDebug(flag: Boolean) = tasks().forEach { it.configure { t -> t.enableDebug(flag) } } override fun noStdLib(flag: Boolean) = tasks().forEach { it.configure { t -> t.noStdLib(flag) } } override fun noMain(flag: Boolean) = tasks().forEach { it.configure { t -> t.noMain(flag) } } override fun enableOptimizations(flag: Boolean) = tasks().forEach { it.configure { t -> t.enableOptimizations(flag) } } override fun enableAssertions(flag: Boolean) = tasks().forEach { it.configure { t -> t.enableAssertions(flag) } } override fun entryPoint(entryPoint: String) = tasks().forEach { it.configure { t -> t.entryPoint(entryPoint) } } override fun measureTime(flag: Boolean) = tasks().forEach { it.configure { t -> t.measureTime(flag) } } override fun dependencies(closure: Closure<Unit>) = tasks().forEach { it.configure { t -> t.dependencies(closure) } } } open class KonanProgram(name: String, project: ProjectInternal, targets: Iterable<String> = project.konanExtension.targets ) : KonanCompileConfig<KonanCompileProgramTask>(name, KonanCompileProgramTask::class.java, project, targets ) { override val typeForDescription: String get() = "executable" override val defaultBaseDir: File get() = project.konanBinBaseDir } open class KonanDynamic(name: String, project: ProjectInternal, targets: Iterable<String> = project.konanExtension.targets) : KonanCompileConfig<KonanCompileDynamicTask>(name, KonanCompileDynamicTask::class.java, project, targets ) { override val typeForDescription: String get() = "dynamic library" override val defaultBaseDir: File get() = project.konanBinBaseDir override fun targetIsSupported(target: KonanTarget): Boolean = target != WASM32 } open class KonanFramework(name: String, project: ProjectInternal, targets: Iterable<String> = project.konanExtension.targets) : KonanCompileConfig<KonanCompileFrameworkTask>(name, KonanCompileFrameworkTask::class.java, project, targets ) { override val typeForDescription: String get() = "framework" override val defaultBaseDir: File get() = project.konanBinBaseDir override fun targetIsSupported(target: KonanTarget): Boolean = target.family.isAppleFamily } open class KonanLibrary(name: String, project: ProjectInternal, targets: Iterable<String> = project.konanExtension.targets) : KonanCompileConfig<KonanCompileLibraryTask>(name, KonanCompileLibraryTask::class.java, project, targets ) { override val typeForDescription: String get() = "library" override val defaultBaseDir: File get() = project.konanLibsBaseDir } open class KonanBitcode(name: String, project: ProjectInternal, targets: Iterable<String> = project.konanExtension.targets) : KonanCompileConfig<KonanCompileBitcodeTask>(name, KonanCompileBitcodeTask::class.java, project, targets ) { override val typeForDescription: String get() = "bitcode" override fun generateTaskDescription(task: KonanCompileBitcodeTask) = "Generates bitcode for the artifact '${task.name}' and target '${task.konanTarget}'" override fun generateAggregateTaskDescription(task: Task) = "Generates bitcode for the artifact '${task.name}' for all supported and declared targets'" override fun generateTargetAliasTaskDescription(task: Task, targetName: String) = "Generates bitcode for the artifact '${task.name}' for '$targetName'" override val defaultBaseDir: File get() = project.konanBitcodeBaseDir }
apache-2.0
f4358268220a07d1f62125e048467ff8
44.222222
144
0.679454
4.674537
false
true
false
false
jwren/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/buildSystem/gradle/GradlePlugin.kt
4
9196
// 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.tools.projectWizard.plugins.buildSystem.gradle import kotlinx.collections.immutable.toPersistentList import org.jetbrains.kotlin.tools.projectWizard.Versions import org.jetbrains.kotlin.tools.projectWizard.core.* import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting import org.jetbrains.kotlin.tools.projectWizard.core.service.FileSystemWizardService import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.* import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.SettingsGradleFileIR import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.* import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.printBuildFile import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath import org.jetbrains.kotlin.tools.projectWizard.plugins.templates.TemplatesPlugin import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.updateBuildFiles import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplate import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplateDescriptor abstract class GradlePlugin(context: Context) : BuildSystemPlugin(context) { override val path = pluginPath companion object : PluginSettingsOwner() { override val pluginPath = "buildSystem.gradle" val gradleProperties by listProperty( "kotlin.code.style" to "official" ) val settingsGradleFileIRs by listProperty<BuildSystemIR>() val createGradlePropertiesFile by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runAfter(KotlinPlugin.createModules) runBefore(TemplatesPlugin.renderFileTemplates) isAvailable = isGradle withAction { TemplatesPlugin.addFileTemplate.execute( FileTemplate( FileTemplateDescriptor( "gradle/gradle.properties.vm", "gradle.properties".asPath() ), StructurePlugin.projectPath.settingValue, mapOf( "properties" to gradleProperties .propertyValue .distinctBy { it.first } ) ) ) } } val localProperties by listProperty<Pair<String, String>>() val createLocalPropertiesFile by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runAfter(KotlinPlugin.createModules) runBefore(TemplatesPlugin.renderFileTemplates) isAvailable = isGradle withAction { val properties = localProperties.propertyValue if (properties.isEmpty()) return@withAction UNIT_SUCCESS TemplatesPlugin.addFileTemplate.execute( FileTemplate( FileTemplateDescriptor( "gradle/local.properties.vm", "local.properties".asPath() ), StructurePlugin.projectPath.settingValue, mapOf( "properties" to localProperties.propertyValue ) ) ) } } private val isGradle = checker { buildSystemType.isGradle } val gradleVersion by valueSetting( "<GRADLE_VERSION>", GenerationPhase.PROJECT_GENERATION, parser = Version.parser ) { defaultValue = value(Versions.GRADLE) } val initGradleWrapperTask by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runBefore(TemplatesPlugin.renderFileTemplates) isAvailable = isGradle withAction { TemplatesPlugin.addFileTemplate.execute( FileTemplate( FileTemplateDescriptor( "gradle/gradle-wrapper.properties.vm", "gradle" / "wrapper" / "gradle-wrapper.properties" ), StructurePlugin.projectPath.settingValue, mapOf( "version" to gradleVersion.settingValue ) ) ) } } val mergeCommonRepositories by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runBefore(createModules) runAfter(takeRepositoriesFromDependencies) runAfter(KotlinPlugin.createPluginRepositories) isAvailable = isGradle withAction { val buildFiles = buildFiles.propertyValue if (buildFiles.size == 1) return@withAction UNIT_SUCCESS val moduleRepositories = buildFiles.mapNotNull { buildFileIR -> if (buildFileIR.isRoot) null else buildFileIR.irs.mapNotNull { it.safeAs<RepositoryIR>()?.repository } } val allRepositories = moduleRepositories.flatMapTo(hashSetOf()) { it } val commonRepositories = allRepositories.filterTo( hashSetOf(KotlinPlugin.version.propertyValue.repository) ) { repo -> moduleRepositories.all { repo in it } } updateBuildFiles { buildFile -> buildFile.withReplacedIrs( buildFile.irs .filterNot { it.safeAs<RepositoryIR>()?.repository in commonRepositories } .toPersistentList() ).let { if (it.isRoot && commonRepositories.isNotEmpty()) { val repositories = commonRepositories.map(::RepositoryIR).distinctAndSorted() it.withIrs(AllProjectsRepositoriesIR(repositories)) } else it }.asSuccess() } } } val createSettingsFileTask by pipelineTask(GenerationPhase.PROJECT_GENERATION) { runAfter(KotlinPlugin.createModules) runAfter(KotlinPlugin.createPluginRepositories) isAvailable = isGradle withAction { val (createBuildFile, buildFileName) = settingsGradleBuildFileData ?: return@withAction UNIT_SUCCESS val repositories = getPluginRepositoriesWithDefaultOnes().map { PluginManagementRepositoryIR(RepositoryIR(it)) } val settingsGradleIR = SettingsGradleFileIR( StructurePlugin.name.settingValue, allModulesPaths.map { path -> path.joinToString(separator = "") { ":$it" } }, buildPersistenceList { +repositories +settingsGradleFileIRs.propertyValue } ) val buildFileText = createBuildFile().printBuildFile { settingsGradleIR.render(this) } service<FileSystemWizardService>().createFile( projectPath / buildFileName, buildFileText ) } } } override val settings: List<PluginSetting<*, *>> = super.settings + listOf( gradleVersion, ) override val pipelineTasks: List<PipelineTask> = super.pipelineTasks + listOf( createGradlePropertiesFile, createLocalPropertiesFile, initGradleWrapperTask, createSettingsFileTask, mergeCommonRepositories, ) override val properties: List<Property<*>> = super.properties + listOf( gradleProperties, settingsGradleFileIRs, localProperties ) } val Reader.settingsGradleBuildFileData get() = when (buildSystemType) { BuildSystemType.GradleKotlinDsl -> BuildFileData( { GradlePrinter(GradlePrinter.GradleDsl.KOTLIN) }, "settings.gradle.kts" ) BuildSystemType.GradleGroovyDsl -> BuildFileData( { GradlePrinter(GradlePrinter.GradleDsl.GROOVY) }, "settings.gradle" ) else -> null }
apache-2.0
c4218ffe8295b7cf0e76a52b2d78fa0c
41.776744
158
0.596346
6.196765
false
false
false
false
androidx/androidx
compose/ui/ui-test-junit4/src/androidAndroidTest/kotlin/androidx/compose/ui/test/junit4/WaitingForPopupTest.kt
3
2581
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test.junit4 import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Modifier import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.isPopup import androidx.compose.ui.test.runComposeUiTest import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Popup import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalTestApi::class) class WaitingForPopupTest { @Composable private fun ShowPopup() { Popup { Box(Modifier.size(10.dp, 10.dp)) } } @Test fun popupInFirstComposition() = runComposeUiTest { setContent { ShowPopup() } onNode(isPopup()).assertExists() } @Test fun popupInLaterComposition() = runComposeUiTest { val showPopup = mutableStateOf(false) setContent { if (showPopup.value) { ShowPopup() } } onNode(isPopup()).assertDoesNotExist() showPopup.value = true onNode(isPopup()).assertExists() } @Test fun popupTogglingRepeatedly() = runComposeUiTest { val showPopup = mutableStateOf(false) setContent { if (showPopup.value) { ShowPopup() } } onNode(isPopup()).assertDoesNotExist() // (no particular reason for 4x, could've been 10x just as well) repeat(4) { showPopup.value = !showPopup.value if (showPopup.value) { onNode(isPopup()).assertExists() } else { onNode(isPopup()).assertDoesNotExist() } } } }
apache-2.0
b6c3bc3ed0223300ceb9e67df9791141
29.011628
75
0.664084
4.480903
false
true
false
false
androidx/androidx
compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/external/kotlinx/collections/immutable/implementations/immutableMap/PersistentHashMapBuilderContentIterators.kt
3
5112
/* * Copyright 2016-2019 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package androidx.compose.runtime.external.kotlinx.collections.immutable.implementations.immutableMap import androidx.compose.runtime.external.kotlinx.collections.immutable.internal.assert internal class TrieNodeMutableEntriesIterator<K, V>( private val parentIterator: PersistentHashMapBuilderEntriesIterator<K, V> ) : TrieNodeBaseIterator<K, V, MutableMap.MutableEntry<K, V>>() { override fun next(): MutableMap.MutableEntry<K, V> { assert(hasNextKey()) index += 2 @Suppress("UNCHECKED_CAST") return MutableMapEntry(parentIterator, buffer[index - 2] as K, buffer[index - 1] as V) } } private class MutableMapEntry<K, V>( private val parentIterator: PersistentHashMapBuilderEntriesIterator<K, V>, key: K, override var value: V ) : MapEntry<K, V>(key, value), MutableMap.MutableEntry<K, V> { override fun setValue(newValue: V): V { val result = value value = newValue parentIterator.setValue(key, newValue) return result } } internal open class PersistentHashMapBuilderBaseIterator<K, V, T>( private val builder: PersistentHashMapBuilder<K, V>, path: Array<TrieNodeBaseIterator<K, V, T>> ) : MutableIterator<T>, PersistentHashMapBaseIterator<K, V, T>(builder.node, path) { private var lastIteratedKey: K? = null private var nextWasInvoked = false private var expectedModCount = builder.modCount override fun next(): T { checkForComodification() lastIteratedKey = currentKey() nextWasInvoked = true return super.next() } override fun remove() { checkNextWasInvoked() if (hasNext()) { val currentKey = currentKey() builder.remove(lastIteratedKey) resetPath(currentKey.hashCode(), builder.node, currentKey, 0) } else { builder.remove(lastIteratedKey) } lastIteratedKey = null nextWasInvoked = false expectedModCount = builder.modCount } fun setValue(key: K, newValue: V) { if (!builder.containsKey(key)) return if (hasNext()) { val currentKey = currentKey() builder[key] = newValue resetPath(currentKey.hashCode(), builder.node, currentKey, 0) } else { builder[key] = newValue } expectedModCount = builder.modCount } private fun resetPath(keyHash: Int, node: TrieNode<*, *>, key: K, pathIndex: Int) { val shift = pathIndex * LOG_MAX_BRANCHING_FACTOR if (shift > MAX_SHIFT) { // collision path[pathIndex].reset(node.buffer, node.buffer.size, 0) while (path[pathIndex].currentKey() != key) { path[pathIndex].moveToNextKey() } pathLastIndex = pathIndex return } val keyPositionMask = 1 shl indexSegment(keyHash, shift) if (node.hasEntryAt(keyPositionMask)) { // key is directly in buffer val keyIndex = node.entryKeyIndex(keyPositionMask) // assert(node.keyAtIndex(keyIndex) == key) path[pathIndex].reset(node.buffer, ENTRY_SIZE * node.entryCount(), keyIndex) pathLastIndex = pathIndex return } // assert(node.hasNodeAt(keyPositionMask)) // key is in node val nodeIndex = node.nodeIndex(keyPositionMask) val targetNode = node.nodeAtIndex(nodeIndex) path[pathIndex].reset(node.buffer, ENTRY_SIZE * node.entryCount(), nodeIndex) resetPath(keyHash, targetNode, key, pathIndex + 1) } private fun checkNextWasInvoked() { if (!nextWasInvoked) throw IllegalStateException() } private fun checkForComodification() { if (builder.modCount != expectedModCount) throw ConcurrentModificationException() } } internal class PersistentHashMapBuilderEntriesIterator<K, V>( builder: PersistentHashMapBuilder<K, V> ) : MutableIterator<MutableMap.MutableEntry<K, V>> { private val base = PersistentHashMapBuilderBaseIterator<K, V, MutableMap.MutableEntry<K, V>>( builder, Array(TRIE_MAX_HEIGHT + 1) { TrieNodeMutableEntriesIterator(this) } ) override fun hasNext(): Boolean = base.hasNext() override fun next(): MutableMap.MutableEntry<K, V> = base.next() override fun remove(): Unit = base.remove() fun setValue(key: K, newValue: V): Unit = base.setValue(key, newValue) } internal class PersistentHashMapBuilderKeysIterator<K, V>(builder: PersistentHashMapBuilder<K, V>) : PersistentHashMapBuilderBaseIterator<K, V, K>(builder, Array(TRIE_MAX_HEIGHT + 1) { TrieNodeKeysIterator<K, V>() }) internal class PersistentHashMapBuilderValuesIterator<K, V>(builder: PersistentHashMapBuilder<K, V>) : PersistentHashMapBuilderBaseIterator<K, V, V>(builder, Array(TRIE_MAX_HEIGHT + 1) { TrieNodeValuesIterator<K, V>() })
apache-2.0
927bfca83429870ded95f0c72173a062
33.782313
123
0.655908
4.288591
false
false
false
false
GunoH/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/core/templates.kt
4
2374
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core import com.intellij.ide.fileTemplates.FileTemplate import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.name.FqName import java.util.* private const val FUNCTION_BODY_TEMPLATE = "New Kotlin Function Body.kt" private const val PROPERTY_INITIALIZER_TEMPLATE = "New Kotlin Property Initializer.kt" private const val SECONDARY_CONSTRUCTOR_BODY_TEMPLATE = "New Kotlin Secondary Constructor Body.kt" private const val ATTRIBUTE_FUNCTION_NAME = "FUNCTION_NAME" private const val ATTRIBUTE_PROPERTY_NAME = "PROPERTY_NAME" enum class TemplateKind(val templateFileName: String) { FUNCTION(FUNCTION_BODY_TEMPLATE), SECONDARY_CONSTRUCTOR(SECONDARY_CONSTRUCTOR_BODY_TEMPLATE), PROPERTY_INITIALIZER(PROPERTY_INITIALIZER_TEMPLATE) } fun getFunctionBodyTextFromTemplate( project: Project, kind: TemplateKind, name: String?, returnType: String, classFqName: FqName? = null ): String { val fileTemplate = FileTemplateManager.getInstance(project)!!.getCodeTemplate(kind.templateFileName) val properties = Properties() properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, returnType) if (classFqName != null) { properties.setProperty(FileTemplate.ATTRIBUTE_CLASS_NAME, classFqName.asString()) properties.setProperty(FileTemplate.ATTRIBUTE_SIMPLE_CLASS_NAME, classFqName.shortName().asString()) } if (name != null) { val attribute = when (kind) { TemplateKind.FUNCTION, TemplateKind.SECONDARY_CONSTRUCTOR -> ATTRIBUTE_FUNCTION_NAME TemplateKind.PROPERTY_INITIALIZER -> ATTRIBUTE_PROPERTY_NAME } properties.setProperty(attribute, name) } return try { fileTemplate.getText(properties) } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { // TODO: This is dangerous. // Is there any way to avoid catching all exceptions? throw IncorrectOperationException("Failed to parse file template", e) } }
apache-2.0
6164c94e8c28c7b00f300f362ee8582a
40.649123
158
0.749789
4.591876
false
false
false
false
vickychijwani/kotlin-koans-android
app/src/main/code/me/vickychijwani/kotlinkoans/features/settings/SettingsActivity.kt
1
3398
package me.vickychijwani.kotlinkoans.features.settings import android.app.Activity import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceFragment import me.vickychijwani.kotlinkoans.KotlinKoansApplication import me.vickychijwani.kotlinkoans.R import me.vickychijwani.kotlinkoans.util.Prefs import me.vickychijwani.kotlinkoans.util.getBoolean import me.vickychijwani.kotlinkoans.util.getStringAsInt class SettingsActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeListener { companion object { val RESULT_CODE_SETTINGS_NOT_CHANGED = 100 val RESULT_CODE_SETTINGS_CHANGED = 101 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) fragmentManager.beginTransaction() .replace(R.id.settings_container, SettingsFragment()) .commit() setResult(RESULT_CODE_SETTINGS_NOT_CHANGED) } override fun onResume() { super.onResume() Prefs.with(this).registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() Prefs.with(this).unregisterOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { setResult(RESULT_CODE_SETTINGS_CHANGED) } } class SettingsFragment : PreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) preferenceManager.sharedPreferencesName = Prefs.getFileName( KotlinKoansApplication.getInstance()) addPreferencesFromResource(R.xml.preferences) if (activity != null) { val prefs = Prefs.with(activity) updateIndentSizeEnabled(prefs) updateIndentSizePrefSummary(prefs) } } override fun onAttach(context: Context) { super.onAttach(context) updateIndentSizePrefSummary(Prefs.with(context)) } override fun onResume() { super.onResume() Prefs.with(activity).registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() Prefs.with(activity).unregisterOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(prefs: SharedPreferences, key: String) { when (key) { getString(R.string.pref_auto_indent) -> updateIndentSizeEnabled(prefs) getString(R.string.pref_indent_size) -> updateIndentSizePrefSummary(prefs) } } private fun updateIndentSizeEnabled(prefs: SharedPreferences) { findPreference(getString(R.string.pref_indent_size))?.let { pref -> pref.isEnabled = prefs.getBoolean(activity, R.string.pref_auto_indent, R.bool.pref_auto_indent_default) } } private fun updateIndentSizePrefSummary(prefs: SharedPreferences) { findPreference(getString(R.string.pref_indent_size))?.let { pref -> val indentSize = prefs.getStringAsInt(activity, R.string.pref_indent_size, R.integer.pref_indent_size_default) pref.summary = "$indentSize spaces" } } }
mit
e05a0e1350e067e1a7a2fd2ff3473c73
33.323232
99
0.700706
4.989721
false
false
false
false
GunoH/intellij-community
java/java-impl/src/com/intellij/externalSystem/JavaModuleData.kt
12
1426
// 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.externalSystem import com.intellij.openapi.externalSystem.model.Key import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.model.project.AbstractExternalEntityData import com.intellij.pom.java.LanguageLevel import com.intellij.serialization.PropertyMapping class JavaModuleData @PropertyMapping("owner", "languageLevel", "targetBytecodeVersion") constructor( owner: ProjectSystemId, var languageLevel: LanguageLevel?, var targetBytecodeVersion: String? ) : AbstractExternalEntityData(owner) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is JavaModuleData) return false if (!super.equals(other)) return false if (languageLevel != other.languageLevel) return false if (targetBytecodeVersion != other.targetBytecodeVersion) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + languageLevel.hashCode() result = 31 * result + targetBytecodeVersion.hashCode() return result } override fun toString() = "java module" companion object { @JvmField val KEY = Key.create(JavaModuleData::class.java, JavaProjectData.KEY.processingWeight + 1) } }
apache-2.0
2e2a07630861e73813d3fda84de2b02e
32.97619
140
0.76087
4.6
false
false
false
false
WillowChat/Kale
src/main/kotlin/chat/willow/kale/KaleMetadataFactory.kt
2
1184
package chat.willow.kale import chat.willow.kale.core.message.IrcMessage import chat.willow.kale.core.tag.IKaleTagRouter import chat.willow.kale.core.tag.ITagStore import chat.willow.kale.core.tag.Tag import chat.willow.kale.core.tag.TagStore typealias KaleMetadataStore = ITagStore interface IKaleMetadataFactory { fun construct(message: IrcMessage): KaleMetadataStore } class KaleMetadataFactory(private val tagRouter: IKaleTagRouter): IKaleMetadataFactory { private val LOGGER = loggerFor<KaleMetadataFactory>() override fun construct(message: IrcMessage): KaleMetadataStore { val metadata = TagStore() for ((key, value) in message.tags) { val tag = Tag(key, value) val factory = tagRouter.parserFor(tag.name) if (factory == null) { LOGGER.debug("no parser for tag $tag") continue } val parsedTag = factory.parse(tag) if (parsedTag == null) { LOGGER.warn("factory failed to parse tag: $factory $tag") continue } metadata.store(parsedTag) } return metadata } }
isc
7e32e671bcec01da885cc7b84b85ea5a
25.333333
88
0.643581
4.305455
false
false
false
false
Jire/Charlatano
src/main/kotlin/com/charlatano/game/Weapons.kt
1
3226
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game enum class Weapons(val id: Int, val automatic: Boolean = false, val grenade: Boolean = false, val knife: Boolean = false, val sniper: Boolean = false, val boltAction: Boolean = false, val pistol: Boolean = false, val shotgun: Boolean = false) { NONE(0), DESERT_EAGLE(1, pistol = true), DUAL_BERRETA(2, pistol = true), FIVE_SEVEN(3, pistol = true), GLOCK(4, pistol = true), AK47(7, automatic = true), AUG(8, automatic = true), AWP(9, sniper = true, boltAction = true), FAMAS(10, automatic = true), G3SG1(11, sniper = true), GALIL(13, automatic = true), M249(14, automatic = true), M4A4(16, automatic = true), MAC10(17, automatic = true), P90(19, automatic = true), UMP45(24, automatic = true), XM1014(25, shotgun = true), PP_BIZON(26, automatic = true), MAG7(27, boltAction = true, shotgun = true), NEGEV(28, automatic = true), SAWED_OFF(29, boltAction = true, shotgun = true), TEC9(30, pistol = true), ZEUS_X27(31), P2000(32, pistol = true), MP7(33, automatic = true), MP9(34, automatic = true), NOVA(35, boltAction = true, shotgun = true), P250(36, pistol = true), SCAR20(38, sniper = true), SG556(39, automatic = true), SSG08(40, sniper = true, boltAction = true), KNIFE(42, knife = true), FLASH_GRENADE(43, grenade = true), EXPLOSIVE_GRENADE(44, grenade = true), SMOKE_GRENADE(45, grenade = true), MOLOTOV(46, grenade = true), DECOY_GRENADE(47, grenade = true), INCENDIARY_GRENADE(48, grenade = true), C4(49), KNIFE_T(59, knife = true), M4A1_SILENCER(60, automatic = true), USP_SILENCER(61, pistol = true), CZ75A(63, automatic = true, pistol = true), R8_REVOLVER(64, boltAction = true, pistol = true), KNIFE_BAYONET(500, knife = true), KNIFE_FLIP(505, knife = true), KNIFE_GUT(506, knife = true), KNIFE_KARAMBIT(507, knife = true), KNIFE_M9_BAYONET(508, knife = true), KNIFE_TACTICAL(509, knife = true), KNIFE_TALCHION(512, knife = true), KNIFE_BOWIE(514, knife = true), KNIFE_BUTTERFLY(515, knife = true), KNIFE_PUSH(516, knife = true), FISTS(69, knife = true), MEDISHOT(57, knife = true), TABLET(72, knife = true), DIVERSION_DEVICE(82, knife = true), FIRE_BOMB(81, knife = true), CHARGE(70, knife = true), HAMMER(76, knife = true); companion object { private val cachedValues = values() operator fun get(id: Int) = cachedValues.firstOrNull { it.id == id } ?: NONE } }
agpl-3.0
26ee557da6adbfb982602ddcd469aac7
32.968421
108
0.677929
2.783434
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/PermissionManager.kt
1
1481
package ch.rmy.android.http_shortcuts.utils import android.Manifest.permission.ACCESS_FINE_LOCATION import android.Manifest.permission.POST_NOTIFICATIONS import android.Manifest.permission.READ_EXTERNAL_STORAGE import android.content.Context import android.content.pm.PackageManager import android.os.Build import androidx.core.app.ActivityCompat import com.markodevcic.peko.Peko import com.markodevcic.peko.PermissionResult import javax.inject.Inject class PermissionManager @Inject constructor( private val context: Context, ) { @Inject lateinit var activityProvider: ActivityProvider suspend fun requestFileStoragePermissionIfNeeded() = requestPermissionIfNeeded(READ_EXTERNAL_STORAGE) suspend fun requestLocationPermissionIfNeeded(): Boolean = requestPermissionIfNeeded(ACCESS_FINE_LOCATION) fun shouldShowRationaleForLocationPermission(): Boolean = ActivityCompat.shouldShowRequestPermissionRationale(activityProvider.getActivity(), ACCESS_FINE_LOCATION) fun hasNotificationPermission(): Boolean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { ActivityCompat.checkSelfPermission(context, POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED } else { true } private suspend fun requestPermissionIfNeeded(permission: String): Boolean = Peko.requestPermissionsAsync(activityProvider.getActivity(), permission) is PermissionResult.Granted }
mit
28f283e39dfef17f7fc5946160392b89
35.121951
113
0.78528
5.071918
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/curl_command/src/main/kotlin/ch/rmy/curlcommand/CurlCommand.kt
1
3559
package ch.rmy.curlcommand import java.io.Serializable import java.net.URLEncoder class CurlCommand private constructor() : Serializable { var url = "" private set var method = METHOD_GET private set val headers: Map<String, String> get() = headersInternal private val headersInternal = mutableMapOf<String, String>() val data: List<String> get() = dataInternal var usesBinaryData: Boolean = false private set private val dataInternal = mutableListOf<String>() var timeout = 0 private set var username = "" private set var password = "" private set var isFormData: Boolean = false private set var proxyHost: String = "" private set var proxyPort: Int = 0 private set class Builder { private val curlCommand = CurlCommand() private var forceGet = false private var methodSet = false fun url(url: String) = also { curlCommand.url = if (url.startsWith("http:", ignoreCase = true) || url.startsWith("https:", ignoreCase = true)) { url } else { "http://$url" } } fun method(method: String) = also { methodSet = true curlCommand.method = method.uppercase() } fun methodIfNotYetSet(method: String) = also { if (!methodSet) { method(method) } } fun data(data: String) = also { if (data.isNotEmpty()) { curlCommand.dataInternal.add(data) } } fun isFormData() = also { curlCommand.isFormData = true } fun usesBinaryData() = also { curlCommand.usesBinaryData = true } fun addParameter(key: String, value: String) = also { curlCommand.dataInternal.add(encode(key) + "=" + encode(value)) } fun addFileParameter(key: String) = also { curlCommand.isFormData = true curlCommand.dataInternal.add(encode(key) + "=@file") } fun timeout(timeout: Int) = also { curlCommand.timeout = timeout } fun username(username: String) = also { curlCommand.username = username } fun password(password: String) = also { curlCommand.password = password } fun header(key: String, value: String) = also { curlCommand.headersInternal[key] = value } fun proxy(host: String, port: Int) = also { curlCommand.proxyHost = host curlCommand.proxyPort = port } fun forceGet() { method(METHOD_GET) forceGet = true } fun build(): CurlCommand { if (forceGet) { // TODO: This is a naive implementation, which is not generally correct val queryString = curlCommand.dataInternal.joinToString("&") curlCommand.dataInternal.clear() curlCommand.url += if (curlCommand.url.contains("?")) { "&" } else { "?" } + queryString } return curlCommand } } companion object { private const val PARAMETER_ENCODING = "UTF-8" const val METHOD_GET = "GET" private fun encode(text: String): String = URLEncoder.encode(text, PARAMETER_ENCODING) } }
mit
2eb38925445fe16ae4a2d600c9187b38
25.962121
126
0.534701
4.809459
false
false
false
false
Austin72/Charlatano
src/main/kotlin/com/charlatano/game/entity/Bomb.kt
1
2142
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game.entity import com.charlatano.game.CSGO.ENTITY_SIZE import com.charlatano.game.CSGO.clientDLL import com.charlatano.game.CSGO.csgoEXE import com.charlatano.game.CSGO.engineDLL import com.charlatano.game.netvars.NetVarOffsets.bBombDefused import com.charlatano.game.netvars.NetVarOffsets.flC4Blow import com.charlatano.game.netvars.NetVarOffsets.hOwnerEntity import com.charlatano.game.netvars.NetVarOffsets.szLastPlaceName import com.charlatano.game.offsets.ClientOffsets.dwEntityList import com.charlatano.game.offsets.EngineOffsets.dwGlobalVars import com.charlatano.utils.extensions.uint typealias Bomb = Long internal fun Bomb.defused(): Boolean = csgoEXE.boolean(this + bBombDefused) internal fun Bomb.timeLeft(): Int = (-(engineDLL.float(dwGlobalVars + 16) - csgoEXE.float(this + flC4Blow))).toInt() internal fun Bomb.planted() = this != -1L && !defused() && timeLeft() > 0 internal fun Bomb.owner() = csgoEXE.uint(this + hOwnerEntity) internal fun Bomb.carrier(): Player { val owner = owner() return if (owner > 0) clientDLL.uint(dwEntityList + ((owner and 0xFFF) - 1L) * 0x10) else 0 } internal fun Bomb.planter(): Player = clientDLL.uint(dwEntityList + (carrier() * ENTITY_SIZE)) internal fun Bomb.location(): String = csgoEXE.read(planter() + szLastPlaceName, 32, true)?.getString(0) ?: ""
agpl-3.0
09ea2c7379795e2f3ea1e6a06319bfa3
41.86
116
0.763772
3.59396
false
false
false
false
paoloach/zdomus
cs5463/app/src/main/java/it/achdjian/paolo/cs5463/CommandFragment.kt
1
2399
package it.achdjian.paolo.cs5463 import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.RadioButton import it.achdjian.paolo.cs5463.Constants.CLUSTER_ELECTRICAL_MEASUREMENT import it.achdjian.paolo.cs5463.domusEngine.DomusEngine /** * Created by Paolo Achdjian on 12/28/17. */ class CommandFragment : Fragment() { var cmd:Int = 0 var cluster:Int=CLUSTER_ELECTRICAL_MEASUREMENT override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.command, container, false) val button = rootView.findViewById<Button>(R.id.execute) button.setOnClickListener { val data =ViewModelProviders.of(this.activity).get(SmartPlugViewModel::class.java).smartPlug.value if (data != null) { DomusEngine.postCmd(data.networkAddress, data.endpoint, cluster, cmd) } } rootView.findViewById<RadioButton>(R.id.calibrateVDC).setOnClickListener { cmd = 0x10;cluster=Constants.CLUSTER_ELECTRICAL_MEASUREMENT } rootView.findViewById<RadioButton>(R.id.calibrateIDC).setOnClickListener { cmd = 0x11;cluster=Constants.CLUSTER_ELECTRICAL_MEASUREMENT } rootView.findViewById<RadioButton>(R.id.calibrateVAC).setOnClickListener { cmd = 0x12;cluster=Constants.CLUSTER_ELECTRICAL_MEASUREMENT } rootView.findViewById<RadioButton>(R.id.calibrateIAC).setOnClickListener { cmd = 0x13;cluster=Constants.CLUSTER_ELECTRICAL_MEASUREMENT } rootView.findViewById<RadioButton>(R.id.startMeasure).setOnClickListener { cmd = 0x16;cluster=Constants.CLUSTER_ELECTRICAL_MEASUREMENT } rootView.findViewById<RadioButton>(R.id.clearStatus).setOnClickListener { cmd = 0x17;cluster=Constants.CLUSTER_ELECTRICAL_MEASUREMENT } rootView.findViewById<RadioButton>(R.id.reset).setOnClickListener { cmd = 0x18;cluster=Constants.CLUSTER_ELECTRICAL_MEASUREMENT } rootView.findViewById<RadioButton>(R.id.togle).setOnClickListener { cmd = 2;cluster=Constants.ON_OFF_CLUSTER } return rootView } companion object { fun newInstance() = CommandFragment() } }
gpl-2.0
99194240204a8809d17e13051ff59721
52.333333
144
0.746144
4.038721
false
false
false
false
EMResearch/EvoMaster
core/src/test/kotlin/org/evomaster/core/output/TestCaseWriterTest.kt
1
52903
package org.evomaster.core.output import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType import org.evomaster.core.EMConfig import org.evomaster.core.TestUtils import org.evomaster.core.database.DbAction import org.evomaster.core.database.DbActionGeneBuilder import org.evomaster.core.database.DbActionResult import org.evomaster.core.database.schema.Column import org.evomaster.core.database.schema.ColumnDataType.* import org.evomaster.core.database.schema.ForeignKey import org.evomaster.core.database.schema.Table import org.evomaster.core.output.EvaluatedIndividualBuilder.Companion.buildResourceEvaluatedIndividual import org.evomaster.core.output.service.PartialOracles import org.evomaster.core.output.service.RestTestCaseWriter import org.evomaster.core.problem.rest.* import org.evomaster.core.search.EvaluatedIndividual import org.evomaster.core.search.FitnessValue import org.evomaster.core.search.gene.* import org.evomaster.core.search.gene.datetime.DateGene import org.evomaster.core.search.gene.sql.SqlAutoIncrementGene import org.evomaster.core.search.gene.sql.SqlForeignKeyGene import org.evomaster.core.search.gene.sql.SqlPrimaryKeyGene import org.evomaster.core.search.gene.UUIDGene import org.evomaster.core.search.gene.numeric.IntegerGene import org.evomaster.core.search.gene.string.StringGene import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import javax.ws.rs.core.MediaType class TestCaseWriterTest { //TODO: BMR- changed the tests to not use expectationsActive. This may require updating. private fun getConfig(format: OutputFormat): EMConfig { val config = EMConfig() config.outputFormat = format config.expectationsActive = false config.testTimeout = -1 return config } @Test fun testEmptyDbInitialization() { val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(emptyList<DbAction>().toMutableList()) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testOneAction() { val aColumn = Column("aColumn", VARCHAR, 10, databaseType = DatabaseType.H2) val aTable = Table("myTable", setOf(aColumn), HashSet<ForeignKey>()) val id = 0L val gene = StringGene(aColumn.name, "stringValue", 0, 12) val insertIntoTableAction = DbAction(aTable, setOf(aColumn), id, mutableListOf(gene)) val dbInitialization = mutableListOf(insertIntoTableAction) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(dbInitialization) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"myTable\", 0L)") indent() indent() add(".d(\"aColumn\", \"\\\"stringValue\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } private fun buildEvaluatedIndividual(dbInitialization: MutableList<DbAction>): Triple<OutputFormat, String, EvaluatedIndividual<RestIndividual>> { val format = OutputFormat.JAVA_JUNIT_4 val baseUrlOfSut = "baseUrlOfSut" val sampleType = SampleType.RANDOM val restActions = emptyList<RestCallAction>().toMutableList() val individual = RestIndividual(restActions, sampleType, dbInitialization) TestUtils.doInitializeIndividualForTesting(individual) val fitnessVal = FitnessValue(0.0) val results = dbInitialization.map { DbActionResult().also { it.setInsertExecutionResult(true) } } val ei = EvaluatedIndividual(fitnessVal, individual, results) return Triple(format, baseUrlOfSut, ei) } @Test fun testTwoAction() { val aColumn = Column("aColumn", VARCHAR, 10, databaseType = DatabaseType.H2) val aTable = Table("myTable", setOf(aColumn), HashSet<ForeignKey>()) val gene0 = StringGene(aColumn.name, "stringValue0", 0, 16) val insertIntoTableAction0 = DbAction(aTable, setOf(aColumn), 0L, mutableListOf(gene0)) val gene1 = StringGene(aColumn.name, "stringValue1", 0, 16) val insertIntoTableAction1 = DbAction(aTable, setOf(aColumn), 1L, mutableListOf(gene1)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insertIntoTableAction0, insertIntoTableAction1)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"myTable\", 0L)") indent() indent() add(".d(\"aColumn\", \"\\\"stringValue0\\\"\")") deindent() add(".and().insertInto(\"myTable\", 1L)") indent() add(".d(\"aColumn\", \"\\\"stringValue1\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testTwoColumns() { val column0 = Column("Column0", VARCHAR, 10, databaseType = DatabaseType.H2) val column1 = Column("Column1", VARCHAR, 10, databaseType = DatabaseType.H2) val aTable = Table("myTable", setOf(column0, column1), HashSet<ForeignKey>()) val id = 0L val gene0 = StringGene(column0.name, "stringValue0", 0, 16) val gene1 = StringGene(column1.name, "stringValue1", 0, 16) val insertIntoTableAction = DbAction(aTable, setOf(column0, column1), id, mutableListOf(gene0, gene1)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insertIntoTableAction)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"myTable\", 0L)") indent() indent() add(".d(\"Column0\", \"\\\"stringValue0\\\"\")") add(".d(\"Column1\", \"\\\"stringValue1\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testIntegerColumn() { val idColumn = Column("Id", INTEGER, 10, primaryKey = false, databaseType = DatabaseType.H2) val nameColumn = Column("Name", VARCHAR, 10, primaryKey = false, databaseType = DatabaseType.H2) val aTable = Table("myTable", setOf(idColumn, nameColumn), HashSet<ForeignKey>()) val id = 0L val integerGene = IntegerGene(idColumn.name, 42, 0, 50) val stringGene = StringGene(nameColumn.name, "nameValue", 0, 10) val insertIntoTableAction = DbAction(aTable, setOf(idColumn, nameColumn), id, listOf(integerGene, stringGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insertIntoTableAction)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"myTable\", 0L)") indent() indent() add(".d(\"Id\", \"42\")") add(".d(\"Name\", \"\\\"nameValue\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testPrimaryKeyColumn() { val idColumn = Column("Id", INTEGER, 10, primaryKey = true, databaseType = DatabaseType.H2) val nameColumn = Column("Name", VARCHAR, 10, primaryKey = false, databaseType = DatabaseType.H2) val aTable = Table("myTable", setOf(idColumn, nameColumn), HashSet<ForeignKey>()) val id = 0L val integerGene = IntegerGene(idColumn.name, 42, 0, 100) val primaryKeyGene = SqlPrimaryKeyGene(idColumn.name, "myTable", integerGene, 10) val stringGene = StringGene(nameColumn.name, "nameValue", 0, 10) val insertIntoTableAction = DbAction(aTable, setOf(idColumn, nameColumn), id, listOf(primaryKeyGene, stringGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insertIntoTableAction)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"myTable\", 0L)") indent() indent() add(".d(\"Id\", \"42\")") add(".d(\"Name\", \"\\\"nameValue\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testForeignKeyColumn() { val idColumn = Column("Id", INTEGER, 10, primaryKey = true, databaseType = DatabaseType.H2) val table0 = Table("Table0", setOf(idColumn), HashSet<ForeignKey>()) val fkColumn = Column("fkId", INTEGER, 10, primaryKey = false, databaseType = DatabaseType.H2) val table1 = Table("Table1", setOf(idColumn, fkColumn), HashSet<ForeignKey>()) val pkGeneUniqueId = 12345L val integerGene = IntegerGene(idColumn.name, 42, 0, 100) val primaryKeyTable0Gene = SqlPrimaryKeyGene(idColumn.name, "Table0", integerGene, pkGeneUniqueId) val primaryKeyTable1Gene = SqlPrimaryKeyGene(idColumn.name, "Table1", integerGene, 10) val firstInsertionId = 1001L val insertIntoTable0 = DbAction(table0, setOf(idColumn), firstInsertionId, listOf(primaryKeyTable0Gene)) val secondInsertionId = 1002L val foreignKeyGene = SqlForeignKeyGene(fkColumn.name, secondInsertionId, "Table0", false, uniqueIdOfPrimaryKey = pkGeneUniqueId) val insertIntoTable1 = DbAction(table1, setOf(idColumn, fkColumn), secondInsertionId, listOf(primaryKeyTable1Gene, foreignKeyGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insertIntoTable0.copy() as DbAction, insertIntoTable1.copy() as DbAction)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 1001L)") indent() indent() add(".d(\"Id\", \"42\")") deindent() add(".and().insertInto(\"Table1\", 1002L)") indent() add(".d(\"Id\", \"42\")") add(".d(\"fkId\", \"42\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testBooleanColumn() { val aColumn = Column("aColumn", BOOLEAN, 10, databaseType = DatabaseType.H2) val aTable = Table("myTable", setOf(aColumn), HashSet<ForeignKey>()) val id = 0L val gene = BooleanGene(aColumn.name, false) val insertIntoTableAction = DbAction(aTable, setOf(aColumn), id, mutableListOf(gene)) val dbInitialization = mutableListOf(insertIntoTableAction) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(dbInitialization) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"myTable\", 0L)") indent() indent() add(".d(\"aColumn\", \"false\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testNullableForeignKeyColumn() { val idColumn = Column("Id", INTEGER, 10, primaryKey = true, databaseType = DatabaseType.H2) val table0 = Table("Table0", setOf(idColumn), HashSet<ForeignKey>()) val fkColumn = Column("fkId", INTEGER, 10, primaryKey = false, nullable = true, databaseType = DatabaseType.H2) val table1 = Table("Table1", setOf(idColumn, fkColumn), HashSet<ForeignKey>()) val integerGene = IntegerGene(idColumn.name, 42, 0, 100) val primaryKeyTable0Gene = SqlPrimaryKeyGene(idColumn.name, "Table0", integerGene, 10) val primaryKeyTable1Gene = SqlPrimaryKeyGene(idColumn.name, "Table1", integerGene, 10) val firstInsertionId = 1001L val insertIntoTable0 = DbAction(table0, setOf(idColumn), firstInsertionId, listOf(primaryKeyTable0Gene)) val secondInsertionId = 1002L val foreignKeyGene = SqlForeignKeyGene(fkColumn.name, secondInsertionId, "Table0", true, -1L) val insertIntoTable1 = DbAction(table1, setOf(idColumn, fkColumn), secondInsertionId, listOf(primaryKeyTable1Gene, foreignKeyGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insertIntoTable0.copy() as DbAction, insertIntoTable1.copy() as DbAction)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 1001L)") indent() indent() add(".d(\"Id\", \"42\")") deindent() deindent() indent() add(".and().insertInto(\"Table1\", 1002L)") indent() add(".d(\"Id\", \"42\")") add(".d(\"fkId\", \"NULL\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testTimeStampColumn() { val aColumn = Column("aColumn", TIMESTAMP, 10, databaseType = DatabaseType.H2) val aTable = Table("myTable", setOf(aColumn), HashSet<ForeignKey>()) val id = 0L val gene = DbActionGeneBuilder().buildSqlTimestampGene(aColumn.name) val insertIntoTableAction = DbAction(aTable, setOf(aColumn), id, mutableListOf(gene)) val dbInitialization = mutableListOf(insertIntoTableAction) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(dbInitialization) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"myTable\", 0L)") indent() indent() add(".d(\"aColumn\", \"\\\"2016-03-12 00:00:00\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testThreeAction() { val aColumn = Column("aColumn", VARCHAR, 10, databaseType = DatabaseType.H2) val aTable = Table("myTable", setOf(aColumn), HashSet<ForeignKey>()) val gene0 = StringGene(aColumn.name, "stringValue0", 0, 16) val insertIntoTableAction0 = DbAction(aTable, setOf(aColumn), 0L, mutableListOf(gene0)) val gene1 = StringGene(aColumn.name, "stringValue1", 0, 16) val insertIntoTableAction1 = DbAction(aTable, setOf(aColumn), 1L, mutableListOf(gene1)) val gene2 = StringGene(aColumn.name, "stringValue2", 0, 16) val insertIntoTableAction2 = DbAction(aTable, setOf(aColumn), 2L, mutableListOf(gene2)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insertIntoTableAction0, insertIntoTableAction1, insertIntoTableAction2)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"myTable\", 0L)") indent() indent() add(".d(\"aColumn\", \"\\\"stringValue0\\\"\")") deindent() add(".and().insertInto(\"myTable\", 1L)") indent() add(".d(\"aColumn\", \"\\\"stringValue1\\\"\")") deindent() add(".and().insertInto(\"myTable\", 2L)") indent() add(".d(\"aColumn\", \"\\\"stringValue2\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testTimeStampForeignKeyColumn() { val idColumn = Column("Id", TIMESTAMP, 10, primaryKey = true, databaseType = DatabaseType.H2) val table0 = Table("Table0", setOf(idColumn), HashSet<ForeignKey>()) val fkColumn = Column("fkId", TIMESTAMP, 10, primaryKey = false, databaseType = DatabaseType.H2) val table1 = Table("Table1", setOf(idColumn, fkColumn), HashSet<ForeignKey>()) val pkGeneUniqueId = 12345L val timeStampGene = DbActionGeneBuilder().buildSqlTimestampGene(idColumn.name) val primaryKeyTable0Gene = SqlPrimaryKeyGene(idColumn.name, "Table0", timeStampGene, pkGeneUniqueId) val primaryKeyTable1Gene = SqlPrimaryKeyGene(idColumn.name, "Table1", timeStampGene, 10) val firstInsertionId = 1001L val insertIntoTable0 = DbAction(table0, setOf(idColumn), firstInsertionId, listOf(primaryKeyTable0Gene)) val secondInsertionId = 1002L val foreignKeyGene = SqlForeignKeyGene(fkColumn.name, secondInsertionId, "Table0", false, pkGeneUniqueId) val insertIntoTable1 = DbAction(table1, setOf(idColumn, fkColumn), secondInsertionId, listOf(primaryKeyTable1Gene, foreignKeyGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insertIntoTable0.copy() as DbAction, insertIntoTable1.copy() as DbAction)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 1001L)") indent() indent() add(".d(\"Id\", \"\\\"2016-03-12 00:00:00\\\"\")") deindent() add(".and().insertInto(\"Table1\", 1002L)") indent() add(".d(\"Id\", \"\\\"2016-03-12 00:00:00\\\"\")") add(".d(\"fkId\", \"\\\"2016-03-12 00:00:00\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testIndirectForeignKeyColumn() { val table0_Id = Column("Id", INTEGER, 10, primaryKey = true, autoIncrement = true, databaseType = DatabaseType.H2) val table0 = Table("Table0", setOf(table0_Id), HashSet<ForeignKey>()) val table1_Id = Column("Id", INTEGER, 10, primaryKey = true, foreignKeyToAutoIncrement = true, databaseType = DatabaseType.H2) val table1 = Table("Table1", setOf(table1_Id), HashSet<ForeignKey>()) val table2_Id = Column("Id", INTEGER, 10, primaryKey = true, foreignKeyToAutoIncrement = true, databaseType = DatabaseType.H2) val table2 = Table("Table2", setOf(table2_Id), HashSet<ForeignKey>()) val insertId0 = 1001L val autoGene = SqlAutoIncrementGene(table0_Id.name) val pkGene0 = SqlPrimaryKeyGene(table0_Id.name, "Table0", autoGene, insertId0) val insert0 = DbAction(table0, setOf(table0_Id), insertId0, listOf(pkGene0)) val insertId1 = 1002L val fkGene0 = SqlForeignKeyGene(table1_Id.name, insertId1, "Table0", false, insertId0) val pkGene1 = SqlPrimaryKeyGene(table1_Id.name, "Table1", fkGene0, insertId1) val insert1 = DbAction(table1, setOf(table1_Id), insertId1, listOf(pkGene1)) val insertId2 = 1003L val fkGene1 = SqlForeignKeyGene(table2_Id.name, insertId2, "Table1", false, insertId1) val pkGene2 = SqlPrimaryKeyGene(table2_Id.name, "Table2", fkGene1, insertId2) val insert2 = DbAction(table2, setOf(table2_Id), insertId2, listOf(pkGene2)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert0, insert1, insert2)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 1001L)") indent() add(".and().insertInto(\"Table1\", 1002L)") indent() add(".r(\"Id\", 1001L)") deindent() add(".and().insertInto(\"Table2\", 1003L)") indent() add(".r(\"Id\", 1002L)") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testInsertDateColumnType() { val idColumn = Column("Id", INTEGER, 10, primaryKey = true, autoIncrement = true, databaseType = DatabaseType.H2) val dateColumn = Column("birthDate", DATE, 10, primaryKey = false, autoIncrement = false, databaseType = DatabaseType.H2) val table = Table("Table0", setOf(idColumn, dateColumn), HashSet<ForeignKey>()) val autoGene = SqlAutoIncrementGene(table.name) val pkGene0 = SqlPrimaryKeyGene(idColumn.name, "Table0", autoGene, 10) val dateGene = DateGene(dateColumn.name) val insert = DbAction(table, setOf(idColumn, dateColumn), 0L, listOf(pkGene0, dateGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)") indent() indent() add(".d(\"birthDate\", \"\\\"2016-03-12\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testUUIDColumnType() { val idColumn = Column("Id", INTEGER, 10, primaryKey = true, autoIncrement = true, databaseType = DatabaseType.H2) val uuidColumn = Column("uuidCode", UUID, 10, primaryKey = false, autoIncrement = false, databaseType = DatabaseType.H2) val table = Table("Table0", setOf(idColumn, uuidColumn), HashSet<ForeignKey>()) val autoGene = SqlAutoIncrementGene(table.name) val pkGene0 = SqlPrimaryKeyGene(idColumn.name, "Table0", autoGene, 10) val uuidGene = UUIDGene(uuidColumn.name) val insert = DbAction(table, setOf(idColumn, uuidColumn), 0L, listOf(pkGene0, uuidGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)") indent() indent() add(".d(\"uuidCode\", \"\\\"00000000-0000-0000-0000-000000000000\\\"\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testJSONBEmpty() { val idColumn = Column("Id", INTEGER, 10, primaryKey = true, autoIncrement = true, databaseType = DatabaseType.POSTGRES) val jsonbColumn = Column("jsonbColumn", JSONB, 10, primaryKey = false, autoIncrement = false, databaseType = DatabaseType.POSTGRES) val table = Table("Table0", setOf(idColumn, jsonbColumn), HashSet<ForeignKey>()) val autoGene = SqlAutoIncrementGene(table.name) val pkGene0 = SqlPrimaryKeyGene(idColumn.name, "Table0", autoGene, 10) val objectGene = ObjectGene(jsonbColumn.name, listOf()) val insert = DbAction(table, setOf(idColumn, jsonbColumn), 0L, listOf(pkGene0, objectGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)") indent() indent() add(".d(\"jsonbColumn\", \"'{}'\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testJSONBColumnType() { val idColumn = Column("Id", INTEGER, 10, primaryKey = true, autoIncrement = true, databaseType = DatabaseType.POSTGRES) val jsonbColumn = Column("jsonbColumn", JSONB, 10, primaryKey = false, autoIncrement = false, databaseType = DatabaseType.POSTGRES) val table = Table("Table0", setOf(idColumn, jsonbColumn), HashSet<ForeignKey>()) val autoGene = SqlAutoIncrementGene(table.name) val pkGene0 = SqlPrimaryKeyGene(idColumn.name, "Table0", autoGene, 10) val objectGene = ObjectGene(jsonbColumn.name, listOf(IntegerGene("integerField"))) val insert = DbAction(table, setOf(idColumn, jsonbColumn), 0L, listOf(pkGene0, objectGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)") indent() indent() add(".d(\"jsonbColumn\", \"'{\\\"integerField\\\":0}'\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testJSONBoolean() { val idColumn = Column("Id", INTEGER, 10, primaryKey = true, autoIncrement = true, databaseType = DatabaseType.POSTGRES) val jsonbColumn = Column("jsonbColumn", JSONB, 10, primaryKey = false, autoIncrement = false, databaseType = DatabaseType.POSTGRES) val table = Table("Table0", setOf(idColumn, jsonbColumn), HashSet<ForeignKey>()) val autoGene = SqlAutoIncrementGene(table.name) val pkGene0 = SqlPrimaryKeyGene(idColumn.name, "Table0", autoGene, 10) val objectGene = ObjectGene(jsonbColumn.name, listOf(BooleanGene("booleanField"))) val insert = DbAction(table, setOf(idColumn, jsonbColumn), 0L, listOf(pkGene0, objectGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)") indent() indent() add(".d(\"jsonbColumn\", \"'{\\\"booleanField\\\":true}'\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testJSONString() { val idColumn = Column("Id", INTEGER, 10, primaryKey = true, autoIncrement = true, databaseType = DatabaseType.POSTGRES) val jsonbColumn = Column("jsonbColumn", JSONB, 10, primaryKey = false, autoIncrement = false, databaseType = DatabaseType.POSTGRES) val table = Table("Table0", setOf(idColumn, jsonbColumn), HashSet<ForeignKey>()) val autoGene = SqlAutoIncrementGene(table.name) val pkGene0 = SqlPrimaryKeyGene(idColumn.name, "Table0", autoGene, 10) val objectGene = ObjectGene(jsonbColumn.name, listOf(StringGene("stringField"))) val insert = DbAction(table, setOf(idColumn, jsonbColumn), 0L, listOf(pkGene0, objectGene)) val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert)) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)") indent() indent() add(".d(\"jsonbColumn\", \"'{\\\"stringField\\\":\\\"foo\\\"}'\")") deindent() add(".dtos();") deindent() add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } @Test fun testVarGeneration(){ //TODO: this needs a rename val format = OutputFormat.JAVA_JUNIT_4 val baseUrlOfSut = "baseUrlOfSut" val sampleType = SampleType.RANDOM val action = RestCallAction("1", HttpVerb.GET, RestPath(""), mutableListOf()) val restActions = listOf(action).toMutableList() val individual = RestIndividual(restActions, sampleType) TestUtils.doInitializeIndividualForTesting(individual) val fitnessVal = FitnessValue(0.0) val result = RestCallResult() result.setTimedout(timedout = true) val results = listOf(result) val ei = EvaluatedIndividual<RestIndividual>(fitnessVal, individual, results) val config = getConfig(format) config.expectationsActive = true val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = Lines().apply { add("@Test") add("public void test() throws Exception {") indent() add("") add("try{") indent() add("given().accept(\"*/*\")") indent() indent() add(".get(baseUrlOfSut + \"\");") deindent() deindent() deindent() add("} catch(Exception e){") add("}") deindent() add("}") } assertEquals(expectedLines.toString(), lines.toString()) } /* fun testResultValue(){ val objectGene = ObjectGene("Object", listOf(StringGene("stringField"))) val format = OutputFormat.JAVA_JUNIT_4 val baseUrlOfSut = "baseUrlOfSut" val sampleType = SampleType.RANDOM val restActions = emptyList<RestAction>().toMutableList() val individual = RestIndividual(restActions, sampleType, dbInitialization) val fitnessVal = FitnessValue(0.0) val results = emptyList<ActionResult>().toMutableList() val ei = EvaluatedIndividual<RestIndividual>(fitnessVal, individual, results) } */ @Test fun testDbInBetween() { val fooId = Column("Id", INTEGER, 10, primaryKey = true, databaseType = DatabaseType.H2) val foo = Table("Foo", setOf(fooId), setOf()) val fkId = Column("fkId", INTEGER, 10, primaryKey = false, databaseType = DatabaseType.H2) val bar = Table("Bar", setOf(fooId, fkId), setOf()) val pkGeneUniqueId = 12345L val integerGene = IntegerGene(fooId.name, 42, 0, 100) val pkFoo = SqlPrimaryKeyGene(fooId.name, "Foo", integerGene, pkGeneUniqueId) val pkBar = SqlPrimaryKeyGene(fooId.name, "Bar", integerGene, 10) val fooInsertionId = 1001L val fooInsertion = DbAction(foo, setOf(fooId), fooInsertionId, listOf(pkFoo)) val barInsertionId = 1002L val foreignKeyGene = SqlForeignKeyGene(fkId.name, barInsertionId, "Foo", false, uniqueIdOfPrimaryKey = pkGeneUniqueId) val barInsertion = DbAction(bar, setOf(fooId, fkId), barInsertionId, listOf(pkBar, foreignKeyGene)) val fooAction = RestCallAction("1", HttpVerb.GET, RestPath("/foo"), mutableListOf()) val barAction = RestCallAction("2", HttpVerb.GET, RestPath("/bar"), mutableListOf()) val (format, baseUrlOfSut, ei) = buildResourceEvaluatedIndividual( dbInitialization = mutableListOf(), groups = mutableListOf( (mutableListOf(fooInsertion.copy() as DbAction) to mutableListOf(fooAction.copy() as RestCallAction)), (mutableListOf(barInsertion.copy() as DbAction) to mutableListOf(barAction.copy() as RestCallAction)) ) ) val config = getConfig(format) config.expectationsActive = false config.resourceSampleStrategy = EMConfig.ResourceSamplingStrategy.ConArchive config.probOfApplySQLActionToCreateResources=0.1 val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = """ @Test public void test() throws Exception { List<InsertionDto> insertions0 = sql().insertInto("Foo", 1001L) .d("Id", "42") .dtos(); InsertionResultsDto insertions0result = controller.execInsertionsIntoDatabase(insertions0); try{ given().accept("*/*") .get(baseUrlOfSut + "/foo"); } catch(Exception e){ } List<InsertionDto> insertions1 = sql(insertions0).insertInto("Bar", 1002L) .d("Id", "42") .d("fkId", "42") .dtos(); InsertionResultsDto insertions1result = controller.execInsertionsIntoDatabase(insertions1, insertions0result); try{ given().accept("*/*") .get(baseUrlOfSut + "/bar"); } catch(Exception e){ } } """.trimIndent() assertEquals(expectedLines, lines.toString()) } @Test fun testDbInBetweenSkipFailure() { val fooId = Column("Id", INTEGER, 10, primaryKey = true, databaseType = DatabaseType.H2) val foo = Table("Foo", setOf(fooId), setOf()) val fkId = Column("fkId", INTEGER, 10, primaryKey = false, databaseType = DatabaseType.H2) val bar = Table("Bar", setOf(fooId, fkId), setOf()) val pkGeneUniqueId = 12345L val integerGene = IntegerGene(fooId.name, 42, 0, 100) val pkFoo = SqlPrimaryKeyGene(fooId.name, "Foo", integerGene, pkGeneUniqueId) val pkBar = SqlPrimaryKeyGene(fooId.name, "Bar", integerGene, 10) val fooInsertionId = 1001L val fooInsertion = DbAction(foo, setOf(fooId), fooInsertionId, listOf(pkFoo)) val barInsertionId = 1002L val foreignKeyGene = SqlForeignKeyGene(fkId.name, barInsertionId, "Foo", false, uniqueIdOfPrimaryKey = pkGeneUniqueId) val barInsertion = DbAction(bar, setOf(fooId, fkId), barInsertionId, listOf(pkBar, foreignKeyGene)) val fooAction = RestCallAction("1", HttpVerb.GET, RestPath("/foo"), mutableListOf()) val barAction = RestCallAction("2", HttpVerb.GET, RestPath("/bar"), mutableListOf()) val groups = mutableListOf( (mutableListOf(fooInsertion.copy() as DbAction) to mutableListOf(fooAction.copy() as RestCallAction)), (mutableListOf(barInsertion.copy() as DbAction) to mutableListOf(barAction.copy() as RestCallAction)) ) val (format, baseUrlOfSut, ei) = buildResourceEvaluatedIndividual( dbInitialization = mutableListOf(), groups = groups ) val fooInsertionResult = ei.seeResults(groups[0].first) assertEquals(1, fooInsertionResult.size) assertTrue(fooInsertionResult[0] is DbActionResult) (fooInsertionResult[0] as DbActionResult).setInsertExecutionResult(false) val config = getConfig(format) config.resourceSampleStrategy = EMConfig.ResourceSamplingStrategy.ConArchive config.probOfApplySQLActionToCreateResources=0.1 config.skipFailureSQLInTestFile = true val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = """ @Test public void test() throws Exception { try{ given().accept("*/*") .get(baseUrlOfSut + "/foo"); } catch(Exception e){ } List<InsertionDto> insertions1 = sql().insertInto("Bar", 1002L) .d("Id", "42") .d("fkId", "42") .dtos(); InsertionResultsDto insertions1result = controller.execInsertionsIntoDatabase(insertions1); try{ given().accept("*/*") .get(baseUrlOfSut + "/bar"); } catch(Exception e){ } } """.trimIndent() assertEquals(expectedLines, lines.toString()) } @Test fun testDbInBetweenWithEmptyDb() { val fooAction = RestCallAction("1", HttpVerb.GET, RestPath("/foo"), mutableListOf()) val barAction = RestCallAction("2", HttpVerb.GET, RestPath("/bar"), mutableListOf()) val (format, baseUrlOfSut, ei) = buildResourceEvaluatedIndividual( dbInitialization = mutableListOf(), groups = mutableListOf( (mutableListOf<DbAction>() to mutableListOf(fooAction)), (mutableListOf<DbAction>() to mutableListOf(barAction)) ) ) val config = getConfig(format) config.resourceSampleStrategy = EMConfig.ResourceSamplingStrategy.ConArchive config.probOfApplySQLActionToCreateResources=0.1 val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = """ @Test public void test() throws Exception { try{ given().accept("*/*") .get(baseUrlOfSut + "/foo"); } catch(Exception e){ } try{ given().accept("*/*") .get(baseUrlOfSut + "/bar"); } catch(Exception e){ } } """.trimIndent() assertEquals(expectedLines, lines.toString()) } @Test fun testTestWithObjectAssertion(){ val fooAction = RestCallAction("1", HttpVerb.GET, RestPath("/foo"), mutableListOf()) val fooResult = RestCallResult() fooResult.setStatusCode(200) fooResult.setBody(""" [ {}, { "id":"foo", "properties":[ {}, { "name":"mapProperty1", "type":"string", "value":"one" }, { "name":"mapProperty2", "type":"string", "value":"two" }], "empty":{} } ] """.trimIndent()) fooResult.setBodyType(MediaType.APPLICATION_JSON_TYPE) val (format, baseUrlOfSut, ei) = buildResourceEvaluatedIndividual( dbInitialization = mutableListOf(), groups = mutableListOf( (mutableListOf<DbAction>() to mutableListOf(fooAction)) ), results = mutableListOf(fooResult), format = OutputFormat.JS_JEST ) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = """ test("test", async () => { const res_0 = await superagent .get(baseUrlOfSut + "/foo").set('Accept', "*/*") .ok(res => res.status); expect(res_0.status).toBe(200); expect(res_0.header["content-type"].startsWith("application/json")).toBe(true); expect(res_0.body.length).toBe(2); expect(Object.keys(res_0.body[0]).length).toBe(0); expect(res_0.body[1].properties.length).toBe(3); expect(Object.keys(res_0.body[1].properties[0]).length).toBe(0); expect(res_0.body[1].properties[1].name).toBe("mapProperty1"); expect(res_0.body[1].properties[1].type).toBe("string"); expect(res_0.body[1].properties[1].value).toBe("one"); expect(res_0.body[1].properties[2].name).toBe("mapProperty2"); expect(res_0.body[1].properties[2].type).toBe("string"); expect(res_0.body[1].properties[2].value).toBe("two"); expect(Object.keys(res_0.body[1].empty).length).toBe(0); }); """.trimIndent() assertEquals(expectedLines, lines.toString()) } @Test fun testTestWithObjectLengthAssertion(){ val fooAction = RestCallAction("1", HttpVerb.GET, RestPath("/foo"), mutableListOf()) val fooResult = RestCallResult() fooResult.setStatusCode(200) fooResult.setBody(""" { "p1":{}, "p2":{ "id":"foo", "properties":[ {}, { "name":"mapProperty1", "type":"string", "value":"one" }, { "name":"mapProperty2", "type":"string", "value":"two" }], "empty":{} } } """.trimIndent()) fooResult.setBodyType(MediaType.APPLICATION_JSON_TYPE) val (format, baseUrlOfSut, ei) = buildResourceEvaluatedIndividual( dbInitialization = mutableListOf(), groups = mutableListOf( (mutableListOf<DbAction>() to mutableListOf(fooAction)) ), results = mutableListOf(fooResult), format = OutputFormat.JS_JEST ) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = """ test("test", async () => { const res_0 = await superagent .get(baseUrlOfSut + "/foo").set('Accept', "*/*") .ok(res => res.status); expect(res_0.status).toBe(200); expect(res_0.header["content-type"].startsWith("application/json")).toBe(true); expect(Object.keys(res_0.body.p1).length).toBe(0); expect(res_0.body.p2.properties.length).toBe(3); expect(Object.keys(res_0.body.p2.properties[0]).length).toBe(0); expect(res_0.body.p2.properties[1].name).toBe("mapProperty1"); expect(res_0.body.p2.properties[1].type).toBe("string"); expect(res_0.body.p2.properties[1].value).toBe("one"); expect(res_0.body.p2.properties[2].name).toBe("mapProperty2"); expect(res_0.body.p2.properties[2].type).toBe("string"); expect(res_0.body.p2.properties[2].value).toBe("two"); expect(Object.keys(res_0.body.p2.empty).length).toBe(0); }); """.trimIndent() assertEquals(expectedLines, lines.toString()) } @Test fun testApplyAssertionEscapes(){ val fooAction = RestCallAction("1", HttpVerb.GET, RestPath("/foo"), mutableListOf()) val fooResult = RestCallResult() val email = "[email protected]" fooResult.setStatusCode(200) fooResult.setBody(""" { "email":$email } """.trimIndent()) fooResult.setBodyType(MediaType.APPLICATION_JSON_TYPE) val (format, baseUrlOfSut, ei) = buildResourceEvaluatedIndividual( dbInitialization = mutableListOf(), groups = mutableListOf( (mutableListOf<DbAction>() to mutableListOf(fooAction)) ), results = mutableListOf(fooResult), format = OutputFormat.JS_JEST ) val config = getConfig(format) val test = TestCase(test = ei, name = "test") val writer = RestTestCaseWriter(config, PartialOracles()) val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut) val expectedLines = """ test("test", async () => { const res_0 = await superagent .get(baseUrlOfSut + "/foo").set('Accept', "*/*") .ok(res => res.status); expect(res_0.status).toBe(200); expect(res_0.header["content-type"].startsWith("application/json")).toBe(true); expect(res_0.body.email).toBe("$email"); }); """.trimIndent() assertEquals(expectedLines, lines.toString()) } }
lgpl-3.0
4270ff4eff46a4b63809424a2a2b8765
36.814868
154
0.604767
4.699147
false
true
false
false
DR-YangLong/spring-boot-kotlin-demo
src/main/kotlin/site/yanglong/promotion/service/impl/UserServiceImpl.kt
1
1758
package site.yanglong.promotion.service.impl import com.baomidou.mybatisplus.mapper.EntityWrapper import com.baomidou.mybatisplus.plugins.Page import com.baomidou.mybatisplus.service.impl.ServiceImpl import org.springframework.stereotype.Service import site.yanglong.promotion.mapper.UserBaseMapper import site.yanglong.promotion.model.UserBase import site.yanglong.promotion.model.dto.UserPermissions import site.yanglong.promotion.service.UserService /** * package: site.yanglong.promotion.service.impl <br/> * functional describe:implement user-service interface * * @author DR.YangLong [[email protected]] * @version 1.0 2017/7/13 */ @Service class UserServiceImpl : ServiceImpl<UserBaseMapper, UserBase>(), UserService { override fun findByName(name: String, page: Int, size: Int): List<UserBase> { val wrapper: EntityWrapper<UserBase> = EntityWrapper<UserBase>() wrapper.like("userName", name) return baseMapper.selectPage(Page<UserBase>(page, size), wrapper) } //乐观锁,不用事务 override fun updateByOptimisticLock(user: UserBase): Boolean { if (user.userId == null) return false val userBase: UserBase? = baseMapper.selectById(user.userId) if (null != userBase) { val version: Long? = userBase.lockVersion user.lockVersion = version return baseMapper.updateById(user) > 0 } return false } override fun listUserPermissions(userId: Long): UserPermissions { var permissions = UserPermissions() val perms = baseMapper.selectPerms(userId) val roles = baseMapper.selectRoles(userId) permissions.perms = perms permissions.roles = roles return permissions } }
apache-2.0
e7e59c59171c20c6488855446ede57db
35.3125
81
0.716418
4.118203
false
false
false
false
badoualy/kotlogram
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/transport/MTProtoTcpConnection.kt
1
6004
package com.github.badoualy.telegram.mtproto.transport import com.github.badoualy.telegram.tl.ByteBufferUtils.* import org.slf4j.LoggerFactory import org.slf4j.MarkerFactory import java.io.IOException import java.net.ConnectException import java.net.InetSocketAddress import java.net.StandardSocketOptions import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.SelectionKey import java.nio.channels.Selector import java.nio.channels.SocketChannel import java.util.concurrent.TimeUnit internal class MTProtoTcpConnection @Throws(IOException::class) @JvmOverloads constructor(override val ip: String, override val port: Int, tag: String, abridgedProtocol: Boolean = true) : MTProtoConnection { private val ATTEMPT_COUNT = 3 override var tag: String = tag set(value) { field = value marker = MarkerFactory.getMarker(tag) } override var marker = MarkerFactory.getMarker(tag)!! private set private var socketChannel: SocketChannel private val msgHeaderBuffer = ByteBuffer.allocate(1) private val msgLengthBuffer = ByteBuffer.allocate(3) private var selectionKey: SelectionKey? = null init { var attempt = 1 do { socketChannel = SocketChannel.open() socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true) //socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true) socketChannel.configureBlocking(true) try { socketChannel.connect(InetSocketAddress(ip, port)) socketChannel.finishConnect() if (abridgedProtocol) { // @see https://core.telegram.org/mtproto/samples-auth_key logger.info(marker, "Using abridged protocol") socketChannel.write(ByteBuffer.wrap(byteArrayOf(0xef.toByte()))) } logger.info(marker, "Connected to $ip:$port") break } catch(e: Exception) { logger.error(marker, "Failed to connect", e) try { socketChannel.close() } catch (e: Exception) { } } Thread.sleep(TimeUnit.SECONDS.toMillis(2)) if (attempt == ATTEMPT_COUNT) throw ConnectException("Failed to join Telegram server at $ip:$port") } while (attempt++ < ATTEMPT_COUNT) } @Throws(IOException::class) override fun readMessage(): ByteArray { /* (0x01..0x7e = data length divided by 4; or 0x7f followed by 3 length bytes (little endian) divided by 4) */ // Read message length var length = readByteAsInt(readBytes(1, msgHeaderBuffer)) if (length == 0x7f) length = readInt24(readBytes(3, msgLengthBuffer)) logger.debug(marker, "About to read a message of length ${length * 4}") val buffer = readBytes(length * 4) // TODO: fix to return ByteBuffer val bytes = ByteArray(buffer.remaining()) buffer.get(bytes, 0, buffer.remaining()) return bytes } @Throws(IOException::class) override fun writeMessage(request: ByteArray) { val length = request.size / 4 val headerLength = if (length >= 127) 4 else 1 val totalLength = request.size + headerLength val buffer = ByteBuffer.allocate(totalLength) /* There is an abridged version of the same protocol: if the client sends 0xef as the first byte (**important:** only prior to the very first data packet), then packet length is encoded by a single byte (0x01..0x7e = data length divided by 4; or 0x7f followed by 3 length bytes (little endian) divided by 4) followed by the data themselves (sequence number and CRC32 not added). In this case, server responses look the same (the server does not send 0xef as the first byte). */ if (headerLength == 4) { writeByte(127, buffer) writeInt24(length, buffer) } else { writeByte(length, buffer) } buffer.put(request) buffer.flip() writeBytes(buffer) } @Throws(IOException::class) override fun executeMethod(request: ByteArray): ByteArray { writeMessage(request) return readMessage() } override fun register(selector: Selector): SelectionKey { socketChannel.configureBlocking(false) selectionKey = socketChannel.register(selector, SelectionKey.OP_READ) return selectionKey!! } override fun unregister(): SelectionKey? { val selector = selectionKey?.selector() selectionKey?.cancel() selector?.wakeup() socketChannel.configureBlocking(true) // Default mode return selectionKey } override fun setBlocking(blocking: Boolean) = socketChannel.configureBlocking(blocking)!! @Throws(IOException::class) override fun close() { logger.debug(marker, "Closing connection") socketChannel.close() } override fun isOpen() = socketChannel.isOpen && socketChannel.isConnected private fun readBytes(length: Int, recycledBuffer: ByteBuffer? = null, order: ByteOrder = ByteOrder.BIG_ENDIAN): ByteBuffer { recycledBuffer?.clear() val buffer = recycledBuffer ?: ByteBuffer.allocate(length) buffer.order(order) var totalRead = 0 while (totalRead < length) { val read = socketChannel.read(buffer) if (read == -1) throw IOException("Reached end-of-stream") totalRead += read } buffer.flip() return buffer } private fun writeBytes(buffer: ByteBuffer) { while (buffer.hasRemaining()) socketChannel.write(buffer) } companion object { private val logger = LoggerFactory.getLogger(MTProtoTcpConnection::class.java) } }
mit
cefd65fbaf5c7f8e8a28d27beb6b6527
33.705202
143
0.636742
4.720126
false
false
false
false
diareuse/mCache
app/src/main/java/wiki/depasquale/mcachepreview/User.kt
1
2525
package wiki.depasquale.mcachepreview import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * diareuse on 26.03.2017 */ class User { @SerializedName("login") @Expose var login: String? = null @SerializedName("id") @Expose var id: Int? = null @SerializedName("avatar_url") @Expose var avatarUrl: String? = null @SerializedName("gravatar_id") @Expose var gravatarId: String? = null @SerializedName("url") @Expose var url: String? = null @SerializedName("html_url") @Expose var htmlUrl: String? = null @SerializedName("followers_url") @Expose var followersUrl: String? = null @SerializedName("following_url") @Expose var followingUrl: String? = null @SerializedName("gists_url") @Expose var gistsUrl: String? = null @SerializedName("starred_url") @Expose var starredUrl: String? = null @SerializedName("subscriptions_url") @Expose var subscriptionsUrl: String? = null @SerializedName("organizations_url") @Expose var organizationsUrl: String? = null @SerializedName("repos_url") @Expose var reposUrl: String? = null @SerializedName("events_url") @Expose var eventsUrl: String? = null @SerializedName("received_events_url") @Expose var receivedEventsUrl: String? = null @SerializedName("type") @Expose var type: String? = null @SerializedName("site_admin") @Expose var siteAdmin: Boolean? = null @SerializedName("name") @Expose var name: String? = null @SerializedName("company") @Expose var company: String? = null @SerializedName("blog") @Expose var blog: String? = null @SerializedName("location") @Expose var location: String? = null @SerializedName("email") @Expose var email: String? = null @SerializedName("hireable") @Expose var hireable: Boolean? = null @SerializedName("bio") @Expose var bio: Any? = null @SerializedName("public_repos") @Expose var publicRepos: Int? = null @SerializedName("public_gists") @Expose var publicGists: Int? = null @SerializedName("followers") @Expose var followers: Int? = null @SerializedName("following") @Expose var following: Int? = null @SerializedName("created_at") @Expose var createdAt: String? = null @SerializedName("updated_at") @Expose var updatedAt: String? = null }
apache-2.0
2b49d0aaa2dc873eebda2290109b743e
23.278846
49
0.642772
4.059486
false
false
false
false
vjache/klips
src/main/java/org/klips/engine/rete/db/BetaNodeDB.kt
1
4627
package org.klips.engine.rete.db import org.klips.engine.rete.db.Serializer import org.klips.dsl.Facet.ConstFacet import org.klips.dsl.facet import org.klips.dsl.ref import org.klips.engine.Binding import org.klips.engine.ComposeBinding import org.klips.engine.Modification import org.klips.engine.Modification.Assert import org.klips.engine.Modification.Retire import org.klips.engine.SingletonBinding import org.klips.engine.query.BindingSet import org.klips.engine.query.SimpleMappedBindingSet import org.klips.engine.rete.BetaNode import org.klips.engine.rete.Node import org.klips.engine.util.putIfAbsent import org.klips.engine.util.to import java.util.* import java.util.concurrent.atomic.AtomicInteger @Suppress("UNCHECKED_CAST") class BetaNodeDB(strategy: StrategyOneDB, f1: Node, f2: Node) : BetaNode(strategy.log, f1, f2), BindingRepo { val rId by lazy { strategy.rIds.andIncrement } private val ids = AtomicInteger(0) // bindings ids private val bIdRef = ref<Int>("##BINDING_ID##") private val indexRefs = commonRefs.toList().plus(bIdRef) private val leftIndex: MutableMap<Binding, MutableSet<Binding>> by lazy { strategy.db.openMultiMap( "b-node_db_left_$rId", BindingComparator(indexRefs), BindingSerializerDB(indexRefs, strategy.tupleFactory), BindingSerializerDB(f1.refs, strategy.tupleFactory)) } private val rightIndex: MutableMap<Binding, MutableSet<Binding>> by lazy { strategy.db.openMultiMap( "b-node_db_right_$rId", BindingComparator(indexRefs), BindingSerializerDB(indexRefs, strategy.tupleFactory), BindingSerializerDB(f2.refs, strategy.tupleFactory)) } private val bindings: MutableMap<Int, Binding> by lazy { strategy.db.openMap( "b-node_db_cache_$rId", Comparator { t1, t2 -> t1 - t2 }, Serializer.INT, BindingSerializerDB(refs, strategy.tupleFactory)) } override fun fetchBinding(id: Int) = BindingDB(id, bindings[id]!!) val bindingsRev: MutableMap<Binding, Int> by lazy { strategy.db.openMap( "b-node_db_cache_rev_$rId", BindingComparator(refs), BindingSerializerDB(refs, strategy.tupleFactory), Serializer.INT) } override fun modifyIndex(source: Node, key: Binding, mdf: Modification<Binding>, hookModify:() -> Unit): Boolean { val bId = (mdf.arg as BindingDB).dbId val index = when (source) { left -> leftIndex right -> rightIndex else -> throw IllegalArgumentException("Bad source: $source") } return when(mdf){ is Assert -> { hookModify() index[key]!!.add(SingletonBinding(bIdRef to bId.facet)) } is Retire -> { val modified = index[key]!!.remove(SingletonBinding(bIdRef to bId.facet)) hookModify() modified } } } override fun lookupIndex(source: Node, key: Binding): BindingSet { return when (source) { left -> SimpleMappedBindingSet(left.refs, leftIndex[key]!!) { val bId = (it[bIdRef] as ConstFacet<Int>).value (left as BindingRepo).fetchBinding(bId) } right -> SimpleMappedBindingSet(right.refs, rightIndex[key]!!) { val bId = (it[bIdRef] as ConstFacet<Int>).value (right as BindingRepo).fetchBinding(bId) } else -> throw IllegalArgumentException("Bad source: $source") } } override fun composeBinding(source: Node, mdf: Modification<Binding>, cachedBinding: Binding): Binding { val binding = when (source) { left -> ComposeBinding(mdf.arg, cachedBinding) right -> ComposeBinding(cachedBinding, mdf.arg) else -> throw IllegalArgumentException() } val bId:Int when (mdf) { is Assert -> { bId = ids.andIncrement bindings.putIfAbsent(bId, binding)?.let { throw IllegalStateException() } bindingsRev.putIfAbsent(binding, bId) } is Retire -> { bId = bindingsRev.remove(binding)!! bindings.remove(bId) } else -> throw IllegalArgumentException() } return BindingDB(bId, binding) } }
apache-2.0
32ab4290875a50179c2c8566c5865d93
35.433071
109
0.604495
4.328344
false
false
false
false
gradle/gradle
build-logic/integration-testing/src/main/kotlin/gradlebuild/integrationtests/tasks/DistributionTest.kt
2
8167
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.integrationtests.tasks import gradlebuild.cleanup.services.CachesCleaner import gradlebuild.integrationtests.model.GradleDistribution import org.gradle.api.Named import org.gradle.api.Project import org.gradle.api.file.Directory import org.gradle.api.file.FileCollection import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.services.BuildService import org.gradle.api.tasks.Classpath import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.Nested import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.testing.Test import org.gradle.api.tasks.testing.TestListener import org.gradle.process.CommandLineArgumentProvider import org.gradle.work.DisableCachingByDefault import java.io.File import java.util.SortedSet /** * Tests that check the end-to-end behavior of a Gradle distribution. * They can have a locally built Gradle distribution on their runtime classpath * and distributions as well as local repositories as additional test inputs * to test functionality that requires rea distributions (like the wrapper) * or separately published libraries (like the Tooling API Jar). */ @DisableCachingByDefault(because = "Abstract super-class, not to be instantiated directly") abstract class DistributionTest : Test() { /** * To further categorize tests. (We should simplify this and get rid of the subclasses if possible) */ @get:Internal abstract val prefix: String /** * A local Gradle installation (unpacked distribution) to test against if the tests should fork a new Gradle process (non-embedded) */ @Internal val gradleInstallationForTest = GradleInstallationForTestEnvironmentProvider(project, this) /** * A 'normalized' distribution to test against if needed */ @Internal val normalizedDistributionZip = DistributionZipEnvironmentProvider(project, "normalized") /** * A 'bin' distribution to test - for integration tests testing the final distributions */ @Internal val binDistributionZip = DistributionZipEnvironmentProvider(project, "bin") /** * A 'all' distribution to test - for integration tests testing the final distributions */ @Internal val allDistributionZip = DistributionZipEnvironmentProvider(project, "all") /** * A 'docs' distribution to test - for integration tests testing the final distributions */ @Internal val docsDistributionZip = DistributionZipEnvironmentProvider(project, "docs") /** * A 'src' distribution to test - for integration tests testing the final distributions */ @Internal val srcDistributionZip = DistributionZipEnvironmentProvider(project, "src") /** * A local repository if needed by the tests (for Tooling API Jar or Kotlin DSL plugins) */ @Internal val localRepository = LocalRepositoryEnvironmentProvider(project) @get:Internal abstract val tracker: Property<BuildService<*>> @get:Internal abstract val cachesCleaner: Property<CachesCleaner> init { jvmArgumentProviders.add(gradleInstallationForTest) jvmArgumentProviders.add(localRepository) jvmArgumentProviders.add(normalizedDistributionZip) jvmArgumentProviders.add(binDistributionZip) jvmArgumentProviders.add(allDistributionZip) jvmArgumentProviders.add(docsDistributionZip) jvmArgumentProviders.add(srcDistributionZip) } override fun executeTests() { cachesCleaner.get().cleanUpCaches() if (tracker.isPresent) { val daemonTrackerService = tracker.get() val testListener = daemonTrackerService.javaClass.getMethod("newDaemonListener").invoke(daemonTrackerService) as TestListener addTestListener(testListener) } super.executeTests() } } class LocalRepositoryEnvironmentProvider(project: Project) : CommandLineArgumentProvider, Named { @Internal val localRepo = project.objects.fileCollection() @get:Classpath val jars: SortedSet<File> get() = localRepo.asFileTree.matching { include("**/*.jar") exclude("**/*-javadoc.jar") }.files.toSortedSet() /** * Make sure this stays type FileCollection (lazy) to avoid losing dependency information. */ @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) val metadatas: FileCollection get() = localRepo.asFileTree.matching { include("**/*.pom") include("**/*.xml") include("**/*.module") } override fun asArguments() = if (!localRepo.isEmpty) mapOf("integTest.localRepository" to localRepo.singleFile).asSystemPropertyJvmArguments() else emptyList() @Internal override fun getName() = "libsRepository" } class GradleInstallationForTestEnvironmentProvider(project: Project, private val testTask: DistributionTest) : CommandLineArgumentProvider, Named { @Internal val gradleHomeDir = project.objects.fileCollection() @Internal val gradleUserHomeDir = project.objects.directoryProperty() @Internal val gradleSnippetsDir = project.objects.directoryProperty() @Internal val daemonRegistry = project.objects.directoryProperty() @get:Nested val gradleDistribution = GradleDistribution(gradleHomeDir) @Internal val distZipVersion = project.version.toString() override fun asArguments(): Iterable<String> { val distributionDir = if (gradleHomeDir.files.size == 1) gradleHomeDir.singleFile else null val distributionName = if (distributionDir != null) { // complete distribution is used from 'build/bin distribution' distributionDir.parentFile.parentFile.name } else { // gradle-runtime-api-info.jar in 'build/libs' testTask.classpath.filter { it.name.startsWith("gradle-runtime-api-info") }.singleFile.parentFile.parentFile.parentFile.name } return ( (if (distributionDir != null) mapOf("integTest.gradleHomeDir" to distributionDir) else emptyMap()) + mapOf( "integTest.gradleUserHomeDir" to absolutePathOf(gradleUserHomeDir.dir(distributionName)), "integTest.samplesdir" to absolutePathOf(gradleSnippetsDir), "org.gradle.integtest.daemon.registry" to absolutePathOf(daemonRegistry.dir(distributionName)), "integTest.distZipVersion" to distZipVersion ) ).asSystemPropertyJvmArguments() } @Internal override fun getName() = "gradleInstallationForTest" } class DistributionZipEnvironmentProvider(project: Project, private val distributionType: String) : CommandLineArgumentProvider, Named { @Classpath val distributionZip = project.objects.fileCollection() override fun asArguments() = if (distributionZip.isEmpty) { emptyList() } else { mapOf("integTest.${distributionType}Distribution" to distributionZip.singleFile).asSystemPropertyJvmArguments() } @Internal override fun getName() = "${distributionType}Distribution" } private fun absolutePathOf(provider: Provider<Directory>) = provider.get().asFile.absolutePath internal fun <K, V> Map<K, V>.asSystemPropertyJvmArguments(): Iterable<String> = map { (key, value) -> "-D$key=$value" }
apache-2.0
1294c8d78181f8bce5493e4c63799d22
34.051502
147
0.71691
4.748256
false
true
false
false
tangying91/profit
src/main/java/org/profit/app/analyse/StockMockTrading.kt
1
5245
package org.profit.app.analyse import org.profit.util.StockUtils /** * 回溯历史数据 * 根据既定策略进行模拟交易 */ class StockMockTrading(code: String, private val statCount: Int = 100) : StockAnalyzer(code) { private var initMoney = 100000.0 // 初始本金 private var totalMoney = initMoney // 初始本金 private var leftMoney = initMoney // 剩余资金 private val initPositions = 0.3 // 初始仓位 private val perMoney = 3000 // 每次加减仓金额 private var stockNumber = 0 // 初始股票数量 private var lastBuyPrice = 0.0 private var serialSellCount = 0 // 连续卖出次数 override fun analyse(results: MutableList<String>) { // 获取数据,后期可以限制天数 val list = readHistories(statCount).sortedBy { it.dateTime } if (list.size != statCount) { return } // 购入初始仓位,以第一天的尾盘价格买入 val sn = calcStockNumber(money = (leftMoney * initPositions).toInt(), price = list[0].close) val cost = sn * list[0].close leftMoney -= cost stockNumber += sn lastBuyPrice = list[0].close println("仓位初始化成功,买入价格${list[0].close}, 当前持有股票数量$stockNumber 股,剩余资金 $leftMoney") // 后面循环处理 for (i in 1 until list.size) { val data = list[i] val open = data.open val date = data.date // 看下降了多少个百分比 val downPercent = (data.low - open).div(open) val upPercent = (data.high - open).div(open) // 下降3个点 val p1 = -0.03 if (downPercent <= p1) { doStockBuy(date, StockUtils.twoDigits(open * (1 + p1)).toDouble()) } // 下降6个点 val p2 = -0.06 if (downPercent <= p2) { doStockBuy(date, StockUtils.twoDigits(open * (1 + p1)).toDouble()) } // 上涨3个点 val u1 = 0.02 if (upPercent >= u1) { serialSellCount++ } if (serialSellCount >= 3) { doStockSell(date, StockUtils.twoDigits(open * (1 + u1)).toDouble()) } } val totalDay = list.size val percent = (list[statCount - 1].open - list[0].close).div(list[0].close) println("$code 完成了 $totalDay 个交易日的模拟交易.") println("目前剩余本金 $leftMoney, 股票数量 $stockNumber, 总市值 ${stockNumber * list[statCount - 1].close}, 剩余资金 $leftMoney, 总资产${stockNumber * list[statCount - 1].close + leftMoney}") println("$code 在过去 $totalDay 个交易日里,区间涨幅为 ${StockUtils.twoDigits(percent * 100)}%. 如果一次性买入,最终剩余 ${initMoney * (1 + percent)}") } /** * 根据价格换算股票数量 * 股票只能是100的整数倍 */ private fun calcStockNumber(money: Int, price: Double): Int { return ((money.toDouble().div(price).toInt() / 100) * 100) } /** * 执行买入 */ private fun doStockBuy(date: String, price: Double) { val buyMoney = if (stockNumber == 0) { (initMoney * initPositions).toInt() } else { perMoney } // 先检查钱是否足够 if (leftMoney < buyMoney) { println("$date 触发加仓价格$price, 但是当前只有 $leftMoney,加仓失败!") return } // 加仓成功 val sn = calcStockNumber(money = buyMoney, price = price) val cost = sn * price leftMoney -= cost stockNumber += sn serialSellCount = 0 lastBuyPrice = price println("$date 触发加仓价格$price, 买入,当前剩余$stockNumber 股,总市值${stockNumber * price}, 剩余资金 $leftMoney, 总资产${stockNumber * price + leftMoney}") } /** * 执行卖出策略 */ private fun doStockSell(date: String, price: Double) { // 先检查股票数量是否足够 val sn = calcStockNumber(money = perMoney, price = price) if (sn > stockNumber) { println("$date 触发卖出价格$price, 但是当前只有 $stockNumber 股,卖出失败!") return } // 卖出成功 val sell = sn * price leftMoney += sell stockNumber -= sn println("$date 触发卖出价格$price, 卖出成功,当前剩余$stockNumber 股,总市值${stockNumber * price}, 剩余资金 $leftMoney, 总资产${stockNumber * price + leftMoney}") // 连续卖出三次,清仓处理 if (serialSellCount >= 4) { val sell1 = stockNumber * price leftMoney += sell1 stockNumber = 0 serialSellCount = 0 println("$date 触发清仓策略$price, 剩余资金 $leftMoney!!!") } } }
apache-2.0
f41454d999ce26ae405ce90114244615
30.307143
179
0.528423
3.338996
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/datatypes/promotion.kt
1
2219
package edu.kit.iti.formal.automation.datatypes fun getPromotion(a: AnyDt, b: AnyDt): AnyDt? = a.accept(PromotionVisitor(b)) infix fun AnyDt.promoteWith(other: AnyDt): AnyDt? = getPromotion(this, other) class PromotionVisitor(val other: AnyDt) : DataTypeVisitor<AnyDt> { override fun defaultVisit(obj: Any) = null override fun visit(real: AnyReal): AnyDt? { return when (other) { is AnyReal -> //silent assumption: only REAL and LREAL if (real == other) real else AnyReal.LREAL is AnyInt -> real else -> null } } override fun visit(anyInt: AnyInt): AnyDt? { return when (other) { is AnyReal -> getPromotion(other, anyInt) is AnyInt -> { when { (anyInt.isSigned && other.isSigned) -> if (anyInt.bitLength >= other.bitLength) anyInt else other (!anyInt.isSigned && !other.isSigned) -> if (anyInt.bitLength >= other.bitLength) anyInt else other else -> findNext(anyInt, other) } } else -> null } } override fun visit(anyBit: AnyBit): AnyDt? { return when (other) { is AnyBit -> if (anyBit.bitLength >= other.bitLength) anyBit else other else -> null } } override fun visit(enumerateType: EnumerateType): AnyDt? { return when (other) { enumerateType -> enumerateType is AnyInt -> getPromotion(AnyInt(enumerateType.bitlength), other) else -> null } } override fun visit(string: IECString.STRING): AnyDt? { return if (string == other) string else null } override fun visit(wString: IECString.WSTRING): AnyDt? { return if (wString == other) wString else null } private fun findNext(a: AnyInt, b: AnyInt): AnyInt { var (signed, unsigned) = if (a.isSigned) Pair(a, b) else Pair(b, a) while (signed.upperBound < unsigned.upperBound) { signed = signed.next() ?: break } return signed } }
gpl-3.0
b82982dca1e32676f6fbf3bcb8f5ce7f
31.15942
82
0.549347
4.210626
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/util/AppUpgrade.kt
1
5534
package com.battlelancer.seriesguide.util import android.app.AlarmManager import android.app.PendingIntent import android.content.ContentValues import android.content.Context import android.content.Intent import androidx.core.content.getSystemService import androidx.preference.PreferenceManager import com.battlelancer.seriesguide.BuildConfig import com.battlelancer.seriesguide.SgApp import com.battlelancer.seriesguide.appwidget.ListWidgetProvider import com.battlelancer.seriesguide.backend.settings.HexagonSettings import com.battlelancer.seriesguide.extensions.ExtensionManager import com.battlelancer.seriesguide.provider.SeriesGuideContract import com.battlelancer.seriesguide.provider.SgRoomDatabase import com.battlelancer.seriesguide.settings.AppSettings import com.battlelancer.seriesguide.sync.SgSyncAdapter import com.battlelancer.seriesguide.traktapi.TraktSettings import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /** * If necessary, runs upgrade code after an update with a higher version code is installed. */ class AppUpgrade( private val context: Context, private val lastVersion: Int = AppSettings.getLastVersionCode(context), private val currentVersion: Int = BuildConfig.VERSION_CODE ) { /** * Returns true if the app was updated from a previous version. */ fun upgradeIfNewVersion(): Boolean { return if (lastVersion < currentVersion) { doUpgrades() // Update last version to current version PreferenceManager.getDefaultSharedPreferences(context).edit() .putInt(AppSettings.KEY_VERSION, currentVersion) .apply() true } else { false } } private fun doUpgrades() { // Run some required tasks after updating to certain versions. // NOTE: see version codes for upgrade description. if (lastVersion < SgApp.RELEASE_VERSION_12_BETA5) { // flag all episodes as outdated val values = ContentValues() values.put(SeriesGuideContract.Episodes.LAST_UPDATED, 0) context.contentResolver.update( SeriesGuideContract.Episodes.CONTENT_URI, values, null, null ) // sync is triggered in last condition // (if we are in here we will definitely hit the ones below) } if (lastVersion < SgApp.RELEASE_VERSION_16_BETA1) { Utils.clearLegacyExternalFileCache(context) } if (lastVersion < SgApp.RELEASE_VERSION_23_BETA4) { // make next trakt sync download watched movies TraktSettings.resetMoviesLastWatchedAt(context) } if (lastVersion < SgApp.RELEASE_VERSION_26_BETA3) { // flag all shows outdated so delta sync will pick up, if full sync gets aborted val values = ContentValues() values.put(SeriesGuideContract.Shows.LASTUPDATED, 0) context.contentResolver.update( SeriesGuideContract.Shows.CONTENT_URI, values, null, null ) // force a sync SgSyncAdapter.requestSyncFullImmediate(context, true) } // This was never doing anything (ops batch never applied), so removed. // if (lastVersion < SgApp.RELEASE_VERSION_34_BETA4) { // ActivityTools.populateShowsLastWatchedTime(this) // } if (lastVersion < SgApp.RELEASE_VERSION_36_BETA2) { // used account name to determine sign-in state before switch to Google Sign-In if (!HexagonSettings.getAccountName(context).isNullOrEmpty()) { // tell users to sign in again PreferenceManager.getDefaultSharedPreferences(context).edit() .putBoolean(HexagonSettings.KEY_SHOULD_VALIDATE_ACCOUNT, true) .apply() } } if (lastVersion < SgApp.RELEASE_VERSION_40_BETA4) { ExtensionManager.get(context).setDefaultEnabledExtensions(context) } if (lastVersion < SgApp.RELEASE_VERSION_40_BETA6) { // cancel old widget alarm using implicit intent val am = context.getSystemService<AlarmManager>() if (am != null) { val pi = PendingIntent.getBroadcast( context, ListWidgetProvider.REQUEST_CODE, Intent(ListWidgetProvider.ACTION_DATA_CHANGED), // Mutable because it was created without flags which defaulted to mutable. PendingIntentCompat.flagMutable ) am.cancel(pi) } // new alarm is set automatically as upgrading causes app widgets to update } if (lastVersion != SgApp.RELEASE_VERSION_50_1 && lastVersion < SgApp.RELEASE_VERSION_51_BETA4) { // Movies were not added in all cases when syncing, so ensure they are now. TraktSettings.resetMoviesLastWatchedAt(context) HexagonSettings.resetSyncState(context) } if (lastVersion < SgApp.RELEASE_VERSION_59_BETA1) { // Changed ID of Canceled show status for better sorting. SgApp.coroutineScope.launch(Dispatchers.IO) { SgRoomDatabase.getInstance(context).sgShow2Helper().migrateCanceledShowStatus() } } } }
apache-2.0
13b42bdc5095154add03a633e373bef4
39.108696
95
0.642935
5.201128
false
false
false
false
UweTrottmann/SeriesGuide
billing/src/main/java/com/uwetrottmann/seriesguide/billing/localdb/LocalBillingDb.kt
1
2074
/** * Copyright (C) 2018 Google Inc. All Rights Reserved. * * 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.uwetrottmann.seriesguide.billing.localdb import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters @Database( entities = [ AugmentedSkuDetails::class, CachedPurchase::class, GoldStatus::class ], version = 2, exportSchema = false ) @TypeConverters(PurchaseTypeConverter::class) abstract class LocalBillingDb : RoomDatabase() { abstract fun purchaseDao(): PurchaseDao abstract fun entitlementsDao(): EntitlementsDao abstract fun skuDetailsDao(): AugmentedSkuDetailsDao companion object { @Volatile private var INSTANCE: LocalBillingDb? = null private const val DATABASE_NAME = "purchase_db" @JvmStatic fun getInstance(context: Context): LocalBillingDb = INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it } } private fun buildDatabase(appContext: Context): LocalBillingDb { return Room.databaseBuilder(appContext, LocalBillingDb::class.java, DATABASE_NAME) .allowMainThreadQueries() // Gold status detection currently runs on main thread. .fallbackToDestructiveMigration() // Data is cache, so it is OK to delete .build() } } }
apache-2.0
726362c0bb92d01ee2fefd2961a7186a
33.566667
97
0.685149
4.857143
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/shows/search/BaseSearchFragment.kt
1
1688
package com.battlelancer.seriesguide.shows.search import android.os.Bundle import android.view.View import android.widget.GridView import androidx.core.view.ViewCompat import androidx.fragment.app.Fragment import org.greenrobot.eventbus.EventBus abstract class BaseSearchFragment : Fragment() { abstract val emptyView: View abstract val gridView: GridView var initialSearchArgs: Bundle? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { // use initial query (if any) val queryEvent = EventBus.getDefault() .getStickyEvent(SearchActivityImpl.SearchQueryEvent::class.java) if (queryEvent != null) { initialSearchArgs = queryEvent.args } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // enable app bar scrolling out of view ViewCompat.setNestedScrollingEnabled(gridView, true) emptyView.visibility = View.GONE } override fun onStart() { super.onStart() EventBus.getDefault().register(this) } override fun onStop() { super.onStop() EventBus.getDefault().unregister(this) } protected fun updateEmptyState(hasNoResults: Boolean, hasQuery: Boolean) { if (hasNoResults && hasQuery) { emptyView.visibility = View.VISIBLE gridView.visibility = View.GONE } else { emptyView.visibility = View.GONE gridView.visibility = View.VISIBLE } } }
apache-2.0
9e9a3e490fc5039568709dbfc59a1488
26.225806
80
0.655213
4.979351
false
false
false
false
Kotlin/anko
anko/library/generated/design/src/main/java/Layouts.kt
2
23246
@file:JvmName("DesignLayoutsKt") package org.jetbrains.anko.design import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.widget.LinearLayout import android.support.design.widget.AppBarLayout import android.view.View import android.widget.FrameLayout import android.support.design.widget.BottomNavigationView import android.support.design.widget.CollapsingToolbarLayout import android.support.design.widget.CoordinatorLayout import android.support.design.widget.TabLayout import android.support.design.widget.TextInputLayout open class _AppBarLayout(ctx: Context): AppBarLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AppBarLayout.LayoutParams.() -> Unit ): T { val layoutParams = AppBarLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AppBarLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: AppBarLayout.LayoutParams.() -> Unit ): T { val layoutParams = AppBarLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = AppBarLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: AppBarLayout.LayoutParams.() -> Unit ): T { val layoutParams = AppBarLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float ): T { val layoutParams = AppBarLayout.LayoutParams(width, height, weight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: AppBarLayout.LayoutParams.() -> Unit ): T { val layoutParams = AppBarLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = AppBarLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: AppBarLayout.LayoutParams.() -> Unit ): T { val layoutParams = AppBarLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = AppBarLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams?, init: AppBarLayout.LayoutParams.() -> Unit ): T { val layoutParams = AppBarLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams? ): T { val layoutParams = AppBarLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: AppBarLayout.LayoutParams?, init: AppBarLayout.LayoutParams.() -> Unit ): T { val layoutParams = AppBarLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: AppBarLayout.LayoutParams? ): T { val layoutParams = AppBarLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _BottomNavigationView(ctx: Context): BottomNavigationView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _CollapsingToolbarLayout(ctx: Context): CollapsingToolbarLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: CollapsingToolbarLayout.LayoutParams.() -> Unit ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: CollapsingToolbarLayout.LayoutParams.() -> Unit ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: CollapsingToolbarLayout.LayoutParams.() -> Unit ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: CollapsingToolbarLayout.LayoutParams.() -> Unit ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: CollapsingToolbarLayout.LayoutParams.() -> Unit ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: CollapsingToolbarLayout.LayoutParams.() -> Unit ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = CollapsingToolbarLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _CoordinatorLayout(ctx: Context): CoordinatorLayout(ctx) { inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: CoordinatorLayout.LayoutParams.() -> Unit ): T { val layoutParams = CoordinatorLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = CoordinatorLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: CoordinatorLayout.LayoutParams?, init: CoordinatorLayout.LayoutParams.() -> Unit ): T { val layoutParams = CoordinatorLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: CoordinatorLayout.LayoutParams? ): T { val layoutParams = CoordinatorLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.MarginLayoutParams?, init: CoordinatorLayout.LayoutParams.() -> Unit ): T { val layoutParams = CoordinatorLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.MarginLayoutParams? ): T { val layoutParams = CoordinatorLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: CoordinatorLayout.LayoutParams.() -> Unit ): T { val layoutParams = CoordinatorLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = CoordinatorLayout.LayoutParams(p!!) [email protected] = layoutParams return this } } open class _TabLayout(ctx: Context): TabLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TextInputLayout(ctx: Context): TextInputLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = LinearLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } }
apache-2.0
f58ed7c3feddea19f34df7a489c2c412
31.603086
87
0.622172
4.94701
false
false
false
false
Geobert/Efficio
app/src/main/kotlin/fr/geobert/efficio/db/StoreCompositionTable.kt
1
2468
package fr.geobert.efficio.db import android.app.Activity import android.content.ContentValues import android.content.Context import android.content.CursorLoader import android.provider.BaseColumns import fr.geobert.efficio.data.Department object StoreCompositionTable : BaseTable() { override val TABLE_NAME: String = "department_weight" val COL_STORE_ID = "store_id" val COL_DEP_ID = "dep_id" val COL_WEIGHT = "dep_weight" override fun CREATE_COLUMNS(): String = "$COL_STORE_ID INTEGER NOT NULL, " + "$COL_DEP_ID INTEGER NOT NULL, " + "$COL_WEIGHT REAL NOT NULL, " + "${foreignId(COL_STORE_ID, StoreTable.TABLE_NAME)}, " + foreignId(COL_DEP_ID, DepartmentTable.TABLE_NAME) val TABLE_JOINED = "$TABLE_NAME " + " LEFT OUTER JOIN ${StoreTable.TABLE_NAME} ON $TABLE_NAME.$COL_STORE_ID = ${StoreTable.TABLE_NAME}.${BaseColumns._ID}" + " LEFT OUTER JOIN ${DepartmentTable.TABLE_NAME} ON $TABLE_NAME.$COL_DEP_ID = ${DepartmentTable.TABLE_NAME}.${BaseColumns._ID}" override val COLS_TO_QUERY: Array<String> = arrayOf("${StoreTable.TABLE_NAME}.${BaseColumns._ID}", "${StoreTable.TABLE_NAME}.${StoreTable.COL_NAME} as store_name", "${DepartmentTable.TABLE_NAME}.${BaseColumns._ID} as $COL_DEP_ID", "${DepartmentTable.TABLE_NAME}.${DepartmentTable.COL_NAME} as dep_name", "${StoreCompositionTable.TABLE_NAME}.${BaseColumns._ID} as store_compo_id", "$TABLE_NAME.$COL_WEIGHT") val RESTRICT_TO_STORE = "($TABLE_NAME.$COL_STORE_ID = ?)" val ORDERING = "$COL_WEIGHT asc" fun getDepFromStoreLoader(activity: Context, storeId: Long): CursorLoader { return CursorLoader(activity, CONTENT_URI, COLS_TO_QUERY, RESTRICT_TO_STORE, arrayOf(storeId.toString()), ORDERING) } fun create(ctx: Context, storeId: Long, department: Department): Long { val v = ContentValues() v.put(COL_STORE_ID, storeId) v.put(COL_DEP_ID, department.id) v.put(COL_WEIGHT, department.weight) val res = ctx.contentResolver.insert(CONTENT_URI, v) return res.lastPathSegment.toLong() } fun updateDepWeight(activity: Activity, department: Department): Int { val v = ContentValues() v.put(COL_WEIGHT, department.weight) val id = department.storeCompoId return if (id != null) update(activity, id, v) else 0 } }
gpl-2.0
7f48d701c56c23f7f12ae36808154cdc
40.15
138
0.65316
3.779479
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/ContextStringToUserInfoConverter.kt
1
1683
package net.perfectdreams.loritta.cinnamon.discord.utils import dev.kord.common.entity.Snowflake import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.pudding.data.CachedUserInfo import net.perfectdreams.loritta.cinnamon.pudding.data.UserId /** * Converts a String, using a CommandContext, to a CachedUserInfo object */ object ContextStringToUserInfoConverter { suspend fun convert(context: ApplicationCommandContext, input: String): CachedUserInfo? { if (input.startsWith("<@") && input.endsWith(">")) { // Is a mention... maybe? val userId = input.removePrefix("<@") .removePrefix("!") .removeSuffix(">") .toLongOrNull() ?: return null // If the input is not a long, then return the input val user = context.interaKTionsContext.interactionData.resolved?.users?.get(Snowflake(userId)) ?: return null // If there isn't any matching user, then return null return CachedUserInfo( UserId(user.id.value), user.username, user.discriminator, user.data.avatar ) } val snowflake = try { Snowflake(input) } catch (e: NumberFormatException) { null } // If the snowflake is not null, then it *may* be a user ID! if (snowflake != null) { val cachedUserInfo = context.loritta.getCachedUserInfo(UserId(snowflake.value)) if (cachedUserInfo != null) return cachedUserInfo } return null } }
agpl-3.0
3271c8107b475f8e8efe517cfb63fdb9
37.272727
175
0.628045
5.084592
false
false
false
false
shyiko/ktlint
ktlint/src/test/kotlin/com/pinterest/ktlint/internal/FileUtilsFileSequenceTest.kt
1
5051
package com.pinterest.ktlint.internal import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import java.io.File import java.nio.file.Files import java.nio.file.Path import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.After import org.junit.Before import org.junit.Test /** * Tests for [fileSequence] method. */ internal class FileUtilsFileSequenceTest { private val tempFileSystem = Jimfs.newFileSystem(Configuration.forCurrentPlatform()) private val rootDir = tempFileSystem.rootDirectories.first().toString() private val project1Files = listOf( "${rootDir}project1/.git/ignored.kts", "${rootDir}project1/build.gradle.kts", "${rootDir}project1/src/scripts/someScript.kts", "${rootDir}project1/src/main/kotlin/One.kt", "${rootDir}project1/src/main/kotlin/example/Two.kt", ).map { it.normalizePath() } private val project2Files = listOf( "${rootDir}project2/build.gradle.kts", "${rootDir}project2/src/main/java/Three.kt" ).map { it.normalizePath() } @Before fun setUp() { project1Files.createFiles() } @After fun tearDown() { tempFileSystem.close() } @Test fun `On empty patterns should include all kt and kts files`() { val foundFiles = getFiles() assertThat(foundFiles).hasSize(project1Files.size - 1) assertThat(foundFiles).containsAll(project1Files.drop(1)) } @Test fun `Should ignore hidden dirs on empty patterns`() { val foundFiles = getFiles() assertThat(foundFiles).doesNotContain(project1Files.first()) } @Test fun `Should return only files matching passed pattern`() { val expectedResult = project1Files.drop(1).filter { it.endsWith(".kt") } val foundFiles = getFiles( listOf( "**/src/**/*.kt".normalizeGlob() ) ) assertThat(foundFiles).hasSize(expectedResult.size) assertThat(foundFiles).containsAll(expectedResult) } @Test fun `Should ignore hidden folders when some pattern is passed`() { val expectedResult = project1Files.drop(1).filter { it.endsWith(".kts") } val foundFiles = getFiles( listOf( "project1/**/*.kts".normalizeGlob(), "project1/*.kts".normalizeGlob() ) ) assertThat(foundFiles).hasSize(expectedResult.size) assertThat(foundFiles).containsAll(expectedResult) } @Test fun `Should ignore files in negated pattern`() { val foundFiles = getFiles( listOf( "project1/src/**/*.kt".normalizeGlob(), "!project1/src/**/example/*.kt".normalizeGlob() ) ) assertThat(foundFiles).hasSize(1) assertThat(foundFiles).containsAll(project1Files.subList(3, 4)) } @Test fun `Should return only files for the the current rootDir matching passed patterns`() { project2Files.createFiles() val foundFiles = getFiles( listOf( "**/main/**/*.kt".normalizeGlob() ), tempFileSystem.getPath("${rootDir}project2".normalizePath()) ) assertThat(foundFiles).hasSize(1) assertThat(foundFiles).containsAll(project2Files.subList(1, 1)) } @Test fun `Should treat correctly root path without separator in the end`() { val foundFiles = getFiles( patterns = listOf("src/main/kotlin/One.kt".normalizeGlob()), rootDir = tempFileSystem.getPath("${rootDir}project1".normalizePath()) ) assertThat(foundFiles).hasSize(1) assertThat(foundFiles.first()).isEqualTo(project1Files[3]) } @Test fun `Should fail the search when glob contain absolute path`() { val globs = listOf( "src/main/kotlin/One.kt".normalizeGlob(), "!${rootDir}project1/src/main/kotlin/example/Two.kt".normalizeGlob() ) try { getFiles( patterns = globs ) fail("No exception was thrown!") } catch (e: IllegalArgumentException) { assertThat(e.message).contains( globs.last().removePrefix("!") ) } } private fun String.normalizePath() = replace('/', File.separatorChar) private fun String.normalizeGlob(): String = replace("/", globSeparator) private fun List<String>.createFiles() = forEach { val filePath = tempFileSystem.getPath(it) val fileDir = filePath.parent if (!Files.exists(fileDir)) Files.createDirectories(fileDir) Files.createFile(filePath) } private fun getFiles( patterns: List<String> = emptyList(), rootDir: Path = tempFileSystem.rootDirectories.first() ): List<String> = tempFileSystem .fileSequence(patterns, rootDir) .map { it.toString() } .toList() }
mit
958e7636dfe89d1df0274525b1de4b82
30.372671
91
0.620669
4.438489
false
true
false
false
cketti/okhttp
okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt
1
9962
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.dnsoverhttps import java.io.IOException import java.net.HttpURLConnection import java.net.InetAddress import java.net.UnknownHostException import java.util.ArrayList import java.util.concurrent.CountDownLatch import okhttp3.CacheControl import okhttp3.Call import okhttp3.Callback import okhttp3.Dns import okhttp3.HttpUrl import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Protocol import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import okhttp3.internal.platform.Platform import okhttp3.internal.publicsuffix.PublicSuffixDatabase /** * [DNS over HTTPS implementation][doh_spec]. * * > A DNS API client encodes a single DNS query into an HTTP request * > using either the HTTP GET or POST method and the other requirements * > of this section. The DNS API server defines the URI used by the * > request through the use of a URI Template. * * ### Warning: This is a non-final API. * * As of OkHttp 3.14, this feature is an unstable preview: the API is subject to change, and the * implementation is incomplete. We expect that OkHttp 4.6 or 4.7 will finalize this API. Until * then, expect API and behavior changes when you update your OkHttp dependency.** * * [doh_spec]: https://tools.ietf.org/html/draft-ietf-doh-dns-over-https-13 */ class DnsOverHttps internal constructor( @get:JvmName("client") val client: OkHttpClient, @get:JvmName("url") val url: HttpUrl, @get:JvmName("includeIPv6") val includeIPv6: Boolean, @get:JvmName("post") val post: Boolean, @get:JvmName("resolvePrivateAddresses") val resolvePrivateAddresses: Boolean, @get:JvmName("resolvePublicAddresses") val resolvePublicAddresses: Boolean ) : Dns { @Throws(UnknownHostException::class) override fun lookup(hostname: String): List<InetAddress> { if (!resolvePrivateAddresses || !resolvePublicAddresses) { val privateHost = isPrivateHost(hostname) if (privateHost && !resolvePrivateAddresses) { throw UnknownHostException("private hosts not resolved") } if (!privateHost && !resolvePublicAddresses) { throw UnknownHostException("public hosts not resolved") } } return lookupHttps(hostname) } @Throws(UnknownHostException::class) private fun lookupHttps(hostname: String): List<InetAddress> { val networkRequests = ArrayList<Call>(2) val failures = ArrayList<Exception>(2) val results = ArrayList<InetAddress>(5) buildRequest(hostname, networkRequests, results, failures, DnsRecordCodec.TYPE_A) if (includeIPv6) { buildRequest(hostname, networkRequests, results, failures, DnsRecordCodec.TYPE_AAAA) } executeRequests(hostname, networkRequests, results, failures) return if (results.isNotEmpty()) { results } else { throwBestFailure(hostname, failures) } } private fun buildRequest( hostname: String, networkRequests: MutableList<Call>, results: MutableList<InetAddress>, failures: MutableList<Exception>, type: Int ) { val request = buildRequest(hostname, type) val response = getCacheOnlyResponse(request) response?.let { processResponse(it, hostname, results, failures) } ?: networkRequests.add( client.newCall(request)) } private fun executeRequests( hostname: String, networkRequests: List<Call>, responses: MutableList<InetAddress>, failures: MutableList<Exception> ) { val latch = CountDownLatch(networkRequests.size) for (call in networkRequests) { call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { synchronized(failures) { failures.add(e) } latch.countDown() } override fun onResponse(call: Call, response: Response) { processResponse(response, hostname, responses, failures) latch.countDown() } }) } try { latch.await() } catch (e: InterruptedException) { failures.add(e) } } private fun processResponse( response: Response, hostname: String, results: MutableList<InetAddress>, failures: MutableList<Exception> ) { try { val addresses = readResponse(hostname, response) synchronized(results) { results.addAll(addresses) } } catch (e: Exception) { synchronized(failures) { failures.add(e) } } } @Throws(UnknownHostException::class) private fun throwBestFailure(hostname: String, failures: List<Exception>): List<InetAddress> { if (failures.isEmpty()) { throw UnknownHostException(hostname) } val failure = failures[0] if (failure is UnknownHostException) { throw failure } val unknownHostException = UnknownHostException(hostname) unknownHostException.initCause(failure) for (i in 1 until failures.size) { unknownHostException.addSuppressed(failures[i]) } throw unknownHostException } private fun getCacheOnlyResponse(request: Request): Response? { if (!post && client.cache != null) { try { // Use the cache without hitting the network first // 504 code indicates that the Cache is stale val preferCache = CacheControl.Builder() .onlyIfCached() .build() val cacheRequest = request.newBuilder().cacheControl(preferCache).build() val cacheResponse = client.newCall(cacheRequest).execute() if (cacheResponse.code != HttpURLConnection.HTTP_GATEWAY_TIMEOUT) { return cacheResponse } } catch (ioe: IOException) { // Failures are ignored as we can fallback to the network // and hopefully repopulate the cache. } } return null } @Throws(Exception::class) private fun readResponse(hostname: String, response: Response): List<InetAddress> { if (response.cacheResponse == null && response.protocol !== Protocol.HTTP_2) { Platform.get().log("Incorrect protocol: ${response.protocol}", Platform.WARN) } response.use { if (!response.isSuccessful) { throw IOException("response: " + response.code + " " + response.message) } val body = response.body if (body!!.contentLength() > MAX_RESPONSE_SIZE) { throw IOException( "response size exceeds limit ($MAX_RESPONSE_SIZE bytes): ${body.contentLength()} bytes" ) } val responseBytes = body.source().readByteString() return DnsRecordCodec.decodeAnswers(hostname, responseBytes) } } private fun buildRequest(hostname: String, type: Int): Request = Request.Builder().header("Accept", DNS_MESSAGE.toString()).apply { val query = DnsRecordCodec.encodeQuery(hostname, type) if (post) { url(url).post(query.toRequestBody(DNS_MESSAGE)) } else { val encoded = query.base64Url().replace("=", "") val requestUrl = url.newBuilder().addQueryParameter("dns", encoded).build() url(requestUrl) } }.build() class Builder { internal var client: OkHttpClient? = null internal var url: HttpUrl? = null internal var includeIPv6 = true internal var post = false internal var systemDns = Dns.SYSTEM internal var bootstrapDnsHosts: List<InetAddress>? = null internal var resolvePrivateAddresses = false internal var resolvePublicAddresses = true fun build(): DnsOverHttps { val client = this.client ?: throw NullPointerException("client not set") return DnsOverHttps( client.newBuilder().dns(buildBootstrapClient(this)).build(), checkNotNull(url) { "url not set" }, includeIPv6, post, resolvePrivateAddresses, resolvePublicAddresses ) } fun client(client: OkHttpClient) = apply { this.client = client } fun url(url: HttpUrl) = apply { this.url = url } fun includeIPv6(includeIPv6: Boolean) = apply { this.includeIPv6 = includeIPv6 } fun post(post: Boolean) = apply { this.post = post } fun resolvePrivateAddresses(resolvePrivateAddresses: Boolean) = apply { this.resolvePrivateAddresses = resolvePrivateAddresses } fun resolvePublicAddresses(resolvePublicAddresses: Boolean) = apply { this.resolvePublicAddresses = resolvePublicAddresses } fun bootstrapDnsHosts(bootstrapDnsHosts: List<InetAddress>?) = apply { this.bootstrapDnsHosts = bootstrapDnsHosts } fun bootstrapDnsHosts(vararg bootstrapDnsHosts: InetAddress): Builder = bootstrapDnsHosts(bootstrapDnsHosts.toList()) fun systemDns(systemDns: Dns) = apply { this.systemDns = systemDns } } companion object { val DNS_MESSAGE: MediaType = "application/dns-message".toMediaType() const val MAX_RESPONSE_SIZE = 64 * 1024 private fun buildBootstrapClient(builder: Builder): Dns { val hosts = builder.bootstrapDnsHosts return if (hosts != null) { BootstrapDns(builder.url!!.host, hosts) } else { builder.systemDns } } internal fun isPrivateHost(host: String): Boolean { return PublicSuffixDatabase.get().getEffectiveTldPlusOne(host) == null } } }
apache-2.0
4b51b65ee720336c157c285e7a436053
29.652308
99
0.682995
4.407965
false
false
false
false
EdenTewelde/project_alpha_omega
src/main/kotlin/Main.kt
2
3776
import com.univocity.parsers.common.record.Record import com.univocity.parsers.csv.CsvParser import com.univocity.parsers.csv.CsvParserSettings import com.univocity.parsers.csv.CsvWriter import com.univocity.parsers.csv.CsvWriterSettings import java.util.* fun main(args: Array<String>) { val roadNetwork = readNetworkFromCsv("/cars.csv") roadNetwork.analyzeNetwork() writeNetworkToCsv(roadNetwork, "ResultingData.csv") } private fun readNetworkFromCsv(fileName: String): Network { //Changed the return "Car" into "Network", because there is the "listOfCars" val capacity = 5 val settings = CsvParserSettings() settings.format.setLineSeparator("\n") settings.isHeaderExtractionEnabled = true val csvParser = CsvParser(settings) val reader = FileAccess().getReader(fileName) val carRows: MutableList<Record> = csvParser.parseAllRecords(reader) val listOfCars: MutableList<Car> = mutableListOf() val mapOfCarIDs: MutableMap<Int,Car> = mutableMapOf() for (carRow in carRows) { val carID = carRow.values.get(0) val id = carID.toInt() val carHour = carRow.values.get(1) val hour = carHour.toInt() // only creates a new car if carID doesn't exist yet if (!mapOfCarIDs.contains(id)) { val newCar = Car(id,true) listOfCars.add(newCar) mapOfCarIDs.put(id,newCar) } // add the hour to car with this ID mapOfCarIDs.get(id)!!.wantsToDriveAtHour.add(hour) } return Network(capacity, listOfCars) } private fun writeNetworkToCsv(network: Network, fileName: String) { val settings = CsvWriterSettings() settings.format.setLineSeparator("\n") val writer = FileAccess().getWriter(fileName) val csvWriter = CsvWriter(writer, settings) csvWriter.writeHeaders("Car-ID", "wantsToDriveAtHour", "delayedAtHour") val carRows: MutableList<Array<Any>> = mutableListOf() for (car in network.listOfCars) { val id = car.id //hours a car wants to drive var wantsToDriveAtHour = " " for (hour in car.wantsToDriveAtHour) { wantsToDriveAtHour += "$hour;" } wantsToDriveAtHour = wantsToDriveAtHour.dropLast(1) // hours a car is delayed var delayedAtHour = " " for (hour in car.isDelayedAtHour) { delayedAtHour += "$hour;" } delayedAtHour = delayedAtHour.dropLast(1) val row: Array<Any> = arrayOf(id, wantsToDriveAtHour, delayedAtHour) carRows.add(row) } csvWriter.writeRowsAndClose(carRows) } fun scenario(numberOfCars: Int, capacity: Int) { /* * Creates a given a number of cars * A road network is created with the given capacity * Simulating 24 hours and prints for each hour which cars want to drive and which cars are delayed */ val listOfCars: MutableList<Car> = mutableListOf() val road = Network(capacity, listOfCars) for (i in 1..numberOfCars) { val newCar = Car(i) listOfCars.add(newCar) for (hour in 1..24) { if (Random().nextBoolean()) { newCar.wantsToDriveAtHour.add(hour) } } } road.analyzeNetwork() for (hour in 1..24){ println("Hour: $hour") var wantToDrive = " Cars that want to drive: " var delayed = " Car that are delayed: " for (car in listOfCars) { if (car.wantsToDriveAtHour(hour)) { wantToDrive += "${car.id}, " } if (car.isDelayedAtHour(hour)) { delayed += "${car.id}, " } } // removes the trailing comma println(wantToDrive.dropLast(2)) println(delayed.dropLast(2)) } }
cc0-1.0
0051d7c725e471659ebb59820e4cd7c2
33.962963
102
0.636388
3.837398
false
false
false
false
vanniktech/Emoji
emoji/src/commonTest/kotlin/com/vanniktech/emoji/EmojiTest.kt
1
2122
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji import org.junit.Assert.assertEquals import org.junit.Test class EmojiTest { @Test fun multipleCodePoints() { val emoji = TestEmoji(intArrayOf(0x1234, 0x5678), listOf("test"), false) assertEquals(2, emoji.unicode.length) assertEquals(String(intArrayOf(0x1234, 0x5678), 0, 2), emoji.unicode) } @Test fun baseWithoutVariant() { val emoji = TestEmoji(intArrayOf(0x1234), listOf("test"), false) assertEquals(emoji, emoji.base) } @Test fun baseWithVariant() { val variant = TestEmoji(intArrayOf(0x4321), listOf("test"), false) val emoji = TestEmoji(intArrayOf(0x1234), listOf("test"), false, listOf(variant)) assertEquals(emoji, variant.base) } @Test fun baseWithMultipleVariants() { val variant = TestEmoji(intArrayOf(0x4321), listOf("test"), false) val variant2 = TestEmoji(intArrayOf(0x5678), listOf("test"), false) val emoji = TestEmoji(intArrayOf(0x1234), listOf("test"), false, listOf(variant, variant2)) assertEquals(emoji, variant.base) assertEquals(emoji, variant2.base) } @Test fun baseWithRecursiveVariant() { val variantOfVariant = TestEmoji(intArrayOf(0x4321), listOf("test"), false) val variant = TestEmoji(intArrayOf(0x5678), listOf("test"), false, listOf(variantOfVariant)) val emoji = TestEmoji(intArrayOf(0x1234), listOf("test"), false, listOf(variant)) assertEquals(emoji, variantOfVariant.base) assertEquals(emoji, variant.base) } }
apache-2.0
daee5c79701489ad453cd8eef52e5b96
37.545455
96
0.723585
3.833635
false
true
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/properties/PropertyTestingAssertNone.kt
1
13851
package io.kotest.properties import io.kotest.assertions.Failures @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A> assertNone(noinline fn: PropertyContext.(a: A) -> Unit) = assertNone(1000, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A> assertNone(iterations: Int, noinline fn: PropertyContext.(a: A) -> Unit) { assertNone(iterations, Gen.default(), fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A> assertNone(gena: Gen<A>, fn: PropertyContext.(a: A) -> Unit) = assertNone(1000, gena, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A> Gen<A>.assertNone(iterations: Int = 1000, fn: PropertyContext.(a0: A) -> Unit) = assertNone(iterations, this, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A> Gen<A>.assertNone(iterations: Int = 1000, fn: PropertyContext.(a0: A, a1: A) -> Unit) = assertNone(iterations, this, this, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A> Gen<A>.assertNone(iterations: Int = 1000, fn: PropertyContext.(a0: A, a1: A, a2: A) -> Unit) = assertNone(iterations, this, this, this, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A> Gen<A>.assertNone(iterations: Int = 1000, fn: PropertyContext.(a0: A, a1: A, a2: A, a3: A) -> Unit) = assertNone(iterations, this, this, this, this, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A> Gen<A>.assertNone(iterations: Int = 1000, fn: PropertyContext.(a0: A, a1: A, a2: A, a3: A, a4: A) -> Unit) = assertNone(iterations, this, this, this, this, this, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A> Gen<A>.assertNone(iterations: Int = 1000, fn: PropertyContext.(a0: A, a1: A, a2: A, a3: A, a4: A, a5: A) -> Unit) = assertNone(iterations, this, this, this, this, this, this, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A> assertNone(iterations: Int, gena: Gen<A>, fn: PropertyContext.(a: A) -> Unit) { if (iterations <= 0) throw IllegalArgumentException("Iterations should be a positive number") val context = PropertyContext() fun test(a: A) { context.inc() val passed = try { context.fn(a) true } catch (e: AssertionError) { false } catch (e: Exception) { throw e } if (passed) throw Failures.failure("Property passed for\n$a\nafter ${context.attempts()} attempts") } for (a in gena.constants()) { test(a) } val avalues = gena.random().iterator() while (context.attempts() < iterations) { val a = avalues.next() test(a) } outputClassifications(context) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B> assertNone(noinline fn: PropertyContext.(a: A, b: B) -> Unit) { assertNone(Gen.default(), Gen.default(), fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B> assertNone(iterations: Int, noinline fn: PropertyContext.(a: A, b: B) -> Unit) { assertNone(iterations, Gen.default(), Gen.default(), fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B> assertNone(gena: Gen<A>, genb: Gen<B>, fn: PropertyContext.(a: A, b: B) -> Unit) = assertNone(1000, gena, genb, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B> assertNone(iterations: Int, gena: Gen<A>, genb: Gen<B>, fn: PropertyContext.(a: A, b: B) -> Unit) { val context = PropertyContext() fun test(a: A, b: B) { context.inc() val passed = try { context.fn(a, b) true } catch (e: AssertionError) { false } catch (e: Exception) { throw e } if (passed) throw Failures.failure("Property passed for\n$a\n$b\nafter ${context.attempts()} attempts") } for (a in gena.constants()) { for (b in genb.constants()) { test(a, b) } } val avalues = gena.random().iterator() val bvalues = genb.random().iterator() while (context.attempts() < iterations) { val a = avalues.next() val b = bvalues.next() test(a, b) } outputClassifications(context) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B, reified C> assertNone(noinline fn: PropertyContext.(a: A, b: B, c: C) -> Unit) { assertNone(1000, fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B, reified C> assertNone(iterations: Int, noinline fn: PropertyContext.(a: A, b: B, c: C) -> Unit) { assertNone(iterations, Gen.default(), Gen.default(), Gen.default(), fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C> assertNone(gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, fn: PropertyContext.(a: A, b: B, c: C) -> Unit) = assertNone(1000, gena, genb, genc, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C> assertNone(iterations: Int, gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, fn: PropertyContext.(a: A, b: B, c: C) -> Unit) { if (iterations <= 0) throw IllegalArgumentException("Iterations should be a positive number") val context = PropertyContext() fun test(a: A, b: B, c: C) { context.inc() val passed = try { context.fn(a, b, c) true } catch (e: AssertionError) { false } catch (e: Exception) { throw e } if (passed) throw Failures.failure("Property passed for\n$a\n$b\n$c\nafter ${context.attempts()} attempts") } for (a in gena.constants()) { for (b in genb.constants()) { for (c in genc.constants()) { test(a, b, c) } } } val avalues = gena.random().iterator() val bvalues = genb.random().iterator() val cvalues = genc.random().iterator() while (context.attempts() < iterations) { val a = avalues.next() val b = bvalues.next() val c = cvalues.next() test(a, b, c) } outputClassifications(context) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B, reified C, reified D> assertNone(noinline fn: PropertyContext.(a: A, b: B, c: C, D) -> Unit) { assertNone(1000, fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B, reified C, reified D> assertNone(iterations: Int, noinline fn: PropertyContext.(a: A, b: B, c: C, D) -> Unit) { assertNone(iterations, Gen.default(), Gen.default(), Gen.default(), Gen.default(), fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D> assertNone(gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, fn: PropertyContext.(a: A, b: B, c: C, d: D) -> Unit) = assertNone(1000, gena, genb, genc, gend, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D> assertNone(iterations: Int, gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, fn: PropertyContext.(a: A, b: B, c: C, d: D) -> Unit) { val context = PropertyContext() fun test(a: A, b: B, c: C, d: D) { context.inc() val passed = try { context.fn(a, b, c, d) true } catch (e: AssertionError) { false } catch (e: Exception) { throw e } if (passed) throw Failures.failure("Property passed for\n$a\n$b\n$c\n$d\nafter ${context.attempts()} attempts") } for (a in gena.constants()) { for (b in genb.constants()) { for (c in genc.constants()) { for (d in gend.constants()) { test(a, b, c, d) } } } } val avalues = gena.random().iterator() val bvalues = genb.random().iterator() val cvalues = genc.random().iterator() val dvalues = gend.random().iterator() while (context.attempts() < iterations) { test(avalues.next(), bvalues.next(), cvalues.next(), dvalues.next()) } outputClassifications(context) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B, reified C, reified D, reified E> assertNone(noinline fn: PropertyContext.(a: A, b: B, c: C, d: D, e: E) -> Unit) = assertNone(1000, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B, reified C, reified D, reified E> assertNone(iterations: Int, noinline fn: PropertyContext.(a: A, b: B, c: C, d: D, e: E) -> Unit) { assertNone(iterations, Gen.default(), Gen.default(), Gen.default(), Gen.default(), Gen.default(), fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D, E> assertNone(gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, gene: Gen<E>, fn: PropertyContext.(a: A, b: B, c: C, d: D, e: E) -> Unit) = assertNone(1000, gena, genb, genc, gend, gene, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D, E> assertNone(iterations: Int, gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, gene: Gen<E>, fn: PropertyContext.(a: A, b: B, c: C, d: D, e: E) -> Unit) { if (iterations <= 0) throw IllegalArgumentException("Iterations should be a positive number") val context = PropertyContext() fun test(a: A, b: B, c: C, d: D, e: E) { context.inc() val passed = try { context.fn(a, b, c, d, e) true } catch (e: AssertionError) { false } catch (e: Exception) { throw e } if (passed) throw Failures.failure("Property passed for\n$a\n$b\n$c\n$d\n$e\nafter ${context.attempts()} attempts") } for (a in gena.constants()) { for (b in genb.constants()) { for (c in genc.constants()) { for (d in gend.constants()) { for (e in gene.constants()) { test(a, b, c, d, e) } } } } } val avalues = gena.random().iterator() val bvalues = genb.random().iterator() val cvalues = genc.random().iterator() val dvalues = gend.random().iterator() val evalues = gene.random().iterator() while (context.attempts() < iterations) { val a = avalues.next() val b = bvalues.next() val c = cvalues.next() val d = dvalues.next() val e = evalues.next() test(a, b, c, d, e) } outputClassifications(context) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B, reified C, reified D, reified E, reified F> assertNone(noinline fn: PropertyContext.(a: A, b: B, c: C, d: D, e: E, f: F) -> Unit) { assertNone(1000, fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <reified A, reified B, reified C, reified D, reified E, reified F> assertNone(iterations: Int, noinline fn: PropertyContext.(a: A, b: B, c: C, d: D, e: E, f: F) -> Unit) { assertNone(iterations, Gen.default(), Gen.default(), Gen.default(), Gen.default(), Gen.default(), Gen.default(), fn) } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D, E, F> assertNone(gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, gene: Gen<E>, genf: Gen<F>, fn: PropertyContext.(a: A, b: B, c: C, d: D, e: E, f: F) -> Unit) = assertNone(1000, gena, genb, genc, gend, gene, genf, fn) @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D, E, F> assertNone(iterations: Int, gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, gene: Gen<E>, genf: Gen<F>, fn: PropertyContext.(a: A, b: B, c: C, d: D, e: E, f: F) -> Unit) { if (iterations <= 0) throw IllegalArgumentException("Iterations should be a positive number") val context = PropertyContext() fun test(a: A, b: B, c: C, d: D, e: E, f: F) { context.inc() val passed = try { context.fn(a, b, c, d, e, f) true } catch (e: AssertionError) { false } catch (e: Exception) { throw e } if (passed) throw Failures.failure("Property passed for\n$a\n$b\n$c\n$d\n$e\n$f\nafter ${context.attempts()} attempts") } for (a in gena.constants()) { for (b in genb.constants()) { for (c in genc.constants()) { for (d in gend.constants()) { for (e in gene.constants()) { for (f in genf.constants()) { test(a, b, c, d, e, f) } } } } } } val avalues = gena.random().iterator() val bvalues = genb.random().iterator() val cvalues = genc.random().iterator() val dvalues = gend.random().iterator() val evalues = gene.random().iterator() val fvalues = genf.random().iterator() while (context.attempts() < iterations) { val a = avalues.next() val b = bvalues.next() val c = cvalues.next() val d = dvalues.next() val e = evalues.next() val f = fvalues.next() test(a, b, c, d, e, f) } outputClassifications(context) }
apache-2.0
ae657c9731581871c4c18dd1c8ac56cb
42.971429
202
0.643491
3.113284
false
true
false
false
wireapp/wire-android
app/src/main/kotlin/com/waz/zclient/core/network/accesstoken/AccessToken.kt
1
1030
package com.waz.zclient.core.network.accesstoken import com.waz.zclient.core.extension.empty import com.waz.zclient.core.network.api.token.AccessTokenResponse import com.waz.zclient.storage.db.accountdata.AccessTokenEntity data class AccessToken( val token: String, val tokenType: String, val expiresIn: String ) { companion object { val EMPTY = AccessToken(String.empty(), String.empty(), String.empty()) } } class AccessTokenMapper { fun from(entity: AccessTokenEntity) = AccessToken( token = entity.token, tokenType = entity.tokenType, expiresIn = entity.expiresInMillis.toString() ) fun from(response: AccessTokenResponse) = AccessToken( token = response.token, tokenType = response.type, expiresIn = response.expiresIn ) fun toEntity(accessToken: AccessToken) = AccessTokenEntity( token = accessToken.token, tokenType = accessToken.tokenType, expiresInMillis = accessToken.expiresIn.toLong() ) }
gpl-3.0
eb3a7529a8675722c212a3b3d44e3a45
28.428571
79
0.7
4.458874
false
false
false
false
toastkidjp/Jitte
lib/src/main/java/jp/toastkid/lib/preference/ColorPair.kt
1
1749
package jp.toastkid.lib.preference import android.content.res.ColorStateList import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.widget.TextView import androidx.annotation.ColorInt import androidx.core.graphics.drawable.DrawableCompat import com.google.android.material.floatingactionbutton.FloatingActionButton /** * Color pair of toolbar and so on... * * @author toastkidjp */ class ColorPair( @param:ColorInt private val bgColor: Int, @param:ColorInt private val fontColor: Int ) { @ColorInt fun bgColor(): Int = bgColor @ColorInt fun fontColor(): Int = fontColor /** * Set background and text color. * * @param tv */ fun setTo(tv: TextView?) { tv?.setBackgroundColor(bgColor) tv?.setTextColor(fontColor) tv?.compoundDrawables?.forEach { it?.colorFilter = PorterDuffColorFilter(fontColor, PorterDuff.Mode.SRC_IN) } } /** * Apply colors to passed [FloatingActionButton]. * * @param floatingActionButton [FloatingActionButton] */ fun applyTo(floatingActionButton: FloatingActionButton?) { floatingActionButton?.backgroundTintList = ColorStateList.valueOf(bgColor) floatingActionButton?.drawable?.also { DrawableCompat.setTint(it, fontColor) floatingActionButton.setImageDrawable(it) } } fun applyReverseTo(floatingActionButton: FloatingActionButton?) { floatingActionButton?.backgroundTintList = ColorStateList.valueOf(fontColor) floatingActionButton?.drawable?.also { DrawableCompat.setTint(it, bgColor) floatingActionButton.setImageDrawable(it) } } }
epl-1.0
11976a4cef480eec2d00b19d365f8fbf
29.155172
86
0.694683
5.236527
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsSortImplTraitMembersInspection.kt
1
2771
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.RsItemElement import org.rust.lang.core.psi.ext.RsTraitOrImpl import org.rust.lang.core.psi.ext.elementType import org.rust.lang.core.psi.ext.resolveToTrait class RsSortImplTraitMembersInspection : RsLocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitImplItem(impl: RsImplItem) { val trait = impl.traitRef?.resolveToTrait ?: return val typeRef = impl.typeReference ?: return if (sortedImplItems(impl.items(), trait.items()) == null) return val textRange = TextRange(0, typeRef.startOffsetInParent + typeRef.textLength) holder.registerProblem( impl, textRange, "Different impl member order from the trait", SortImplTraitMembersFix() ) } } companion object { private fun sortedImplItems(implItems: List<RsItemElement>, traitItems: List<RsItemElement>): List<RsItemElement>? { val implItemMap = implItems.associate { it.key() to it } val sortedImplItems = traitItems.mapNotNull { implItemMap[it.key()] } if (sortedImplItems.size != implItems.size || sortedImplItems == implItems) return null return sortedImplItems } } private class SortImplTraitMembersFix : LocalQuickFix { override fun getFamilyName() = "Apply same member order" override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val impl = descriptor.psiElement as? RsImplItem ?: return val trait = impl.traitRef?.resolveToTrait ?: return val implItems = impl.items() val traitItems = trait.items() val sortedImplItems = sortedImplItems(implItems, traitItems)?.map { it.copy() } ?: return traitItems.zip(implItems).forEachIndexed { index, (traitItem, implItem) -> if (traitItem.key() != implItem.key()) implItem.replace(sortedImplItems[index]) } } } } private fun RsTraitOrImpl.items(): List<RsItemElement> = members?.children?.mapNotNull { if (it is RsFunction || it is RsConstant || it is RsTypeAlias) it as? RsItemElement else null } ?: emptyList() private fun RsItemElement.key() = name to elementType
mit
6c4c8af63efdcf8f824d79004b7577b8
42.984127
124
0.68459
4.491086
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/documentation/flexbox/TextInsideContainer.kt
1
2158
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.samples.litho.documentation.flexbox import com.facebook.litho.Column import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Style import com.facebook.litho.core.height import com.facebook.litho.core.heightPercent import com.facebook.litho.core.margin import com.facebook.litho.core.padding import com.facebook.litho.core.widthPercent import com.facebook.litho.dp import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.sp class TextInsideContainer : KComponent() { // start_example override fun ComponentScope.render(): Component { return Column(style = Style.height(135.dp).padding(16.dp)) { child( Column(style = Style.heightPercent(100f).widthPercent(100f)) { // either remove widthPercent / heightPercent here so that both siblings can grow // equally child(Text(text = "This is a really long text.", textSize = 20.sp, maxLines = 1)) child( Text( style = Style.margin(top = 8.dp), text = "Subtitle text", textSize = 20.sp, maxLines = 1)) }) child( Text( // or add flex(shrink = 0f) so that this component does not shrink style = Style.margin(top = 16.dp), text = "Small footer text", textSize = 20.sp, maxLines = 1)) } } // end_example }
apache-2.0
7e27d1377f13b15c42ddabe82dac8b07
34.966667
93
0.662651
4.174081
false
false
false
false
anton-okolelov/intellij-rust
src/test/kotlin/org/rust/lang/core/type/RsSnapshotMapTest.kt
2
1367
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.type import junit.framework.TestCase import org.rust.lang.core.types.infer.SnapshotMap import org.rust.lang.core.types.infer.UnificationTable /** * [SnapshotMap] shares snapshot logic with [UnificationTable], so snapshot/rollback mechanics * mostly tested in [RsUnificationTableTest] */ class RsSnapshotMapTest : TestCase() { private object Key private sealed class Value { object Value1 : Value() object Value2 : Value() } fun `test simple insert`() { val map = SnapshotMap<Key, Value>() map.put(Key, Value.Value1) check(map.get(Key) == Value.Value1) } fun `test snapshot-rollback insert`() { val map = SnapshotMap<Key, Value>() val snapshot = map.startSnapshot() map.put(Key, Value.Value1) check(map.get(Key) == Value.Value1) snapshot.rollback() check(map.get(Key) == null) } fun `test snapshot-rollback overwrite`() { val map = SnapshotMap<Key, Value>() map.put(Key, Value.Value1) val snapshot = map.startSnapshot() map.put(Key, Value.Value2) check(map.get(Key) == Value.Value2) snapshot.rollback() check(map.get(Key) == Value.Value1) } }
mit
3a20e46a4eedab7c6ff4f63f3c2d3d64
26.897959
94
0.637893
3.76584
false
true
false
false
siosio/DomaSupport
src/main/java/siosio/doma/inspection/dao/DaoInspector.kt
1
4195
package siosio.doma.inspection.dao import com.intellij.codeInspection.* import com.intellij.psi.* import siosio.doma.* import siosio.doma.inspection.* import siosio.doma.inspection.dao.quickfix.* import siosio.doma.psi.* import java.util.* fun rule(rule: DaoInspectionRule.() -> Unit): DaoInspectionRule { val daoInspectionRule = DaoInspectionRule() daoInspectionRule.rule() return daoInspectionRule } interface DaoRule { fun inspect(problemsHolder: ProblemsHolder, daoMethod: PsiDaoMethod): Unit } /** * DAOクラスのインスペクションルール */ class DaoInspectionRule : Rule<PsiDaoMethod> { private val rules: MutableList<DaoRule> = ArrayList() override fun inspect(problemsHolder: ProblemsHolder, element: PsiDaoMethod) { rules.forEach { it.inspect(problemsHolder, element) } } fun sql(required: Boolean) { val sql = Sql(required) rules.add(sql) } fun parameterRule(init: ParameterRule.() -> Unit) { val parameterRule = ParameterRule().apply(init) requireNotNull(parameterRule.message) { "message must be set" } rules.add(parameterRule) } fun returnRule(init: ReturnRule.() -> Unit) { val returnTypeRule = ReturnRule() .apply(init) rules.add(returnTypeRule) } } /** * SQLファイルの検査を行うクラス。 */ class Sql(private val required: Boolean) : DaoRule { override fun inspect(problemsHolder: ProblemsHolder, daoMethod: PsiDaoMethod) { if (!required && !daoMethod.useSqlFile() || daoMethod.getModule() == null) { return } if (daoMethod.getAnnotation(sqlAnnotationName) != null || daoMethod.getAnnotation(sqlExperimentalAnnotationName) != null) { return } if (!daoMethod.containsSqlFile()) { problemsHolder.registerProblem( daoMethod.nameIdentifier!!, DomaBundle.message("inspection.dao.sql-not-found"), ProblemHighlightType.ERROR, CreateSqlFileQuickFixFactory.create(daoMethod)) } } } /** * パラメータの検査を行うクラス */ class ParameterRule : DaoRule { var message: String? = null var errorElement: (PsiDaoMethod) -> PsiElement = { psiDaoMethod -> psiDaoMethod.parameterList } var errorElements: (PsiDaoMethod) -> List<PsiElement> = { psiDaoMethod -> listOf(errorElement.invoke(psiDaoMethod)) } var rule: List<PsiParameter>.(PsiDaoMethod) -> Boolean = { _ -> true } var quickFix: ((PsiElement) -> LocalQuickFix)? = null override fun inspect(problemsHolder: ProblemsHolder, daoMethod: PsiDaoMethod) { val params = daoMethod.parameterList.parameters.toList() if (!params.rule(daoMethod)) { val register: (PsiElement) -> Unit = when (quickFix) { null -> { el -> problemsHolder.registerProblem(el, DomaBundle.message(message!!)) } else -> { el -> problemsHolder.registerProblem(el, DomaBundle.message(message!!), quickFix!!.invoke(el)) } } errorElements.invoke(daoMethod) .forEach(register) } } } /** * 戻り値の検査を行うクラス */ class ReturnRule : DaoRule { var message: String? = null var errorElement: (PsiDaoMethod) -> PsiElement = { psiDaoMethod -> psiDaoMethod.returnTypeElement!! } var rule: PsiTypeElement.(PsiDaoMethod) -> Boolean = { _ -> true } var quickFix: (() -> LocalQuickFix)? = null var messageArgs: Array<String> = emptyArray() override fun inspect(problemsHolder: ProblemsHolder, daoMethod: PsiDaoMethod) { val returnTypeElement = daoMethod.returnTypeElement ?: return if (returnTypeElement.rule(daoMethod).not()) { when(quickFix) { null -> problemsHolder.registerProblem(errorElement.invoke(daoMethod), DomaBundle.message(message!!, *messageArgs)) else -> problemsHolder.registerProblem(errorElement.invoke(daoMethod), DomaBundle.message(message!!, *messageArgs), quickFix!!.invoke()) } } } }
mit
c3d93c778ab9f96b45a01fa022295c6d
33.327731
152
0.644553
4.397201
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/support/DateHelper.kt
1
2590
package info.papdt.express.helper.support import android.content.Context import android.text.format.DateUtils import info.papdt.express.helper.R import java.util.* import java.util.concurrent.TimeUnit object DateHelper { fun getRelativeTimeTextAboutDays(time: Long): CharSequence { return DateUtils.getRelativeTimeSpanString( time, System.currentTimeMillis(), DateUtils.DAY_IN_MILLIS) } fun isUnknownTimeForGroup(time: Date): Boolean { val now = Calendar.getInstance().time return now.year + 1 == time.year && now.month == time.month && now.date == time.date } fun getDifferenceDaysForGroup(time: Date): Long { val now = Calendar.getInstance() val nowDate = now.time val diffDays = getDifferenceDays(time, nowDate) return when { diffDays < 3 -> diffDays diffDays <= 7 -> 7 diffDays <= 30 -> 30 diffDays <= 30 * 6 -> (diffDays / 30) * 30 diffDays <= 365 -> 365 else -> (diffDays.toFloat() / 365f).toLong() * 365 + 1 } } fun getDifferenceDaysTextForGroup(context: Context, diffDays: Long): String { return context.run { when { diffDays < 0 -> getString(R.string.diff_time_pending) diffDays == 0L -> getString(R.string.diff_time_today) diffDays == 1L -> getString(R.string.diff_time_yesterday) diffDays == 2L -> getString(R.string.diff_time_two_days_ago) diffDays == 3L -> getString(R.string.diff_time_three_days_ago) diffDays <= 7L -> getString(R.string.diff_time_in_this_week) diffDays <= 30L -> getString(R.string.diff_time_in_this_month) diffDays <= 30 * 6L -> getString(R.string.diff_time_some_months_ago, diffDays / 30) diffDays <= 365 -> getString(R.string.diff_time_in_this_year) else -> getString(R.string.diff_time_some_years_ago, diffDays / 365) } } } fun getDifferenceDays(d1: Date, d2: Date): Long { return TimeUnit.DAYS.convert(d2.time - d1.time, TimeUnit.MILLISECONDS) } fun dateToCalendar(date: Date): Calendar { val calendar = Calendar.getInstance() calendar.time = date return calendar } fun Calendar.getDaysOfMonth(): Int = get(Calendar.DAY_OF_MONTH) fun Calendar.getMonth(): Int = get(Calendar.MONTH) fun Calendar.getYear(): Int = get(Calendar.YEAR) fun Calendar.getDaysOfYear(): Int = get(Calendar.DAY_OF_YEAR) }
gpl-3.0
c9b7b53174ec0632b98945e79232b35b
36.550725
99
0.611197
3.906486
false
false
false
false
kory33/SignVote
src/main/kotlin/com/github/kory33/signvote/command/SignVoteCommandExecutor.kt
1
2742
package com.github.kory33.signvote.command import com.github.kory33.signvote.command.subcommand.* import com.github.kory33.signvote.constants.SubCommands import com.github.kory33.signvote.core.SignVote import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import java.util.* /** * Executor of SignVote root command. * This class acts as a proxy for all other specific "sub-commands" * such as "/signvote create" or "/signvote save". * All the sub-commands should have been put into * "command map" in the constructor of this class. * See the constructor's implementation for more details. */ class SignVoteCommandExecutor /** * Constructs and automatically registers sub-commands * @param plugin instance of SignVote plugin */ (plugin: SignVote) : CommandExecutor { private val subCommandExecutorMap: Map<String, SubCommandExecutor> private val defaultCommandExecutor: SubCommandExecutor init { val commandMaps = HashMap<String, SubCommandExecutor>() commandMaps.put(SubCommands.CREATE, CreateCommandExecutor(plugin)) commandMaps.put(SubCommands.ADD_SCORE, AddScoreCommandExecutor(plugin)) commandMaps.put(SubCommands.LIST, ListCommandExecutor(plugin)) commandMaps.put(SubCommands.OPEN, OpenCommandExecutor(plugin)) commandMaps.put(SubCommands.CLOSE, CloseCommandExecutor(plugin)) commandMaps.put(SubCommands.VOTE, VoteCommandExecutor(plugin)) commandMaps.put(SubCommands.UNVOTE, UnvoteCommandExecutor(plugin)) commandMaps.put(SubCommands.DELETEVP, DeleteVPCommandExecutor(plugin)) commandMaps.put(SubCommands.DELETE, DeleteCommandExecutor(plugin)) commandMaps.put(SubCommands.RELOAD, ReloadCommandExecutor(plugin)) commandMaps.put(SubCommands.SAVE, SaveCommandExecutor(plugin)) commandMaps.put(SubCommands.STATS, StatsCommandExecutor(plugin)) this.defaultCommandExecutor = HelpCommandExecutor(plugin, HashMap(commandMaps)) this.subCommandExecutorMap = Collections.unmodifiableMap(commandMaps) } override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { val argList = ArrayList(Arrays.asList(*args)) var executor: SubCommandExecutor? if (args.isEmpty()) { executor = this.defaultCommandExecutor } else { executor = this.subCommandExecutorMap[argList.removeAt(0)] } if (executor == null) { executor = this.defaultCommandExecutor } if (!executor.onCommand(sender, command, argList)) { executor.displayHelp(sender) } return true } }
gpl-3.0
be70481242059cf9a21c2099215dfad9
36.561644
114
0.731218
4.502463
false
false
false
false
mrebollob/LoteriadeNavidad
androidApp/src/main/java/com/mrebollob/loteria/android/presentation/home/ui/StatsSectionView.kt
1
3916
package com.mrebollob.loteria.android.presentation.home.ui import android.content.res.Configuration import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.mrebollob.loteria.android.R import com.mrebollob.loteria.android.presentation.platform.ui.theme.Grey4 import com.mrebollob.loteria.android.presentation.platform.ui.theme.LotteryTheme @Composable fun StatsSectionView( modifier: Modifier = Modifier, totalBet: Float, totalPrize: Float? ) { Column( modifier = modifier ) { Card( modifier = Modifier.fillMaxWidth(), elevation = 4.dp, ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 8.dp, vertical = 16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp), ) { Column( modifier = Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally ) { Text( color = Grey4, text = stringResource(id = R.string.lottery_stats_total_bet), textAlign = TextAlign.Center, style = MaterialTheme.typography.subtitle2 ) Text( text = stringResource(id = R.string.lottery_stats_money_format, totalBet), style = MaterialTheme.typography.h6, textAlign = TextAlign.Center, color = MaterialTheme.colors.onBackground ) } Column( modifier = Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally ) { Text( color = Grey4, text = stringResource(id = R.string.lottery_stats_total_prize), textAlign = TextAlign.Center, style = MaterialTheme.typography.subtitle2 ) Text( text = if (totalPrize != null) { stringResource(id = R.string.lottery_stats_money_format, totalPrize) } else { stringResource(id = R.string.lottery_stats_total_prize_empty) }, style = MaterialTheme.typography.h6, textAlign = TextAlign.Center, color = MaterialTheme.colors.onBackground ) } } } } } @Preview("Stats section") @Preview("Stats section (dark)", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun PreviewStatsSectionView() { LotteryTheme { Surface( modifier = Modifier.fillMaxSize() ) { Column( modifier = Modifier.padding(16.dp) ) { StatsSectionView( totalBet = 20.5f, totalPrize = null ) } } } }
apache-2.0
97b1febd70e68918a5d42cb8f7da3637
35.598131
98
0.558223
5.214381
false
false
false
false
zamesilyasa/kandrextensions
lib/src/main/kotlin/com/wnc_21/kandroidextensions/db/SQLiteDatabaseExtensions.kt
1
1318
package com.wnc_21.kandroidextensions.db import android.database.Cursor import android.database.DatabaseUtils import android.database.sqlite.SQLiteDatabase fun SQLiteDatabase.optQuery(table: String, columns: Array<out String>? = null, selection: String? = null, selectionArgs: Array<out String>? = null, groupBy: String? = null, having: String? = null, orderBy: String? = null, distinct: Boolean? = null, limit: String? = null): Cursor { return query(distinct ?: false, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit) } fun SQLiteDatabase.runTransaction(func: (db: SQLiteDatabase) -> Unit) { if (this.isReadOnly) { throw IllegalStateException("Transaction is not possible in read-only database instance") } try { beginTransaction() func(this) setTransactionSuccessful() } finally { endTransaction() } } fun SQLiteDatabase.count(table: String, selection: String? = null, selectionArgs: Array<String>? = null): Long { return DatabaseUtils.queryNumEntries(this, table, selection, selectionArgs) }
apache-2.0
9c7216073d6a373cd5cc7bb9e50e40b7
35.638889
112
0.598634
5.011407
false
false
false
false
bachhuberdesign/deck-builder-gwent
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/stattrack/StatTrackRepository.kt
1
2762
package com.bachhuberdesign.deckbuildergwent.features.stattrack import android.content.ContentValues import com.bachhuberdesign.deckbuildergwent.inject.annotation.PersistedScope import com.squareup.sqlbrite.BriteDatabase import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import javax.inject.Inject /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ @PersistedScope class StatTrackRepository @Inject constructor(val database: BriteDatabase) { companion object { @JvmStatic val TAG: String = StatTrackRepository::class.java.name } /** * Inserts a new row into [Match.TABLE] *OR* updates the row if an id is already set. * * @param match Match to persist */ fun saveMatch(match: Match): Int { val values = ContentValues() values.put(Match.DECK_ID, match.deckId) values.put(Match.OUTCOME, match.outcome) values.put(Match.OPPONENT_FACTION, match.opponentFaction) values.put(Match.OPPONENT_LEADER, match.opponentLeader) values.put(Match.NOTES, match.notes) values.put(Match.PLAYED_DATE, match.playedDate.time) values.put(Match.CREATED_DATE, match.createdDate.time) values.put(Match.LAST_UPDATE, match.lastUpdate.time) if (match.id == 0) { match.id = database.insert(Match.TABLE, values).toInt() } else { database.update(Match.TABLE, values, "${Match.ID} = ${match.id}") } return match.id } /** * Deletes a row from [Match.TABLE]. * * @param matchId ID of the match to be deleted. * @return [Boolean] True if match was successfully deleted, false if no row deleted. */ fun deleteMatch(matchId: Int): Boolean { return database.delete(Match.TABLE, "${Match.ID} = $matchId") > 0 } /** * * @return [Match] */ fun getMostRecentMatch(): Match? { val cursor = database.query("SELECT * FROM ${Match.TABLE} " + "ORDER BY ${Match.LAST_UPDATE} DESC " + "LIMIT 1") cursor.use { cursor -> if (cursor.moveToNext()) { return Match.MAPPER.apply(cursor) } else { return null } } } /** * @param deckId ID of the deck to observe. */ fun observeMatchesForDeck(deckId: Int): Observable<MutableList<Match>> { val query = "SELECT * FROM ${Match.TABLE} " + "WHERE ${Match.DECK_ID} = $deckId" return database.createQuery(Match.TABLE, query) .mapToList(Match.MAP1) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } }
apache-2.0
b12081a73cbf2485879948380e349fa8
29.7
89
0.616582
4.122388
false
false
false
false
Kotlin/dokka
plugins/all-modules-page/src/test/kotlin/templates/ResolveLinkGfmCommandResolutionTest.kt
1
2788
package org.jetbrains.dokka.allModulesPage.templates import org.jetbrains.dokka.DokkaModuleDescriptionImpl import org.jetbrains.dokka.allModulesPage.MultiModuleAbstractTest import org.jetbrains.dokka.base.resolvers.shared.RecognizedLinkFormat import org.jetbrains.dokka.gfm.GfmCommand.Companion.templateCommand import org.jetbrains.dokka.gfm.GfmPlugin import org.jetbrains.dokka.gfm.ResolveLinkGfmCommand import org.jetbrains.dokka.gfm.templateProcessing.GfmTemplateProcessingPlugin import org.jetbrains.dokka.links.DRI import org.junit.Rule import org.junit.jupiter.api.Test import org.junit.rules.TemporaryFolder import java.io.File import kotlin.test.assertEquals class ResolveLinkGfmCommandResolutionTest : MultiModuleAbstractTest() { @get:Rule val folder: TemporaryFolder = TemporaryFolder() private fun configuration() = dokkaConfiguration { modules = listOf( DokkaModuleDescriptionImpl( name = "module1", relativePathToOutputDirectory = folder.root.resolve("module1"), includes = emptySet(), sourceOutputDirectory = folder.root.resolve("module1"), ), DokkaModuleDescriptionImpl( name = "module2", relativePathToOutputDirectory = folder.root.resolve("module2"), includes = emptySet(), sourceOutputDirectory = folder.root.resolve("module2"), ) ) outputDir = folder.root } @Test fun `should resolve link to another module`(){ val testedDri = DRI( packageName = "package2", classNames = "Sample", ) val link = StringBuilder().apply { templateCommand(ResolveLinkGfmCommand(testedDri)){ append("Sample text inside") } }.toString() val expected = "[Sample text inside](../module2/package2/-sample/index.md)" val content = setup(link) val configuration = configuration() testFromData(configuration, pluginOverrides = listOf(GfmTemplateProcessingPlugin(), GfmPlugin()), useOutputLocationFromConfig = true) { finishProcessingSubmodules = { assertEquals(expected, content.readText().trim()) } } } private fun setup(content: String): File { folder.create() val innerModule1 = folder.newFolder( "module1") val innerModule2 = folder.newFolder( "module2") val packageList = innerModule2.resolve("package-list") packageList.writeText(mockedPackageListForPackages(RecognizedLinkFormat.DokkaGFM, "package2")) val contentFile = innerModule1.resolve("index.md") contentFile.writeText(content) return contentFile } }
apache-2.0
57309f05eb850e3de6f3e8a5ad80eb17
36.675676
143
0.670732
4.831889
false
true
false
false
0Chencc/CTFCrackTools
src/org/ctfcracktools/fuction/CoreFunc.kt
1
21561
package org.ctfcracktools.fuction import org.apache.commons.codec.binary.Base32 import org.apache.commons.codec.binary.Base64.* import org.apache.commons.text.StringEscapeUtils import java.net.URLDecoder import java.net.URLEncoder import java.util.* import java.util.regex.Matcher import java.util.regex.Pattern import javax.swing.JOptionPane /** * @author 林晨0chencc * @since 2017/12/2 * @version 1.0.2 */ class CoreFunc{ /** * 主函数 * @param input 需要加密/解密的字符串传入 * @param type 加密类型 * @return String 编码后的结果 */ fun callFunc(input:String,type:String): String? { val funcMap = mutableMapOf(CodeMode.CRYPTO_FENCE to ::fence, CodeMode.CRYPTO_CAESAR to ::caesar, CodeMode.CRYPTO_PIG to ::pigCode, CodeMode.CRYPTO_ROT13 to ::rot13, CodeMode.CRYPTO_HEX_2_STRING to ::hextoString, CodeMode.CRYPTO_STRING_2_HEX to ::stringtoHex, CodeMode.CRYPTO_UNICODE_2_ASCII to ::unicodeToAscii, CodeMode.CRYPTO_ASCII_2_UNICODE to ::asciiToUnicode, CodeMode.CRYPTO_REVERSE to ::reverse, CodeMode.DECODE_MORSE to ::morseDecode, CodeMode.DECODE_BACON to ::baconCodeDecode, CodeMode.DECODE_BASE64 to ::base64de, CodeMode.DECODE_BASE32 to ::base32de, CodeMode.DECODE_URL to ::urlDecoder, CodeMode.DECODE_UNICODE to ::unicodeDecode, CodeMode.DECODE_HTML to ::htmlDecode, CodeMode.DECODE_VIGENERE to ::vigenereDeCode, CodeMode.ENCODE_MORSE to ::morseEncode, CodeMode.ENCODE_BACON to ::baconCodeEncode, CodeMode.ENCODE_BASE64 to ::base64en, CodeMode.ENCODE_BASE32 to ::base32en, CodeMode.ENCODE_URL to ::urlEncoder, CodeMode.ENCODE_UNICODE to ::unicodeEncode, CodeMode.ENCODE_HTML to ::htmlEncode, CodeMode.ENCODE_VIGENERE to ::vigenereEnCode) return funcMap[type]?.let { it(input) } } /** * 栅栏密码 * @param input 待加密解密的字符串 * @return String */ private fun fence(input: String):String { val str:Array<String?> = arrayOfNulls<String>(1024) val x = IntArray(1024) val result = StringBuffer() var a = 0 var nums = 0 if (input.length!=1&&input.length!=2) { (2 until input.length).forEach { i -> if (input.length % i == 0) { x[a] = i a++ } } } if(a!=0) { (0 until a).forEach { i -> result.append("${i + 1}:") (0 until input.length / x[i]).forEach { j -> str[nums] = input.substring(0 + (x[i] * j), x[i] + (x[i] * j)) nums++ } (0 until str[0]!!.length).forEach { ji -> (0 until nums).forEach { s -> result.append(str[s]!!.substring(ji,ji+1)) } } nums =0 result.append("\n") } }else{ val newstrlenth:Int = input.replace(" ","").length if (newstrlenth !=1 && newstrlenth !=2){ (2..newstrlenth-1).forEach { i -> if (newstrlenth%i==0){ x[a]=i a++ } } } if (a != 0) { (0 until a).forEach { it -> result.append(" " + x[it]) } (0 until a).forEach { i -> result.append("${i+1}:") (0 until newstrlenth / x[i]).forEach { j -> str[nums] = input.substring(0 + x[i] * j, x[i] + x[i] * j) nums++ } (0 until str[0]!!.length).forEach { j -> (0 until nums).forEach { result.append(str[it]!!.substring(j, j + 1)) } } nums = 0 result.append('\n') } } } return result.toString() } /** * 凯撒密码/Caesar Code * @param input 待加密解密的字符串 * @return String */ private fun caesar(input:String):String{ val word:CharArray=input.toCharArray() val result = StringBuffer() (0 until 26).forEach { (word.indices).forEach { j -> if (word[j].isUpperCase()){ if(word[j]=='Z') word[j]='A' else word[j] = (word[j].toInt() + 1).toChar() }else if(word[j].isLowerCase()){ if(word[j]=='z') word[j]='a' else word[j]=(word[j].toInt()+1).toChar() } } result.append(word+'\n') } return result.toString() } /** * 维吉利亚密码 * @param input 待加解密的字符串 * @param mode VIGENERE_MODE_DECODE为解密 VIGENERE_MODE_DECODE为加密 * @return String */ private fun vigenereCode(input:String,mode:String):String{ val pass = input.toCharArray() val key = JOptionPane.showInputDialog("Please input key").toCharArray() var i = 0 var j:Int var q = 0 var k:Int var m:Int when(mode){ CodeMode.DECODE_VIGENERE -> return StringBuilder() .let{ result -> while (i<pass.size) { when { pass[i].isUpperCase() -> { j = q%key.size k = UpperCase.indexOf(key[j].toUpperCase()) m = UpperCase.indexOf(pass[i]) result.append(UpperCase[(m+k)%26]) q++ } pass[i].isLowerCase() -> { j = q%key.size k = LowerCase.indexOf(key[j].toLowerCase()) m = LowerCase.indexOf(pass[i]) result.append(LowerCase[(m+k)%26]) q++ } else -> result.append(pass[i]) } i++ } result } .toString() CodeMode.ENCODE_VIGENERE -> return StringBuilder() .let{ result -> while (i<pass.size) { when { pass[i].isUpperCase() -> { j = q%key.size k = UpperCase.indexOf(key[j].toUpperCase()) m = UpperCase.indexOf(pass[i]) if(m<k) m+=26 result.append(UpperCase[m-k]) q++ } pass[i].isLowerCase() -> { j = q%key.size k = LowerCase.indexOf(key[j].toLowerCase()) m = LowerCase.indexOf(pass[i]) if(m<k) m+=26 result.append(LowerCase[m-k]) q++ } else -> result.append(pass[i]) } i++ } result } .toString() else -> return "None" } } /** * 维吉利亚密码加密 依赖vigenereCode * @param input 待加密的字符串 * @return String */ private fun vigenereEnCode(input:String): String = vigenereCode(input, CodeMode.ENCODE_VIGENERE) /** * 维吉利亚解密 依赖vigenereCode * @param input 待解密的字符串 * @return String */ private fun vigenereDeCode(input:String):String = vigenereCode(input, CodeMode.DECODE_VIGENERE) /** * 猪圈密码 * @param input 待解密的字符串 * @return String */ private fun pigCode(input:String):String{ val result = StringBuffer() val keymap= mapOf('A' to 'J','B' to 'K','C' to 'L','D' to 'M', 'E' to 'N','F' to 'O','G' to 'P','H' to 'Q','I' to 'R','J' to 'A','K' to 'B','L' to 'C', 'M' to 'D','N' to 'E','O' to 'F','P' to 'G','Q' to 'H','R' to 'I','S' to 'W','T' to 'X', 'U' to 'Y','V' to 'Z','W' to 'S','X' to 'T','Y' to 'U','Z' to 'V') val word = input.toCharArray() for (i in word.indices){ if (word[i].isUpperCase()){ result.append(keymap.get(word[i])!!) }else if(word[i].isLowerCase()){ result.append(keymap.get(word[i].toUpperCase())!!.toLowerCase()) }else{ result.append(word[i]) } } return result.toString() } /** * ROT13 * @param input 待编码的字符串 * @return String */ private fun rot13(input:String):String{ var word = input.toCharArray() val result = StringBuffer() for (i in 0 until word.size){ when { word[i] in 'a'..'m' -> word[i]=(word[i].toInt()+13).toChar() word[i] in 'A'..'M' -> word[i]=(word[i].toInt()+13).toChar() word[i] in 'n'..'z' -> word[i]=(word[i].toInt()-13).toChar() word[i] in 'N'..'Z' -> word[i]=(word[i].toInt()-13).toChar() } result.append(word[i]) } return result.toString() } /** * 培根密码加密 * @param input 待加密的字符串 * @return String */ private fun baconCodeEncode(input:String):String{ val keymap = mapOf("A" to "aaaaa","B" to "aaaab","C" to "aaaba", "D" to "aaabb","E" to "aabaa","F" to "aabab","G" to "aabba","H" to "aabbb","I" to "abaaa", "J" to "abaab","K" to "ababa","L" to "ababb","M" to "abbaa","N" to "abbab","O" to "abbba", "P" to "abbbb","Q" to "baaaa","R" to "baaab","S" to "baaba","T" to "baabb","U" to "babaa", "V" to "babab","W" to "babba","X" to "babbb","Y" to "bbaaa","Z" to "bbaab","a" to "AAAAA", "b" to "AAAAB","c" to "AAABA","d" to "AAABB","e" to "AABAA","f" to "AABAB","g" to "AABBA", "h" to "AABBB","i" to "ABAAA","j" to "ABAAB","k" to "ABABA","l" to "ABABB","m" to "ABBAA", "n" to "ABBAB","o" to "ABBBA","p" to "ABBBB","q" to "BAAAA", "r" to "BAAAB","s" to "BAABA","t" to "BAABB","u" to "BABAA","v" to "BABAB","w" to "BABBA", "x" to "BABBB","y" to "BBAAA","z" to "BBAAB") return StringBuilder() .let{ result -> if(is26word(input)) { splitNum(input,1).forEach {result.append(keymap[it])} }else{ result.append("有字符不属于26字母其中") } result } .toString() } /** * 培根密码解密 * @param input 待加密的字符串 * @return String */ private fun baconCodeDecode(input: String):String{ val keymap = mapOf("aaaaa" to 'A',"aaaab" to 'B',"aaaba" to 'C', "aaabb" to 'D',"aabaa" to 'E',"aabab" to 'F',"aabba" to 'G',"aabbb" to 'H',"abaaa" to 'I', "abaab" to 'J',"ababa" to 'K',"ababb" to 'L',"abbaa" to 'M',"abbab" to 'N',"abbba" to 'O', "abbbb" to 'P',"baaaa" to 'Q',"baaab" to 'R',"baaba" to 'S',"baabb" to 'T',"babaa" to 'U', "babab" to 'V',"babba" to 'W',"babbb" to 'X',"bbaaa" to 'Y',"bbaab" to 'Z',//UpperCase大写字符 "AAAAA" to 'a',"AAAAB" to 'b',"AAABA" to 'c',"AAABB" to 'd',"AABAA" to 'e',"AABAB" to 'f', "AABBA" to 'g',"AABBB" to 'h',"ABAAA" to 'i',"ABAAB" to 'j',"ABABA" to 'k', "ABABB" to 'l',"ABBAA" to 'm',"ABBAB" to 'n',"ABBBA" to 'o', "ABBBB" to 'p',"BAAAA" to 'q', "BAAAB" to 'r',"BAABA" to 's',"BAABB" to 't',"BABAA" to 'u',"BABAB" to 'v',"BABBA" to 'w', "BABBB" to 'x',"BBAAA" to 'y',"BBAAB" to 'z' ) return StringBuilder() .let{ result -> if(isBacon(input)){ val inputnew = input.replace(" ","") splitNum(inputnew,5,"[ab]{5}").forEach { result.append(keymap[it]) } }else{ result.append("并非是培根密码") } result } .toString() } private fun base64de(input: String):String = String(decodeBase64(input)) private fun base64en(input: String):String = encodeBase64String(input.toByteArray()) private fun base32de(input:String):String = String(Base32().decode(input)) private fun base32en(input:String):String = Base32().encodeAsString(input.toByteArray()) /** * 16进制转字符串 * @param input 待编码的字符串 * @return String */ private fun hextoString(input:String):String{ return StringBuilder() .let{ result -> (0 until input.length-1 step 2) .map{ input.substring(it, it+2) } .map { Integer.parseInt(it,16) } .forEach { result.append(it.toChar()) } result } .toString() } /** * 字符串转16进制 * @param input 待编码的字符串 * @return String */ private fun stringtoHex(input:String):String{ return StringBuilder() .let{ result -> input.toCharArray().forEach {result.append(Integer.toHexString(it.toInt())) } result } .toString() } /** * 摩斯电码编码 * @param input 待编码的字符串 * @return String */ private fun morseEncode(input: String):String { return StringBuilder() .let{ result -> input.toLowerCase().toCharArray().forEach { when { isChar(it) -> result.append(morseCharacters[(it - 'a')]+" ") isDigit(it) -> result.append(morseDigits[(it - '0')]+" ") isSymbol(it) -> result.append(morseSymbols[symbols.indexOf(it)]+" ") // else -> result.append(" ") } } result } .toString() } /** * 摩斯密码解码 * @param input 待解码的字符串 * @return String */ private fun morseDecode(input:String):String{ initMorseTable() val morse=format(input) val st=StringTokenizer(morse) val result=StringBuilder(morse.length / 2) while (st.hasMoreTokens()) { result.append(htMorse[st.nextToken()]) } return result.toString() } private fun urlEncoder(input: String):String = URLEncoder.encode(input,"utf-8").replace("+","%20")//Url编码加密 private fun urlDecoder(input: String):String = URLDecoder.decode(input,"utf-8")//Url编码解密 private fun unicodeEncode(input: String):String{ return StringBuilder() .let { result -> input.toCharArray().forEach {result.append("\\u"+Integer.toHexString(it.toInt())) } result } .toString() } private fun unicodeDecode(input: String):String{ return StringBuilder() .let{ result -> val hex=input.split("\\u") (1 until hex.size) .map { Integer.parseInt(hex[it], 16) } .forEach { result.append(it.toChar()) } result } .toString() } /** * Unicode编码转Ascii编码 * @param input 待编码的字符串 * @return String */ private fun unicodeToAscii(input:String):String{ return StringBuilder() .let{ result -> val pout = Pattern.compile("\\&\\#(\\d+)").matcher(input) while (pout.find()){ result.append(Integer.valueOf(pout.group(1)).toInt().toChar()) } result } .toString() } /** * Ascii编码转Unicode编码 * @param input 待编码的字符串 * @return String */ private fun asciiToUnicode(input: String):String{ return StringBuilder() .let { result -> input.toCharArray().forEach { result.append("&#"+it.toInt()+";")} result } .toString() } /** * 字符翻转,顾名思义 * @param input 待翻转的字符串 * @return String */ private fun reverse(input:String):String{ val result = StringBuilder() val tmp = input.toCharArray() var a=tmp.size-1 while (a > -1) { result.append(tmp[a]) a-=1 } return result.toString() } /* fun HillCodeEncode(input:String,key:String):String{ val keymatrix:CharArray = key.split(" ") as CharArray var tmp[]:<String?>Array when{ keymatrix.size/4 == 0 -> 0 until keymatrix.size%4.forEach{ } } return StringBuffer() .let { result-> } .toString() }*/ private fun htmlEncode(input:String): String = StringEscapeUtils.escapeHtml4(input) private fun htmlDecode(input:String):String = StringEscapeUtils.unescapeHtml4(input) /* 内置方法/内置常量 */ private val UpperCase:String ="ABCDEFGHIJKLMNOPQRSTUVWXYZ" private val LowerCase:String = "abcdefghijklmnopqrstuvwxyz" // private val SplitString = {//多次切割字符串 // input:String -> // val tmp = input.split(",") // val result = StringBuilder() // tmp.forEach{ // val tmp_1 = it.split(" to ") // result.append(tmp_1[1]+" to "+tmp_1[0]+",") // } // result.toString() // } private fun splitNum(input:String,num:Int):Array<String?>{ val str:Array<String?> = arrayOfNulls(input.length/num) (1..input.length/num).forEach { i->str.set(i-1,input.substring(i*num-num,i*num)) } return str } private fun splitNum(input:String,num:Int,pattern:String):Array<String?>{ val r:Pattern = Pattern.compile(pattern) val m: Matcher = r.matcher(input) var input_m = "" var a = true while (a){ if(!m.find()) a=false else input_m += m.group() } return splitNum(input_m,num) } val isBacon = { input:String -> var tmp:Boolean = false input.toCharArray().forEach { tmp = (it=='A'||it=='B')||(it == 'a'||it=='b') } tmp } val is26word = { input:String -> var tmp = false input.toCharArray().forEach { tmp = isChar(it) } tmp } var htMorse: Hashtable<String, Char> = Hashtable() private fun initMorseTable(){ (0..25).forEach { i -> htMorse.put(morseCharacters[i], Character.valueOf((65+i).toChar())) } (0..9).forEach { i -> htMorse.put(morseDigits[i], Character.valueOf((48+i).toChar())) } (0..16).forEach{ i -> htMorse.put(morseSymbols[i], symbols[i]) } } val isChar = {c:Char -> c.isLowerCase()||c.isUpperCase()} val isDigit = {c:Char -> (c >='0')&&(c <= '9')} val isSymbol = {c:Char -> c in symbols} /* moresCode */ private val morseCharacters = arrayOf(".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "src", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..") private val morseDigits = arrayOf("-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.") private val morseSymbols = arrayOf(".-.-.-","---...","--..--","-.-.-.","..--..","-...-",".----.","-..-.","-.-.--", "-....-", "..--.-",".-..-.","-.--.","-.--.-","...-..-", ".--.-.",".-...") private val symbols: Array<Char> = arrayOf('.', ':', ',', ';', '?', '=', '\'', '/', '!', '-', '_', '"', '(', ')', '$', '@', '&') val format = { input:String-> val word = input.toCharArray() val result = StringBuilder() for(i in word.indices){ when{ word[i] == '\n' -> word[i]=' ' word[i] == '.' -> { result.append(word[i]) } word[i] == '-' -> { result.append(word[i]) } word[i] == ' ' -> { result.append(word[i]) } } } result.toString() } }
gpl-3.0
5b771d79fa8442bef7be33e22dccc9d9
35.184483
132
0.448706
3.775319
false
false
false
false
Fitbit/MvRx
dogs/src/main/java/com/airbnb/mvrx/dogs/DogViewModel.kt
1
1152
package com.airbnb.mvrx.dogs import com.airbnb.mvrx.MvRxViewModelFactory import com.airbnb.mvrx.ViewModelContext import com.airbnb.mvrx.dogs.data.DogRepository import com.airbnb.mvrx.dogs.utils.MvRxViewModel import io.reactivex.schedulers.Schedulers class DogViewModel( initialState: DogState, private val dogRepository: DogRepository ) : MvRxViewModel<DogState>(initialState) { init { dogRepository.getDogs().execute { copy(dogs = it) } } fun loveDog(dogId: Long) = setState { copy(lovedDogId = dogId) } fun adoptLovedDog() = withState { state -> val lovedDog = state.lovedDog ?: throw IllegalStateException("You must love a dog first!") dogRepository.adoptDog(lovedDog) .subscribeOn(Schedulers.io()) .execute { copy(adoptionRequest = it) } } companion object : MvRxViewModelFactory<DogViewModel, DogState> { override fun create(viewModelContext: ViewModelContext, state: DogState): DogViewModel? { val dogRepository = viewModelContext.app<DogApplication>().dogsRepository return DogViewModel(state, dogRepository) } } }
apache-2.0
e24de52656d1ffef3e8b05defe519751
33.909091
98
0.709201
4.189091
false
false
false
false
JimSeker/ui
RecyclerViews/LotsofLists_kt/app/src/main/java/edu/cs4730/lotsoflists_kt/MainActivity.kt
1
12453
package edu.cs4730.lotsoflists_kt import android.content.res.Configuration import android.os.Bundle import android.util.Log import android.view.* import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import android.widget.AdapterView.OnItemClickListener import android.widget.ArrayAdapter import android.widget.EditText import android.widget.ListView import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.FloatingActionButton /** * complex example of a navigation drawer with recyclerview. Plus you can add more items * to the list and add more categories (ie new lists) as well. * * * The list data is all handled in the ViewModel, ListsViewModel. */ class MainActivity : AppCompatActivity() { private lateinit var toolbar: Toolbar private lateinit var mDrawerToggle: ActionBarDrawerToggle private lateinit var mDrawerlayout: DrawerLayout private lateinit var mDrawerList: ListView lateinit var mRecyclerView: RecyclerView lateinit var mAdapter: myAdapter lateinit var fab: FloatingActionButton lateinit var addBut: FloatingActionButton var IsCatInput = false lateinit var mViewModel: ListsViewModel lateinit var catAdapter: ArrayAdapter<String> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //use the androidx toolbar instead of the default one. toolbar = findViewById<View>(R.id.app_bar) as Toolbar setSupportActionBar(toolbar) mViewModel = ViewModelProvider(this)[ListsViewModel::class.java] //setup the RecyclerView mRecyclerView = findViewById<View>(R.id.list) as RecyclerView mRecyclerView.layoutManager = LinearLayoutManager(this) mRecyclerView.itemAnimator = DefaultItemAnimator() //setup the adapter, which is myAdapter, see the code. mAdapter = myAdapter(null, R.layout.my_row, this) //observer will fix the null //add the adapter to the recyclerview mRecyclerView.adapter = mAdapter mViewModel.listLD.observe( this ) { myList -> mAdapter.newData(myList) } //swipe listener for the recycler view //ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT |ItemTouchHelper.LEFT) { val simpleItemTouchCallback: ItemTouchHelper.SimpleCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { //likely allows to for animations? or moving items in the view I think. return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { //called when it has been animated off the screen. So item is no longer showing. //use ItemtouchHelper.X to find the correct one. if (direction == ItemTouchHelper.RIGHT) { //Toast.makeText(getBaseContext(),"Right?", Toast.LENGTH_SHORT).show(); val item = viewHolder.absoluteAdapterPosition //think this is where in the array it is. //((myAdapter)viewHolder).myName.getText(); mViewModel.removeItem(item) } } } val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback) itemTouchHelper.attachToRecyclerView(mRecyclerView) fab = findViewById<View>(R.id.fab) as FloatingActionButton mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { //yes this code is kind of a mess. And better I got some of from here: //https://github.com/Suleiman19/Android-Material-Design-for-pre-Lollipop/tree/master/MaterialSample/app/src/main/java/com/suleiman/material/activities //in the fabhideactivity.java var scrollDist = 0 private var isVisible = true private val HIDE_THRESHOLD = 100f private val SHOW_THRESHOLD = 50f override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == RecyclerView.SCROLL_STATE_IDLE) { //but I want the fab back after the scrolling is done. Not scroll down a little... that is just stupid. if (!isVisible) { fab.animate().translationY(0f).setInterpolator(DecelerateInterpolator(2F)) .start() //scrollDist = 0; isVisible = true Log.v("c", "state changed, show be showing....") } } } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) //so animate to slide down and then and set invisible variables or something. // Check scrolled distance against the minimum if (isVisible && scrollDist > HIDE_THRESHOLD) { // Hide fab & reset scrollDist fab.animate() .translationY((fab.height + resources.getDimensionPixelSize(R.dimen.fab_margin)).toFloat()) .setInterpolator(AccelerateInterpolator(2F)).start() scrollDist = 0 isVisible = false Log.v("onScrolled", "maded fab invisible") } else if (!isVisible && scrollDist < -SHOW_THRESHOLD) { // Show fab & reset scrollDist fab.animate().translationY(0f).setInterpolator(DecelerateInterpolator(2F)) .start() scrollDist = 0 isVisible = true Log.v("onScrolled", "maded fab visible") } // Whether we scroll up or down, calculate scroll distance if (isVisible && dy > 0 || !isVisible && dy < 0) { scrollDist += dy } } }) fab.setOnClickListener { IsCatInput = false showInputDialog("Input New Data") } // enable ActionBar app icon to behave as action to toggle nav drawer supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.setHomeButtonEnabled(true) mDrawerlayout = findViewById<View>(R.id.drawer_layout) as DrawerLayout mDrawerToggle = object : ActionBarDrawerToggle( this, // host activity mDrawerlayout, //drawerlayout object toolbar, //toolbar R.string.drawer_open, //open drawer description required! R.string.drawer_close ) { //closed drawer description //called once the drawer has closed. override fun onDrawerOpened(drawerView: View) { super.onDrawerOpened(drawerView) supportActionBar!!.title = "Categories" invalidateOptionsMenu() // creates call to onPrepareOptionsMenu() } //called when the drawer is now open. override fun onDrawerClosed(drawerView: View) { super.onDrawerClosed(drawerView) supportActionBar!!.setTitle(R.string.app_name) invalidateOptionsMenu() // creates call to onPrepareOptionsMenu() } } //To disable the icon for the drawer, change this to false //mDrawerToggle.setDrawerIndicatorEnabled(true); mDrawerlayout.addDrawerListener(mDrawerToggle) //setup the addcat "button" addBut = findViewById<View>(R.id.addCat) as FloatingActionButton addBut.setOnClickListener { IsCatInput = true showInputDialog("Add New Category") } //lastly setup the listview with some simple categories via an array. catAdapter = ArrayAdapter<String>( this, R.layout.drawer_list_item, ArrayList<String>() ) //mViewModel.getAllCat() ); mViewModel.catLD.observe( this ) { strings -> catAdapter.clear() catAdapter.addAll(strings) } mDrawerList = findViewById<View>(R.id.left_drawer) as ListView mDrawerList.adapter = catAdapter mDrawerList.setItemChecked(mViewModel.getlist(), true) //set the highlight correctly. mDrawerList.onItemClickListener = OnItemClickListener { arg0, view, position, index -> //yes, this should do something for more interesting. but this is an example. val item = mDrawerList.adapter.getItem(position).toString() //change the list view to correct one. mViewModel.setlist(position) // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true) //now close the drawer! mDrawerlayout.closeDrawers() } } /** * We are going to add data * setup a dialog fragment to ask the user for the new item data or category. */ fun showInputDialog(title: String?) { val inflater = LayoutInflater.from(this) val textenter = inflater.inflate(R.layout.layout_dialog, null) val userinput = textenter.findViewById<View>(R.id.item_added) as EditText val builder = AlertDialog.Builder(ContextThemeWrapper(this, R.style.AppTheme_Dialog)) builder.setView(textenter).setTitle(title) builder.setPositiveButton( "Add" ) { dialog, id -> //add the list and allow the observer to fixes the lists. if (IsCatInput) { //add new category mViewModel.addCat(userinput.text.toString()) } else { //add new data item to list. mViewModel.addItem(userinput.text.toString()) } //Toast.makeText(getBaseContext(), userinput.getText().toString(), Toast.LENGTH_LONG).show(); } .setNegativeButton( "Cancel" ) { dialog, id -> dialog.cancel() } val dialog = builder.create() dialog.show() } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId return if (id == R.id.action_settings) { true } else super.onOptionsItemSelected(item) } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig) } }
apache-2.0
b1dc1adb3a8dca81aba61a9b871ab03d
44.615385
162
0.628122
5.390909
false
false
false
false
square/moshi
moshi/src/main/java/com/squareup/moshi/AdapterMethodsFactory.kt
1
14552
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.squareup.moshi import com.squareup.moshi.internal.canonicalize import com.squareup.moshi.internal.checkNull import com.squareup.moshi.internal.hasNullable import com.squareup.moshi.internal.jsonAnnotations import com.squareup.moshi.internal.knownNotNull import com.squareup.moshi.internal.toStringWithAnnotations import java.io.IOException import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.lang.reflect.ParameterizedType import java.lang.reflect.Type internal class AdapterMethodsFactory( private val toAdapters: List<AdapterMethod>, private val fromAdapters: List<AdapterMethod> ) : JsonAdapter.Factory { override fun create( type: Type, annotations: Set<Annotation>, moshi: Moshi ): JsonAdapter<*>? { val toAdapter = get(toAdapters, type, annotations) val fromAdapter = get(fromAdapters, type, annotations) if (toAdapter == null && fromAdapter == null) return null val delegate: JsonAdapter<Any>? = if (toAdapter == null || fromAdapter == null) { try { moshi.nextAdapter(this, type, annotations) } catch (e: IllegalArgumentException) { val missingAnnotation = if (toAdapter == null) "@ToJson" else "@FromJson" throw IllegalArgumentException( "No $missingAnnotation adapter for ${type.toStringWithAnnotations(annotations)}", e ) } } else { null } toAdapter?.bind(moshi, this) fromAdapter?.bind(moshi, this) return object : JsonAdapter<Any>() { override fun toJson(writer: JsonWriter, value: Any?) { when { toAdapter == null -> knownNotNull(delegate).toJson(writer, value) !toAdapter.nullable && value == null -> writer.nullValue() else -> { try { toAdapter.toJson(moshi, writer, value) } catch (e: InvocationTargetException) { val cause = e.cause if (cause is IOException) throw cause throw JsonDataException("$cause at ${writer.path}", cause) } } } } override fun fromJson(reader: JsonReader): Any? { return when { fromAdapter == null -> knownNotNull(delegate).fromJson(reader) !fromAdapter.nullable && reader.peek() == JsonReader.Token.NULL -> reader.nextNull<Any>() else -> { try { fromAdapter.fromJson(moshi, reader) } catch (e: InvocationTargetException) { val cause = e.cause if (cause is IOException) throw cause throw JsonDataException("$cause at ${reader.path}", cause) } } } } override fun toString() = "JsonAdapter$annotations($type)" } } companion object { operator fun invoke(adapter: Any): AdapterMethodsFactory { val toAdapters = mutableListOf<AdapterMethod>() val fromAdapters = mutableListOf<AdapterMethod>() val classAndSuperclasses = generateSequence(adapter.javaClass) { it.superclass }.iterator() while (classAndSuperclasses.hasNext()) { val clazz = classAndSuperclasses.next() for (declaredMethod in clazz.declaredMethods) { if (declaredMethod.isAnnotationPresent(ToJson::class.java)) { val toAdapter = toAdapter(adapter, declaredMethod) val conflicting = get(toAdapters, toAdapter.type, toAdapter.annotations) checkNull(conflicting) { "Conflicting @ToJson methods:\n ${it.method}\n ${toAdapter.method}" } toAdapters.add(toAdapter) } if (declaredMethod.isAnnotationPresent(FromJson::class.java)) { val fromAdapter = fromAdapter(adapter, declaredMethod) val conflicting = get(fromAdapters, fromAdapter.type, fromAdapter.annotations) checkNull(conflicting) { "Conflicting @FromJson methods:\n ${it.method}\n ${fromAdapter.method}" } fromAdapters.add(fromAdapter) } } } require(toAdapters.isNotEmpty() || fromAdapters.isNotEmpty()) { "Expected at least one @ToJson or @FromJson method on ${adapter.javaClass.name}" } return AdapterMethodsFactory(toAdapters, fromAdapters) } /** * Returns an object that calls a `method` method on `adapter` in service of * converting an object to JSON. */ private fun toAdapter(adapter: Any, method: Method): AdapterMethod { method.isAccessible = true val returnType = method.genericReturnType val parameterTypes = method.genericParameterTypes val parameterAnnotations = method.parameterAnnotations val methodSignatureIncludesJsonWriterAndJsonAdapter = parameterTypes.size >= 2 && parameterTypes[0] == JsonWriter::class.java && returnType == Void.TYPE && parametersAreJsonAdapters(2, parameterTypes) return when { // void pointToJson(JsonWriter jsonWriter, Point point) { // void pointToJson(JsonWriter jsonWriter, Point point, JsonAdapter<?> adapter, ...) { methodSignatureIncludesJsonWriterAndJsonAdapter -> { val qualifierAnnotations = parameterAnnotations[1].jsonAnnotations object : AdapterMethod( adaptersOffset = 2, type = parameterTypes[1], parameterCount = parameterTypes.size, annotations = qualifierAnnotations, adapter = adapter, method = method, nullable = true ) { override fun toJson(moshi: Moshi, writer: JsonWriter, value: Any?) { invokeMethod(writer, value) } } } parameterTypes.size == 1 && returnType != Void.TYPE -> { // List<Integer> pointToJson(Point point) { val returnTypeAnnotations = method.jsonAnnotations val qualifierAnnotations = parameterAnnotations[0].jsonAnnotations val nullable = parameterAnnotations[0].hasNullable object : AdapterMethod( adaptersOffset = 1, type = parameterTypes[0], parameterCount = parameterTypes.size, annotations = qualifierAnnotations, adapter = adapter, method = method, nullable = nullable ) { private lateinit var delegate: JsonAdapter<Any> override fun bind(moshi: Moshi, factory: JsonAdapter.Factory) { super.bind(moshi, factory) val shouldSkip = Types.equals(parameterTypes[0], returnType) && qualifierAnnotations == returnTypeAnnotations delegate = if (shouldSkip) { moshi.nextAdapter(factory, returnType, returnTypeAnnotations) } else { moshi.adapter(returnType, returnTypeAnnotations) } } override fun toJson(moshi: Moshi, writer: JsonWriter, value: Any?) { delegate.toJson(writer, invokeMethod(value)) } } } else -> { throw IllegalArgumentException( """ Unexpected signature for $method. @ToJson method signatures may have one of the following structures: <any access modifier> void toJson(JsonWriter writer, T value) throws <any>; <any access modifier> void toJson(JsonWriter writer, T value, JsonAdapter<any> delegate, <any more delegates>) throws <any>; <any access modifier> R toJson(T value) throws <any>; """.trimIndent() ) } } } /** Returns true if `parameterTypes[offset]` contains only JsonAdapters. */ private fun parametersAreJsonAdapters(offset: Int, parameterTypes: Array<Type>): Boolean { for (i in offset until parameterTypes.size) { val parameterType = parameterTypes[i] if (parameterType !is ParameterizedType) return false if (parameterType.rawType != JsonAdapter::class.java) return false } return true } /** * Returns an object that calls a `method` method on `adapter` in service of * converting an object from JSON. */ private fun fromAdapter(adapter: Any, method: Method): AdapterMethod { method.isAccessible = true val returnType = method.genericReturnType val returnTypeAnnotations = method.jsonAnnotations val parameterTypes = method.genericParameterTypes val parameterAnnotations = method.parameterAnnotations val methodSignatureIncludesJsonReaderAndJsonAdapter = parameterTypes.isNotEmpty() && parameterTypes[0] == JsonReader::class.java && returnType != Void.TYPE && parametersAreJsonAdapters(1, parameterTypes) return when { methodSignatureIncludesJsonReaderAndJsonAdapter -> { // Point pointFromJson(JsonReader jsonReader) { // Point pointFromJson(JsonReader jsonReader, JsonAdapter<?> adapter, ...) { object : AdapterMethod( adaptersOffset = 1, type = returnType, parameterCount = parameterTypes.size, annotations = returnTypeAnnotations, adapter = adapter, method = method, nullable = true ) { override fun fromJson(moshi: Moshi, reader: JsonReader) = invokeMethod(reader) } } parameterTypes.size == 1 && returnType != Void.TYPE -> { // Point pointFromJson(List<Integer> o) { val qualifierAnnotations = parameterAnnotations[0].jsonAnnotations val nullable = parameterAnnotations[0].hasNullable object : AdapterMethod( adaptersOffset = 1, type = returnType, parameterCount = parameterTypes.size, annotations = returnTypeAnnotations, adapter = adapter, method = method, nullable = nullable ) { lateinit var delegate: JsonAdapter<Any> override fun bind(moshi: Moshi, factory: JsonAdapter.Factory) { super.bind(moshi, factory) delegate = if (Types.equals(parameterTypes[0], returnType) && qualifierAnnotations == returnTypeAnnotations) { moshi.nextAdapter(factory, parameterTypes[0], qualifierAnnotations) } else { moshi.adapter(parameterTypes[0], qualifierAnnotations) } } override fun fromJson(moshi: Moshi, reader: JsonReader): Any? { val intermediate = delegate.fromJson(reader) return invokeMethod(intermediate) } } } else -> { throw IllegalArgumentException( """ Unexpected signature for $method. @FromJson method signatures may have one of the following structures: <any access modifier> R fromJson(JsonReader jsonReader) throws <any>; <any access modifier> R fromJson(JsonReader jsonReader, JsonAdapter<any> delegate, <any more delegates>) throws <any>; <any access modifier> R fromJson(T value) throws <any>; """.trimIndent() ) } } } /** Returns the matching adapter method from the list. */ private fun get( adapterMethods: List<AdapterMethod>, type: Type, annotations: Set<Annotation> ): AdapterMethod? { for (adapterMethod in adapterMethods) { if (Types.equals(adapterMethod.type, type) && adapterMethod.annotations == annotations) { return adapterMethod } } return null } } internal abstract class AdapterMethod( private val adaptersOffset: Int, type: Type, parameterCount: Int, val annotations: Set<Annotation>, val adapter: Any, val method: Method, val nullable: Boolean ) { val type = type.canonicalize() private val jsonAdapters: Array<JsonAdapter<*>?> = arrayOfNulls(parameterCount - adaptersOffset) open fun bind(moshi: Moshi, factory: JsonAdapter.Factory) { if (jsonAdapters.isNotEmpty()) { val parameterTypes = method.genericParameterTypes val parameterAnnotations = method.parameterAnnotations for (i in adaptersOffset until parameterTypes.size) { val type = (parameterTypes[i] as ParameterizedType).actualTypeArguments[0] val jsonAnnotations = parameterAnnotations[i].jsonAnnotations jsonAdapters[i - adaptersOffset] = if (Types.equals(this.type, type) && annotations == jsonAnnotations) { moshi.nextAdapter(factory, type, jsonAnnotations) } else { moshi.adapter<Any>(type, jsonAnnotations) } } } } open fun toJson(moshi: Moshi, writer: JsonWriter, value: Any?): Unit = throw AssertionError() open fun fromJson(moshi: Moshi, reader: JsonReader): Any? = throw AssertionError() /** Invoke the method with one fixed argument, plus any number of JSON adapter arguments. */ protected fun invokeMethod(arg: Any?): Any? { val args = arrayOfNulls<Any>(1 + jsonAdapters.size) args[0] = arg jsonAdapters.copyInto(args, 1, 0, jsonAdapters.size) return try { method.invoke(adapter, *args) } catch (e: IllegalAccessException) { throw AssertionError() } } /** Invoke the method with two fixed arguments, plus any number of JSON adapter arguments. */ protected fun invokeMethod(arg0: Any?, arg1: Any?): Any? { val args = arrayOfNulls<Any>(2 + jsonAdapters.size) args[0] = arg0 args[1] = arg1 jsonAdapters.copyInto(args, 2, 0, jsonAdapters.size) return try { method.invoke(adapter, *args) } catch (e: IllegalAccessException) { throw AssertionError() } } } }
apache-2.0
d4d465c5946c66b955aa4c7e1a3811c0
38.11828
142
0.627062
5.031812
false
false
false
false
runesong/scribbler
src/main/java/scribbler/config/LocalConfiguration.kt
1
4649
package scribbler.config import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication import org.springframework.boot.autoconfigure.web.ServerProperties import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.context.ApplicationListener import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import org.springframework.http.RequestEntity import org.springframework.http.ResponseEntity import org.springframework.http.client.ClientHttpResponse import org.springframework.web.client.DefaultResponseErrorHandler import org.springframework.web.client.ResourceAccessException import org.springframework.web.client.RestTemplate import org.springframework.web.util.UriTemplate import scribbler.LOG import java.io.IOException import java.net.URI import java.util.* import kotlin.concurrent.thread @Profile("local") @Configuration @ConditionalOnWebApplication open class LocalConfiguration { @Bean @ConfigurationProperties("browse") open fun browserProperties(): BrowserProperties { return BrowserProperties() } @Bean open fun browserStartupListener(): EmbeddedServletContainerInitializedListener { return EmbeddedServletContainerInitializedListener() } class BrowserProperties { var enabled: Boolean = false var uri: UriTemplate = UriTemplate("{scheme}://{address}:{port}{context-path}{servlet-path}") } class EmbeddedServletContainerInitializedListener : ApplicationListener<EmbeddedServletContainerInitializedEvent> { @Autowired private val server: ServerProperties? = null @Autowired private val browser: BrowserProperties? = null private val max = 5000L; override fun onApplicationEvent(event: EmbeddedServletContainerInitializedEvent) { thread(name = "startupListener") { if (server!!.ssl.trustStore != null) { System.setProperty("javax.net.ssl.trustStore", server.ssl.trustStore) } val uri = buildUri(event.embeddedServletContainer.port) val request = RequestEntity.get(uri).build() var response: ResponseEntity<String>? = null val start = System.currentTimeMillis() var exception: Throwable? = null var client = RestTemplate() client.errorHandler = object : DefaultResponseErrorHandler() { override fun handleError(response: ClientHttpResponse) { } } do { try { response = client.exchange(request, String::class.java) } catch (ex: ResourceAccessException) { exception = ex } } while (response?.statusCode == null && !timedOut(start, exception)) if (response?.statusCode != null) { LOG.info(String.format( "%n----------------------------------------" + "%n" + "%n The application is ready:" + "%n %s" + "%n" + "%n----------------------------------------", uri )) if (browser!!.enabled) { openBrowser(uri) } } } } private fun buildUri(port: Int): URI { val variables = HashMap<String, Any>() variables.put("scheme", if (server!!.ssl.isEnabled) "https" else "http") variables.put("address", if (server.address == null) "localhost" else server.address) variables.put("port", port) variables.put("context-path", if (server.contextPath == null) "" else server.contextPath) variables.put("servlet-path", if (server.servletPath == null) "/" else server.servletPath) return browser!!.uri.expand(variables) } private fun openBrowser(uri: URI) { val headless = java.lang.Boolean.getBoolean("java.awt.headless") try { if (headless) { System.setProperty("java.awt.headless", "false") System.setProperty("apple.awt.UIElement", "true") } java.awt.Desktop.getDesktop().browse(uri) } catch (ex: IOException) { LOG.debug("Failed to open desktop browser.", ex) LOG.error("Failed to open desktop browser: {}", ex.message); } finally { if (headless) { System.setProperty("java.awt.headless", headless.toString()) } } } private fun timedOut(start: Long, exception: Throwable?): Boolean { if (System.currentTimeMillis() - start > max) { if (exception == null) { LOG.error("Listener timed out while waiting for server to start.") } else { LOG.error("Listener timed out while waiting for server to start: {}", exception.message) } return true; } Thread.sleep(250) return false; } } }
apache-2.0
474d0c0df5796d71903adda6ab04642d
32.688406
116
0.714132
4.004307
false
true
false
false
arranlomas/Ask-A-Question
app/src/main/java/com/arran/askaquestion/views/main/mvp/MainActivity.kt
1
4989
package com.arran.askaquestion.views.main.mvp import android.os.Bundle import android.widget.EditText import com.afollestad.materialdialogs.MaterialDialog import com.arran.askaquestion.AskAQuestion import com.arran.askaquestion.R import com.arran.askaquestion.models.Channel import com.arran.askaquestion.views.base.BaseActivity import com.arran.askaquestion.views.main.MainActivityModule import com.arran.askaquestion.views.question.QuestionsFragment import com.mikepenz.materialdrawer.Drawer import com.mikepenz.materialdrawer.DrawerBuilder import com.mikepenz.materialdrawer.model.SecondaryDrawerItem import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem import kotlinx.android.synthetic.main.activity_main.* import javax.inject.Inject class MainActivity : BaseActivity(), MainContract.View { private val DEFAULT_DRAWER_ITEMS = 2 @Inject lateinit var presenter: MainContract.Presenter private lateinit var nawDrawer: Drawer val drawerItemsMap = mutableMapOf<SecondaryDrawerItem, Channel?>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) AskAQuestion.presenterComponent.add(MainActivityModule()).inject(this) presenter.attachView(this) refreshQuestionsFragment() setupNavigationDrawer(emptyList()) } fun setupNavigationDrawer(channels: List<Channel>) { drawerItemsMap.clear() val item1 = SecondaryDrawerItem().withIdentifier(0).withName(R.string.drawer_item_new_channel) val item2 = SecondaryDrawerItem().withIdentifier(1).withName(R.string.drawer_item_join_channel) drawerItemsMap.put(item1, null) drawerItemsMap.put(item2, null) channels.forEachIndexed { index, channel -> val channelDrawerItem = SecondaryDrawerItem().withIdentifier((index + DEFAULT_DRAWER_ITEMS).toLong()).withName(channel.channelName) drawerItemsMap.put(channelDrawerItem, channel) } nawDrawer = DrawerBuilder() .withActivity(this) .withToolbar(main_toolbar) .withOnDrawerItemClickListener { view, position, drawerItem -> onDrawerItemSelected(drawerItem) true } .build() drawerItemsMap.forEach { secondaryDrawerItem, _ -> nawDrawer.addItem(secondaryDrawerItem) } } private fun onDrawerItemSelected(drawerItem: IDrawerItem<*, *>) { nawDrawer.closeDrawer() when (drawerItem.identifier) { 0L -> showCreateChannelDialog() 1L -> showJoinChannelDialog() else -> { drawerItemsMap[drawerItem]?.let { refreshQuestionsFragment(it.firebaseKey) } ?: showError() } } } private fun showCreateChannelDialog() { MaterialDialog.Builder(this) .title(R.string.create_new_channel_dialog_title) .customView(R.layout.dialog_channel_details, true) .positiveText(R.string.create_new_channel_dialog_positive) .onPositive { dialog, _ -> val channelName = dialog.customView?.findViewById<EditText>(R.id.channel_name_input)?.text?.toString() val channelPassword = dialog.customView?.findViewById<EditText>(R.id.channel_password_input)?.text?.toString() if (channelName != null && channelPassword != null) presenter.createNewChannel(channelName, channelPassword) else showError() } .show() } private fun showJoinChannelDialog() { MaterialDialog.Builder(this) .title(R.string.join_channel_dialog_title) .customView(R.layout.dialog_channel_details, true) .positiveText(R.string.join_channel_dialog_positive) .onPositive { dialog, _ -> val channelName = dialog.customView?.findViewById<EditText>(R.id.channel_name_input)?.text?.toString() val channelPassword = dialog.customView?.findViewById<EditText>(R.id.channel_password_input)?.text?.toString() if (channelName != null && channelPassword != null) presenter.joinChannel(channelName, channelPassword) else showError() } .show() } private fun refreshQuestionsFragment(channelKey: String? = null) { val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.replace(R.id.main_content, QuestionsFragment.newInstance(channelKey)) fragmentTransaction.commit() } override fun onDestroy() { super.onDestroy() presenter.detachView() } override fun updateChannels(channels: List<Channel>) { nawDrawer.closeDrawer() setupNavigationDrawer(channels) } }
gpl-3.0
7dcade5116d173a53a22be89a74597e9
40.575
143
0.662858
4.969124
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/ui/TvNavigationElement.kt
1
3472
/* * Copyright (c) 2020 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.ui import android.annotation.SuppressLint import android.content.Context import android.content.ContextWrapper import android.graphics.Rect import android.util.AttributeSet import android.view.View import androidx.appcompat.app.AppCompatActivity import com.ichi2.anki.NavigationDrawerActivity import timber.log.Timber /** Hack to allow the navigation and options menu to appear when on a TV * This is a view to handle dispatchUnhandledMove without using onKeyUp/Down * (which interferes with other view events) */ class TvNavigationElement : View { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) @Suppress("unused") constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) { Timber.d("onFocusChanged %d", direction) super.onFocusChanged(gainFocus, direction, previouslyFocusedRect) } override fun dispatchUnhandledMove(focused: View, direction: Int): Boolean { Timber.d("dispatchUnhandledMove %d", direction) val activity = activity ?: return super.dispatchUnhandledMove(focused, direction) if (direction == FOCUS_LEFT && activity is NavigationDrawerActivity) { // COULD_BE_BETTER: This leaves focus on the top item when navigation occurs. val navigationDrawerActivity = activity navigationDrawerActivity.toggleDrawer() navigationDrawerActivity.focusNavigation() return true } if (direction == FOCUS_RIGHT) { Timber.d("Opening options menu") // COULD_BE_BETTER: This crashes inside the framework if right is pressed on the openOptionsMenu(activity) return true } return super.dispatchUnhandledMove(focused, direction) } @SuppressLint("RestrictedApi") private fun openOptionsMenu(activity: AppCompatActivity) { // This occasionally glitches graphically on my emulator val supportActionBar = activity.supportActionBar supportActionBar?.openOptionsMenu() } private val activity: AppCompatActivity? get() { var context = context while (context is ContextWrapper) { if (context is AppCompatActivity) { return context } context = context.baseContext } return null } }
gpl-3.0
a3148720e929544220d6f2f6c2b9c1de
42.4
144
0.700461
4.869565
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/stats/insights/AllTimeInsightsRestClient.kt
2
2781
package org.wordpress.android.fluxc.network.rest.wpcom.stats.insights import android.content.Context import com.android.volley.RequestQueue import com.google.gson.annotations.SerializedName import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.endpoint.WPCOMREST import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Error import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Success import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.StatsUtils import org.wordpress.android.fluxc.store.StatsStore.FetchStatsPayload import org.wordpress.android.fluxc.store.toStatsError import java.util.Date import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton class AllTimeInsightsRestClient @Inject constructor( dispatcher: Dispatcher, private val wpComGsonRequestBuilder: WPComGsonRequestBuilder, appContext: Context?, @Named("regular") requestQueue: RequestQueue, accessToken: AccessToken, userAgent: UserAgent, val statsUtils: StatsUtils ) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) { suspend fun fetchAllTimeInsights(site: SiteModel, forced: Boolean): FetchStatsPayload<AllTimeResponse> { val url = WPCOMREST.sites.site(site.siteId).stats.urlV1_1 val params = mapOf<String, String>() val response = wpComGsonRequestBuilder.syncGetRequest( this, url, params, AllTimeResponse::class.java, enableCaching = true, forced = forced ) return when (response) { is Success -> { FetchStatsPayload(response.data) } is Error -> { FetchStatsPayload(response.error.toStatsError()) } } } data class AllTimeResponse( @SerializedName("date") val date: Date? = null, @SerializedName("stats") val stats: StatsResponse? ) { data class StatsResponse( @SerializedName("visitors") val visitors: Int?, @SerializedName("views") val views: Int?, @SerializedName("posts") val posts: Int?, @SerializedName("views_best_day") val viewsBestDay: String?, @SerializedName("views_best_day_total") val viewsBestDayTotal: Int? ) } }
gpl-2.0
f834a7dfa5713cdbef8e35c61459c786
40.507463
108
0.714851
4.596694
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/entity/AbstractEntityProtocol.kt
1
13455
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.entity import it.unimi.dsi.fastutil.objects.Object2LongMap import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap import org.lanternpowered.server.entity.LanternEntity import org.lanternpowered.server.entity.event.EntityEvent import org.lanternpowered.server.entity.event.EntityEventType import org.lanternpowered.server.entity.player.LanternPlayer import org.lanternpowered.server.network.packet.Packet import org.spongepowered.api.entity.Entity import org.spongepowered.api.entity.living.player.Player import org.spongepowered.math.vector.Vector3d import java.util.ArrayList import java.util.HashSet import java.util.Optional import java.util.OptionalInt import java.util.function.Supplier /** * @property entity The entity that is being tracked. */ abstract class AbstractEntityProtocol<E : LanternEntity> protected constructor( val entity: E ) { lateinit var entityProtocolManager: EntityProtocolManager /** * All the players tracking this entity. */ @JvmField val trackers: MutableSet<LanternPlayer> = HashSet() /** * The entity id of the entity. */ var rootEntityId = EntityProtocolManager.INVALID_ENTITY_ID private set /** * The number of ticks between every update. */ var tickRate = 4 /** * The tracking range of the entity. */ var trackingRange = 64.0 private var tickCounter = 0 @JvmField val playerInteractTimes: Object2LongMap<Player> = Object2LongOpenHashMap() @JvmField val entityEvents: MutableList<EntityEvent> = ArrayList() internal inner class SimpleEntityProtocolContext : EntityProtocolUpdateContext { lateinit var trackers: Set<LanternPlayer> override fun getById(entityId: Int): Optional<LanternEntity> { return entityProtocolManager.getEntityProtocolById(entityId).map { obj -> obj.entity } } override fun getId(entity: Entity): OptionalInt { val optProtocol = entityProtocolManager.getEntityProtocolByEntity(entity) return optProtocol.map { protocol: AbstractEntityProtocol<*> -> OptionalInt.of(protocol.rootEntityId) }.orElseGet { OptionalInt.empty() } } override fun sendToSelf(packet: Packet) { if (entity is LanternPlayer) entity.connection.send(packet) } override fun sendToSelf(messageSupplier: Supplier<Packet>) { if (entity is Player) this.sendToSelf(messageSupplier.get()) } override fun sendToAll(packet: Packet) { for (tracker in this.trackers) tracker.connection.send(packet) } override fun sendToAll(message: Supplier<Packet>) { if (this.trackers.isNotEmpty()) { sendToAll(message.get()) } } override fun sendToAllExceptSelf(packet: Packet) { for (tracker in this.trackers) { if (tracker != entity) tracker.connection.send(packet) } } override fun sendToAllExceptSelf(messageSupplier: Supplier<Packet>) { if (this.trackers.isNotEmpty()) this.sendToAllExceptSelf(messageSupplier.get()) } } private fun newContext(): SimpleEntityProtocolContext = SimpleEntityProtocolContext() /** * Destroys the entity. This removes all the trackers and sends a destroy * message to the client. * * @param context The entity protocol context */ fun destroy(context: EntityProtocolInitContext) { if (this.trackers.isNotEmpty()) { // Destroy the entity on all the clients val ctx = this.newContext() val events = this.processEvents(death = true, alive = true) ctx.trackers = this.trackers if (events?.deathOrAlive != null) { for (event in events.deathOrAlive) this.handleEvent(ctx, event) } destroy(ctx) this.trackers.clear() synchronized(this.playerInteractTimes) { this.playerInteractTimes.clear() } } this.remove(context) } protected open fun remove(context: EntityProtocolInitContext) { // Release the entity id of the entity if (this.entity !is NetworkIdHolder) { context.release(this.rootEntityId) } this.rootEntityId = EntityProtocolManager.INVALID_ENTITY_ID } /** * Initializes this entity protocol. This acquires the ids * that are required to spawn the entity. * * @param context The entity protocol context */ open fun init(context: EntityProtocolInitContext) { if (entity is NetworkIdHolder) { initRootId((entity as NetworkIdHolder).networkId) } else { // Allocate the next free id initRootId(context.acquire()) } } /** * Initializes the root entity id of this protocol. * * @param rootEntityId The root entity id */ protected fun initRootId(rootEntityId: Int) { check(rootEntityId != EntityProtocolManager.INVALID_ENTITY_ID) { "The root entity id cannot be invalid." } check(this.rootEntityId == EntityProtocolManager.INVALID_ENTITY_ID) { "This entity protocol is already initialized." } this.rootEntityId = rootEntityId } internal inner class TrackerUpdateContextData(val entityProtocol: AbstractEntityProtocol<*>) { val ctx = newContext() var added: MutableSet<LanternPlayer>? = null var removed: Set<LanternPlayer>? = null var update: MutableSet<LanternPlayer>? = null } internal fun buildUpdateContextData(players: Set<LanternPlayer>): TrackerUpdateContextData? { val mutablePlayers = HashSet(players) val removed: MutableSet<LanternPlayer> = HashSet() val added: MutableSet<LanternPlayer> = HashSet() val pos = this.entity.position val trackerIt = this.trackers.iterator() while (trackerIt.hasNext()) { val tracker = trackerIt.next() val flag = mutablePlayers.remove(tracker) if (tracker != this.entity && (!flag || !this.isVisible(pos, tracker))) { trackerIt.remove() removed.add(tracker) } } for (tracker in mutablePlayers) { if (tracker == entity || this.isVisible(pos, tracker)) added.add(tracker) } val flag0 = this.tickCounter++ % this.tickRate == 0 && this.trackers.isNotEmpty() val flag1 = added.isNotEmpty() val flag2 = removed.isNotEmpty() if (!flag0 && !flag1 && !flag2) return null val contextData = TrackerUpdateContextData(this) if (flag0 || flag1) contextData.update = HashSet(this.trackers) if (flag1) { contextData.added = added this.trackers.addAll(added) } if (flag2) contextData.removed = removed return contextData } internal fun updateTrackers(contextData: TrackerUpdateContextData) { val ctx = contextData.ctx val events = processEvents(contextData.removed != null, true) val removed = contextData.removed if (removed != null) { ctx.trackers = removed if (events?.deathOrAlive != null) { for (event in events.deathOrAlive) this.handleEvent(ctx, event) } this.destroy(ctx) synchronized(this.playerInteractTimes) { for (tracker in removed) this.playerInteractTimes.removeLong(tracker) } } var trackers: MutableSet<LanternPlayer>? = null val update = contextData.update if (update != null) { ctx.trackers = update this.update(ctx) if (events != null) { if (trackers == null) { trackers = update.toMutableSet() } else { trackers.addAll(update) } } } val added = contextData.added if (added != null) { ctx.trackers = added this.spawn(ctx) if (events != null) { if (trackers == null) { trackers = added } else { trackers.addAll(added) } } } if (trackers != null) { ctx.trackers = trackers for (event in events!!.alive) this.handleEvent(ctx, event) } } fun updateTrackerLocale(player: LanternPlayer) { if (!trackers.contains(player)) { return } val ctx = this.newContext() ctx.trackers = setOf(player) this.updateTranslations(ctx) } private inner class TempEvents(val deathOrAlive: List<EntityEvent>?, val alive: List<EntityEvent>) private fun processEvents(death: Boolean, alive: Boolean): TempEvents? { if (!death && !alive) return null var aliveList: List<EntityEvent> synchronized(this.entityEvents) { if (this.entityEvents.isNotEmpty()) { aliveList = ArrayList(this.entityEvents) this.entityEvents.clear() } else { return null } } var deathOrAliveList: MutableList<EntityEvent>? = null if (death) { for (event in aliveList) { if (event.type() == EntityEventType.DEATH_OR_ALIVE) { if (deathOrAliveList == null) { deathOrAliveList = ArrayList() } deathOrAliveList.add(event) } } } return TempEvents(deathOrAliveList, aliveList) } internal fun postUpdateTrackers(contextData: TrackerUpdateContextData) { val ctx = contextData.ctx val update = contextData.update if (update != null) { ctx.trackers = update this.postUpdate(ctx) } val added = contextData.added if (added != null) { ctx.trackers = added this.postSpawn(ctx) } } private fun isVisible(pos: Vector3d, tracker: LanternPlayer): Boolean { return pos.distanceSquared(tracker.position) < trackingRange * trackingRange && isVisible(tracker) } /** * Gets whether the tracked entity is visible for the tracker. * * @param tracker The tracker * @return Whether the tracker can see the entity */ protected fun isVisible(tracker: LanternPlayer): Boolean { return tracker.canSee(entity) } /** * Spawns the tracked entity. * * @param context The entity update context */ protected abstract fun spawn(context: EntityProtocolUpdateContext) /** * Destroys the tracked entity. * * @param context The entity update context */ protected abstract fun destroy(context: EntityProtocolUpdateContext) /** * Updates the tracked entity. * * @param context The entity update context */ protected abstract fun update(context: EntityProtocolUpdateContext) /** * Updates the tracked entity for [Locale] changes. * * @param context The context */ protected abstract fun updateTranslations(context: EntityProtocolUpdateContext) protected open fun handleEvent(context: EntityProtocolUpdateContext, event: EntityEvent) {} /** * Post spawns the tracked entity. This method will be called after * all the entities that were pending for updates/spawns are processed. * * @param context The entity update context */ protected open fun postSpawn(context: EntityProtocolUpdateContext) {} /** * Post updates the tracked entity. This method will be called after * all the entities that were pending for updates/spawns are processed. * * @param context The entity update context */ protected open fun postUpdate(context: EntityProtocolUpdateContext) {} /** * Is called when the specified [LanternPlayer] tries to interact * with this entity, or at least one of the ids assigned to it. * * @param player The player that interacted with the entity * @param entityId The entity the player interacted with * @param position The position where the player interacted with the entity, if present */ fun playerInteract(player: LanternPlayer, entityId: Int, position: Vector3d?) {} /** * Is called when the specified [LanternPlayer] tries to attach * this entity, or at least one of the ids assigned to it. * * @param player The player that attack the entity * @param entityId The entity id the player attacked */ fun playerAttack(player: LanternPlayer, entityId: Int) {} }
mit
4322b493b4cc1803ffa610333db2f37d
33.063291
149
0.615162
4.731013
false
false
false
false
kantega/niagara
niagara-http/src/main/kotlin/org/kantega/niagara/http/route.kt
1
10299
package org.kantega.niagara.http import io.vavr.collection.List import io.vavr.control.Option import io.vavr.kotlin.Try import io.vavr.kotlin.component1 import io.vavr.kotlin.component2 import org.kantega.niagara.data.* import org.kantega.niagara.http.RouteResult.Companion.failed import org.kantega.niagara.http.RouteResult.Companion.match import org.kantega.niagara.http.RouteResult.Companion.notMatched import org.kantega.niagara.json.JsonDecoder import org.kantega.niagara.json.JsonValue import org.kantega.niagara.json.io.JsonParser import kotlin.collections.dropLastWhile import kotlin.collections.toTypedArray data class RouteMatcher(val f: (Request) -> RouteResult<Request>) { fun match(request: Request): RouteResult<Request> = f(request) fun bind(g: (Request) -> RouteResult<Request>) = RouteMatcher { r -> f(r).flatMap { r2 -> g(r2) } } infix fun <A> thenExtract(f: (Request) -> RouteResult<P2<Request, A>>) = RouteExtractor { request -> RouteResult.match(request).fold( { match -> f(match.value) }, { notMatched() }, { fail -> Failed(fail.failure) } ) } } data class RouteExtractor<A>(val f: (Request) -> RouteResult<P2<Request, A>>) { fun extract(request: Request): RouteResult<P2<Request, A>> = f(request) fun <B> map(f: (A) -> B): RouteExtractor<B> = RouteExtractor { input -> extract(input).map { (req, value) -> p(req, f(value)) } } fun <B> bind(f: (A) -> RouteResult<B>): RouteExtractor<B> = RouteExtractor { input -> extract(input).flatMap { (req, value) -> f(value).map({ b -> p(req, b) }) } } } interface Route<A> { fun handle(input: Request): RouteResult<P2<Request, A>> infix fun or(other: Route<A>): Route<A> { return OrEndpoint(this, other) } fun <B> bind(next: (A) -> Route<B>): Route<B> = ChainedEndpoints(this, next) } object Root : Route<HNil> { override fun handle(input: Request): RouteResult<P2<Request, HNil>> = match(p(input, HNil)) } data class ExtractingRoute<A, HL : HList>(val extractor: RouteExtractor<A>, val rest: Route<HL>) : Route<HCons<A, HL>> { override fun handle(input: Request): RouteResult<P2<Request, HCons<A, HL>>> { val result = rest.handle(input) return result.flatMap { (tailremainder, tail) -> extractor.extract(tailremainder).map { (remainder, a) -> p(remainder, HCons(a, tail)) } } } } data class MatchingRoute<HL : HList>(val matcher: RouteMatcher, val rest: Route<HL>) : Route<HL> { override fun handle(input: Request): RouteResult<P2<Request, HL>> { val result = rest.handle(input) return result.flatMap { (tailremainder, tail) -> matcher.match(tailremainder).map { remainder -> p(remainder, tail) } } } } data class HandlingRoute<A, HL : HList>(val handler: (Request, HL) -> A, val tail: Route<HL>) : Route<A> { override fun handle(input: Request): RouteResult<P2<Request, A>> { val result = tail.handle(input) return result.map { (remainder, tail) -> p(remainder, handler(remainder, tail)) } } } data class OrEndpoint<A>(val one: Route<A>, val other: Route<A>) : Route<A> { override fun handle(input: Request): RouteResult<P2<Request, A>> { return one.handle(input).fold( { m -> m }, { other.handle(input) }, { f -> f } ) } } data class ChainedEndpoints<A, B>(val first: Route<A>, val onSuccess: (A) -> Route<B>) : Route<B> { override fun handle(input: Request): RouteResult<P2<Request, B>> { return first.handle(input).flatMap({ res -> onSuccess(res._2).handle(res._1) }) } } operator fun <A> Route<A>.plus(other: Route<A>): Route<A> = this or other operator fun RouteMatcher.div(path: String): Route<HNil> = Root / this / path(path) operator fun RouteMatcher.div(other: RouteMatcher): Route<HNil> = Root / this / other operator fun <A> RouteMatcher.div(other: RouteExtractor<A>): Route<HCons<A, HNil>> = Root / this / other operator fun <A> RouteExtractor<A>.div(other: RouteMatcher): Route<HCons<A, HNil>> = Root / this / other operator fun <A, B> RouteExtractor<A>.div(other: RouteExtractor<B>): Route<HCons<B, HCons<A, HNil>>> = Root / this / other operator fun <HL : HList> Route<HL>.div(matcher: RouteMatcher): Route<HL> = MatchingRoute(matcher, this) operator fun <HL : HList> Route<HL>.div(path: String): Route<HL> = MatchingRoute(path(path), this) operator fun <A, HL : HList> Route<HL>.div(extractor: RouteExtractor<A>): Route<HCons<A, HL>> = ExtractingRoute(extractor, this) fun <A, HL : HList> Route<HL>.handler(handler: (Request, HL) -> A): Route<A> = HandlingRoute(handler, this) operator fun <A> Route<HNil>.invoke(h: (Request) -> A): Route<A> = handler({ req, _ -> h(req) }) operator fun <A, B> Route<HCons<A, HNil>>.invoke(h: (Request, A) -> B): Route<B> = handler { req, hlist -> h(req, hlist.head) } operator fun <A, B, C> Route<HCons<A, HCons<B, HNil>>>.invoke(h: (Request, A, B) -> C): Route<C> = handler { req, hlist -> h(req, hlist.head, hlist.tail.head) } operator fun <A, B, C, D> Route<HCons<A, HCons<B, HCons<C, HNil>>>>.invoke(h: (Request, A, B, C) -> D): Route<D> = handler { req, hlist -> h(req, hlist.head, hlist.tail.head, hlist.tail.tail.head) } operator fun <A, B, C, D, E> Route<HCons<A, HCons<B, HCons<C, HCons<D, HNil>>>>>.invoke(h: (Request, A, B, C, D) -> E): Route<E> = handler { req, hlist -> h(req, hlist.head, hlist.tail.head, hlist.tail.tail.head, hlist.tail.tail.tail.head) } operator fun <A, B, C, D, E, F> Route<HCons<A, HCons<B, HCons<C, HCons<D, HCons<E, HNil>>>>>>.invoke(h: (Request, A, B, C, D, E) -> F): Route<F> = handler { req, hlist -> h(req, hlist.head, hlist.tail.head, hlist.tail.tail.head, hlist.tail.tail.tail.head, hlist.tail.tail.tail.tail.head) } operator fun <A, B, C, D, E, F, G> Route<HCons<A, HCons<B, HCons<C, HCons<D, HCons<E, HCons<F, HNil>>>>>>>.invoke(h: (Request, A, B, C, D, E, F) -> G): Route<G> = handler { req, hlist -> h(req, hlist.head, hlist.tail.head, hlist.tail.tail.head, hlist.tail.tail.tail.head, hlist.tail.tail.tail.tail.head, hlist.tail.tail.tail.tail.tail.head) } operator fun <A, B, C, D, E, F, G,H > Route<HCons<A, HCons<B, HCons<C, HCons<D, HCons<E, HCons<F, HCons<G, HNil>>>>>>>>.invoke(h: (Request, A, B, C, D, E, F, G) -> H): Route<H> = handler { req, hlist -> h(req, hlist.head, hlist.tail.head, hlist.tail.tail.head, hlist.tail.tail.tail.head, hlist.tail.tail.tail.tail.head, hlist.tail.tail.tail.tail.tail.head, hlist.tail.tail.tail.tail.tail.tail.head) } val end = RouteMatcher { input -> if (input.remainingPath.isEmpty) match(input) else notMatched() } val pathParam = RouteExtractor { input -> if (input.remainingPath.isEmpty) notMatched() else match(p(input.advancePath(1), input.remainingPath.head())) } val optionalPathParam = RouteExtractor { input -> if (input.remainingPath.isEmpty) match(p(input, Option.none())) else match(p(input.advancePath(1), Option.of(input.remainingPath.head()))) } fun method(method: String): RouteMatcher = RouteMatcher { input -> if (input.method.toLowerCase() == method.toLowerCase()) match(input) else notMatched() } fun path(path: String): RouteMatcher = path(List.of(*path.split("/".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray())) fun path(path: List<String>): RouteMatcher = RouteMatcher { input -> if (path isPrefixOf input.remainingPath) match(input.advancePath(path.length())) else notMatched() } val ROOT = Root val GET = method("GET") val POST = method("POST") val PUT = method("PUT") fun qp(name:String) = queryParam(name) fun qpInt(name:String)= queryParamAsInt(name) fun queryParam(name: String) = RouteExtractor { input -> input.queryParams .get(name) .flatMap { it.headOption() } .fold( { notMatched<P2<Request, String>>() }, { n -> match(p(input, n)) } ) } fun queryParamAsInt(name: String) = RouteExtractor { input -> input.queryParams .get(name) .flatMap({ list -> if (!list.isEmpty) Try { list.head().toInt() }.toOption() else Option.none() }) .fold( { notMatched<P2<Request, Int>>() }, { n -> match(p(input, n)) } ) } fun queryParamAsLong(name: String) = RouteExtractor { input -> input.queryParams .get(name) .flatMap({ list -> if (!list.isEmpty) Try { list.head().toLong() }.toOption() else Option.none() }) .fold( { notMatched<P2<Request, Long>>() }, { n -> match(p(input, n)) } ) } fun mediaType(mediaType: MediaType) = RouteMatcher { request -> request .requestHeaders .get("Content-Type") .flatMap { list -> list.headOption() } .fold( { notMatched() }, { headerValue -> if (headerValue.startsWith(mediaType.type)) match(request) else notMatched() } ) } val json = mediaType(APPLICATION_JSON) .thenExtract { input -> JsonParser.parse(input.body).fold( { nel -> failed<P2<Request, JsonValue>>(nel.toList().mkString(",")) }, { json -> match(p(input, json)) }) } fun <A> json(decoder: JsonDecoder<A>): RouteExtractor<A> = json .bind { json -> decoder(json) .fold( { nel -> failed<A>(nel.toList().mkString(",")) }, { v -> match(v) }) } fun <A> notFound(): Route<A> = NotFoundEndpoint() fun <A> fail(reason: String): Route<A> = FailingEndpoint(reason) fun <A> value(a: A) = RouteExtractor { input -> match(p(input, a)) } fun <A> routes(vararg routes: Route<A>): Route<A> = List.of(*routes).foldLeft(notFound(), { accum, route -> accum or route }) class NotFoundEndpoint<A> : Route<A> { override fun handle(input: Request): RouteResult<P2<Request, A>> = notMatched() override fun or(other: Route<A>): Route<A> = other } data class FailingEndpoint<A>(val reason: String) : Route<A> { override fun handle(input: Request): RouteResult<P2<Request, A>> = failed(reason) }
apache-2.0
a616997d4eadfae912c688cbced63c59
30.689231
223
0.62375
3.131347
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/effect/firework/LanternFireworkEffect.kt
1
1764
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.effect.firework import org.lanternpowered.api.effect.firework.FireworkEffect import org.lanternpowered.api.effect.firework.FireworkShape import org.lanternpowered.api.util.Color import org.lanternpowered.server.data.DataQueries import org.spongepowered.api.data.persistence.DataContainer import org.spongepowered.api.data.persistence.Queries internal data class LanternFireworkEffect( private val flicker: Boolean, private val trails: Boolean, private val colors: List<Color>, private val fades: List<Color>, private val shape: FireworkShape ) : FireworkEffect { override fun flickers(): Boolean = this.flicker override fun hasTrail(): Boolean = this.trails override fun getColors(): List<Color> = this.colors override fun getFadeColors(): List<Color> = this.fades override fun getShape(): FireworkShape = this.shape override fun getContentVersion(): Int = 1 override fun toContainer(): DataContainer { return DataContainer.createNew() .set(Queries.CONTENT_VERSION, contentVersion) .set(DataQueries.FIREWORK_SHAPE, this.shape) .set(DataQueries.FIREWORK_COLORS, this.colors) .set(DataQueries.FIREWORK_FADE_COLORS, this.fades) .set(DataQueries.FIREWORK_TRAILS, this.trails) .set(DataQueries.FIREWORK_FLICKERS, this.flicker) } }
mit
5ecb7bdf2f89f1d54e196ca00abbbc08
39.090909
70
0.710884
4.073903
false
false
false
false
Kotlin/kotlinx.serialization
formats/json-tests/commonTest/src/kotlinx/serialization/features/PolymorphicOnClassesTest.kt
1
5761
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.features import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.internal.* import kotlinx.serialization.json.* import kotlinx.serialization.modules.* import kotlinx.serialization.test.* import kotlin.reflect.* import kotlin.test.* class PolymorphicOnClassesTest { // this has implicit @Polymorphic interface IMessage { val body: String } // and this class too has implicit @Polymorphic @Serializable abstract class Message : IMessage { abstract override val body: String } @Polymorphic @Serializable @SerialName("SimpleMessage") // to cut out package prefix open class SimpleMessage : Message() { override var body: String = "Simple" } @Serializable @SerialName("DoubleSimpleMessage") class DoubleSimpleMessage(val body2: String) : SimpleMessage() @Serializable @SerialName("MessageWithId") open class MessageWithId(val id: Int, override val body: String) : Message() @Serializable class Holder( val iMessage: IMessage, val iMessageList: List<IMessage>, val message: Message, val msgSet: Set<Message>, val simple: SimpleMessage, // all above should be polymorphic val withId: MessageWithId // but this not ) private fun genTestData(): Holder { var cnt = -1 fun gen(): MessageWithId { cnt++ return MessageWithId(cnt, "Message #$cnt") } return Holder(gen(), listOf(gen(), gen()), gen(), setOf(SimpleMessage()), DoubleSimpleMessage("DoubleSimple"), gen()) } @Suppress("UNCHECKED_CAST") private val testModule = SerializersModule { listOf(Message::class, IMessage::class, SimpleMessage::class).forEach { clz -> polymorphic(clz as KClass<IMessage>) { subclass(SimpleMessage.serializer()) subclass(DoubleSimpleMessage.serializer()) subclass(MessageWithId.serializer()) } } } @Test fun testEnablesImplicitlyOnInterfacesAndAbstractClasses() { val json = Json { prettyPrint = false useArrayPolymorphism = true serializersModule = testModule encodeDefaults = true } val data = genTestData() assertEquals( """{"iMessage":["MessageWithId",{"id":0,"body":"Message #0"}],""" + """"iMessageList":[["MessageWithId",{"id":1,"body":"Message #1"}],""" + """["MessageWithId",{"id":2,"body":"Message #2"}]],"message":["MessageWithId",{"id":3,"body":"Message #3"}],""" + """"msgSet":[["SimpleMessage",{"body":"Simple"}]],"simple":["DoubleSimpleMessage",{"body":"Simple",""" + """"body2":"DoubleSimple"}],"withId":{"id":4,"body":"Message #4"}}""", json.encodeToString(Holder.serializer(), data) ) } @Test fun testDescriptor() { val polyDesc = Holder.serializer().descriptor.elementDescriptors.first() assertEquals(PolymorphicSerializer(IMessage::class).descriptor, polyDesc) assertEquals(2, polyDesc.elementsCount) assertEquals(PrimitiveKind.STRING, polyDesc.getElementDescriptor(0).kind) } private fun SerialDescriptor.inContext(module: SerializersModule): List<SerialDescriptor> = when (kind) { PolymorphicKind.OPEN -> module.getPolymorphicDescriptors(this) else -> error("Expected this function to be called on OPEN descriptor") } @Test fun testResolvePolymorphicDescriptor() { val polyDesc = Holder.serializer().descriptor.elementDescriptors.first() // iMessage: IMessage assertEquals(PolymorphicKind.OPEN, polyDesc.kind) val inheritors = polyDesc.inContext(testModule) val names = listOf("SimpleMessage", "DoubleSimpleMessage", "MessageWithId").toSet() assertEquals(names, inheritors.map(SerialDescriptor::serialName).toSet(), "Expected correct inheritor names") assertTrue(inheritors.all { it.kind == StructureKind.CLASS }, "Expected all inheritors to be CLASS") } @Test fun testDocSampleWithAllDistinct() { fun allDistinctNames(descriptor: SerialDescriptor, module: SerializersModule) = when (descriptor.kind) { is PolymorphicKind.OPEN -> module.getPolymorphicDescriptors(descriptor) .map { it.elementNames.toList() }.flatten().toSet() is SerialKind.CONTEXTUAL -> module.getContextualDescriptor(descriptor)?.elementNames?.toList().orEmpty().toSet() else -> descriptor.elementNames.toSet() } val polyDesc = Holder.serializer().descriptor.elementDescriptors.first() // iMessage: IMessage assertEquals(setOf("id", "body", "body2"), allDistinctNames(polyDesc, testModule)) assertEquals(setOf("id", "body"), allDistinctNames(MessageWithId.serializer().descriptor, testModule)) } @Test fun testSerializerLookupForInterface() { // On JVM and JS IR it can be supported via reflection/runtime hacks // on Native, unfortunately, only with intrinsics. if (currentPlatform == Platform.NATIVE || currentPlatform == Platform.JS_LEGACY) return val msgSer = serializer<IMessage>() assertEquals(IMessage::class, (msgSer as AbstractPolymorphicSerializer).baseClass) } @Test fun testSerializerLookupForAbstractClass() { val absSer = serializer<Message>() assertEquals(Message::class, (absSer as AbstractPolymorphicSerializer).baseClass) } }
apache-2.0
acb71c75c129008330e426ae30bfb60f
37.66443
133
0.653532
4.890492
false
true
false
false
sylvan-library/api
src/main/kotlin/io/sylvanlibrary/api/handlers/RenderHandler.kt
1
1107
package io.sylvanlibrary.api.handlers import io.sylvanlibrary.api.models.QueryResult import io.sylvanlibrary.api.utils.isHeaderHtml import io.sylvanlibrary.api.utils.isHeaderJson import ratpack.handling.Context import ratpack.handling.Handler import ratpack.jackson.Jackson import java.util.* class RenderHandler: Handler { override fun handle(ctx: Context) { var queryResult = ctx.maybeGet(QueryResult::class.java) var result = if (queryResult.isPresent) { queryResult.get().result } else { ctx.response.status(404) null } if (result is Optional<*>) { result = if (result.isPresent) result.get() else null } val acceptHeader = ctx.request.headers["accept"] // For ease of browser testing, allow requests to return json. This will probably change later on // Null is treated as though the user wants our default behaviour, which is json if (acceptHeader == null || acceptHeader.isHeaderJson() || acceptHeader.isHeaderHtml()) ctx.render(Jackson.json(result)) else ctx.response.status(406) ctx.response.send() } }
mit
bcc1233f6c071b223bdafab1b49602b1
28.918919
101
0.719061
3.953571
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/session/ui/SessionViewHolder.kt
1
2480
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.session.ui import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import mozilla.components.browser.session.Session import org.mozilla.focus.R import org.mozilla.focus.ext.beautifyUrl import org.mozilla.focus.ext.requireComponents import org.mozilla.focus.telemetry.TelemetryWrapper import java.lang.ref.WeakReference class SessionViewHolder internal constructor( private val fragment: SessionsSheetFragment, private val textView: TextView ) : RecyclerView.ViewHolder(textView), View.OnClickListener { companion object { @JvmField internal val LAYOUT_ID = R.layout.item_session } private var sessionReference: WeakReference<Session> = WeakReference<Session>(null) init { textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_link, 0, 0, 0) textView.setOnClickListener(this) } fun bind(session: Session) { this.sessionReference = WeakReference(session) updateTitle(session) val isCurrentSession = fragment.requireComponents.sessionManager.selectedSession == session updateTextBackgroundColor(isCurrentSession) } private fun updateTextBackgroundColor(isCurrentSession: Boolean) { val drawable = if (isCurrentSession) { R.drawable.background_list_item_current_session } else { R.drawable.background_list_item_session } textView.setBackgroundResource(drawable) } private fun updateTitle(session: Session) { textView.text = if (session.title.isEmpty()) session.url.beautifyUrl() else session.title } override fun onClick(view: View) { val session = sessionReference.get() ?: return selectSession(session) } private fun selectSession(session: Session) { fragment.animateAndDismiss().addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { fragment.requireComponents.sessionManager.select(session) TelemetryWrapper.switchTabInTabsTrayEvent() } }) } }
mpl-2.0
5e6f2f710c81786e989e72758ed5426f
32.513514
99
0.712097
4.769231
false
false
false
false
ursjoss/scipamato
core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/code/CodeEditPageTest.kt
1
13460
package ch.difty.scipamato.core.web.code import ch.difty.scipamato.core.entity.CodeClass import ch.difty.scipamato.core.entity.code.CodeDefinition import ch.difty.scipamato.core.entity.code.CodeTranslation import ch.difty.scipamato.core.persistence.OptimisticLockingException import ch.difty.scipamato.core.web.authentication.LogoutPage import ch.difty.scipamato.core.web.code.CodeEditHeaderPanel.CodeMustMatchCodeClassValidator import ch.difty.scipamato.core.web.common.BasePageTest import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapButton import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkboxx.CheckBoxX import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelect import io.mockk.confirmVerified import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.amshove.kluent.shouldBeNull import org.amshove.kluent.shouldBeTrue import org.apache.wicket.feedback.FeedbackMessage import org.apache.wicket.markup.html.form.Form import org.apache.wicket.markup.html.form.TextField import org.apache.wicket.markup.repeater.RefreshingView import org.apache.wicket.model.Model import org.apache.wicket.request.mapper.parameter.PageParameters import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.springframework.dao.DataIntegrityViolationException import org.springframework.dao.DuplicateKeyException @Suppress("PrivatePropertyName", "VariableNaming") internal class CodeEditPageTest : BasePageTest<CodeEditPage>() { private lateinit var codeDefinitionDummy: CodeDefinition private lateinit var formDummy: Form<*> private lateinit var codeField: TextField<String> private lateinit var codeClasses: BootstrapSelect<CodeClass> private val cc1 = CodeClass(1, "CC1", "c1") private val cc2 = CodeClass(2, "Region", "d2") private val kt_de = CodeTranslation(1, "de", "Name1", "some comment", 1) private val kt_de2 = CodeTranslation(1, "de", "Name1a", null, 1) private val kt_en = CodeTranslation(2, "en", "name1", null, 1) private val kt_fr = CodeTranslation(3, "fr", "nom1", null, 1) private val cd = CodeDefinition("2A", "de", cc2, 1, false, 1, kt_de, kt_en, kt_fr, kt_de2) public override fun setUpHook() { codeDefinitionDummy = mockk() formDummy = mockk() codeField = TextField("code") codeClasses = BootstrapSelect("codeClasses") every { codeClassServiceMock.find(any()) } returns listOf(cc2) } @AfterEach fun tearDown() { confirmVerified(codeServiceMock) } override fun makePage(): CodeEditPage = CodeEditPage(Model.of(cd), null) override val pageClass: Class<CodeEditPage> get() = CodeEditPage::class.java public override fun assertSpecificComponents() { var b = "form" tester.assertComponent(b, Form::class.java) b += ":headerPanel:" var bb = b + "code" tester.assertLabel(bb + "Label", "Code") tester.assertModelValue(bb, "2A") bb = b + "codeClass" tester.assertLabel(bb + "Label", "Code Class") tester.assertComponent(bb, BootstrapSelect::class.java) tester.assertModelValue(bb, cc2) tester.assertContains("<option selected=\"selected\" value=\"2\">2 - Region</option>") bb = b + "sort" tester.assertLabel(bb + "Label", "Sort") tester.assertComponent(bb, TextField::class.java) bb = b + "internal" tester.assertLabel(bb + "Label", "Internal") tester.assertComponent(bb, CheckBoxX::class.java) tester.assertComponent(b + "back", BootstrapButton::class.java) tester.assertComponent(b + "submit", BootstrapButton::class.java) tester.assertComponent(b + "delete", BootstrapButton::class.java) bb = "form:translations" tester.assertLabel(bb + "Label", "Code Translations and Comments") bb += "Panel:translations" tester.assertComponent(bb, RefreshingView::class.java) bb += ":" assertTranslation(bb, 1, "de", "Name1", "some comment") assertTranslation(bb, 2, "de", "Name1a", null) assertTranslation(bb, 3, "en", "name1", null) assertTranslation(bb, 4, "fr", "nom1", null) } private fun assertTranslation(bb: String, idx: Int, langCode: String, name: String, comment: String?) { tester.assertLabel("$bb$idx:langCode", langCode) tester.assertComponent("$bb$idx:name", TextField::class.java) tester.assertModelValue("$bb$idx:name", name) tester.assertComponent("$bb$idx:comment", TextField::class.java) tester.assertModelValue("$bb$idx:comment", comment) } @Test fun submitting_withSuccessfulServiceCall_addsInfoMsg() { every { codeServiceMock.saveOrUpdate(any()) } returns cd runSubmitTest() tester.assertInfoMessages("Successfully saved code 2A: DE: 'foo','Name1a'; EN: 'name1'; FR: 'nom1'.") tester.assertNoErrorMessage() } private fun runSubmitTest() { tester.startPage(CodeEditPage(Model.of(cd), null)) val formTester = tester.newFormTester("form") formTester.setValue("translationsPanel:translations:1:name", "foo") assertTranslation("form:translationsPanel:translations:", 1, "de", "Name1", "some comment") formTester.submit("headerPanel:submit") assertTranslation("form:translationsPanel:translations:", 5, "de", "foo", "some comment") verify { codeServiceMock.saveOrUpdate(any()) } } @Test fun submitting_withUnsuccessfulServiceCall_addsErrorMsg() { every { codeServiceMock.saveOrUpdate(any()) } returns null runSubmitTest() tester.assertNoInfoMessage() tester.assertErrorMessages("Could not save code 2A.") } @Test fun submitting_withOptimisticLockingException_addsErrorMsg() { every { codeServiceMock.saveOrUpdate(any()) } throws OptimisticLockingException("tblName", "rcd", OptimisticLockingException.Type.UPDATE) runSubmitTest() tester.assertNoInfoMessage() tester.assertErrorMessages( "The tblName with id 2A has been modified concurrently " + "by another user. Please reload it and apply your changes once more." ) } @Test fun submitting_withOtherException_addsErrorMsg() { every { codeServiceMock.saveOrUpdate(any()) } throws RuntimeException("fooMsg") runSubmitTest() tester.assertNoInfoMessage() tester.assertErrorMessages("An unexpected error occurred when trying to save the code 2A: fooMsg") } @Test fun submitting_withDuplicateKeyConstraintViolationException_addsErrorMsg() { val msg = ( "...Detail: Key (code_class_id, sort)=(2, 1) already exists.; " + "nested exception is org.postgresql.util.PSQLException: " + "ERROR: duplicate key value violates unique constraint..." ) every { codeServiceMock.saveOrUpdate(any()) } throws DuplicateKeyException(msg) runSubmitTest() tester.assertNoInfoMessage() tester.assertErrorMessages("The sort index 1 is already in use for codes of code class 2.") } @Test fun submitting_withDuplicateKeyConstraintViolationException_withUnexpectedMsg_addsThatErrorMsg() { val msg = "something unexpected happened" every { codeServiceMock.saveOrUpdate(any()) } throws DuplicateKeyException(msg) runSubmitTest() tester.assertNoInfoMessage() tester.assertErrorMessages("something unexpected happened") } @Test fun submitting_withNullCode_preventsSave() { assertCodeCodeClassMismatch(null) } @Test fun submitting_withBlankCode_preventsSave() { assertCodeCodeClassMismatch("") } @Test fun submitting_withCodeCodeClassMismatch_preventsSave() { assertCodeCodeClassMismatch("3A") } private fun assertCodeCodeClassMismatch(code: String?) { tester.startPage(CodeEditPage(Model.of(cd), null)) val formTester = tester.newFormTester("form") formTester.setValue("headerPanel:code", code) formTester.submit("headerPanel:submit") tester.assertErrorMessages("The first digit of the Code must match the Code Class Number.") verify(exactly = 0) { codeServiceMock.saveOrUpdate(any()) } } @Test fun submittingDelete_delegatesDeleteToService() { every { codeServiceMock.delete(any(), any()) } returns codeDefinitionDummy every { codeServiceMock.getCodeClass1("en_us") } returns cc1 every { codeServiceMock.countByFilter(any()) } returns 0 tester.startPage(CodeEditPage(Model.of(cd), null)) val formTester = tester.newFormTester("form") formTester.submit("headerPanel:delete") tester.assertNoInfoMessage() tester.assertNoErrorMessage() verify { codeServiceMock.delete("2A", 1) } verify(exactly = 0) { codeServiceMock.saveOrUpdate(any()) } verify { codeServiceMock.getCodeClass1("en_us") } verify { codeServiceMock.countByFilter(any()) } } @Test fun submittingDelete_withServiceReturningNull_informsAboutRepoError() { every { codeServiceMock.delete(any(), any()) } returns null tester.startPage(CodeEditPage(Model.of(cd), null)) val formTester = tester.newFormTester("form") formTester.submit("headerPanel:delete") tester.assertNoInfoMessage() tester.assertErrorMessages("Could not delete code 2A.") verify { codeServiceMock.delete("2A", 1) } verify(exactly = 0) { codeServiceMock.saveOrUpdate(any()) } } @Test fun submittingDelete_withForeignKeyConstraintViolationException_addsErrorMsg() { val msg = "... is still referenced from table \"paper_code\".; " + "nested exception is org.postgresql.util.PSQLException..." every { codeServiceMock.delete(any(), any()) } throws DataIntegrityViolationException(msg) tester.startPage(CodeEditPage(Model.of(cd), null)) val formTester = tester.newFormTester("form") formTester.submit("headerPanel:delete") tester.assertNoInfoMessage() tester.assertErrorMessages("You cannot delete code '2A' as it is still assigned to at least one paper.") verify { codeServiceMock.delete(any(), any()) } } @Test fun submittingDelete_withOptimisticLockingException_addsErrorMsg() { every { codeServiceMock.delete(any(), any()) } throws OptimisticLockingException("code_class", OptimisticLockingException.Type.DELETE) tester.startPage(CodeEditPage(Model.of(cd), null)) val formTester = tester.newFormTester("form") formTester.submit("headerPanel:delete") tester.assertNoInfoMessage() tester.assertErrorMessages( "The code_class with id 2A has been modified concurrently by another user. " + "Please reload it and apply your changes once more." ) verify { codeServiceMock.delete(any(), any()) } } @Test fun submittingDelete_withException_addsErrorMsg() { every { codeServiceMock.delete(any(), any()) } throws RuntimeException("boom") tester.startPage(CodeEditPage(Model.of(cd), null)) val formTester = tester.newFormTester("form") formTester.submit("headerPanel:delete") tester.assertNoInfoMessage() tester.assertErrorMessages("An unexpected error occurred when trying to delete code 2A: boom") verify { codeServiceMock.delete(any(), any()) } } @Test fun clickingBackButton_withPageWithoutCallingPageRef_forwardsToCodeListPage() { every { codeServiceMock.getCodeClass1("en_us") } returns cc1 every { codeServiceMock.countByFilter(any()) } returns 0 tester.startPage(CodeEditPage(Model.of(cd), null)) val formTester = tester.newFormTester("form") formTester.submit("headerPanel:back") tester.assertRenderedPage(CodeListPage::class.java) // from CodeListPage verify { codeServiceMock.getCodeClass1("en_us") } verify { codeServiceMock.countByFilter(any()) } } @Test fun clickingBackButton_withPageWithCallingPageRef_forwardsToThat() { tester.startPage(CodeEditPage(Model.of(cd), LogoutPage(PageParameters()).pageReference)) val formTester = tester.newFormTester("form") formTester.submit("headerPanel:back") tester.assertRenderedPage(LogoutPage::class.java) } @Test fun withNullCodeClasses_failsValidation() { codeClasses.convertedInput.shouldBeNull() assertValidationDidNotPass() } @Test fun withNonNullCodeClass_withNullCode_failsValidation() { codeClasses.convertedInput = CodeClass(1, "CC1", "") codeField.convertedInput.shouldBeNull() assertValidationDidNotPass() } @Test fun withNonNullCodeClass_withBlankCode_failsValidation() { codeClasses.convertedInput = CodeClass(1, "CC1", "") codeField.convertedInput = "" assertValidationDidNotPass() } private fun assertValidationDidNotPass() { val validator = CodeMustMatchCodeClassValidator(codeField, codeClasses) validator.validate(formDummy) codeField.feedbackMessages.hasMessage(FeedbackMessage.ERROR).shouldBeTrue() } }
bsd-3-clause
504b5402afce7154d10ad3291411c6a2
41.730159
112
0.689302
4.28117
false
true
false
false
McGars/percents
feature/details/src/main/java/com/gars/percents/details/presentation/adapter/TableDataSource.kt
1
1981
package com.gars.percents.details.presentation.adapter import com.gars.percents.common.StringResources import com.gars.percents.details.R import com.gars.percents.details.data.AccrualItem class TableDataSource( private val items: List<AccrualItem>, private val stringResources: StringResources ) { private companion object { const val COLUMN_MONTH = 0 const val COLUMN_DATE = 1 const val COLUMN_TAKEOFF = 2 const val COLUMN_PROFIT = 3 const val COLUMN_TOTAL = 4 } val size get() = items.size fun getCellData(column: Int, row: Int): TableCell { val item = items[row] return when (column) { COLUMN_MONTH -> TableCell(item.monthNumber) COLUMN_DATE -> TableCell(item.date) COLUMN_TAKEOFF -> TableCell(item.takeOff, item.takeOffColor, item.investment) COLUMN_PROFIT -> TableCell(item.profit, item.incomingColor, item.incomingPercents) COLUMN_TOTAL -> TableCell(item.total) else -> throw RuntimeException("no column exists $column") } } fun getHeaderData(column: Int): TableCell { return when (column) { COLUMN_MONTH -> TableCell( text = column.toString() ) COLUMN_DATE -> TableCell( text = stringResources.getString(R.string.result_page_date) ) COLUMN_TAKEOFF -> TableCell( text = stringResources.getString(R.string.result_page_takeoff), subtext = stringResources.getString(R.string.result_page_add_in_month) ) COLUMN_PROFIT -> TableCell( text = stringResources.getString(R.string.result_page_incomming), ) COLUMN_TOTAL -> TableCell( text = stringResources.getString(R.string.result_page_total) ) else -> throw RuntimeException("no column exists $column") } } }
apache-2.0
e3bdb8a1a0a23f54f62cc4a1ce408719
33.172414
94
0.610298
4.373068
false
false
false
false
KotlinKit/Reactant
Core/src/main/kotlin/org/brightify/reactant/autolayout/internal/view/IntrinsicDimensionManager.kt
1
2930
package org.brightify.reactant.autolayout.internal.view import org.brightify.reactant.autolayout.Constraint import org.brightify.reactant.autolayout.ConstraintOperator import org.brightify.reactant.autolayout.ConstraintPriority import org.brightify.reactant.autolayout.ConstraintVariable import org.brightify.reactant.autolayout.internal.ConstraintItem import org.brightify.reactant.core.util.onChange /** * @author <a href="mailto:[email protected]">Filip Dolnik</a> */ internal class IntrinsicDimensionManager(dimensionVariable: ConstraintVariable) { var size: Double by onChange(-1.0) { _, _, _ -> updateEquations() } var contentHuggingPriority: ConstraintPriority by onChange(ConstraintPriority.low) { _, _, _ -> updateEquations() } var contentCompressionResistancePriority: ConstraintPriority by onChange(ConstraintPriority.high) { _, _, _ -> updateEquations() } val isUsingEqualConstraint: Boolean get() = contentHuggingPriority == contentCompressionResistancePriority val equalConstraintForNecessityDecider: Constraint get() = equalConstraint.priority(contentHuggingPriority) private val equalConstraint = Constraint(dimensionVariable.view, listOf(ConstraintItem(dimensionVariable, ConstraintOperator.equal))) private val contentHuggingConstraint = Constraint(dimensionVariable.view, listOf(ConstraintItem(dimensionVariable, ConstraintOperator.lessOrEqual))) private val contentCompressionResistanceConstraint = Constraint(dimensionVariable.view, listOf(ConstraintItem(dimensionVariable, ConstraintOperator.greaterOrEqual))) val usedConstraints = setOf(equalConstraint, contentHuggingConstraint, contentCompressionResistanceConstraint) init { deactivateConstraints() equalConstraint.initialize() contentHuggingConstraint.initialize() contentCompressionResistanceConstraint.initialize() } private fun updateEquations() { deactivateConstraints() if (size >= 0) { if (isUsingEqualConstraint) { equalConstraint.offset = size equalConstraint.priority = contentHuggingPriority equalConstraint.activate() } else { contentHuggingConstraint.offset = size contentCompressionResistanceConstraint.offset = size contentHuggingConstraint.priority = contentHuggingPriority contentCompressionResistanceConstraint.priority = contentCompressionResistancePriority contentHuggingConstraint.activate() contentCompressionResistanceConstraint.activate() } } } private fun deactivateConstraints() { equalConstraint.deactivate() contentHuggingConstraint.deactivate() contentCompressionResistanceConstraint.deactivate() } }
mit
4226ae73e2671a35e765e0e56dde4d1b
39.150685
114
0.727645
5.241503
false
false
false
false
EricssonResearch/scott-eu
lyo-services/webapp-whc/src/main/java/se/ericsson/cf/scott/sandbox/whc/xtra/planning/PlanRequestBuilder.kt
1
978
package se.ericsson.cf.scott.sandbox.whc.xtra.planning import org.apache.jena.rdf.model.Model import org.apache.jena.rdf.model.ModelFactory import org.slf4j.Logger import org.slf4j.LoggerFactory class PlanRequestBuilder { companion object { val log: Logger = LoggerFactory.getLogger(PlanRequestBuilder::class.java) } private lateinit var problemBuilder: ProblemBuilder private lateinit var domain: Model fun build(): Model { val m = ModelFactory.createDefaultModel() m.add(domain) val state: ProblemRequestState = problemBuilder.build() m.add(state.model) log.debug("Completed building a planning request") return m } fun domainFromModel(domain: Model): PlanRequestBuilder { this.domain = domain return this } fun withStateBuilder(problemBuilder: ProblemBuilder): PlanRequestBuilder { this.problemBuilder = problemBuilder return this } }
apache-2.0
7fd1373c81b4e24aec63b4334610f962
23.45
81
0.698364
4.346667
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/ColorParameter.kt
1
2577
/* ParaTask 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.paratask.parameters import javafx.scene.paint.Color import javafx.util.StringConverter import uk.co.nickthecoder.paratask.ParameterException import uk.co.nickthecoder.paratask.parameters.fields.ColorField import uk.co.nickthecoder.paratask.parameters.fields.ParameterField import uk.co.nickthecoder.paratask.util.uncamel /** * A Color, without an alpha channel. */ class ColorParameter( name: String, label: String = name.uncamel(), description: String = "", hint: String = "", value: Color = Color.WHITE) : AbstractValueParameter<Color>( name = name, label = label, description = description, hint = hint, value = value) { override val converter = object : StringConverter<Color>() { override fun fromString(str: String): Color { val trimmed = str.trim() try { return Color.web(trimmed, 1.0) } catch (e: Exception) { throw ParameterException(this@ColorParameter, "Not a Color") } } override fun toString(obj: Color): String { val r = Math.round(obj.red * 255.0).toInt(); val g = Math.round(obj.green * 255.0).toInt() val b = Math.round(obj.blue * 255.0).toInt() return String.format("#%02x%02x%02x", r, g, b) } } override fun errorMessage(v: Color?): String? { if (isProgrammingMode()) return null if (v == null) { return "Required" } return null } override fun isStretchy() = false override fun createField(): ParameterField = ColorField(this).build() override fun toString(): String = "Color" + super.toString() override fun copy() = ColorParameter( name = name, label = label, description = description, hint = hint, value = value) }
gpl-3.0
807654892c9b1cf2267f25f541eb9945
30.048193
94
0.651533
4.273632
false
false
false
false
jereksel/LibreSubstratum
app/src/main/kotlin/com/jereksel/libresubstratum/utils/ZipUtils.kt
1
2529
/* * Copyright (C) 2017 Andrzej Ressel ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.jereksel.libresubstratum.utils import java.io.* import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipInputStream object ZipUtils { fun File.extractZip(dest: File, prefix: String = "", progressCallback: (Int) -> Unit = {}, streamTransform: (InputStream) -> InputStream = { it }) { if (dest.exists()) { dest.deleteRecursively() } dest.mkdirs() val length = ZipFile(this).size() FileInputStream(this).use { fis -> ZipInputStream(BufferedInputStream(fis)).use { zis -> zis.generateSequence().forEachIndexed { index, ze -> val fileName = ze.name.removeSuffix(".enc") progressCallback((index * 100) / length) // Log.d("extractZip", fileName) if (!fileName.startsWith(prefix)) { return@forEachIndexed } if (ze.isDirectory) { File(dest, fileName).mkdirs() return@forEachIndexed } val destFile = File(dest, fileName) destFile.parentFile.mkdirs() destFile.createNewFile() FileOutputStream(destFile).use { fout -> streamTransform(zis).copyTo(fout) } if (Thread.interrupted()) { return } } } } } //We can't just use second function alone - we will close entry when there is no entry opened yet fun ZipInputStream.generateSequence() = generateSequence({ this.nextEntry }, { this.closeEntry(); this.nextEntry }) }
mit
11a4ddc1e657bd22e81e8957140b788b
32.289474
119
0.574931
5.007921
false
false
false
false
googlecodelabs/kotlin-coroutines
ktx-library-codelab/step-05/myktxlibrary/src/main/java/com/example/android/myktxlibrary/LocationUtils.kt
1
1720
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.myktxlibrary import android.annotation.SuppressLint import android.location.Location import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationRequest import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException fun createLocationRequest() = LocationRequest.create().apply { interval = 3000 fastestInterval = 2000 priority = LocationRequest.PRIORITY_HIGH_ACCURACY } fun Location.asString(format: Int = Location.FORMAT_DEGREES): String { val latitude = Location.convert(latitude, format) val longitude = Location.convert(longitude, format) return "Location is: $latitude, $longitude" } @SuppressLint("MissingPermission") suspend fun FusedLocationProviderClient.awaitLastLocation(): Location = suspendCancellableCoroutine { continuation -> lastLocation.addOnSuccessListener { location -> continuation.resume(location) }.addOnFailureListener { e -> continuation.resumeWithException(e) } }
apache-2.0
013a5e2f59a77778c17aafd092c8896a
35.595745
75
0.761047
4.817927
false
false
false
false
nemerosa/ontrack
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ui/graphql/GQLTypeGitHubEngineConfiguration.kt
1
3675
package net.nemerosa.ontrack.extension.github.ui.graphql import graphql.Scalars.GraphQLString import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.github.app.GitHubAppTokenService import net.nemerosa.ontrack.extension.github.client.OntrackGitHubClientFactory import net.nemerosa.ontrack.extension.github.model.GitHubAuthenticationType import net.nemerosa.ontrack.extension.github.model.GitHubEngineConfiguration import net.nemerosa.ontrack.extension.github.model.getAppInstallationTokenInformation import net.nemerosa.ontrack.graphql.schema.GQLFieldContributor import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.schema.graphQLFieldContributions import net.nemerosa.ontrack.graphql.support.stringField import org.springframework.stereotype.Component @Component class GQLTypeGitHubEngineConfiguration( private val fieldContributors: List<GQLFieldContributor>, private val gqlTypeGitHubRateLimit: GQLTypeGitHubRateLimit, private val gqlTypeGitHubAppToken: GQLTypeGitHubAppToken, private val gitHubClientFactory: OntrackGitHubClientFactory, private val gitHubAppTokenService: GitHubAppTokenService, ) : GQLType { override fun getTypeName(): String = GitHubEngineConfiguration::class.java.simpleName override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Configuration to connect to GitHub") .stringField( "name", "Name of the configuration" ) .stringField( GitHubEngineConfiguration::url, "URL to GitHub" ) .stringField( "user", "User used to connect to GitHub. Can be used with a password or an OAuth2 token. Not needed if using only the OAUth2 token or a GitHub App." ) .stringField( GitHubEngineConfiguration::appId, "ID of the GitHub App used for authentication" ) .stringField( GitHubEngineConfiguration::appInstallationAccountName, "Name of the account where the GitHub App is installed." ) .field { it.name("rateLimits") .description("Rate limits for this configuration") .type(gqlTypeGitHubRateLimit.typeRef) .dataFetcher { env -> val config: GitHubEngineConfiguration = env.getSource() val client = gitHubClientFactory.create(config) client.getRateLimit() } } .field { it.name("authenticationType") .description("Authentication type") .type(GraphQLString) .dataFetcher { env -> val config: GitHubEngineConfiguration = env.getSource() config.authenticationType().name } } .field { it.name("appToken") .description("GitHub App token information") .type(gqlTypeGitHubAppToken.typeRef) .dataFetcher { env -> val config: GitHubEngineConfiguration = env.getSource() if (config.authenticationType() == GitHubAuthenticationType.APP) { gitHubAppTokenService.getAppInstallationTokenInformation(config) } else { null } } } .fields(GitHubEngineConfiguration::class.java.graphQLFieldContributions(fieldContributors)) .build() }
mit
c6327715dd343097ef4567d7542b23e9
42.247059
152
0.657959
5.501497
false
true
false
false
DankBots/Mega-Gnar
src/main/kotlin/gg/octave/bot/utils/DiscordLogBack.kt
1
1486
package gg.octave.bot.utils import ch.qos.logback.classic.Level import ch.qos.logback.classic.PatternLayout import ch.qos.logback.classic.spi.ILoggingEvent import ch.qos.logback.core.AppenderBase import club.minnced.discord.webhook.WebhookClient class DiscordLogBack : AppenderBase<ILoggingEvent>() { private var patternLayout: PatternLayout? = null override fun append(event: ILoggingEvent) { if (client == null) { return } if (!event.level.isGreaterOrEqual(Level.INFO)) { return } var content = patternLayout!!.doLayout(event) if (!content.contains("UnknownHostException")) //Spams the shit out of console, not needed if (content.length > 2000) { val sb = StringBuilder(":warning: Received a message but it was too long. ") val url = Utils.hasteBin(content) sb.append(url ?: "Error while posting to HasteBin.") content = sb.toString() } client?.send(content) } override fun start() { patternLayout = PatternLayout() patternLayout!!.context = getContext() patternLayout!!.pattern = "`%d{HH:mm:ss}` `%t/%level` `%logger{0}` %msg" patternLayout!!.start() super.start() } companion object { private var client: WebhookClient? = null fun enable(webhookClient: WebhookClient) { client = webhookClient } } }
mit
e319ae82f29a19d748ccfdf300f902aa
28.72
98
0.615074
4.345029
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/jobs/BackgroundJobFactory.kt
1
9407
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.jobs import android.annotation.SuppressLint import android.app.NotificationManager import android.content.ContentResolver import android.content.Context import android.content.res.Resources import android.os.Build import androidx.annotation.RequiresApi import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.work.ListenableWorker import androidx.work.WorkerFactory import androidx.work.WorkerParameters import com.nextcloud.client.account.UserAccountManager import com.nextcloud.client.core.Clock import com.nextcloud.client.device.DeviceInfo import com.nextcloud.client.device.PowerManagementService import com.nextcloud.client.integrations.deck.DeckApi import com.nextcloud.client.logger.Logger import com.nextcloud.client.network.ConnectivityService import com.nextcloud.client.preferences.AppPreferences import com.owncloud.android.datamodel.ArbitraryDataProvider import com.owncloud.android.datamodel.SyncedFolderProvider import com.owncloud.android.datamodel.UploadsStorageManager import com.owncloud.android.utils.theme.ViewThemeUtils import org.greenrobot.eventbus.EventBus import javax.inject.Inject import javax.inject.Provider /** * This factory is responsible for creating all background jobs and for injecting worker dependencies. */ @Suppress("LongParameterList") // satisfied by DI class BackgroundJobFactory @Inject constructor( private val logger: Logger, private val preferences: AppPreferences, private val contentResolver: ContentResolver, private val clock: Clock, private val powerManagementService: PowerManagementService, private val backgroundJobManager: Provider<BackgroundJobManager>, private val deviceInfo: DeviceInfo, private val accountManager: UserAccountManager, private val resources: Resources, private val dataProvider: ArbitraryDataProvider, private val uploadsStorageManager: UploadsStorageManager, private val connectivityService: ConnectivityService, private val notificationManager: NotificationManager, private val eventBus: EventBus, private val deckApi: DeckApi, private val viewThemeUtils: Provider<ViewThemeUtils>, private val localBroadcastManager: Provider<LocalBroadcastManager> ) : WorkerFactory() { @SuppressLint("NewApi") @Suppress("ComplexMethod") // it's just a trivial dispatch override fun createWorker( context: Context, workerClassName: String, workerParameters: WorkerParameters ): ListenableWorker? { val workerClass = try { Class.forName(workerClassName).kotlin } catch (ex: ClassNotFoundException) { null } // ContentObserverWork requires N return if (deviceInfo.apiLevel >= Build.VERSION_CODES.N && workerClass == ContentObserverWork::class) { createContentObserverJob(context, workerParameters, clock) } else { when (workerClass) { ContactsBackupWork::class -> createContactsBackupWork(context, workerParameters) ContactsImportWork::class -> createContactsImportWork(context, workerParameters) FilesSyncWork::class -> createFilesSyncWork(context, workerParameters) OfflineSyncWork::class -> createOfflineSyncWork(context, workerParameters) MediaFoldersDetectionWork::class -> createMediaFoldersDetectionWork(context, workerParameters) NotificationWork::class -> createNotificationWork(context, workerParameters) AccountRemovalWork::class -> createAccountRemovalWork(context, workerParameters) CalendarBackupWork::class -> createCalendarBackupWork(context, workerParameters) CalendarImportWork::class -> createCalendarImportWork(context, workerParameters) FilesExportWork::class -> createFilesExportWork(context, workerParameters) FilesUploadWorker::class -> createFilesUploadWorker(context, workerParameters) else -> null // caller falls back to default factory } } } private fun createFilesExportWork( context: Context, params: WorkerParameters ): ListenableWorker { return FilesExportWork( context, accountManager.user, contentResolver, viewThemeUtils.get(), params ) } private fun createContentObserverJob( context: Context, workerParameters: WorkerParameters, clock: Clock ): ListenableWorker? { val folderResolver = SyncedFolderProvider(contentResolver, preferences, clock) @RequiresApi(Build.VERSION_CODES.N) if (deviceInfo.apiLevel >= Build.VERSION_CODES.N) { return ContentObserverWork( context, workerParameters, folderResolver, powerManagementService, backgroundJobManager.get() ) } else { return null } } private fun createContactsBackupWork(context: Context, params: WorkerParameters): ContactsBackupWork { return ContactsBackupWork( context, params, resources, dataProvider, contentResolver, accountManager ) } private fun createContactsImportWork(context: Context, params: WorkerParameters): ContactsImportWork { return ContactsImportWork( context, params, logger, contentResolver ) } private fun createCalendarBackupWork(context: Context, params: WorkerParameters): CalendarBackupWork { return CalendarBackupWork( context, params, contentResolver, accountManager, preferences ) } private fun createCalendarImportWork(context: Context, params: WorkerParameters): CalendarImportWork { return CalendarImportWork( context, params, logger, contentResolver ) } private fun createFilesSyncWork(context: Context, params: WorkerParameters): FilesSyncWork { return FilesSyncWork( context = context, params = params, resources = resources, contentResolver = contentResolver, userAccountManager = accountManager, preferences = preferences, uploadsStorageManager = uploadsStorageManager, connectivityService = connectivityService, powerManagementService = powerManagementService, clock = clock ) } private fun createOfflineSyncWork(context: Context, params: WorkerParameters): OfflineSyncWork { return OfflineSyncWork( context = context, params = params, contentResolver = contentResolver, userAccountManager = accountManager, connectivityService = connectivityService, powerManagementService = powerManagementService ) } private fun createMediaFoldersDetectionWork(context: Context, params: WorkerParameters): MediaFoldersDetectionWork { return MediaFoldersDetectionWork( context, params, resources, contentResolver, accountManager, preferences, clock, viewThemeUtils.get() ) } private fun createNotificationWork(context: Context, params: WorkerParameters): NotificationWork { return NotificationWork( context, params, notificationManager, accountManager, deckApi, viewThemeUtils.get() ) } private fun createAccountRemovalWork(context: Context, params: WorkerParameters): AccountRemovalWork { return AccountRemovalWork( context, params, uploadsStorageManager, accountManager, backgroundJobManager.get(), clock, eventBus, preferences ) } private fun createFilesUploadWorker(context: Context, params: WorkerParameters): FilesUploadWorker { return FilesUploadWorker( uploadsStorageManager, connectivityService, powerManagementService, accountManager, viewThemeUtils.get(), localBroadcastManager.get(), context, params ) } }
gpl-2.0
00eb74a52a2c43dfdd625960159299cc
36.035433
120
0.677368
5.735976
false
false
false
false
hewking/HUILibrary
app/src/main/java/com/hewking/custom/WaterRippleView.kt
1
5903
package com.hewking.custom import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.util.AttributeSet import android.view.View import android.view.animation.LinearInterpolator import androidx.core.content.ContextCompat import com.hewking.custom.util.dp2px import com.hewking.custom.util.getColor import com.hewking.custom.util.textHeight /** * 类的描述: * 创建人员:hewking * 创建时间:2018/12/15 * 修改人员:hewking * 修改时间:2018/12/15 * 修改备注: * Version: 1.0.0 */ class WaterRippleView(ctx : Context,attrs : AttributeSet) : View(ctx,attrs) { // 进度 [0,100] private var progress : Int = 50 set(value) { field = value invalidate() } // 绘制半径 var radius = 0f // 波浪动画 offset var offset = 0f var textColor = getColor(R.color.pink_f5b8c2) var textSize = dp2px(14f) private var path : Path = Path() private var bizerPath = Path() private val mPaint by lazy{ Paint().apply{ color = ContextCompat.getColor(context,R.color.yellow_EADA50) style = Paint.Style.FILL_AND_STROKE isAntiAlias = true } } private val textPaint by lazy{ Paint().apply{ isAntiAlias = true style = Paint.Style.STROKE color = textColor textSize = [email protected]() } } init { } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var wSize = MeasureSpec.getSize(widthMeasureSpec) val wMode = MeasureSpec.getMode(widthMeasureSpec) var hSize = MeasureSpec.getSize(heightMeasureSpec) val hMode = MeasureSpec.getMode(heightMeasureSpec) if (wMode != MeasureSpec.EXACTLY) { wSize = dp2px(200f) } if (hMode != MeasureSpec.EXACTLY) { hSize = dp2px(200f) } val size = Math.min(hSize,wSize) setMeasuredDimension(size,size) } // layout 之后调用 override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) radius = Math.min(w,h).div(2f) path.addCircle(w.div(2f),h.div(2f),radius,Path.Direction.CW)// 顺时针 ValueAnimator.ofFloat(0f,1f).apply { duration = 1000 interpolator = LinearInterpolator() repeatCount = ValueAnimator.INFINITE repeatMode = ValueAnimator.RESTART addUpdateListener { offset = it.animatedValue as Float postInvalidateOnAnimation() } addListener(object : AnimatorListenerAdapter(){ override fun onAnimationRepeat(animation: Animator?) { super.onAnimationRepeat(animation) } }) start() } if (BuildConfig.DEBUG) { ValueAnimator.ofFloat(0f,1f).apply{ repeatCount = ValueAnimator.INFINITE repeatMode = ValueAnimator.RESTART duration = 8000 addUpdateListener { progress = (it.animatedValue as Float).times(100).toInt() postInvalidateOnAnimation() } addListener(object : AnimatorListenerAdapter(){ override fun onAnimationRepeat(animation: Animator?) { super.onAnimationRepeat(animation) } }) start() } } } override fun onDraw(canvas: Canvas?) { canvas?:return canvas.save() canvas.clipPath(path) canvas.save() canvas.translate(width.div(2f),height.div(2f)) val lowheight = progress.div(100f).times(2).times(radius) // val start = Math.sqrt(Math.pow(radius.toDouble(),2.toDouble()) + Math.pow(radius.toDouble() - lowheight,2.toDouble())) // val end = - start // val sc = canvas.saveLayer(-radius,-radius,radius,radius,mPaint,Canvas.ALL_SAVE_FLAG) // canvas.drawPaint(mPaint) // mPaint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.SRC)) bizerPath.reset() val waveHeight = radius.div(8) val waveWidth = radius.div(2) bizerPath.moveTo(- 2 * waveWidth,radius - lowheight) val start = - 4 * waveWidth + offset * 2 * waveWidth for(i in 0 until 4) { bizerPath.quadTo(start + (4 * i + 1) * 0.5f * waveWidth ,radius - lowheight - waveHeight ,start + (2 * i + 1) * waveWidth ,radius - lowheight) bizerPath.quadTo(start + (4 * i + 3) * 0.5f * waveWidth ,radius - lowheight + waveHeight ,start + (i + 1) * 2 * waveWidth ,radius - lowheight) } bizerPath.lineTo(radius,radius) bizerPath.lineTo(-radius,radius) bizerPath.close() canvas.drawPath(bizerPath,mPaint) // mPaint.xfermode = null // canvas.restoreToCount(sc) // draw progress val text = "$progress %" canvas.drawText(text ,-textPaint.measureText(text).div(2) ,textPaint.textHeight().div(2) - textPaint.descent() ,textPaint) canvas.restore() canvas.restore() // if (BuildConfig.DEBUG) { // DrawHelper.drawCoordinate(canvas,width,height) // } } }
mit
c4e9b9bac9b0bf6b945329820a3bd2da
29.928571
128
0.56378
4.377543
false
false
false
false
soywiz/korge
korge-dragonbones/src/commonMain/kotlin/com/dragonbones/animation/AnimationState.kt
1
45959
package com.dragonbones.animation /** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors * * 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. */ import com.dragonbones.armature.* import com.dragonbones.core.* import com.dragonbones.event.* import com.soywiz.kds.iterators.* import com.dragonbones.model.* import com.dragonbones.util.* import com.soywiz.kds.* import kotlin.math.* /** * - The animation state is generated when the animation data is played. * @see dragonBones.Animation * @see dragonBones.AnimationData * @version DragonBones 3.0 * @language en_US */ /** * - 动画状态由播放动画数据时产生。 * @see dragonBones.Animation * @see dragonBones.AnimationData * @version DragonBones 3.0 * @language zh_CN */ class AnimationState(pool: SingleObjectPool<AnimationState>) : BaseObject(pool) { override fun toString(): String { return "[class dragonBones.AnimationState]" } /** * @private */ var actionEnabled: Boolean = false /** * @private */ var additive: Boolean = false /** * - Whether the animation state has control over the display object properties of the slots. * Sometimes blend a animation state does not want it to control the display object properties of the slots, * especially if other animation state are controlling the display object properties of the slots. * @default true * @version DragonBones 5.0 * @language en_US */ /** * - 动画状态是否对插槽的显示对象属性有控制权。 * 有时混合一个动画状态并不希望其控制插槽的显示对象属性, * 尤其是其他动画状态正在控制这些插槽的显示对象属性时。 * @default true * @version DragonBones 5.0 * @language zh_CN */ var displayControl: Boolean = false /** * - Whether to reset the objects without animation to the armature pose when the animation state is start to play. * This property should usually be set to false when blend multiple animation states. * @default true * @version DragonBones 5.1 * @language en_US */ /** * - 开始播放动画状态时是否将没有动画的对象重置为骨架初始值。 * 通常在混合多个动画状态时应该将该属性设置为 false。 * @default true * @version DragonBones 5.1 * @language zh_CN */ var resetToPose: Boolean = false /** * @private */ var blendType: AnimationBlendType = AnimationBlendType.None /** * - The play times. [0: Loop play, [1~N]: Play N times] * @version DragonBones 3.0 * @language en_US */ /** * - 播放次数。 [0: 无限循环播放, [1~N]: 循环播放 N 次] * @version DragonBones 3.0 * @language zh_CN */ var playTimes: Int = 1 /** * - The blend layer. * High layer animation state will get the blend weight first. * When the blend weight is assigned more than 1, the remaining animation states will no longer get the weight assigned. * @readonly * @version DragonBones 5.0 * @language en_US */ /** * - 混合图层。 * 图层高的动画状态会优先获取混合权重。 * 当混合权重分配超过 1 时,剩余的动画状态将不再获得权重分配。 * @readonly * @version DragonBones 5.0 * @language zh_CN */ var layer: Int = 0 /** * - The play speed. * The value is an overlay relationship with {@link dragonBones.Animation#timeScale}. * [(-N~0): Reverse play, 0: Stop play, (0~1): Slow play, 1: Normal play, (1~N): Fast play] * @default 1.0 * @version DragonBones 3.0 * @language en_US */ /** * - 播放速度。 * 该值与 {@link dragonBones.Animation#timeScale} 是叠加关系。 * [(-N~0): 倒转播放, 0: 停止播放, (0~1): 慢速播放, 1: 正常播放, (1~N): 快速播放] * @default 1.0 * @version DragonBones 3.0 * @language zh_CN */ var timeScale: Double = 1.0 /** * @private */ var parameterX: Double = 0.0 /** * @private */ var parameterY: Double = 0.0 /** * @private */ var positionX: Double = 0.0 /** * @private */ var positionY: Double = 0.0 /** * - The auto fade out time when the animation state play completed. * [-1: Do not fade out automatically, [0~N]: The fade out time] (In seconds) * @default -1.0 * @version DragonBones 5.0 * @language en_US */ /** * - 动画状态播放完成后的自动淡出时间。 * [-1: 不自动淡出, [0~N]: 淡出时间] (以秒为单位) * @default -1.0 * @version DragonBones 5.0 * @language zh_CN */ var autoFadeOutTime: Double = 0.0 /** * @private */ var fadeTotalTime: Double = 0.0 /** * - The name of the animation state. (Can be different from the name of the animation data) * @readonly * @version DragonBones 5.0 * @language en_US */ /** * - 动画状态名称。 (可以不同于动画数据) * @readonly * @version DragonBones 5.0 * @language zh_CN */ var name: String = "" /** * - The blend group name of the animation state. * This property is typically used to specify the substitution of multiple animation states blend. * @readonly * @version DragonBones 5.0 * @language en_US */ /** * - 混合组名称。 * 该属性通常用来指定多个动画状态混合时的相互替换关系。 * @readonly * @version DragonBones 5.0 * @language zh_CN */ var group: String = "" private var _timelineDirty: Int = 2 /** * - xx: Play Enabled, Fade Play Enabled * @internal */ var _playheadState: Int = 0 /** * -1: Fade in, 0: Fade complete, 1: Fade out; * @internal */ var _fadeState: Int = -1 /** * -1: Fade start, 0: Fading, 1: Fade complete; * @internal */ var _subFadeState: Int = -1 /** * @internal */ var _position: Double = 0.0 /** * @internal */ var _duration: Double = 0.0 private var _weight: Double = 1.0 private var _fadeTime: Double = 0.0 private var _time: Double = 0.0 /** * @internal */ var _fadeProgress: Double = 0.0 /** * @internal */ var _weightResult: Double = 0.0 private val _boneMask: FastArrayList<String> = FastArrayList() private val _boneTimelines: FastArrayList<TimelineState> = FastArrayList() private val _boneBlendTimelines: FastArrayList<TimelineState> = FastArrayList() private val _slotTimelines: FastArrayList<TimelineState> = FastArrayList() private val _slotBlendTimelines: FastArrayList<TimelineState> = FastArrayList() private val _constraintTimelines: FastArrayList<TimelineState> = FastArrayList() private val _animationTimelines: FastArrayList<TimelineState> = FastArrayList() private val _poseTimelines: FastArrayList<TimelineState> = FastArrayList() private var _animationData: AnimationData? = null private var _armature: Armature? = null /** * @internal */ var _actionTimeline: ActionTimelineState? = null // Initial value. private var _zOrderTimeline: ZOrderTimelineState? = null // Initial value. private var _activeChildA: AnimationState? = null private var _activeChildB: AnimationState? = null /** * @internal */ var _parent: AnimationState? = null override fun _onClear(): Unit { this._boneTimelines.fastForEach { timeline -> timeline.returnToPool() } this._boneBlendTimelines.fastForEach { timeline -> timeline.returnToPool() } this._slotTimelines.fastForEach { timeline -> timeline.returnToPool() } this._slotBlendTimelines.fastForEach { timeline -> timeline.returnToPool() } this._constraintTimelines.fastForEach { timeline -> timeline.returnToPool() } this._animationTimelines.fastForEach { timeline -> val animationState = timeline.targetAnimationState!! if (animationState._parent == this) { animationState._fadeState = 1 animationState._subFadeState = 1 animationState._parent = null } timeline.returnToPool() } this._actionTimeline?.returnToPool() this._zOrderTimeline?.returnToPool() this.actionEnabled = false this.additive = false this.displayControl = false this.resetToPose = false this.blendType = AnimationBlendType.None this.playTimes = 1 this.layer = 0 this.timeScale = 1.0 this._weight = 1.0 this.parameterX = 0.0 this.parameterY = 0.0 this.positionX = 0.0 this.positionY = 0.0 this.autoFadeOutTime = 0.0 this.fadeTotalTime = 0.0 this.name = "" this.group = "" this._timelineDirty = 2 this._playheadState = 0 this._fadeState = -1 this._subFadeState = -1 this._position = 0.0 this._duration = 0.0 this._fadeTime = 0.0 this._time = 0.0 this._fadeProgress = 0.0 this._weightResult = 0.0 this._boneMask.clear() this._boneTimelines.clear() this._boneBlendTimelines.clear() this._slotTimelines.clear() this._slotBlendTimelines.clear() this._constraintTimelines.clear() this._animationTimelines.clear() this._poseTimelines.clear() // this._bonePoses.clear(); this._animationData = null // this._armature = null // this._actionTimeline = null // this._zOrderTimeline = null this._activeChildA = null this._activeChildB = null this._parent = null } private fun _updateTimelines(): Unit { // Update constraint timelines. this._armature!!._constraints.fastForEach { constraint -> val timelineDatas = this._animationData?.getConstraintTimelines(constraint.name) if (timelineDatas != null) { timelineDatas.fastForEach { timelineData -> when (timelineData.type) { TimelineType.IKConstraint -> { val timeline = pool.iKConstraintTimelineState.borrow() timeline.targetIKConstraint = constraint as IKConstraint timeline.init(this._armature!!, this, timelineData) this._constraintTimelines.add(timeline) } else -> Unit } } } else if (this.resetToPose) { // Pose timeline. val timeline = pool.iKConstraintTimelineState.borrow() timeline.targetIKConstraint = constraint as IKConstraint timeline.init(this._armature!!, this, null) this._constraintTimelines.add(timeline) this._poseTimelines.add(timeline) } } } private fun _updateBoneAndSlotTimelines(): Unit { run { // Update bone and surface timelines. val boneTimelines: FastStringMap<FastArrayList<TimelineState>> = FastStringMap() // Create bone timelines map. this._boneTimelines.fastForEach { timeline -> val timelineName = ((timeline.targetBlendState)!!.targetBone)!!.name if (timelineName !in boneTimelines) { boneTimelines[timelineName] = FastArrayList() } boneTimelines[timelineName]?.add(timeline) } this._boneBlendTimelines.fastForEach { timeline -> val timelineName = ((timeline.targetBlendState)!!.targetBone)!!.name if (timelineName !in boneTimelines) { boneTimelines[timelineName] = FastArrayList() } boneTimelines[timelineName]?.add(timeline) } // this._armature!!.getBones().fastForEach { bone -> val timelineName = bone.name if (!this.containsBoneMask(timelineName)) { return@fastForEach } if (timelineName in boneTimelines) { // Remove bone timeline from map. boneTimelines.remove(timelineName) } else { // Create new bone timeline. val timelineDatas = this._animationData?.getBoneTimelines(timelineName) val blendState = this._armature!!.animation.getBlendState(BlendState.BONE_TRANSFORM, bone.name, bone) if (timelineDatas != null) { timelineDatas.fastForEach { timelineData -> when (timelineData.type) { TimelineType.BoneAll -> { val timeline = pool.boneAllTimelineState.borrow() timeline.targetBlendState = blendState timeline.init(this._armature!!, this, timelineData) this._boneTimelines.add(timeline) } TimelineType.BoneTranslate -> { val timeline = pool.boneTranslateTimelineState.borrow() timeline.targetBlendState = blendState timeline.init(this._armature!!, this, timelineData) this._boneTimelines.add(timeline) } TimelineType.BoneRotate -> { val timeline = pool.boneRotateTimelineState.borrow() timeline.targetBlendState = blendState timeline.init(this._armature!!, this, timelineData) this._boneTimelines.add(timeline) } TimelineType.BoneScale -> { val timeline = pool.boneScaleTimelineState.borrow() timeline.targetBlendState = blendState timeline.init(this._armature!!, this, timelineData) this._boneTimelines.add(timeline) } TimelineType.BoneAlpha -> { val timeline = pool.alphaTimelineState.borrow() timeline.targetBlendState = this._armature!!.animation.getBlendState(BlendState.BONE_ALPHA, bone.name, bone) timeline.init(this._armature!!, this, timelineData) this._boneBlendTimelines.add(timeline) } TimelineType.Surface -> { val timeline = pool.surfaceTimelineState.borrow() timeline.targetBlendState = this._armature!!.animation.getBlendState(BlendState.SURFACE, bone.name, bone) timeline.init(this._armature!!, this, timelineData) this._boneBlendTimelines.add(timeline) } else -> Unit } } } else if (this.resetToPose) { // Pose timeline. if (bone._boneData?.isBone == true) { val timeline = pool.boneAllTimelineState.borrow() timeline.targetBlendState = blendState timeline.init(this._armature!!, this, null) this._boneTimelines.add(timeline) this._poseTimelines.add(timeline) } else { val timeline = pool.surfaceTimelineState.borrow() timeline.targetBlendState = this._armature!!.animation.getBlendState(BlendState.SURFACE, bone.name, bone) timeline.init(this._armature!!, this, null) this._boneBlendTimelines.add(timeline) this._poseTimelines.add(timeline) } } } } boneTimelines.fastKeyForEach { k -> // Remove bone timelines. boneTimelines[k]!!.fastForEach { timeline -> var index = this._boneTimelines.indexOf(timeline) if (index >= 0) { this._boneTimelines.splice(index, 1) timeline.returnToPool() } index = this._boneBlendTimelines.indexOf(timeline) if (index >= 0) { this._boneBlendTimelines.splice(index, 1) timeline.returnToPool() } } } } run { // Update slot timelines. val slotTimelines: FastStringMap<FastArrayList<TimelineState>> = FastStringMap() val ffdFlags = IntArrayList() // Create slot timelines map. this._slotTimelines.fastForEach { timeline -> val timelineName = (timeline.targetSlot)!!.name if (timelineName !in slotTimelines) { slotTimelines[timelineName] = FastArrayList() } slotTimelines[timelineName]?.add(timeline) } this._slotBlendTimelines.fastForEach { timeline -> val timelineName = ((timeline.targetBlendState)!!.targetSlot)!!.name if (timelineName !in slotTimelines) { slotTimelines[timelineName] = FastArrayList() } slotTimelines[timelineName]?.add(timeline) } // this._armature!!.getSlots().fastForEach { slot -> val boneName = slot.parent.name if (!this.containsBoneMask(boneName)) { return@fastForEach } val timelineName = slot.name if (timelineName in slotTimelines) { // Remove slot timeline from map. slotTimelines.remove(timelineName) } else { // Create new slot timeline. var displayIndexFlag = false var colorFlag = false ffdFlags.length = 0 val timelineDatas = this._animationData?.getSlotTimelines(timelineName) if (timelineDatas != null) { timelineDatas.fastForEach { timelineData -> when (timelineData.type) { TimelineType.SlotDisplay -> { val timeline = pool.slotDisplayTimelineState.borrow() timeline.targetSlot = slot timeline.init(this._armature!!, this, timelineData) this._slotTimelines.add(timeline) displayIndexFlag = true } TimelineType.SlotZIndex -> { val timeline = pool.slotZIndexTimelineState.borrow() timeline.targetBlendState = this._armature!!.animation.getBlendState( BlendState.SLOT_Z_INDEX, slot.name, slot ) timeline.init(this._armature!!, this, timelineData) this._slotBlendTimelines.add(timeline) } TimelineType.SlotColor -> { val timeline = pool.slotColorTimelineState.borrow() timeline.targetSlot = slot timeline.init(this._armature!!, this, timelineData) this._slotTimelines.add(timeline) colorFlag = true } TimelineType.SlotDeform -> { val timeline = pool.deformTimelineState.borrow() timeline.targetBlendState = this._armature!!.animation.getBlendState( BlendState.SLOT_DEFORM, slot.name, slot ) timeline.init(this._armature!!, this, timelineData) if (timeline.targetBlendState != null) { this._slotBlendTimelines.add(timeline) ffdFlags.push(timeline.geometryOffset) } else { timeline.returnToPool() } } TimelineType.SlotAlpha -> { val timeline = pool.alphaTimelineState.borrow() timeline.targetBlendState = this._armature!!.animation.getBlendState( BlendState.SLOT_ALPHA, slot.name, slot ) timeline.init(this._armature!!, this, timelineData) this._slotBlendTimelines.add(timeline) } else -> { } } } } if (this.resetToPose) { // Pose timeline. if (!displayIndexFlag) { val timeline = pool.slotDisplayTimelineState.borrow() timeline.targetSlot = slot timeline.init(this._armature!!, this, null) this._slotTimelines.add(timeline) this._poseTimelines.add(timeline) } if (!colorFlag) { val timeline = pool.slotColorTimelineState.borrow() timeline.targetSlot = slot timeline.init(this._armature!!, this, null) this._slotTimelines.add(timeline) this._poseTimelines.add(timeline) } for (i in 0 until slot.displayFrameCount) { val displayFrame = slot.getDisplayFrameAt(i) if (displayFrame.deformVertices.isEmpty()) { continue } val geometryData = displayFrame.getGeometryData() if (geometryData != null && ffdFlags.indexOf(geometryData.offset) < 0) { val timeline = pool.deformTimelineState.borrow() timeline.geometryOffset = geometryData.offset // timeline.displayFrame = displayFrame // timeline.targetBlendState = this._armature!!.animation.getBlendState( BlendState.SLOT_DEFORM, slot.name, slot ) timeline.init(this._armature!!, this, null) this._slotBlendTimelines.add(timeline) this._poseTimelines.add(timeline) } } } } } slotTimelines.fastValueForEach { slotTimelines2 -> // Remove slot timelines. slotTimelines2.fastForEach { timeline -> var index = this._slotTimelines.indexOf(timeline) if (index >= 0) { this._slotTimelines.splice(index, 1) timeline.returnToPool() } index = this._slotBlendTimelines.indexOf(timeline) if (index >= 0) { this._slotBlendTimelines.splice(index, 1) timeline.returnToPool() } } } } } private fun _advanceFadeTime(passedTime: Double) { var passedTime = passedTime val isFadeOut = this._fadeState > 0 if (this._subFadeState < 0) { // Fade start event. this._subFadeState = 0 val eventActive = this._parent == null && this.actionEnabled if (eventActive) { val eventType = if (isFadeOut) EventObject.FADE_OUT else EventObject.FADE_IN if (this._armature!!.eventDispatcher.hasDBEventListener(eventType)) { val eventObject = pool.eventObject.borrow() eventObject.type = eventType eventObject.armature = this._armature!! eventObject.animationState = this this._armature!!.eventDispatcher!!.queueEvent(eventObject) } } } if (passedTime < 0.0) { passedTime = -passedTime } this._fadeTime += passedTime if (this._fadeTime >= this.fadeTotalTime) { // Fade complete. this._subFadeState = 1 this._fadeProgress = if (isFadeOut) 0.0 else 1.0 } else if (this._fadeTime > 0.0) { // Fading. this._fadeProgress = if (isFadeOut) (1.0 - this._fadeTime / this.fadeTotalTime) else (this._fadeTime / this.fadeTotalTime) } else { // Before fade. this._fadeProgress = if (isFadeOut) 1.0 else 0.0 } if (this._subFadeState > 0) { // Fade complete event. if (!isFadeOut) { this._playheadState = this._playheadState or 1 // x1 this._fadeState = 0 } val eventActive = this._parent == null && this.actionEnabled if (eventActive) { val eventType = if (isFadeOut) EventObject.FADE_OUT_COMPLETE else EventObject.FADE_IN_COMPLETE if (this._armature!!.eventDispatcher.hasDBEventListener(eventType)) { val eventObject = pool.eventObject.borrow() eventObject.type = eventType eventObject.armature = this._armature!! eventObject.animationState = this this._armature!!.eventDispatcher!!.queueEvent(eventObject) } } } } /** * @internal */ fun init(armature: Armature, animationData: AnimationData, animationConfig: AnimationConfig): Unit { if (this._armature != null) { return } this._armature = armature this._animationData = animationData // this.resetToPose = animationConfig.resetToPose this.additive = animationConfig.additive this.displayControl = animationConfig.displayControl this.actionEnabled = animationConfig.actionEnabled this.blendType = animationData.blendType this.layer = animationConfig.layer this.playTimes = animationConfig.playTimes this.timeScale = animationConfig.timeScale this.fadeTotalTime = animationConfig.fadeInTime this.autoFadeOutTime = animationConfig.autoFadeOutTime this.name = if (animationConfig.name.isNotEmpty()) animationConfig.name else animationConfig.animation this.group = animationConfig.group // this._weight = animationConfig.weight if (animationConfig.pauseFadeIn) { this._playheadState = 2 // 10 } else { this._playheadState = 3 // 11 } if (animationConfig.duration < 0.0) { this._position = 0.0 this._duration = this._animationData!!.duration if (animationConfig.position != 0.0) { if (this.timeScale >= 0.0) { this._time = animationConfig.position } else { this._time = animationConfig.position - this._duration } } else { this._time = 0.0 } } else { this._position = animationConfig.position this._duration = animationConfig.duration this._time = 0.0 } if (this.timeScale < 0.0 && this._time == 0.0) { this._time = -0.000001 // Turn to end. } if (this.fadeTotalTime <= 0.0) { this._fadeProgress = 0.999999 // Make different. } if (animationConfig.boneMask.length > 0) { this._boneMask.lengthSet = animationConfig.boneMask.length //for (var i = 0, l = this._boneMask.length; i < l; ++i) { for (i in 0 until this._boneMask.length) { this._boneMask[i] = animationConfig.boneMask[i] } } this._actionTimeline = pool.actionTimelineState.borrow() this._actionTimeline!!.init(this._armature!!, this, this._animationData!!.actionTimeline) this._actionTimeline!!._currentTime = this._time if (this._actionTimeline!!._currentTime < 0.0) { this._actionTimeline!!._currentTime = this._duration - this._actionTimeline!!._currentTime } if (this._animationData!!.zOrderTimeline != null) { this._zOrderTimeline = pool.zOrderTimelineState.borrow() this._zOrderTimeline!!.init(this._armature!!, this, this._animationData!!.zOrderTimeline) } } /** * @internal */ fun advanceTime(passedTime: Double, cacheFrameRate: Double) { var passedTime = passedTime // Update fade time. if (this._fadeState != 0 || this._subFadeState != 0) { this._advanceFadeTime(passedTime) } // Update time. if (this._playheadState == 3) { // 11 if (this.timeScale != 1.0) { passedTime *= this.timeScale } this._time += passedTime } // Update timeline. if (this._timelineDirty != 0) { if (this._timelineDirty == 2) { this._updateTimelines() } this._timelineDirty = 0 this._updateBoneAndSlotTimelines() } val isBlendDirty = this._fadeState != 0 || this._subFadeState == 0 val isCacheEnabled = this._fadeState == 0 && cacheFrameRate > 0.0 var isUpdateTimeline = true var isUpdateBoneTimeline = true var time = this._time this._weightResult = this._weight * this._fadeProgress if (this._parent != null) { this._weightResult *= this._parent!!._weightResult } if (this._actionTimeline!!.playState <= 0) { // Update main timeline. this._actionTimeline?.update(time) } if (this._weight == 0.0) { return } if (isCacheEnabled) { // Cache time internval. val internval = cacheFrameRate * 2.0 this._actionTimeline!!._currentTime = floor(this._actionTimeline!!._currentTime * internval) / internval } if (this._zOrderTimeline != null && this._zOrderTimeline!!.playState <= 0) { // Update zOrder timeline. this._zOrderTimeline?.update(time) } if (isCacheEnabled) { // Update cache. val cacheFrameIndex = floor(this._actionTimeline!!._currentTime * cacheFrameRate).toInt() // uint if (this._armature?._cacheFrameIndex == cacheFrameIndex) { // Same cache. isUpdateTimeline = false isUpdateBoneTimeline = false } else { this._armature?._cacheFrameIndex = cacheFrameIndex if (this._animationData!!.cachedFrames[cacheFrameIndex]) { // Cached. isUpdateBoneTimeline = false } else { // Cache. this._animationData!!.cachedFrames[cacheFrameIndex] = true } } } if (isUpdateTimeline) { var isBlend = false var prevTarget: BlendState? = null // if (isUpdateBoneTimeline) { //for (var i = 0, l = this._boneTimelines.length; i < l; ++i) { for (i in 0 until this._boneTimelines.length) { val timeline = this._boneTimelines[i] if (timeline.playState <= 0) { timeline.update(time) } if (timeline.targetBlendState != prevTarget) { val blendState = timeline.targetBlendState isBlend = blendState!!.update(this) prevTarget = blendState if (blendState.dirty == 1) { val pose = (blendState.targetBone)!!.animationPose pose.xf = 0f pose.yf = 0f pose.rotation = 0f pose.skew = 0f pose.scaleX = 1f pose.scaleY = 1f } } if (isBlend) { timeline.blend(isBlendDirty) } } } //for (var i = 0, l = this._boneBlendTimelines.length; i < l; ++i) { for (i in 0 until this._boneBlendTimelines.length) { val timeline = this._boneBlendTimelines[i] if (timeline.playState <= 0) { timeline.update(time) } if ((timeline.targetBlendState)!!.update(this)) { timeline.blend(isBlendDirty) } } if (this.displayControl) { //for (var i = 0, l = this._slotTimelines.length; i < l; ++i) { for (i in 0 until this._slotTimelines.length) { val timeline = this._slotTimelines[i] if (timeline.playState <= 0) { val slot = timeline.targetSlot val displayController = slot!!.displayController if ( displayController == null || displayController == this.name || displayController == this.group ) { timeline.update(time) } } } } //for (var i = 0, l = this._slotBlendTimelines.length; i < l; ++i) { for (i in 0 until this._slotBlendTimelines.length) { val timeline = this._slotBlendTimelines[i] if (timeline.playState <= 0) { val blendState = timeline.targetBlendState timeline.update(time) if (blendState!!.update(this)) { timeline.blend(isBlendDirty) } } } //for (var i = 0, l = this._constraintTimelines.length; i < l; ++i) { for (i in 0 until this._constraintTimelines.length) { val timeline = this._constraintTimelines[i] if (timeline.playState <= 0) { timeline.update(time) } } if (this._animationTimelines.lengthSet > 0) { var dL = 100.0 var dR = 100.0 var leftState: AnimationState? = null var rightState: AnimationState? = null //for (var i = 0, l = this._animationTimelines.length; i < l; ++i) { for (i in 0 until this._animationTimelines.length) { val timeline = this._animationTimelines[i] if (timeline.playState <= 0) { timeline.update(time) } if (this.blendType == AnimationBlendType.E1D) { // TODO val animationState = timeline.targetAnimationState val d = this.parameterX - animationState!!.positionX if (d >= 0.0) { if (d < dL) { dL = d leftState = animationState } } else { if (-d < dR) { dR = -d rightState = animationState } } } } if (leftState != null) { if (this._activeChildA != leftState) { if (this._activeChildA != null) { this._activeChildA!!.weight = 0.0 } this._activeChildA = leftState this._activeChildA!!.activeTimeline() } if (this._activeChildB != rightState) { if (this._activeChildB != null) { this._activeChildB!!.weight = 0.0 } this._activeChildB = rightState } leftState.weight = dR / (dL + dR) if (rightState != null) { rightState.weight = 1.0 - leftState.weight } } } } if (this._fadeState == 0) { if (this._subFadeState > 0) { this._subFadeState = 0 if (this._poseTimelines.lengthSet > 0) { // Remove pose timelines. this._poseTimelines.fastForEach { timeline -> var index = this._boneTimelines.indexOf(timeline) if (index >= 0) { this._boneTimelines.splice(index, 1) timeline.returnToPool() return@fastForEach } index = this._boneBlendTimelines.indexOf(timeline) if (index >= 0) { this._boneBlendTimelines.splice(index, 1) timeline.returnToPool() return@fastForEach } index = this._slotTimelines.indexOf(timeline) if (index >= 0) { this._slotTimelines.splice(index, 1) timeline.returnToPool() return@fastForEach } index = this._slotBlendTimelines.indexOf(timeline) if (index >= 0) { this._slotBlendTimelines.splice(index, 1) timeline.returnToPool() return@fastForEach } index = this._constraintTimelines.indexOf(timeline) if (index >= 0) { this._constraintTimelines.splice(index, 1) timeline.returnToPool() return@fastForEach } } this._poseTimelines.lengthSet = 0 } } if (this._actionTimeline!!.playState > 0) { if (this.autoFadeOutTime >= 0.0) { // Auto fade out. this.fadeOut(this.autoFadeOutTime) } } } } /** * - Continue play. * @version DragonBones 3.0 * @language en_US */ /** * - 继续播放。 * @version DragonBones 3.0 * @language zh_CN */ fun play(): Unit { this._playheadState = 3 // 11 } /** * - Stop play. * @version DragonBones 3.0 * @language en_US */ /** * - 暂停播放。 * @version DragonBones 3.0 * @language zh_CN */ fun stop(): Unit { this._playheadState = this._playheadState and 1 // 0x } /** * - Fade out the animation state. * @param fadeOutTime - The fade out time. (In seconds) * @param pausePlayhead - Whether to pause the animation playing when fade out. * @version DragonBones 3.0 * @language en_US */ /** * - 淡出动画状态。 * @param fadeOutTime - 淡出时间。 (以秒为单位) * @param pausePlayhead - 淡出时是否暂停播放。 * @version DragonBones 3.0 * @language zh_CN */ fun fadeOut(fadeOutTime: Double, pausePlayhead: Boolean = true): Unit { var fadeOutTime = fadeOutTime if (fadeOutTime < 0.0) { fadeOutTime = 0.0 } if (pausePlayhead) { this._playheadState = this._playheadState and 2 // x0 } if (this._fadeState > 0) { if (fadeOutTime > this.fadeTotalTime - this._fadeTime) { // If the animation is already in fade out, the new fade out will be ignored. return } } else { this._fadeState = 1 this._subFadeState = -1 if (fadeOutTime <= 0.0 || this._fadeProgress <= 0.0) { this._fadeProgress = 0.000001 // Modify fade progress to different value. } this._boneTimelines.fastForEach { timeline -> timeline.fadeOut() } this._boneBlendTimelines.fastForEach { timeline -> timeline.fadeOut() } this._slotTimelines.fastForEach { timeline -> timeline.fadeOut() } this._slotBlendTimelines.fastForEach { timeline -> timeline.fadeOut() } this._constraintTimelines.fastForEach { timeline -> timeline.fadeOut() } this._animationTimelines.fastForEach { timeline -> timeline.fadeOut() // val animaitonState = timeline.targetAnimationState animaitonState!!.fadeOut(999999.0, true) } } this.displayControl = false // this.fadeTotalTime = if (this._fadeProgress > 0.000001) fadeOutTime / this._fadeProgress else 0.0 this._fadeTime = this.fadeTotalTime * (1.0 - this._fadeProgress) } /** * - Check if a specific bone mask is included. * @param boneName - The bone name. * @version DragonBones 3.0 * @language en_US */ /** * - 检查是否包含特定骨骼遮罩。 * @param boneName - 骨骼名称。 * @version DragonBones 3.0 * @language zh_CN */ fun containsBoneMask(boneName: String): Boolean { return this._boneMask.lengthSet == 0 || this._boneMask.indexOf(boneName) >= 0 } /** * - Add a specific bone mask. * @param boneName - The bone name. * @param recursive - Whether or not to add a mask to the bone's sub-bone. * @version DragonBones 3.0 * @language en_US */ /** * - 添加特定的骨骼遮罩。 * @param boneName - 骨骼名称。 * @param recursive - 是否为该骨骼的子骨骼添加遮罩。 * @version DragonBones 3.0 * @language zh_CN */ fun addBoneMask(boneName: String, recursive: Boolean = true) { val currentBone = this._armature?.getBone(boneName) ?: return if (this._boneMask.indexOf(boneName) < 0) { // Add mixing this._boneMask.add(boneName) } if (recursive) { // Add recursive mixing. this._armature!!.getBones().fastForEach { bone -> if (this._boneMask.indexOf(bone.name) < 0 && currentBone.contains(bone)) { this._boneMask.add(bone.name) } } } this._timelineDirty = 1 } /** * - Remove the mask of a specific bone. * @param boneName - The bone name. * @param recursive - Whether to remove the bone's sub-bone mask. * @version DragonBones 3.0 * @language en_US */ /** * - 删除特定骨骼的遮罩。 * @param boneName - 骨骼名称。 * @param recursive - 是否删除该骨骼的子骨骼遮罩。 * @version DragonBones 3.0 * @language zh_CN */ fun removeBoneMask(boneName: String, recursive: Boolean = true): Unit { val index = this._boneMask.indexOf(boneName) if (index >= 0) { // Remove mixing. this._boneMask.splice(index, 1) } if (recursive) { val currentBone = this._armature?.getBone(boneName) if (currentBone != null) { val bones = this._armature!!.getBones() if (this._boneMask.lengthSet > 0) { // Remove recursive mixing. bones.fastForEach { bone -> val index = this._boneMask.indexOf(bone.name) if (index >= 0 && currentBone.contains(bone)) { this._boneMask.splice(index, 1) } } } else { // Add unrecursive mixing. bones.fastForEach { bone -> if (bone == currentBone) { return@fastForEach } if (!currentBone.contains(bone)) { this._boneMask.add(bone.name) } } } } } this._timelineDirty = 1 } /** * - Remove all bone masks. * @version DragonBones 3.0 * @language en_US */ /** * - 删除所有骨骼遮罩。 * @version DragonBones 3.0 * @language zh_CN */ fun removeAllBoneMask() { this._boneMask.lengthSet = 0 this._timelineDirty = 1 } /** * @private */ fun addState(animationState: AnimationState, timelineDatas: FastArrayList<TimelineData>? = null) { timelineDatas?.fastForEach { timelineData -> when (timelineData.type) { TimelineType.AnimationProgress -> { val timeline = pool.animationProgressTimelineState.borrow() timeline.targetAnimationState = animationState timeline.init(this._armature!!, this, timelineData) this._animationTimelines.add(timeline) if (this.blendType != AnimationBlendType.None) { val animaitonTimelineData = timelineData as AnimationTimelineData animationState.positionX = animaitonTimelineData.x animationState.positionY = animaitonTimelineData.y animationState.weight = 0.0 } animationState._parent = this this.resetToPose = false } TimelineType.AnimationWeight -> { val timeline = pool.animationWeightTimelineState.borrow() timeline.targetAnimationState = animationState timeline.init(this._armature!!, this, timelineData) this._animationTimelines.add(timeline) } TimelineType.AnimationParameter -> { val timeline = pool.animationParametersTimelineState.borrow() timeline.targetAnimationState = animationState timeline.init(this._armature!!, this, timelineData) this._animationTimelines.add(timeline) } else -> { } } } if (animationState._parent == null) { animationState._parent = this } } /** * @internal */ fun activeTimeline(): Unit { this._slotTimelines.fastForEach { timeline -> timeline.dirty = true timeline._currentTime = -1.0 } } /** * - Whether the animation state is fading in. * @version DragonBones 5.1 * @language en_US */ /** * - 是否正在淡入。 * @version DragonBones 5.1 * @language zh_CN */ val isFadeIn: Boolean get() { return this._fadeState < 0 } /** * - Whether the animation state is fading out. * @version DragonBones 5.1 * @language en_US */ /** * - 是否正在淡出。 * @version DragonBones 5.1 * @language zh_CN */ val isFadeOut: Boolean get() { return this._fadeState > 0 } /** * - Whether the animation state is fade completed. * @version DragonBones 5.1 * @language en_US */ /** * - 是否淡入或淡出完毕。 * @version DragonBones 5.1 * @language zh_CN */ val isFadeComplete: Boolean get() { return this._fadeState == 0 } /** * - Whether the animation state is playing. * @version DragonBones 3.0 * @language en_US */ /** * - 是否正在播放。 * @version DragonBones 3.0 * @language zh_CN */ val isPlaying: Boolean get() { return (this._playheadState and 2) != 0 && this._actionTimeline!!.playState <= 0 } /** * - Whether the animation state is play completed. * @version DragonBones 3.0 * @language en_US */ /** * - 是否播放完毕。 * @version DragonBones 3.0 * @language zh_CN */ val isCompleted: Boolean get() { return this._actionTimeline!!.playState > 0 } /** * - The times has been played. * @version DragonBones 3.0 * @language en_US */ /** * - 已经循环播放的次数。 * @version DragonBones 3.0 * @language zh_CN */ val currentPlayTimes: Int get() { return this._actionTimeline!!.currentPlayTimes } /** * - The total time. (In seconds) * @version DragonBones 3.0 * @language en_US */ /** * - 总播放时间。 (以秒为单位) * @version DragonBones 3.0 * @language zh_CN */ val totalTime: Double get() { return this._duration } /** * - The time is currently playing. (In seconds) * @version DragonBones 3.0 * @language en_US */ /** * - 当前播放的时间。 (以秒为单位) * @version DragonBones 3.0 * @language zh_CN */ var currentTime: Double get() = this._actionTimeline!!._currentTime set(value) { var value = value val currentPlayTimes = this._actionTimeline!!.currentPlayTimes - (if (this._actionTimeline!!.playState > 0) 1 else 0) if (value < 0 || this._duration < value) { value = (value % this._duration) + currentPlayTimes * this._duration if (value < 0) { value += this._duration } } if ( this.playTimes > 0 && currentPlayTimes == this.playTimes - 1 && value == this._duration && this._parent == null ) { value = this._duration - 0.000001 // } if (this._time == value) { return } this._time = value this._actionTimeline!!.setCurrentTime(this._time) this._zOrderTimeline?.playState = -1 this._boneTimelines.fastForEach { timeline -> timeline.playState = -1 } this._slotTimelines.fastForEach { timeline -> timeline.playState = -1 } } /** * - The blend weight. * @default 1.0 * @version DragonBones 5.0 * @language en_US */ /** * - 混合权重。 * @default 1.0 * @version DragonBones 5.0 * @language zh_CN */ /** * - The animation data. * @see dragonBones.AnimationData * @version DragonBones 3.0 * @language en_US */ var weight: Double get() = this._weight set(value) { if (this._weight == value) return this._weight = value for (n in 0 until _boneTimelines.size) _boneTimelines[n].dirty = true for (n in 0 until _boneBlendTimelines.size) _boneBlendTimelines[n].dirty = true for (n in 0 until _slotBlendTimelines.size) _slotBlendTimelines[n].dirty = true } /** * - 动画数据。 * @see dragonBones.AnimationData * @version DragonBones 3.0 * @language zh_CN */ val animationData: AnimationData get() = this._animationData!! } /** * @internal */ class BlendState(pool: SingleObjectPool<BlendState>) : BaseObject(pool) { companion object { const val BONE_TRANSFORM: String = "boneTransform" const val BONE_ALPHA: String = "boneAlpha" const val SURFACE: String = "surface" const val SLOT_DEFORM: String = "slotDeform" const val SLOT_ALPHA: String = "slotAlpha" const val SLOT_Z_INDEX: String = "slotZIndex" } override fun toString(): String { return "[class dragonBones.BlendState]" } var dirty: Int = 0 var layer: Int = 0 var leftWeight: Double = 0.0 var layerWeight: Double = 0.0 var blendWeight: Double = 0.0 //var target: BaseObject? = null var targetSlot: Slot? = null var targetBone: Bone? = null var targetSurface: Surface? = null var targetTransformObject: TransformObject? = null val targetCommon: TransformObject? get() = targetSlot ?: targetBone ?: targetSurface ?: targetTransformObject override fun _onClear() { this.reset() this.targetSlot = null this.targetBone = null this.targetSurface = null this.targetTransformObject = null } fun reset() { this.dirty = 0 this.layer = 0 this.leftWeight = 0.0 this.layerWeight = 0.0 this.blendWeight = 0.0 } fun update(animationState: AnimationState): Boolean { val animationLayer = animationState.layer var animationWeight = animationState._weightResult if (this.dirty > 0) { if (this.leftWeight > 0.0) { if (this.layer != animationLayer) { if (this.layerWeight >= this.leftWeight) { this.dirty++ this.layer = animationLayer this.leftWeight = 0.0 this.blendWeight = 0.0 return false } this.layer = animationLayer this.leftWeight -= this.layerWeight this.layerWeight = 0.0 } animationWeight *= this.leftWeight this.dirty++ this.blendWeight = animationWeight this.layerWeight += this.blendWeight return true } return false } this.dirty++ this.layer = animationLayer this.leftWeight = 1.0 this.blendWeight = animationWeight this.layerWeight = animationWeight return true } }
apache-2.0
7cb4402fbfb531f87668bdffe9497373
27.251101
137
0.636319
3.587836
false
false
false
false
martin-nordberg/KatyDOM
Katydid-VDOM-JVM/src/main/kotlin/jvm/katydid/kdom/KDomElement.kt
1
2107
// // (C) Copyright 2017-2019 Martin E. Nordberg III // Apache 2.0 License // package jvm.katydid.kdom import jvm.katydid.infrastructure.indent import x.katydid.vdom.dom.Element //--------------------------------------------------------------------------------------------------------------------- /** * Implementation of DOM Element for generating HTML text for testing or server-side rendering. */ class KDomElement( override val ownerDocument: KDomDocument, override val nodeName: String ) : KDomNode(), Element { private val _attributes: MutableMap<String, String> = sortedMapOf() //// override var nodeValue: String? get() = null set(_) {} override val tagName: String get() { return nodeName.toLowerCase() } //// override fun removeAttribute(name: String) { _attributes.remove(name) } override fun setAttribute(name: String, value: String) { _attributes[name] = value } override fun toHtmlString(indent: Int): String { val result = StringBuilder() result.indent(indent) result.append("<", tagName) for (attr in _attributes) { result.append(" ", attr.key, "=\"", attr.value, "\"") } var child = this.firstChild if (child == null) { result.append(">") } else { result.append(">\n") while (child != null) { result.append(child.toHtmlString(indent + 2)) result.append('\n') child = child.nextSibling } result.indent(indent) } if (!elementsWithoutEndTags.contains(tagName)) { result.append("</", tagName, ">") } return result.toString() } //// private companion object { val elementsWithoutEndTags = hashSetOf( "br", "hr", "img", "input", "source", "track", "wbr" ) } } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
0f1eeadbf173c42bfa7151465032cd06
22.411111
119
0.490745
4.934426
false
false
false
false
xbh0902/cryptlib
app/src/main/java/me/xbh/cryptlib/ui/MainActivity.kt
1
5425
package me.xbh.cryptlib.ui import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import kotlinx.android.synthetic.main.activity_main.* import me.xbh.cryptlib.R import me.xbh.cryptlib.databinding.ActivityMainBinding import me.xbh.lib.sdk.CryptManager import me.xbh.lib.core.CryptService /** * <p> * 描述: * </p> * 创建日期:2017年11月22日. * @author [email protected] * @version 1.0 */ class MainActivity : AppCompatActivity() { val TAG = "Test" lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_main) val threadJava = Thread(object: Runnable{ override fun run() { val start = System.currentTimeMillis() val text = "{name:\"你好啊,我不好!你真的ok吗?\", age:120}" val cm = CryptManager.getStandard() Log.i(TAG, "c_md5=>${cm.md5(text)}") var count = 0 do { Log.i(TAG, "================= RSA-BEGIN =================") val pubkey = cm.getRsaPubKey(1) // val enstr = cm.encrypt(rsa, "jVIr32Ju5H85laQY", pubkey) val destr = cm.decrypt("Y7R1J829EraGPqBXdXVDRD65X943eKtvhp33kmoXNFAfH15qdFv8b3JySyyT+3ZjU2j3Nn3zaQUTX6V9C8zoeQvBYEN3FK7bVWwPwGBTkJ5Uw6+sthZUfWCqPZWFLtvSM3qOJymmcvaNPu648/V99RI4Sx3J/2vQQzIdorcrDKY=", pubkey, CryptService.RSA) // Log.i(TAG, "encrypt=>$enstr") Log.i(TAG, "decrypt=>$destr") Log.i(TAG, "pubkey=>$pubkey") Log.i(TAG, "================= RSA-END =================") Log.i(TAG, "================= AES-BEGIN =================") val key = destr val plainText = cm.decrypt("/BBBv9p/VGs5P9hBvCUHzok3hpJ+f8pVE2VbeYkMjJLGMw5igBtav58JN9NJilYVgJzCIrKfm618" + "P1ovtJueYh5Y4gaewftOsPP3PwsBPoORpADFiI8ttVPEbRextUjCgE7uVUkUAftomE9eFeAdbGRv" + "jqeot7B6eCHeIIPFbOo+ZOCk7uX36UiT0tNXcu+hh3ezuOXrSsgi5a/Io++xSRsUEAgcj3JY+UHe" + "h4Ig2WFgaFOnOtjeWl/LHE4A7ww9qK11ONsgb7q6I1LfFwNjNWpSeerbOLkbJCwfnP1yW2gVvwwL" + "GmMvQ1wFgZNBwYAs", key, CryptService.AES) Log.i(TAG, "decrypt=>$plainText") Log.i(TAG, "AESLOCALKEY=>${cm.getAesLocalKey(this@MainActivity)}") Log.i(TAG, "================= AES-END =================") count++ } while (count < 1000) val end = System.currentTimeMillis() runOnUiThread { tv_java.text = "java:${end - start}" } } } ).start() val threadCxx = Thread(object: Runnable{ override fun run() { val start = System.currentTimeMillis() val text = "{name:\"你好啊,我不好!你真的ok吗?\", age:120}" val cm = CryptManager.getDefault() Log.i(TAG, "c_md5=>${cm.md5(text)}") var count = 0 do { Log.i(TAG, "================= RSA-BEGIN =================") val pubkey = cm.getRsaPubKey(1) // val enstr = cm.encrypt(rsa, "jVIr32Ju5H85laQY", pubkey) val destr = cm.decrypt("Y7R1J829EraGPqBXdXVDRD65X943eKtvhp33kmoXNFAfH15qdFv8b3JySyyT+3ZjU2j3Nn3zaQUTX6V9C8zoeQvBYEN3FK7bVWwPwGBTkJ5Uw6+sthZUfWCqPZWFLtvSM3qOJymmcvaNPu648/V99RI4Sx3J/2vQQzIdorcrDKY=", pubkey, CryptService.RSA) // Log.i(TAG, "encrypt=>$enstr") Log.i(TAG, "decrypt=>$destr") Log.i(TAG, "pubkey=>$pubkey") Log.i(TAG, "================= RSA-END =================") Log.i(TAG, "================= AES-BEGIN =================") val key = destr val plainText = cm.decrypt("/BBBv9p/VGs5P9hBvCUHzok3hpJ+f8pVE2VbeYkMjJLGMw5igBtav58JN9NJilYVgJzCIrKfm618" + "P1ovtJueYh5Y4gaewftOsPP3PwsBPoORpADFiI8ttVPEbRextUjCgE7uVUkUAftomE9eFeAdbGRv" + "jqeot7B6eCHeIIPFbOo+ZOCk7uX36UiT0tNXcu+hh3ezuOXrSsgi5a/Io++xSRsUEAgcj3JY+UHe" + "h4Ig2WFgaFOnOtjeWl/LHE4A7ww9qK11ONsgb7q6I1LfFwNjNWpSeerbOLkbJCwfnP1yW2gVvwwL" + "GmMvQ1wFgZNBwYAs", key, CryptService.AES) Log.i(TAG, "decrypt=>$plainText") Log.i(TAG, "AESLOCALKEY=>${cm.getAesLocalKey(this@MainActivity)}") Log.i(TAG, "================= AES-END =================") count++ } while (count < 1000) val end = System.currentTimeMillis() runOnUiThread { tv_cxx.text = "cxx:${end - start}" } } } ).start() } override fun onResume() { super.onResume() } }
mit
5964c790784021f4d3c50a10232040dd
43.231405
218
0.51467
3.246966
false
false
false
false
panpf/sketch
sketch-video-ffmpeg/src/androidTest/java/com/github/panpf/sketch/video/ffmpeg/test/decode/FFmpegVideoFrameBitmapDecoderTest.kt
1
12774
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.video.ffmpeg.test.decode import android.graphics.Bitmap import android.media.MediaMetadataRetriever import android.os.Build import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.github.panpf.sketch.cache.CachePolicy.DISABLED import com.github.panpf.sketch.datasource.AssetDataSource import com.github.panpf.sketch.datasource.DataFrom.LOCAL import com.github.panpf.sketch.decode.FFmpegVideoFrameBitmapDecoder import com.github.panpf.sketch.decode.internal.createInSampledTransformed import com.github.panpf.sketch.fetch.FetchResult import com.github.panpf.sketch.fetch.newAssetUri import com.github.panpf.sketch.request.ImageRequest import com.github.panpf.sketch.request.LoadRequest import com.github.panpf.sketch.request.internal.RequestContext import com.github.panpf.sketch.request.videoFrameMillis import com.github.panpf.sketch.request.videoFrameOption import com.github.panpf.sketch.request.videoFramePercent import com.github.panpf.sketch.resize.Precision.LESS_PIXELS import com.github.panpf.sketch.sketch import com.github.panpf.sketch.util.Size import com.github.panpf.sketch.video.ffmpeg.test.utils.corners import com.github.panpf.tools4a.device.Devicex import com.github.panpf.tools4j.test.ktx.assertThrow import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class FFmpegVideoFrameBitmapDecoderTest { @Test fun testFactory() { val context = InstrumentationRegistry.getInstrumentation().context val sketch = context.sketch val factory = FFmpegVideoFrameBitmapDecoder.Factory() Assert.assertEquals("FFmpegVideoFrameBitmapDecoder", factory.toString()) // normal LoadRequest(context, newAssetUri("sample.mp4")).let { val fetchResult = FetchResult(AssetDataSource(sketch, it, "sample.mp4"), null) factory.create(sketch, it.toRequestContext(), fetchResult) }.apply { Assert.assertNull(this) } LoadRequest(context, newAssetUri("sample.mp4")).let { val fetchResult = FetchResult(AssetDataSource(sketch, it, "sample.mp4"), "video/mp4") factory.create(sketch, it.toRequestContext(), fetchResult) }.apply { Assert.assertNotNull(this) } // data error LoadRequest(context, newAssetUri("sample.png")).let { val fetchResult = FetchResult(AssetDataSource(sketch, it, "sample.png"), "video/mp4") factory.create(sketch, it.toRequestContext(), fetchResult) }.apply { Assert.assertNotNull(this) } // mimeType error LoadRequest(context, newAssetUri("sample.mp4")).let { val fetchResult = FetchResult(AssetDataSource(sketch, it, "sample.mp4"), "image/png") factory.create(sketch, it.toRequestContext(), fetchResult) }.apply { Assert.assertNull(this) } } @Test fun testFactoryEqualsAndHashCode() { val element1 = FFmpegVideoFrameBitmapDecoder.Factory() val element11 = FFmpegVideoFrameBitmapDecoder.Factory() Assert.assertNotSame(element1, element11) Assert.assertEquals(element1, element1) Assert.assertEquals(element1, element11) Assert.assertNotEquals(element1, Any()) Assert.assertNotEquals(element1, null) Assert.assertEquals(element1.hashCode(), element1.hashCode()) Assert.assertEquals(element1.hashCode(), element11.hashCode()) } @Test fun testDecode() { if (Build.VERSION.SDK_INT < 24 && Devicex.isEmulator()) { // UnsatisfiedLinkError /data/app/com.github.panpf.sketch.video.ffmpeg.test-1/lib/arm64/libssl.so return } val context = InstrumentationRegistry.getInstrumentation().context val sketch = context.sketch val factory = FFmpegVideoFrameBitmapDecoder.Factory() LoadRequest(context, newAssetUri("sample.mp4")).run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { factory.create(sketch, [email protected](), fetchResult)!!.decode() } }.apply { Assert.assertEquals("Bitmap(500x250,ARGB_8888)", bitmap.toShortInfoString()) Assert.assertEquals( "ImageInfo(500x250,'video/mp4',UNDEFINED)", imageInfo.toShortString() ) Assert.assertEquals(LOCAL, dataFrom) Assert.assertNull(transformedList) } LoadRequest(context, newAssetUri("sample.mp4")) { resize(300, 300, LESS_PIXELS) }.run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { factory.create(sketch, [email protected](), fetchResult)!!.decode() } }.apply { Assert.assertEquals("Bitmap(250x125,ARGB_8888)", bitmap.toShortInfoString()) Assert.assertEquals( "ImageInfo(500x250,'video/mp4',UNDEFINED)", imageInfo.toShortString() ) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals(listOf(createInSampledTransformed(2)), transformedList) } LoadRequest(context, newAssetUri("sample.png")).run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } assertThrow(NullPointerException::class) { runBlocking { factory.create(sketch, [email protected](), fetchResult)!! .decode() } } } } @Test fun testDecodeVideoFrameMicros() { if (Build.VERSION.SDK_INT < 24 && Devicex.isEmulator()) { // UnsatisfiedLinkError /data/app/com.github.panpf.sketch.video.ffmpeg.test-1/lib/arm64/libssl.so return } val context = InstrumentationRegistry.getInstrumentation().context val sketch = context.sketch val factory = FFmpegVideoFrameBitmapDecoder.Factory() val bitmap1 = LoadRequest(context, newAssetUri("sample.mp4")) { memoryCachePolicy(DISABLED) resultCachePolicy(DISABLED) videoFrameOption(MediaMetadataRetriever.OPTION_CLOSEST) }.run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { factory.create(sketch, [email protected](), fetchResult)!!.decode() } }.bitmap val bitmap11 = LoadRequest(context, newAssetUri("sample.mp4")) { memoryCachePolicy(DISABLED) resultCachePolicy(DISABLED) videoFrameOption(MediaMetadataRetriever.OPTION_CLOSEST) }.run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { factory.create(sketch, [email protected](), fetchResult)!!.decode() } }.bitmap val bitmap2 = LoadRequest(context, newAssetUri("sample.mp4")) { memoryCachePolicy(DISABLED) resultCachePolicy(DISABLED) videoFrameOption(MediaMetadataRetriever.OPTION_CLOSEST) videoFrameMillis(500) }.run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { factory.create(sketch, [email protected](), fetchResult)!!.decode() } }.bitmap Assert.assertEquals(bitmap1.corners(), bitmap11.corners()) Assert.assertNotEquals(bitmap1.corners(), bitmap2.corners()) } @Test fun testDecodeVideoFramePercent() { if (Build.VERSION.SDK_INT < 24 && Devicex.isEmulator()) { // UnsatisfiedLinkError /data/app/com.github.panpf.sketch.video.ffmpeg.test-1/lib/arm64/libssl.so return } val context = InstrumentationRegistry.getInstrumentation().context val sketch = context.sketch val factory = FFmpegVideoFrameBitmapDecoder.Factory() val bitmap1 = LoadRequest(context, newAssetUri("sample.mp4")) { memoryCachePolicy(DISABLED) resultCachePolicy(DISABLED) videoFrameOption(MediaMetadataRetriever.OPTION_CLOSEST) }.run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { factory.create(sketch, [email protected](), fetchResult)!!.decode() } }.bitmap val bitmap11 = LoadRequest(context, newAssetUri("sample.mp4")) { memoryCachePolicy(DISABLED) resultCachePolicy(DISABLED) videoFrameOption(MediaMetadataRetriever.OPTION_CLOSEST) }.run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { factory.create(sketch, [email protected](), fetchResult)!!.decode() } }.bitmap val bitmap2 = LoadRequest(context, newAssetUri("sample.mp4")) { memoryCachePolicy(DISABLED) resultCachePolicy(DISABLED) videoFrameOption(MediaMetadataRetriever.OPTION_CLOSEST) videoFramePercent(0.45f) }.run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { factory.create(sketch, [email protected](), fetchResult)!!.decode() } }.bitmap Assert.assertEquals(bitmap1.corners(), bitmap11.corners()) Assert.assertNotEquals(bitmap1.corners(), bitmap2.corners()) } @Test fun testDecodeVideoOption() { if (Build.VERSION.SDK_INT < 24 && Devicex.isEmulator()) { // UnsatisfiedLinkError /data/app/com.github.panpf.sketch.video.ffmpeg.test-1/lib/arm64/libssl.so return } val context = InstrumentationRegistry.getInstrumentation().context val sketch = context.sketch val factory = FFmpegVideoFrameBitmapDecoder.Factory() val bitmap1 = LoadRequest(context, newAssetUri("sample.mp4")) { memoryCachePolicy(DISABLED) resultCachePolicy(DISABLED) videoFramePercent(0.5f) }.run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { try { factory.create(sketch, [email protected](), fetchResult)!! .decode() } catch (e: Exception) { e.printStackTrace() null } } }?.bitmap val bitmap2 = LoadRequest(context, newAssetUri("sample.mp4")) { memoryCachePolicy(DISABLED) resultCachePolicy(DISABLED) videoFramePercent(0.5f) videoFrameOption(MediaMetadataRetriever.OPTION_CLOSEST) }.run { val fetcher = sketch.components.newFetcher(this) val fetchResult = runBlocking { fetcher.fetch() } runBlocking { factory.create(sketch, [email protected](), fetchResult)!!.decode() } }.bitmap Assert.assertNotEquals(bitmap1?.corners(), bitmap2.corners()) } private fun Bitmap.toShortInfoString(): String = "Bitmap(${width}x${height},$config)" } fun ImageRequest.toRequestContext(resizeSize: Size? = null): RequestContext { return RequestContext(this, resizeSize ?: runBlocking { resizeSizeResolver.size() }) }
apache-2.0
080efa81db7e4a0c6919f5710e40848a
40.209677
109
0.644043
4.836804
false
true
false
false
stripe/stripe-android
payments-core/src/test/java/com/stripe/android/model/PaymentIntentTest.kt
1
8828
package com.stripe.android.model import android.net.Uri import com.google.common.truth.Truth.assertThat import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import kotlin.test.Test import kotlin.test.assertFailsWith @RunWith(RobolectricTestRunner::class) class PaymentIntentTest { @Test fun parseIdFromClientSecret_parsesCorrectly() { val clientSecret = "pi_1CkiBMLENEVhOs7YMtUehLau_secret_s4O8SDh7s6spSmHDw1VaYPGZA" val paymentIntentId = PaymentIntent.ClientSecret(clientSecret).paymentIntentId assertThat(paymentIntentId) .isEqualTo("pi_1CkiBMLENEVhOs7YMtUehLau") } @Test fun parsePaymentIntentWith3DS2PaymentMethods() { val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2 assertThat(paymentIntent.requiresAction()) .isTrue() assertThat(paymentIntent.paymentMethodTypes) .containsExactly("card") assertThat(paymentIntent.canceledAt) .isEqualTo(0) assertThat(paymentIntent.captureMethod) .isEqualTo(PaymentIntent.CaptureMethod.Automatic) assertThat(paymentIntent.confirmationMethod) .isEqualTo(PaymentIntent.ConfirmationMethod.Manual) assertThat(paymentIntent.nextActionData) .isNotNull() assertThat(paymentIntent.receiptEmail) .isEqualTo("[email protected]") assertThat(paymentIntent.cancellationReason) .isNull() } @Test fun parsePaymentIntentWithBlikPaymentMethods() { val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_BLIK_AUTHORIZE assertThat(paymentIntent.requiresAction()) .isTrue() assertThat(paymentIntent.paymentMethodTypes) .containsExactly("blik") } @Test fun parsePaymentIntentWithWeChatPayPaymentMethods() { val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_WECHAT_PAY_AUTHORIZE assertThat(paymentIntent.requiresAction()) .isTrue() assertThat(paymentIntent.paymentMethodTypes) .containsExactly("wechat_pay") } @Test fun parsePaymentIntentWithKlarnaPaymentMethods() { val paymentIntent = PaymentIntentFixtures.PI_WITH_KLARNA_IN_PAYMENT_METHODS assertThat(paymentIntent.paymentMethodTypes) .containsExactly("klarna") } @Test fun parsePaymentIntentWithAffirmPaymentMethods() { val paymentIntent = PaymentIntentFixtures.PI_WITH_AFFIRM_IN_PAYMENT_METHODS assertThat(paymentIntent.paymentMethodTypes) .containsExactly("affirm") } @Test fun parsePaymentIntentWithUSBankAccountPaymentMethods() { val paymentIntent = PaymentIntentFixtures.PI_WITH_US_BANK_ACCOUNT_IN_PAYMENT_METHODS assertThat(paymentIntent.paymentMethodTypes) .containsExactly("us_bank_account") } @Test fun getNextActionData_whenUseStripeSdkWith3ds2() { val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2 assertThat(paymentIntent.nextActionData) .isInstanceOf(StripeIntent.NextActionData.SdkData.Use3DS2::class.java) val sdkData = paymentIntent.nextActionData as StripeIntent.NextActionData.SdkData.Use3DS2 assertThat(sdkData.serverName) .isEqualTo("mastercard") } @Test fun getNextActionData_whenUseStripeSdkWith3ds1() { val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_3DS1 assertThat(paymentIntent.nextActionData) .isInstanceOf(StripeIntent.NextActionData.SdkData.Use3DS1::class.java) val sdkData = paymentIntent.nextActionData as StripeIntent.NextActionData.SdkData.Use3DS1 assertThat(sdkData.url) .isNotEmpty() } @Test fun getNextActionData_whenRedirectToUrl() { val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_REDIRECT assertThat(paymentIntent.nextActionData) .isInstanceOf(StripeIntent.NextActionData.RedirectToUrl::class.java) val redirectData = paymentIntent.nextActionData as StripeIntent.NextActionData.RedirectToUrl assertThat(redirectData.url) .isEqualTo( Uri.parse( "https://hooks.stripe.com/3d_secure_2_eap/begin_test/src_1Ecaz6CR" + "Mbs6FrXfuYKBRSUG/src_client_secret_F6octeOshkgxT47dr0ZxSZiv" ) ) assertThat(redirectData.returnUrl) .isEqualTo("stripe://deeplink") } @Test fun getNextActionData_whenBlikAuthorize() { val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_BLIK_AUTHORIZE assertThat(paymentIntent.nextActionData) .isInstanceOf(StripeIntent.NextActionData.BlikAuthorize::class.java) } @Test fun getNextActionData_whenWeChatPay() { val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_WECHAT_PAY_AUTHORIZE assertThat(paymentIntent.nextActionData) .isInstanceOf(StripeIntent.NextActionData.WeChatPayRedirect::class.java) val weChat = (paymentIntent.nextActionData as StripeIntent.NextActionData.WeChatPayRedirect).weChat assertThat(weChat).isEqualTo( WeChat( appId = "wx65997d6307c3827d", nonce = "some_random_string", packageValue = "Sign=WXPay", partnerId = "wx65997d6307c3827d", prepayId = "test_transaction", timestamp = "1619638941", sign = "8B26124BABC816D7140034DDDC7D3B2F1036CCB2D910E52592687F6A44790D5E" ) ) } @Test fun getNextActionData_whenVerifyWithMicrodeposits() { val paymentIntent = PaymentIntentFixtures.PI_WITH_US_BANK_ACCOUNT_IN_PAYMENT_METHODS assertThat(paymentIntent.nextActionData) .isInstanceOf(StripeIntent.NextActionData.VerifyWithMicrodeposits::class.java) val verify = (paymentIntent.nextActionData as StripeIntent.NextActionData.VerifyWithMicrodeposits) assertThat(verify).isEqualTo( StripeIntent.NextActionData.VerifyWithMicrodeposits( arrivalDate = 1647241200, hostedVerificationUrl = "https://payments.stripe.com/microdeposit/pacs_test_YWNjdF8" + "xS2J1SjlGbmt1bWlGVUZ4LHBhX25vbmNlX0xJcFVEaERaU0JOVVR3akhxMXc5eklOQkl3UTlwNWo00" + "00v3GS1Jej", microdepositType = MicrodepositType.AMOUNTS ) ) } @Test fun getLastPaymentError_parsesCorrectly() { val lastPaymentError = requireNotNull(PaymentIntentFixtures.PI_WITH_LAST_PAYMENT_ERROR.lastPaymentError) assertThat(lastPaymentError.paymentMethod?.id) .isEqualTo("pm_1F7J1bCRMbs6FrXfQKsYwO3U") assertThat(lastPaymentError.code) .isEqualTo("payment_intent_authentication_failure") assertThat(lastPaymentError.type) .isEqualTo(PaymentIntent.Error.Type.InvalidRequestError) assertThat(lastPaymentError.docUrl) .isEqualTo("https://stripe.com/docs/error-codes/payment-intent-authentication-failure") assertThat(lastPaymentError.message) .isEqualTo( "The provided PaymentMethod has failed authentication. You can provide " + "payment_method_data or a new PaymentMethod to attempt to fulfill this " + "PaymentIntent again." ) } @Test fun testCanceled() { assertThat(PaymentIntentFixtures.CANCELLED.status) .isEqualTo(StripeIntent.Status.Canceled) assertThat(PaymentIntentFixtures.CANCELLED.cancellationReason) .isEquivalentAccordingToCompareTo(PaymentIntent.CancellationReason.Abandoned) assertThat(PaymentIntentFixtures.CANCELLED.canceledAt) .isEqualTo(1567091866L) } @Test fun clientSecret_withInvalidKeys_throwsException() { assertFailsWith<IllegalArgumentException> { PaymentIntent.ClientSecret("pi_12345") } assertFailsWith<IllegalArgumentException> { PaymentIntent.ClientSecret("pi_12345_secret_") } assertFailsWith<IllegalArgumentException> { SetupIntent.ClientSecret("pi_secret") } assertFailsWith<IllegalArgumentException> { SetupIntent.ClientSecret("pi_secret_a") } assertFailsWith<IllegalArgumentException> { PaymentIntent.ClientSecret("pi_a1b2c3_secret_x7y8z9pi_a1b2c3_secret_x7y8z9") } } @Test fun clientSecret_withValidKeys_succeeds() { assertThat(PaymentIntent.ClientSecret("pi_a1b2c3_secret_x7y8z9").value) .isEqualTo("pi_a1b2c3_secret_x7y8z9") } }
mit
4815b03f1381b42300fba520afd94406
38.765766
102
0.682601
4.483494
false
true
false
false
paulofernando/localchat
app/src/main/kotlin/site/paulo/localchat/data/manager/UserLocationManager.kt
1
2298
/* * Copyright 2017 Paulo Fernando * * 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 site.paulo.localchat.data.manager import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.location.Location import androidx.core.content.ContextCompat import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import site.paulo.localchat.data.DataManager import timber.log.Timber import javax.inject.Singleton @Singleton object UserLocationManager { var dataManager: DataManager? = null var context: Context? = null var callNext: (() -> Unit)? = null private lateinit var fusedLocationClient: FusedLocationProviderClient fun init(context: Context, dataManager: DataManager) { this.context = context this.dataManager = dataManager fusedLocationClient = LocationServices.getFusedLocationProviderClient(context) } fun start(callNext: (() -> Unit)? = null) { val ctx = this.context ?: return val permission = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) if (permission != PackageManager.PERMISSION_GRANTED) { Timber.e("Permission to location denied") } else { this.callNext = callNext fusedLocationClient.lastLocation .addOnSuccessListener { location: Location? -> Timber.d("Location: lon -> ${location?.longitude} | lat -> ${location?.latitude}") dataManager?.updateUserLocation(location, UserLocationManager.callNext) Timber.d("Location has been sent to server") } } } }
apache-2.0
53248f86c4ec5762c3c7568d4c9df99c
35.492063
106
0.696258
4.910256
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/rest/rest-dto/src/main/kotlin/org/tsdes/advanced/rest/dto/RestResponseFactory.kt
1
1275
package org.tsdes.advanced.rest.dto import org.springframework.http.ResponseEntity import java.net.URI object RestResponseFactory { fun <T> notFound(message: String): ResponseEntity<WrappedResponse<T>> { return ResponseEntity.status(404).body( WrappedResponse<T>(code = 404, message = message) .validated()) } fun <T> userFailure(message: String, httpCode: Int = 400): ResponseEntity<WrappedResponse<T>> { return ResponseEntity.status(httpCode).body( WrappedResponse<T>(code = httpCode, message = message) .validated()) } fun <T> payload(httpCode: Int, data: T): ResponseEntity<WrappedResponse<T>> { return ResponseEntity.status(httpCode).body( WrappedResponse(code = httpCode, data = data) .validated()) } fun noPayload(httpCode: Int): ResponseEntity<WrappedResponse<Void>> { return ResponseEntity.status(httpCode).body( WrappedResponse<Void>(code = httpCode).validated()) } fun created(uri: URI): ResponseEntity<WrappedResponse<Void>> { return ResponseEntity.created(uri).body( WrappedResponse<Void>(code = 201).validated()) } }
lgpl-3.0
71a5e88e796ae3c15f58885ef56abce7
30.121951
99
0.626667
4.619565
false
false
false
false
androidx/androidx
lifecycle/integration-tests/incrementality/src/test/kotlin/androidx/lifecycle/IncrementalAnnotationProcessingTest.kt
3
13215
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.lifecycle import androidx.testutils.gradle.ProjectSetupRule import com.google.common.truth.Truth.assertThat import org.gradle.tooling.GradleConnector import org.gradle.tooling.ProjectConnection import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.io.File import java.nio.file.Files import java.nio.file.Path @RunWith(JUnit4::class) class IncrementalAnnotationProcessingTest { companion object { private const val MAIN_DIR = "app/src/main" private const val BUILD_DIR = "app/build" private const val SOURCE_DIR = "$MAIN_DIR/java/androidx/lifecycle/incap" private const val GENERATED_SOURCE_DIR = BUILD_DIR + "/generated/ap_generated_sources/debug/out/androidx/lifecycle/incap" private const val CLASSES_DIR = "$BUILD_DIR/intermediates/javac/debug/classes" private const val GENERATED_PROGUARD_DIR = "$CLASSES_DIR/META-INF/proguard" private const val APP_CLASS_DIR = "$CLASSES_DIR/androidx/lifecycle/incap" } @get:Rule val projectSetup = ProjectSetupRule() private lateinit var projectRoot: File private lateinit var fooObserver: File private lateinit var barObserver: File private lateinit var genFooAdapter: File private lateinit var genBarAdapter: File private lateinit var genFooProguard: File private lateinit var genBarProguard: File private lateinit var fooObserverClass: File private lateinit var barObserverClass: File private lateinit var genFooAdapterClass: File private lateinit var genBarAdapterClass: File private lateinit var projectConnection: ProjectConnection @Before fun setup() { projectRoot = projectSetup.rootDir fooObserver = File(projectRoot, "$SOURCE_DIR/FooObserver.java") barObserver = File(projectRoot, "$SOURCE_DIR/BarObserver.java") genFooAdapter = File( projectRoot, GENERATED_SOURCE_DIR + "/FooObserver_LifecycleAdapter.java" ) genBarAdapter = File( projectRoot, GENERATED_SOURCE_DIR + "/BarObserver_LifecycleAdapter.java" ) genFooProguard = File( projectRoot, GENERATED_PROGUARD_DIR + "/androidx.lifecycle.incap.FooObserver.pro" ) genBarProguard = File( projectRoot, GENERATED_PROGUARD_DIR + "/androidx.lifecycle.incap.BarObserver.pro" ) fooObserverClass = File(projectRoot, "$APP_CLASS_DIR/FooObserver.class") barObserverClass = File(projectRoot, "$APP_CLASS_DIR/BarObserver.class") genFooAdapterClass = File( projectRoot, APP_CLASS_DIR + "/FooObserver_LifecycleAdapter.class" ) genBarAdapterClass = File( projectRoot, APP_CLASS_DIR + "/BarObserver_LifecycleAdapter.class" ) projectRoot.mkdirs() setupProjectBuildGradle() setupAppBuildGradle() setupSettingsGradle() setupAndroidManifest() addSource() projectConnection = GradleConnector.newConnector() .forProjectDirectory(projectRoot).connect() } @Test fun checkModifySource() { projectConnection .newBuild() .forTasks("clean", "compileDebugJavaWithJavac") .run() val fooAdapterFirstBuild = Files.getLastModifiedTime(genFooAdapter.toPath()).toMillis() val barAdapterFirstBuild = Files.getLastModifiedTime(genBarAdapter.toPath()).toMillis() val fooProguardFirstBuild = Files.getLastModifiedTime(genFooProguard.toPath()).toMillis() val barProguardFirstBuild = Files.getLastModifiedTime(genBarProguard.toPath()).toMillis() val fooObserverClassFirstBuild = Files.getLastModifiedTime(fooObserverClass.toPath()).toMillis() val barObserverClassFirstBuild = Files.getLastModifiedTime(barObserverClass.toPath()).toMillis() val fooAdapterClassFirstBuild = Files.getLastModifiedTime(genFooAdapterClass.toPath()).toMillis() val barAdapterClassFirstBuild = Files.getLastModifiedTime(genBarAdapterClass.toPath()).toMillis() searchAndReplace(fooObserver.toPath(), "FooObserver_Log", "Modified_FooObserver_Log") projectConnection .newBuild() .forTasks("compileDebugJavaWithJavac") .run() val fooAdapterSecondBuild = Files.getLastModifiedTime(genFooAdapter.toPath()).toMillis() val barAdapterSecondBuild = Files.getLastModifiedTime(genBarAdapter.toPath()).toMillis() val fooProguardSecondBuild = Files.getLastModifiedTime(genFooProguard.toPath()).toMillis() val barProguardSecondBuild = Files.getLastModifiedTime(genBarProguard.toPath()).toMillis() val fooObserverClassSecondBuild = Files.getLastModifiedTime(fooObserverClass.toPath()).toMillis() val barObserverClassSecondBuild = Files.getLastModifiedTime(barObserverClass.toPath()).toMillis() val fooAdapterClassSecondBuild = Files.getLastModifiedTime(genFooAdapterClass.toPath()).toMillis() val barAdapterClassSecondBuild = Files.getLastModifiedTime(genBarAdapterClass.toPath()).toMillis() // FooObserver's adapter and its proguard file are regenerated // FooObserver and its regenerated adapter are recompiled assertThat(fooAdapterFirstBuild).isLessThan(fooAdapterSecondBuild) assertThat(fooProguardFirstBuild).isLessThan(fooProguardSecondBuild) assertThat(fooObserverClassFirstBuild).isLessThan(fooObserverClassSecondBuild) assertThat(fooAdapterClassFirstBuild).isLessThan(fooAdapterClassSecondBuild) // BarObserver's adapter and its proguard are not regenerated // BarObserver and its generated adapter are not recompiled assertThat(barAdapterFirstBuild).isEqualTo(barAdapterSecondBuild) assertThat(barProguardFirstBuild).isEqualTo(barProguardSecondBuild) assertThat(barObserverClassFirstBuild).isEqualTo(barObserverClassSecondBuild) assertThat(barAdapterClassFirstBuild).isEqualTo(barAdapterClassSecondBuild) } @Test fun checkDeleteOneSource() { projectConnection .newBuild() .forTasks("clean", "compileDebugJavaWithJavac") .run() val barAdapterFirstBuild = Files.getLastModifiedTime(genBarAdapter.toPath()).toMillis() val barProguardFirstBuild = Files.getLastModifiedTime(genBarProguard.toPath()).toMillis() val barObserverClassFirstBuild = Files.getLastModifiedTime(barObserverClass.toPath()).toMillis() val barAdapterClassFirstBuild = Files.getLastModifiedTime(genBarAdapterClass.toPath()).toMillis() assertThat(genFooAdapter.exists()).isTrue() assertThat(genFooProguard.exists()).isTrue() fooObserver.delete() projectConnection .newBuild() .forTasks("compileDebugJavaWithJavac") .run() val barAdapterSecondBuild = Files.getLastModifiedTime(genBarAdapter.toPath()).toMillis() val barProguardSecondBuild = Files.getLastModifiedTime(genBarProguard.toPath()).toMillis() val barObserverClassSecondBuild = Files.getLastModifiedTime(barObserverClass.toPath()).toMillis() val barAdapterClassSecondBuild = Files.getLastModifiedTime(genBarAdapterClass.toPath()).toMillis() // FooObserver's adapter and its proguard file are deleted since FooObserver is removed assertThat(genFooAdapter.exists()).isFalse() assertThat(genFooProguard.exists()).isFalse() // BarObserver's adapter and its proguard are not regenerated // BarObserver and its generated adapter are not recompiled assertThat(barAdapterFirstBuild).isEqualTo(barAdapterSecondBuild) assertThat(barProguardFirstBuild).isEqualTo(barProguardSecondBuild) assertThat(barObserverClassFirstBuild).isEqualTo(barObserverClassSecondBuild) assertThat(barAdapterClassFirstBuild).isEqualTo(barAdapterClassSecondBuild) } @After fun closeProjectConnection() { projectConnection.close() } private fun setupProjectBuildGradle() { val repositoriesBlock = buildString { appendLine("repositories {") projectSetup.allRepositoryPaths.forEach { appendLine("""maven { url "$it" }""") } appendLine("}") } addFileWithContent( "build.gradle", """ buildscript { ${repositoriesBlock.prependIndent(" ")} dependencies { classpath "${projectSetup.props.agpDependency}" } } allprojects { $repositoriesBlock } task clean(type: Delete) { delete rootProject.buildDir } """.trimIndent() ) } private fun setupAppBuildGradle() { addFileWithContent( "app/build.gradle", """ apply plugin: 'com.android.application' android { namespace "androidx.lifecycle.incap" compileSdkVersion ${projectSetup.props.compileSdkVersion} buildToolsVersion "${projectSetup.props.buildToolsVersion}" defaultConfig { minSdkVersion ${projectSetup.props.minSdkVersion} } signingConfigs { debug { storeFile file("${projectSetup.props.debugKeystore}") } } } dependencies { // Use the latest lifecycle-runtime to keep up with lifecycle-compiler implementation "androidx.lifecycle:lifecycle-runtime:+" // Use the latest version to test lifecycle-compiler artifact built from tip of tree annotationProcessor "androidx.lifecycle:lifecycle-compiler:+" } """.trimIndent() ) } private fun setupSettingsGradle() { addFileWithContent( "settings.gradle", """ include ':app' """.trimIndent() ) } private fun setupAndroidManifest() { addFileWithContent( "$MAIN_DIR/AndroidManifest.xml", """ <manifest/> """.trimIndent() ) } private fun addSource() { addFileWithContent( "$SOURCE_DIR/FooObserver.java", """ package androidx.lifecycle.incap; import android.util.Log; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.OnLifecycleEvent; class FooObserver implements LifecycleObserver { private String mLog = "FooObserver_Log"; @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void onResume() { Log.i(mLog, "onResume"); } } """.trimIndent() ) addFileWithContent( "$SOURCE_DIR/BarObserver.java", """ package androidx.lifecycle.incap; import android.util.Log; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.OnLifecycleEvent; class BarObserver implements LifecycleObserver { private String mLog = "BarObserver_Log"; @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void onResume() { Log.i(mLog, "onResume"); } } """.trimIndent() ) } private fun addFileWithContent(relativePath: String, content: String) { val file = File(projectRoot, relativePath) file.parentFile.mkdirs() file.writeText(content) } private fun searchAndReplace(file: Path, search: String, replace: String) { val content = String(Files.readAllBytes(file)) val newContent = content.replace(search, replace) Files.write(file, newContent.toByteArray()) } }
apache-2.0
777bcea037fc6be2d5d21607a574ae91
36.974138
100
0.646538
5.15808
false
false
false
false
androidx/androidx
camera/integration-tests/viewtestapp/src/main/java/androidx/camera/integration/view/ComposeUiFragment.kt
3
5560
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.view import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.camera.core.Camera import androidx.camera.core.CameraSelector import androidx.camera.core.FocusMeteringAction import androidx.camera.core.FocusMeteringResult import androidx.camera.core.MeteringPointFactory import androidx.camera.core.Preview import androidx.camera.core.impl.utils.executor.CameraXExecutors import androidx.camera.integration.view.MainActivity.CAMERA_DIRECTION_BACK import androidx.camera.integration.view.MainActivity.CAMERA_DIRECTION_FRONT import androidx.camera.integration.view.MainActivity.INTENT_EXTRA_CAMERA_DIRECTION import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.compose.runtime.Composable import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.viewinterop.AndroidView import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.LifecycleOwner import com.google.common.util.concurrent.FutureCallback import com.google.common.util.concurrent.Futures private const val TAG = "ComposeUiFragment" class ComposeUiFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val cameraProvider = ProcessCameraProvider.getInstance(requireContext()).get() val previewView = PreviewView(requireContext()) return ComposeView(requireContext()).apply { setContent { AddPreviewView( cameraProvider, previewView ) } } } @Composable private fun AddPreviewView(cameraProvider: ProcessCameraProvider, previewView: PreviewView) { previewView.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) previewView.scaleType = PreviewView.ScaleType.FILL_CENTER AndroidView( factory = { previewView } ) CameraXExecutors.mainThreadExecutor().execute { bindPreview(cameraProvider, this, previewView) } } private fun bindPreview( cameraProvider: ProcessCameraProvider, lifecycleOwner: LifecycleOwner, previewView: PreviewView, ) { val preview = Preview.Builder().build() val cameraSelector = getCameraSelector() preview.setSurfaceProvider(previewView.surfaceProvider) val camera = cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview) setUpFocusAndMetering(camera, previewView) } private fun getCameraSelector(): CameraSelector { var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA val bundle: Bundle? = requireActivity().intent.extras if (bundle != null) { cameraSelector = when (bundle.getString(INTENT_EXTRA_CAMERA_DIRECTION, CAMERA_DIRECTION_BACK)) { CAMERA_DIRECTION_BACK -> CameraSelector.DEFAULT_BACK_CAMERA CAMERA_DIRECTION_FRONT -> CameraSelector.DEFAULT_FRONT_CAMERA else -> CameraSelector.DEFAULT_BACK_CAMERA } } return cameraSelector } private fun setUpFocusAndMetering(camera: Camera, previewView: PreviewView) { previewView.setOnTouchListener { _, motionEvent: MotionEvent -> when (motionEvent.action) { MotionEvent.ACTION_DOWN -> return@setOnTouchListener true MotionEvent.ACTION_UP -> { val factory: MeteringPointFactory = previewView.meteringPointFactory val action = FocusMeteringAction.Builder( factory.createPoint(motionEvent.x, motionEvent.y) ).build() Futures.addCallback( camera.cameraControl.startFocusAndMetering(action), object : FutureCallback<FocusMeteringResult?> { override fun onSuccess(result: FocusMeteringResult?) { Log.d(TAG, "Focus and metering succeeded") } override fun onFailure(t: Throwable) { Log.e(TAG, "Focus and metering failed", t) } }, ContextCompat.getMainExecutor(requireContext()) ) return@setOnTouchListener true } else -> return@setOnTouchListener false } } } }
apache-2.0
cfdc05b307456cc4ac3bda0407feed09
37.881119
97
0.661691
5.45098
false
false
false
false
nrizzio/Signal-Android
app/src/spinner/java/org/thoughtcrime/securesms/StorageServicePlugin.kt
1
1919
package org.thoughtcrime.securesms import org.signal.spinner.Plugin import org.signal.spinner.PluginResult import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.keyvalue.SignalStore class StorageServicePlugin : Plugin { override val name: String = "Storage" override val path: String = PATH override fun get(): PluginResult { val columns = listOf("Type", "Data") val rows = mutableListOf<List<String>>() val manager = ApplicationDependencies.getSignalServiceAccountManager() val storageServiceKey = SignalStore.storageService().orCreateStorageKey val storageManifestVersion = manager.storageManifestVersion val manifest = manager.getStorageManifestIfDifferentVersion(storageServiceKey, storageManifestVersion - 1).get() val signalStorageRecords = manager.readStorageRecords(storageServiceKey, manifest.storageIds) for (record in signalStorageRecords) { val row = mutableListOf<String>() if (record.account.isPresent) { row += "Account" row += record.account.get().toProto().toString() } else if (record.contact.isPresent) { row += "Contact" row += record.contact.get().toProto().toString() } else if (record.groupV1.isPresent) { row += "GV1" row += record.groupV1.get().toProto().toString() } else if (record.groupV2.isPresent) { row += "GV2" row += record.groupV2.get().toProto().toString() } else if (record.storyDistributionList.isPresent) { row += "Distribution List" row += record.storyDistributionList.get().toProto().toString() } else { row += "Unknown" row += "" } rows += row } rows.sortBy { it.first() } return PluginResult.TableResult( columns = columns, rows = rows ) } companion object { const val PATH = "/storage" } }
gpl-3.0
0d96bb1baa35eb96fb1c13a71e86789b
32.086207
116
0.676394
4.431871
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/util/AddRemoveMutableList.desktop.kt
3
1505
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.util /** * Helper for implementing a wrapper around some collections * that has only `add` and `removeAt` methods. */ internal abstract class AddRemoveMutableList<T> : AbstractMutableList<T>() { override fun set(index: Int, element: T): T { val old = removeAt(index) add(index, element) return old } override fun add(index: Int, element: T) { if (index == size) { performAdd(element) } else { val removed = slice(index until size) removeRange(index, size) performAdd(element) addAll(removed) } } override fun removeAt(index: Int): T { val old = this[index] performRemove(index) return old } protected abstract fun performAdd(element: T) protected abstract fun performRemove(index: Int) }
apache-2.0
ac01a3e890c264fa4ad9552837587886
29.1
76
0.659136
4.263456
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Any.kt
1
266
package com.simplemobiletools.commons.extensions // extensions used mostly at importing app settings for now fun Any.toBoolean() = toString() == "true" fun Any.toInt() = Integer.parseInt(toString()) fun Any.toStringSet() = toString().split(",".toRegex()).toSet()
gpl-3.0
a89b0697b4658f12ee4ad74e5fdcdb57
32.25
63
0.733083
4.092308
false
false
false
false
ealva-com/ealvalog
ealvalog-core/src/main/java/com/ealva/ealvalog/core/BasicMarker.kt
1
4660
/* * Copyright 2017 Eric A. Snell * * This file is part of eAlvaLog. * * 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.ealva.ealvalog.core import com.ealva.ealvalog.Marker import java.io.IOException import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.util.FormattableFlags.ALTERNATE import java.util.FormattableFlags.LEFT_JUSTIFY import java.util.FormattableFlags.UPPERCASE import java.util.Formatter import java.util.concurrent.CopyOnWriteArraySet /** * Basic Marker implementation * * * Created by Eric A. Snell on 2/28/17. */ open class BasicMarker(override var name: String) : Marker { private var containedMarkers = CopyOnWriteArraySet<Marker>() private// threadLocalStringBuilder.get(); Not thread local builder until we know we're logging markers a lot val stringBuilder: StringBuilder get() = StringBuilder() override fun add(marker: Marker): Boolean { return containedMarkers.add(marker) } override fun remove(marker: Marker): Boolean { return containedMarkers.remove(marker) } override fun isOrContains(marker: Marker): Boolean { return this == marker || containedMarkers.contains(marker) } override fun isOrContains(markerName: String): Boolean { return name == markerName || containedMarkers.find { it.name == markerName } != null } override fun iterator(): Iterator<Marker> { return containedMarkers.iterator() } override fun toString(): String { return if (containedMarkers.isEmpty()) { name } else toStringBuilder(StringBuilder(), true).toString() } override fun toStringBuilder(builder: StringBuilder, includeContained: Boolean): StringBuilder { // subclasses would typically invoke super.toStringBuilder(builder) first if (containedMarkers.isEmpty()) { return builder.append(name) } if (includeContained) { builder.append(name).append(OPEN) containedMarkers.forEachIndexed { i, marker -> if (i != 0) { builder.append(SEPARATOR) } marker.toStringBuilder(builder, true) } builder.append(CLOSE) } return builder } @Throws(IOException::class, ClassNotFoundException::class) private fun readObject(inputStream: ObjectInputStream) { inputStream.defaultReadObject() name = inputStream.readUTF() @Suppress("UNCHECKED_CAST") containedMarkers = inputStream.readObject() as CopyOnWriteArraySet<Marker> } @Throws(IOException::class) private fun writeObject(out: ObjectOutputStream) { out.defaultWriteObject() out.writeUTF(name) out.writeObject(containedMarkers) } override fun formatTo(formatter: Formatter, flags: Int, width: Int, precision: Int) { val useAlternate = flags and ALTERNATE == ALTERNATE val leftJustify = flags and LEFT_JUSTIFY == LEFT_JUSTIFY val upperCase = flags and UPPERCASE == UPPERCASE val builder = stringBuilder toStringBuilder(builder, useAlternate) if (precision != -1 && builder.length > precision) { builder.setLength(precision - 1) builder.append('…') } if (width != -1 && width > builder.length) { builder.ensureCapacity(width) val padAmount = width - builder.length if (leftJustify) { for (i in 0 until padAmount) { builder.append(' ') } } else { for (i in 0 until padAmount) { // could possibly be more efficient to insert from long string of spaces, // but Knuth would not approve builder.insert(0, ' ') } } } formatter.format(if (upperCase) builder.toString().toUpperCase() else builder.toString()) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as BasicMarker if (name != other.name) return false return true } override fun hashCode(): Int { return name.hashCode() } companion object { private const val serialVersionUID = 445780917635303838L private const val OPEN = '[' private const val SEPARATOR = ',' private const val CLOSE = ']' } }
apache-2.0
5bd5158dfb293117a5c04aa3b2ac141d
29.051613
110
0.694719
4.261665
false
false
false
false