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
ericfabreu/ktmdb
ktmdb/src/test/kotlin/com/ericfabreu/ktmdb/ListTest.kt
1
3410
package com.ericfabreu.ktmdb import com.ericfabreu.ktmdb.models.ListV3 import com.ericfabreu.ktmdb.models.ListV4 import com.ericfabreu.ktmdb.models.ListV4.ListMediaItem import com.ericfabreu.ktmdb.utils.LoggableTest import com.ericfabreu.ktmdb.utils.MediaHelper.MediaType import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner /** * Tests for user lists (both v3 and v4). */ @RunWith(RobolectricTestRunner::class) class ListTest : LoggableTest() { companion object { private const val LIST_NAME = "test list" private const val LIST_NAME_CHANGED = "new test list name" private const val ITEM_COUNT = 2 private const val MOVIE_ID_MEMENTO = 77 private const val MOVIE_ID_WW = 297762 private const val TV_ID_GOT = 1399 } @Test @Throws(Exception::class) fun canUseV3Lists() { val listId = ListV3.createList(tmdb, BuildConfig.TmdbSessionId, LIST_NAME)!!.toString() assert(ListV3.addMovie(tmdb, BuildConfig.TmdbSessionId, listId, MOVIE_ID_MEMENTO)) assert(ListV3.addMovie(tmdb, BuildConfig.TmdbSessionId, listId, MOVIE_ID_WW)) // Check that movies were added successfully val details = ListV3.getList(tmdb, listId) assertEquals(LIST_NAME, details.name) assertEquals(ITEM_COUNT, details.itemCount) // Check that we can remove movies and clear lists assert(ListV3.removeMovie(tmdb, BuildConfig.TmdbSessionId, listId, MOVIE_ID_MEMENTO)) assertEquals(ITEM_COUNT - 1, ListV3.getList(tmdb, listId).itemCount) assert(ListV3.clearList(tmdb, BuildConfig.TmdbSessionId, listId)) assert(ListV3.getList(tmdb, listId).items.isEmpty()) assert(ListV3.deleteList(tmdb, BuildConfig.TmdbSessionId, listId)) } @Test @Throws(Exception::class) fun canUseV4Lists() { val listId = ListV4.createList(tmdb, BuildConfig.TmdbAccessToken, LIST_NAME)!! val movieItem = ListMediaItem(MediaType.MOVIE, MOVIE_ID_WW) val tvItem = ListMediaItem(MediaType.TV, TV_ID_GOT) val tvWithComment = ListMediaItem(MediaType.TV, TV_ID_GOT, LIST_NAME) val items = listOf(movieItem, tvItem) ListV4.addItems(tmdb, listId, BuildConfig.TmdbAccessToken, items).forEach { assert(it) } val details = ListV4.getList(tmdb, listId) assertEquals(LIST_NAME, details.name) assertEquals(ITEM_COUNT, details.results.size) // Ensure that list can be updated assert(ListV4.updateList(tmdb, listId, BuildConfig.TmdbAccessToken, LIST_NAME_CHANGED)) assert(ListV4.removeItems(tmdb, listId, BuildConfig.TmdbAccessToken, listOf(movieItem)).first()) assertFalse(ListV4.getItemStatus(tmdb, listId, BuildConfig.TmdbAccessToken, MOVIE_ID_WW, MediaType.MOVIE)) ListV4.updateItems(tmdb, listId, BuildConfig.TmdbAccessToken, listOf(tvWithComment)) assertEquals(LIST_NAME, ListV4.getList(tmdb, listId, BuildConfig.TmdbAccessToken).comments.first().comment) assert(ListV4.clearList(tmdb, 29268, BuildConfig.TmdbAccessToken)) assert(ListV4.getList(tmdb, listId, BuildConfig.TmdbAccessToken).results.isEmpty()) assert(ListV4.deleteList(tmdb, listId, BuildConfig.TmdbAccessToken)) } }
mit
08540b24dfcf43f84efd7ac7848a9839
43.868421
99
0.711437
3.892694
false
true
false
false
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/database/subscription/SubscriptionDAO.kt
1
3928
package org.schabi.newpipe.database.subscription import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.RewriteQueriesToDropUnusedColumns import androidx.room.Transaction import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Maybe import org.schabi.newpipe.database.BasicDAO @Dao abstract class SubscriptionDAO : BasicDAO<SubscriptionEntity> { @Query("SELECT COUNT(*) FROM subscriptions") abstract fun rowCount(): Flowable<Long> @Query("SELECT * FROM subscriptions WHERE service_id = :serviceId") abstract override fun listByService(serviceId: Int): Flowable<List<SubscriptionEntity>> @Query("SELECT * FROM subscriptions ORDER BY name COLLATE NOCASE ASC") abstract override fun getAll(): Flowable<List<SubscriptionEntity>> @Query( """ SELECT * FROM subscriptions WHERE name LIKE '%' || :filter || '%' ORDER BY name COLLATE NOCASE ASC """ ) abstract fun getSubscriptionsFiltered(filter: String): Flowable<List<SubscriptionEntity>> @RewriteQueriesToDropUnusedColumns @Query( """ SELECT * FROM subscriptions s LEFT JOIN feed_group_subscription_join fgs ON s.uid = fgs.subscription_id WHERE (fgs.subscription_id IS NULL OR fgs.group_id = :currentGroupId) ORDER BY name COLLATE NOCASE ASC """ ) abstract fun getSubscriptionsOnlyUngrouped( currentGroupId: Long ): Flowable<List<SubscriptionEntity>> @RewriteQueriesToDropUnusedColumns @Query( """ SELECT * FROM subscriptions s LEFT JOIN feed_group_subscription_join fgs ON s.uid = fgs.subscription_id WHERE (fgs.subscription_id IS NULL OR fgs.group_id = :currentGroupId) AND s.name LIKE '%' || :filter || '%' ORDER BY name COLLATE NOCASE ASC """ ) abstract fun getSubscriptionsOnlyUngroupedFiltered( currentGroupId: Long, filter: String ): Flowable<List<SubscriptionEntity>> @Query("SELECT * FROM subscriptions WHERE url LIKE :url AND service_id = :serviceId") abstract fun getSubscriptionFlowable(serviceId: Int, url: String): Flowable<List<SubscriptionEntity>> @Query("SELECT * FROM subscriptions WHERE url LIKE :url AND service_id = :serviceId") abstract fun getSubscription(serviceId: Int, url: String): Maybe<SubscriptionEntity> @Query("SELECT * FROM subscriptions WHERE uid = :subscriptionId") abstract fun getSubscription(subscriptionId: Long): SubscriptionEntity @Query("DELETE FROM subscriptions") abstract override fun deleteAll(): Int @Query("DELETE FROM subscriptions WHERE url LIKE :url AND service_id = :serviceId") abstract fun deleteSubscription(serviceId: Int, url: String): Int @Query("SELECT uid FROM subscriptions WHERE url LIKE :url AND service_id = :serviceId") internal abstract fun getSubscriptionIdInternal(serviceId: Int, url: String): Long? @Insert(onConflict = OnConflictStrategy.IGNORE) internal abstract fun silentInsertAllInternal(entities: List<SubscriptionEntity>): List<Long> @Transaction open fun upsertAll(entities: List<SubscriptionEntity>): List<SubscriptionEntity> { val insertUidList = silentInsertAllInternal(entities) insertUidList.forEachIndexed { index: Int, uidFromInsert: Long -> val entity = entities[index] if (uidFromInsert != -1L) { entity.uid = uidFromInsert } else { val subscriptionIdFromDb = getSubscriptionIdInternal(entity.serviceId, entity.url) ?: throw IllegalStateException("Subscription cannot be null just after insertion.") entity.uid = subscriptionIdFromDb update(entity) } } return entities } }
gpl-3.0
0d4f47ebe001df73d647bbfc279ba083
34.071429
105
0.693483
4.947103
false
false
false
false
LateNightProductions/CardKeeper
app/src/main/java/com/awscherb/cardkeeper/ui/card_detail/CardDetailFragment.kt
1
4848
package com.awscherb.cardkeeper.ui.card_detail import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.appcompat.widget.Toolbar import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.lifecycle.coroutineScope import com.awscherb.cardkeeper.R import com.awscherb.cardkeeper.data.model.ScannedCode import com.awscherb.cardkeeper.ui.base.BaseFragment import com.awscherb.cardkeeper.ui.create.InvalidFormat import com.awscherb.cardkeeper.ui.create.InvalidText import com.awscherb.cardkeeper.ui.create.InvalidTitle import com.awscherb.cardkeeper.ui.create.SaveResult import com.awscherb.cardkeeper.ui.create.SaveSuccess import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.zxing.BarcodeFormat.AZTEC import com.google.zxing.BarcodeFormat.DATA_MATRIX import com.google.zxing.BarcodeFormat.QR_CODE import com.google.zxing.WriterException import com.journeyapps.barcodescanner.BarcodeEncoder import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import javax.inject.Inject class CardDetailFragment : BaseFragment() { private val viewModel by activityViewModels<CardDetailViewModel> { factory } @Inject lateinit var factory: CardDetailViewModelFactory private val encoder: BarcodeEncoder = BarcodeEncoder() private lateinit var toolbar: Toolbar private lateinit var title: EditText private lateinit var text: TextView private lateinit var image: ImageView private lateinit var save: FloatingActionButton //================================================================================ // Lifecycle methods //================================================================================ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = inflater.inflate(R.layout.fragment_card_detail, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewComponent.inject(this) toolbar = view.findViewById(R.id.fragment_card_detail_toolbar) title = view.findViewById(R.id.fragment_card_detail_title) text = view.findViewById(R.id.fragment_card_detail_text) image = view.findViewById(R.id.fragment_card_detail_image) save = view.findViewById(R.id.fragment_card_detail_save) toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back_24) toolbar.setNavigationOnClickListener { activity?.onBackPressed() } save.setOnClickListener { viewModel.save() } viewModel.card.onEach { showCard(it) }.launchIn(lifecycleScope) viewModel.saveResult .filterNotNull() .onEach { onSaveResult(it) viewModel.saveResult.value = null } .launchIn(lifecycleScope) } //================================================================================ // View methods //================================================================================ private fun showCard(code: ScannedCode) { // Set title title.setText(code.title) text.setText(code.text) toolbar.title = code.title // Set image scaleType according to barcode type val scaleType = when (code.format) { QR_CODE, AZTEC, DATA_MATRIX -> ImageView.ScaleType.FIT_CENTER else -> ImageView.ScaleType.FIT_XY } image.scaleType = scaleType // Load image try { image.setImageBitmap( encoder.encodeBitmap(code.text, code.format, 200, 200) ) } catch (e: WriterException) { e.printStackTrace() } title.addLifecycleTextWatcher { viewModel.title.value = it } } private fun onSaveResult(result: SaveResult) { when (result) { InvalidTitle -> showSnackbar(R.string.fragment_create_invalid_title) InvalidText -> showSnackbar(R.string.fragment_create_invalid_text) InvalidFormat -> showSnackbar(R.string.fragment_create_invalid_format) is SaveSuccess -> onCardSaved() } } private fun setSaveVisible(visible: Boolean) { save.visibility = if (visible) View.VISIBLE else View.GONE } private fun onCardSaved() { showSnackbar(R.string.fragment_card_detail_saved) activity?.onBackPressed() } }
apache-2.0
10d051270d75aefb47cc288e72e8f7ae
33.628571
86
0.656147
4.766962
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/actions/DeleteBookmarkTypeAction.kt
2
1292
// 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 com.intellij.ide.bookmark.actions import com.intellij.ide.bookmark.BookmarkBundle.messagePointer import com.intellij.ide.bookmark.BookmarkType import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction internal class DeleteBookmarkTypeAction : DumbAwareAction(messagePointer("mnemonic.chooser.mnemonic.delete.action.text")) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(event: AnActionEvent) { if (checkMultipleSelectionAndDisableAction(event)) return val manager = event.bookmarksManager val bookmark = event.contextBookmark val type = bookmark?.let { manager?.getType(it) } event.presentation.isEnabledAndVisible = type != null && type != BookmarkType.DEFAULT } override fun actionPerformed(event: AnActionEvent) { val manager = event.bookmarksManager ?: return val bookmark = event.contextBookmark ?: return manager.setType(bookmark, BookmarkType.DEFAULT) } init { isEnabledInModalContext = true } }
apache-2.0
9db1dfec7d295ca790f7ef37f6374589
40.677419
158
0.7887
4.875472
false
false
false
false
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/presentation/widget/adapter/UserListAdapter.kt
1
3236
/* * Copyright (c) 2017. Rei Matsushita * * 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 me.rei_m.hbfavmaterial.presentation.widget.adapter import android.content.Context import android.databinding.DataBindingUtil import android.databinding.ObservableArrayList import android.databinding.ObservableList import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import me.rei_m.hbfavmaterial.databinding.ListItemUserBinding import me.rei_m.hbfavmaterial.model.entity.Bookmark import me.rei_m.hbfavmaterial.model.entity.BookmarkUser import me.rei_m.hbfavmaterial.viewmodel.widget.adapter.UserListItemViewModel /** * ユーザー一覧を管理するAdaptor. */ class UserListAdapter(context: Context?, private val injector: Injector, private val bookmarkUserList: ObservableArrayList<BookmarkUser>) : ArrayAdapter<BookmarkUser>(context, 0, bookmarkUserList) { private val inflater: LayoutInflater = LayoutInflater.from(context) private val bookmarkUserListChangedCallback = object : ObservableList.OnListChangedCallback<ObservableArrayList<Bookmark>>() { override fun onItemRangeInserted(p0: ObservableArrayList<Bookmark>?, p1: Int, p2: Int) { notifyDataSetChanged() } override fun onItemRangeRemoved(p0: ObservableArrayList<Bookmark>?, p1: Int, p2: Int) { notifyDataSetChanged() } override fun onItemRangeMoved(p0: ObservableArrayList<Bookmark>?, p1: Int, p2: Int, p3: Int) { notifyDataSetChanged() } override fun onChanged(p0: ObservableArrayList<Bookmark>?) { notifyDataSetChanged() } override fun onItemRangeChanged(p0: ObservableArrayList<Bookmark>?, p1: Int, p2: Int) { notifyDataSetChanged() } } init { bookmarkUserList.addOnListChangedCallback(bookmarkUserListChangedCallback) } fun releaseCallback() { bookmarkUserList.removeOnListChangedCallback(bookmarkUserListChangedCallback) } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { val binding: ListItemUserBinding if (convertView == null) { binding = ListItemUserBinding.inflate(inflater, parent, false) binding.viewModel = injector.userListItemViewModel() } else { binding = DataBindingUtil.getBinding(convertView) } binding.viewModel!!.bookmarkUser.set(getItem(position)) binding.executePendingBindings() return binding.root } interface Injector { fun userListItemViewModel(): UserListItemViewModel } }
apache-2.0
e10f22d309d2be84c8cd4e307a36bb99
35.942529
147
0.719664
4.89939
false
false
false
false
ReplayMod/ReplayMod
src/main/kotlin/com/replaymod/core/gui/utils/focus.kt
1
3628
package com.replaymod.core.gui.utils import gg.essential.elementa.UIComponent import gg.essential.elementa.effects.Effect import gg.essential.universal.UKeyboard /** Marks components which can receive focus via [enableTabFocusChange]. */ private class CanReceiveFocus : Effect() /** Limits (tab) focus changes to stay within the children of the decorated component. */ class FocusTrap : Effect() /** * Enables tab-behavior for this component. Specifically this allows the user to switch away from this component to * instead focus the next component by pressing Tab (with Shift to go backwards) and in turn allows this component to * receive focus from another tab-enabled component. * * Use [FocusTrap] to limit tab switching to specific sub-tree of the component hierarchy. */ fun <T : UIComponent> T.enableTabFocusChange() = apply { enableEffect(CanReceiveFocus()) onKeyType { _, keyCode -> if (keyCode == UKeyboard.KEY_TAB) { val backwards = UKeyboard.isShiftKeyDown() val nextComponent = parent.findNextFocusableComponent(this, backwards) ?: return@onKeyType nextComponent.grabWindowFocus() } } } /** * Returns the next focusable component after the given [fromComponent] as returned by a depth-first search of the * entire component hierarchy (but without actually running the entire search, and wrapping around). * If this or a parent component has the [FocusTrap] effect, then the search will stay within the sub-tree with the * respective component at its root. * * When [backwards] is `true`, the entire search is performed in reverse, returning the previous focusable component. * * When [fromComponent] is given, then this will recursively search up the tree if the next element cannot be found in * this subtree. If [fromComponent] is `null` (searching a sibling sub-tree of the original sub-tree), then `null` is * return if the next element cannot be found in this subtree. * * If the search is unsuccessful (because there is no focusable component other than [fromComponent]), then `null` is * returned. */ private fun UIComponent.findNextFocusableComponent(fromComponent: UIComponent?, backwards: Boolean): UIComponent? { fun findNextInRange(range: IntProgression): UIComponent? { for (index in range) { val child = children[index] return if (child.effects.any { it is CanReceiveFocus }) { child } else { child.findNextFocusableComponent(null, backwards) ?: continue } } return null } if (fromComponent != null) { val fromIndex = children.indexOf(fromComponent) val higherRange = (fromIndex + 1)..children.lastIndex val lowerRange = 0 until fromIndex // first check siblings in the respective direction findNextInRange(if (backwards) lowerRange.reversed() else higherRange)?.let { return it } // then go one level up and check siblings there, recursively if (parent != this && effects.none { it is FocusTrap }) { parent.findNextFocusableComponent(this, backwards)?.let { return it } } // and finally, back on this level, check the other half of siblings findNextInRange(if (backwards) higherRange.reversed() else lowerRange)?.let { return it } } else { // check all children in the respective order findNextInRange(if (backwards) children.indices.reversed() else children.indices)?.let { return it } } // looped all the way round and still haven't found anything return null }
gpl-3.0
c0a52de39e3357ea0edcb0ed7ff0388c
43.790123
118
0.701764
4.598226
false
false
false
false
jwren/intellij-community
platform/util-ex/src/com/intellij/util/error.kt
3
1050
// 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.util import com.intellij.util.lang.CompoundRuntimeException import org.jetbrains.annotations.ApiStatus fun throwIfNotEmpty(errors: List<Throwable>) { val size = errors.size if (size == 1) { throw errors.first() } else if (size != 0) { throw CompoundRuntimeException(errors) } } @ApiStatus.Internal fun getErrorsAsString(errors: List<Throwable>, includeStackTrace: Boolean = true): CharSequence { val sb = StringBuilder() sb.append("${errors.size} errors:\n") for (i in errors.indices) { sb.append("[").append(i + 1).append("]: ------------------------------\n") val error = errors[i] val line = if (includeStackTrace) ExceptionUtil.getThrowableText(error) else error.message!! sb.append(line) if (!line.endsWith('\n')) { sb.append('\n') } } sb.append("-".repeat(5)) sb.append("------------------------------\n") return sb }
apache-2.0
1724c1403fe21da1b5b4fa6b1ae5fec3
30.848485
140
0.647619
3.846154
false
false
false
false
smmribeiro/intellij-community
java/idea-ui/src/com/intellij/codeInsight/daemon/impl/LibrarySourceNotificationProvider.kt
5
5432
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.daemon.impl import com.intellij.diff.DiffContentFactory import com.intellij.diff.DiffManager import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.ide.JavaUiBundle import com.intellij.ide.util.PsiNavigationSupport import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.source.PsiExtensibleClass import com.intellij.psi.util.PsiFormatUtil.* import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotificationProvider import com.intellij.ui.LightColors import com.intellij.util.diff.Diff import java.util.function.Function import javax.swing.JComponent class LibrarySourceNotificationProvider : EditorNotificationProvider { private companion object { private val LOG = logger<LibrarySourceNotificationProvider>() private val ANDROID_SDK_PATTERN = ".*/platforms/android-\\d+/android.jar!/.*".toRegex() private const val FIELD = SHOW_NAME or SHOW_TYPE or SHOW_FQ_CLASS_NAMES or SHOW_RAW_TYPE private const val METHOD = SHOW_NAME or SHOW_PARAMETERS or SHOW_RAW_TYPE private const val PARAMETER = SHOW_TYPE or SHOW_FQ_CLASS_NAMES or SHOW_RAW_TYPE private const val CLASS = SHOW_NAME or SHOW_FQ_CLASS_NAMES or SHOW_EXTENDS_IMPLEMENTS or SHOW_RAW_TYPE } override fun collectNotificationData( project: Project, file: VirtualFile, ): Function<in FileEditor, out JComponent?> { if (file.fileType is LanguageFileType && ProjectRootManager.getInstance(project).fileIndex.isInLibrarySource(file)) { val psiFile = PsiManager.getInstance(project).findFile(file) if (psiFile is PsiJavaFile) { val offender = psiFile.classes.find { differs(it) } if (offender != null) { val clsFile = offender.originalElement.containingFile?.virtualFile if (clsFile != null && !clsFile.path.matches(ANDROID_SDK_PATTERN)) { return Function { val panel = EditorNotificationPanel(LightColors.RED) panel.text = JavaUiBundle.message("library.source.mismatch", offender.name) panel.createActionLabel(JavaUiBundle.message("library.source.open.class")) { if (!project.isDisposed && clsFile.isValid) { PsiNavigationSupport.getInstance().createNavigatable(project, clsFile, -1).navigate(true) } } panel.createActionLabel(JavaUiBundle.message("library.source.show.diff")) { if (!project.isDisposed && clsFile.isValid) { val cf = DiffContentFactory.getInstance() val request = SimpleDiffRequest(null, cf.create(project, clsFile), cf.create(project, file), clsFile.path, file.path) DiffManager.getInstance().showDiff(project, request) } } logMembers(offender) return@Function panel } } } } } return EditorNotificationProvider.CONST_NULL } private fun differs(src: PsiClass): Boolean { val cls = src.originalElement return cls !== src && cls is PsiClass && (differs(fields(src), fields(cls), ::format) || differs(methods(src), methods(cls), ::format) || differs(inners(src), inners(cls), ::format)) } private fun <T : PsiMember> differs(srcMembers: List<T>, clsMembers: List<T>, format: (T) -> String) = srcMembers.size != clsMembers.size || srcMembers.map(format).sorted() != clsMembers.map(format).sorted() private fun fields(c: PsiClass) = if (c is PsiExtensibleClass) c.ownFields else c.fields.asList() private fun methods(c: PsiClass) = (if (c is PsiExtensibleClass) c.ownMethods else c.methods.asList()).filterNot(::ignoreMethod) private fun ignoreMethod(m: PsiMethod): Boolean { if (m.isConstructor) { return m.parameterList.parametersCount == 0 // default constructor } else { return m.name.contains("$\$bridge") // org.jboss.bridger.Bridger adds ACC_BRIDGE | ACC_SYNTHETIC to such methods } } private fun inners(c: PsiClass) = if (c is PsiExtensibleClass) c.ownInnerClasses else c.innerClasses.asList() private fun format(f: PsiField) = formatVariable(f, FIELD, PsiSubstitutor.EMPTY) private fun format(m: PsiMethod) = formatMethod(m, PsiSubstitutor.EMPTY, METHOD, PARAMETER) private fun format(c: PsiClass) = formatClass(c, CLASS).removeSuffix(" extends java.lang.Object") private fun logMembers(offender: PsiClass) { if (!LOG.isTraceEnabled) { return } val cls = offender.originalElement as? PsiClass ?: return val sourceMembers = formatMembers(offender) val clsMembers = formatMembers(cls) val diff = Diff.linesDiff(sourceMembers.toTypedArray(), clsMembers.toTypedArray()) ?: return LOG.trace("Class: ${cls.qualifiedName}\n$diff") } private fun formatMembers(c: PsiClass): List<String> { return fields(c).map(::format).sorted() + methods(c).map(::format).sorted() + inners(c).map(::format).sorted() } }
apache-2.0
ead64046a929ddd2392256b03d4ca361
43.162602
135
0.701031
4.257053
false
false
false
false
smmribeiro/intellij-community
build/tasks/src/org/jetbrains/intellij/build/tasks/reorderJars.kt
1
7648
// 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. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment", "BlockingMethodInNonBlockingContext") package org.jetbrains.intellij.build.tasks import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.context.Context import it.unimi.dsi.fastutil.longs.LongSet import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import org.jetbrains.intellij.build.io.* import java.io.InputStream import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.util.* @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val excludedLibJars = java.util.Set.of("testFramework.core.jar", "testFramework.jar", "testFramework-java.jar") private fun getClassLoadingLog(): InputStream { val osName = System.getProperty("os.name") val classifier = when { osName.startsWith("windows", ignoreCase = true) -> "windows" osName.startsWith("mac", ignoreCase = true) -> "mac" else -> "linux" } return PackageIndexBuilder::class.java.classLoader.getResourceAsStream("$classifier/class-report.txt")!! } private val sourceToNames: Map<String, MutableList<String>> by lazy { val sourceToNames = LinkedHashMap<String, MutableList<String>>() getClassLoadingLog().bufferedReader().forEachLine { val data = it.split(':', limit = 2) val sourcePath = data[1] // main jar is scrambled - doesn't make sense to reorder it if (sourcePath != "lib/idea.jar") { sourceToNames.computeIfAbsent(sourcePath) { mutableListOf() }.add(data[0]) } } sourceToNames } internal fun reorderJar(relativePath: String, file: Path, traceContext: Context) { val orderedNames = sourceToNames.get(relativePath) ?: return tracer.spanBuilder("reorder jar") .setParent(traceContext) .setAttribute("relativePath", relativePath) .setAttribute("file", file.toString()) .startSpan() .use { reorderJar(jarFile = file, orderedNames = orderedNames, resultJarFile = file) } } fun generateClasspath(homeDir: Path, mainJarName: String, antTargetFile: Path?): List<String> { val libDir = homeDir.resolve("lib") val appFile = libDir.resolve("app.jar") tracer.spanBuilder("generate app.jar") .setAttribute("dir", homeDir.toString()) .setAttribute("mainJarName", mainJarName) .startSpan() .use { transformFile(appFile) { target -> writeNewZip(target) { zipCreator -> val packageIndexBuilder = PackageIndexBuilder() copyZipRaw(appFile, packageIndexBuilder, zipCreator) val mainJar = libDir.resolve(mainJarName) if (Files.exists(mainJar)) { // no such file in community (no closed sources) copyZipRaw(mainJar, packageIndexBuilder, zipCreator) Files.delete(mainJar) } // packing to product.jar maybe disabled val productJar = libDir.resolve("product.jar") if (Files.exists(productJar)) { copyZipRaw(productJar, packageIndexBuilder, zipCreator) Files.delete(productJar) } packageIndexBuilder.writePackageIndex(zipCreator) } } } reorderJar("lib/app.jar", appFile, Context.current()) tracer.spanBuilder("generate classpath") .setAttribute("dir", homeDir.toString()) .startSpan() .use { span -> val osName = System.getProperty("os.name") val classifier = when { osName.startsWith("windows", ignoreCase = true) -> "windows" osName.startsWith("mac", ignoreCase = true) -> "mac" else -> "linux" } val sourceToNames = readClassLoadingLog( classLoadingLog = PackageIndexBuilder::class.java.classLoader.getResourceAsStream("$classifier/class-report.txt")!!, rootDir = homeDir, mainJarName = mainJarName ) val files = computeAppClassPath(sourceToNames, libDir) if (antTargetFile != null) { files.add(antTargetFile) } val result = files.map { libDir.relativize(it).toString() } span.setAttribute(AttributeKey.stringArrayKey("result"), result) return result } } private fun computeAppClassPath(sourceToNames: Map<Path, List<String>>, libDir: Path): LinkedHashSet<Path> { // sorted to ensure stable performance results val existing = TreeSet<Path>() addJarsFromDir(libDir) { paths -> paths.filterTo(existing) { !excludedLibJars.contains(it.fileName.toString()) } } val result = LinkedHashSet<Path>() // add first - should be listed first sourceToNames.keys.filterTo(result) { it.parent == libDir && existing.contains(it) } result.addAll(existing) return result } private inline fun addJarsFromDir(dir: Path, consumer: (Sequence<Path>) -> Unit) { Files.newDirectoryStream(dir).use { stream -> consumer(stream.asSequence().filter { it.toString().endsWith(".jar") }) } } internal fun readClassLoadingLog(classLoadingLog: InputStream, rootDir: Path, mainJarName: String): Map<Path, List<String>> { val sourceToNames = LinkedHashMap<Path, MutableList<String>>() classLoadingLog.bufferedReader().forEachLine { val data = it.split(':', limit = 2) var sourcePath = data[1] if (sourcePath == "lib/idea.jar") { sourcePath = "lib/$mainJarName" } sourceToNames.computeIfAbsent(rootDir.resolve(sourcePath)) { mutableListOf() }.add(data[0]) } return sourceToNames } data class PackageIndexEntry(val path: Path, val classPackageIndex: LongSet, val resourcePackageIndex: LongSet) private class EntryData(@JvmField val name: String, @JvmField val entry: ZipEntry) fun reorderJar(jarFile: Path, orderedNames: List<String>, resultJarFile: Path): PackageIndexEntry { val orderedNameToIndex = Object2IntOpenHashMap<String>(orderedNames.size) orderedNameToIndex.defaultReturnValue(-1) for ((index, orderedName) in orderedNames.withIndex()) { orderedNameToIndex.put(orderedName, index) } val tempJarFile = resultJarFile.resolveSibling("${resultJarFile.fileName}_reorder") val packageIndexBuilder = PackageIndexBuilder() mapFileAndUse(jarFile) { sourceBuffer, fileSize -> val entries = mutableListOf<EntryData>() readZipEntries(sourceBuffer, fileSize) { name, entry -> entries.add(EntryData(name, entry)) } // ignore existing package index on reorder - a new one will be computed even if it is the same, do not optimize for simplicity entries.sortWith(Comparator { o1, o2 -> val o2p = o2.name if ("META-INF/plugin.xml" == o2p) { return@Comparator Int.MAX_VALUE } val o1p = o1.name if ("META-INF/plugin.xml" == o1p) { -Int.MAX_VALUE } else { val i1 = orderedNameToIndex.getInt(o1p) if (i1 == -1) { if (orderedNameToIndex.containsKey(o2p)) 1 else 0 } else { val i2 = orderedNameToIndex.getInt(o2p) if (i2 == -1) -1 else (i1 - i2) } } }) writeNewZip(tempJarFile) { zipCreator -> for (item in entries) { packageIndexBuilder.addFile(item.name) zipCreator.uncompressedData(item.name, item.entry.getByteBuffer()) } packageIndexBuilder.writePackageIndex(zipCreator) } } try { Files.move(tempJarFile, resultJarFile, StandardCopyOption.REPLACE_EXISTING) } catch (e: Exception) { throw e } finally { Files.deleteIfExists(tempJarFile) } return PackageIndexEntry(path = resultJarFile, packageIndexBuilder.classPackageHashSet, packageIndexBuilder.resourcePackageHashSet) }
apache-2.0
1af2d72d415e3e179d6cbf0edf753a2c
35.251185
158
0.69443
4.174672
false
false
false
false
smmribeiro/intellij-community
platform/script-debugger/protocol/protocol-reader/src/TypeWriter.kt
13
8700
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.protocolReader import org.jetbrains.jsonProtocol.JsonObjectBased import java.lang.reflect.Method import java.util.* internal const val FIELD_PREFIX = '_' internal const val NAME_VAR_NAME = "_n" private fun assignField(out: TextOutput, fieldName: String) = out.append(FIELD_PREFIX).append(fieldName).append(" = ") internal class TypeRef<T>(val typeClass: Class<T>) { var type: TypeWriter<T>? = null } internal class TypeWriter<T>(val typeClass: Class<T>, jsonSuperClass: TypeRef<*>?, private val volatileFields: List<VolatileFieldBinding>, private val methodHandlerMap: LinkedHashMap<Method, MethodHandler>, /** Loaders that should read values and save them in field array on parse time. */ private val fieldLoaders: List<FieldLoader>, private val hasLazyFields: Boolean) { /** Subtype aspects of the type or null */ val subtypeAspect = if (jsonSuperClass == null) null else ExistingSubtypeAspect(jsonSuperClass) fun writeInstantiateCode(scope: ClassScope, out: TextOutput) { writeInstantiateCode(scope, false, out) } fun writeInstantiateCode(scope: ClassScope, deferredReading: Boolean, out: TextOutput) { val className = scope.getTypeImplReference(this) if (deferredReading || subtypeAspect == null) { out.append(className) } else { subtypeAspect.writeInstantiateCode(className, out) } } fun write(fileScope: FileScope) { val out = fileScope.output val valueImplClassName = fileScope.getTypeImplShortName(this) out.append("private class ").append(valueImplClassName).append('(').append(JSON_READER_PARAMETER_DEF).comma().append("preReadName: String?") subtypeAspect?.writeSuperFieldJava(out) out.append(") : ").append(typeClass.canonicalName).openBlock() if (hasLazyFields || JsonObjectBased::class.java.isAssignableFrom(typeClass)) { out.append("private var ").append(PENDING_INPUT_READER_NAME).append(": ").append(JSON_READER_CLASS_NAME).append("? = reader.subReader()!!").newLine() } val classScope = fileScope.newClassScope() for (field in volatileFields) { field.writeFieldDeclaration(classScope, out) out.newLine() } for (loader in fieldLoaders) { if (loader.asImpl) { out.append("override") } else { out.append("private") } out.append(" var ").appendName(loader) fun addType() { out.append(": ") loader.valueReader.appendFinishedValueTypeName(out) out.append("? = null") } if (loader.valueReader is PrimitiveValueReader) { val defaultValue = loader.defaultValue ?: loader.valueReader.defaultValue if (defaultValue != null) { out.append(" = ").append(defaultValue) } else { addType() } } else { addType() } out.newLine() } if (fieldLoaders.isNotEmpty()) { out.newLine() } writeConstructorMethod(classScope, out) out.newLine() subtypeAspect?.writeParseMethod(classScope, out) for ((key, value) in methodHandlerMap.entries) { out.newLine() value.writeMethodImplementationJava(classScope, key, out) out.newLine() } writeBaseMethods(out) subtypeAspect?.writeGetSuperMethodJava(out) writeEqualsMethod(valueImplClassName, out) out.indentOut().append('}') } /** * Generates Java implementation of standard methods of JSON type class (if needed): * {@link org.jetbrains.jsonProtocol.JsonObjectBased#getDeferredReader()} */ private fun writeBaseMethods(out: TextOutput) { val method: Method try { method = typeClass.getMethod("getDeferredReader") } catch (ignored: NoSuchMethodException) { // Method not found, skip. return } out.newLine() writeMethodDeclarationJava(out, method) out.append(" = ").append(PENDING_INPUT_READER_NAME) } private fun writeEqualsMethod(valueImplClassName: String, out: TextOutput) { if (fieldLoaders.isEmpty()) { return } out.newLine().append("override fun equals(other: Any?): Boolean = ") out.append("other is ").append(valueImplClassName) // at first we should compare primitive values, then enums, then string, then objects fun fieldWeight(reader: ValueReader): Int { var w = 10 if (reader is PrimitiveValueReader) { w-- if (reader.className != "String") { w-- } } else if (reader is EnumReader) { // -1 as primitive, -1 as not a string w -= 2 } return w } for (loader in fieldLoaders.sortedWith(Comparator<FieldLoader> { f1, f2 -> fieldWeight((f1.valueReader)) - fieldWeight((f2.valueReader))})) { out.append(" && ") out.appendName(loader).append(" == ").append("other.").appendName(loader) } out.newLine() } private fun writeConstructorMethod(classScope: ClassScope, out: TextOutput) { out.append("init").block { if (fieldLoaders.isEmpty()) { out.append(READER_NAME).append(".skipValue()") } else { out.append("var ").append(NAME_VAR_NAME).append(" = preReadName") out.newLine().append("if (").append(NAME_VAR_NAME).append(" == null && reader.hasNext() && reader.beginObject().hasNext())").block { out.append(NAME_VAR_NAME).append(" = reader.nextName()") } out.newLine() writeReadFields(out, classScope) // we don't read all data if we have lazy fields, so, we should not check end of stream //if (!hasLazyFields) { out.newLine().newLine().append(READER_NAME).append(".endObject()") //} } } } private fun writeReadFields(out: TextOutput, classScope: ClassScope) { val stopIfAllFieldsWereRead = hasLazyFields val hasOnlyOneFieldLoader = fieldLoaders.size == 1 val isTracedStop = stopIfAllFieldsWereRead && !hasOnlyOneFieldLoader if (isTracedStop) { out.newLine().append("var i = 0") } out.newLine().append("loop@ while (").append(NAME_VAR_NAME).append(" != null)").block { (out + "when (" + NAME_VAR_NAME + ")").block { var isFirst = true for (fieldLoader in fieldLoaders) { if (fieldLoader.skipRead) { continue } if (!isFirst) { out.newLine() } out.append('"') if (fieldLoader.jsonName.first() == '$') { out.append('\\') } out.append(fieldLoader.jsonName).append('"').append(" -> ") if (stopIfAllFieldsWereRead && !isTracedStop) { out.openBlock() } val primitiveValueName = if (fieldLoader.valueReader is ObjectValueReader) fieldLoader.valueReader.primitiveValueName else null if (primitiveValueName != null) { out.append("if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT)").openBlock() } out.appendName(fieldLoader).append(" = ") try { fieldLoader.valueReader.writeReadCode(classScope, false, out) } catch (e: UnsupportedOperationException) { out.append("throw UnsupportedOperationException()").newLine() } if (primitiveValueName != null) { out.closeBlock().newLine().append("else").block { assignField(out, "${primitiveValueName}Type") out.append("reader.peek()").newLine() assignField(out, primitiveValueName) out + "reader.nextString(true)" } } if (stopIfAllFieldsWereRead && !isTracedStop) { out.newLine().append(READER_NAME).append(".skipValues()").newLine().append("break@loop").closeBlock() } if (isFirst) { isFirst = false } } out.newLine().append("else ->") if (isTracedStop) { out.block { out.append("reader.skipValue()") out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()" out.newLine() + "continue@loop" } } else { out.space().append("reader.skipValue()") } } out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()" if (isTracedStop) { out.newLine().newLine().append("if (i++ == ").append(fieldLoaders.size - 1).append(")").block { (out + READER_NAME + ".skipValues()").newLine() + "break" } } } } }
apache-2.0
09db0b880702f2070ee57122e2a496b0
31.958333
206
0.615747
4.427481
false
false
false
false
AlexKrupa/kotlin-koans
src/i_introduction/_4_Lambdas/Lambdas.kt
1
685
package i_introduction._4_Lambdas import util.TODO import util.doc4 fun example() { val sum = { x: Int, y: Int -> x + y } val square: (Int) -> Int = { x -> x * x } sum(1, square(2)) == 5 } fun todoTask4(collection: Collection<Int>): Nothing = TODO( """ Task 4. Rewrite 'JavaCode4.task4()' in Kotlin using lambdas. You can find the appropriate function tail call on 'head' through IntelliJ IDEA's code completion feature. (Don't use the class 'Iterables'). """, documentation = doc4(), references = { JavaCode4().task4(collection) }) fun task4(collection: Collection<Int>): Boolean = collection.any { it % 42 == 0 }
mit
e5ad501bf119dcd2c89bbb53d997f38a
23.464286
114
0.616058
3.682796
false
false
false
false
acristescu/GreenfieldTemplate
app/src/offline/java/io/zenandroid/greenfield/service/MockFlickrService.kt
1
1537
package io.zenandroid.greenfield.service import androidx.annotation.VisibleForTesting import com.google.gson.FieldNamingPolicy import com.google.gson.GsonBuilder import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import io.zenandroid.greenfield.model.ImageListResponse import io.zenandroid.greenfield.util.EspressoIdlingResource import java.io.InputStreamReader import java.util.concurrent.TimeUnit import javax.inject.Inject /** * created by acristescu */ class MockFlickrService @Inject constructor() : FlickrService { private var mockResponse = ImageListResponse() private var delay = 0 init { val gson = GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create() mockResponse = gson.fromJson( InputStreamReader(javaClass.classLoader!!.getResourceAsStream("assets/mock_data.json")), ImageListResponse::class.java ) } override fun getImageList(tags: String?): Single<ImageListResponse> { EspressoIdlingResource.increment() return Single.just(mockResponse) .delay(delay.toLong(), TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .doFinally { EspressoIdlingResource.decrement() } } @VisibleForTesting fun setDelay(delay: Int) { this.delay = delay } }
apache-2.0
8c5ee26931d02391578b28a3441dcac5
31.702128
104
0.709174
5.055921
false
false
false
false
testIT-LivingDoc/livingdoc2
livingdoc-tests/src/test/kotlin/org/livingdoc/example/DividerDocumentMdParallelFailFast.kt
2
2084
package org.livingdoc.example import org.assertj.core.api.Assertions.assertThat import org.livingdoc.api.Before import org.livingdoc.api.disabled.Disabled import org.livingdoc.api.documents.ExecutableDocument import org.livingdoc.api.documents.FailFast import org.livingdoc.api.fixtures.decisiontables.BeforeRow import org.livingdoc.api.fixtures.decisiontables.Check import org.livingdoc.api.fixtures.decisiontables.DecisionTableFixture import org.livingdoc.api.fixtures.decisiontables.Input import org.livingdoc.api.fixtures.scenarios.Binding import org.livingdoc.api.fixtures.scenarios.ScenarioFixture import org.livingdoc.api.fixtures.scenarios.Step import org.livingdoc.api.tagging.Tag /** * [ExecutableDocuments][ExecutableDocument] can also be specified in Markdown * * @see ExecutableDocument */ @Tag("markdown") @Disabled @FailFast(onExceptionTypes = [IllegalArgumentException::class]) @ExecutableDocument("local://DividerFailFast.md") class DividerDocumentMdParallelFailFast { @DecisionTableFixture(parallel = true) class DividerDecisionTableFixture { private lateinit var sut: Divider @Input("a") private var valueA: Float = 0f private var valueB: Float = 0f @BeforeRow fun beforeRow() { sut = Divider() } @Input("b") fun setValueB(valueB: Float) { this.valueB = valueB } @Check("a / b = ?") fun checkDivide(expectedValue: Float) { val result = sut.divide(valueA, valueB) assertThat(result).isEqualTo(expectedValue) } } @ScenarioFixture class DividerScenarioFixture { private lateinit var sut: Divider @Before fun before() { sut = Divider() } @Step("dividing {a} by {b} equals {c}") fun divide( @Binding("a") a: Float, @Binding("b") b: Float, @Binding("c") c: Float ) { val result = sut.divide(a, b) assertThat(result).isEqualTo(c) } } }
apache-2.0
bb6692e9ca486059b6431e53f8756518
27.162162
78
0.661708
4.40592
false
false
false
false
MediaArea/MediaInfo
Source/GUI/Android/app/src/main/java/net/mediaarea/mediainfo/ReportDetailFragment.kt
1
13265
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ package net.mediaarea.mediainfo import java.io.OutputStream import java.io.File import androidx.fragment.app.Fragment import androidx.documentfile.provider.DocumentFile import androidx.preference.PreferenceManager.getDefaultSharedPreferences import android.os.Build import android.os.Bundle import android.os.Environment import android.app.Activity import android.content.SharedPreferences import android.content.Context import android.content.Intent import android.text.TextUtils import android.view.* import android.widget.Toast import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import com.github.angads25.filepicker.model.DialogConfigs import com.github.angads25.filepicker.model.DialogProperties import com.github.angads25.filepicker.view.FilePickerDialog import kotlinx.android.synthetic.main.report_detail.view.* class ReportDetailFragment : Fragment() { companion object { const val SAVE_FILE_REQUEST_CODE: Int = 1 } private val disposable: CompositeDisposable = CompositeDisposable() private lateinit var activityListener: ReportActivityListener private var sharedPreferences: SharedPreferences? = null private var view: String = "HTML" var id: Int? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { if (it.containsKey(Core.ARG_REPORT_ID)) { val newId: Int = it.getInt(Core.ARG_REPORT_ID) if (newId != -1) id = newId } } setHasOptionsMenu(true) } override fun onAttach(context: Context) { super.onAttach(context) try { activityListener = activity as ReportActivityListener } catch (_: Throwable) { throw ClassCastException(activity.toString() + " must implement ReportActivityListener") } sharedPreferences = getDefaultSharedPreferences(context) val oldSharedPreferences = activity?.getSharedPreferences(getString(R.string.preferences_key), Context.MODE_PRIVATE) val key = getString(R.string.preferences_view_key) if (sharedPreferences?.contains(key) == false && oldSharedPreferences?.contains(key) == true) { sharedPreferences?.edit() ?.putString(key, oldSharedPreferences.getString(key, "HTML")) ?.apply() } sharedPreferences?.getString(getString(R.string.preferences_view_key), "HTML").let { if (it != null) view = it } } override fun onStop() { super.onStop() // clear all the subscription disposable.clear() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.report_detail, container, false) // Show the report id?.let { id -> disposable.add(activityListener.getReportViewModel().getReport(id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSuccess { val report: String = Core.convertReport(it.report, view) var content = "" if (view != "HTML") { content += "<html><body><pre>" content += TextUtils.htmlEncode(report.replace("\t", " ")) content += "</pre></body></html>" } else { content+=report } val background=resources.getString(0+R.color.background).removeRange(1, 3) val foreground=resources.getString(0+R.color.foreground).removeRange(1, 3) content = content.replace("<body>", "<body style=\"background-color: ${background}; color: ${foreground};\">") rootView.report_detail.loadDataWithBaseURL(null, content, "text/html", "utf-8", null) }.subscribe()) } return rootView } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_detail, menu) menu.findItem(R.id.action_export_report).let { it.setOnMenuItemClickListener { if (Build.VERSION.SDK_INT >= 21) { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) startActivityForResult(intent, SAVE_FILE_REQUEST_CODE) } else { if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) { val properties = DialogProperties() properties.selection_mode = DialogConfigs.SINGLE_MODE properties.selection_type = DialogConfigs.DIR_SELECT properties.root = File(DialogConfigs.DEFAULT_DIR) properties.error_dir = File(DialogConfigs.DEFAULT_DIR) properties.offset = File(DialogConfigs.DEFAULT_DIR) properties.extensions = null val dialog = FilePickerDialog(context, properties) dialog.setTitle(R.string.export_title) dialog.setDialogSelectionListener { select: Array<String> -> if (select.isEmpty()) onError() id.let {id -> if (id == null) { onError() } else { disposable .add(activityListener.getReportViewModel().getReport(id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { report: Report -> if (report.report.isEmpty()) { onError() } else { val directory = File(select[0]) if (!directory.canWrite()) { onError() } else { saveReport(DocumentFile.fromFile(directory), report) } } }) } } } dialog.show() } else { onError() } } true } } val viewMenu: SubMenu = menu.findItem(R.id.action_change_view).subMenu for (current: Core.ReportView in Core.views) { val index: Int = Core.views.indexOf(current) var desc = current.desc if (desc == "Text") { desc = resources.getString(R.string.text_output_desc) } viewMenu.add(R.id.menu_views_group, Menu.NONE, index, desc).setOnMenuItemClickListener { if (view != current.name) { view = current.name // Save new default sharedPreferences ?.edit() ?.putString(getString(R.string.preferences_view_key), view) ?.apply() // Reset view parentFragmentManager.fragments.forEach { val fragment = it as? ReportDetailFragment if (fragment!=null) { fragment.view = current.name if (fragment.isAdded) { parentFragmentManager .beginTransaction() .detach(it) .commit() parentFragmentManager .beginTransaction() .attach(it) .commit() } } } } true }.setCheckable(true).isChecked = (current.name == view) viewMenu.setGroupCheckable(R.id.menu_views_group, true, true) } } override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { if (resultCode == Activity.RESULT_OK) { when (requestCode) { SAVE_FILE_REQUEST_CODE -> { if (resultData == null || resultData.data == null) { onError() return } id.let { if (it == null) { onError() return } disposable .add(activityListener.getReportViewModel().getReport(it) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { report: Report -> if (report.report.isEmpty()) { onError() } else { val currentContext: Context? = context if (currentContext == null) { onError() } else { val data = resultData.data if (data == null) { onError() } else { val directory = DocumentFile.fromTreeUri(currentContext, data) if (directory == null) { onError() } else { if (!directory.canWrite()) { onError() } else { saveReport(directory, report) } } } } } }) } } } } } private fun saveReport(directory: DocumentFile, report: Report) { val reportText: String = Core.convertReport(report.report, view, true) val filename: String = String.format("%s.%s", report.filename, view) val mime: String = Core.views.find { it.name == view }?.mime ?: "text/plain" try { val document = directory.createFile(mime, filename) if (document == null) { onError() } else { val ostream: OutputStream? = context?.contentResolver?.openOutputStream(document.uri) if (ostream == null) { onError() } else { ostream.write(reportText.toByteArray()) ostream.flush() ostream.close() } } } catch (e: Exception) { onError() } } private fun onError() { val applicationContext = activity?.applicationContext if (applicationContext!=null) { val toast = Toast.makeText(applicationContext, R.string.error_write_text, Toast.LENGTH_LONG) toast.show() } } }
bsd-2-clause
3efc3d1a174239fbabe3155a1a1cbf3f
41.111111
134
0.44101
6.301663
false
false
false
false
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/api/http/TachiWebRoute.kt
1
5878
/* * Copyright 2016 Andy Bao * * 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 xyz.nulldev.ts.api.http import com.jayway.jsonpath.Configuration import com.jayway.jsonpath.JsonPath import com.jayway.jsonpath.Option import org.json.JSONObject import org.slf4j.LoggerFactory import spark.Request import spark.Response import spark.Route import xyz.nulldev.ts.api.http.auth.SessionManager import xyz.nulldev.ts.api.v2.http.jvcompat.JavalinShim import xyz.nulldev.ts.api.java.TachiyomiAPI import xyz.nulldev.ts.api.java.model.ServerAPIInterface import java.util.* /** * Project: TachiServer * Author: nulldev * Creation Date: 30/09/16 */ abstract class TachiWebRoute( val requiresAuth: Boolean = true ) : Route { // Warn if route does not use Javalin yet init { if(this !is JavalinShim) logger.warn("${this::class.simpleName} is a v1 API!") } protected val api: ServerAPIInterface = TachiyomiAPI @Throws(Exception::class) override fun handle(request: Request, response: Response): Any? { try { response.header("Access-Control-Allow-Origin", "*") response.header("Access-Control-Allow-Credentials", "true") var session: String? = request.cookie("session") if (session.isNullOrBlank()) { //Try session header if session is not provided in cookie session = request.headers(SESSION_HEADER) if(session.isNullOrBlank()) { session = sessionManager.newSession() response.removeCookie("session") response.cookie("session", session) } } request.attribute("session", session) //Auth all sessions if auth not enabled if (!SessionManager.authEnabled()) { sessionManager.authenticateSession(session!!) } if (!sessionManager.isAuthenticated(session!!) && requiresAuth) { //Not authenticated! return error("Not authenticated!") } else { val res = try { handleReq(request, response) } catch(t: Throwable) { val uuid = UUID.randomUUID() logger.error("Route handler failure (error ID: $uuid)!", t) return error("Unknown API handler error!", uuid) } // Filter response val jsonWhitelist = (request.queryParamsValues("jw") ?: emptyArray()).map { it.trim() }.filter { it.isNotBlank() }.map { JsonPath.compile(it) } val jsonBlacklist = (request.queryParamsValues("jb") ?: emptyArray()).map { it.trim() }.filter { it.isNotBlank() }.map { JsonPath.compile(it) } return if(jsonWhitelist.isNotEmpty() || jsonBlacklist.isNotEmpty()) { val parsed = try { JsonPath.parse(res.toString()) } catch(e: Exception) { logger.warn("Json path filtering failed on route: ${this::class.qualifiedName}", e) return res } // Handle blacklist for(path in jsonBlacklist) try { parsed.delete(path) } catch(t: Throwable) {} // Handle whitelist if(jsonWhitelist.isNotEmpty()) { val pathObtainer = JsonPath.using(Configuration.builder() .options(Option.AS_PATH_LIST, Option.ALWAYS_RETURN_LIST) .build()).parse(parsed.jsonString()) val valid = jsonWhitelist.flatMap { try { pathObtainer.read<List<String>>(it) } catch(t: Throwable) { null } ?: emptyList() } pathObtainer.read<List<String>>("$..*").forEach { path -> if(path !in valid && !valid.any { it.startsWith(path) }) try {parsed.delete(path)} catch(t: Throwable) {} } } parsed.jsonString() } else res } } catch (e: Exception) { val uuid = UUID.randomUUID() logger.error("Exception handling route (error ID: $uuid)!", e) return error("Unknown internal server error!", uuid) } } abstract fun handleReq(request: Request, response: Response): Any? companion object { const val SESSION_HEADER = "TW-Session" private val logger = LoggerFactory.getLogger(TachiWebRoute::class.java) val sessionManager = SessionManager() fun error(message: String, uuid: UUID? = null): JSONObject = success(false).put("error", message).apply { if(uuid != null) put("uuid", uuid.toString()) } @JvmOverloads fun success(success: Boolean = true): JSONObject = JSONObject().put("success", success) } }
apache-2.0
c25c50d93fd5c9f6265ac19657c6ebcb
36.685897
107
0.543892
4.964527
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/libjamiclient/src/main/kotlin/net/jami/model/Call.kt
1
11410
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Adrien Béraud <[email protected]> * Rayan Osseiran <[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 net.jami.model import ezvcard.Ezvcard import ezvcard.VCard import net.jami.call.CallPresenter import net.jami.utils.Log import net.jami.utils.ProfileChunk import net.jami.utils.StringUtils import net.jami.utils.VCardUtils import java.util.* class Call : Interaction { override val daemonIdString: String? private var isPeerHolding = false var isAudioMuted = false var isVideoMuted = false private val isRecording = false var callStatus = CallStatus.NONE private set var timestampEnd: Long = 0 set(timestampEnd) { field = timestampEnd if (timestampEnd != 0L && !isMissed) duration = timestampEnd - timestamp } var duration: Long? = null get() { if (field == null) { val element = toJson(mExtraFlag)[KEY_DURATION] if (element != null) { field = element.asLong } } return if (field == null) 0 else field } set(value) { if (value == duration) return field = value if (duration != null && duration != 0L) { val jsonObject = extraFlag jsonObject.addProperty(KEY_DURATION, value) mExtraFlag = fromJson(jsonObject) isMissed = false } } var isMissed = true private set var audioCodec: String? = null private set var videoCodec: String? = null private set var contactNumber: String? = null private set var confId: String? = null var mediaList: List<Media>? = null private var mProfileChunk: ProfileChunk? = null constructor( daemonId: String?, author: String?, account: String?, conversation: ConversationHistory?, contact: Contact?, direction: Direction, mediaList: List<Media>, ) { daemonIdString = daemonId try { this.daemonId = daemonId?.toLong() } catch (e: Exception) { Log.e(TAG, "Can't parse CallId $daemonId") } this.author = if (direction == Direction.INCOMING) author else null this.account = account this.conversation = conversation isIncoming = direction == Direction.INCOMING timestamp = System.currentTimeMillis() mType = InteractionType.CALL.toString() this.contact = contact mIsRead = 1 this.mediaList = mediaList } constructor(interaction: Interaction) { id = interaction.id author = interaction.author conversation = interaction.conversation isIncoming = author != null timestamp = interaction.timestamp mType = InteractionType.CALL.toString() mStatus = interaction.status.toString() daemonId = interaction.daemonId daemonIdString = super.daemonIdString mIsRead = if (interaction.isRead) 1 else 0 account = interaction.account mExtraFlag = fromJson(interaction.extraFlag) isMissed = duration == 0L mIsRead = 1 contact = interaction.contact } constructor(daemonId: String?, account: String?, contactNumber: String?, direction: Direction, timestamp: Long) { daemonIdString = daemonId try { this.daemonId = daemonId?.toLong() } catch (e: Exception) { Log.e(TAG, "Can't parse CallId $daemonId") } isIncoming = direction == Direction.INCOMING this.account = account author = if (direction == Direction.INCOMING) contactNumber else null this.contactNumber = contactNumber this.timestamp = timestamp mType = InteractionType.CALL.toString() mIsRead = 1 } constructor(daemonId: String?, call_details: Map<String, String>) : this( daemonId, call_details[KEY_ACCOUNT_ID], call_details[KEY_PEER_NUMBER], Direction.fromInt(call_details[KEY_CALL_TYPE]!!.toInt()), System.currentTimeMillis()) { setCallState(CallStatus.fromString(call_details[KEY_CALL_STATE]!!)) setDetails(call_details) } fun setDetails(details: Map<String, String>) { isPeerHolding = details[KEY_PEER_HOLDING].toBoolean() isAudioMuted = details[KEY_AUDIO_MUTED].toBoolean() isVideoMuted = details[KEY_VIDEO_MUTED].toBoolean() audioCodec = details[KEY_AUDIO_CODEC] videoCodec = details[KEY_VIDEO_CODEC] val confId = details[KEY_CONF_ID] this.confId = if (StringUtils.isEmpty(confId)) null else confId } val isConferenceParticipant: Boolean get() = confId != null val durationString: String get() { val mDuration = duration!! / 1000 if (mDuration < 60) { return String.format(Locale.getDefault(), "%02d secs", mDuration) } return if (mDuration < 3600) String.format(Locale.getDefault(), "%02d mins %02d secs", mDuration % 3600 / 60, mDuration % 60) else String.format(Locale.getDefault(), "%d h %02d mins %02d secs", mDuration / 3600, mDuration % 3600 / 60, mDuration % 60) } fun setCallState(callStatus: CallStatus) { this.callStatus = callStatus if (callStatus == CallStatus.CURRENT) { isMissed = false mStatus = InteractionStatus.SUCCESS.toString() } else if (isRinging || isOnGoing) { mStatus = InteractionStatus.SUCCESS.toString() } else if (this.callStatus == CallStatus.FAILURE) { mStatus = InteractionStatus.FAILURE.toString() } } /*override var timestamp: Long get() = super.timestamp set(timestamp) { var timestamp = timestamp timestamp = timestamp }*/ val isRinging: Boolean get() = callStatus.isRinging val isOnGoing: Boolean get() = callStatus.isOnGoing /*override var isIncoming: Direction get() = super.isIncoming set(direction) { field = direction == Direction.INCOMING }*/ fun appendToVCard(messages: Map<String, String>): VCard? { for ((key, value) in messages) { val messageKeyValue = VCardUtils.parseMimeAttributes(key) val mimeType = messageKeyValue[VCardUtils.VCARD_KEY_MIME_TYPE] if (VCardUtils.MIME_PROFILE_VCARD != mimeType) { continue } val part = messageKeyValue[VCardUtils.VCARD_KEY_PART]!!.toInt() val nbPart = messageKeyValue[VCardUtils.VCARD_KEY_OF]!!.toInt() if (null == mProfileChunk) { mProfileChunk = ProfileChunk(nbPart) } mProfileChunk?.let { profile -> profile.addPartAtIndex(value, part) if (profile.isProfileComplete) { val ret = Ezvcard.parse(profile.completeProfile).first() mProfileChunk = null return@appendToVCard ret } } } return null } fun hasMedia(label: Media.MediaType): Boolean { val mediaList = mediaList ?: return false for (media in mediaList) { // todo check -> isEnabled est il utile ? Si le media n'est pas activé alors le daemon ne nous le transmets pas ? if (media.isEnabled && media.mediaType == label) { return true } } return false } fun hasActiveMedia(label: Media.MediaType): Boolean { val mediaList = mediaList ?: return false for (media in mediaList) { if (media.isEnabled && !media.isMuted && media.mediaType == label) return true } return false } fun hasActiveScreenSharing(): Boolean { val mediaList = mediaList ?: return false for (media in mediaList) { if (media.source == "camera://desktop" && media.isEnabled && !media.isMuted) return true } return false } enum class CallStatus { NONE, SEARCHING, CONNECTING, RINGING, CURRENT, HUNGUP, BUSY, FAILURE, HOLD, UNHOLD, INACTIVE, OVER; val isRinging: Boolean get() = this == CONNECTING || this == RINGING || this == NONE || this == SEARCHING val isOnGoing: Boolean get() = this == CURRENT || this == HOLD || this == UNHOLD val isOver: Boolean get() = this == HUNGUP || this == BUSY || this == FAILURE || this == OVER companion object { fun fromString(state: String): CallStatus { return when (state) { "SEARCHING" -> SEARCHING "CONNECTING" -> CONNECTING "INCOMING", "RINGING" -> RINGING "CURRENT" -> CURRENT "HUNGUP" -> HUNGUP "BUSY" -> BUSY "FAILURE" -> FAILURE "HOLD" -> HOLD "UNHOLD" -> UNHOLD "INACTIVE" -> INACTIVE "OVER" -> OVER "NONE" -> NONE else -> NONE } } fun fromConferenceString(state: String): CallStatus { return when (state) { "ACTIVE_ATTACHED" -> CURRENT "ACTIVE_DETACHED", "HOLD" -> HOLD else -> NONE } } } } enum class Direction(val value: Int) { INCOMING(0), OUTGOING(1); companion object { fun fromInt(value: Int): Direction { return if (value == INCOMING.value) INCOMING else OUTGOING } } } companion object { val TAG = Call::class.simpleName!! const val KEY_ACCOUNT_ID = "ACCOUNTID" const val KEY_HAS_VIDEO = "HAS_VIDEO" const val KEY_CALL_TYPE = "CALL_TYPE" const val KEY_CALL_STATE = "CALL_STATE" const val KEY_PEER_NUMBER = "PEER_NUMBER" const val KEY_PEER_HOLDING = "PEER_HOLDING" const val KEY_AUDIO_MUTED = "AUDIO_MUTED" const val KEY_VIDEO_MUTED = "VIDEO_MUTED" const val KEY_AUDIO_CODEC = "AUDIO_CODEC" const val KEY_VIDEO_CODEC = "VIDEO_CODEC" const val KEY_REGISTERED_NAME = "REGISTERED_NAME" const val KEY_DURATION = "duration" const val KEY_CONF_ID = "CONF_ID" } }
gpl-3.0
77c1b1799ddc7bba1011b25db771eb07
34.76489
135
0.576438
4.539594
false
false
false
false
ibinti/intellij-community
platform/script-debugger/backend/src/SuspendContextManagerBase.kt
3
2792
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.rejectedPromise import org.jetbrains.concurrency.resolvedPromise import java.util.concurrent.atomic.AtomicReference abstract class SuspendContextManagerBase<T : SuspendContextBase<CALL_FRAME>, CALL_FRAME : CallFrame> : SuspendContextManager<CALL_FRAME> { val contextRef = AtomicReference<T>() protected val suspendCallback = AtomicReference<AsyncPromise<Void>>() protected abstract val debugListener: DebugEventListener fun setContext(newContext: T) { if (!contextRef.compareAndSet(null, newContext)) { throw IllegalStateException("Attempt to set context, but current suspend context is already exists") } } open fun updateContext(newContext: SuspendContext<*>) { } // dismiss context on resumed protected fun dismissContext() { contextRef.get()?.let { contextDismissed(it) } } protected fun dismissContextOnDone(promise: Promise<*>): Promise<*> { val context = contextOrFail promise.done { contextDismissed(context) } return promise } fun contextDismissed(context: T) { if (!contextRef.compareAndSet(context, null)) { throw IllegalStateException("Expected $context, but another suspend context exists") } context.valueManager.markObsolete() debugListener.resumed(context.vm) } override val context: SuspendContext<CALL_FRAME>? get() = contextRef.get() override val contextOrFail: T get() = contextRef.get() ?: throw IllegalStateException("No current suspend context") override fun suspend() = suspendCallback.get() ?: if (context == null) doSuspend() else resolvedPromise() protected abstract fun doSuspend(): Promise<*> override fun setOverlayMessage(message: String?) { } override fun restartFrame(callFrame: CALL_FRAME): Promise<Boolean> = restartFrame(callFrame, contextOrFail) protected open fun restartFrame(callFrame: CALL_FRAME, currentContext: T) = rejectedPromise<Boolean>("Unsupported") override fun canRestartFrame(callFrame: CallFrame) = false override val isRestartFrameSupported = false }
apache-2.0
8556c071b27542dce6089d5bf5327799
33.481481
138
0.751074
4.614876
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/webview/sso/ui/SsoWebViewActivity.kt
2
3614
package chat.rocket.android.webview.sso.ui import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.webkit.CookieManager import android.webkit.WebView import android.webkit.WebViewClient import chat.rocket.android.R import kotlinx.android.synthetic.main.activity_web_view.* import kotlinx.android.synthetic.main.app_bar.* fun Context.ssoWebViewIntent(webPageUrl: String, casToken: String): Intent { return Intent(this, SsoWebViewActivity::class.java).apply { putExtra(INTENT_WEB_PAGE_URL, webPageUrl) putExtra(INTENT_SSO_TOKEN, casToken) } } private const val INTENT_WEB_PAGE_URL = "web_page_url" const val INTENT_SSO_TOKEN = "cas_token" /** * This class is responsible to handle the authentication thought single sign-on protocol (CAS and SAML). */ class SsoWebViewActivity : AppCompatActivity() { private lateinit var webPageUrl: String private lateinit var casToken: String private var isWebViewSetUp: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_web_view) webPageUrl = intent.getStringExtra(INTENT_WEB_PAGE_URL) requireNotNull(webPageUrl) { "no web_page_url provided in Intent extras" } casToken = intent.getStringExtra(INTENT_SSO_TOKEN) requireNotNull(casToken) { "no cas_token provided in Intent extras" } // Ensures that the cookies is always removed when opening the webview. CookieManager.getInstance().removeAllCookies(null) setupToolbar() } override fun onResume() { super.onResume() if (!isWebViewSetUp) { setupWebView() isWebViewSetUp = true } } override fun onBackPressed() { if (web_view.canGoBack()) { web_view.goBack() } else { closeView() } } private fun setupToolbar() { toolbar.title = getString(R.string.title_authentication) toolbar.setNavigationIcon(R.drawable.ic_close_white_24dp) toolbar.setNavigationOnClickListener { closeView() } } @SuppressLint("SetJavaScriptEnabled") private fun setupWebView() { web_view.settings.javaScriptEnabled = true web_view.webViewClient = object : WebViewClient() { override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { // The user may have already been logged in the SSO, so check if the URL contains // the "ticket" or "validate" word (that means the user is successful authenticated // and we don't need to wait until the page is fully loaded). if (url.contains("ticket") || url.contains("validate")) { closeView(Activity.RESULT_OK) } } override fun onPageFinished(view: WebView, url: String) { if (url.contains("ticket") || url.contains("validate")) { closeView(Activity.RESULT_OK) } else { view_loading.hide() } } } web_view.loadUrl(webPageUrl) } private fun closeView(activityResult: Int = Activity.RESULT_CANCELED) { setResult(activityResult, Intent().putExtra(INTENT_SSO_TOKEN, casToken)) finish() overridePendingTransition(R.anim.hold, R.anim.slide_down) } }
mit
72aba06b8e592aea044263eb64e41e9a
34.792079
105
0.65938
4.489441
false
false
false
false
thomasnield/kotlin-statistics
src/main/kotlin/org/nield/kotlinstatistics/ComparableStatistics.kt
1
1822
package org.nield.kotlinstatistics inline fun <T, R : Comparable<R>,K> Sequence<T>.minBy(crossinline keySelector: (T) -> K, crossinline valueSelector: (T) -> R) = groupApply(keySelector, valueSelector) { it.min() } inline fun <T, R : Comparable<R>,K> Iterable<T>.minBy(crossinline keySelector: (T) -> K, crossinline valueSelector: (T) -> R) = asSequence().minBy(keySelector, valueSelector) fun <K,R: Comparable<R>> Sequence<Pair<K, R>>.minBy() = groupApply({it.first}, {it.second}) { it.min() } fun <K, R: Comparable<R>> Iterable<Pair<K, R>>.minBy() = asSequence().minBy() inline fun <T, R : Comparable<R>,K> Sequence<T>.maxBy(crossinline keySelector: (T) -> K, crossinline valueSelector: (T) -> R) = groupApply(keySelector, valueSelector) { it.max() } inline fun <T, R : Comparable<R>,K> Iterable<T>.maxBy(crossinline keySelector: (T) -> K, crossinline valueSelector: (T) -> R) = asSequence().maxBy(keySelector, valueSelector) fun <T : Comparable<T>,K> Sequence<Pair<K, T>>.maxBy() = groupApply({it.first}, {it.second}) { it.max() } fun <T : Comparable<T>,K> Iterable<Pair<K, T>>.maxBy() = asSequence().maxBy() fun <T: Comparable<T>> Sequence<T>.range() = toList().range() fun <T: Comparable<T>> Iterable<T>.range() = toList().let { (it.min()?:throw Exception("At least one element must be present"))..(it.max()?:throw Exception("At least one element must be present")) } inline fun <T, R : Comparable<R>,K> Sequence<T>.rangeBy(crossinline keySelector: (T) -> K, crossinline valueSelector: (T) -> R) = groupApply(keySelector, valueSelector) { it.range() } inline fun <T, R : Comparable<R>,K> Iterable<T>.rangeBy(crossinline keySelector: (T) -> K, crossinline valueSelector: (T) -> R) = asSequence().rangeBy(keySelector, valueSelector)
apache-2.0
d9af7ef0ce285decedd3b5e8b56d6de5
43.439024
198
0.659166
3.411985
false
false
false
false
AndroidX/constraintlayout
demoProjects/ComposeMail/app/src/main/java/com/example/composemail/ui/theme/Theme.kt
2
1981
/* * Copyright (C) 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 com.example.composemail.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.Colors import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color private val LightColorPalette = lightColors( primary = Color(0xFF6200EE), primaryVariant = Color(0xFF3700B3), secondary = Color(0xFF03DAC5), onSecondary = Color(0xFFECECEC) /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) private val DarkColorPalette = darkColors( primary = Color(0xFFBB86FC), primaryVariant = Color(0xFF3700B3), secondary = Color(0xFF03DAC5), onSecondary = Color(0xFFFCFCFC) ) val Colors.textBackgroundColor: Color get() = Color(0xFFADB7C5) @Composable fun ComposeMailTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
apache-2.0
2a76f1715a132f4a0ad48a6c4bf3ae09
28.58209
99
0.735992
4.118503
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-experience-bukkit/src/main/kotlin/com/rpkit/experience/bukkit/listener/RPKCharacterSwitchListener.kt
1
1873
package com.rpkit.experience.bukkit.listener import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterSwitchEvent import com.rpkit.core.service.Services import com.rpkit.experience.bukkit.RPKExperienceBukkit import com.rpkit.experience.bukkit.experience.RPKExperienceService import org.bukkit.event.EventHandler import org.bukkit.event.Listener class RPKCharacterSwitchListener(private val plugin: RPKExperienceBukkit) : Listener { @EventHandler fun onCharacterSwitch(event: RPKBukkitCharacterSwitchEvent) { val experienceService = Services[RPKExperienceService::class.java] ?: return val newCharacter = event.character if (newCharacter != null) { experienceService.loadExperience(newCharacter).join() val characterLevel = experienceService.getPreloadedLevel(newCharacter) ?: 1 val characterExperience = experienceService.getPreloadedExperience(newCharacter) ?: 0 plugin.server.scheduler.runTask(plugin, Runnable { val minecraftProfile = event.minecraftProfile val bukkitPlayer = plugin.server.getPlayer(minecraftProfile.minecraftUUID) if (bukkitPlayer != null) { bukkitPlayer.level = characterLevel bukkitPlayer.exp = (characterExperience - experienceService.getExperienceNeededForLevel(characterLevel)).toFloat() / (experienceService.getExperienceNeededForLevel(characterLevel + 1) - experienceService.getExperienceNeededForLevel( characterLevel )).toFloat() } }) } val oldCharacter = event.fromCharacter if (oldCharacter != null) { experienceService.unloadExperience(oldCharacter) } } }
apache-2.0
de94b42c1be01d93981ba8b39ee7978e
47.051282
147
0.674853
5.710366
false
false
false
false
sproshev/tcity
app/src/main/kotlin/com/tcity/android/background/parser/ProjectsParser.kt
1
2014
/* * Copyright 2014 Semyon Proshev * * 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.tcity.android.background.parser import java.io.IOException import java.io.InputStream import android.util.JsonReader import com.tcity.android.db.Project throws(javaClass<IOException>()) public fun parseProjects(stream: InputStream): List<Project> { return parse(stream, "project", ::parseProject, { !it.id.equals(Project.ROOT_PROJECT_ID) }) } throws(javaClass<IOException>()) private fun parseProject(reader: JsonReader): Project { reader.beginObject() var id: String? = null var name: String? = null var parentId: String? = null var archived = false while (reader.hasNext()) { when (reader.nextName()) { "id" -> id = reader.nextString() "name" -> name = reader.nextString() "parentProjectId" -> parentId = reader.nextString() "archived" -> archived = reader.nextBoolean() else -> reader.skipValue() } } reader.endObject() if (id == Project.ROOT_PROJECT_ID) { parentId = Project.ROOT_PROJECT_ID } if (id == null) { throw IOException("Invalid project json: \"id\" is absent") } if (name == null) { throw IOException("Invalid project json: \"name\" is absent") } if (parentId == null) { throw IOException("Invalid project json: \"parentProjectId\" is absent") } return Project(id!!, name!!, parentId!!, archived) }
apache-2.0
2be6341e460b07d894d9e067f1b62834
29.074627
95
0.662363
4.110204
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/ui/BalloonTranslationPane.kt
1
4513
package cn.yiiguxing.plugin.translate.ui import cn.yiiguxing.plugin.translate.Settings import cn.yiiguxing.plugin.translate.trans.Lang import cn.yiiguxing.plugin.translate.util.invokeLater import com.intellij.openapi.project.Project import com.intellij.util.ui.JBUI import java.awt.Dimension import javax.swing.JComponent import javax.swing.JScrollPane class BalloonTranslationPane( project: Project?, settings: Settings, private val maxWidth: Int ) : TranslationPane<LangComboBoxLink>(project, settings) { private lateinit var dictViewerScrollWrapper: JScrollPane private var lastScrollValue: Int = 0 private var ignoreEvent = false private var onLanguageChangedHandler: ((Lang, Lang) -> Unit)? = null override val originalFoldingLength: Int = 100 val sourceLanguage: Lang? get() = sourceLangComponent.selected val targetLanguage: Lang? get() = targetLangComponent.selected init { border = JBUI.Borders.empty(OFFSET, OFFSET, OFFSET, -GAP) maximumSize = Dimension(maxWidth, Int.MAX_VALUE) onFixLanguage { sourceLangComponent.selected = it } } private fun LangComboBoxLink.swap(old: Lang?, new: Lang?) { if (new == selected && old != Lang.AUTO && new != Lang.AUTO) { ignoreEvent = true selected = old ignoreEvent = false } } override fun onCreateLanguageComponent(): LangComboBoxLink = LangComboBoxLink().apply { isOpaque = false addItemListener { newLang, oldLang, _ -> if (!ignoreEvent) { when (this) { sourceLangComponent -> targetLangComponent.swap(oldLang, newLang) targetLangComponent -> sourceLangComponent.swap(oldLang, newLang) } val src = sourceLangComponent.selected val target = targetLangComponent.selected if (src != null && target != null) { onLanguageChangedHandler?.invoke(src, target) } } } } override fun onWrapViewer(viewer: Viewer): JComponent { val maxHeight = if (isOriginalOrTranslationViewer(viewer)) MAX_VIEWER_SMALL else MAX_VIEWER_HEIGHT val scrollPane = object : ScrollPane(viewer) { override fun getPreferredSize(): Dimension { val preferredSize = super.getPreferredSize() if (preferredSize.height > maxHeight) { return Dimension(preferredSize.width, maxHeight) } return preferredSize } } viewer.border = JBUI.Borders.empty(0, 0, 0, OFFSET + GAP) if (isDictViewer(viewer)) { dictViewerScrollWrapper = scrollPane } return scrollPane } override fun onRowCreated(row: JComponent) { if (row !is ScrollPane) { val border = row.border val toMerge = JBUI.Borders.empty(0, 0, 0, OFFSET + GAP) row.border = if (border != null) JBUI.Borders.merge(border, toMerge, false) else toMerge } } override fun onBeforeFoldingExpand() { lastScrollValue = dictViewerScrollWrapper.verticalScrollBar.value dictViewerScrollWrapper.let { it.preferredSize = Dimension(it.width, it.height) } } override fun onFoldingExpanded() { dictViewerScrollWrapper.verticalScrollBar.run { invokeLater { value = lastScrollValue } } } override fun getPreferredSize(): Dimension { val preferredSize = super.getPreferredSize() if (preferredSize.width > maxWidth) { return Dimension(maxWidth, preferredSize.height) } return preferredSize } override fun LangComboBoxLink.updateLanguage(lang: Lang?) { ignoreEvent = true selected = lang ignoreEvent = false } fun setSupportedLanguages(src: List<Lang>, target: List<Lang>) { sourceLangComponent.setLanguages(src) targetLangComponent.setLanguages(target) } fun onLanguageChanged(handler: (src: Lang, target: Lang) -> Unit) { onLanguageChangedHandler = handler } companion object { private const val OFFSET = 10 const val MAX_VIEWER_SMALL = 200 const val MAX_VIEWER_HEIGHT = 250 private fun LangComboBoxLink.setLanguages(languages: List<Lang>) { model = LanguageListModel.sorted(languages, selected) } } }
mit
6bd805d70a3853a82784c28a34dd12b7
31.710145
106
0.633503
4.750526
false
false
false
false
FWDekker/intellij-randomness
src/main/kotlin/com/fwdekker/randomness/template/TemplateEditor.kt
1
1252
package com.fwdekker.randomness.template import com.fwdekker.randomness.StateEditor import com.fwdekker.randomness.ui.addChangeListenerTo import javax.swing.JPanel import javax.swing.JTextField /** * Component for editing non-children-related aspects of [Template]s. * * @param template the template to edit */ @Suppress("LateinitUsage") // Initialized by scene builder class TemplateEditor(template: Template) : StateEditor<Template>(template) { override lateinit var rootComponent: JPanel private set override val preferredFocusedComponent get() = nameInput private lateinit var nameInput: JTextField init { loadState() } override fun loadState(state: Template) { super.loadState(state) nameInput.text = state.name.trim() } override fun readState() = Template( name = nameInput.text.trim(), schemes = originalState.schemes.map { it.deepCopy(retainUuid = true) }, arrayDecorator = originalState.arrayDecorator.deepCopy(retainUuid = true).also { it.enabled = false } ).also { it.uuid = originalState.uuid } override fun addChangeListener(listener: () -> Unit) = addChangeListenerTo(nameInput, listener = listener) }
mit
7e7bb73e606c22cc30e6a698fb21d9f9
28.116279
113
0.704473
4.569343
false
false
false
false
nfrankel/kaadin
kaadin-core/src/test/kotlin/ch/frankel/kaadin/interaction/LinkTest.kt
1
3126
/* * Copyright 2016 Nicolas Fränkel * * 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 ch.frankel.kaadin.interaction import ch.frankel.kaadin.horizontalLayout import ch.frankel.kaadin.link import com.vaadin.server.FontAwesome.* import com.vaadin.ui.* import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test class LinkTest { @Test fun `link should be added to layout`() { val layout = horizontalLayout { link("dummy") } assertThat(layout.componentCount).isEqualTo(1) val component = layout.getComponent(0) assertThat(component).isNotNull.isInstanceOf(Link::class.java) } @Test(dependsOnMethods = ["link should be added to layout"]) fun `link should display a specific caption`() { val caption = "Hello world" val layout = horizontalLayout { link(caption) } val link = layout.getComponent(0) as Link assertThat(link.caption).isEqualTo(caption) } @Test(dependsOnMethods = ["link should be added to layout"]) fun `link should open a specific resource`() { val target = AMAZON val layout = horizontalLayout { link("dummy", target) } val link = layout.getComponent(0) as Link assertThat(link.resource).isEqualTo(target) } @Test(dependsOnMethods = ["link should be added to layout"]) fun `link should display a specific caption and open a specific resource`() { val caption = "Hello world" val target = AMAZON val layout = horizontalLayout { link(caption, target) } val link = layout.getComponent(0) as Link assertThat(link.caption).isEqualTo(caption) assertThat(link.resource).isEqualTo(target) } @Test(dependsOnMethods = ["link should be added to layout"]) fun `link should open in a specific target`() { val targetName = "_blank" val layout = horizontalLayout { link("dummy", targetName = targetName) } val link = layout.getComponent(0) as Link // Not possible to simulate click, must check state assertThat(link.targetName).isEqualTo(targetName) } @Test(dependsOnMethods = ["link should be added to layout"]) fun `link should be configurable in the lambda`() { val data = "dummy" val layout = horizontalLayout { link("caption") { this.data = data } } val link = layout.getComponent(0) as Link assertThat(link.data).isEqualTo(data) } }
apache-2.0
7348ffcf30d5774894c293c4c1b4c65e
32.978261
81
0.65024
4.542151
false
true
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/base/BasicScaledImageCommand.kt
1
1456
package net.perfectdreams.loritta.morenitta.commands.vanilla.images.base import net.perfectdreams.loritta.morenitta.api.commands.CommandBuilder import net.perfectdreams.loritta.morenitta.api.commands.CommandContext import net.perfectdreams.loritta.common.utils.createImage import net.perfectdreams.loritta.common.utils.image.Image import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils open class BasicScaledImageCommand( loritta: LorittaBot, labels: List<String>, descriptionKey: String, sourceTemplatePath: String, val scaleXTo: Int, val scaleYTo: Int, val x: Int, val y: Int, builder: CommandBuilder<CommandContext>.() -> (Unit) = {}, slashCommandName: String? = null ) : BasicImageCommand( loritta, labels, descriptionKey, sourceTemplatePath, { builder.invoke(this) executes { slashCommandName?.let { OutdatedCommandUtils.sendOutdatedCommandMessage( this, locale, it ) } val contextImage = validate(image(0)) val template = loritta.assets.loadImage(sourceTemplatePath, loadFromCache = true) val base = createImage(template.width, template.height) val graphics = base.createGraphics() val scaled = contextImage.getScaledInstance(scaleXTo, scaleYTo, Image.ScaleType.SMOOTH) graphics.drawImage(scaled, x, y) graphics.drawImage(template, 0, 0) sendImage(base, sourceTemplatePath) } }, slashCommandName )
agpl-3.0
65de527e76f686a131a4df7420409e5f
26.490566
90
0.773352
3.811518
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/fun/BomDiaECiaExecutor.kt
1
1997
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun` import net.perfectdreams.loritta.common.utils.TodoFixThisData import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.loritta.cinnamon.pudding.tables.bomdiaecia.BomDiaECiaMatches import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.selectAll class BomDiaECiaExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) { inner class Options : LocalizedApplicationCommandOptions(loritta) { val text = string("text", TodoFixThisData) } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { context.deferChannelMessageEphemerally() val text = args[options.text] val currentActiveBomDiaECia = context.loritta.pudding.transaction { BomDiaECiaMatches.selectAll() .orderBy(BomDiaECiaMatches.id, SortOrder.DESC) .limit(1) .first() } // Wrong if (text != currentActiveBomDiaECia[BomDiaECiaMatches.text]) { context.sendEphemeralMessage { content = "Texto errado!" } return } // Correct context.sendEphemeralMessage { content = "oloco você ganhou" } // TODO: Get current active bom dia & cia // TODO: Trigger win/lose scenario, if needed // TODO: context.sendEphemeralMessage { content = "oloco" } } }
agpl-3.0
18b9f18380a6ebb69da4c9a4c69b68b0
37.403846
114
0.712926
5.053165
false
false
false
false
Citrus-CAF/packages_apps_Margarita
app/src/main/kotlin/com/citrus/theme/ThemeFunctions.kt
1
5723
package com.citrus.theme import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.content.pm.Signature import android.os.RemoteException import com.citrus.theme.AdvancedConstants.BLACKLISTED_APPLICATIONS import com.citrus.theme.AdvancedConstants.ORGANIZATION_THEME_SYSTEMS import com.citrus.theme.AdvancedConstants.OTHER_THEME_SYSTEMS @Suppress("ConstantConditionIf") object ThemeFunctions { fun isCallingPackageAllowed(packageId: String): Boolean { if (BuildConfig.SUPPORTS_THIRD_PARTY_SYSTEMS) { OTHER_THEME_SYSTEMS.contains(packageId) } return ORGANIZATION_THEME_SYSTEMS.contains(packageId) } fun getSelfVerifiedPirateTools(context: Context): Boolean { val pm = context.packageManager val packages = pm.getInstalledApplications(PackageManager.GET_META_DATA) val listOfInstalled = arrayListOf<String>() packages.mapTo(listOfInstalled) { it.packageName } return BLACKLISTED_APPLICATIONS.any { listOfInstalled.contains(it) } } @Suppress("DEPRECATION") @SuppressLint("PackageManagerGetSignatures") fun checkApprovedSignature(context: Context, packageName: String): Boolean { SIGNATURES.filter { try { val pm = context.packageManager val pi = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES) if (pi.signatures != null && pi.signatures.size == 1 && ((SIGNATURES[0] == pi.signatures[0]) || (SIGNATURES[1] == pi.signatures[0]))) { return true } return false } catch (e: RemoteException) { return false } }.forEach { return true } return false } @Suppress("DEPRECATION") @SuppressLint("PackageManagerGetSignatures") fun getSelfSignature(context: Context): Int { try { val sigs = context.packageManager.getPackageInfo( context.packageName, PackageManager.GET_SIGNATURES ).signatures return sigs[0].hashCode() } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return 0 } // Enforce a way to get official support from the team, by ensuring that only private val SUBSTRATUM_SIGNATURE = Signature("" + "308202eb308201d3a003020102020411c02f2f300d06092a864886f70d01010b050030263124302206" + "03550403131b5375627374726174756d20446576656c6f706d656e74205465616d301e170d31363037" + "30333032333335385a170d3431303632373032333335385a3026312430220603550403131b53756273" + "74726174756d20446576656c6f706d656e74205465616d30820122300d06092a864886f70d01010105" + "000382010f003082010a02820101008855626336f645a335aa5d40938f15db911556385f72f72b5f8b" + "ad01339aaf82ae2d30302d3f2bba26126e8da8e76a834e9da200cdf66d1d5977c90a4e4172ce455704" + "a22bbe4a01b08478673b37d23c34c8ade3ec040a704da8570d0a17fce3c7397ea63ebcde3a2a3c7c5f" + "983a163e4cd5a1fc80c735808d014df54120e2e5708874739e22e5a22d50e1c454b2ae310b480825ab" + "3d877f675d6ac1293222602a53080f94e4a7f0692b627905f69d4f0bb1dfd647e281cc0695e0733fa3" + "efc57d88706d4426c4969aff7a177ac2d9634401913bb20a93b6efe60e790e06dad3493776c2c0878c" + "e82caababa183b494120edde3d823333efd464c8aea1f51f330203010001a321301f301d0603551d0e" + "04160414203ec8b075d1c9eb9d600100281c3924a831a46c300d06092a864886f70d01010b05000382" + "01010042d4bd26d535ce2bf0375446615ef5bf25973f61ecf955bdb543e4b6e6b5d026fdcab09fec09" + "c747fb26633c221df8e3d3d0fe39ce30ca0a31547e9ec693a0f2d83e26d231386ff45f8e4fd5c06095" + "8681f9d3bd6db5e940b1e4a0b424f5c463c79c5748a14a3a38da4dd7a5499dcc14a70ba82a50be5fe0" + "82890c89a27e56067d2eae952e0bcba4d6beb5359520845f1fdb7df99868786055555187ba46c69ee6" + "7fa2d2c79e74a364a8b3544997dc29cc625395e2f45bf8bdb2c9d8df0d5af1a59a58ad08b32cdbec38" + "19fa49201bb5b5aadeee8f2f096ac029055713b77054e8af07cd61fe97f7365d0aa92d570be98acb89" + "41b8a2b0053b54f18bfde092eb") // Also allow our CI builds private val SUBSTRATUM_CI_SIGNATURE = Signature("" + "308201dd30820146020101300d06092a864886f70d010105050030373116301406035504030c0d416e" + "64726f69642044656275673110300e060355040a0c07416e64726f6964310b30090603550406130255" + "53301e170d3137303232333036303730325a170d3437303231363036303730325a3037311630140603" + "5504030c0d416e64726f69642044656275673110300e060355040a0c07416e64726f6964310b300906" + "035504061302555330819f300d06092a864886f70d010101050003818d00308189028181008aa6cf56" + "e3ba4d0921da3baf527529205efbe440e1f351c40603afa5e6966e6a6ef2def780c8be80d189dc6101" + "935e6f8340e61dc699cfd34d50e37d69bf66fbb58619d0ebf66f22db5dbe240b6087719aa3ceb1c68f" + "3fa277b8846f1326763634687cc286b0760e51d1b791689fa2d948ae5f31cb8e807e00bd1eb72788b2" + "330203010001300d06092a864886f70d0101050500038181007b2b7e432bff612367fbb6fdf8ed0ad1" + "a19b969e4c4ddd8837d71ae2ec0c35f52fe7c8129ccdcdc41325f0bcbc90c38a0ad6fc0c604a737209" + "17d37421955c47f9104ea56ad05031b90c748b94831969a266fa7c55bc083e20899a13089402be49a5" + "edc769811adc2b0496a8a066924af9eeb33f8d57d625a5fa150f7bc18e55") // Whitelisted signatures private val SIGNATURES = arrayOf( SUBSTRATUM_SIGNATURE, SUBSTRATUM_CI_SIGNATURE ) }
apache-2.0
7ff418239dcd4460dcc0194549361e47
51.990741
98
0.736677
2.934872
false
false
false
false
madtcsa/AppManager
app/src/main/java/com/md/appmanager/AppInfo.kt
1
1318
package com.md.appmanager import android.graphics.drawable.Drawable import java.io.Serializable class AppInfo : Serializable { var name: String? = null private set var apk: String? = null private set var version: String? = null private set var source: String? = null private set var data: String? = null private set var icon: Drawable? = null var isSystem: Boolean? = null private set constructor(name: String, apk: String, version: String, source: String, data: String, icon: Drawable, isSystem: Boolean?) { this.name = name this.apk = apk this.version = version this.source = source this.data = data this.icon = icon this.isSystem = isSystem } constructor(string: String) { val split = string.split("##".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray() if (split.size == 6) { this.name = split[0] this.apk = split[1] this.version = split[2] this.source = split[3] this.data = split[4] this.isSystem = java.lang.Boolean.getBoolean(split[5]) } } override fun toString(): String { return "$name##$apk##$version##$source##$data##$isSystem" } }
gpl-3.0
f5ee0cef6b809e99a4788e7801ab7990
26.458333
127
0.579666
4.144654
false
false
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/inject/DatabaseModule.kt
1
2398
package be.digitalia.fosdem.inject import android.content.Context import androidx.annotation.WorkerThread import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.preferencesDataStoreFile import androidx.room.Room import androidx.room.RoomDatabase import androidx.sqlite.db.SupportSQLiteDatabase import be.digitalia.fosdem.db.AppDatabase import be.digitalia.fosdem.db.BookmarksDao import be.digitalia.fosdem.db.ScheduleDao import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.runBlocking import javax.inject.Named import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { private const val DB_FILE = "fosdem.sqlite" private const val DB_DATASTORE_FILE = "database" @Provides @Named("Database") fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> { return PreferenceDataStoreFactory.create( produceFile = { context.preferencesDataStoreFile(DB_DATASTORE_FILE) } ) } @Provides @Singleton fun provideAppDatabase( @ApplicationContext context: Context, @Named("Database") dataStore: DataStore<Preferences> ): AppDatabase { return Room.databaseBuilder(context, AppDatabase::class.java, DB_FILE) .setJournalMode(RoomDatabase.JournalMode.TRUNCATE) .fallbackToDestructiveMigration() .addCallback(object : RoomDatabase.Callback() { @WorkerThread override fun onDestructiveMigration(db: SupportSQLiteDatabase) { runBlocking { dataStore.edit { it.clear() } } } }) .build() .also { // Manual dependency injection it.dataStore = dataStore } } @Provides fun provideScheduleDao(appDatabase: AppDatabase): ScheduleDao = appDatabase.scheduleDao @Provides fun provideBookmarksDao(appDatabase: AppDatabase): BookmarksDao = appDatabase.bookmarksDao }
apache-2.0
e4dcad1cb5fa3466880be7ee272748c2
34.279412
94
0.716847
5.235808
false
false
false
false
DataDozer/DataDozer
core/src/main/kotlin/org/datadozer/Analysis.kt
1
3012
package org.datadozer import org.apache.lucene.analysis.custom.CustomAnalyzer import org.apache.lucene.analysis.util.TokenFilterFactory import org.apache.lucene.analysis.util.TokenizerFactory import org.datadozer.models.Analyzer import java.io.StringReader /* * Licensed to DataDozer under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. DataDozer licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Utility function to get tokens from the search string based upon the passed analyzer * This will enable us to avoid using the Lucene query parser * We cannot use simple white space based token generation as it really depends * upon the analyzer used */ fun parseTextUsingAnalyzer(analyzer: LuceneAnalyzer, fieldName: String, queryText: String, tokens: ArrayList<String>) { val source = analyzer.tokenStream(fieldName, StringReader(queryText)) // Get the CharTermAttribute from the TokenStream val termAtt = source.addAttribute(org.apache.lucene.analysis.tokenattributes.CharTermAttribute::class.java) source.use { source -> source.reset() while (source.incrementToken()) { tokens.add(termAtt.toString()) } source.end() } } /** * Creates a Lucene analyzer from the DataDozer analyzer definition */ fun getCustomAnalyzer(analyzer: Analyzer): LuceneAnalyzer { val builder = CustomAnalyzer.builder() builder.withTokenizer(analyzer.tokenizer.tokenizerName, analyzer.tokenizer.parametersMap) for (filter in analyzer.filtersList) { builder.addTokenFilter(filter.filterName, filter.parametersMap) } return builder.build() } /** * Returns keyword analyzer */ fun getKeywordAnalyzer(): LuceneAnalyzer { return CustomAnalyzer.builder() .withTokenizer("keyword") .addTokenFilter("lowercase") .build() } /** * Checks if a given filter is present in the system and returns true if * it is found. */ fun checkFilterExists(filterName: String): Boolean { val filters = TokenFilterFactory::availableTokenFilters.invoke() return filters.contains(filterName) } /** * Checks if a given tokenizer is present in the system and returns true if * it is found. */ fun checkTokenizerExists(filterName: String): Boolean { val tokenizers = TokenizerFactory::availableTokenizers.invoke() return tokenizers.contains(filterName) }
apache-2.0
93a474c6e6a9b75f41504c814a269ffe
34.447059
119
0.742696
4.422907
false
false
false
false
chRyNaN/GuitarChords
sample/src/main/java/com/chrynan/sample/ui/adapter/ChordListAdapter.kt
1
1482
package com.chrynan.sample.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.chrynan.aaaah.* import com.chrynan.sample.R import com.chrynan.sample.viewmodel.AdapterItemViewModel import com.chrynan.sample.viewmodel.ChordListViewModel import kotlinx.android.synthetic.main.adapter_chord_list.view.* import javax.inject.Inject import javax.inject.Named @Adapter class ChordListAdapter @Inject constructor( @Named("NestedChordListAdapter") private val adapter: ManagerRecyclerViewAdapter<AdapterItemViewModel>, private val viewPool: RecyclerView.RecycledViewPool ) : AnotherAdapter<ChordListViewModel>() { override val viewType = AdapterViewType.from(this::class.java) override fun onHandlesItem(item: Any) = item is ChordListViewModel override fun onCreateView(parent: ViewGroup, inflater: LayoutInflater, viewType: ViewType): View = inflater.inflate(R.layout.adapter_chord_list, parent, false) override fun View.onBindItem(item: ChordListViewModel, position: Int) { titleTextView?.text = item.title recyclerView?.adapter = adapter recyclerView?.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) recyclerView?.setRecycledViewPool(viewPool) adapter.items = item.items } }
apache-2.0
e0d0bdda0b16a882211bdb76852aed0c
40.194444
111
0.775978
4.811688
false
false
false
false
jitsi/jitsi-videobridge
jvb/src/main/kotlin/org/jitsi/videobridge/relay/RelayEndpointSender.kt
1
5644
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.relay import org.jitsi.nlj.Features import org.jitsi.nlj.PacketHandler import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.RtpSender import org.jitsi.nlj.RtpSenderImpl import org.jitsi.nlj.format.PayloadType import org.jitsi.nlj.rtcp.RtcpEventNotifier import org.jitsi.nlj.rtcp.RtcpListener import org.jitsi.nlj.rtp.RtpExtension import org.jitsi.nlj.srtp.SrtpTransformers import org.jitsi.nlj.stats.NodeStatsBlock import org.jitsi.nlj.util.PacketInfoQueue import org.jitsi.nlj.util.StreamInformationStore import org.jitsi.nlj.util.StreamInformationStoreImpl import org.jitsi.rtp.rtcp.RtcpPacket import org.jitsi.utils.logging.DiagnosticContext import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.cdebug import org.jitsi.utils.logging2.createChildLogger import org.jitsi.utils.queue.CountingErrorHandler import org.jitsi.videobridge.TransportConfig import org.jitsi.videobridge.transport.ice.IceTransport import org.jitsi.videobridge.util.TaskPools import org.json.simple.JSONObject import java.time.Instant /** * An object that sends media from a single local endpoint to a single remote relay. */ class RelayEndpointSender( val relay: Relay, val id: String, parentLogger: Logger, diagnosticContext: DiagnosticContext ) { private val logger = createChildLogger(parentLogger) private val streamInformationStore: StreamInformationStore = StreamInformationStoreImpl() val rtcpEventNotifier = RtcpEventNotifier().apply { addRtcpEventListener( object : RtcpListener { override fun rtcpPacketReceived(packet: RtcpPacket, receivedTime: Instant?) { throw IllegalStateException("got rtcpPacketReceived callback from a sender") } override fun rtcpPacketSent(packet: RtcpPacket) { relay.rtcpPacketSent(packet, id) } }, external = true ) } private val rtpSender: RtpSender = RtpSenderImpl( "${relay.id}-$id", rtcpEventNotifier, TaskPools.CPU_POOL, TaskPools.SCHEDULED_POOL, streamInformationStore, logger, diagnosticContext ).apply { onOutgoingPacket(object : PacketHandler { override fun processPacket(packetInfo: PacketInfo) { packetInfo.addEvent(SRTP_QUEUE_ENTRY_EVENT) outgoingSrtpPacketQueue.add(packetInfo) } }) } /** * The queue we put outgoing SRTP packets onto so they can be sent * out via the Relay's [IceTransport] on an IO thread. */ private val outgoingSrtpPacketQueue = PacketInfoQueue( "${javaClass.simpleName}-outgoing-packet-queue", TaskPools.IO_POOL, { packet -> relay.doSendSrtp(packet) }, TransportConfig.queueSize ).apply { setErrorHandler(queueErrorCounter) } private var expired = false fun addPayloadType(payloadType: PayloadType) = streamInformationStore.addRtpPayloadType(payloadType) fun addRtpExtension(rtpExtension: RtpExtension) = streamInformationStore.addRtpExtensionMapping(rtpExtension) fun setSrtpInformation(srtpTransformers: SrtpTransformers) { rtpSender.setSrtpTransformers(srtpTransformers) } fun sendPacket(packetInfo: PacketInfo) = rtpSender.processPacket(packetInfo) fun setFeature(feature: Features, enabled: Boolean) { rtpSender.setFeature(feature, enabled) } fun getOutgoingStats() = rtpSender.getPacketStreamStats() fun getNodeStats(): NodeStatsBlock { return NodeStatsBlock("Remote Endpoint $id").apply { addBlock(streamInformationStore.getNodeStats()) addBlock(rtpSender.getNodeStats()) } } fun getDebugState(): JSONObject { val debugState = JSONObject() debugState["expired"] = expired val block = getNodeStats() debugState[block.name] = block.toJson() return debugState } fun expire() { if (expired) { return } expired = true try { updateStatsOnExpire() rtpSender.stop() logger.cdebug { getNodeStats().prettyPrint(0) } rtpSender.tearDown() } catch (t: Throwable) { logger.error("Exception while expiring: ", t) } outgoingSrtpPacketQueue.close() } private fun updateStatsOnExpire() { val relayStats = relay.statistics val outgoingStats = rtpSender.getPacketStreamStats() relayStats.apply { bytesSent.getAndAdd(outgoingStats.bytes) packetsSent.getAndAdd(outgoingStats.packets) } } companion object { /** * Count the number of dropped packets and exceptions. */ @JvmField val queueErrorCounter = CountingErrorHandler() private const val SRTP_QUEUE_ENTRY_EVENT = "Entered RelayEndpointSender SRTP sender outgoing queue" } }
apache-2.0
e8e63540408368e1156e64296261eccf
31.813953
113
0.68657
4.444094
false
false
false
false
hzsweers/RxBinding
rxbinding-viewpager2/src/androidTest/java/com/jakewharton/rxbinding3/viewpager2/RxViewPager2TestActivity.kt
1
1753
package com.jakewharton.rxbinding3.viewpager2 import android.app.Activity import android.os.Bundle import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams import android.view.ViewGroup.LayoutParams.MATCH_PARENT import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 class RxViewPager2TestActivity : Activity() { private lateinit var viewPager2: ViewPager2 fun getViewPager2(): ViewPager2 = viewPager2 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewPager2 = ViewPager2(this).apply { id = PAGER_ID adapter = TestAdapter(RAINBOW) } setContentView(viewPager2) } private class TestAdapter(private val colors: List<Int>) : RecyclerView.Adapter<TestViewHolder>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): TestViewHolder = TestViewHolder(View(parent.context).apply { layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT) }) override fun getItemCount(): Int = colors.size override fun onBindViewHolder( holder: TestViewHolder, position: Int ) { holder.itemView.setBackgroundResource(colors[position]) } } companion object { const val PAGER_ID = Int.MAX_VALUE val RAINBOW = listOf( android.R.color.holo_red_light, android.R.color.holo_orange_dark, android.R.color.holo_orange_light, android.R.color.holo_green_light, android.R.color.holo_blue_light, android.R.color.holo_blue_dark, android.R.color.holo_purple ) } private class TestViewHolder(item: View) : RecyclerView.ViewHolder(item) }
apache-2.0
c63e94130541bbdf515bbe25e88677af
26.390625
101
0.711352
4.224096
false
true
false
false
gravidence/gravifon
gravifon/src/main/kotlin/org/gravidence/gravifon/ui/PlaylistComposable.kt
1
13910
package org.gravidence.gravifon.ui import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.input.key.* import androidx.compose.ui.input.pointer.PointerEvent import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlinx.datetime.Clock import org.gravidence.gravifon.GravifonContext import org.gravidence.gravifon.domain.track.StreamVirtualTrack import org.gravidence.gravifon.domain.track.VirtualTrack import org.gravidence.gravifon.domain.track.format.format import org.gravidence.gravifon.event.EventBus import org.gravidence.gravifon.event.playlist.PlayCurrentFromPlaylistEvent import org.gravidence.gravifon.event.playlist.RemoveFromPlaylistEvent import org.gravidence.gravifon.playback.PlaybackStatus import org.gravidence.gravifon.playlist.Playlist import org.gravidence.gravifon.playlist.item.AlbumPlaylistItem import org.gravidence.gravifon.playlist.item.PlaylistItem import org.gravidence.gravifon.playlist.item.TrackPlaylistItem import org.gravidence.gravifon.playlist.layout.ScrollPosition import org.gravidence.gravifon.playlist.layout.StatusColumn import org.gravidence.gravifon.playlist.layout.TrackInfoColumn import org.gravidence.gravifon.ui.component.* import org.gravidence.gravifon.ui.theme.gListItemColor import org.gravidence.gravifon.ui.theme.gShape import org.gravidence.gravifon.ui.util.ListHolder import org.gravidence.gravifon.util.DesktopUtil import org.gravidence.gravifon.util.firstNotEmptyOrNull import java.awt.event.MouseEvent class PlaylistState( val playlistItems: MutableState<ListHolder<PlaylistItem>>, val playlist: Playlist ) { val playlistTableState = PlaylistTableState(this) private fun selectedPlaylistItems(): List<PlaylistItem> { return playlistTableState.selectedRows.value.map { playlistItems.value.list[it] } } fun selectedTracks(): List<VirtualTrack> { return selectedPlaylistItems() .filterIsInstance<TrackPlaylistItem>() .map { it.track } } fun effectivelySelectedTracks(): List<VirtualTrack> { return firstNotEmptyOrNull(selectedPlaylistItems(), playlistItems.value.list) .orEmpty() .filterIsInstance<TrackPlaylistItem>() .map { it.track } } fun prepareMetadataDialog(tracks: List<VirtualTrack>) { GravifonContext.trackMetadataDialogState.prepare( playlist = playlist, tracks = tracks, ) GravifonContext.trackMetadataDialogVisible.value = true } } @Composable fun rememberPlaylistState( playlistItems: ListHolder<PlaylistItem> = ListHolder(listOf()), playlist: Playlist ) = remember(playlistItems) { PlaylistState( playlistItems = mutableStateOf(playlistItems), playlist = playlist ) } class PlaylistTableState( private val playlistState: PlaylistState ) : TableState<PlaylistItem>( layout = layout(playlistState), grid = grid(playlistState), initialVerticalScrollPosition = playlistState.playlist.verticalScrollPosition, ) { @OptIn(ExperimentalComposeUiApi::class) override fun onKeyEvent(keyEvent: KeyEvent): Boolean { return super.onKeyEvent(keyEvent) || if (keyEvent.type == KeyEventType.KeyUp) { when (keyEvent.key) { Key.Delete -> { EventBus.publish(RemoveFromPlaylistEvent(playlistState.playlist, selectedRows.value)) selectedRows.value = setOf() true } Key.Enter -> if (keyEvent.isAltPressed) { playlistState.prepareMetadataDialog(playlistState.effectivelySelectedTracks()) true } else { false } else -> false } } else { false } } override fun onRowRelease(rowIndex: Int, pointerEvent: PointerEvent) { super.onRowRelease(rowIndex, pointerEvent) (pointerEvent.nativeEvent as? MouseEvent)?.let { if (it.button == 1 && it.clickCount == 2) { EventBus.publish(PlayCurrentFromPlaylistEvent(playlistState.playlist, playlistState.playlistItems.value.list[rowIndex])) } } } override fun onVerticalScroll(scrollPosition: ScrollPosition) { super.onVerticalScroll(scrollPosition) playlistState.playlist.verticalScrollPosition = scrollPosition } override fun onTableColumnWidthChange(index: Int, delta: Dp) { super.onTableColumnWidthChange(index, delta) val playlistColumnsUpdated = playlistState.playlist.layout.columns.mapIndexed { i, c -> if (i == index) { val updatedWidth = layout.value.columns[i].width!! + delta when (c) { is StatusColumn -> c.copy(width = updatedWidth.value.toInt()) is TrackInfoColumn -> c.copy(width = updatedWidth.value.toInt()) } } else { c } } playlistState.playlist.layout = playlistState.playlist.layout.copy(columns = playlistColumnsUpdated) } companion object { fun layout(playlistState: PlaylistState): MutableState<TableLayout> { val columns = playlistState.playlist.layout.columns.map { TableColumn(header = it.header, width = it.width.dp) } return mutableStateOf( TableLayout( displayHeaders = true, columns = columns ) ) } fun grid(playlistState: PlaylistState): MutableState<TableGrid<PlaylistItem>?> { return mutableStateOf( TableGrid( rows = mutableStateOf( playlistState.playlistItems.value.list.map { playlistRow(it, playlistState) }.toMutableList() ) ) ) } private fun playlistRow(playlistItem: PlaylistItem, playlistState: PlaylistState): TableRow<PlaylistItem> { return TableRow( when (playlistItem) { is TrackPlaylistItem -> { playlistState.playlist.layout.columns.map { when (it) { is StatusColumn -> mutableStateOf(statusCell(playlistItem, playlistState, it)) is TrackInfoColumn -> mutableStateOf(trackInfoCell(playlistItem, it)) } }.toMutableList() } is AlbumPlaylistItem -> { TODO("Not yet implemented") } } ) } private val statusIconModifier = Modifier.size(20.dp) private fun statusCell(trackPlaylistItem: TrackPlaylistItem, playlistState: PlaylistState, column: StatusColumn): TableCell<PlaylistItem> { return TableCell( value = GravifonContext.playbackStatusState.value.toString(), content = { _, rowIndex, _, _ -> run { // force cell refresh on active track change GravifonContext.activeTrack.value === trackPlaylistItem.track } Box( modifier = Modifier .fillMaxSize() .background(color = gListItemColor, shape = gShape) .padding(5.dp) ) { Row( horizontalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.fillMaxWidth() ) { Text("") // workaround to align cell's height with other cells if (column.showExpirationStatus) { (trackPlaylistItem.track as? StreamVirtualTrack)?.expiresAfter?.let { val delta = it.minus(Clock.System.now()) if (delta < column.expirationThreshold) { val text = if (delta.isNegative()) "Stream expired" else "Stream expires in ${delta.inWholeMinutes} minutes" val icon = if (delta.isNegative()) Icons.Filled.HourglassEmpty else Icons.Filled.HourglassBottom TextTooltip( tooltip = text ) { Icon( imageVector = icon, contentDescription = "Expiration Status", modifier = statusIconModifier ) } } } } if (column.showFailureStatus && trackPlaylistItem.track.failing) { TextTooltip( tooltip = "Last attempt to play the track has failed" ) { Icon( imageVector = Icons.Filled.Error, contentDescription = "Failure Status", modifier = statusIconModifier ) } } if (column.showPlaybackStatus && playlistState.playlist.position() == rowIndex + 1) { TextTooltip( tooltip = "Track playback status" ) { Icon( imageVector = resolvePlaybackStatusIcon( GravifonContext.playbackStatusState.value, playlistState.playlist, GravifonContext.activePlaylist.value ), contentDescription = "Playback Status", modifier = statusIconModifier ) } } } } } ) } private fun trackInfoCell(trackPlaylistItem: TrackPlaylistItem, column: TrackInfoColumn): TableCell<PlaylistItem> { return TableCell( value = trackPlaylistItem.track.format(column.format), content = { _, _, _, _ -> Text( text = trackPlaylistItem.track.format(column.format), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier .fillMaxWidth() .background(color = gListItemColor, shape = gShape) .padding(5.dp) ) } ) } private fun resolvePlaybackStatusIcon(playbackStatus: PlaybackStatus, thisPlaylist: Playlist, activePlaylist: Playlist?): ImageVector { return if (thisPlaylist === activePlaylist) { when (playbackStatus) { PlaybackStatus.PLAYING -> Icons.Filled.PlayCircle PlaybackStatus.PAUSED -> Icons.Filled.PauseCircle PlaybackStatus.STOPPED -> Icons.Filled.StopCircle } } else { Icons.Filled.StopCircle } } } } fun buildContextMenu(playlistState: PlaylistState): List<ContextMenuItem> { val contextMenuItems: MutableList<ContextMenuItem> = mutableListOf() playlistState.selectedTracks() .filterIsInstance<StreamVirtualTrack>() .takeIf { it.isNotEmpty() } ?.let { streams -> contextMenuItems += ContextMenuItem("Open stream source page") { streams.forEach { stream -> DesktopUtil.openInBrowser(stream.sourceUrl) } } } playlistState.effectivelySelectedTracks() .takeIf { it.isNotEmpty() } ?.let { tracks -> contextMenuItems += ContextMenuItem("Edit metadata") { playlistState.prepareMetadataDialog(tracks) } } return contextMenuItems } @Composable fun PlaylistComposable(playlistState: PlaylistState) { Box( modifier = Modifier .fillMaxHeight() .border(width = 1.dp, color = Color.Black, shape = gShape) ) { ContextMenuArea( items = { buildContextMenu(playlistState) } ) { Table(playlistState.playlistTableState) } } }
mit
1fc9dc8caf8dd35e3feb29ff7b0ada29
40.278932
148
0.552193
5.788598
false
false
false
false
zensum/franz
src/test/kotlin/JobStatusesTest.kt
1
9092
package franz import franz.engine.kafka_one.JobId import franz.engine.kafka_one.JobStatuses import franz.engine.kafka_one.jobId import org.apache.kafka.clients.consumer.ConsumerRecord import org.apache.kafka.clients.consumer.OffsetAndMetadata import org.apache.kafka.common.TopicPartition import org.junit.jupiter.api.Test import kotlin.test.* private typealias JS = JobStatuses<String, String> private typealias CR = ConsumerRecord<String, String> private const val DEFAULT_TOPIC = "test_topic" private const val ALTERNATE_TOPIC = "other_topic" private const val DEFAULT_VALUE = "test_value" private const val DEFAULT_PARTITION = 1 private const val DEFAULT_KEY = "test_key" private fun CROffsetPartition(partition: Int, offset: Int) = CR( DEFAULT_TOPIC, partition, offset.toLong(), DEFAULT_KEY, DEFAULT_VALUE ) private fun CROffset(x: Int) = CROffsetPartition(DEFAULT_PARTITION, x) private val ALTERNATE_TOPIC_P1 = TopicPartition(ALTERNATE_TOPIC, DEFAULT_PARTITION) private val DEFAULT_TOPIC_PARTITION = TopicPartition(DEFAULT_TOPIC, DEFAULT_PARTITION) private val DEFAULT_TOPIC_P2 = TopicPartition(DEFAULT_TOPIC, 2) private val CR1 = CROffset(1) private val CR2 = CROffset(2) private val CR3 = CROffset(3) private val P2CR1 = CROffsetPartition(2, 1) private val P2CR2 = CROffsetPartition(2, 2) private val P2CR3 = CROffsetPartition(2, 3) private val OTHER_TOPIC_CR1 = CR(ALTERNATE_TOPIC, 1, 1, DEFAULT_KEY, DEFAULT_VALUE) private val FAILED = JobStatus.TransientFailure // js is immutable, and JS() its zero value private val js = JS() private fun jsWith(updates: Map<JobId, JobStatus>) = js.update(updates) private fun recordsWStatuses(vararg pairs: Pair<CR, JobStatus>) = pairs.toMap().mapKeys { (k, _) -> k.jobId() } private fun recordWStatus(cr: CR, status: JobStatus) = mapOf(cr.jobId() to status) class JobStatusesTest { @Test fun testAddingJob() { js.addJobs(listOf(CR1)).let { assertNotEquals(js, it, "Adding a record should modify JS") } } @Test fun testAddingNoJobs() { js.addJobs(emptyList()).let { assertEquals(js, it, "Adding the empty list of jobs should have no effect") } } @Test fun testAddingJobIdempotent() { js.addJobs(listOf(CR1)).let { val anotherAdd = js.addJobs(listOf(CR1)) assertEquals(it, anotherAdd, "Repeated adds of the same record should be idempotent") } } @Test fun testEmptyNotCommittable() { js.committableOffsets().let { assertTrue("No offsets should be committable") { it.isEmpty() } } } @Test fun testTrivialCommittable() { jsWith(recordWStatus(CR1, JobStatus.Success)).committableOffsets().let { val res = it[DEFAULT_TOPIC_PARTITION] assertNotNull(res, "The default partition should have a committable offset" ) val offset = res!!.offset() assertEquals(offset, CR1.offset() + 1, "The offset of the Successful job should be comitted") } } @Test fun testTrivialNonCommittable() { jsWith(recordWStatus(CR1, JobStatus.Incomplete)).committableOffsets().let { assertTrue("No offsets should be committable") { it.isEmpty() } } } @Test fun testHeadOfLineNonCommittable() { jsWith(recordsWStatuses( CR1 to JobStatus.Incomplete, CR2 to JobStatus.Success )).committableOffsets().let { assertTrue("No offsets should be committable") { it.isEmpty() } } } @Test fun testSomeCommittable() { jsWith(recordsWStatuses( CR1 to JobStatus.Success, CR2 to JobStatus.Incomplete, CR3 to JobStatus.Success )).committableOffsets().let { val res = it[DEFAULT_TOPIC_PARTITION] assertNotNull(res, "One partition should be committable") val offset = res!!.offset() assertEquals(offset, CR1.offset() + 1) } } @Test fun testSinglePartitionCommitable() { jsWith(recordsWStatuses( CR1 to JobStatus.Success, P2CR1 to JobStatus.Incomplete )).committableOffsets().let { assertNull(it[DEFAULT_TOPIC_P2], "Partition 2 should not be committable") assertNotNull(it[DEFAULT_TOPIC_PARTITION], "Partition 1 should be committable") assertEquals(CR1.offset() + 1, it[DEFAULT_TOPIC_PARTITION]!!.offset(), "CR1 should be committable") } } @Test fun testAlternateTopicCommittable() { jsWith(recordsWStatuses( OTHER_TOPIC_CR1 to JobStatus.Success, P2CR1 to JobStatus.Incomplete )).committableOffsets().let { assertNull(it[DEFAULT_TOPIC_PARTITION], "Default topic partition should not be committable") assertNotNull(it[ALTERNATE_TOPIC_P1], "alternate topic, partition 1 should be committable") assertEquals(OTHER_TOPIC_CR1.offset() + 1, it[ALTERNATE_TOPIC_P1]!!.offset(), "OTHER_TOPIC_CR1 should be committable" ) } } @Test fun testRescheduleTransientUnchangedOnEmpty() { val (newJS, retry) = js.rescheduleTransientFailures() assertEquals(js, newJS, "Jobs should be unchanged") assertTrue("Nothing should be retried") { retry.isEmpty() } } @Test fun testRescheduleTransientUnchangedNotFailed() { val origJs = jsWith(recordsWStatuses(CR1 to JobStatus.Incomplete)) origJs.rescheduleTransientFailures().let { (newJS, retry) -> assertEquals(origJs, newJS, "Jobs should be unchanged") assertTrue("Nothing should be retried") { retry.isEmpty() } } } @Test fun testRescheduleTransientFailedJob() { val origJs = js .addJobs(listOf(CR1)) .update(recordsWStatuses(CR1 to FAILED)) origJs.rescheduleTransientFailures().let { (newJS, retry) -> assertNotEquals(origJs, newJS, "Jobs should be changed") assertEquals(1, retry.count(), "Exactly one job should returned for retrying") assertEquals(CR1, retry[0], "CR1 should be retried") } } @Test fun testRescheduleTwoTransientFailedJobs() { val origJs = js .addJobs(listOf(CR1, CR2)) .update(recordsWStatuses(CR1 to FAILED, CR2 to FAILED)) origJs.rescheduleTransientFailures().let { (newJS, retry) -> assertNotEquals(origJs, newJS, "Jobs should be changed") assertEquals(2, retry.count(), "Exactly one job should returned for retrying") assertTrue("CR1 to be retried") { retry.contains(CR1) } assertTrue("CR2 to be retried") { retry.contains(CR2) } } } @Test fun testRemoveCommittedEmpty() { val orig = jsWith(recordsWStatuses(CR1 to JobStatus.Success, CR2 to JobStatus.Success)) orig.removeCommitted(emptyMap()).let { assertEquals(orig, it, "Should be unchanged") } } @Test fun testRemoveCommittedAll() { jsWith(recordsWStatuses(CR1 to JobStatus.Success, CR2 to JobStatus.Success)) .removeCommitted(mapOf(DEFAULT_TOPIC_PARTITION to OffsetAndMetadata(3))).let { assertEquals(js, it, "Should be unchanged") } } @Test fun testRemoveCommittedSome() { jsWith(recordsWStatuses(CR1 to JobStatus.Success, CR2 to JobStatus.Success)) .removeCommitted(mapOf(DEFAULT_TOPIC_PARTITION to OffsetAndMetadata(2))).let { assertEquals( jsWith(recordsWStatuses(CR2 to JobStatus.Success)), it, "Should contain only CR2" ) } } @Test fun testRemoveCommittedBehind() { val orig = jsWith(recordsWStatuses(CR2 to JobStatus.Success, CR3 to JobStatus.Success)) orig.removeCommitted(mapOf(DEFAULT_TOPIC_PARTITION to OffsetAndMetadata(1))).let { assertEquals(orig, it, "Should be unchanged") } } @Test fun testRemoveOnePartition() { jsWith(recordsWStatuses(CR1 to JobStatus.Success, P2CR1 to JobStatus.Success)) .removeCommitted(mapOf(DEFAULT_TOPIC_PARTITION to OffsetAndMetadata(2))).let { assertEquals( jsWith(recordsWStatuses(P2CR1 to JobStatus.Success)), it, "Partition 2 should be safe from partition one removal" ) } } @Test fun testRemoveTwoPartitions() { jsWith(recordsWStatuses(CR1 to JobStatus.Success, P2CR1 to JobStatus.Success)) .removeCommitted(mapOf( DEFAULT_TOPIC_PARTITION to OffsetAndMetadata(2), DEFAULT_TOPIC_P2 to OffsetAndMetadata(3))).let { assertEquals(js, it, "all records should be removed") } } }
mit
79a9142dfcacd4cd9f33b2e91367afcf
37.362869
111
0.632864
4.142141
false
true
false
false
zensum/franz
src/test/kotlin/WorkerInterceptorTest.kt
1
13735
package franz import franz.engine.mock.MockConsumerActor import franz.engine.mock.MockMessage import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import kotlin.test.assertEquals class DummyException(): Throwable() class WorkerInterceptorTest { fun createTestMessage(): MockMessage<String> = MockMessage(0, "", "this is a test message") @Test fun installNoFeature(){ runBlocking { val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString().createFactory()) .handlePiped { it .end() } assertEquals(0, worker.getInterceptors().size) } } @Test fun installSingleFeature(){ runBlocking { val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString().createFactory()) .install(WorkerInterceptor()) .handlePiped { it .execute { true } .sideEffect { } .end() } assertEquals(1, worker.getInterceptors().size) } } @Test fun installMultipleFeatures(){ runBlocking { val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString().createFactory()) .install(WorkerInterceptor()) .install(WorkerInterceptor()) .install(WorkerInterceptor()) .handlePiped { it .end() } assertEquals(3, worker.getInterceptors().size) } } @Test fun installInterceptor(){ runBlocking { val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString(listOf(createTestMessage())).createFactory()) .install(WorkerInterceptor { i, d -> i.executeNext(d) }) .handlePiped { it .sideEffect { } .end() } assertEquals(1, worker.getInterceptors().size) } } @Test fun installMultipleInterceptor(){ runBlocking { val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString(listOf(createTestMessage())).createFactory()) .install(WorkerInterceptor { i, d -> i.executeNext(d) }) .install(WorkerInterceptor { i, d -> i.executeNext(d) }) .handlePiped { it .sideEffect { } .end() } assertEquals(2, worker.getInterceptors().size) } } @Test fun interceptorContinueExecution(){ runBlocking { var setFlagged = false val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString(listOf(createTestMessage())).createFactory()) .install(WorkerInterceptor { i, d -> i.executeNext(d) }) .handlePiped { it .sideEffect { setFlagged = true } .end() } worker.start() assertTrue(setFlagged) } } @Test fun interceptorStopExecution(){ runBlocking { var setFlagged = false val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString(listOf(createTestMessage())).createFactory()) .install(WorkerInterceptor()) /* Explicitly don't runt it.executeNext() */ .install(WorkerInterceptor { i, d -> i.executeNext(d) }) .handlePiped { it .sideEffect { setFlagged = true } .end() } worker.start() assertFalse(setFlagged) } } @Test fun throwsUnhandled(){ runBlocking { val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString(listOf(createTestMessage())).createFactory()) .handlePiped { it .sideEffect { } .end() } worker.start() } } @Test fun tryCatchInInterceptorWithRequire(){ var throwable: Throwable? = null runBlocking { val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString(listOf(createTestMessage())).createFactory()) .install(WorkerInterceptor { i, default -> try { i.executeNext(default) } catch (e: Throwable) { throwable = e } JobStatus.PermanentFailure }) .handlePiped { it .require { throw DummyException() } .end() } worker.start() assertNotNull(throwable) assertEquals(JobStateException::class.java, throwable!!::class.java) } } @Test fun tryCatchInInterceptorWithMap(){ runBlocking { var throwable: Throwable? = null val engine = MockConsumerActor.ofString(listOf(createTestMessage())) val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(engine.createFactory()) .install(WorkerInterceptor { i, default -> try { i.executeNext(default) } catch (e: Throwable) { throwable = e } JobStatus.PermanentFailure }) .handlePiped { it .map { throw DummyException() } .end() } worker.start() assertNotNull(throwable) assertEquals(JobStateException::class.java, throwable!!::class.java) } } @Test fun runSingleInterceptorSeveralStages(){ runBlocking { var count = 0 val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString(listOf(createTestMessage())).createFactory()) .install(WorkerInterceptor { _, _ -> count++ JobStatus.Success }) .handlePiped { it .execute { true } .execute { true } .sideEffect { } .end() } worker.start() // One interceptor, three job stages, one message assertEquals(3, count) } } @Test fun runSingleInterceptorSeveralMessages(){ runBlocking { var count = 0 val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString(listOf( createTestMessage(), createTestMessage(), createTestMessage(), createTestMessage() )).createFactory()) .install(WorkerInterceptor { _, _ -> count++ JobStatus.Success }) .handlePiped { it .sideEffect { } .end() } worker.start() // One interceptor, one job stages, four messages assertEquals(4, count) } } @Test fun overrideJobStatus(){ runBlocking { val mockConsumerActor = MockConsumerActor.ofString(listOf(createTestMessage())) val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(mockConsumerActor.createFactory()) .install(WorkerInterceptor { i, d -> i.executeNext(d) JobStatus.Success }) .handlePiped { it .execute { false } .end() } worker.start() val result = mockConsumerActor.results().first() // As the execute block returns false, this should result in an error. However, the interceptor override the result making it a success assertEquals(JobStatus.Success, result.status) } } @Test fun overrideMultipleJobStatus(){ runBlocking { val mockConsumerActor = MockConsumerActor.ofString(listOf(createTestMessage())) val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(mockConsumerActor.createFactory()) .install(WorkerInterceptor { i, d -> i.executeNext(d) JobStatus.Success }) .handlePiped { it .execute { true } .execute { false } .end() } worker.start() val result = mockConsumerActor.results().first() // As the execute block returns false, this should result in an error. However, the interceptor override the result making it a success assertEquals(JobStatus.Success, result.status) } } @Test fun overrideMultipleInterceptors(){ runBlocking { val mockConsumerActor = MockConsumerActor.ofString(listOf(createTestMessage())) val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(mockConsumerActor.createFactory()) .install(WorkerInterceptor { i, d -> i.executeNext(d) JobStatus.PermanentFailure }) .install(WorkerInterceptor { i, d -> i.executeNext(d) JobStatus.TransientFailure }) .handlePiped { it .execute { true } .execute { false } .end() } worker.start() val result = mockConsumerActor.results().first() // The last interceptor returns a permanent failure, so that should be the final result of the worker assertEquals(JobStatus.PermanentFailure, result.status) } } @Test fun mapJobState(){ runBlocking { var count = 0 val worker = WorkerBuilder.ofByteArray .subscribedTo("TOPIC") .groupId("TOPIC") .setEngine(MockConsumerActor.ofString(listOf(createTestMessage())).createFactory()) .install(WorkerInterceptor { i, d -> count++ i.executeNext(d) }) .handlePiped { it .execute { true } .map { it.key() } .execute { false } .require { false } .end() } worker.start() assertEquals(4, count) } } }
mit
be0f4714be41299b32d31016961e8bd7
31.093458
147
0.435166
6.173034
false
true
false
false
Sevran/DnDice
app/src/main/java/io/deuxsept/dndice/Model/Preferences.kt
1
1929
package io.deuxsept.dndice.Model import android.content.Context import android.support.v7.preference.PreferenceManager /** * Provides utilities to easily access shared preferences */ class Preferences { /** * Context used to retrieve the default shared preferences */ private var _ctx: Context? = null /** * Is the Night mode forced? */ val NightModeForced: Boolean get() = checkContextAndGet("pref_color_theme", false) /** * Do we hide the roll window and only update the toolbar roll info? */ val HideRollWindow: Boolean get() = checkContextAndGet("pref_no_roll_window", false) /** * Do we roll as soon as we select a favourite? */ val QuickFavouritesRoll: Boolean get() = checkContextAndGet("pref_quick_favorite_roll", false) /** * Ensures that the context has properly been set, then returns the value with the * appropriate type * @throws NoSuchMethodException if it doesn't know what to do with this type */ private inline fun <reified T> checkContextAndGet(key: String, default: T): T { if (_ctx == null) throw IllegalStateException("Please setup the context before getting a key") var prefs = PreferenceManager.getDefaultSharedPreferences(_ctx) return when (default) { is Boolean -> prefs.getBoolean(key, default) as T is Int -> prefs.getInt(key, default) as T else -> throw NoSuchMethodException("Not implemented for this particular type") } } private constructor(context: Context) { this._ctx = context } companion object { var prefs: Preferences? = null fun getInstance(context: Context): Preferences { return when(prefs) { null -> Preferences(context) else -> prefs as Preferences } } } }
mit
662d93b2ed8101f9d0a1c5799bb06673
28.692308
91
0.628305
4.727941
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIGestureRecognizerLooper.kt
1
7640
package com.yy.codex.uikit import java.lang.ref.WeakReference import java.util.* /** * Created by cuiminghui on 2017/1/13. */ internal class UIGestureRecognizerLooper internal constructor(internal var hitTestedView: UIView) { internal var gestureRecognizers: List<UIGestureRecognizer> internal var isFinished = false init { gestureRecognizers = getGestureRecognizers(hitTestedView) for (i in gestureRecognizers.indices) { gestureRecognizers[i]._looper = this } gestureRecognizers = gestureRecognizers.sortedWith(Comparator { a, b -> if (a.gesturePriority() == b.gesturePriority()) { if (a._looperOrder > b._looperOrder) { return@Comparator 1 } else { return@Comparator -1 } } else if (a.gesturePriority() > b.gesturePriority()){ return@Comparator 1 } else { return@Comparator -1 } }) resetState() } internal fun onTouchesBegan(touches: List<UITouch>, event: UIEvent) { val copyList = ArrayList(gestureRecognizers) for (i in copyList.indices) { if (checkState(copyList[i])) { copyList[i].touchesBegan(touches, event) checkState(copyList[i]) if (checkBegan(copyList[i]) && !copyList[i].stealable) { break } } } markFailed() } internal fun onTouchesMoved(touches: List<UITouch>, event: UIEvent) { val copyList = ArrayList(gestureRecognizers) for (i in copyList.indices) { if (checkState(copyList[i])) { copyList[i].touchesMoved(touches, event) checkState(copyList[i]) if (checkBegan(copyList[i]) && !copyList[i].stealable) { break } } } markFailed() } internal fun onTouchesEnded(touches: List<UITouch>, event: UIEvent) { val copyList = ArrayList(gestureRecognizers) for (i in copyList.indices) { if (checkState(copyList[i])) { copyList[i].touchesEnded(touches, event) checkState(copyList[i]) if (checkBegan(copyList[i]) && !copyList[i].stealable) { break } } } markFailed() } internal fun onTouchesCancelled(touches: List<UITouch>, event: UIEvent) { val copyList = ArrayList(gestureRecognizers) copyList.indices .filter { checkState(copyList[it]) } .forEach { copyList[it].touchesCancelled() } } internal fun checkState(gestureRecognizer: UIGestureRecognizer): Boolean { val mutableList = gestureRecognizers.toMutableList() if (gestureRecognizer.state == UIGestureRecognizerState.Failed || gestureRecognizer.state == UIGestureRecognizerState.Cancelled) { mutableList.remove(gestureRecognizer) gestureRecognizers = mutableList.toList() return false } else if (gestureRecognizer.state == UIGestureRecognizerState.Ended) { isFinished = true } return true } internal fun checkBegan(gestureRecognizer: UIGestureRecognizer): Boolean { return gestureRecognizer.state == UIGestureRecognizerState.Began || gestureRecognizer.state == UIGestureRecognizerState.Changed || gestureRecognizer.state == UIGestureRecognizerState.Ended } internal fun markFailed() { val recognizedGestures = gestureRecognizers.filter { (it.state == UIGestureRecognizerState.Began || it.state == UIGestureRecognizerState.Changed || it.state == UIGestureRecognizerState.Ended) } if (recognizedGestures.size > 0) { val stealable = recognizedGestures.any { it.stealable && (it.state == UIGestureRecognizerState.Began || it.state == UIGestureRecognizerState.Changed || it.state == UIGestureRecognizerState.Ended) } val stealed = recognizedGestures.any { it.stealer && (it.state == UIGestureRecognizerState.Began || it.state == UIGestureRecognizerState.Changed || it.state == UIGestureRecognizerState.Ended) } if (stealable) { if (!stealed) { gestureRecognizers .filter { !it.stealer && !it.stealable && !(it.state == UIGestureRecognizerState.Began || it.state == UIGestureRecognizerState.Changed || it.state == UIGestureRecognizerState.Ended) } .forEach { it.state = UIGestureRecognizerState.Failed } } else { gestureRecognizers .filter { !it.stealer && !it.stealable && !(it.state == UIGestureRecognizerState.Began || it.state == UIGestureRecognizerState.Changed || it.state == UIGestureRecognizerState.Ended) } .forEach { it.state = UIGestureRecognizerState.Failed } gestureRecognizers.forEach { if (it.stealable && (it.state == UIGestureRecognizerState.Began || it.state == UIGestureRecognizerState.Changed || it.state == UIGestureRecognizerState.Ended)) { it.touchesCancelled() } } } } else { gestureRecognizers .filter { !(it.state == UIGestureRecognizerState.Began || it.state == UIGestureRecognizerState.Changed || it.state == UIGestureRecognizerState.Ended) } .forEach { it.state = UIGestureRecognizerState.Failed } } } } private fun getGestureRecognizers(view: UIView): List<UIGestureRecognizer> { if (!view.userInteractionEnabled) { return listOf() } else { var gestureRecognizers: MutableList<UIGestureRecognizer> = view.gestureRecognizers.toMutableList() val superview = view.superview if (superview != null) { val superGestureRecognizers = getGestureRecognizers(superview) gestureRecognizers.addAll(superGestureRecognizers) } gestureRecognizers = removeConflictRecognizers(gestureRecognizers.toList()).toMutableList() gestureRecognizers.forEachIndexed { idx, recognizer -> recognizer._looperOrder = idx } return gestureRecognizers.toList() } } private fun removeConflictRecognizers(gestureRecognizers: List<UIGestureRecognizer>): List<UIGestureRecognizer> { val longPressHash: HashMap<Int, Boolean> = hashMapOf() return gestureRecognizers.filter { (it as? UILongPressGestureRecognizer)?.let { val aKey = (it.minimumPressDuration * 1000).toInt() if (longPressHash.containsKey(aKey)) { return@filter false } else { longPressHash.put(aKey, true) return@filter true } } return@filter true } } private fun resetState() { gestureRecognizers.forEach { it.state = UIGestureRecognizerState.Possible } } companion object { internal fun isHitTestedView(touches: List<UITouch>, theView: UIView): Boolean { if (touches.size > 0) { return touches[0].hitTestedView === theView } return false } } }
gpl-3.0
58f43cc32568c49f55ff9bfabef7a831
40.521739
211
0.585995
5.120643
false
false
false
false
lskycity/AndroidTools
app/src/main/java/com/lskycity/androidtools/apputils/UpgradeUtils.kt
1
2980
package com.lskycity.androidtools.apputils import android.content.Context import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.lskycity.androidtools.AppConstants import com.lskycity.androidtools.BuildConfig import com.lskycity.androidtools.app.ToolApplication import com.lskycity.support.utils.SharedPreUtils import org.json.JSONException import org.json.JSONObject /** * Created by zhaofliu on 1/3/17. */ object UpgradeUtils { private val CHECK_VERSION_TIME_GAP = (1000 * 60 * 60 * 24 * 7).toLong() //a week @Throws(JSONException::class) fun getVersionInfo(jsonObject: JSONObject): VersionInfo { val info = VersionInfo() info.packageName = jsonObject.getString("package_name") info.versionCode = jsonObject.getInt("version_code") info.versionName = jsonObject.getString("version_name") info.downloadUrl = jsonObject.getString("download_url") info.setCurrentTimeToCheckTime() return info } fun getVersionInfoFromSharedPreference(context: Context): VersionInfo { val info = VersionInfo() info.packageName = BuildConfig.APPLICATION_ID info.versionCode = SharedPreUtils.getInt(context, AppSharedPreUtils.KEY_LAST_DATE_CHECK_VERSION_CODE) info.versionName = SharedPreUtils.getString(context, AppSharedPreUtils.KEY_LAST_DATE_CHECK_VERSION_NAME) info.downloadUrl = SharedPreUtils.getString(context, AppSharedPreUtils.KEY_LAST_DATE_CHECK_VERSION_URL) info.checkTime = SharedPreUtils.getString(context, AppSharedPreUtils.KEY_LAST_DATE_CHECK_VERSION) return info } fun putToSharedPre(context: Context, versionInfo: VersionInfo) { SharedPreUtils.putString(context, AppSharedPreUtils.KEY_LAST_DATE_CHECK_VERSION, versionInfo.checkTime) SharedPreUtils.putInt(context, AppSharedPreUtils.KEY_LAST_DATE_CHECK_VERSION_CODE, versionInfo.versionCode) SharedPreUtils.putString(context, AppSharedPreUtils.KEY_LAST_DATE_CHECK_VERSION_NAME, versionInfo.versionName) SharedPreUtils.putString(context, AppSharedPreUtils.KEY_LAST_DATE_CHECK_VERSION_URL, versionInfo.downloadUrl) } fun checkVersionIfTimeOut() { val currentTime = System.currentTimeMillis() val versionInfo = getVersionInfoFromSharedPreference(ToolApplication.get()) if (currentTime - versionInfo.getCheckTimeLong() > CHECK_VERSION_TIME_GAP) { val jsonObjectRequest = JsonObjectRequest(AppConstants.CHECK_VERSION_URL, null, Response.Listener { jsonObject -> try { val info = UpgradeUtils.getVersionInfo(jsonObject) UpgradeUtils.putToSharedPre(ToolApplication.get(), info) } catch (e: JSONException) { e.printStackTrace() } }, Response.ErrorListener { }) ToolApplication.get().requestQueue.add(jsonObjectRequest) } } }
apache-2.0
eb37a1866bb698626cdaf0d4440dd155
40.971831
125
0.718456
4.28777
false
false
false
false
carlphilipp/stock-tracker-android
src/fr/cph/stock/android/StockTrackerApp.kt
1
3441
/** * Copyright 2017 Carl-Philipp Harmant * * * 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 fr.cph.stock.android import android.app.Activity import android.app.Application import android.content.Intent import android.widget.Toast import fr.cph.stock.android.Constants.ERROR import fr.cph.stock.android.activity.ErrorActivity import fr.cph.stock.android.activity.LoginActivity import org.json.JSONObject /** * This class extends Application. It defines some functions that will be available anywhere within the app * * @author Carl-Philipp Harmant */ class StockTrackerApp : Application() { /** * This function logout the user and removes its login/password from the preferences. It also loads the login activity * * @param activity the activity to finish */ fun logOut(activity: Activity) { val settings = getSharedPreferences(Constants.PREFS_NAME, 0) val login = settings.getString(Constants.LOGIN, null) val password = settings.getString(Constants.PASSWORD, null) if (login != null) { settings.edit().remove(Constants.LOGIN).apply() } if (password != null) { settings.edit().remove(Constants.PASSWORD).apply() } activity.setResult(100) activity.finish() val intent = Intent(this, LoginActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } /** * Check if a session is valid or not * * @param jsonObject the json session object to check * @return true or false */ fun isSessionError(jsonObject: JSONObject): Boolean { val error = jsonObject.optString(ERROR) return error == "No active session" || error == "User session not found" } /** * This function loads the error activity to the screen. It happens usually when the session is timeout and needs to request a * new session id to the server * * @param currentActivity the activity to stop * @param jsonObject the json object containing the error message */ fun loadErrorActivity(currentActivity: Activity, jsonObject: JSONObject) { val intent = Intent(this, ErrorActivity::class.java) intent.putExtra("data", jsonObject.toString()) val settings = getSharedPreferences(Constants.PREFS_NAME, 0) val login = settings.getString(Constants.LOGIN, null) val password = settings.getString(Constants.PASSWORD, null) intent.putExtra(Constants.LOGIN, login) intent.putExtra(Constants.PASSWORD, password) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) currentActivity.finish() } /** * This function toast a toast "updated" message to the screen */ fun toast() { Toast.makeText(applicationContext, "Updated !", Toast.LENGTH_LONG).show() } }
apache-2.0
62693181dad916e331da49ac24f0e25c
34.474227
130
0.6873
4.457254
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/LaTeX.kt
1
5238
/*************************************************************************************** * Copyright (c) 2009 Edu Zamora <[email protected]> * * Copyright (c) 2012 Kostas Spyropoulos <[email protected]> * * Copyright (c) 2015 Houssam Salem <[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.libanki import androidx.annotation.VisibleForTesting import com.ichi2.utils.HtmlUtils.escape import java.util.regex.Matcher import java.util.regex.Pattern /** * This class is used to detect LaTeX tags in HTML and convert them to their corresponding image * file names. * * Anki provides shortcut forms for certain expressions. These three forms are considered valid * LaTeX tags in Anki: * ``` * 1 - [latex]...[/latex] * 2 - [$]...[$] * 3 - [$$]...[$$] * ``` * Unlike the original python implementation of this class, the AnkiDroid version does not support * the generation of LaTeX images. */ object LaTeX { /** * Patterns used to identify LaTeX tags */ private val STANDARD_PATTERN = Pattern.compile( "\\[latex](.+?)\\[/latex]", Pattern.DOTALL or Pattern.CASE_INSENSITIVE ) private val EXPRESSION_PATTERN = Pattern.compile( "\\[\\$](.+?)\\[/\\$]", Pattern.DOTALL or Pattern.CASE_INSENSITIVE ) private val MATH_PATTERN = Pattern.compile( "\\[\\$\\$](.+?)\\[/\\$\\$]", Pattern.DOTALL or Pattern.CASE_INSENSITIVE ) /** * Convert HTML with embedded latex tags to image links. * NOTE: _imgLink produces an alphanumeric filename so there is no need to escape the replacement string. */ fun mungeQA(html: String, col: Collection, svg: Boolean): String { return mungeQA(html, col.media, svg) } fun convertHTML(html: String, media: Media, svg: Boolean): String { val stringBuffer = StringBuffer() STANDARD_PATTERN.matcher(html).run { while (find()) { appendReplacement(stringBuffer, imgLink(group(1)!!, svg, media)) } appendTail(stringBuffer) } return stringBuffer.toString() } fun convertExpression(input: String, media: Media, svg: Boolean): String { val stringBuffer = StringBuffer() EXPRESSION_PATTERN.matcher(input).run { while (find()) { appendReplacement(stringBuffer, imgLink("$" + group(1) + "$", svg, media)) } appendTail(stringBuffer) } return stringBuffer.toString() } fun convertMath(input: String, media: Media, svg: Boolean): String { val stringBuffer = StringBuffer() MATH_PATTERN.matcher(input).run { while (find()) { appendReplacement( stringBuffer, imgLink("\\begin{displaymath}" + group(1) + "\\end{displaymath}", svg, media) ) } appendTail(stringBuffer) } return stringBuffer.toString() } // It's only goal is to allow testing with a different media manager. @VisibleForTesting fun mungeQA(html: String, m: Media, svg: Boolean): String = arrayOf(::convertHTML, ::convertExpression, ::convertMath).fold(html) { input, transformer -> transformer(input, m, svg) } /** * Return an img link for LATEX. */ @VisibleForTesting internal fun imgLink(latex: String, svg: Boolean, m: Media): String { val txt = latexFromHtml(latex) val ext = if (svg) "svg" else "png" val fname = "latex-" + Utils.checksum(txt) + "." + ext return if (m.have(fname)) { Matcher.quoteReplacement("<img class=latex alt=\"" + escape(latex) + "\" src=\"" + fname + "\">") } else { Matcher.quoteReplacement(latex) } } /** * Convert entities and fix newlines. */ private fun latexFromHtml(latex: String): String = Utils.stripHTML(latex.replace("<br( /)?>|<div>".toRegex(), "\n")) }
gpl-3.0
71895885fbb1171c3dc2312eae46af49
40.571429
120
0.537801
4.680965
false
false
false
false
mixitconf/mixit
src/main/kotlin/mixit/talk/handler/TalkDto.kt
1
1065
package mixit.talk.handler import mixit.event.handler.AdminEventHandler import mixit.talk.model.TalkFormat import mixit.user.model.Link import mixit.user.model.User import java.time.LocalDateTime class TalkDto( val id: String?, val slug: String, val format: TalkFormat, val event: String, val title: String, val summary: String, val speakers: List<User>, val language: String, val addedAt: LocalDateTime, val description: String?, val topic: String?, val video: String?, val vimeoPlayer: String?, val room: String?, val roomLink: String?, val start: String?, val end: String?, val date: String?, val favorite: Boolean = false, val photoUrls: List<Link> = emptyList(), val isEn: Boolean = (language == "english"), val isTalk: Boolean = (format == TalkFormat.TALK), val isCurrentEdition: Boolean = AdminEventHandler.CURRENT_EVENT == event, val multiSpeaker: Boolean = (speakers.size > 1), val speakersFirstNames: String = (speakers.joinToString { it.firstname }) )
apache-2.0
405133450b3d24873bd53e19ef5c5fc5
29.428571
77
0.688263
3.959108
false
false
false
false
akvo/akvo-flow-mobile
utils/src/main/java/org/akvo/flow/utils/entity/Form.kt
1
1602
/* * Copyright (C) 2020 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow 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. * * Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.utils.entity data class Form( val id: Int, val formId: String, val surveyId: Long, val name: String, val version: Double, val type: String = "survey", val location: String = "sdcard", val filename: String, val language: String = "en", val cascadeDownloaded: Boolean = true, val deleted: Boolean = false, val groups: MutableList<QuestionGroup> = mutableListOf() ) { fun getResources(): List<String> { val formResources = mutableListOf<String>() for (group in groups) { for (question in group.questions) { val cascadeResource = question.cascadeResource if (!cascadeResource.isNullOrEmpty()) { formResources.add(cascadeResource) } } } return formResources } }
gpl-3.0
c7dc5909bebd306a3df33bfe58a270c6
31.693878
71
0.656679
4.32973
false
false
false
false
Kotlin/kotlinx.serialization
benchmark/src/jmh/kotlin/kotlinx/benchmarks/json/CitmBenchmark.kt
1
1198
package kotlinx.benchmarks.json import kotlinx.benchmarks.model.* import kotlinx.serialization.* import kotlinx.serialization.json.* import kotlinx.serialization.json.Json.Default.decodeFromString import kotlinx.serialization.json.Json.Default.encodeToString import org.openjdk.jmh.annotations.* import java.util.concurrent.* @Warmup(iterations = 7, time = 1) @Measurement(iterations = 7, time = 1) @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @State(Scope.Benchmark) @Fork(2) open class CitmBenchmark { /* * For some reason Citm is kind of de-facto standard cross-language benchmark. * Order of magnitude: 200 ops/sec */ private val input = CitmBenchmark::class.java.getResource("/citm_catalog.json").readBytes().decodeToString() private val citm = Json.decodeFromString(CitmCatalog.serializer(), input) @Setup fun init() { require(citm == Json.decodeFromString(CitmCatalog.serializer(), Json.encodeToString(citm))) } @Benchmark fun decodeCitm(): CitmCatalog = Json.decodeFromString(CitmCatalog.serializer(), input) @Benchmark fun encodeCitm(): String = Json.encodeToString(CitmCatalog.serializer(), citm) }
apache-2.0
6013f6d29a765e3ad16e0a54512703c5
33.228571
112
0.749583
3.864516
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/ConfirmComputationParticipant.kt
1
6231
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers import com.google.cloud.spanner.Value import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.common.identity.InternalId import org.wfanet.measurement.gcloud.spanner.bufferUpdateMutation import org.wfanet.measurement.gcloud.spanner.set import org.wfanet.measurement.internal.kingdom.ComputationParticipant import org.wfanet.measurement.internal.kingdom.ConfirmComputationParticipantRequest import org.wfanet.measurement.internal.kingdom.Measurement import org.wfanet.measurement.internal.kingdom.copy import org.wfanet.measurement.kingdom.deploy.common.DuchyIds import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.ComputationParticipantNotFoundByComputationException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.ComputationParticipantStateIllegalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementStateIllegalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.ComputationParticipantReader import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.computationParticipantsInState private val NEXT_COMPUTATION_PARTICIPANT_STATE = ComputationParticipant.State.READY /** * Sets participant details for a computationParticipant in the database. * * Throws a subclass of [KingdomInternalException] on [execute]. * @throws [ComputationParticipantNotFoundByComputationException] ComputationParticipant not found * @throws [ComputationParticipantStateIllegalException] ComputationParticipant state is not * REQUISITION_PARAMS_SET * @throws [DuchyNotFoundException] Duchy not found */ class ConfirmComputationParticipant(private val request: ConfirmComputationParticipantRequest) : SpannerWriter<ComputationParticipant, ComputationParticipant>() { override suspend fun TransactionScope.runTransaction(): ComputationParticipant { val duchyId = DuchyIds.getInternalId(request.externalDuchyId) ?: throw DuchyNotFoundException(request.externalDuchyId) val computationParticipantResult: ComputationParticipantReader.Result = ComputationParticipantReader() .readByExternalComputationId( transactionContext, ExternalId(request.externalComputationId), InternalId(duchyId) ) ?: throw ComputationParticipantNotFoundByComputationException( ExternalId(request.externalComputationId), request.externalDuchyId ) { "ComputationParticipant for external computation ID ${request.externalComputationId} " + "and external duchy ID ${request.externalDuchyId} not found" } val computationParticipant = computationParticipantResult.computationParticipant val measurementId = computationParticipantResult.measurementId val measurementConsumerId = computationParticipantResult.measurementConsumerId val measurementState = computationParticipantResult.measurementState if (measurementState != Measurement.State.PENDING_PARTICIPANT_CONFIRMATION) { throw MeasurementStateIllegalException( ExternalId(computationParticipant.externalMeasurementConsumerId), ExternalId(computationParticipant.externalMeasurementId), measurementState ) { "Measurement for external computation Id ${request.externalComputationId} " + "and external duchy ID ${request.externalDuchyId} has the wrong state. " + "It should have been in state ${Measurement.State.PENDING_PARTICIPANT_CONFIRMATION} " + "but was in state $measurementState" } } if (computationParticipant.state != ComputationParticipant.State.REQUISITION_PARAMS_SET) { throw ComputationParticipantStateIllegalException( ExternalId(request.externalComputationId), request.externalDuchyId, computationParticipant.state ) { "ComputationParticipant for external computation Id ${request.externalComputationId} " + "and external duchy ID ${request.externalDuchyId} has the wrong state. " + "It should have been in state ${ComputationParticipant.State.REQUISITION_PARAMS_SET} " + "but was in state ${computationParticipant.state}" } } transactionContext.bufferUpdateMutation("ComputationParticipants") { set("MeasurementConsumerId" to measurementConsumerId) set("MeasurementId" to measurementId) set("DuchyId" to duchyId) set("UpdateTime" to Value.COMMIT_TIMESTAMP) set("State" to NEXT_COMPUTATION_PARTICIPANT_STATE) } val otherDuchyIds: List<InternalId> = DuchyIds.entries.map { InternalId(it.internalDuchyId) }.filter { it.value != duchyId } if ( computationParticipantsInState( transactionContext, otherDuchyIds, InternalId(measurementConsumerId), InternalId(measurementId), NEXT_COMPUTATION_PARTICIPANT_STATE ) ) { updateMeasurementState( InternalId(measurementConsumerId), InternalId(measurementId), Measurement.State.PENDING_COMPUTATION ) } return computationParticipant.copy { state = NEXT_COMPUTATION_PARTICIPANT_STATE } } override fun ResultScope<ComputationParticipant>.buildResult(): ComputationParticipant { return checkNotNull(transactionResult).copy { updateTime = commitTimestamp.toProto() } } }
apache-2.0
01448053982d73f7f4ca035253eccaa0
46.204545
119
0.772589
5.196831
false
false
false
false
sabi0/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipWithActionRenderer.kt
2
13528
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("MayBeConstant") package com.intellij.codeInsight.daemon.impl import com.intellij.codeInsight.daemon.DaemonBundle import com.intellij.codeInsight.daemon.impl.tooltips.TooltipActionProvider.isShowActions import com.intellij.codeInsight.daemon.impl.tooltips.TooltipActionProvider.setShowActions import com.intellij.codeInsight.hint.HintManagerImpl import com.intellij.codeInsight.hint.LineTooltipRenderer import com.intellij.icons.AllIcons import com.intellij.ide.TooltipEvent import com.intellij.ide.actions.ActionsCollector import com.intellij.ide.ui.UISettings import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionMenuItem import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.TooltipAction import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.keymap.KeymapUtil.getActiveKeymapShortcuts import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.GraphicsConfig import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.* import com.intellij.ui.components.JBLabel import com.intellij.util.ui.GridBag import com.intellij.util.ui.Html import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.* import java.awt.event.KeyEvent import java.awt.event.MouseEvent import java.awt.geom.RoundRectangle2D import java.util.* import javax.swing.JComponent import javax.swing.JPanel import javax.swing.KeyStroke import javax.swing.MenuSelectionManager import javax.swing.event.HyperlinkEvent val runActionCustomShortcutSet: CustomShortcutSet = CustomShortcutSet( KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK or KeyEvent.ALT_DOWN_MASK)) internal class DaemonTooltipWithActionRenderer(text: String?, private val tooltipAction: TooltipAction?, width: Int, comparable: Array<Any>) : DaemonTooltipRenderer(text, width, comparable) { override fun dressDescription(editor: Editor, tooltipText: String, expand: Boolean): String { if (!LineTooltipRenderer.isActiveHtml(myText!!) || expand) { return super.dressDescription(editor, tooltipText, expand) } val problems = getProblems(tooltipText) val text = StringBuilder() StringUtil.join(problems, { param -> val ref = getLinkRef(param) if (ref != null) { getHtmlForProblemWithLink(param!!) } else { UIUtil.getHtmlBody(Html(param).setKeepFont(true)) } }, UIUtil.BORDER_LINE, text) return text.toString() } override fun getHtmlForProblemWithLink(problem: String): String { //remove "more... (keymap)" info val html = Html(problem).setKeepFont(true) val extendMessage = DaemonBundle.message("inspection.extended.description") var textToProcess = UIUtil.getHtmlBody(html) val indexOfMore = textToProcess.indexOf(extendMessage) if (indexOfMore < 0) return textToProcess val keymapStartIndex = textToProcess.indexOf("(", indexOfMore) if (keymapStartIndex > 0) { val keymapEndIndex = textToProcess.indexOf(")", keymapStartIndex) if (keymapEndIndex > 0) { textToProcess = textToProcess.substring(0, keymapStartIndex) + textToProcess.substring(keymapEndIndex + 1, textToProcess.length) } } return textToProcess.replace(extendMessage, "") } override fun fillPanel(editor: Editor, grid: JPanel, hint: LightweightHint, hintHint: HintHint, actions: ArrayList<AnAction>, tooltipReloader: TooltipReloader) { super.fillPanel(editor, grid, hint, hintHint, actions, tooltipReloader) val hasMore = LineTooltipRenderer.isActiveHtml(myText!!) if (tooltipAction == null && !hasMore) return val settingsComponent = createSettingsComponent(hintHint, tooltipReloader, hasMore) val settingsConstraints = GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, JBUI.insets(4, 7, 4, 4), 0, 0) grid.add(settingsComponent, settingsConstraints) if (isShowActions()) { addActionsRow(hintHint, hint, editor, actions, grid) } } private fun addActionsRow(hintHint: HintHint, hint: LightweightHint, editor: Editor, actions: ArrayList<AnAction>, grid: JComponent) { if (tooltipAction == null || !hintHint.isAwtTooltip) return val buttons = JPanel(GridBagLayout()) val wrapper = createActionPanelWithBackground(hint, grid) wrapper.add(buttons, BorderLayout.WEST) buttons.border = JBUI.Borders.empty() buttons.isOpaque = false val runFixAction = Runnable { hint.hide() tooltipAction.execute(editor) } val shortcutRunActionText = KeymapUtil.getShortcutsText(runActionCustomShortcutSet.shortcuts) val shortcutShowAllActionsText = getKeymap(IdeActions.ACTION_SHOW_INTENTION_ACTIONS) val gridBag = GridBag() .fillCellHorizontally() .anchor(GridBagConstraints.WEST) buttons.add(createActionLabel(tooltipAction.text, runFixAction, hintHint.textBackground), gridBag.next().insets(5, 8, 5, 4)) buttons.add(createKeymapHint(shortcutRunActionText), gridBag.next().insets(0, 4, 0, 12)) val showAllFixes = Runnable { hint.hide() tooltipAction.showAllActions(editor) } buttons.add(createActionLabel("More actions...", showAllFixes, hintHint.textBackground), gridBag.next().insets(5, 12, 5, 4)) buttons.add(createKeymapHint(shortcutShowAllActionsText), gridBag.next().fillCellHorizontally().insets(0, 4, 0, 20)) actions.add(object : AnAction() { override fun actionPerformed(e: AnActionEvent) { runFixAction.run() } init { registerCustomShortcutSet(runActionCustomShortcutSet, editor.contentComponent) } }) actions.add(object : AnAction() { override fun actionPerformed(e: AnActionEvent) { showAllFixes.run() } init { registerCustomShortcutSet(getActiveKeymapShortcuts(IdeActions.ACTION_SHOW_INTENTION_ACTIONS), editor.contentComponent) } }) val buttonsConstraints = GridBagConstraints(0, 1, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, JBUI.insetsTop(0), 0, 0) grid.add(wrapper, buttonsConstraints) } private fun createActionPanelWithBackground(hint: LightweightHint, grid: JComponent): JPanel { val wrapper: JPanel = object : JPanel(BorderLayout()) { override fun paint(g: Graphics?) { g!!.color = UIUtil.getToolTipActionBackground() val graphics2D = g as Graphics2D val cfg = GraphicsConfig(g) cfg.setAntialiasing(true) graphics2D.fill(RoundRectangle2D.Double(1.0, 0.0, bounds.width - 2.5, (bounds.height / 2).toDouble(), 0.0, 0.0)) val arc = BalloonImpl.ARC.toDouble() val double = RoundRectangle2D.Double(1.0, 0.0, bounds.width - 2.5, (bounds.height - 1).toDouble(), arc, arc) graphics2D.fill(double) cfg.restore() super.paint(g) } } wrapper.isOpaque = false wrapper.border = JBUI.Borders.empty() return wrapper } private fun getKeymap(key: String): String { val keymapManager = KeymapManager.getInstance() if (keymapManager != null) { val keymap = keymapManager.activeKeymap return KeymapUtil.getShortcutsText(keymap.getShortcuts(key)) } return "" } private fun createKeymapHint(shortcutRunAction: String): JComponent { val fixHint = object : JBLabel(shortcutRunAction) { override fun getForeground(): Color { return getKeymapColor() } } fixHint.border = JBUI.Borders.empty() fixHint.font = getActionFont() return fixHint } override fun createRenderer(text: String?, width: Int): LineTooltipRenderer { return DaemonTooltipWithActionRenderer(text, tooltipAction, width, equalityObjects) } override fun canAutoHideOn(event: TooltipEvent): Boolean { if (isOwnAction(event.action)) { return false } if (MenuSelectionManager.defaultManager().selectedPath.isNotEmpty()) { return false } val inputEvent = event.inputEvent if (inputEvent is MouseEvent) { val source = inputEvent.source if (source is ActionMenuItem && isOwnAction(source.anAction)) { return false } } return super.canAutoHideOn(event) } private fun isOwnAction(action: AnAction?) = action is ShowDocAction || action is ShowActionsAction || action is SettingsActionGroup private class SettingsActionGroup(actions: List<AnAction>) : DefaultActionGroup(actions), HintManagerImpl.ActionToIgnore, DumbAware { init { isPopup = true } } override fun isContentAction(dressedText: String?): Boolean { return super.isContentAction(dressedText) || tooltipAction != null } private fun createSettingsComponent(hintHint: HintHint, reloader: TooltipReloader, hasMore: Boolean): JComponent { val presentation = Presentation() presentation.icon = AllIcons.Actions.More val actions = mutableListOf<AnAction>() actions.add(ShowActionsAction(reloader, tooltipAction != null)) val docAction = ShowDocAction(reloader, hasMore) actions.add(docAction) val actionGroup = SettingsActionGroup(actions) val settingsButton = object : ActionButton(actionGroup, presentation, ActionPlaces.UNKNOWN, Dimension(18, 18)) { override fun paintComponent(g: Graphics?) { val state = popState if (state == ActionButtonComponent.POPPED && UIUtil.isUnderDarcula()) { val look = buttonLook look.paintBackground(g!!, this, getSettingsIconHoverBackgroundColor()) look.paintIcon(g, this, icon) look.paintBorder(g, this) return } paintButtonLook(g) } } settingsButton.setNoIconsInPopup(true) settingsButton.border = JBUI.Borders.empty() settingsButton.isOpaque = false val wrapper = JPanel(BorderLayout()) wrapper.add(settingsButton, BorderLayout.EAST) wrapper.border = JBUI.Borders.empty() wrapper.background = hintHint.textBackground wrapper.isOpaque = false return wrapper } private inner class ShowActionsAction(val reloader: TooltipReloader, val isEnabled: Boolean) : ToggleAction( "Show Quick Fixes"), HintManagerImpl.ActionToIgnore { override fun isSelected(e: AnActionEvent): Boolean { return isShowActions() } override fun setSelected(e: AnActionEvent, state: Boolean) { setShowActions(state) reloader.reload(myCurrentWidth > 0) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = isEnabled super.update(e) } } private inner class ShowDocAction(val reloader: TooltipReloader, val isEnabled: Boolean) : ToggleAction( "Show Inspection Description"), HintManagerImpl.ActionToIgnore, DumbAware, PopupAction { init { shortcutSet = getActiveKeymapShortcuts(IdeActions.ACTION_SHOW_ERROR_DESCRIPTION) } override fun isSelected(e: AnActionEvent): Boolean { return myCurrentWidth > 0 } override fun setSelected(e: AnActionEvent, state: Boolean) { ActionsCollector.getInstance().record("tooltip.actions.show.description.gear", this::class.java) reloader.reload(state) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = isEnabled super.update(e) } } } fun createActionLabel(text: String, action: Runnable, background: Color): HyperlinkLabel { val label = object : HyperlinkLabel(text, background) { override fun getTextOffset(): Int { return 0 } } label.border = JBUI.Borders.empty() label.addHyperlinkListener(object : HyperlinkAdapter() { override fun hyperlinkActivated(e: HyperlinkEvent) { action.run() } }) val toolTipFont = getActionFont() label.font = toolTipFont return label } private fun getKeymapColor(): Color { return JBColor.namedColor("tooltips.actions.keymap.text.color", JBColor(0x99a4ad, 0x919191)) } private fun getSettingsIconHoverBackgroundColor(): Color { return JBColor.namedColor("tooltips.actions.settings.icon.background.color", JBColor(0xe9eac0, 0x44494c)) } private fun getActionFont(): Font? { val toolTipFont = UIUtil.getToolTipFont() if (toolTipFont == null || SystemInfo.isWindows) return toolTipFont //if font was changed from default we dont have a good heuristic to customize it if (JBUI.Fonts.label() != toolTipFont || UISettings.instance.overrideLafFonts) return toolTipFont if (SystemInfo.isMac) { return toolTipFont.deriveFont(toolTipFont.size - 1f) } if (SystemInfo.isLinux) { return toolTipFont.deriveFont(toolTipFont.size - 1f) } return toolTipFont }
apache-2.0
8cdecf7729d94eb6dec4f82411a7ed31
34.137662
140
0.696703
4.428151
false
false
false
false
lllllT/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/data/repository/AccountDataRepository.kt
2
1651
package com.bl_lia.kirakiratter.data.repository import com.bl_lia.kirakiratter.data.repository.datasource.account.AccountDataStoreFactory import com.bl_lia.kirakiratter.domain.entity.Account import com.bl_lia.kirakiratter.domain.entity.Relationship import com.bl_lia.kirakiratter.domain.entity.Status import com.bl_lia.kirakiratter.domain.repository.AccountRepository import io.reactivex.Single import javax.inject.Inject import javax.inject.Singleton @Singleton class AccountDataRepository @Inject constructor( private val accountDataStoreFactory: AccountDataStoreFactory ): AccountRepository { override fun statuses(id: Int): Single<List<Status>> = accountDataStoreFactory.create().status(id) override fun moreStatuses(id: Int, maxId: Int?, sinceId: Int?): Single<List<Status>> = accountDataStoreFactory.create().moreStatus(id, maxId, sinceId) override fun relationship(id: Int): Single<Relationship> = accountDataStoreFactory.create().relationship(id) override fun follow(id: Int): Single<Relationship> = accountDataStoreFactory.create().follow(id) override fun unfollow(id: Int): Single<Relationship> = accountDataStoreFactory.create().unfollow(id) override fun verifyCredentials(): Single<Account> = accountDataStoreFactory.createCache() .verifyCredentials() .flatMap { account -> if (account.isInvalid) { accountDataStoreFactory.createApi().verifyCredentials() } else { Single.just(account) } } }
mit
9384ac588931208a014746cec3cb70f0
46.2
154
0.695942
4.972892
false
false
false
false
ziggy42/Blum
app/src/main/java/com/andreapivetta/blu/ui/newtweet/NewTweetPresenter.kt
1
4839
package com.andreapivetta.blu.ui.newtweet import com.andreapivetta.blu.common.utils.Patterns import com.andreapivetta.blu.data.model.Tweet import com.andreapivetta.blu.data.twitter.TweetsQueue import com.andreapivetta.blu.data.twitter.getTweetUrl import com.andreapivetta.blu.ui.base.BasePresenter import java.io.InputStream /** * Created by andrea on 20/05/16. */ class NewTweetPresenter : BasePresenter<NewTweetMvpView>() { private val MAX_URL_LENGTH = 23 // it will change private var charsLeft: Int = 140 private var lastAtIndex: Int = -1 fun charsLeft() = charsLeft fun afterTextChanged(text: String) { checkLength(text) } fun onTextChanged(text: String, start: Int, count: Int) { var query: String? = null val selectedText = text.substring(start, start + count) if (selectedText.length > 1) { if (start > 0 && text[(start - 1)] == '@') { query = selectedText lastAtIndex = start - 1 } else if (selectedText.startsWith("@")) { query = selectedText.substring(1) lastAtIndex = start } } else if (text.isNotEmpty()) { val buffer = StringBuilder() var i = mvpView!!.getSelectionStart() - 1 if (i >= 0) { var c = text[i] while (c != '@' && c != ' ' && i > 0) { buffer.append(c) i-- c = text[i] } if (c == '@') { query = buffer.reverse().toString() lastAtIndex = i } } } if (query != null) { mvpView?.showSuggestions() mvpView?.filterUsers(query) } else { mvpView?.hideSuggestions() } } fun onUserSelected(screenName: String) { val text = mvpView?.getTweet() val selectionStart = mvpView?.getSelectionStart() mvpView?.setText(text?.substring(0, lastAtIndex + 1) + screenName + text?.substring(selectionStart!!, text.length), lastAtIndex + screenName.length + 1) mvpView?.hideSuggestions() } fun sendTweet(images: List<InputStream>) { when { charsLeft < 0 -> mvpView?.showTooManyCharsError() images.isEmpty() && mvpView?.getTweet().isNullOrEmpty() -> mvpView?.showEmptyTweetError() images.isEmpty() -> sendTweet(mvpView?.getTweet()) else -> sendTweet(mvpView?.getTweet(), images) } } fun sendTweet(quotedTweet: Tweet) { when { charsLeft < 0 -> mvpView?.showTooManyCharsError() else -> sendTweet("${mvpView?.getTweet()} ${getTweetUrl(quotedTweet)}") } } fun reply(inReplyToStatusId: Long, images: List<InputStream>) { when { charsLeft < 0 -> mvpView?.showTooManyCharsError() images.isEmpty() && mvpView?.getTweet().isNullOrEmpty() -> mvpView?.showEmptyTweetError() images.isEmpty() -> sendTweet(mvpView?.getTweet(), inReplyToStatusId) else -> sendTweet(mvpView?.getTweet(), images, inReplyToStatusId) } } fun takePicture(nImages: Int) { if (nImages < 4) mvpView?.takePicture() else mvpView?.showTooManyImagesError() } fun grabImage(nImages: Int) { if (nImages < 4) mvpView?.grabImage() else mvpView?.showTooManyImagesError() } private fun checkLength(text: String) { var wordsLength = 0 var urls = 0 text.split(" ").forEach { if (isUrl(it)) urls++ else wordsLength += it.length } charsLeft = 140 - text.count { it == ' ' } - wordsLength - (urls * MAX_URL_LENGTH) mvpView?.refreshToolbar() } private fun isUrl(text: String) = Patterns.WEB_URL.matcher(text).matches() private fun sendTweet(status: String?) { if (status != null) TweetsQueue.add(TweetsQueue.StatusUpdate.valueOf(status)) mvpView?.close() } private fun sendTweet(status: String?, images: List<InputStream>) { if (status != null) TweetsQueue.add(TweetsQueue.StatusUpdate.valueOf(status, images)) mvpView?.close() } private fun sendTweet(status: String?, inReplyToStatusId: Long) { if (status != null) TweetsQueue.add(TweetsQueue.StatusUpdate.valueOf(status, inReplyToStatusId)) mvpView?.close() } private fun sendTweet(status: String?, images: List<InputStream>, inReplyToStatusId: Long) { if (status != null) TweetsQueue.add(TweetsQueue.StatusUpdate.valueOf(status, images, inReplyToStatusId)) mvpView?.close() } }
apache-2.0
d7ec470921c9bb119f453a2f5ca89116
31.92517
100
0.571812
4.419178
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/run/latex/LatexOutputPath.kt
1
6486
package nl.hannahsten.texifyidea.run.latex import com.intellij.execution.ExecutionException import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.application.runReadAction import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.settings.sdk.LatexSdkUtil import nl.hannahsten.texifyidea.util.files.FileUtil import nl.hannahsten.texifyidea.util.files.createExcludedDir import nl.hannahsten.texifyidea.util.files.psiFile import nl.hannahsten.texifyidea.util.files.referencedFileSet import java.io.File /** * Output file as a virtual file, or a promise to provide a path that can be constructed when the run configuration is actually created. * This allows for custom output paths in the run configuration template. * * Supported placeholders: * - $contentRoot * - $mainFile * * @param variant: out or auxil */ class LatexOutputPath(private val variant: String, var contentRoot: VirtualFile?, var mainFile: VirtualFile?, private val project: Project) { companion object { const val projectDirString = "{projectDir}" const val mainFileString = "{mainFileParent}" } fun clone(): LatexOutputPath { return LatexOutputPath(variant, contentRoot, mainFile, project).apply { if ([email protected]()) this.pathString = [email protected] } } // Acts as a sort of cache var virtualFile: VirtualFile? = null var pathString: String = "$projectDirString/$variant" /** * Get the output path based on the values of [virtualFile] and [pathString], create it if it does not exist. */ fun getAndCreatePath(): VirtualFile? { // No auxil directory should be present/created when there's no MiKTeX around, assuming that TeX Live does not support this if (!LatexSdkUtil.isMiktexAvailable && variant == "auxil") { return null } // Just to be sure, avoid using jetbrains /bin path as output if (pathString.isBlank()) { pathString = "$projectDirString/$variant" } // Caching of the result return getPath().also { virtualFile = it } } private fun getPath(): VirtualFile? { // When we previously made the mistake of calling findRelativePath with an empty string, the output path will be set to thee /bin folder of IntelliJ. Fix that here, to be sure if (virtualFile?.path?.endsWith("/bin") == true) { virtualFile = null } if (virtualFile != null) { return virtualFile!! } else { val pathString = if (pathString.contains(projectDirString)) { if (contentRoot == null) return if (mainFile != null) mainFile?.parent else null pathString.replace(projectDirString, contentRoot?.path ?: return null) } else { if (mainFile == null) return null pathString.replace(mainFileString, mainFile?.parent?.path ?: return null) } val path = LocalFileSystem.getInstance().findFileByPath(pathString) if (path != null && path.isDirectory) { return path } else { // Try to create the path createOutputPath(pathString)?.let { return it } } // Path is invalid (perhaps the user provided an invalid path) Notification("LaTeX", "Invalid output path", "Output path $pathString of the run configuration could not be created, trying default path ${contentRoot?.path + "/" + variant}", NotificationType.WARNING).notify(project) // Create and return default path if (contentRoot != null) { val defaultPathString = contentRoot!!.path + "/" + variant createOutputPath(defaultPathString)?.let { return it } } if (contentRoot != null) { return contentRoot!! } return null } } private fun getDefaultOutputPath(): VirtualFile? { if (mainFile == null) return null var defaultOutputPath: VirtualFile? = null runReadAction { val moduleRoot = ProjectRootManager.getInstance(project).fileIndex.getContentRootForFile(mainFile!!) if (moduleRoot?.path != null) { defaultOutputPath = LocalFileSystem.getInstance().findFileByPath(moduleRoot.path + "/" + variant) } } return defaultOutputPath } /** * Whether the current output path is the default. */ fun isDefault() = getDefaultOutputPath() == virtualFile /** * Creates the output directory to place all produced files. */ private fun createOutputPath(outPath: String): VirtualFile? { val mainFile = mainFile ?: return null if (outPath.isBlank()) return null val fileIndex = ProjectRootManager.getInstance(project).fileIndex // Create output path for non-MiKTeX systems (MiKTeX creates it automatically) val module = fileIndex.getModuleForFile(mainFile, false) if (File(outPath).mkdirs()) { module?.createExcludedDir(outPath) return LocalFileSystem.getInstance().refreshAndFindFileByPath(outPath) } return null } /** * Copy subdirectories of the source directory to the output directory for includes to work in non-MiKTeX systems */ @Throws(ExecutionException::class) fun updateOutputSubDirs() { val includeRoot = mainFile?.parent val outPath = virtualFile?.path ?: return val files: Set<PsiFile> try { files = mainFile?.psiFile(project)?.referencedFileSet() ?: emptySet() } catch (e: IndexNotReadyException) { throw ExecutionException("Please wait until the indices are built.", e) } // Create output paths (see issue #70 on GitHub) files.asSequence() .mapNotNull { FileUtil.pathRelativeTo(includeRoot?.path ?: return@mapNotNull null, it.virtualFile.parent.path) } .forEach { File(outPath + it).mkdirs() } } }
mit
5db2299b2dbfd5c5883c8c71402d1b3d
38.315152
229
0.652482
5.027907
false
false
false
false
googlecast/CastVideos-android
app-kotlin/src/main/kotlin/com/google/sample/cast/refplayer/queue/ui/QueueListAdapter.kt
1
15232
/* * Copyright 2022 Google LLC. 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.google.sample.cast.refplayer.queue.ui import android.util.Log import android.content.Context import androidx.recyclerview.widget.RecyclerView import android.view.ViewGroup import android.view.View import android.view.LayoutInflater import com.google.sample.cast.refplayer.R import com.google.android.gms.cast.framework.CastContext import com.android.volley.toolbox.NetworkImageView import android.widget.TextView import com.android.volley.toolbox.ImageLoader import android.widget.ImageView import android.widget.ImageButton import android.widget.ProgressBar import android.view.View.OnTouchListener import android.view.MotionEvent import com.google.android.gms.cast.framework.media.MediaQueue import com.google.android.gms.cast.framework.media.MediaQueueRecyclerViewAdapter import com.android.volley.toolbox.ImageLoader.ImageListener import com.android.volley.VolleyError import com.android.volley.toolbox.ImageLoader.ImageContainer import androidx.core.view.MotionEventCompat import androidx.annotation.IntDef import androidx.recyclerview.widget.ItemTouchHelper import com.google.android.gms.cast.* import com.google.sample.cast.refplayer.queue.QueueDataProvider import com.google.sample.cast.refplayer.utils.CustomVolleyRequest import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy /** * An adapter to show the list of queue items. */ class QueueListAdapter( mediaQueue: MediaQueue, context: Context, dragStartListener: OnStartDragListener ) : MediaQueueRecyclerViewAdapter<QueueListAdapter.QueueItemViewHolder>(mediaQueue), QueueItemTouchHelperCallback.ItemTouchHelperAdapter { private val mAppContext: Context private val mProvider: QueueDataProvider? private val mDragStartListener: OnStartDragListener private val mItemViewOnClickListener: View.OnClickListener private var mEventListener: EventListener? = null private var mImageLoader: ImageLoader? = null private val myMediaQueueCallback: ListAdapterMediaQueueCallback = ListAdapterMediaQueueCallback() init { mAppContext = context.applicationContext mProvider = QueueDataProvider.Companion.getInstance(context) mDragStartListener = dragStartListener mItemViewOnClickListener = View.OnClickListener { view -> if (view.getTag(R.string.queue_tag_item) != null) { val item = view.getTag(R.string.queue_tag_item) as MediaQueueItem Log.d(TAG, item.itemId.toString()) } onItemViewClick(view) } getMediaQueue().registerCallback(myMediaQueueCallback) setHasStableIds(false) } private fun onItemViewClick(view: View) { mEventListener?.onItemViewClicked(view) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QueueItemViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.queue_row, parent, false) return QueueItemViewHolder(view) } override fun onBindViewHolder(holder: QueueItemViewHolder, position: Int) { Log.d(TAG, "[upcoming] onBindViewHolder() for position: $position") holder.setIsRecyclable(false) val item = getItem(position) if (item == null) { holder.updateControlsStatus(QueueItemViewHolder.NONE) } else if (mProvider!!.isCurrentItem(item)) { holder.updateControlsStatus(QueueItemViewHolder.CURRENT) updatePlayPauseButtonImageResource(holder.mPlayPause) } else if (mProvider.isUpcomingItem(item)) { holder.updateControlsStatus(QueueItemViewHolder.UPCOMING) } else { holder.updateControlsStatus(QueueItemViewHolder.NONE) } holder.mContainer.setTag(R.string.queue_tag_item, item) holder.mPlayPause.setTag(R.string.queue_tag_item, item) holder.mPlayUpcoming.setTag(R.string.queue_tag_item, item) holder.mStopUpcoming.setTag(R.string.queue_tag_item, item) // Set listeners holder.mContainer.setOnClickListener(mItemViewOnClickListener) holder.mPlayPause.setOnClickListener(mItemViewOnClickListener) holder.mPlayUpcoming.setOnClickListener(mItemViewOnClickListener) holder.mStopUpcoming.setOnClickListener(mItemViewOnClickListener) val info = item?.media var imageUrl: String? = null if (info != null && info.metadata != null) { val metaData = info.metadata holder.mTitleView.text = metaData!!.getString(MediaMetadata.KEY_TITLE) holder.mDescriptionView.text = metaData.getString(MediaMetadata.KEY_SUBTITLE) val images = metaData.images if (images != null && images.isNotEmpty()) { imageUrl = images[0].url.toString() } } else { holder.mTitleView.text = null holder.mDescriptionView.text = null } if (imageUrl != null) { mImageLoader = CustomVolleyRequest.Companion.getInstance(mAppContext)?.imageLoader val imageListener: ImageListener = object : ImageListener { override fun onErrorResponse(error: VolleyError) { holder.mProgressLoading.visibility = View.GONE holder.mImageView.setErrorImageResId(R.drawable.ic_action_alerts_and_states_warning) } override fun onResponse(response: ImageContainer, isImmediate: Boolean) { if (response.bitmap != null) { holder.mProgressLoading.visibility = View.GONE holder.mImageView.setImageBitmap(response.bitmap) } } } holder.mImageView.setImageUrl( mImageLoader!![imageUrl, imageListener].requestUrl, mImageLoader ) } else { holder.mProgressLoading.postDelayed({ holder.mProgressLoading.visibility = View.GONE holder.mImageView.setDefaultImageResId(R.drawable.cast_album_art_placeholder) holder.mImageView.setImageResource(R.drawable.cast_album_art_placeholder) }, 3000) } holder.mDragHandle.setOnTouchListener(OnTouchListener { view, event -> if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) { mDragStartListener.onStartDrag(holder) } else if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_BUTTON_RELEASE) { view.clearFocus() view.clearAnimation() holder.setIsRecyclable(false) return@OnTouchListener true } false }) } override fun onItemDismiss(position: Int) { mProvider!!.removeFromQueue(position) } override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean { if (fromPosition == toPosition) { return false } mProvider!!.moveItem(fromPosition, toPosition) notifyItemMoved(fromPosition, toPosition) return true } override fun dispose() { super.dispose() //unregister callback val queue = mediaQueue if (queue != null) { queue.unregisterCallback(myMediaQueueCallback) } } fun setEventListener(eventListener: EventListener?) { mEventListener = eventListener } private fun updatePlayPauseButtonImageResource(button: ImageButton) { val castSession = CastContext.getSharedInstance(mAppContext) .sessionManager.currentCastSession val remoteMediaClient = castSession?.remoteMediaClient if (remoteMediaClient == null) { button.visibility = View.GONE return } val status = remoteMediaClient.playerState when (status) { MediaStatus.PLAYER_STATE_PLAYING -> button.setImageResource(PAUSE_RESOURCE) MediaStatus.PLAYER_STATE_PAUSED -> button.setImageResource(PLAY_RESOURCE) else -> button.visibility = View.GONE } } /** * Handles ListAdapter notification upon MediaQueue data changes. */ internal inner class ListAdapterMediaQueueCallback : MediaQueue.Callback() { override fun itemsInsertedInRange(start: Int, end: Int) { notifyItemRangeInserted(start, end) } override fun itemsReloaded() { notifyDataSetChanged() } override fun itemsRemovedAtIndexes(ints: IntArray) { for (i in ints) { notifyItemRemoved(i) } } override fun itemsReorderedAtIndexes(list: List<Int>, i: Int) { notifyDataSetChanged() } override fun itemsUpdatedAtIndexes(ints: IntArray) { for (i in ints) { notifyItemChanged(i) } } override fun mediaQueueChanged() { notifyDataSetChanged() } } class QueueItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), ItemTouchHelperViewHolder { private val mContext: Context val mPlayPause: ImageButton private val mControls: View private val mUpcomingControls: View val mPlayUpcoming: ImageButton val mStopUpcoming: ImageButton var mImageView: NetworkImageView var mContainer: ViewGroup var mDragHandle: ImageView var mTitleView: TextView var mDescriptionView: TextView var mProgressLoading: ProgressBar override fun onItemSelected() { } override fun onItemClear() { itemView.setBackgroundColor(0) } @Retention(RetentionPolicy.SOURCE) @IntDef(CURRENT, UPCOMING, NONE) private annotation class ControlStatus init { mContext = itemView.context mContainer = itemView.findViewById<View>(R.id.container) as ViewGroup mDragHandle = itemView.findViewById<View>(R.id.drag_handle) as ImageView mTitleView = itemView.findViewById<View>(R.id.textView1) as TextView mDescriptionView = itemView.findViewById<View>(R.id.textView2) as TextView mImageView = itemView.findViewById<View>(R.id.imageView1) as NetworkImageView mPlayPause = itemView.findViewById<View>(R.id.play_pause) as ImageButton mControls = itemView.findViewById(R.id.controls) mUpcomingControls = itemView.findViewById(R.id.controls_upcoming) mPlayUpcoming = itemView.findViewById<View>(R.id.play_upcoming) as ImageButton mStopUpcoming = itemView.findViewById<View>(R.id.stop_upcoming) as ImageButton mProgressLoading = itemView.findViewById<View>(R.id.item_progress) as ProgressBar } fun updateControlsStatus(@ControlStatus status: Int) { var bgResId = R.drawable.bg_item_normal_state mTitleView.setTextAppearance(mContext, R.style.Base_TextAppearance_AppCompat_Subhead) mDescriptionView.setTextAppearance( mContext, R.style.Base_TextAppearance_AppCompat_Caption ) Log.d(TAG, "updateControlsStatus for status = $status") when (status) { CURRENT -> { bgResId = R.drawable.bg_item_normal_state mControls.visibility = View.VISIBLE mPlayPause.visibility = View.VISIBLE mUpcomingControls.visibility = View.GONE mDragHandle.setImageResource(DRAG_HANDLER_DARK_RESOURCE) } UPCOMING -> { mControls.visibility = View.VISIBLE mPlayPause.visibility = View.GONE mUpcomingControls.visibility = View.VISIBLE mDragHandle.setImageResource(DRAG_HANDLER_LIGHT_RESOURCE) bgResId = R.drawable.bg_item_upcoming_state mTitleView.setTextAppearance( mContext, R.style.TextAppearance_AppCompat_Small_Inverse ) mTitleView.setTextAppearance( mTitleView.context, R.style.Base_TextAppearance_AppCompat_Subhead_Inverse ) mDescriptionView.setTextAppearance( mContext, R.style.Base_TextAppearance_AppCompat_Caption ) } else -> { mControls.visibility = View.GONE mPlayPause.visibility = View.GONE mUpcomingControls.visibility = View.GONE mDragHandle.setImageResource(DRAG_HANDLER_DARK_RESOURCE) } } mContainer.setBackgroundResource(bgResId) super.itemView.requestLayout() } companion object { const val CURRENT = 0 const val UPCOMING = 1 const val NONE = 2 } } /** * Interface for catching clicks on the ViewHolder items */ interface EventListener { fun onItemViewClicked(view: View) } /** * Interface to notify an item ViewHolder of relevant callbacks from [ ]. */ interface ItemTouchHelperViewHolder { /** * Called when the [ItemTouchHelper] first registers an item as being moved or * swiped. * Implementations should update the item view to indicate it's active state. */ fun onItemSelected() /** * Called when the [ItemTouchHelper] has completed the move or swipe, and the active * item state should be cleared. */ fun onItemClear() } /** * Listener for manual initiation of a drag. */ interface OnStartDragListener { /** * Called when a view is requesting a start of a drag. */ fun onStartDrag(viewHolder: RecyclerView.ViewHolder?) } companion object { private const val TAG = "QueueListAdapter" private const val PLAY_RESOURCE = R.drawable.ic_play_arrow_grey600_48dp private const val PAUSE_RESOURCE = R.drawable.ic_pause_grey600_48dp private const val DRAG_HANDLER_DARK_RESOURCE = R.drawable.ic_drag_updown_grey_24dp private const val DRAG_HANDLER_LIGHT_RESOURCE = R.drawable.ic_drag_updown_white_24dp } }
apache-2.0
8675a9acf1176e6b30f005173e5566f9
39.298942
104
0.64719
5.007232
false
false
false
false
andreyfomenkov/green-cat
plugin/src/ru/fomenkov/plugin/repository/ClasspathOptimizer.kt
1
1881
package ru.fomenkov.plugin.repository import ru.fomenkov.plugin.util.CURRENT_DIR import ru.fomenkov.plugin.util.HOME_DIR import java.io.File class ClasspathOptimizer { fun optimize(classpath: Set<String>): Set<String> { return classpath .asSequence() .map(::Entry) .toSet() .asSequence() .map { entry -> entry.path } .filterNot { path -> path.endsWith("/lint.jar") } .filterNot { path -> path.endsWith("-api.jar") } .filter { path -> val file = File(path) file.isFile || file.isDirectory && (file.list() ?: emptyArray()).isNotEmpty() } .map { path -> if (path.startsWith(CURRENT_DIR)) { path.substring(CURRENT_DIR.length + 1, path.length) } else { toRelativePath(path) } }.toSet() } private fun toRelativePath(path: String): String { val partsCount = CURRENT_DIR.subSequence(HOME_DIR.length + 1, CURRENT_DIR.length).split("/").size val parts = path.split("/").filter { part -> part.isNotBlank() }.toMutableList() for (i in 0 until partsCount) { parts[i] = ".." } return parts.joinToString(separator = "/") } private data class Entry(val path: String) { private val id: String = if (path.contains("/transformed/")) { val parts = path.split("/") val index = parts.indexOfLast { part -> part == "transformed" } check(index != -1) { "Failed to get directory index" } parts.subList(index + 1, parts.size).joinToString(separator = "/") } else { path } override fun hashCode() = id.hashCode() override fun equals(other: Any?) = other == id } }
apache-2.0
9b275d97f31ae648243cb0404852a7dd
32.607143
105
0.532695
4.374419
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/playback/MediaPlayerPlayback.kt
1
12914
package com.simplecity.amp_library.playback import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.TimeInterpolator import android.animation.ValueAnimator import android.content.Context import android.media.AudioAttributes import android.media.MediaPlayer import android.net.Uri import android.os.PowerManager import android.text.TextUtils import android.util.Log import com.simplecity.amp_library.model.Song import com.simplecity.amp_library.utils.LogUtils import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import java.io.File internal class MediaPlayerPlayback(context: Context) : LocalPlayback(context), MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { private var currentMediaPlayer: MediaPlayer? = createMediaPlayer(context) private var nextMediaPlayer: MediaPlayer? = null override var isInitialized: Boolean = false private var isFadingDown: Boolean = false private var isFadingUp: Boolean = false private var fadeAnimator: ValueAnimator? = null override val isPlaying: Boolean get() = synchronized(this) { if (!isInitialized || isFadingDown) { return false } else { return currentMediaPlayer?.isPlaying ?: false || isFadingUp } } override val duration: Long get() = synchronized(this) { if (isInitialized) { try { return currentMediaPlayer?.duration?.toLong() ?: 0 } catch (e: IllegalStateException) { Log.e(TAG, "Error in getDuration() of MediaPlayerPlayback: " + e.localizedMessage) } } return 0 } override val position: Long get() = synchronized(this) { if (isInitialized) { try { return currentMediaPlayer?.currentPosition?.toLong() ?: 0 } catch (e: IllegalStateException) { Log.e(TAG, "Error in getPosition() of MediaPlayerPlayback: " + e.localizedMessage) } } return 0 } override val audioSessionId: Int get() = synchronized(this) { var sessionId = 0 if (isInitialized) { try { sessionId = currentMediaPlayer?.audioSessionId ?: 0 } catch (e: IllegalStateException) { Log.e(TAG, "Error in getAudioSessionId() of MediaPlayerPlayback: " + e.localizedMessage) } } return sessionId } override fun load(song: Song, playWhenReady: Boolean, seekPosition: Long, completion: ((Boolean) -> Unit)?) { synchronized(this) { fadeAnimator?.cancel() currentMediaPlayer?.let { currentMediaPlayer -> setDataSourceImpl(currentMediaPlayer, song.path) { success -> isInitialized = success if (isInitialized) { // Invalidate any old 'next data source', will be re-set via external call to setNextDataSource(). setNextDataSource(null) if (seekPosition != 0L) { seekTo(seekPosition) } if (playWhenReady) { start() } } completion?.invoke(isInitialized) } } } } private fun setDataSourceImpl(mediaPlayer: MediaPlayer, path: String, completion: (Boolean) -> Unit) { synchronized(this) { if (TextUtils.isEmpty(path)) { completion(false) } try { mediaPlayer.reset() if (path.startsWith("content://")) { val uri = Uri.parse(path) mediaPlayer.setDataSource(context, uri) } else { mediaPlayer.setDataSource(Uri.fromFile(File(path)).toString()) } mediaPlayer.setAudioAttributes( AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build() ) mediaPlayer.setOnPreparedListener { mediaPlayer.setOnPreparedListener(null) completion(true) } mediaPlayer.prepareAsync() } catch (e: Exception) { LogUtils.logException(TAG, "setDataSourceImpl failed. Path: [$path]", e) completion(false) } mediaPlayer.setOnCompletionListener(this) mediaPlayer.setOnErrorListener(this) } } override fun setNextDataSource(path: String?) { synchronized(this) { try { currentMediaPlayer?.setNextMediaPlayer(null) } catch (ignored: IllegalArgumentException) { // Nothing to do } releaseNextMediaPlayer() if (TextUtils.isEmpty(path)) { return } nextMediaPlayer = createMediaPlayer(context) nextMediaPlayer!!.audioSessionId = audioSessionId setDataSourceImpl(nextMediaPlayer!!, path!!) { success -> if (success) { try { currentMediaPlayer?.setNextMediaPlayer(nextMediaPlayer) } catch (e: Exception) { LogUtils.logException(TAG, "setNextDataSource failed - failed to call setNextMediaPlayer on currentMediaPlayer", e) releaseNextMediaPlayer() } } else { LogUtils.logException(TAG, "setDataSourceImpl failed for path: [$path]. Setting next media player to null", null) releaseNextMediaPlayer() } } } } private fun releaseNextMediaPlayer() { nextMediaPlayer?.release() nextMediaPlayer = null } override fun start() { synchronized(this) { super.start() fadeIn() try { currentMediaPlayer?.start() } catch (e: RuntimeException) { LogUtils.logException(TAG, "start() failed", e) } callbacks?.onPlayStateChanged(this) } } override fun stop() { synchronized(this) { super.stop() if (isInitialized) { try { currentMediaPlayer?.reset() } catch (e: IllegalStateException) { LogUtils.logException(TAG, "stop() failed", e) } isInitialized = false } callbacks?.onPlayStateChanged(this) } } /** * You cannot use this player anymore after calling release() */ override fun release() { synchronized(this) { stop() currentMediaPlayer?.release() } } override fun pause(fade: Boolean) { synchronized(this) { if (fade) { fadeOut() } else { if (isInitialized) { super.pause(fade) try { currentMediaPlayer?.pause() } catch (e: IllegalStateException) { Log.e(TAG, "Error pausing MediaPlayerPlayback: " + e.localizedMessage) } callbacks?.onPlayStateChanged(this) } } } } override fun seekTo(position: Long) { synchronized(this) { if (isInitialized) { try { currentMediaPlayer?.seekTo(position.toInt()) } catch (e: IllegalStateException) { Log.e(TAG, "Error seeking MediaPlayerPlayback: " + e.localizedMessage) } } } } override fun setVolume(volume: Float) { synchronized(this) { if (isInitialized) { try { currentMediaPlayer?.setVolume(volume, volume) } catch (e: IllegalStateException) { Log.e(TAG, "Error setting MediaPlayerPlayback volume: " + e.localizedMessage) } } } } override val resumeWhenSwitched: Boolean = false override fun onError(mp: MediaPlayer, what: Int, extra: Int): Boolean { when (what) { MediaPlayer.MEDIA_ERROR_SERVER_DIED -> { isInitialized = false currentMediaPlayer?.release() currentMediaPlayer = createMediaPlayer(context) callbacks?.onError(this, "Server died") return true } else -> { } } callbacks?.onError(this, "Unknown error") return false } override fun onCompletion(mediaPlayer: MediaPlayer) { if (mediaPlayer === currentMediaPlayer && nextMediaPlayer != null) { currentMediaPlayer?.release() currentMediaPlayer = nextMediaPlayer nextMediaPlayer = null callbacks?.onTrackEnded(this, true) } else { callbacks?.onTrackEnded(this, false) } } override fun updateLastKnownStreamPosition() { } private fun createMediaPlayer(context: Context): MediaPlayer { val mediaPlayer = MediaPlayer() mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK) return mediaPlayer } private fun fadeIn() { // Animator needs to run on thread with a looper. isFadingUp = true Observable.fromCallable { val currentVolume = fadeAnimator?.animatedValue as? Float ?: 0f fadeAnimator?.cancel() setVolume(currentVolume) fadeAnimator = ValueAnimator.ofFloat(currentVolume, 1f) fadeAnimator!!.duration = 250 fadeAnimator!!.interpolator = FadeInterpolator(2) fadeAnimator!!.addUpdateListener { animation -> setVolume(animation.animatedValue as Float) } fadeAnimator!!.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) isFadingUp = false } override fun onAnimationCancel(animation: Animator?) { super.onAnimationCancel(animation) fadeAnimator!!.removeAllListeners() isFadingUp = false } }) fadeAnimator!!.start() } .subscribeOn(AndroidSchedulers.mainThread()) .subscribe() } private fun fadeOut() { // Animator needs to run on thread with a looper. isFadingDown = true Observable.fromCallable { val currentVolume = fadeAnimator?.animatedValue as? Float ?: 1f fadeAnimator?.cancel() fadeAnimator = ValueAnimator.ofFloat(currentVolume, 0f) fadeAnimator!!.duration = 150 fadeAnimator!!.interpolator = FadeInterpolator(1) fadeAnimator!!.addUpdateListener { animation -> setVolume(animation.animatedValue as Float) } fadeAnimator!!.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) isFadingDown = false pause(false) } override fun onAnimationCancel(animation: Animator?) { super.onAnimationCancel(animation) fadeAnimator!!.removeAllListeners() isFadingDown = false } }) fadeAnimator!!.start() } .subscribeOn(AndroidSchedulers.mainThread()) .subscribe() } /** * @param multiplier exaggerates the logarithmic curve. * Higher numbers mean the majority of change occurs over the mid-section of the curve. * Numbers < 1.0 approximate a 'linear' curve. */ private class FadeInterpolator(private val multiplier: Int) : TimeInterpolator { override fun getInterpolation(input: Float): Float { return (Math.exp((input * multiplier).toDouble()) * input / Math.exp(multiplier.toDouble())).toFloat() } } companion object { private const val TAG = "MediaPlayerPlayback" } }
gpl-3.0
18dea285732a2282879f544229579d1e
32.632813
142
0.543519
5.699029
false
false
false
false
c4software/Android-Password-Store
app/src/main/java/com/zeapo/pwdstore/utils/PasswordRecyclerAdapter.kt
1
4869
/* * Copyright © 2014-2019 The Android Password Store Authors. All Rights Reserved. * SPDX-License-Identifier: GPL-2.0 */ package com.zeapo.pwdstore.utils import android.view.Menu import android.view.MenuItem import android.view.View import androidx.appcompat.view.ActionMode import com.zeapo.pwdstore.PasswordFragment import com.zeapo.pwdstore.PasswordStore import com.zeapo.pwdstore.R import java.util.ArrayList import java.util.TreeSet class PasswordRecyclerAdapter( private val activity: PasswordStore, private val listener: PasswordFragment.OnFragmentInteractionListener, values: ArrayList<PasswordItem> ) : EntryRecyclerAdapter(values) { var actionMode: ActionMode? = null private var canEdit: Boolean = false private val actionModeCallback = object : ActionMode.Callback { // Called when the action mode is created; startActionMode() was called override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { // Inflate a menu resource providing context menu items mode.menuInflater.inflate(R.menu.context_pass, menu) // hide the fab activity.findViewById<View>(R.id.fab).visibility = View.GONE return true } // Called each time the action mode is shown. Always called after onCreateActionMode, but // may be called multiple times if the mode is invalidated. override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { menu.findItem(R.id.menu_edit_password).isVisible = canEdit return true // Return false if nothing is done } // Called when the user selects a contextual menu item override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.menu_delete_password -> { activity.deletePasswords(this@PasswordRecyclerAdapter, TreeSet(selectedItems)) mode.finish() // Action picked, so close the CAB return true } R.id.menu_edit_password -> { activity.editPassword(values[selectedItems.iterator().next()]) mode.finish() return true } R.id.menu_move_password -> { val selectedPasswords = ArrayList<PasswordItem>() for (id in selectedItems) { selectedPasswords.add(values[id]) } activity.movePasswords(selectedPasswords) return false } else -> return false } } // Called when the user exits the action mode override fun onDestroyActionMode(mode: ActionMode) { val it = selectedItems.iterator() while (it.hasNext()) { // need the setSelected line in onBind notifyItemChanged(it.next()) it.remove() } actionMode = null // show the fab activity.findViewById<View>(R.id.fab).visibility = View.VISIBLE } } override fun getOnLongClickListener(holder: ViewHolder, pass: PasswordItem): View.OnLongClickListener { return View.OnLongClickListener { if (actionMode != null) { return@OnLongClickListener false } toggleSelection(holder.adapterPosition) canEdit = pass.type == PasswordItem.TYPE_PASSWORD // Start the CAB using the ActionMode.Callback actionMode = activity.startSupportActionMode(actionModeCallback) actionMode?.title = "" + selectedItems.size actionMode?.invalidate() notifyItemChanged(holder.adapterPosition) true } } override fun getOnClickListener(holder: ViewHolder, pass: PasswordItem): View.OnClickListener { return View.OnClickListener { if (actionMode != null) { toggleSelection(holder.adapterPosition) actionMode?.title = "" + selectedItems.size if (selectedItems.isEmpty()) { actionMode?.finish() } else if (selectedItems.size == 1 && (canEdit.not())) { if (values[selectedItems.iterator().next()].type == PasswordItem.TYPE_PASSWORD) { canEdit = true actionMode?.invalidate() } } else if (selectedItems.size >= 1 && canEdit) { canEdit = false actionMode?.invalidate() } } else { listener.onFragmentInteraction(pass) } notifyItemChanged(holder.adapterPosition) } } }
gpl-3.0
6e0726ea2d4c4c5b20420d3d95e6c343
39.231405
107
0.588743
5.44519
false
false
false
false
hanks-zyh/KotlinExample
src/LearnNumbers.kt
1
546
/** * Created by hanks on 15-10-28. */ fun main(args: Array<String>) { val a = 2.3 val b = 2.3F val c = 2 val d = 2L val e = 0x2a val f = false val g = 0b01010 println("$a , $b , $c , $d , $e , $f , $g") val aa: Int = 1000 println(aa == aa) //true println(aa === aa) //true val boxedA: Int? = aa val anotherBoxedA: Int? = aa println(boxedA == anotherBoxedA) //true println(boxedA === anotherBoxedA) //false val bb: Int? = 1 val cc: Long? = bb?.toLong() println(cc) }
apache-2.0
99f991dc389df1094b9f368fa0dc99b1
17.862069
47
0.518315
2.858639
false
false
false
false
pjq/rpi
android/app/src/main/java/me/pjq/rpicar/models/WeatherItem.kt
1
817
package me.pjq.rpicar.models /** * Created by i329817([email protected]) on 10/09/2017. */ class WeatherItem { /** * id : 15 * alt : 0 * lat : 0 * timestamp : 1504980523833 * date : Sep 10, 2017 2:08:43 AM * location : home * pm25 : 36 * pm25_cf : 41 * pm10 : 41 * pm10_cf : 41 * temperature : 25.9 * humidity : 69.8 * raw_data : */ var id: Int = 0 var alt: Int = 0 var lat: Int = 0 var timestamp: Long = 0 var date: String? = null var location: String? = null var pm25: Int = 0 get() = (field * 2).toInt() var pm25_cf: Int = 0 var pm10: Int = 0 var pm10_cf: Int = 0 var temperature: Double = 0.toDouble() var humidity: Double = 0.toDouble() var raw_data: String? = null }
apache-2.0
15924ff2a517e8a253bf1e6676f7fe5a
19.948718
59
0.52754
3.059925
false
false
false
false
DSolyom/ViolinDS
ViolinDS/app/src/main/java/ds/violin/v1/Global.kt
1
9245
/* Copyright 2016 Dániel Sólyom 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 ds.violin.v1 import android.app.Activity import android.app.Application import android.content.Context import android.content.SharedPreferences import android.content.pm.ApplicationInfo import android.os.Bundle import android.util.DisplayMetrics import ds.violin.v1.app.violin.ActivityViolin import ds.violin.v1.app.violin.PlayingViolin import ds.violin.v1.util.common.Debug import ds.violin.v1.datasource.base.SingleUseBackgroundWorkerThread import ds.violin.v1.datasource.sqlite.SQLiteSessionHandling import ds.violin.v1.extensions.getSerializable import ds.violin.v1.extensions.putSerializable import ds.violin.v1.util.ConnectionChecker import java.util.* private val TAG = "GLOBAL" /** * this interface must be implemented in Application */ interface Global { companion object { const val TAG_ACTIVITY_REFRESH = "__VIOLIN_REFRESH_" /** application context */ lateinit var context: Context /** current running activity */ var currentActivity: Activity? = null /** app running in debug mode? */ var isDebug: Boolean = false /** device has large screen? */ var isLargeScreen: Boolean = false /** dimensions and dip multiplier, etc */ var screenMetrics: DisplayMetrics? = null // TODO: move these somewhere far better lateinit var httpSessionsTODO: HashMap<*, *> lateinit var sqliteOpenHelpersTODO: HashMap<*, *> /** * instance of [SharedPreferences] according to your preferences set in the constructor */ lateinit var preferences: SharedPreferences /** * a saved [SharedPreferences.Editor] to chain edit through calls/objects * * !note: if you would just quick commit something, please use preferences#edit */ lateinit var editor: SharedPreferences.Editor /** -------------------------------------------------------------------------------------- * [screenMetrics] */ val dipMultiplier: Float get() { return screenMetrics!!.density } val dipImageMultiplier: Float get() { return dipMultiplier * when (isLargeScreen) { true -> 2 false -> 1 } } val screenWidth: Int get() { return screenMetrics!!.widthPixels } val screenHeight: Int get() { return screenMetrics!!.heightPixels } /** -------------------------------------------------------------------------------------- * [Locale] */ var language: String? get() { return preferences.getString(TAG + "_language", null) } set(value) { val editor = preferences.edit() editor.putString(TAG + "_language", value) editor.commit() forceLocale() } /** * timezone to use - phones timezone is the default set in [ActivityLifecycleCallbacks.onActivityCreated] */ lateinit var timezone: TimeZone /** * */ internal fun forceLocale() { val language = language ?: return val res = context.resources; val config = res.configuration; try { config.locale = Locale(language); res.updateConfiguration(config, context.resources.displayMetrics); Debug.logD(TAG, "forced locale: " + language); } catch(e: Throwable) { ; } } /** -------------------------------------------------------------------------------------- * [Activity] * * request an [PlayingViolin] to reload it's entities when it next becomes active * and to tell it's Violins to do their too */ fun invalidateEntitiesIn(violinId: String) { val editor = preferences.edit() editor.putBoolean(TAG_ACTIVITY_REFRESH + violinId, true) editor.apply() } /** * request all [PlayingViolin]s to reload their entities when it next becomes active * and to tell it's Violins to do their too */ fun invalidateEntitiesAll() { val editor = preferences.edit() editor.putSerializable(TAG_ACTIVITY_REFRESH + "__ALL__", ArrayList<String>()) editor.apply() } /** * check activity if data reloading is requested also presumed it's handled and remove * the request (id) */ fun shouldInvalidateEntities(violinId: String): Boolean { val tag = TAG_ACTIVITY_REFRESH + violinId var should = false if (preferences.getBoolean(tag, false)) { val editor = preferences.edit() editor.putBoolean(tag, false) editor.apply() should = true } @Suppress("UNCHECKED_CAST") val loaded = preferences.getSerializable(TAG_ACTIVITY_REFRESH + "__ALL__", ArrayList<String>()) as ArrayList<String> if (!loaded.contains(tag)) { loaded.add(tag) editor.putSerializable(TAG_ACTIVITY_REFRESH + "__ALL__", loaded) editor.apply() should = true } return should } } fun initStaticHolding(application: Application, httpSessions: HashMap<*, *>, sqliteOpenHelpers: HashMap<*, *>) { context = application.applicationContext httpSessionsTODO = httpSessions sqliteOpenHelpersTODO = sqliteOpenHelpers try { val pm = context!!.packageManager val debuggableFlagValue = pm?.getApplicationInfo(context!!.packageName, 0)!!.flags and ApplicationInfo.FLAG_DEBUGGABLE isDebug = debuggableFlagValue != 0 } catch(e: Throwable) { e.printStackTrace(); } /** clean up any [SingleUseBackgroundWorkerThread] / results */ SingleUseBackgroundWorkerThread.cleanup() application.registerActivityLifecycleCallbacks(ActivityLifecycleCallbacks) } } /** ------------------------------------------------------------------------------------------- * Application.ActivityLifecycleCallbacks */ private object ActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { Global.currentActivity = activity Global.preferences = activity.getSharedPreferences("ds.violin.shared_preferences", Context.MODE_PRIVATE) Global.editor = Global.preferences.edit() try { if (Global.screenMetrics == null) { Global.screenMetrics = DisplayMetrics() activity.windowManager.defaultDisplay.getMetrics(Global.screenMetrics) Global.isLargeScreen = (Math.min(Global.screenHeight, Global.screenWidth).toFloat() / Global.dipMultiplier) >= 600 Global.currentActivity!!.windowManager.defaultDisplay.getMetrics(Global.screenMetrics) } } catch(e: Throwable) { Debug.logException(e); } if (activity is ActivityViolin) { activity.onCreated(savedInstanceState) } Global.timezone = Calendar.getInstance().timeZone Global.forceLocale() } override fun onActivityStarted(activity: Activity) { Global.currentActivity = activity if (activity is ActivityViolin) { ConnectionChecker.registerReceiver(activity, activity) activity.onStarted() } Global.forceLocale() } override fun onActivityResumed(activity: Activity) { Global.currentActivity = activity if (activity is ActivityViolin) { activity.activityActivated = true } } override fun onActivityPaused(activity: Activity) { if (activity == Global.currentActivity) { Global.currentActivity = null } if (activity is ActivityViolin) { activity.activityActivated = false ConnectionChecker.unregisterReceiver(activity) } } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) { } override fun onActivityDestroyed(activity: Activity) { } }
apache-2.0
5e5c3e8ac856f50bdc91091adffa4812
32.129032
130
0.585524
5.414763
false
false
false
false
tomhenne/Jerusalem
src/main/java/de/esymetric/jerusalem/ownDataRepresentation/fileSystem/PartitionedWayCostFile.kt
1
4217
package de.esymetric.jerusalem.ownDataRepresentation.fileSystem import de.esymetric.jerusalem.ownDataRepresentation.Transition import de.esymetric.jerusalem.routing.RoutingHeuristics.Companion.BLOCKED_WAY_COST import de.esymetric.jerusalem.utils.BufferedRandomAccessFile import de.esymetric.jerusalem.utils.BufferedRandomAccessFileCache import java.io.File import java.io.IOException class PartitionedWayCostFile(var dataDirectoryPath: String, var readOnly: Boolean) { var filePath: String? = null var currentLatLonDir = LatLonDir(-1000.0, -1000.0) var raf: BufferedRandomAccessFile? = null var rafCache = BufferedRandomAccessFileCache() var numberOfWayCosts = 0 init { if (readOnly) rafCache.setMaxCacheSize(30) else rafCache.setMaxCacheSize(10) } private fun checkAndCreateRandomAccessFile(lld: LatLonDir) { if (lld.equals(currentLatLonDir)) return currentLatLonDir = lld filePath = (currentLatLonDir.makeDir(dataDirectoryPath, !readOnly) + File.separatorChar + FILENAME) raf = rafCache.getRandomAccessFile(filePath!!, readOnly) try { val fileLength = raf!!.length() numberOfWayCosts = (fileLength / SENTENCE_LENGTH).toInt() } catch (e: IOException) { e.printStackTrace() } } fun close() { rafCache.close() } fun insertWay( lld: LatLonDir, costFoot: Double, costBike: Double, costRacingBike: Double, costMountainBike: Double, costCar: Double, costCarShortest: Double ): Int { checkAndCreateRandomAccessFile(lld) return try { val id = numberOfWayCosts raf!!.seek(numberOfWayCosts.toLong() * SENTENCE_LENGTH) raf!!.writeUShort(costDouble2Short(costFoot)) raf!!.writeUShort(costDouble2Short(costBike)) raf!!.writeUShort(costDouble2Short(costRacingBike)) raf!!.writeUShort(costDouble2Short(costMountainBike)) raf!!.writeUShort(costDouble2Short(costCar)) raf!!.writeUShort(costDouble2Short(costCarShortest)) numberOfWayCosts++ id } catch (e: IOException) { e.printStackTrace() -1 } } fun readTransitionCost(lld: LatLonDir, wayCostID: Int, t: Transition): Boolean { checkAndCreateRandomAccessFile(lld) return try { raf!!.seek(wayCostID.toLong() * SENTENCE_LENGTH) t.costFoot = short2DoubleCost(raf!!.readUShort()) t.costBike = short2DoubleCost(raf!!.readUShort()) t.costRacingBike = short2DoubleCost(raf!!.readUShort()) t.costMountainBike = short2DoubleCost(raf!!.readUShort()) t.costCar = short2DoubleCost(raf!!.readUShort()) t.costCarShortest = short2DoubleCost(raf!!.readUShort()) true } catch (e: IOException) { e.printStackTrace() false } } fun deleteAllWayCostFiles() { for (f in File(dataDirectoryPath).listFiles()) if (f.isDirectory && f.name.startsWith("lat_")) for (g in f.listFiles()) if (g.isDirectory && g.name.startsWith( "lng_" ) ) for (h in g.listFiles()) if (h.isFile && h.name == FILENAME) h.delete() } private fun costDouble2Short(cost: Double) : UShort { if (cost == BLOCKED_WAY_COST) return BLOCKED_WAY_COST_USHORT var costM = cost * MULT_FACTOR_SHORT_TO_DOUBLE if (costM > 64000.0 || costM < 0.0) { println("Error: invalid cost " + cost) costM = 64000.0 } return costM.toUInt().toUShort() } private fun short2DoubleCost(cost: UShort): Double { if ( cost == BLOCKED_WAY_COST_USHORT ) return BLOCKED_WAY_COST return cost.toDouble() / MULT_FACTOR_SHORT_TO_DOUBLE } companion object { const val SENTENCE_LENGTH = 12L const val FILENAME = "wayCost.data" const val MULT_FACTOR_SHORT_TO_DOUBLE = 64.0 const val BLOCKED_WAY_COST_USHORT = UShort.MAX_VALUE } }
apache-2.0
f808adc934375ba6a118314647d424f7
36.706422
167
0.621295
4.238191
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/internal/connection/ExchangeFinder.kt
4
11591
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.connection import java.io.IOException import java.net.Socket import okhttp3.Address import okhttp3.EventListener import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.Route import okhttp3.internal.canReuseConnectionFor import okhttp3.internal.closeQuietly import okhttp3.internal.http.ExchangeCodec import okhttp3.internal.http.RealInterceptorChain import okhttp3.internal.http2.ConnectionShutdownException import okhttp3.internal.http2.ErrorCode import okhttp3.internal.http2.StreamResetException /** * Attempts to find the connections for an exchange and any retries that follow. This uses the * following strategies: * * 1. If the current call already has a connection that can satisfy the request it is used. Using * the same connection for an initial exchange and its follow-ups may improve locality. * * 2. If there is a connection in the pool that can satisfy the request it is used. Note that it is * possible for shared exchanges to make requests to different host names! See * [RealConnection.isEligible] for details. * * 3. If there's no existing connection, make a list of routes (which may require blocking DNS * lookups) and attempt a new connection them. When failures occur, retries iterate the list of * available routes. * * If the pool gains an eligible connection while DNS, TCP, or TLS work is in flight, this finder * will prefer pooled connections. Only pooled HTTP/2 connections are used for such de-duplication. * * It is possible to cancel the finding process. * * Instances of this class are not thread-safe. Each instance is thread-confined to the thread * executing [call]. */ class ExchangeFinder( private val connectionPool: RealConnectionPool, internal val address: Address, private val call: RealCall, private val eventListener: EventListener ) { private var routeSelection: RouteSelector.Selection? = null private var routeSelector: RouteSelector? = null private var refusedStreamCount = 0 private var connectionShutdownCount = 0 private var otherFailureCount = 0 private var nextRouteToTry: Route? = null fun find( client: OkHttpClient, chain: RealInterceptorChain ): ExchangeCodec { try { val resultConnection = findHealthyConnection( connectTimeout = chain.connectTimeoutMillis, readTimeout = chain.readTimeoutMillis, writeTimeout = chain.writeTimeoutMillis, pingIntervalMillis = client.pingIntervalMillis, connectionRetryEnabled = client.retryOnConnectionFailure, doExtensiveHealthChecks = chain.request.method != "GET" ) return resultConnection.newCodec(client, chain) } catch (e: RouteException) { trackFailure(e.lastConnectException) throw e } catch (e: IOException) { trackFailure(e) throw RouteException(e) } } /** * Finds a connection and returns it if it is healthy. If it is unhealthy the process is repeated * until a healthy connection is found. */ @Throws(IOException::class) private fun findHealthyConnection( connectTimeout: Int, readTimeout: Int, writeTimeout: Int, pingIntervalMillis: Int, connectionRetryEnabled: Boolean, doExtensiveHealthChecks: Boolean ): RealConnection { while (true) { val candidate = findConnection( connectTimeout = connectTimeout, readTimeout = readTimeout, writeTimeout = writeTimeout, pingIntervalMillis = pingIntervalMillis, connectionRetryEnabled = connectionRetryEnabled ) // Confirm that the connection is good. if (candidate.isHealthy(doExtensiveHealthChecks)) { return candidate } // If it isn't, take it out of the pool. candidate.noNewExchanges() // Make sure we have some routes left to try. One example where we may exhaust all the routes // would happen if we made a new connection and it immediately is detected as unhealthy. if (nextRouteToTry != null) continue val routesLeft = routeSelection?.hasNext() ?: true if (routesLeft) continue val routesSelectionLeft = routeSelector?.hasNext() ?: true if (routesSelectionLeft) continue throw IOException("exhausted all routes") } } /** * Returns a connection to host a new stream. This prefers the existing connection if it exists, * then the pool, finally building a new connection. * * This checks for cancellation before each blocking operation. */ @Throws(IOException::class) private fun findConnection( connectTimeout: Int, readTimeout: Int, writeTimeout: Int, pingIntervalMillis: Int, connectionRetryEnabled: Boolean ): RealConnection { if (call.isCanceled()) throw IOException("Canceled") // Attempt to reuse the connection from the call. val callConnection = call.connection // This may be mutated by releaseConnectionNoEvents()! if (callConnection != null) { var toClose: Socket? = null synchronized(callConnection) { if (callConnection.noNewExchanges || !sameHostAndPort(callConnection.route().address.url)) { toClose = call.releaseConnectionNoEvents() } } // If the call's connection wasn't released, reuse it. We don't call connectionAcquired() here // because we already acquired it. if (call.connection != null) { check(toClose == null) return callConnection } // The call's connection was released. toClose?.closeQuietly() eventListener.connectionReleased(call, callConnection) } // We need a new connection. Give it fresh stats. refusedStreamCount = 0 connectionShutdownCount = 0 otherFailureCount = 0 // Attempt to get a connection from the pool. if (connectionPool.callAcquirePooledConnection(address, call, null, false)) { val result = call.connection!! eventListener.connectionAcquired(call, result) return result } // Nothing in the pool. Figure out what route we'll try next. val routes: List<Route>? val route: Route if (nextRouteToTry != null) { // Use a route from a preceding coalesced connection. routes = null route = nextRouteToTry!! nextRouteToTry = null } else if (routeSelection != null && routeSelection!!.hasNext()) { // Use a route from an existing route selection. routes = null route = routeSelection!!.next() } else { // Compute a new route selection. This is a blocking operation! var localRouteSelector = routeSelector if (localRouteSelector == null) { localRouteSelector = RouteSelector(address, call.client.routeDatabase, call, eventListener) this.routeSelector = localRouteSelector } val localRouteSelection = localRouteSelector.next() routeSelection = localRouteSelection routes = localRouteSelection.routes if (call.isCanceled()) throw IOException("Canceled") // Now that we have a set of IP addresses, make another attempt at getting a connection from // the pool. We have a better chance of matching thanks to connection coalescing. if (connectionPool.callAcquirePooledConnection(address, call, routes, false)) { val result = call.connection!! eventListener.connectionAcquired(call, result) return result } route = localRouteSelection.next() } // Connect. Tell the call about the connecting call so async cancels work. val newConnection = RealConnection(connectionPool, route) call.connectionToCancel = newConnection try { newConnection.connect( connectTimeout, readTimeout, writeTimeout, pingIntervalMillis, connectionRetryEnabled, call, eventListener ) } finally { call.connectionToCancel = null } call.client.routeDatabase.connected(newConnection.route()) // If we raced another call connecting to this host, coalesce the connections. This makes for 3 // different lookups in the connection pool! if (connectionPool.callAcquirePooledConnection(address, call, routes, true)) { val result = call.connection!! nextRouteToTry = route newConnection.socket().closeQuietly() eventListener.connectionAcquired(call, result) return result } synchronized(newConnection) { connectionPool.put(newConnection) call.acquireConnectionNoEvents(newConnection) } eventListener.connectionAcquired(call, newConnection) return newConnection } fun trackFailure(e: IOException) { nextRouteToTry = null if (e is StreamResetException && e.errorCode == ErrorCode.REFUSED_STREAM) { refusedStreamCount++ } else if (e is ConnectionShutdownException) { connectionShutdownCount++ } else { otherFailureCount++ } } /** * Returns true if the current route has a failure that retrying could fix, and that there's * a route to retry on. */ fun retryAfterFailure(): Boolean { if (refusedStreamCount == 0 && connectionShutdownCount == 0 && otherFailureCount == 0) { return false // Nothing to recover from. } if (nextRouteToTry != null) { return true } val retryRoute = retryRoute() if (retryRoute != null) { // Lock in the route because retryRoute() is racy and we don't want to call it twice. nextRouteToTry = retryRoute return true } // If we have a routes left, use 'em. if (routeSelection?.hasNext() == true) return true // If we haven't initialized the route selector yet, assume it'll have at least one route. val localRouteSelector = routeSelector ?: return true // If we do have a route selector, use its routes. return localRouteSelector.hasNext() } /** * Return the route from the current connection if it should be retried, even if the connection * itself is unhealthy. The biggest gotcha here is that we shouldn't reuse routes from coalesced * connections. */ private fun retryRoute(): Route? { if (refusedStreamCount > 1 || connectionShutdownCount > 1 || otherFailureCount > 0) { return null // This route has too many problems to retry. } val connection = call.connection ?: return null synchronized(connection) { if (connection.routeFailureCount != 0) return null if (!connection.route().address.url.canReuseConnectionFor(address.url)) return null return connection.route() } } /** * Returns true if the host and port are unchanged from when this was created. This is used to * detect if followups need to do a full connection-finding process including DNS resolution, and * certificate pin checks. */ fun sameHostAndPort(url: HttpUrl): Boolean { val routeUrl = address.url return url.port == routeUrl.port && url.host == routeUrl.host } }
apache-2.0
e1c12417b59f8d44cfcf56d5c93c3cc4
34.338415
100
0.69994
4.610581
false
false
false
false
Esri/arcgis-runtime-demos-android
android-demos/GeotriggerMonitoring/GeotriggerMonitoringDemo-WithGeotriggers/app/src/main/java/com/arcgisruntime/sample/geotriggermonitoringdemo/view/MainActivity.kt
1
2904
package com.arcgisruntime.sample.geotriggermonitoringdemo.view import android.Manifest import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.arcgisruntime.sample.geotriggermonitoringdemo.R import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.security.AuthenticationManager import com.esri.arcgisruntime.security.DefaultAuthenticationChallengeHandler import androidx.core.app.ActivityCompat import android.content.pm.PackageManager import androidx.core.content.ContextCompat import com.arcgisruntime.sample.geotriggermonitoringdemo.domain.GeotriggerMonitoringService import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private val reqPermissions = arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) private val PERMISSION_REQUEST_CODE = 2 var canStartService = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) AuthenticationManager.setAuthenticationChallengeHandler( DefaultAuthenticationChallengeHandler(this) ) // authentication with an API key or named user is required to access basemaps and other // location services ArcGISRuntimeEnvironment.setApiKey(getString(R.string.API_KEY)) startMonitoringService() } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String?>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode != PERMISSION_REQUEST_CODE) { return } if (grantResults.isEmpty()) { return } for (grantResult in grantResults) { if (grantResult == PackageManager.PERMISSION_DENIED) { return } } } fun startMonitoringService() { val intent = Intent(applicationContext, GeotriggerMonitoringService::class.java) if (canStartService) { startService(intent) } else { // Check permissions to see if failure may be due to lack of permissions. for (permission in reqPermissions) { if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED ) { // If permissions are not already granted, request permission from the user. ActivityCompat.requestPermissions(this, reqPermissions, PERMISSION_REQUEST_CODE) } else { canStartService = true } } startService(intent) } } }
apache-2.0
9849c271cfeab91c4a535342e7096e36
35.3125
100
0.682163
5.438202
false
false
false
false
nemerosa/ontrack
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/SCMCatalogImpl.kt
1
3027
package net.nemerosa.ontrack.extension.scm.catalog import net.nemerosa.ontrack.common.Time import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.model.structure.NameDescription import net.nemerosa.ontrack.model.support.ApplicationLogEntry import net.nemerosa.ontrack.model.support.ApplicationLogService import net.nemerosa.ontrack.model.support.StorageService import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class SCMCatalogImpl( private val storageService: StorageService, private val scmCatalogProviders: List<SCMCatalogProvider>, private val applicationLogService: ApplicationLogService ) : SCMCatalog { override fun collectSCMCatalog(logger: (String) -> Unit) { // Gets existing keys val keys = storageService.getKeys(SCM_CATALOG_STORE).toMutableSet() // Getting new & updated items scmCatalogProviders.forEach { provider -> logger("Collecting SCM Catalog for ${provider.id}") val entries = try { provider.entries } catch (ex: Exception) { applicationLogService.log( ApplicationLogEntry.error( ex, NameDescription.nd("scm-provider-access", "Cannot access SCM provider"), "Cannot get SCM entries from ${provider.id}" ).withDetail("provider", provider.id) ) emptyList<SCMCatalogSource>() } entries.forEach { source -> logger("SCM Catalog entry: $source") // As entry val entry = SCMCatalogEntry( scm = provider.id, config = source.config, repository = source.repository, repositoryPage = source.repositoryPage, lastActivity = source.lastActivity, createdAt = source.createdAt, timestamp = Time.now(), teams = source.teams ) // Stores the entry storageService.store( SCM_CATALOG_STORE, entry.key, entry ) // Stored keys.remove(entry.key) } } // Cleaning everything keys.forEach { storageService.delete(SCM_CATALOG_STORE, it) } } override val catalogEntries: Sequence<SCMCatalogEntry> get() = storageService.getData(SCM_CATALOG_STORE, SCMCatalogEntry::class.java).values.asSequence() override fun getCatalogEntry(key: String): SCMCatalogEntry? = storageService.retrieve(SCM_CATALOG_STORE, key, SCMCatalogEntry::class.java).getOrNull() } private const val SCM_CATALOG_STORE = "scm-catalog"
mit
6309413d88414ffc80e55bfc36aef3ac
38.311688
106
0.582425
5.574586
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/notifications/AppNotificationManagerImpl.kt
1
4687
package com.nextcloud.client.notifications import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.res.Resources import android.graphics.BitmapFactory import android.os.Build import androidx.core.app.NotificationCompat import com.nextcloud.client.account.User import com.owncloud.android.R import com.owncloud.android.datamodel.OCFile import com.owncloud.android.ui.activity.FileDisplayActivity import com.owncloud.android.ui.notifications.NotificationUtils import com.owncloud.android.ui.preview.PreviewImageActivity import com.owncloud.android.ui.preview.PreviewImageFragment import com.owncloud.android.utils.theme.ViewThemeUtils import javax.inject.Inject class AppNotificationManagerImpl @Inject constructor( private val context: Context, private val resources: Resources, private val platformNotificationsManager: NotificationManager, private val viewThemeUtils: ViewThemeUtils ) : AppNotificationManager { companion object { const val PROGRESS_PERCENTAGE_MAX = 100 const val PROGRESS_PERCENTAGE_MIN = 0 } private fun builder(channelId: String): NotificationCompat.Builder { val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationCompat.Builder(context, channelId) } else { NotificationCompat.Builder(context) } viewThemeUtils.androidx.themeNotificationCompatBuilder(context, builder) return builder } override fun buildDownloadServiceForegroundNotification(): Notification { val icon = BitmapFactory.decodeResource(resources, R.drawable.notification_icon) return builder(NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD) .setContentTitle(resources.getString(R.string.app_name)) .setContentText(resources.getString(R.string.foreground_service_download)) .setSmallIcon(R.drawable.notification_icon) .setLargeIcon(icon) .build() } override fun postDownloadTransferProgress(fileOwner: User, file: OCFile, progress: Int, allowPreview: Boolean) { val builder = builder(NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD) val content = resources.getString( R.string.downloader_download_in_progress_content, progress, file.fileName ) builder .setSmallIcon(R.drawable.ic_cloud_download) .setTicker(resources.getString(R.string.downloader_download_in_progress_ticker)) .setContentTitle(resources.getString(R.string.downloader_download_in_progress_ticker)) .setOngoing(true) .setProgress(PROGRESS_PERCENTAGE_MAX, progress, progress <= PROGRESS_PERCENTAGE_MIN) .setContentText(content) if (allowPreview) { val openFileIntent = if (PreviewImageFragment.canBePreviewed(file)) { PreviewImageActivity.previewFileIntent(context, fileOwner, file) } else { FileDisplayActivity.openFileIntent(context, fileOwner, file) } openFileIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP val pendingOpenFileIntent = PendingIntent.getActivity( context, System.currentTimeMillis().toInt(), openFileIntent, PendingIntent.FLAG_IMMUTABLE ) builder.setContentIntent(pendingOpenFileIntent) } platformNotificationsManager.notify(AppNotificationManager.TRANSFER_NOTIFICATION_ID, builder.build()) } override fun postUploadTransferProgress(fileOwner: User, file: OCFile, progress: Int) { val builder = builder(NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD) val content = resources.getString( R.string.uploader_upload_in_progress_content, progress, file.fileName ) builder .setSmallIcon(R.drawable.ic_cloud_upload) .setTicker(resources.getString(R.string.uploader_upload_in_progress_ticker)) .setContentTitle(resources.getString(R.string.uploader_upload_in_progress_ticker)) .setOngoing(true) .setProgress(PROGRESS_PERCENTAGE_MAX, progress, progress <= PROGRESS_PERCENTAGE_MIN) .setContentText(content) platformNotificationsManager.notify(AppNotificationManager.TRANSFER_NOTIFICATION_ID, builder.build()) } override fun cancelTransferNotification() { platformNotificationsManager.cancel(AppNotificationManager.TRANSFER_NOTIFICATION_ID) } }
gpl-2.0
cdb177fdab56bfd7a3e0d1268769ade7
42.398148
116
0.710049
5.007479
false
false
false
false
Kerr1Gan/ShareBox
share/src/main/java/com/ethan/and/db/DataBaseHelper.kt
1
1833
package com.common.flesh.db import android.content.Context import android.database.DatabaseErrorHandler import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.util.Log import com.ethan.and.db.table.BaseTable /** * Created by Ethan_Xiang on 2017/8/14. */ class DataBaseHelper : SQLiteOpenHelper { companion object { private const val TAG = "DataBaseHelper" } private var mTables: List<BaseTable>? = null constructor(context: Context, name: String, factory: SQLiteDatabase.CursorFactory?, version: Int) : super(context, name, factory, version) { } constructor(context: Context, name: String, factory: SQLiteDatabase.CursorFactory?, version: Int, errorHandler: DatabaseErrorHandler?) : super(context, name, factory, version, errorHandler) { } fun setTables(tables: List<BaseTable>) { mTables = tables } override fun onCreate(db: SQLiteDatabase?) { Log.e(TAG, "onCreate db table size " + mTables?.size) if (mTables != null) { for (table in mTables!!) { Log.e(TAG, "create db " + table::class.java) table.createTable(db!!) } } } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { Log.e(TAG, "onUpgrade db table size " + mTables?.size) if (mTables != null) { for (table in mTables!!) { Log.e(TAG, "upgrade db " + table::class.java) table.updateTable(db!!, oldVersion, newVersion) } } } override fun onOpen(db: SQLiteDatabase?) { super.onOpen(db) if (db?.isReadOnly() == false) { // Enable foreign key constraints db.execSQL("PRAGMA foreign_keys=ON;"); } } }
apache-2.0
42855876f1a402ddad0d214c79141d38
31.175439
144
0.624659
4.194508
false
false
false
false
olonho/carkot
kotstd/kt/progressionUtil.kt
1
2498
package kotlin // a mod b (in arithmetical sense) private fun mod(a: Int, b: Int): Int { val mod = a % b return if (mod >= 0) mod else mod + b } private fun mod(a: Long, b: Long): Long { val mod = a % b return if (mod >= 0) mod else mod + b } // (a - b) mod c private fun differenceModulo(a: Int, b: Int, c: Int): Int { return mod(mod(a, c) - mod(b, c), c) } private fun differenceModulo(a: Long, b: Long, c: Long): Long { return mod(mod(a, c) - mod(b, c), c) } /** * Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range * from [start] to [end] in case of a positive [step], or from [end] to [start] in case of a negative * [step]. * * No validation on passed parameters is performed. The given parameters should satisfy the condition: either * `step > 0` and `start >= end`, or `step < 0` and`start >= end`. * @param start first element of the progression * @param end ending bound for the progression * @param step increment, or difference of successive elements in the progression * @return the final element of the progression * @suppress */ fun getProgressionLastElement(start: Int, end: Int, step: Int): Int { if (step > 0) { return end - differenceModulo(end, start, step) } else if (step < 0) { return end + differenceModulo(start, end, -step) } else { println("Step is zero.") assert(false) return -1 } } /** * Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range * from [start] to [end] in case of a positive [step], or from [end] to [start] in case of a negative * [step]. * * No validation on passed parameters is performed. The given parameters should satisfy the condition: either * `step > 0` and `start >= end`, or `step < 0` and`start >= end`. * @param start first element of the progression * @param end ending bound for the progression * @param step increment, or difference of successive elements in the progression * @return the final element of the progression * @suppress */ internal fun getProgressionLastElement(start: Long, end: Long, step: Long): Long { if (step > 0) { return end - differenceModulo(end, start, step) } else if (step < 0) { return end + differenceModulo(start, end, -step) } else { println("Step is zero.") assert(false) return -1L } }
mit
2e9ec7842af177a0726cc88e7fee94f3
34.183099
131
0.653723
3.578797
false
false
false
false
material-components/material-components-android-examples
Owl/app/src/main/java/com/materialstudies/owl/ui/lessons/LessonsSheetFragment.kt
1
8569
/* * 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.materialstudies.owl.ui.lessons import android.content.res.ColorStateList import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.addCallback import androidx.annotation.ColorInt import androidx.annotation.Px import androidx.core.view.WindowInsetsCompat.Type import androidx.core.view.doOnLayout import androidx.core.view.forEach import androidx.core.view.postDelayed import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.navOptions import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED import com.google.android.material.shape.MaterialShapeDrawable import com.google.android.material.shape.ShapeAppearanceModel import com.materialstudies.owl.R import com.materialstudies.owl.databinding.FragmentLessonsSheetBinding import com.materialstudies.owl.model.Course import com.materialstudies.owl.model.lessons import com.materialstudies.owl.util.doOnApplyWindowInsets import com.materialstudies.owl.util.lerp import com.materialstudies.owl.util.lerpArgb /** * A [Fragment] displaying a list of lessons as a bottom sheet. */ class LessonsSheetFragment : Fragment() { private lateinit var binding: FragmentLessonsSheetBinding private val onClick: (Int) -> Unit = { step -> val course = this.course if (course != null) { binding.lessonsSheet.postDelayed(300L) { val action = LessonsSheetFragmentDirections.actionLessonsSheetToLesson(course.id, step) // FIXME should be able to `navigate(action)` but not working val navController = findNavController() val onLesson = navController.currentDestination?.id != R.id.lesson navController.navigate( R.id.lesson, action.arguments, navOptions { launchSingleTop = true anim { enter = if (onLesson) R.anim.slide_in_up else -1 popExit = R.anim.slide_out_down } } ) } BottomSheetBehavior.from(binding.lessonsSheet).state = STATE_COLLAPSED } } private val lessonAdapter = LessonAdapter(onClick).apply { submitList(lessons) } var course: Course? = null set(value) { field = value binding.course = value } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentLessonsSheetBinding.inflate(inflater, container, false).apply { val behavior = BottomSheetBehavior.from(lessonsSheet) val backCallback = requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, false) { behavior.state = STATE_COLLAPSED } val sheetStartColor = lessonsSheet.context.getColor(R.color.owl_pink_500) val sheetEndColor = lessonsSheet.context.getColorStateList(R.color.primary_sheet).defaultColor val sheetBackground = MaterialShapeDrawable( ShapeAppearanceModel.builder( lessonsSheet.context, R.style.ShapeAppearance_Owl_MinimizedSheet, 0 ).build() ).apply { fillColor = ColorStateList.valueOf(sheetStartColor) } lessonsSheet.background = sheetBackground lessonsSheet.doOnLayout { val peek = behavior.peekHeight val maxTranslationX = (it.width - peek).toFloat() lessonsSheet.translationX = (lessonsSheet.width - peek).toFloat() // Alter views based on the sheet expansion behavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { backCallback.isEnabled = newState == STATE_EXPANDED } override fun onSlide(bottomSheet: View, slideOffset: Float) { lessonsSheet.translationX = lerp(maxTranslationX, 0f, 0f, 0.15f, slideOffset) sheetBackground.interpolation = lerp(1f, 0f, 0f, 0.15f, slideOffset) sheetBackground.fillColor = ColorStateList.valueOf( lerpArgb( sheetStartColor, sheetEndColor, 0f, 0.3f, slideOffset ) ) playlistIcon.alpha = lerp(1f, 0f, 0f, 0.15f, slideOffset) sheetExpand.alpha = lerp(1f, 0f, 0f, 0.15f, slideOffset) sheetExpand.visibility = if (slideOffset < 0.5) View.VISIBLE else View.GONE playlistTitle.alpha = lerp(0f, 1f, 0.2f, 0.8f, slideOffset) collapsePlaylist.alpha = lerp(0f, 1f, 0.2f, 0.8f, slideOffset) playlistTitleDivider.alpha = lerp(0f, 1f, 0.2f, 0.8f, slideOffset) playlist.alpha = lerp(0f, 1f, 0.2f, 0.8f, slideOffset) } }) lessonsSheet.doOnApplyWindowInsets { _, insets, _, _ -> behavior.peekHeight = peek + insets.getInsets(Type.navigationBars()).bottom } } collapsePlaylist.setOnClickListener { behavior.state = STATE_COLLAPSED } sheetExpand.setOnClickListener { behavior.state = STATE_EXPANDED } playlist.adapter = lessonAdapter playlist.addItemDecoration( InsetDivider( resources.getDimensionPixelSize(R.dimen.divider_inset), resources.getDimensionPixelSize((R.dimen.divider_height)), playlist.context.getColor(R.color.divider) ) ) } return binding.root } } /** * A [RecyclerView.ItemDecoration] which is inset from the left by the given amount. */ class InsetDivider( @Px private val inset: Int, @Px private val height: Int, @ColorInt private val dividerColor: Int ) : RecyclerView.ItemDecoration() { private val dividerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = dividerColor style = Paint.Style.STROKE strokeWidth = height.toFloat() } override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val points = mutableListOf<Float>() parent.forEach { if (parent.getChildAdapterPosition(it) < state.itemCount - 1) { val bottom = it.bottom.toFloat() points.add((it.left + inset).toFloat()) points.add(bottom) points.add(it.right.toFloat()) points.add(bottom) } } c.drawLines(points.toFloatArray(), dividerPaint) } override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { outRect.top = height / 2 outRect.bottom = height / 2 } }
apache-2.0
cb9b8c546ce8ae593ac5ee80aad3afa0
39.419811
99
0.605088
5.061429
false
false
false
false
hewking/HUILibrary
app/src/main/java/com/hewking/custom/MultiImageLayout.kt
1
4251
package com.hewking.custom import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.ViewGroup import android.widget.ImageView import androidx.core.view.children import kotlin.math.ceil import kotlin.math.floor class MultiImageLayout(val ctx: Context, attrs: AttributeSet) : ViewGroup(ctx, attrs) { private var dividerPadding: Float var imageUrls: MutableList<String>? = null set(value) { field = value initAllImageView() } var adapter: Adapter? = null set(value) { field = value requestLayout() } init { val styledAttrs = ctx.obtainStyledAttributes(attrs, R.styleable.MultiImageLayout) dividerPadding = styledAttrs.getDimension(R.styleable.MultiImageLayout_dividerPadding, 3f) styledAttrs.recycle() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val wMode = MeasureSpec.getMode(widthMeasureSpec) val wSize = MeasureSpec.getSize(widthMeasureSpec) var hSize = MeasureSpec.getSize(heightMeasureSpec) val imageCount = childCount val rows = when (imageCount) { 4 -> 2 else -> { 3 } } if (wMode == MeasureSpec.EXACTLY && childCount > 0) { if (imageCount > 0) { hSize = if (imageCount > 1) { val imageWidth = (wSize - 2 * dividerPadding).div(3).toInt() children.forEach { val imageSpec = MeasureSpec.makeMeasureSpec(imageWidth, MeasureSpec.EXACTLY) it.measure(imageSpec, imageSpec) } ceil(imageCount.div(rows.toDouble())).toInt() * imageWidth } else { getChildAt(0).measure(MeasureSpec.makeMeasureSpec(wSize,MeasureSpec.AT_MOST) , MeasureSpec.makeMeasureSpec(wSize,MeasureSpec.AT_MOST)) wSize } } } setMeasuredDimension(wSize, hSize) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { val imageCount = childCount if (imageCount > 1) { val child = getChildAt(0) val childWidth = child.measuredWidth // 1. 3 个以下显示一行,宽度childWidth // 2. 四个显示两行,正方形排列 // 3. 5,6个显示两行 // 4. 7-9个显示三行 val rows = when (imageCount) { 4 -> 2 else -> { 3 } } for (childIndex in 0 until childCount) { val i = childIndex.rem(rows) val j = floor(childIndex.div(rows.toDouble())).toInt() getChildAt(childIndex).layout(dividerPadding.toInt() + i * childWidth , j * childWidth + dividerPadding.toInt(), childWidth * (i + 1) , childWidth * (j + 1)) adapter?.displayImage(getChildAt(childIndex) as ImageView, imageUrls?.get(childIndex) ?: "") } } else if (imageCount > 0) { val childIndex = 0 val imageChild = getChildAt(childIndex) imageChild.layout(dividerPadding.toInt(), dividerPadding.toInt(), imageChild.measuredWidth + dividerPadding.toInt(), imageChild.measuredHeight + dividerPadding.toInt()) adapter?.displayImage(getChildAt(childIndex) as ImageView, imageUrls?.get(childIndex) ?: "") } } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) } private fun initAllImageView() { removeAllViews() imageUrls?.let { it.forEach { _ -> val iv = ImageView(ctx).apply { scaleType = ImageView.ScaleType.CENTER_CROP } addView(iv) } } } interface Adapter { fun displayImage(image: ImageView, url: String) } }
mit
45c17cd78f7d04e4bad10299237df202
33.61157
122
0.544304
4.796105
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/util/PatchPlayground.kt
1
2978
package com.engineer.imitate.util import android.app.Application import android.content.Context import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.example.cpp_native.internal.PatchUtil import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.apache.commons.io.FileUtils import org.apache.commons.io.IOUtil import java.io.File import java.io.FileOutputStream private const val TAG = "PatchPlayground" private const val PATCH = "patch" class PatchViewModel(val app: Application) : AndroidViewModel(app) { fun copyFile() { val exceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable -> Log.e(TAG, "exceptionHandler: " + throwable.stackTraceToString()) } viewModelScope.launch(exceptionHandler) { if (prepare(app)) { Log.d(TAG, "copy success start merge") if (mergeFile(app)) { Log.d(TAG, "merge success") } } } } } suspend fun prepare(context: Context): Boolean { val baseDir = context.cacheDir.absolutePath + File.separator + PATCH + File.separator withContext(Dispatchers.IO) { val targetDir = File(baseDir) Log.i(TAG, "prepare: $targetDir") if (targetDir.exists().not()) { targetDir.mkdir() } val result = baseDir + "result.txt" val resultFile = File(result) if (resultFile.exists()) { Log.i(TAG, "delete resultFile " + resultFile.delete()) } val patchDir = context.assets.list(PATCH) patchDir?.forEach { val f = PATCH + File.separator + it Log.i(TAG, "copy file $f") val input = context.assets.open(f) val fileOut = targetDir.absolutePath + File.separator + it val outputStream = FileOutputStream(fileOut) IOUtil.copy(input, outputStream) } val file = File(baseDir) if (file.isDirectory) { val list = file.listFiles() list.forEach { l -> Log.i(TAG, "fileName: ${l.absolutePath} ") } } } return File(baseDir).listFiles()?.size ?: 0 >= 2 } suspend fun mergeFile(context: Context): Boolean { val baseDir = context.cacheDir.absolutePath + File.separator + PATCH + File.separator val result = baseDir + "result.txt" val oldFile = baseDir + "lastest.txt" val patchFile = baseDir + "diff.patch" withContext(Dispatchers.IO) { PatchUtil.patchAPK(oldFile, result, patchFile) } val mergeResult = FileUtils.fileRead(result) Log.e(TAG, "mergeFile() called with: mergeResult = $mergeResult") Log.e(TAG, "mergeFile() called with: ${"123456789" == mergeResult.trim()}") return "123456789" == mergeResult.trim() }
apache-2.0
c8dd5fa5f2e17aa96010358f5aa790f2
32.852273
89
0.640698
4.315942
false
false
false
false
Setekh/Gleipnir-Graphics
src/main/kotlin/eu/corvus/corax/scene/graph/SceneGraphImpl.kt
1
5678
/** * Copyright (c) 2013-2019 Corvus Corax Entertainment * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of Corvus Corax Entertainment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package eu.corvus.corax.scene.graph import eu.corvus.corax.app.GleipnirApplication import eu.corvus.corax.graphics.buffers.isUploaded import eu.corvus.corax.graphics.context.RendererContext import eu.corvus.corax.scene.* import eu.corvus.corax.scene.assets.AssetManager import eu.corvus.corax.scene.geometry.Geometry import eu.corvus.corax.scripts.ScriptManager import eu.corvus.corax.utils.ItemBuffer import eu.corvus.corax.utils.Logger import eu.corvus.corax.utils.toRadians import kotlinx.coroutines.* import org.koin.core.get /** * @author Vlad Ravenholm on 12/2/2019 */ class SceneGraphImpl( private val rendererContext: RendererContext, private val assetManager: AssetManager, private val scriptManager: ScriptManager ) : SceneGraph, Object() { override val sceneTree: Node = Node("Scene Tree") override val renderBuffer: ItemBuffer<Geometry> = ItemBuffer() override var isRenderReady: Boolean = false private set override val cameras: List<Camera> = mutableListOf() private val job = SupervisorJob() private val sceneScope = CoroutineScope(Dispatchers.Main + job) private var loadJob: Job? = null private var lastLoadPath = "" override suspend fun processTree() { cameras as MutableList cameras.clear() cameras += sceneTree.findAllCameras() if (cameras.isEmpty()) { // add a camera to at least see something val app = get<GleipnirApplication>() cameras.add(Camera("Din oficiu").apply { val width = app.width val height = app.height useAsPerspective(70f.toRadians(), width / height.toFloat()) updateResize(width, height) transform.translation.set(0f, 0f, 5f) sceneTree.appendChild(this) scriptManager.onGraphReady() }) } } override fun loadScene(path: String) { if (lastLoadPath.isNotEmpty()) { scriptManager.onGraphDestroy() } lastLoadPath = path sceneTree.removeChildren() loadJob?.cancel() loadJob = sceneScope.launch { isRenderReady = false Logger.info("Loading scene $path") val spatial = assetManager.loadSpatial(path) sceneTree.appendChild(spatial) withContext(Dispatchers.IO) { processTree() } isRenderReady = cameras.isNotEmpty() if (!isRenderReady) Logger.warn("Nothing to render with!") Logger.info("Scene loaded") } } override fun resizeViewPort(width: Int, height: Int) { cameras.forEach { it.updateResize(width, height) } } override fun saveScene(path: String) { if (!lastLoadPath.endsWith("coss")) { //TODO ask for conversion to corvus serialized scene Logger.warn("Please pick where to save") } TODO("Implement") } override fun prepareGraph(camera: Camera, tpf: Float) { scriptManager.onGraphUpdate(tpf) // todo check cull hint for camera renderBuffer.clear() queueScene(sceneTree, tpf) renderBuffer.flip() } private fun queueScene(scene: Node, tpf: Float) { when (scene) { is Geometry -> { // TODO queue should implement a sorting method, for translucent and transparent objects scene.vertexArrayObject?.let { vao -> if (!vao.isUploaded()) rendererContext.createArrayBufferData(vao) } scene.material.prepareUpload(assetManager, rendererContext) renderBuffer.put(scene) } } if (scene is Spatial) scene.update(tpf) repeat(scene.children.size) { val node = scene.child(it) queueScene(node, tpf) } } override fun free() { super.free() job.cancel() scriptManager.onGraphDestroy() } }
bsd-3-clause
3cde682baeec62fbe139a0261b6e1f24
31.82659
117
0.657626
4.620016
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/repository/git/prop/GitAutoProperty.kt
1
3269
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.repository.git.prop import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.FileMode import org.tmatesoft.svn.core.SVNProperty import svnserver.repository.git.path.PathMatcher /** * Parse and processing .gitignore. * * @author Artem V. Navrotskiy <[email protected]> */ internal class GitAutoProperty /** * Set property to all matched file. * * @param matcher File matcher. * @param property Property name. * @param value Property value. */ constructor(private val matcher: PathMatcher, private val property: String, private val value: String) : GitProperty { override fun apply(props: MutableMap<String, String>) { val mask: String? = matcher.svnMaskGlobal if (mask != null) { var autoprops: String = props.getOrDefault(SVNProperty.INHERITABLE_AUTO_PROPS, "") var beg = 0 while (true) { if (autoprops.substring(beg).startsWith(mask + MASK_SEPARATOR)) { var end: Int = autoprops.indexOf('\n', beg + 1) if (end < 0) { end = autoprops.length } autoprops = (autoprops.substring(0, end) + "; " + property + "=" + value + autoprops.substring(end)) break } beg = autoprops.indexOf('\n', beg + 1) if (beg < 0) { autoprops = (autoprops + mask + MASK_SEPARATOR + property + "=" + value + "\n") break } } props[SVNProperty.INHERITABLE_AUTO_PROPS] = autoprops } } override val filterName: String? get() { return null } override fun createForChild(name: String, mode: FileMode): GitProperty? { if (mode.objectType == Constants.OBJ_BLOB) { return null } if (matcher.svnMaskGlobal != null) { return null } val matcherChild: PathMatcher = matcher.createChild(name, true) ?: return null return GitAutoProperty(matcherChild, property, value) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that: GitAutoProperty = other as GitAutoProperty return ((matcher == that.matcher) && (property == that.property) && (value == that.value)) } override fun hashCode(): Int { var result: Int = matcher.hashCode() result = 31 * result + property.hashCode() result = 31 * result + value.hashCode() return result } companion object { private const val MASK_SEPARATOR: String = " = " } }
gpl-2.0
e4e6a2a12551a0c95176850b50702ffc
35.322222
122
0.571123
4.364486
false
false
false
false
vondear/RxTools
RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityPopupView.kt
1
5690
package com.tamsiree.rxdemo.activity import android.os.Bundle import android.text.TextUtils import android.view.View import android.view.ViewGroup import com.tamsiree.rxdemo.R import com.tamsiree.rxkit.RxDeviceTool.setPortrait import com.tamsiree.rxkit.TLog import com.tamsiree.rxkit.model.ActionItem import com.tamsiree.rxkit.view.RxToast import com.tamsiree.rxui.activity.ActivityBase import com.tamsiree.rxui.view.popupwindows.RxPopupImply import com.tamsiree.rxui.view.popupwindows.RxPopupSingleView import com.tamsiree.rxui.view.popupwindows.tools.RxPopupView import com.tamsiree.rxui.view.popupwindows.tools.RxPopupViewManager import com.tamsiree.rxui.view.popupwindows.tools.RxPopupViewManager.TipListener import kotlinx.android.synthetic.main.activity_popup_view.* /** * @author tamsiree */ class ActivityPopupView : ActivityBase(), TipListener { private var mRxPopupViewManager: RxPopupViewManager? = null @RxPopupView.Align var mAlign = RxPopupView.ALIGN_CENTER private var titlePopup: RxPopupSingleView? = null //提示 一小时后有惊喜 private var popupImply: RxPopupImply? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_popup_view) setPortrait(this) } override fun initView() { rx_title.setLeftFinish(mContext) mRxPopupViewManager = RxPopupViewManager(this) button_align_center.isChecked = true val text = if (TextUtils.isEmpty(text_input_edit_text.text)) TIP_TEXT else text_input_edit_text.text.toString() var builder: RxPopupView.Builder var tipvView: View tv_imply.setOnClickListener { if (popupImply == null) { popupImply = RxPopupImply(mContext) } popupImply?.show(tv_imply) } tv_definition.setOnClickListener { initPopupView() titlePopup?.show(tv_definition, 0) } button_above.setOnClickListener { mRxPopupViewManager?.findAndDismiss(text_view) builder = RxPopupView.Builder(this, text_view, parent_layout, text, RxPopupView.POSITION_ABOVE) builder.setAlign(mAlign) tipvView = mRxPopupViewManager?.show(builder.build())!! } button_below.setOnClickListener { mRxPopupViewManager?.findAndDismiss(text_view) builder = RxPopupView.Builder(this, text_view, parent_layout, text, RxPopupView.POSITION_BELOW) builder.setAlign(mAlign) builder.setBackgroundColor(resources.getColor(R.color.orange)) tipvView = mRxPopupViewManager?.show(builder.build())!! } button_left_to.setOnClickListener { mRxPopupViewManager?.findAndDismiss(text_view) builder = RxPopupView.Builder(this, text_view, parent_layout, text, RxPopupView.POSITION_LEFT_TO) builder.setBackgroundColor(resources.getColor(R.color.greenyellow)) builder.setTextColor(resources.getColor(R.color.Black)) builder.setGravity(RxPopupView.GRAVITY_CENTER) builder.setTextSize(12) tipvView = mRxPopupViewManager?.show(builder.build())!! } button_right_to.setOnClickListener { mRxPopupViewManager?.findAndDismiss(text_view) builder = RxPopupView.Builder(this, text_view, parent_layout, text, RxPopupView.POSITION_RIGHT_TO) builder.setBackgroundColor(resources.getColor(R.color.paleturquoise)) builder.setTextColor(resources.getColor(android.R.color.black)) tipvView = mRxPopupViewManager?.show(builder.build())!! } button_align_center.setOnClickListener { mAlign = RxPopupView.ALIGN_CENTER } button_align_left.setOnClickListener { mAlign = RxPopupView.ALIGN_LEFT } button_align_right.setOnClickListener { mAlign = RxPopupView.ALIGN_RIGHT } } override fun initData() { } private fun initPopupView() { titlePopup = RxPopupSingleView(mContext, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, R.layout.popupwindow_definition_layout) titlePopup?.addAction(ActionItem("标清")) titlePopup?.addAction(ActionItem("高清")) titlePopup?.addAction(ActionItem("超清")) titlePopup?.setItemOnClickListener(object : RxPopupSingleView.OnItemOnClickListener { override fun onItemClick(item: ActionItem?, position: Int) { if (titlePopup!!.getAction(position)?.mTitle == tv_definition.text) { RxToast.showToast(mContext, "当前已经为" + tv_definition.text, 500) } else { if (position in 0..2) { tv_definition.text = titlePopup!!.getAction(position)?.mTitle } } } }) } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) val builder = RxPopupView.Builder(this, text_view, root_layout_s, TIP_TEXT, RxPopupView.POSITION_ABOVE) builder.setAlign(mAlign) mRxPopupViewManager?.show(builder.build()) } override fun onTipDismissed(view: View, anchorViewId: Int, byUser: Boolean) { TLog.d(TAG, "tip near anchor view $anchorViewId dismissed") if (anchorViewId == R.id.text_view) { // Do something when a tip near view with id "R.id.text_view" has been dismissed } } companion object { const val TIP_TEXT = "Tip" private val TAG = ActivityPopupView::class.java.simpleName } }
apache-2.0
299760ba72e0b1c904e36a416830ca12
39.949275
119
0.676637
4.203869
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/feed/view/FeedAdapter.kt
1
4451
package org.wikipedia.feed.view import android.content.Context import android.view.View import android.view.ViewGroup import androidx.core.view.updateLayoutParams import androidx.core.view.updateMargins import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import org.wikipedia.feed.FeedCoordinatorBase import org.wikipedia.feed.accessibility.AccessibilityCard import org.wikipedia.feed.announcement.AnnouncementCardView import org.wikipedia.feed.dayheader.DayHeaderCardView import org.wikipedia.feed.image.FeaturedImageCardView import org.wikipedia.feed.model.Card import org.wikipedia.feed.model.CardType import org.wikipedia.feed.news.NewsCardView import org.wikipedia.feed.offline.OfflineCard import org.wikipedia.feed.offline.OfflineCardView import org.wikipedia.feed.random.RandomCardView import org.wikipedia.feed.searchbar.SearchCardView import org.wikipedia.feed.suggestededits.SuggestedEditsCardView import org.wikipedia.util.DimenUtil import org.wikipedia.views.DefaultRecyclerAdapter import org.wikipedia.views.DefaultViewHolder @Suppress("UNCHECKED_CAST") class FeedAdapter<T : View>(private val coordinator: FeedCoordinatorBase, private val callback: Callback?) : DefaultRecyclerAdapter<Card?, T>(coordinator.cards) { interface Callback : ListCardItemView.Callback, CardHeaderView.Callback, FeaturedImageCardView.Callback, SearchCardView.Callback, NewsCardView.Callback, AnnouncementCardView.Callback, RandomCardView.Callback, ListCardView.Callback, SuggestedEditsCardView.Callback { fun onShowCard(card: Card?) fun onRequestMore() fun onRetryFromOffline() fun onError(t: Throwable) } private var feedView: FeedView? = null private var lastCardReloadTrigger: Card? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder<T> { return DefaultViewHolder(newView(parent.context, viewType)) } override fun onBindViewHolder(holder: DefaultViewHolder<T>, position: Int) { val item = item(position) val view = holder.view as FeedCardView<Card> lastCardReloadTrigger = if (coordinator.finished() && position == itemCount - 1 && item !is OfflineCard && item !is AccessibilityCard && item !== lastCardReloadTrigger && callback != null) { callback.onRequestMore() item } else { null } view.card = item if (view is OfflineCardView && position == 1) { view.setTopPadding() } } override fun onViewAttachedToWindow(holder: DefaultViewHolder<T>) { super.onViewAttachedToWindow(holder) if (holder.view is SearchCardView) { adjustSearchView(holder.view as SearchCardView) } else if (holder.view is DayHeaderCardView) { adjustDayHeaderView(holder.view as DayHeaderCardView) } (holder.view as FeedCardView<*>).callback = callback callback?.onShowCard((holder.view as FeedCardView<*>).card) } override fun onViewDetachedFromWindow(holder: DefaultViewHolder<T>) { (holder.view as FeedCardView<*>).callback = null super.onViewDetachedFromWindow(holder) } override fun getItemViewType(position: Int): Int { return item(position)!!.type().code() } private fun newView(context: Context, viewType: Int): T { return CardType.of(viewType).newView(context) as T } override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { super.onAttachedToRecyclerView(recyclerView) feedView = recyclerView as FeedView } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { super.onDetachedFromRecyclerView(recyclerView) feedView = null } private fun adjustSearchView(view: SearchCardView) { view.updateLayoutParams<StaggeredGridLayoutManager.LayoutParams> { isFullSpan = true bottomMargin = DimenUtil.roundedDpToPx(8F) if (DimenUtil.isLandscape(view.context)) { val margin = (view.parent as View).width / 6 updateMargins(left = margin, right = margin) } } } private fun adjustDayHeaderView(view: DayHeaderCardView) { view.updateLayoutParams<StaggeredGridLayoutManager.LayoutParams> { isFullSpan = true } } }
apache-2.0
a3569a905c7777857a5e7d098334d9d9
38.389381
108
0.719838
4.85917
false
false
false
false
AndroidX/androidx
paging/paging-common/src/main/kotlin/androidx/paging/PagePresenter.kt
3
15991
/* * 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.paging import androidx.paging.LoadState.NotLoading import androidx.paging.LoadType.APPEND import androidx.paging.LoadType.PREPEND import androidx.paging.LoadType.REFRESH import androidx.paging.PageEvent.Insert.Companion.EMPTY_REFRESH_LOCAL import androidx.paging.internal.BUGANIZER_URL /** * Presents post-transform paging data as a list, with list update notifications when * PageEvents are dispatched. */ internal class PagePresenter<T : Any>( pages: List<TransformablePage<T>>, placeholdersBefore: Int, placeholdersAfter: Int, ) : NullPaddedList<T> { constructor( insertEvent: PageEvent.Insert<T> ) : this( pages = insertEvent.pages, placeholdersBefore = insertEvent.placeholdersBefore, placeholdersAfter = insertEvent.placeholdersAfter, ) private val pages: MutableList<TransformablePage<T>> = pages.toMutableList() override var storageCount: Int = pages.fullCount() private set private val originalPageOffsetFirst: Int get() = pages.first().originalPageOffsets.minOrNull()!! private val originalPageOffsetLast: Int get() = pages.last().originalPageOffsets.maxOrNull()!! override var placeholdersBefore: Int = placeholdersBefore private set override var placeholdersAfter: Int = placeholdersAfter private set private fun checkIndex(index: Int) { if (index < 0 || index >= size) { throw IndexOutOfBoundsException("Index: $index, Size: $size") } } override fun toString(): String { val items = List(storageCount) { getFromStorage(it) }.joinToString() return "[($placeholdersBefore placeholders), $items, ($placeholdersAfter placeholders)]" } fun get(index: Int): T? { checkIndex(index) val localIndex = index - placeholdersBefore if (localIndex < 0 || localIndex >= storageCount) { return null } return getFromStorage(localIndex) } fun snapshot(): ItemSnapshotList<T> { return ItemSnapshotList( placeholdersBefore, placeholdersAfter, pages.flatMap { it.data } ) } override fun getFromStorage(localIndex: Int): T { var pageIndex = 0 var indexInPage = localIndex // Since we don't know if page sizes are regular, we walk to correct page. val localPageCount = pages.size while (pageIndex < localPageCount) { val pageSize = pages[pageIndex].data.size if (pageSize > indexInPage) { // stop, found the page break } indexInPage -= pageSize pageIndex++ } return pages[pageIndex].data[indexInPage] } override val size: Int get() = placeholdersBefore + storageCount + placeholdersAfter private fun List<TransformablePage<T>>.fullCount() = sumOf { it.data.size } fun processEvent(pageEvent: PageEvent<T>, callback: ProcessPageEventCallback) { when (pageEvent) { is PageEvent.Insert -> insertPage(pageEvent, callback) is PageEvent.Drop -> dropPages(pageEvent, callback) is PageEvent.LoadStateUpdate -> { callback.onStateUpdate( source = pageEvent.source, mediator = pageEvent.mediator, ) } is PageEvent.StaticList -> throw IllegalStateException( """Paging received an event to display a static list, while still actively loading |from an existing generation of PagingData. If you see this exception, it is most |likely a bug in the library. Please file a bug so we can fix it at: |$BUGANIZER_URL""".trimMargin() ) } } fun initializeHint(): ViewportHint.Initial { val presentedItems = storageCount return ViewportHint.Initial( presentedItemsBefore = presentedItems / 2, presentedItemsAfter = presentedItems / 2, originalPageOffsetFirst = originalPageOffsetFirst, originalPageOffsetLast = originalPageOffsetLast ) } fun accessHintForPresenterIndex(index: Int): ViewportHint.Access { var pageIndex = 0 var indexInPage = index - placeholdersBefore while (indexInPage >= pages[pageIndex].data.size && pageIndex < pages.lastIndex) { // index doesn't appear in current page, keep looking! indexInPage -= pages[pageIndex].data.size pageIndex++ } return pages[pageIndex].viewportHintFor( index = indexInPage, presentedItemsBefore = index - placeholdersBefore, presentedItemsAfter = size - index - placeholdersAfter - 1, originalPageOffsetFirst = originalPageOffsetFirst, originalPageOffsetLast = originalPageOffsetLast ) } /** * Insert the event's page to the presentation list, and dispatch associated callbacks for * change (placeholder becomes real item) or insert (real item is appended). * * For each insert (or removal) there are three potential events: * * 1) change * this covers any placeholder/item conversions, and is done first * * 2) item insert/remove * this covers any remaining items that are inserted/removed, but aren't swapping with * placeholders * * 3) placeholder insert/remove * after the above, placeholder count can be wrong for a number of reasons - approximate * counting or filtering are the most common. In either case, we adjust placeholders at * the far end of the list, so that they don't trigger animations near the user. */ private fun insertPage(insert: PageEvent.Insert<T>, callback: ProcessPageEventCallback) { val count = insert.pages.fullCount() val oldSize = size when (insert.loadType) { REFRESH -> throw IllegalStateException( """Paging received a refresh event in the middle of an actively loading generation |of PagingData. If you see this exception, it is most likely a bug in the library. |Please file a bug so we can fix it at: |$BUGANIZER_URL""".trimMargin() ) PREPEND -> { val placeholdersChangedCount = minOf(placeholdersBefore, count) val placeholdersChangedPos = placeholdersBefore - placeholdersChangedCount val itemsInsertedCount = count - placeholdersChangedCount val itemsInsertedPos = 0 // first update all state... pages.addAll(0, insert.pages) storageCount += count placeholdersBefore = insert.placeholdersBefore // ... then trigger callbacks, so callbacks won't see inconsistent state callback.onChanged(placeholdersChangedPos, placeholdersChangedCount) callback.onInserted(itemsInsertedPos, itemsInsertedCount) val placeholderInsertedCount = size - oldSize - itemsInsertedCount if (placeholderInsertedCount > 0) { callback.onInserted(0, placeholderInsertedCount) } else if (placeholderInsertedCount < 0) { callback.onRemoved(0, -placeholderInsertedCount) } } APPEND -> { val placeholdersChangedCount = minOf(placeholdersAfter, count) val placeholdersChangedPos = placeholdersBefore + storageCount val itemsInsertedCount = count - placeholdersChangedCount val itemsInsertedPos = placeholdersChangedPos + placeholdersChangedCount // first update all state... pages.addAll(pages.size, insert.pages) storageCount += count placeholdersAfter = insert.placeholdersAfter // ... then trigger callbacks, so callbacks won't see inconsistent state callback.onChanged(placeholdersChangedPos, placeholdersChangedCount) callback.onInserted(itemsInsertedPos, itemsInsertedCount) val placeholderInsertedCount = size - oldSize - itemsInsertedCount if (placeholderInsertedCount > 0) { callback.onInserted( position = size - placeholderInsertedCount, count = placeholderInsertedCount ) } else if (placeholderInsertedCount < 0) { callback.onRemoved(size, -placeholderInsertedCount) } } } callback.onStateUpdate( source = insert.sourceLoadStates, mediator = insert.mediatorLoadStates ) } /** * @param pageOffsetsToDrop originalPageOffset of pages that were dropped * @return The number of items dropped */ private fun dropPagesWithOffsets(pageOffsetsToDrop: IntRange): Int { var removeCount = 0 val pageIterator = pages.iterator() while (pageIterator.hasNext()) { val page = pageIterator.next() if (page.originalPageOffsets.any { pageOffsetsToDrop.contains(it) }) { removeCount += page.data.size pageIterator.remove() } } return removeCount } /** * Helper which converts a [PageEvent.Drop] to a set of [ProcessPageEventCallback] events by * dropping all pages that depend on the n-lowest or n-highest originalPageOffsets. * * Note: We never run DiffUtil here because it is safe to assume that empty pages can never * become non-empty no matter what transformations they go through. [ProcessPageEventCallback] * events generated by this helper always drop contiguous sets of items because pages that * depend on multiple originalPageOffsets will always be the next closest page that's non-empty. */ private fun dropPages(drop: PageEvent.Drop<T>, callback: ProcessPageEventCallback) { val oldSize = size if (drop.loadType == PREPEND) { val oldPlaceholdersBefore = placeholdersBefore // first update all state... val itemDropCount = dropPagesWithOffsets(drop.minPageOffset..drop.maxPageOffset) storageCount -= itemDropCount placeholdersBefore = drop.placeholdersRemaining // ... then trigger callbacks, so callbacks won't see inconsistent state // Trim or insert to expected size. val expectedSize = size val placeholdersToInsert = expectedSize - oldSize if (placeholdersToInsert > 0) { callback.onInserted(0, placeholdersToInsert) } else if (placeholdersToInsert < 0) { callback.onRemoved(0, -placeholdersToInsert) } // Compute the index of the first item that must be rebound as a placeholder. // If any placeholders were inserted above, we only need to send onChanged for the next // n = (drop.placeholdersRemaining - placeholdersToInsert) items. E.g., if two nulls // were inserted above, then the onChanged event can start from index = 2. // Note: In cases where more items were dropped than there were previously placeholders, // we can simply rebind n = drop.placeholdersRemaining items starting from position = 0. val firstItemIndex = maxOf(0, oldPlaceholdersBefore + placeholdersToInsert) // Compute the number of previously loaded items that were dropped and now need to be // updated to null. This computes the distance between firstItemIndex (inclusive), // and index of the last leading placeholder (inclusive) in the final list. val changeCount = drop.placeholdersRemaining - firstItemIndex if (changeCount > 0) { callback.onChanged(firstItemIndex, changeCount) } // Dropping from prepend direction implies NotLoading(endOfPaginationReached = false). callback.onStateUpdate( loadType = PREPEND, fromMediator = false, loadState = NotLoading.Incomplete ) } else { val oldPlaceholdersAfter = placeholdersAfter // first update all state... val itemDropCount = dropPagesWithOffsets(drop.minPageOffset..drop.maxPageOffset) storageCount -= itemDropCount placeholdersAfter = drop.placeholdersRemaining // ... then trigger callbacks, so callbacks won't see inconsistent state // Trim or insert to expected size. val expectedSize = size val placeholdersToInsert = expectedSize - oldSize if (placeholdersToInsert > 0) { callback.onInserted(oldSize, placeholdersToInsert) } else if (placeholdersToInsert < 0) { callback.onRemoved(oldSize + placeholdersToInsert, -placeholdersToInsert) } // Number of trailing placeholders in the list, before dropping, that were removed // above during size adjustment. val oldPlaceholdersRemoved = when { placeholdersToInsert < 0 -> minOf(oldPlaceholdersAfter, -placeholdersToInsert) else -> 0 } // Compute the number of previously loaded items that were dropped and now need to be // updated to null. This subtracts the total number of existing placeholders in the // list, before dropping, that were not removed above during size adjustment, from // the total number of expected placeholders. val changeCount = drop.placeholdersRemaining - (oldPlaceholdersAfter - oldPlaceholdersRemoved) if (changeCount > 0) { callback.onChanged( position = size - drop.placeholdersRemaining, count = changeCount ) } // Dropping from append direction implies NotLoading(endOfPaginationReached = false). callback.onStateUpdate( loadType = APPEND, fromMediator = false, loadState = NotLoading.Incomplete ) } } internal companion object { // TODO(b/205350267): Replace this with a static list that does not emit CombinedLoadStates. private val INITIAL = PagePresenter(EMPTY_REFRESH_LOCAL) @Suppress("UNCHECKED_CAST", "SyntheticAccessor") internal fun <T : Any> initial(): PagePresenter<T> = INITIAL as PagePresenter<T> } /** * Callback to communicate events from [PagePresenter] to [PagingDataDiffer] */ internal interface ProcessPageEventCallback { fun onChanged(position: Int, count: Int) fun onInserted(position: Int, count: Int) fun onRemoved(position: Int, count: Int) fun onStateUpdate(loadType: LoadType, fromMediator: Boolean, loadState: LoadState) fun onStateUpdate(source: LoadStates, mediator: LoadStates?) } }
apache-2.0
ebe2f96bb330e3a1b1702fe8cec8162f
42.336043
100
0.632231
5.326782
false
false
false
false
codeka/wwmmo
common/src/main/kotlin/au/com/codeka/warworlds/common/PointCloud.kt
1
4579
package au.com.codeka.warworlds.common import java.util.* /** * A point cloud is, well, a cloud of points. We use it to generate a voronoi/delaunay mapping * that is then use to generate planet textures. * * The points are always bound to the square (0,0), (1,1). */ open class PointCloud { protected var points_: ArrayList<Vector2> constructor(points: ArrayList<Vector2> = ArrayList()) { points_ = points } val points: MutableList<Vector2> get() = points_ /** * Helper class to render this point cloud to the given \c Image (mostly for debugging). */ fun render(img: Image) { for (p in points_) { val x = (img.width * p.x).toInt() val y = (img.height * p.y).toInt() img.drawCircle(x, y, 5.0, Colour.RED) } } /** * Generates points by simply generating random (x,y) coordinates. This isn't usually very useful, * because the points tend to clump up and look unrealistic. */ open class RandomGenerator { fun generate(density: Double, rand: Random): ArrayList<Vector2> { // numPointsFactor will be a number between 0.75 and 1.25 which we'll use to adjust the number // of points we generate var numPointsFactor = rand.nextDouble() numPointsFactor = 0.75 + 0.5 * numPointsFactor var numPoints = 25 + (475 * density * numPointsFactor).toInt() if (numPoints < 25) { numPoints = 25 } val points = ArrayList<Vector2>(numPoints) for (i in 0 until numPoints) { points.add(Vector2(rand.nextDouble(), rand.nextDouble())) } return points } } /** * Uses a poisson generator to generate more "natural" looking random points than the basic * [RandomGenerator] does. */ open class PoissonGenerator { fun generate(density: Double, randomness: Double, rand: Random): ArrayList<Vector2> { val points = ArrayList<Vector2>(30) // give us some initial capacity val unprocessed = ArrayList<Vector2>(50) // give us some initial capacity unprocessed.add(Vector2(rand.nextDouble(), rand.nextDouble())) // we want minDistance to be small when density is high and big when density is small. val minDistance = 0.001 + 1.0 / density * 0.03 // packing is how many points around each point we'll test for a new location. // a high randomness means we'll have a low number (more random) and a low randomness // means a high number (more uniform). val packing = 10 + ((1.0 - randomness) * 90).toInt() while (!unprocessed.isEmpty()) { // get a random point from the unprocessed list val index = rand.nextInt(unprocessed.size) val point = unprocessed[index] unprocessed.removeAt(index) // if there's another point too close to this one, ignore it if (inNeighbourhood(points, point, minDistance)) { continue } // otherwise, this is a good one points.add(point) // now generate a bunch of points around this one... for (i in 0 until packing) { val newPoint = generatePointAround(rand, point, minDistance) if (newPoint.x < 0.0 || newPoint.x > 1.0) { continue } if (newPoint.y < 0.0 || newPoint.y > 1.0) { continue } unprocessed.add(newPoint) } } return points } /** * Generates a new point around the given centre point and at least \c minDistance from it. */ private fun generatePointAround(rand: Random, point: Vector2, minDistance: Double): Vector2 { val radius = minDistance * (1.0 + rand.nextDouble()) val angle = 2.0 * Math.PI * rand.nextDouble() return Vector2( point.x + radius * Math.cos(angle), point.y + radius * Math.sin(angle)) } /** * Checks whether the given new point is too close to any previously-generated points. * * @param points The list of points we've already generated. * @param point The point we've just generated and need to check. * @param minDistance The minimum distance we accept as being valid. * @return Whether the given point is within the neighbourhood of the existing points. */ private fun inNeighbourhood( points: List<Vector2>, point: Vector2, minDistance: Double): Boolean { val n = points.size for (i in 0 until n) { val otherPoint = points[i] if (point.distanceTo(otherPoint) < minDistance) { return true } } return false } } }
mit
5630de496b595c7cd558032e5656983e
33.961832
100
0.62743
4.095707
false
false
false
false
scenerygraphics/SciView
src/main/kotlin/sc/iview/commands/view/Screenshot.kt
1
2401
/*- * #%L * Scenery-backed 3D visualization package for ImageJ. * %% * Copyright (C) 2016 - 2021 SciView developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package sc.iview.commands.view import net.imagej.ImgPlus import net.imglib2.img.Img import org.scijava.ItemIO import org.scijava.command.Command import org.scijava.plugin.Menu import org.scijava.plugin.Parameter import org.scijava.plugin.Plugin import org.scijava.ui.UIService import sc.iview.SciView import sc.iview.commands.MenuWeights.VIEW import sc.iview.commands.MenuWeights.VIEW_SCREENSHOT /** * Command to take a screenshot. The screenshot is opened in ImageJ. * * @author Kyle Harrington */ @Plugin(type = Command::class, menuRoot = "SciView", menu = [Menu(label = "View", weight = VIEW), Menu(label = "Screenshot to ImageJ", weight = VIEW_SCREENSHOT)]) class Screenshot : Command { @Parameter private lateinit var sciview: SciView @Parameter private lateinit var uiService: UIService @Parameter(type = ItemIO.OUTPUT) private var img: Img<*>? = null override fun run() { img = sciview.aRGBScreenshot } }
bsd-2-clause
2a5e0044670bca868cc8637533342342
37.741935
162
0.75177
4.182927
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/model/KotlinAnalysisFileCache.kt
1
2562
/******************************************************************************* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.jetbrains.kotlin.core.model import org.eclipse.jdt.core.IJavaProject import org.jetbrains.kotlin.core.resolve.AnalysisResultWithProvider import org.jetbrains.kotlin.core.resolve.EclipseAnalyzerFacadeForJVM import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.core.builder.KotlinPsiManager data class FileAnalysisResults(val file: KtFile, val analysisResult: AnalysisResultWithProvider) public object KotlinAnalysisFileCache { private @Volatile var lastAnalysedFileCache: FileAnalysisResults? = null @Synchronized fun getAnalysisResult(file: KtFile): AnalysisResultWithProvider { return getImmediatlyFromCache(file) ?: run { val environment = getEnvironment(file.project)!! val analysisResult = resolve(file, environment) lastAnalysedFileCache = FileAnalysisResults(file, analysisResult) lastAnalysedFileCache!!.analysisResult } } fun resetCache() { lastAnalysedFileCache = null } private fun resolve(file: KtFile, environment: KotlinCommonEnvironment): AnalysisResultWithProvider { return when (environment) { is KotlinScriptEnvironment -> EclipseAnalyzerFacadeForJVM.analyzeScript(environment, file) is KotlinEnvironment -> EclipseAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(environment, listOf(file)) else -> throw IllegalArgumentException("Could not analyze file with environment: $environment") } } @Synchronized private fun getImmediatlyFromCache(file: KtFile): AnalysisResultWithProvider? { return if (lastAnalysedFileCache != null && lastAnalysedFileCache!!.file == file) lastAnalysedFileCache!!.analysisResult else null } }
apache-2.0
610c0a8077140b42f9f01377d527cc22
42.440678
122
0.688134
5.25
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/utils/importsUtils.kt
1
2849
/******************************************************************************* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.jetbrains.kotlin.core.utils import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.idea.util.ImportDescriptorResult import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.resolve.ImportPath import java.util.Comparator import org.jetbrains.kotlin.idea.imports.ImportPathComparator import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl import org.jetbrains.kotlin.config.LanguageFeature.DefaultImportOfPackageKotlinComparisons class KotlinImportInserterHelper : ImportInsertHelper() { override val importSortComparator: Comparator<ImportPath> = ImportPathComparator override fun importDescriptor(file: KtFile, descriptor: DeclarationDescriptor, forceAllUnderImport: Boolean): ImportDescriptorResult { throw UnsupportedOperationException() } override fun isImportedWithDefault(importPath: ImportPath, contextFile: KtFile): Boolean { val defaultImports = JvmPlatform.getDefaultImports(LanguageVersionSettingsImpl.DEFAULT.supportsFeature(DefaultImportOfPackageKotlinComparisons)) return importPath.isImported(defaultImports) } override fun mayImportOnShortenReferences(descriptor: DeclarationDescriptor): Boolean { return false } } // TODO: obtain these functions from fqNameUtil.kt (org.jetbrains.kotlin.idea.refactoring.fqName) fun FqName.isImported(importPath: ImportPath, skipAliasedImports: Boolean = true): Boolean { return when { skipAliasedImports && importPath.hasAlias() -> false importPath.isAllUnder && !isRoot -> importPath.fqName == this.parent() else -> importPath.fqName == this } } fun ImportPath.isImported(alreadyImported: ImportPath): Boolean { return if (isAllUnder || hasAlias()) this == alreadyImported else fqName.isImported(alreadyImported) } fun ImportPath.isImported(imports: Iterable<ImportPath>): Boolean = imports.any { isImported(it) }
apache-2.0
d2de0357990b83e2c4f4c9787484dec1
44.967742
152
0.744121
5.00703
false
false
false
false
pyamsoft/power-manager
powermanager-service/src/main/java/com/pyamsoft/powermanager/service/job/ManageJobQueuerEntry.kt
1
1687
/* * Copyright 2017 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.service.job import com.evernote.android.job.util.support.PersistableBundleCompat import com.pyamsoft.powermanager.job.JobQueuerEntry class ManageJobQueuerEntry(tag: String, delay: Long, internal val firstRun: Boolean, internal val oneShot: Boolean, internal val screenOn: Boolean, internal val repeatingOnWindow: Long, internal val repeatingOffWindow: Long) : JobQueuerEntry( tag, delay) { override fun getOptions(): PersistableBundleCompat { val extras = PersistableBundleCompat() extras.putBoolean(KEY_SCREEN, screenOn) extras.putLong(KEY_ON_WINDOW, repeatingOnWindow) extras.putLong(KEY_OFF_WINDOW, repeatingOffWindow) extras.putBoolean(KEY_ONESHOT, oneShot) extras.putBoolean(KEY_FIRST_RUN, firstRun) return extras } companion object { const val KEY_ON_WINDOW = "extra_key__on_window" const val KEY_OFF_WINDOW = "extra_key__off_window" const val KEY_SCREEN = "extra_key__screen" const val KEY_ONESHOT = "extra_key__once" const val KEY_FIRST_RUN = "extra_key__first" } }
apache-2.0
5be2898b8fd451974133d04bfe5b055b
35.673913
98
0.743331
4.016667
false
false
false
false
moovel/android-mvp
mvp-lint/src/main/java/com/moovel/mvp/WrongUsageDetector.kt
1
1750
package com.moovel.mvp import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.intellij.psi.PsiMethod import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.getContainingMethod val ISSUE_VIEW_USAGE_IN_CREATE = Issue.create("UnboundViewUsage", "Using a view which is not bound at this point", "Views are bound in the onStart method and unbound in the onStop Method. Usage at this location will cause" + "the method to throw an ViewNotAttachedException.", Category.MESSAGES, 8, Severity.ERROR, Implementation(WrongUsageDetector::class.java, Scope.JAVA_FILE_SCOPE)) private val unboundAreas = listOf( "onAttach", "onCreate", "onCreateView", "onActivityCreated", "onViewCreated", "onDestroy", "onDestroyView" ) class WrongUsageDetector : Detector(), Detector.UastScanner { override fun getApplicableMethodNames() = listOf("getView") override fun visitMethod(context: JavaContext, node: UCallExpression, method: PsiMethod) { val isGetViewMethod = "getView" == node.methodName val isInPresenter = context.evaluator.isMemberInClass(method, "com.moovel.mvp.MVPPresenter") if (isGetViewMethod && isInPresenter) { val parentMethod = node.getContainingMethod() if (unboundAreas.any { it == parentMethod?.name }) { context.report(ISSUE_VIEW_USAGE_IN_CREATE, node, context.getLocation(node), "Pointless call to getView") } } } }
apache-2.0
dcdaae8a9926abc90b7c67ab5d84cafa
37.888889
165
0.756571
4.050926
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/parser/token/HaskelLexerTokens.kt
1
2795
package org.jetbrains.haskell.parser.token import org.jetbrains.haskell.parser.HaskellTokenType import com.intellij.psi.tree.TokenSet import com.intellij.psi.TokenType import java.util.ArrayList import org.jetbrains.grammar.HaskellLexerTokens import org.jetbrains.haskell.parser.cpp.CPPTokens /** * Created by atsky on 3/12/14. */ public val KEYWORDS: List<HaskellTokenType> = listOf( HaskellLexerTokens.CASE, HaskellLexerTokens.CLASS, HaskellLexerTokens.DATA, HaskellLexerTokens.DEFAULT, HaskellLexerTokens.DERIVING, HaskellLexerTokens.DO, HaskellLexerTokens.ELSE, HaskellLexerTokens.EXPORT, HaskellLexerTokens.IF, HaskellLexerTokens.IMPORT, HaskellLexerTokens.IN, HaskellLexerTokens.INFIX, HaskellLexerTokens.INFIXL, HaskellLexerTokens.INFIXR, HaskellLexerTokens.INSTANCE, HaskellLexerTokens.FORALL, HaskellLexerTokens.FOREIGN, HaskellLexerTokens.LET, HaskellLexerTokens.MODULE, HaskellLexerTokens.NEWTYPE, HaskellLexerTokens.OF, HaskellLexerTokens.THEN, HaskellLexerTokens.WHERE, HaskellLexerTokens.TYPE, HaskellLexerTokens.SAFE, HaskellLexerTokens.UNSAFE) public val OPERATORS: List<HaskellTokenType> = listOf<HaskellTokenType>( HaskellLexerTokens.AT, HaskellLexerTokens.TILDE, HaskellLexerTokens.LAM, HaskellLexerTokens.DARROW, HaskellLexerTokens.BANG, HaskellLexerTokens.RARROW, HaskellLexerTokens.LARROW, HaskellLexerTokens.EQUAL, HaskellLexerTokens.COMMA, HaskellLexerTokens.DOT, HaskellLexerTokens.DOTDOT, HaskellLexerTokens.DCOLON, HaskellLexerTokens.OPAREN, HaskellLexerTokens.CPAREN, HaskellLexerTokens.OCURLY, HaskellLexerTokens.CCURLY, HaskellLexerTokens.OBRACK, HaskellLexerTokens.CBRACK, HaskellLexerTokens.SEMI, HaskellLexerTokens.COLON, HaskellLexerTokens.VBAR, HaskellLexerTokens.UNDERSCORE) public val BLOCK_COMMENT: HaskellTokenType = HaskellTokenType("COMMENT") public val END_OF_LINE_COMMENT: HaskellTokenType = HaskellTokenType("--") public val PRAGMA: HaskellTokenType = HaskellTokenType("PRAGMA") public val TH_VAR_QUOTE: HaskellTokenType = HaskellTokenType("'") public val TH_TY_QUOTE: HaskellTokenType = HaskellTokenType("''") public val NEW_LINE: HaskellTokenType = HaskellTokenType("NL") val COMMENTS: TokenSet = TokenSet.create( END_OF_LINE_COMMENT, BLOCK_COMMENT, PRAGMA, CPPTokens.IF, CPPTokens.ENDIF, CPPTokens.ELSE, CPPTokens.IFDEF) val WHITESPACES: TokenSet = TokenSet.create(TokenType.WHITE_SPACE, NEW_LINE)
apache-2.0
7d5a44c78edb208f221af7e89d61a85b
32.285714
76
0.711628
5.081818
false
false
false
false
0x1bad1d3a/Kaku
app/src/main/java/ca/fuwafuwa/kaku/Dialogs/StarRatingDialogFragment.kt
1
3575
package ca.fuwafuwa.kaku.Dialogs import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.os.Bundle import android.widget.TextView import androidx.fragment.app.DialogFragment import ca.fuwafuwa.kaku.KAKU_PREF_FILE import ca.fuwafuwa.kaku.KAKU_PREF_PLAY_STORE_RATED import ca.fuwafuwa.kaku.R class StarRatingDialogFragment : DialogFragment() { private var rating = 0 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return activity?.let { val builder = AlertDialog.Builder(it) val inflater = requireActivity().layoutInflater; val view = inflater.inflate(R.layout.dialog_rating_stars, null) val star1 = view.findViewById<TextView>(R.id.dialog_rating_star1) val star2 = view.findViewById<TextView>(R.id.dialog_rating_star2) val star3 = view.findViewById<TextView>(R.id.dialog_rating_star3) val star4 = view.findViewById<TextView>(R.id.dialog_rating_star4) val star5 = view.findViewById<TextView>(R.id.dialog_rating_star5) star1.setOnClickListener { star1.text = "★" star2.text = "☆" star3.text = "☆" star4.text = "☆" star5.text = "☆" rating = 1 } star2.setOnClickListener { star1.text = "★" star2.text = "★" star3.text = "☆" star4.text = "☆" star5.text = "☆" rating = 2 } star3.setOnClickListener { star1.text = "★" star2.text = "★" star3.text = "★" star4.text = "☆" star5.text = "☆" rating = 3 } star4.setOnClickListener { star1.text = "★" star2.text = "★" star3.text = "★" star4.text = "★" star5.text = "☆" rating = 4 } star5.setOnClickListener { star1.text = "★" star2.text = "★" star3.text = "★" star4.text = "★" star5.text = "★" rating = 5 } builder.setTitle("What do you think of Kaku?") .setView(view) .setPositiveButton("Ok") { _, _ -> run { if (rating == 5) { PlayStoreRatingDialogFragment().show(requireActivity().supportFragmentManager, "PlayStoreRating") } else { val prefs = requireContext().getSharedPreferences(KAKU_PREF_FILE, Context.MODE_PRIVATE) prefs.edit().putBoolean(KAKU_PREF_PLAY_STORE_RATED, true).apply() FeedbackDialogFragment().show(requireActivity().supportFragmentManager, "Feedback") } } } .setNegativeButton("Cancel") { _, _ -> { } } builder.create() } ?: throw IllegalStateException("Activity cannot be null") } }
bsd-3-clause
ea78dbf92404173057847ba152c82993
32.264151
129
0.457872
4.668874
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/seven/indicatorgroup/IndicatorGroupFragment.kt
1
1935
package com.intfocus.template.subject.seven.indicatorgroup import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.alibaba.fastjson.JSON import com.intfocus.template.R import com.intfocus.template.subject.one.entity.SingleValue import com.intfocus.template.ui.BaseFragment import kotlinx.android.synthetic.main.fragment_indicator_group.* /** * **************************************************** * author jameswong * created on: 17/12/18 下午5:23 * e-mail: [email protected] * name: 横向滑动单值组件页面 * desc: * **************************************************** */ class IndicatorGroupFragment : BaseFragment() { private var mData: List<SingleValue>? = null fun newInstance(data: String): IndicatorGroupFragment { val args = Bundle() val fragment = IndicatorGroupFragment() args.putString("data", data) fragment.arguments = args return fragment } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mData = JSON.parseArray(JSON .parseObject(arguments?.getString("data")) .getJSONArray("main_concern_data") .toJSONString() , SingleValue::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_indicator_group, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) rv_indicator_group.layoutManager = LinearLayoutManager(ctx, LinearLayoutManager.HORIZONTAL, false) mData?.let { rv_indicator_group.adapter = IndicatorGroupAdapter(ctx, it) } } }
gpl-3.0
74e28e32012585cffae60915f16b160b
34.407407
116
0.667713
4.718519
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/data/cache/ChapterCache.kt
1
6756
package eu.kanade.tachiyomi.data.cache import android.content.Context import android.text.format.Formatter import com.github.salomonbrys.kotson.fromJson import com.google.gson.Gson import com.jakewharton.disklrucache.DiskLruCache import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.util.DiskUtil import eu.kanade.tachiyomi.util.saveTo import okhttp3.Response import okio.Okio import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy import java.io.File import java.io.IOException /** * Class used to create chapter cache * For each image in a chapter a file is created * For each chapter a Json list is created and converted to a file. * The files are in format *md5key*.0 * * @param context the application context. * @constructor creates an instance of the chapter cache. */ class ChapterCache(private val context: Context) { companion object { /** Name of cache directory. */ const val PARAMETER_CACHE_DIRECTORY = "chapter_disk_cache" /** Application cache version. */ const val PARAMETER_APP_VERSION = 1 /** The number of values per cache entry. Must be positive. */ const val PARAMETER_VALUE_COUNT = 1 } /** Google Json class used for parsing JSON files. */ private val gson: Gson by injectLazy() // --> EH private val prefs: PreferencesHelper by injectLazy() // <-- EH /** Cache class used for cache management. */ // --> EH private var diskCache = setupDiskCache(prefs.eh_cacheSize().getOrDefault().toLong()) init { prefs.eh_cacheSize().asObservable().skip(1).subscribe { // Save old cache for destruction later val oldCache = diskCache diskCache = setupDiskCache(it.toLong()) oldCache.close() } } // <-- EH /** * Returns directory of cache. */ val cacheDir: File get() = diskCache.directory /** * Returns real size of directory. */ private val realSize: Long get() = DiskUtil.getDirectorySize(cacheDir) /** * Returns real size of directory in human readable format. */ val readableSize: String get() = Formatter.formatFileSize(context, realSize) // --> EH // Cache size is in MB private fun setupDiskCache(cacheSize: Long): DiskLruCache { return DiskLruCache.open(File(context.cacheDir, PARAMETER_CACHE_DIRECTORY), PARAMETER_APP_VERSION, PARAMETER_VALUE_COUNT, cacheSize * 1024 * 1024) } // <-- EH /** * Remove file from cache. * * @param file name of file "md5.0". * @return status of deletion for the file. */ fun removeFileFromCache(file: String): Boolean { // Make sure we don't delete the journal file (keeps track of cache). if (file == "journal" || file.startsWith("journal.")) return false try { // Remove the extension from the file to get the key of the cache val key = file.substringBeforeLast(".") // Remove file from cache. return diskCache.remove(key) } catch (e: Exception) { return false } } /** * Get page list from cache. * * @param chapter the chapter. * @return an observable of the list of pages. */ fun getPageListFromCache(chapter: Chapter): Observable<List<Page>> { return Observable.fromCallable { // Get the key for the chapter. val key = DiskUtil.hashKeyForDisk(getKey(chapter)) // Convert JSON string to list of objects. Throws an exception if snapshot is null diskCache.get(key).use { gson.fromJson<List<Page>>(it.getString(0)) } } } /** * Add page list to disk cache. * * @param chapter the chapter. * @param pages list of pages. */ fun putPageListToCache(chapter: Chapter, pages: List<Page>) { // Convert list of pages to json string. val cachedValue = gson.toJson(pages) // Initialize the editor (edits the values for an entry). var editor: DiskLruCache.Editor? = null try { // Get editor from md5 key. val key = DiskUtil.hashKeyForDisk(getKey(chapter)) editor = diskCache.edit(key) ?: return // Write chapter urls to cache. Okio.buffer(Okio.sink(editor.newOutputStream(0))).use { it.write(cachedValue.toByteArray()) it.flush() } diskCache.flush() editor.commit() editor.abortUnlessCommitted() } catch (e: Exception) { // Ignore. } finally { editor?.abortUnlessCommitted() } } /** * Returns true if image is in cache. * * @param imageUrl url of image. * @return true if in cache otherwise false. */ fun isImageInCache(imageUrl: String): Boolean { try { return diskCache.get(DiskUtil.hashKeyForDisk(imageUrl)) != null } catch (e: IOException) { return false } } /** * Get image file from url. * * @param imageUrl url of image. * @return path of image. */ fun getImageFile(imageUrl: String): File { // Get file from md5 key. val imageName = DiskUtil.hashKeyForDisk(imageUrl) + ".0" return File(diskCache.directory, imageName) } /** * Add image to cache. * * @param imageUrl url of image. * @param response http response from page. * @throws IOException image error. */ @Throws(IOException::class) fun putImageToCache(imageUrl: String, response: Response) { // Initialize editor (edits the values for an entry). var editor: DiskLruCache.Editor? = null try { // Get editor from md5 key. val key = DiskUtil.hashKeyForDisk(imageUrl) editor = diskCache.edit(key) ?: throw IOException("Unable to edit key") // Get OutputStream and write image with Okio. response.body()!!.source().saveTo(editor.newOutputStream(0)) diskCache.flush() editor.commit() } finally { response.body()?.close() editor?.abortUnlessCommitted() } } private fun getKey(chapter: Chapter): String { return "${chapter.manga_id}${chapter.url}" } }
apache-2.0
551fbe57809e0dad98e83926c59439b3
29.160714
94
0.6082
4.435982
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/mvp/presenter/EventPresenter.kt
1
4396
package com.gkzxhn.mygithub.mvp.presenter import android.util.Log import android.view.View import com.gkzxhn.balabala.mvp.contract.BaseView import com.gkzxhn.mygithub.api.OAuthApi import com.gkzxhn.mygithub.bean.info.User import com.gkzxhn.mygithub.constant.SharedPreConstant import com.gkzxhn.mygithub.extension.toast import com.gkzxhn.mygithub.ui.fragment.EventFragment import com.gkzxhn.mygithub.utils.SPUtil import com.gkzxhn.mygithub.utils.Utils import com.gkzxhn.mygithub.utils.rxbus.RxBus import com.trello.rxlifecycle2.kotlin.bindToLifecycle import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_notifications.* import javax.inject.Inject /** * Created by Xuezhi on 2017/11/29. */ class EventPresenter @Inject constructor(private val oAuthApi: OAuthApi, private val view: BaseView, private val rxBus: RxBus) { var lastTime: Long = 0 fun getEvents(username: String) { view.showLoading() oAuthApi.getEventsThatAUserHasReceived(username) .bindToLifecycle(view as EventFragment) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate { view.hideLoading() } .subscribe({ event -> if (event.size > 0) { view.tv_notifications_login.visibility = View.GONE view.srl_notifications.visibility = View.VISIBLE view.loadData(event) if (!event.toString().equals(SPUtil.get(view.context, SharedPreConstant.EVENT, ""))) { SPUtil.put(view.context, SharedPreConstant.EVENT, event.toString()) } SPUtil.put(view.context, SharedPreConstant.LAST_TIME, Utils.parseDate(event[0].created_at, "yyyy-MM-dd'T'HH:mm:ss'Z'") + 8 * 60 * 60 * 1000) } else { view.context.toast("没有数据") } }, { e -> Log.e(javaClass.simpleName, "e = " + e.message) view.context.toast("请先登录") view.tv_notifications_login.visibility = View.VISIBLE view.srl_notifications.visibility = View.GONE }) } fun subscribe() { rxBus.toFlowable(User::class.java) .bindToLifecycle(view as EventFragment) .subscribe( { user: User? -> view.getNewData() } ) /*rxBus.toFlowable(EventAdapterLoaded::class.java) .subscribe({ e: EventAdapterLoaded? -> //var time = Utils.getTiem().time //SPUtil.put(view.context, SharedPreConstant.LAST_TIME, lastTime) Log.i(javaClass.simpleName, "LAST_TIME = " + lastTime) })*/ } fun getRepoDetail(owner: String, repo: String) { view.showLoading() oAuthApi.get(owner, repo) .bindToLifecycle(view as EventFragment) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ repo -> //view.hideLoading() view.toIssues(repo) }, { e -> Log.i(javaClass.simpleName, e.message) }) } fun getEvents() { oAuthApi.getEvents() .bindToLifecycle(view as EventFragment) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate { view.hideLoading() } .subscribe({ event -> Log.i(javaClass.simpleName, "event = $event") }, { e -> Log.e(javaClass.simpleName, "e = " + e.message) view.context.toast("请先登录") view.tv_notifications_login.visibility = View.VISIBLE view.srl_notifications.visibility = View.GONE }) } }
gpl-3.0
1d8e44ab1f97cc9d4dfb651104dbbc6d
40.647619
172
0.551693
4.804396
false
false
false
false
zlyne0/colonization
core/src/net/sf/freecol/common/model/ai/missions/workerrequest/ColonyWorkerMissionHandler.kt
1
5397
package net.sf.freecol.common.model.ai.missions.workerrequest import net.sf.freecol.common.model.ColonyFactory import net.sf.freecol.common.model.Game import net.sf.freecol.common.model.MoveType import net.sf.freecol.common.model.ai.missions.AbstractMission import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer import net.sf.freecol.common.model.ai.missions.transportunit.MoveNoAccessNotificationMissionHandler import net.sf.freecol.common.model.ai.missions.transportunit.TransportUnitRequestMission import net.sf.freecol.common.model.map.path.PathFinder import promitech.colonization.ai.ColonyProductionPlaner import promitech.colonization.ai.CommonMissionHandler import promitech.colonization.ai.MissionHandler import promitech.colonization.ai.MissionHandlerLogger import promitech.colonization.orders.BuildColonyOrder import promitech.colonization.orders.BuildColonyOrder.OrderStatus class ColonyWorkerMissionHandler( private val game: Game, private val pathFinder: PathFinder ) : MissionHandler<ColonyWorkerMission>, MoveNoAccessNotificationMissionHandler { override fun handle( playerMissionsContainer: PlayerMissionsContainer, mission: ColonyWorkerMission ) { val player = playerMissionsContainer.player if (!CommonMissionHandler.isUnitExists(player, mission.unit)) { mission.setDone() return } if (mission.isUnitAtDestination) { if (mission.tile.hasSettlement()) { addWorkerToColony(mission) } else { buildColony(mission) } } else { val transportUnitRequestMission = TransportUnitRequestMission( game.turn, mission.unit, mission.tile, true, true, NOT_WORTH_EMBARK_RANGE ) playerMissionsContainer.addMission(mission, transportUnitRequestMission) } } private fun addWorkerToColony(mission: ColonyWorkerMission) { val colony = mission.tile.settlement.asColony() ColonyProductionPlaner.initColonyBuilderUnit(colony, mission.unit) ColonyProductionPlaner.createPlan(colony) mission.setDone() } private fun buildColony(mission: ColonyWorkerMission) { val buildColonyOrder = BuildColonyOrder(game.map) val check = buildColonyOrder.check(mission.unit, mission.tile) if (check == OrderStatus.OK) { val colonyFactory = ColonyFactory(game, pathFinder) colonyFactory.buildColonyByAI(mission.unit, mission.tile) mission.setDone() } else { if (check == OrderStatus.NO_MOVE_POINTS) { // do nothing wait on next turn for move points } else { // planer should create new mission for unit mission.setDone() } } } override fun moveNoAccessNotification( playerMissionsContainer: PlayerMissionsContainer, colonyWorkerMission: AbstractMission, transportRequestMission: TransportUnitRequestMission, moveType: MoveType ) { if (!(colonyWorkerMission is ColonyWorkerMission)) { return } if (moveType == MoveType.MOVE_NO_ACCESS_SETTLEMENT) { if (MissionHandlerLogger.logger.isDebug) { MissionHandlerLogger.logger.debug("player[%s].ColonyWorkerMission[%s].unit[%s].destination[%s] no move access moveType[%s]", playerMissionsContainer.player.getId(), colonyWorkerMission.id, colonyWorkerMission.unit.id, colonyWorkerMission.tile.toPrettyString(), moveType ) } endMissions(transportRequestMission, colonyWorkerMission, playerMissionsContainer) } else { colonyWorkerMission.increaseMoveNoAccessCounter() if (colonyWorkerMission.isMoveNoAccessCounterAboveRange(MOVE_NO_ACCESS_MAX_ATTEMPT)) { if (MissionHandlerLogger.logger.isDebug) { MissionHandlerLogger.logger.debug("player[%s].ColonyWorkerMission[%s].unit[%s].destination[%s] no move access moveType[%s] max move attempt", playerMissionsContainer.player.getId(), colonyWorkerMission.id, colonyWorkerMission.unit.id, colonyWorkerMission.tile.toPrettyString(), moveType ) } endMissions(transportRequestMission, colonyWorkerMission, playerMissionsContainer) } } } private fun endMissions( transportRequestMission: TransportUnitRequestMission, colonyWorkerMission: AbstractMission, playerMissionsContainer: PlayerMissionsContainer ) { // planer should take unit and create new destination transportRequestMission.setDone() colonyWorkerMission.setDone() // manual unblocking because MissionExecutor control only one handled mission playerMissionsContainer.unblockUnitsFromMission(transportRequestMission) playerMissionsContainer.unblockUnitsFromMission(colonyWorkerMission) } companion object { private const val NOT_WORTH_EMBARK_RANGE = 5 private const val MOVE_NO_ACCESS_MAX_ATTEMPT = 3 } }
gpl-2.0
fde3fdb364beee4ceac60fd9270bb11a
41.833333
161
0.672966
5.25
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/sms/SMSModule.kt
2
4455
package abi44_0_0.expo.modules.sms import android.content.Context import android.content.Intent import android.net.Uri import android.provider.Telephony import android.content.pm.PackageManager import android.os.Bundle import java.util.ArrayList import abi44_0_0.expo.modules.core.ExportedModule import abi44_0_0.expo.modules.core.interfaces.LifecycleEventListener import abi44_0_0.expo.modules.core.ModuleRegistry import abi44_0_0.expo.modules.core.Promise import abi44_0_0.expo.modules.core.interfaces.services.UIManager import abi44_0_0.expo.modules.core.interfaces.ExpoMethod import abi44_0_0.expo.modules.core.interfaces.ActivityProvider private const val TAG = "ExpoSMS" private const val ERROR_TAG = "E_SMS" private const val OPTIONS_ATTACHMENTS_KEY = "attachments" class SMSModule(context: Context, private val smsPackage: String? = null) : ExportedModule(context), LifecycleEventListener { private lateinit var mModuleRegistry: ModuleRegistry private var mPendingPromise: Promise? = null private var mSMSComposerOpened = false override fun getName(): String { return TAG } override fun onCreate(moduleRegistry: ModuleRegistry) { mModuleRegistry = moduleRegistry mModuleRegistry.getModule(UIManager::class.java)?.registerLifecycleEventListener(this) } override fun onDestroy() { // Unregister from old UIManager mModuleRegistry.getModule(UIManager::class.java)?.unregisterLifecycleEventListener(this) } private fun getAttachment(attachment: Map<String?, String?>?, key: String): String? { return attachment?.get(key) } @ExpoMethod fun sendSMSAsync( addresses: ArrayList<String>, message: String, options: Map<String?, Any?>?, promise: Promise ) { if (mPendingPromise != null) { promise.reject( ERROR_TAG + "_SENDING_IN_PROGRESS", "Different SMS sending in progress. Await the old request and then try again." ) return } val attachments = options?.get(OPTIONS_ATTACHMENTS_KEY) as? List<*> // ACTION_SEND causes a weird flicker on Android 10 devices if the messaging app is not already // open in the background, but it seems to be the only intent type that works for including // attachments, so we use it if there are attachments and fall back to ACTION_SENDTO otherwise. val smsIntent = if (attachments?.isNotEmpty() == true) { Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra("address", addresses.joinToString(separator = ";")) val attachment = attachments[0] as? Map<String?, String?> putExtra(Intent.EXTRA_STREAM, Uri.parse(getAttachment(attachment, "uri"))) type = getAttachment(attachment, "mimeType") addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } } else { Intent(Intent.ACTION_SENDTO).apply { data = Uri.parse("smsto:" + addresses.joinToString(separator = ";")) } } val defaultSMSPackage: String? if (smsPackage != null) { defaultSMSPackage = smsPackage } else { defaultSMSPackage = Telephony.Sms.getDefaultSmsPackage(context) } if (defaultSMSPackage != null) { smsIntent.setPackage(defaultSMSPackage) } else { promise.reject(ERROR_TAG + "_NO_SMS_APP", "No messaging application available") return } smsIntent.putExtra("exit_on_sent", true) smsIntent.putExtra("compose_mode", true) smsIntent.putExtra("sms_body", message) mPendingPromise = promise val activityProvider = mModuleRegistry.getModule( ActivityProvider::class.java ) activityProvider.currentActivity.startActivity(smsIntent) mSMSComposerOpened = true } @ExpoMethod fun isAvailableAsync(promise: Promise) { promise.resolve(context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) } override fun onHostResume() { val promise = mPendingPromise if (mSMSComposerOpened && promise != null) { // the only way to check the status of the message is to query the device's SMS database // but this requires READ_SMS permission, which Google is heavily restricting beginning Jan 2019 // so we just resolve with an unknown value promise.resolve( Bundle().apply { putString("result", "unknown") } ) mPendingPromise = null } mSMSComposerOpened = false } override fun onHostPause() = Unit override fun onHostDestroy() = Unit }
bsd-3-clause
c6075591dc863915b1bbc65a88261678
33.269231
125
0.712458
4.325243
false
false
false
false
treelzebub/zinepress
app/src/main/java/net/treelzebub/zinepress/util/extensions/FileExtensions.kt
1
796
package net.treelzebub.zinepress.util.extensions import java.io.* /** * Created by Tre Murillo on 1/8/16 */ fun <T : Serializable> T.serialize(): ByteArray { val bos = ByteArrayOutputStream() var out: ObjectOutputStream? = null try { out = ObjectOutputStream(bos) out.writeObject(this) } finally { try { out?.close() bos.close() } catch (_: IOException) { } return bos.toByteArray() } } @Suppress("UNCHECKED_CAST") fun <T : Serializable> ByteArray.deserialize(): T { val bis = ByteArrayInputStream(this) var input: ObjectInput? = null try { input = ObjectInputStream(bis) } finally { bis.close() input?.close() return input!!.readObject() as T } }
gpl-2.0
ae3adbd3c9f38b54153c1b550b42d5da
21.771429
51
0.584171
4.21164
false
false
false
false
square/wire
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/EnumElement.kt
1
1884
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema.internal.parser import com.squareup.wire.schema.Location import com.squareup.wire.schema.internal.appendDocumentation import com.squareup.wire.schema.internal.appendIndented data class EnumElement( override val location: Location, override val name: String, override val documentation: String = "", override val options: List<OptionElement> = emptyList(), val constants: List<EnumConstantElement> = emptyList(), val reserveds: List<ReservedElement> = emptyList(), ) : TypeElement { // Enums do not allow nested type declarations. override val nestedTypes: List<TypeElement> = emptyList() override fun toSchema() = buildString { appendDocumentation(documentation) append("enum $name {") if (reserveds.isNotEmpty()) { append('\n') for (reserved in reserveds) { appendIndented(reserved.toSchema()) } } if (reserveds.isEmpty() && (options.isNotEmpty() || constants.isNotEmpty())) { append('\n') } if (options.isNotEmpty()) { for (option in options) { appendIndented(option.toSchemaDeclaration()) } } if (constants.isNotEmpty()) { for (constant in constants) { appendIndented(constant.toSchema()) } } append("}\n") } }
apache-2.0
1316b68ad7de74ef177a4622d0f57f29
30.932203
82
0.696391
4.243243
false
false
false
false
Maccimo/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/CommunityLibraryLicenses.kt
1
74619
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") package org.jetbrains.intellij.build import org.jetbrains.intellij.build.LibraryLicense.Companion.jetbrainsLibrary /** * Defines information about licenses of libraries located in 'community', 'contrib' and 'android' repositories. */ object CommunityLibraryLicenses { @JvmStatic @SuppressWarnings("SpellCheckingInspection") val LICENSES_LIST: List<LibraryLicense> = java.util.List.of( LibraryLicense(name = "A fast Java JSON schema validator", libraryName = "json-schema-validator", url = "https://github.com/networknt/json-schema-validator").apache(), LibraryLicense(name = "aalto-xml", libraryName = "aalto-xml", url = "https://github.com/FasterXML/aalto-xml/").apache(), LibraryLicense(name = "AAPT Protos", libraryName = "aapt-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "AhoCorasickDoubleArrayTrie", libraryName = "com.hankcs:aho-corasick-double-array-trie:1.2.2", url = "https://github.com/hankcs/AhoCorasickDoubleArrayTrie").apache(), LibraryLicense(name = "Am Instrument Data proto", libraryName = "libam-instrumentation-data-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Amazon Ion Java", libraryName = "ion", url = "https://github.com/amzn/ion-java").apache(), LibraryLicense(name = "android-test-plugin-host-device-info-proto", libraryName = "android-test-plugin-host-device-info-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "android-test-plugin-host-retention-proto", libraryName = "libstudio.android-test-plugin-host-retention-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "android-test-plugin-result-listener-gradle-proto", libraryName = "libstudio.android-test-plugin-result-listener-gradle-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android ADB Lib", libraryName = "precompiled-adblib", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android AIA Protos", libraryName = "aia-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Analytics Crash", libraryName = "precompiled-analytics-crash", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Analytics Protos", libraryName = "studio-analytics-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Analytics Shared", libraryName = "precompiled-analytics-shared", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Analytics Tracker", libraryName = "precompiled-analytics-tracker", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Annotations", libraryName = "precompiled-android-annotations", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Apk Analyzer", libraryName = "precompiled-analyzer", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Apk Binary Resources", libraryName = "precompiled-binary-resources", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Apk ZLib", libraryName = "apkzlib", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android App Inspector (Background Task, proto)", libraryName = "background-inspector-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android App Inspector (Network, proto)", libraryName = "network_inspector_java_proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Archive Patcher (explainer)", libraryName = "explainer", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Archive Patcher (generator)", libraryName = "generator", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Archive Patcher (shared)", libraryName = "shared", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Baksmali", libraryName = "baksmali", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Builder Model", libraryName = "precompiled-builder-model", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Chunkio", libraryName = "precompiled-chunkio", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Common Library", libraryName = "precompiled-common", url = "https://source.android.com/").apache(), // for android-core-proto module library in intellij.android.core LibraryLicense(name = "Android Core Protos", libraryName = "libandroid-core-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Data Binding Base Library", libraryName = "precompiled-db-baseLibrary", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Data Binding Base Library Support", libraryName = "precompiled-db-baseLibrarySupport", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Data Binding Compiler", libraryName = "precompiled-db-compiler", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Data Binding Compiler Common", libraryName = "precompiled-db-compilerCommon", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Ddm libapp-processes-proto", libraryName = "libapp-processes-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Ddm Library", libraryName = "precompiled-ddmlib", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Deployer Library", libraryName = "precompiled-deployer", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Deployer Library (libjava_sites)", libraryName = "libjava_sites", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android DEX library", libraryName = "dexlib2", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android draw9patch library", libraryName = "precompiled-draw9patch", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android dvlib library", libraryName = "precompiled-dvlib", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Dynamic Layout Inspector", libraryName = "precompiled-dynamic-layout-inspector.common", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Emulator gRPC API", url = "https://source.android.com/", libraryName = "emulator-proto").apache(), LibraryLicense(name = "Android Flags", libraryName = "precompiled-flags", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Gradle model", attachedTo = "intellij.android.core", version = "0.4-SNAPSHOT", url = "https://android.googlesource.com/platform/tools/build/+/master/gradle-model/").apache(), LibraryLicense(name = "Android Instant Apps SDK API", url = "https://source.android.com/", libraryName = "instantapps-api", version = LibraryLicense.CUSTOM_REVISION).apache(), LibraryLicense(name = "Android Jetifier Core", libraryName = "jetifier-core", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Jimfs library", libraryName = "jimfs", url = "https://github.com/google/jimfs").apache(), LibraryLicense(name = "Android Layout Api Library", libraryName = "precompiled-layoutlib-api", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Layout Inspector", libraryName = "precompiled-layoutinspector", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Layout Inspector (Compose Proto)", libraryName = "layout_inspector_compose_java_proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Layout Inspector (Skia Proto)", libraryName = "layoutinspector-skia-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Layout Inspector (Snapshot Proto)", libraryName = "layout_inspector_snapshot_java_proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Layout Inspector (View Proto)", libraryName = "layout_inspector_view_java_proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Layout Library", libraryName = "layoutlib", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android libwebp library", libraryName = "libwebp.jar", url = "https://github.com/webmproject/libwebp", version = LibraryLicense.CUSTOM_REVISION).apache(), LibraryLicense(name = "Android Lint Api", libraryName = "precompiled-lint-api", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Lint Checks", libraryName = "precompiled-lint-checks", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Lint Model", libraryName = "precompiled-lint-model", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Manifest Merger", libraryName = "precompiled-manifest-merger", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Manifest Parser", libraryName = "precompiled-manifest-parser", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android MLKit Common Library", libraryName = "precompiled-mlkit-common", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android ninepatch Library", libraryName = "precompiled-ninepatch", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Perf-Logger Library", libraryName = "precompiled-perf-logger", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Perflib Library", libraryName = "precompiled-perflib", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Pixelprobe Library", libraryName = "precompiled-pixelprobe", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Profiler", libraryName = "studio-grpc", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Repository", libraryName = "precompiled-repository", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Resource Repository", libraryName = "precompiled-resource-repository", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Sdk Common", libraryName = "precompiled-sdk-common", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Sdk Lib", libraryName = "precompiled-sdklib", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android STracer", libraryName = "precompiled-tracer", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android USB Devices", libraryName = "precompiled-usb-devices", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Wizard Template", libraryName = "precompiled-wizardTemplate.impl", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Wizard Template Plugin", libraryName = "precompiled-wizardTemplate.plugin", url = "https://source.android.com/").apache(), LibraryLicense(name = "Android Zipflinger", libraryName = "precompiled-zipflinger", url = "https://source.android.com/").apache(), LibraryLicense(name = "AndroidX Compose Compiler (Hosted)", libraryName = "compiler-hosted-1.1.0-SNAPSHOT.jar", version = "1.1.0-SNAPSHOT", url = "https://source.android.com/").apache(), LibraryLicense(name = "AndroidX Test Library", libraryName = "utp-core-proto", url = "https://source.android.com/").apache(), // for androidx-test-core-proto module library in intellij.android.core LibraryLicense(name = "AndroidX Test Library core protos", libraryName = "androidx-test-core-proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "ANTLR 4.5", libraryName = "compilerCommon.antlr.shaded", url = "https://www.antlr.org", licenseUrl = "https://www.antlr.org/license.html").newBsd(), LibraryLicense(name = "ANTLR 4.5 Runtime", libraryName = "compilerCommon.antlr_runtime.shaded", url = "https://www.antlr.org", licenseUrl = "https://www.antlr.org/license.html").newBsd(), LibraryLicense(name = "ANTLR 4.9 Runtime", libraryName = "antlr4-runtime-4.9", url = "https://www.antlr.org", licenseUrl = "https://www.antlr.org/license.html").newBsd(), LibraryLicense(name = "ap-validation", libraryName = "ap-validation", url = "https://github.com/JetBrains/ap-validation").apache(), LibraryLicense(name = "Apache Ant", version = "1.9", libraryName = "Ant", url = "https://ant.apache.org/", licenseUrl = "https://ant.apache.org/license.html").apache(), LibraryLicense(name = "Apache Axis", libraryName = "axis-1.4", version = "1.4", url = "https://ws.apache.org/axis/").apache(), LibraryLicense(name = "Apache Commons BeanUtils", libraryName = "commons-beanutils.jar", version = "1.6", url = "https://commons.apache.org/beanutils/").apache(), LibraryLicense(name = "Apache Commons CLI", libraryName = "commons-cli", url = "https://commons.apache.org/cli/").apache(), LibraryLicense(name = "Apache Commons Codec", libraryName = "commons-codec", url = "https://commons.apache.org/codec/").apache(), LibraryLicense(name = "Apache Commons Collections", libraryName = "commons-collections", url = "https://commons.apache.org/proper/commons-collections/").apache(), LibraryLicense(name = "Apache Commons Compress", libraryName = "commons-compress", url = "https://commons.apache.org/proper/commons-compress/").apache(), LibraryLicense(name = "Apache Commons Discovery", libraryName = "commons-discovery", url = "https://jakarta.apache.org/commons/discovery/").apache(), LibraryLicense(name = "Apache Commons HTTPClient", libraryName = "http-client-3.1", version = "3.1&nbsp; (with patch by JetBrains)", url = "https://hc.apache.org/httpclient-3.x").apache(), LibraryLicense(name = "Apache Commons Imaging (JetBrains's fork)", libraryName = "commons-imaging", url = "https://github.com/JetBrains/intellij-deps-commons-imaging").apache(), LibraryLicense(name = "Apache Commons IO", libraryName = "commons-io", url = "https://commons.apache.org/io/").apache(), LibraryLicense(name = "Apache Commons Lang", libraryName = "commons-lang", url = "https://commons.apache.org/proper/commons-lang/").apache(), LibraryLicense(name = "Apache Commons Lang", libraryName = "commons-lang3", url = "https://commons.apache.org/proper/commons-lang/").apache(), LibraryLicense(name = "Apache Commons Logging", libraryName = "commons-logging", url = "https://commons.apache.org/logging/").apache(), LibraryLicense(name = "Apache Commons Net", libraryName = "commons-net", url = "https://commons.apache.org/net/").apache(), LibraryLicense(name = "Apache Commons Text", libraryName = "org.apache.commons:commons-text:1.8", url = "https://github.com/apache/commons-text").apache(), LibraryLicense(name = "Apache Ivy", libraryName = "org.apache.ivy", url = "https://github.com/apache/ant-ivy").apache(), LibraryLicense(name = "Apache Lucene", libraryName = "lucene-core", url = "https://lucene.apache.org/java", additionalLibraryNames = listOf( "lucene-suggest", "lucene-memory", "lucene-sandbox", "lucene-codecs", "lucene-highlighter", "lucene-queryparser", "lucene-queries", "lucene-analyzers-common", "org.apache.lucene:lucene-core:2.4.1" )).apache(), LibraryLicense(name = "Apache Tuweni-Toml", libraryName = "tuweni-toml", url = "https://github.com/apache/incubator-tuweni/tree/main/toml").apache(), LibraryLicense(name = "ASM (JetBrains's fork)", libraryName = "ASM", url = "https://github.com/JetBrains/intellij-deps-asm", licenseUrl = "https://github.com/JetBrains/intellij-deps-asm/blob/master/LICENSE.txt", additionalLibraryNames = listOf("asm-capture")).newBsd(), LibraryLicense(name = "ASM Tools", libraryName = "asm-tools", url = "https://asm.ow2.io", licenseUrl = "https://asm.ow2.io/license.html").newBsd(), LibraryLicense(name = "AssertJ fluent assertions", libraryName = "assertJ", url = "https://joel-costigliola.github.io/assertj/").apache(), LibraryLicense(name = "AssertJ Swing", libraryName = "assertj-swing", url = "https://github.com/assertj/assertj-swing").apache(), LibraryLicense(name = "Automaton", libraryName = "automaton", url = "https://www.brics.dk/automaton/").simplifiedBsd(), LibraryLicense(name = "batik", libraryName = "batik-transcoder", url = "https://xmlgraphics.apache.org/batik/").apache(), LibraryLicense(name = "batik", libraryName = "batik-codec", url = "https://xmlgraphics.apache.org/batik/").apache(), LibraryLicense(libraryName = "blockmap", url = "https://github.com/JetBrains/plugin-blockmap-patches").apache(), LibraryLicense(libraryName = "bouncy-castle-provider", url = "https://bouncycastle.org", licenseUrl = "https://bouncycastle.org/licence.html").mit(), LibraryLicense(name = "Byte Buddy agent", libraryName = "byte-buddy-agent", url = "https://github.com/raphw/byte-buddy").apache(), LibraryLicense(name = "caffeine", libraryName = "caffeine", url = "https://github.com/ben-manes/caffeine", licenseUrl = "https://github.com/ben-manes/caffeine/blob/master/LICENSE").apache(), LibraryLicense(name = "CGLib", libraryName = "CGLIB", url = "https://cglib.sourceforge.net/").apache(), LibraryLicense(name = "classgraph", libraryName = "classgraph", url = "https://github.com/classgraph/classgraph", licenseUrl = "https://github.com/codehaus/classworlds/blob/master/classworlds/LICENSE.txt").mit(), LibraryLicense(name = "classworlds", libraryName = "Maven", transitiveDependency = true, version = "1.1", license = "codehaus", url = "https://github.com/codehaus/classworlds", licenseUrl = "https://github.com/codehaus/classworlds/blob/master/classworlds/LICENSE.txt"), LibraryLicense(name = "Common Annotations for the JavaTM Platform API", libraryName = "javax.annotation-api", url = "https://github.com/javaee/javax.annotation", license = "CDDL 1.1 / GPL 2.0 + Classpath", licenseUrl = "https://oss.oracle.com/licenses/CDDL+GPL-1.1"), // for ui-animation-tooling-internal module library in intellij.android.compose-designer LibraryLicense(name = "Compose Animation Tooling", libraryName = "ui-animation-tooling-internal", version = "0.1.0-SNAPSHOT", url = "https://source.android.com/").apache(), // For ADB wireless QR Code generation LibraryLicense(name = "Core barcode encoding/decoding library", url = "https://github.com/zxing/zxing/tree/master/core", libraryName = "zxing-core").apache(), LibraryLicense(name = "coverage-report", libraryName = "coverage-report", url = "https://github.com/JetBrains/coverage-report").apache(), LibraryLicense(name = "coverage.py", attachedTo = "intellij.python", version = "4.2.0", url = "https://coverage.readthedocs.io/", licenseUrl = "https://github.com/nedbat/coveragepy/blob/master/LICENSE.txt").apache(), LibraryLicense(name = "Cucumber-Core", libraryName = "cucumber-core-1.2", url = "https://github.com/cucumber/cucumber-jvm/").mit(), LibraryLicense(name = "Cucumber-Expressions", libraryName = "cucumber-expressions", url = "https://github.com/cucumber/cucumber/").mit(), LibraryLicense(name = "Cucumber-Groovy", libraryName = "cucumber-groovy", url = "https://github.com/cucumber/cucumber-jvm/").mit(), LibraryLicense(name = "Cucumber-Java", libraryName = "cucumber-java", url = "https://github.com/cucumber/cucumber-jvm/").mit(), LibraryLicense(name = "Dart Analysis Server", attachedTo = "intellij.dart", url = "https://github.com/dart-lang/eclipse3", version = LibraryLicense.CUSTOM_REVISION).eplV1(), LibraryLicense(name = "Dart VM Service drivers", attachedTo = "intellij.dart", licenseUrl = "https://github.com/dart-lang/vm_service_drivers/blob/master/LICENSE", url = "https://github.com/dart-lang/vm_service_drivers", version = LibraryLicense.CUSTOM_REVISION).newBsd(), LibraryLicense(name = "dbus-java", libraryName = "dbus-java", license = "LGPL", url = "https://mvnrepository.com/artifact/com.github.hypfvieh/dbus-java"), LibraryLicense(name = "DecentXML", libraryName = "decentxml", url = "https://code.google.com/p/decentxml").newBsd(), LibraryLicense(name = "docutils", attachedTo = "intellij.python", version = "0.12", license = "BSD", url = "https://docutils.sourceforge.io/"), LibraryLicense(libraryName = "DTDParser", version = "1.13", license = "LGPL", url = "https://sourceforge.net/projects/dtdparser/", licenseUrl = "https://www.opensource.org/licenses/lgpl-2.1"), LibraryLicense(name = "Eclipse JDT Core", attachedTo = "intellij.platform.jps.build", version = "4.2.1", license = "CPL 1.0", url = "https://www.eclipse.org/jdt/core/index.php"), LibraryLicense(name = "Eclipse Layout Kernel", url = "https://www.eclipse.org/elk/", libraryName = "eclipse-layout-kernel").eplV1(), LibraryLicense(name = "EditorConfig Java Core", libraryName = "editorconfig-core-java.jar", version = "1.0", url = "https://github.com/editorconfig/editorconfig-core-java/", licenseUrl = "https://github.com/editorconfig/editorconfig-core-java/blob/master/LICENSE").apache(), LibraryLicense(name = "emoji-java", libraryName = "com.vdurmont:emoji-java:5.1.1", url = "https://github.com/vdurmont/emoji-java").mit(), LibraryLicense(name = "entities", url = "https://github.com/fb55/entities", attachedTo = "intellij.vuejs", licenseUrl = "https://github.com/fb55/entities/blob/master/LICENSE", version = LibraryLicense.CUSTOM_REVISION).simplifiedBsd(), LibraryLicense(name = "epydoc", attachedTo = "intellij.python", version = "3.0.1", url = "https://epydoc.sourceforge.net/").mit(), LibraryLicense(name = "error-prone-annotations", libraryName = "error-prone-annotations", url = "https://github.com/google/error-prone", licenseUrl = "https://github.com/google/error-prone/blob/master/COPYING").apache(), LibraryLicense(name = "fastutil", libraryName = "fastutil-min", url = "https://github.com/vigna/fastutil", licenseUrl = "https://github.com/vigna/fastutil/blob/master/LICENSE-2.0").apache(), LibraryLicense(name = "FiraCode", attachedTo = "intellij.platform.resources", version = "1.206", license = "OFL", url = "https://github.com/tonsky/FiraCode", licenseUrl = "https://github.com/tonsky/FiraCode/blob/master/LICENSE"), // for flatbuffers-java module library in android.sdktools.mlkit-common LibraryLicense(name = "FlatBuffers Java API", libraryName = "flatbuffers-java", url = "https://google.github.io/flatbuffers/").apache(), LibraryLicense(name = "FreeMarker", attachedTo = "intellij.java.coverage", version = "2.3.30", url = "https://freemarker.apache.org", licenseUrl = "https://freemarker.apache.org/docs/app_license.html").apache(), LibraryLicense(name = "gauge-java", libraryName = "com.thoughtworks.gauge:gauge-java", url = "https://github.com/getgauge/gauge-java/", licenseUrl = "https://raw.githubusercontent.com/getgauge/gauge-java/master/LICENSE.txt").apache(), LibraryLicense(name = "Gherkin", libraryName = "gherkin", licenseUrl = "https://github.com/cucumber/cucumber/blob/master/gherkin/LICENSE", url = "https://github.com/cucumber/cucumber/tree/master/gherkin").mit(), LibraryLicense(name = "Gherkin keywords", attachedTo = "intellij.gherkin", version = "2.12.2", licenseUrl = "https://github.com/cucumber/cucumber/blob/master/gherkin/LICENSE", url = "https://github.com/cucumber/cucumber/tree/master/gherkin").mit(), LibraryLicense(name = "Google Auto Common Utilities", libraryName = "auto-common", url = "https://github.com/google/auto/tree/master/common").apache(), LibraryLicense(name = "Google Drive API V3", libraryName = "google.apis.api.services.drive", url = "https://github.com/googleapis/google-api-java-client-services/tree/master/clients/google-api-services-drive/v3", licenseUrl = "https://github.com/googleapis/google-api-java-client-services/blob/master/LICENSE").apache(), LibraryLicense(libraryName = "Gradle", url = "https://gradle.org/", licenseUrl = "https://gradle.org/license").apache(), LibraryLicense(name = "Grazie AI", libraryName = "ai.grazie.spell.gec.local.engine", url = "https://packages.jetbrains.team/maven/p/grazi/grazie-platform-public/", additionalLibraryNames = listOf("ai.grazie.nlp.patterns", "ai.grazie.nlp.phonetics", "ai.grazie.nlp.common", "ai.grazie.nlp.langs", "ai.grazie.nlp.similarity", "ai.grazie.nlp-tokenizer", "ai.grazie.nlp.detect", "ai.grazie.nlp.stemmer", "ai.grazie.nlp.tokenizer", "ai.grazie.utils.common", "ai.grazie.utils.json", "ai.grazie.model.gec", "ai.grazie.model.text", "ai.grazie.spell.hunspell.en")).apache(), LibraryLicense(name = "Groovy", libraryName = "org.codehaus.groovy:groovy", url = "https://groovy-lang.org/").apache(), LibraryLicense(name = "Groovy Ant", libraryName = "org.codehaus.groovy:groovy-ant", url = "https://groovy-lang.org/").apache(), LibraryLicense(name = "Groovy JSON", libraryName = "org.codehaus.groovy:groovy-json", url = "https://groovy-lang.org/").apache(), LibraryLicense(name = "Groovy JSR-223", libraryName = "org.codehaus.groovy:groovy-jsr223", url = "https://groovy-lang.org/").apache(), LibraryLicense(name = "Groovy Templates", libraryName = "org.codehaus.groovy:groovy-templates", url = "https://groovy-lang.org/").apache(), LibraryLicense(name = "Groovy XML", libraryName = "org.codehaus.groovy:groovy-xml", url = "https://groovy-lang.org/").apache(), LibraryLicense(name = "gRPC Kotlin: Stub", libraryName = "grpc-kotlin-stub", url = "https://grpc.io/").apache(), LibraryLicense(name = "gRPC: Core", libraryName = "grpc-core", url = "https://grpc.io/").apache(), LibraryLicense(name = "gRPC: Netty Shaded", libraryName = "grpc-netty-shaded", url = "https://grpc.io/").apache(), LibraryLicense(name = "gRPC: Protobuf", libraryName = "grpc-protobuf", url = "https://grpc.io/").apache(), LibraryLicense(name = "gRPC: Stub", libraryName = "grpc-stub", url = "https://grpc.io/").apache(), LibraryLicense(name = "Gson", libraryName = "gson", url = "https://code.google.com/p/google-gson/").apache(), LibraryLicense(libraryName = "Guava", url = "https://github.com/google/guava", licenseUrl = "https://github.com/google/guava/blob/master/COPYING").apache(), LibraryLicense(name = "Hamcrest", libraryName = "hamcrest", url = "https://hamcrest.org/").newBsd(), LibraryLicense(name = "HDR Histogram", libraryName = "HdrHistogram", license = "CC0 1.0 Universal", url = "https://github.com/HdrHistogram/HdrHistogram", licenseUrl = "https://github.com/HdrHistogram/HdrHistogram/blob/master/LICENSE.txt"), LibraryLicense(name = "hppc", url = "https://github.com/carrotsearch/hppc", libraryName = "com.carrotsearch:hppc:0.8.2").apache(), LibraryLicense(name = "htmlparser2", url = "https://github.com/fb55/htmlparser2", attachedTo = "intellij.vuejs", licenseUrl = "https://github.com/fb55/htmlparser2/blob/master/LICENSE", version = LibraryLicense.CUSTOM_REVISION).mit(), LibraryLicense(name = "HttpComponents HttpClient", libraryName = "http-client", url = "https://hc.apache.org/httpcomponents-client-ga/index.html").apache(), LibraryLicense(name = "HttpComponents HttpClient Fluent API", libraryName = "fluent-hc", url = "https://hc.apache.org/httpcomponents-client-ga/index.html").apache(), LibraryLicense(name = "ICU4J", libraryName = "icu4j", license = "Unicode", url = "https://site.icu-project.org/", licenseUrl = "https://www.unicode.org/copyright.html"), LibraryLicense(name = "imgscalr", libraryName = "imgscalr", url = "https://github.com/thebuzzmedia/imgscalr").apache(), LibraryLicense(name = "Inconsolata", attachedTo = "intellij.platform.resources", version = "001.010", license = "OFL", url = "https://github.com/google/fonts/tree/main/ofl/inconsolata", licenseUrl = "https://github.com/google/fonts/blob/master/ofl/inconsolata/OFL.txt"), LibraryLicense(name = "Incremental DOM", attachedTo = "intellij.markdown", version = "0.7.0", url = "https://github.com/google/incremental-dom").apache(), LibraryLicense(name = "indriya", libraryName = "tech.units:indriya:1.3", url = "https://github.com/unitsofmeasurement/indriya", licenseUrl = "https://github.com/unitsofmeasurement/indriya/blob/master/LICENSE").newBsd(), LibraryLicense(name = "ini4j (JetBrains's fork)", libraryName = "ini4j", url = "https://github.com/JetBrains/intellij-deps-ini4j").apache(), LibraryLicense(name = "Instant run protos", libraryName = "deploy_java_proto", url = "https://source.android.com/").apache(), LibraryLicense(name = "Instant run version", libraryName = "libjava_version", url = "https://source.android.com/").apache(), LibraryLicense(name = "ISO RELAX", libraryName = "isorelax", url = "https://sourceforge.net/projects/iso-relax/").mit(), LibraryLicense(name = "Jackson", libraryName = "jackson", url = "https://github.com/FasterXML/jackson").apache(), LibraryLicense(name = "jackson-jr-objects", libraryName = "jackson-jr-objects", url = "https://github.com/FasterXML/jackson-jr").apache(), LibraryLicense(name = "Jackson Databind", libraryName = "jackson-databind", url = "https://github.com/FasterXML/jackson-databind").apache(), LibraryLicense(name = "Jackson Module Kotlin", libraryName = "jackson-module-kotlin", url = "https://github.com/FasterXML/jackson-module-kotlin").apache(), LibraryLicense(name = "JaCoCo", libraryName = "JaCoCo", url = "https://www.eclemma.org/jacoco/").eplV1(), LibraryLicense(name = "Jakarta ORO", libraryName = "OroMatcher", url = "https://jakarta.apache.org/oro/", licenseUrl = "https://svn.apache.org/repos/asf/jakarta/oro/trunk/LICENSE").apache(), LibraryLicense(name = "Jarchivelib", libraryName = "rauschig.jarchivelib", url = "https://github.com/thrau/jarchivelib").apache(), LibraryLicense(libraryName = "Java Compatibility", license = "GPL 2.0 + Classpath", url = "https://github.com/JetBrains/intellij-deps-java-compatibility", licenseUrl = "https://raw.githubusercontent.com/JetBrains/intellij-deps-java-compatibility/master/LICENSE"), LibraryLicense(name = "Java Native Runtime Constants", libraryName = "github.jnr.constants", url = "https://github.com/jnr/jnr-constants").apache(), LibraryLicense(name = "Java Poet", libraryName = "javapoet", url = "https://github.com/square/javapoet").apache(), LibraryLicense(name = "Java Server Pages (JSP) for Visual Studio Code", attachedTo = "intellij.textmate", version = "0.0.3", url = "https://github.com/pthorsson/vscode-jsp", licenseUrl = "https://github.com/pthorsson/vscode-jsp/blob/master/LICENSE").mit(), LibraryLicense(name = "Java Simple Serial Connector", libraryName = "io.github.java.native.jssc", url = "https://github.com/java-native/jssc", license = "LGPL 3.0", licenseUrl = "https://github.com/java-native/jssc/blob/master/LICENSE.txt"), LibraryLicense(name = "Java String Similarity", libraryName = "java-string-similarity", licenseUrl = "https://github.com/tdebatty/java-string-similarity/blob/master/LICENSE.md", url = "https://github.com/tdebatty/java-string-similarity").mit(), LibraryLicense(name = "JavaBeans Activation Framework", libraryName = "javax.activation", url = "https://github.com/javaee/activation", license = "CDDL 1.1 / GPL 2.0 + Classpath", licenseUrl = "https://oss.oracle.com/licenses/CDDL+GPL-1.1"), LibraryLicense(name = "javaslang", libraryName = "javaslang", url = "https://javaslang.io/").apache(), LibraryLicense(name = "javawriter", attachedTo = "intellij.android.core", url = "https://github.com/square/javawriter", version = LibraryLicense.CUSTOM_REVISION).apache(), LibraryLicense(name = "javax inject", libraryName = "javax-inject", url = "https://code.google.com/p/atinject/").apache(), LibraryLicense(name = "JAXB (Java Architecture for XML Binding) API", libraryName = "jaxb-api", url = "https://github.com/javaee/jaxb-spec", license = "CDDL 1.1 / GPL 2.0 + Classpath", licenseUrl = "https://oss.oracle.com/licenses/CDDL+GPL-1.1"), LibraryLicense(name = "JAXB (JSR 222) Reference Implementation", libraryName = "jaxb-runtime", url = "https://github.com/javaee/jaxb-v2", license = "CDDL 1.1 / GPL 2.0 + Classpath", licenseUrl = "https://oss.oracle.com/licenses/CDDL+GPL-1.1"), LibraryLicense(libraryName = "Jaxen", license = "modified Apache", url = "https://github.com/jaxen-xpath/jaxen", licenseUrl = "https://github.com/jaxen-xpath/jaxen/blob/master/LICENSE.txt"), LibraryLicense(name = "Jayway JsonPath", libraryName = "jsonpath", url = "https://github.com/json-path/JsonPath", licenseUrl = "https://github.com/json-path/JsonPath/blob/master/LICENSE").apache(), LibraryLicense(libraryName = "jb-jdi", license = "GPL 2.0 + Classpath", url = "https://github.com/JetBrains/intellij-deps-jdi", licenseUrl = "https://raw.githubusercontent.com/JetBrains/intellij-deps-jdi/master/LICENSE.txt"), LibraryLicense(name = "JCEF", libraryName = "jcef", license = "BSD 3-Clause", licenseUrl = "https://bitbucket.org/chromiumembedded/java-cef/src/master/LICENSE.txt", url = "https://bitbucket.org/chromiumembedded/java-cef"), LibraryLicense(name = "JCIP Annotations", libraryName = "jcip", license = "Creative Commons Attribution License", url = "https://www.jcip.net", licenseUrl = "https://creativecommons.org/licenses/by/2.5"), LibraryLicense(name = "JCodings", libraryName = "joni", transitiveDependency = true, version = "1.0.55", url = "https://github.com/jruby/jcodings", licenseUrl = "https://github.com/jruby/jcodings/blob/master/pom.xml").mit(), LibraryLicense(name = "JediTerm", libraryName = "jediterm-pty", license = "LGPL 3", url = "https://github.com/JetBrains/jediterm", licenseUrl = "https://github.com/JetBrains/jediterm/blob/master/LICENSE-LGPLv3.txt"), LibraryLicense(name = "JediTerm Type Ahead", libraryName = "jediterm-typeahead", license = "LGPL 3", url = "https://github.com/JetBrains/jediterm", licenseUrl = "https://github.com/JetBrains/jediterm/blob/master/LICENSE-LGPLv3.txt"), LibraryLicense(name = "JetBrains Annotations", libraryName = "jetbrains-annotations", url = "https://github.com/JetBrains/java-annotations").apache(), LibraryLicense(name = "JetBrains Annotations for Java 5", libraryName = "jetbrains-annotations-java5", url = "https://github.com/JetBrains/java-annotations").apache(), LibraryLicense(name = "JetBrains Runtime", attachedTo = "intellij.platform.ide.impl", version = "11", license = "GNU General Public License, version 2, with the Classpath Exception", url = "https://github.com/JetBrains/JetBrainsRuntime", licenseUrl = "https://github.com/JetBrains/JetBrainsRuntime/blob/master/LICENSE"), LibraryLicense(name = "JetBrains Runtime API", libraryName = "jbr-api", url = "https://github.com/JetBrains/JetBrainsRuntime").apache(), LibraryLicense(name = "jetCheck", libraryName = "jetCheck", url = "https://github.com/JetBrains/jetCheck").apache(), LibraryLicense(name = "JGit", libraryName = "JGit", license = "Eclipse Distribution License 1.0", licenseUrl = "https://www.eclipse.org/org/documents/edl-v10.php", url = "https://www.eclipse.org/jgit/"), LibraryLicense(name = "JGit (develar's fork)", libraryName = "jgit-develar", version = "4.0", license = "Eclipse Distribution License 1.0", licenseUrl = "https://www.eclipse.org/org/documents/edl-v10.php", url = "https://github.com/develar/jgit"), LibraryLicense(name = "JGoodies Common", libraryName = "jgoodies-common", url = "https://www.jgoodies.com/freeware/libraries/looks/").simplifiedBsd(), LibraryLicense(name = "JGoodies Forms", libraryName = "jgoodies-forms", url = "https://www.jgoodies.com/freeware/libraries/forms/").simplifiedBsd(), LibraryLicense(name = "JNA", libraryName = "jna", license = "LGPL 2.1", url = "https://github.com/java-native-access/jna", licenseUrl = "https://www.opensource.org/licenses/lgpl-2.1.php"), LibraryLicense(name = "JNR-FFI", libraryName = "github.jnr.ffi", url = "https://github.com/jnr/jnr-ffi").apache(), LibraryLicense(name = "jnr-unixsocket", libraryName = "github.jnr.unixsocket", url = "https://github.com/jnr/jnr-unixsocket").apache(), LibraryLicense(name = "Joni", libraryName = "joni", url = "https://github.com/jruby/joni", licenseUrl = "https://github.com/jruby/joni/blob/master/LICENSE").mit(), LibraryLicense(name = "jps-javac-extension", libraryName = "jps-javac-extension", url = "https://github.com/JetBrains/jps-javac-extension/", licenseUrl = "https://github.com/JetBrains/jps-javac-extension/blob/master/LICENSE.txt").apache(), LibraryLicense(name = "JSch", libraryName = "JSch", url = "https://www.jcraft.com/jsch/", licenseUrl = "https://www.jcraft.com/jsch/LICENSE.txt").newBsd(), LibraryLicense(name = "jsch-agent-proxy", libraryName = "jsch-agent-proxy", url = "https://github.com/ymnk/jsch-agent-proxy", licenseUrl = "https://github.com/ymnk/jsch-agent-proxy/blob/master/LICENSE.txt").newBsd(), LibraryLicense(name = "JSON", libraryName = "json.jar", license = "JSON License", licenseUrl = "https://www.json.org/license.html", url = "https://www.json.org/", version = LibraryLicense.CUSTOM_REVISION), LibraryLicense(name = "JSON in Java", libraryName = "org.json:json:20170516", license = "JSON License", licenseUrl = "https://www.json.org/license.html", url = "https://github.com/stleary/JSON-java"), LibraryLicense(name = "JSON Schema (schema.json)", attachedTo = "intellij.json", version = "draft-04", url = "https://json-schema.org/draft-04/schema#").simplifiedBsd(), LibraryLicense(name = "JSON Schema (schema06.json)", attachedTo = "intellij.json", version = "draft-06", url = "https://json-schema.org/draft-06/schema#").simplifiedBsd(), LibraryLicense(name = "JSON Schema (schema07.json)", attachedTo = "intellij.json", version = "draft-07", url = "https://json-schema.org/draft-07/schema#").simplifiedBsd(), LibraryLicense(name = "jsoup", libraryName = "jsoup", url = "https://jsoup.org", licenseUrl = "https://jsoup.org/license").mit(), LibraryLicense(name = "jsr305", libraryName = "jsr305", url = "https://code.google.com/p/jsr-305/", licenseUrl = "https://code.google.com/p/jsr-305/source/browse/trunk/ri/LICENSE").newBsd(), LibraryLicense(name = "JUnit", libraryName = "JUnit3", license = "CPL 1.0", url = "https://junit.org/"), LibraryLicense(name = "JUnit", libraryName = "JUnit4", url = "https://junit.org/").eplV1(), LibraryLicense(name = "JUnit5", libraryName = "JUnit5", url = "https://junit.org/junit5/").eplV2(), LibraryLicense(name = "JUnit5Jupiter", libraryName = "JUnit5Jupiter", url = "https://junit.org/junit5/").eplV2(), LibraryLicense(name = "JUnit5Launcher", libraryName = "JUnit5Launcher", url = "https://junit.org/junit5/").eplV2(), LibraryLicense(name = "JUnit5Vintage", libraryName = "JUnit5Vintage", url = "https://junit.org/junit5/").eplV2(), LibraryLicense(name = "Juniversalchardet", libraryName = "juniversalchardet", url = "https://code.google.com/archive/p/juniversalchardet", license = "MPL 1.1", licenseUrl = "https://www.mozilla.org/MPL/MPL-1.1.html"), LibraryLicense(name = "jzlib", libraryName = "jzlib", url = "https://www.jcraft.com/jzlib/", licenseUrl = "https://www.jcraft.com/jzlib/LICENSE.txt").newBsd(), LibraryLicense(name = "Kodein-DI", libraryName = "kodein-di-jvm", url = "https://github.com/Kodein-Framework/Kodein-DI/blob/master/LICENSE.txt").mit(), LibraryLicense(name = "Kotlin Coroutines for Guava", libraryName = "kotlinx-coroutines-guava", url = "https://github.com/Kotlin/kotlinx.coroutines").apache(), LibraryLicense(name = "Kotlin Coroutines for JDK 8", libraryName = "kotlinx-coroutines-jdk8", url = "https://github.com/Kotlin/kotlinx.coroutines").apache(), LibraryLicense(name = "Kotlin Coroutines for Slf4j", libraryName = "kotlinx-coroutines-slf4j", url = "https://github.com/Kotlin/kotlinx.coroutines").apache(), LibraryLicense(name = "Kotlin Gradle Plugin Model", libraryName = "kotlin-gradle-plugin-model", url = "https://github.com/JetBrains/kotlin/tree/master/libraries/tools/kotlin-gradle-plugin-model").apache(), LibraryLicense(name = "Kotlin multiplatform / multi-format serialization", libraryName = "kotlinx-serialization-core", url = "https://github.com/Kotlin/kotlinx.serialization").apache(), LibraryLicense(name = "Kotlin multiplatform / multi-format serialization", libraryName = "kotlinx-serialization-json", url = "https://github.com/Kotlin/kotlinx.serialization").apache(), LibraryLicense(name = "Kotlin multiplatform / multi-format serialization", libraryName = "kotlinx-serialization-protobuf", url = "https://github.com/Kotlin/kotlinx.serialization").apache(), LibraryLicense(name = "Kotlin reflection library", libraryName = "kotlin-reflect", url = "https://github.com/JetBrains/kotlin").apache(), LibraryLicense(name = "Kotlin Standard Library for JDK 8", libraryName = "kotlin-stdlib-jdk8", url = "https://github.com/JetBrains/kotlin").apache(), LibraryLicense(name = "kotlinx-datetime", libraryName = "kotlinx-datetime", url = "https://github.com/Kotlin/kotlinx-datetime").apache(), LibraryLicense(name = "kotlinx-datetime-jvm", libraryName = "kotlinx-datetime-jvm", url = "https://github.com/Kotlin/kotlinx-datetime").apache(), LibraryLicense(name = "kotlinx.html", libraryName = "org.jetbrains.kotlinx:kotlinx-html-jvm:0.7.3", licenseUrl = "https://github.com/Kotlin/kotlinx.html/blob/master/LICENSE", url = "https://github.com/Kotlin/kotlinx.html").apache(), LibraryLicense(name = "Kryo", libraryName = "Kryo", url = "https://github.com/EsotericSoftware/kryo", licenseUrl = "https://github.com/EsotericSoftware/kryo/blob/master/LICENSE.md").newBsd(), LibraryLicense(name = "kXML2", libraryName = "kxml2", license = "BSD", url = "https://sourceforge.net/projects/kxml/"), LibraryLicense(name = "Language Tool", libraryName = "org.languagetool:languagetool-core:5.7", url = "https://github.com/languagetool-org/languagetool", license = "LGPL 2.1", licenseUrl = "https://www.gnu.org/licenses/lgpl-2.1.txt"), LibraryLicense(name = "Language Tool (English)", libraryName = "org.languagetool:language-en:5.7", url = "https://github.com/languagetool-org/languagetool", license = "LGPL 2.1", licenseUrl = "https://www.gnu.org/licenses/lgpl-2.1.txt"), LibraryLicense(name = "Log4j", libraryName = "Log4J", url = "https://www.slf4j.org/legacy.html#log4j-over-slf4j").apache(), LibraryLicense(name = "lz4-java", libraryName = "lz4-java", url = "https://github.com/lz4/lz4-java", licenseUrl = "https://github.com/lz4/lz4-java/blob/master/LICENSE.txt").apache(), LibraryLicense(name = "markdown4j", libraryName = "markdown4j", url = "https://code.google.com/p/markdown4j/").newBsd(), LibraryLicense(name = "MarkdownJ", libraryName = "markdownj", version = "0.4.2", url = "https://github.com/myabc/markdownj").newBsd(), LibraryLicense(name = "MathJax", attachedTo = "intellij.python", version = "2.6.1", url = "git://github.com/mathjax/MathJax", licenseUrl = "https://github.com/mathjax/MathJax/blob/master/LICENSE").apache(), LibraryLicense(libraryName = "Maven", version = "2.2.1", url = "https://maven.apache.org/").apache(), LibraryLicense(name = "maven-2.2.1-uber", version = "2.2.1", libraryName = "maven-2.2.1-uber.jar", url = "https://maven.apache.org/").apache(), LibraryLicense(name = "Maven Model", libraryName = "maven-model", url = "https://maven.apache.org/").apache(), LibraryLicense(name = "Maven Resolver Provider", url = "https://maven.apache.org/ref/3.6.1/maven-resolver-provider/", libraryName = "maven-resolver-provider", additionalLibraryNames = listOf("org.apache.maven.resolver:maven-resolver-connector-basic", "org.apache.maven.resolver:maven-resolver-transport-http", "org.apache.maven.resolver:maven-resolver-transport-file")).apache(), LibraryLicense(name = "Maven Wrapper", libraryName = "io.takari.maven.wrapper", url = "https://github.com/takari/maven-wrapper").apache(), LibraryLicense(name = "Maven3", attachedTo = "intellij.maven.server.m3.common", additionalLibraryNames = listOf("org.apache.maven.shared:maven-dependency-tree:1.2", "org.apache.maven.archetype:archetype-common:2.2"), version = "3.6.1", url = "https://maven.apache.org/").apache(), LibraryLicense(name = "Memory File System", libraryName = "memoryfilesystem", url = "https://github.com/marschall/memoryfilesystem").mit(), LibraryLicense(name = "mercurial_prompthooks", attachedTo = "intellij.vcs.hg", version = LibraryLicense.CUSTOM_REVISION, license = "GPLv2 (used as hg extension called from hg executable)", url = "https://github.com/willemv/mercurial_prompthooks", licenseUrl = "https://github.com/willemv/mercurial_prompthooks/blob/master/LICENSE.txt"), LibraryLicense(name = "Microba", libraryName = "microba", version = "0.4.2", url = "https://microba.sourceforge.net/", licenseUrl = "https://microba.sourceforge.net/license.txt").newBsd(), LibraryLicense(name = "MigLayout", libraryName = "miglayout-swing", url = "https://www.miglayout.com/", licenseUrl = "https://www.miglayout.com/mavensite/license.html").newBsd(), LibraryLicense(name = "minlog", libraryName = "Kryo", transitiveDependency = true, version = "1.2", url = "https://github.com/EsotericSoftware/minlog").newBsd(), LibraryLicense(name = "morfologik-fsa", libraryName = "org.carrot2:morfologik-fsa:2.1.7", url = "https://github.com/morfologik/morfologik-stemming").simplifiedBsd(), LibraryLicense(name = "morfologik-fsa-builders", libraryName = "org.carrot2:morfologik-fsa-builders:2.1.7", url = "https://github.com/morfologik/morfologik-stemming").simplifiedBsd(), LibraryLicense(name = "morfologik-speller", libraryName = "org.carrot2:morfologik-speller:2.1.7", url = "https://github.com/morfologik/morfologik-stemming").simplifiedBsd(), LibraryLicense(name = "morfologik-stemming", libraryName = "org.carrot2:morfologik-stemming:2.1.7", url = "https://github.com/morfologik/morfologik-stemming").simplifiedBsd(), LibraryLicense(name = "Moshi", libraryName = "moshi", url = "https://github.com/square/moshi").apache(), LibraryLicense(libraryName = "NanoXML", license = "zlib/libpng", url = "https://mvnrepository.com/artifact/be.cyberelf.nanoxml/nanoxml/2.2.3", licenseUrl = "https://www.opensource.org/licenses/zlib-license.html"), LibraryLicense(name = "net.loomchild.segment", libraryName = "net.loomchild:segment:2.0.1", url = "https://github.com/loomchild/segment", licenseUrl = "https://github.com/loomchild/segment/blob/master/LICENSE.txt").mit(), LibraryLicense(name = "netty-buffer", libraryName = "netty-buffer", url = "https://netty.io").apache(), LibraryLicense(name = "netty-codec-http", libraryName = "netty-codec-http", url = "https://netty.io").apache(), LibraryLicense(name = "netty-handler-proxy", libraryName = "netty-handler-proxy", url = "https://netty.io").apache(), LibraryLicense(libraryName = "ngram-slp", url = "https://github.com/SLP-team/SLP-Core", licenseUrl = "https://github.com/SLP-team/SLP-Core/blob/master/LICENSE").mit(), LibraryLicense(name = "Objenesis", libraryName = "Objenesis", url = "https://objenesis.org/").apache(), LibraryLicense(name = "OkHttp", libraryName = "okhttp", url = "https://square.github.io/okhttp/").apache(), LibraryLicense(name = "Okio", libraryName = "okio", url = "https://github.com/square/okio").apache(), LibraryLicense(libraryName = "opentelemetry", url = "https://opentelemetry.io/").apache(), LibraryLicense(libraryName = "opentelemetry-exporter-otlp", url = "https://opentelemetry.io/").apache(), LibraryLicense(libraryName = "opentest4j", url = "https://github.com/ota4j-team/opentest4j").apache(), LibraryLicense(name = "Package Search API Models", libraryName = "package-search-api-models", url = "https://github.com/JetBrains/package-search-api-models", version = "2.2.8").apache(), LibraryLicense(name = "Package Search Version Utils", libraryName = "package-search-version-utils", url = "https://github.com/JetBrains/package-search-version-utils", version = "1.0.1").apache(), LibraryLicense(name = "PEPK", libraryName = "pepk", url = "https://source.android.com/", version = LibraryLicense.CUSTOM_REVISION).apache(), LibraryLicense(name = "Perfetto protos", libraryName = "perfetto-proto", url = "https://source.android.com").apache(), LibraryLicense(name = "pip", attachedTo = "intellij.python", version = "20.3.4", url = "https://pip.pypa.io/", licenseUrl = "https://github.com/pypa/pip/blob/main/LICENSE.txt").mit(), LibraryLicense(name = "plexus-archiver", libraryName = "plexus-archiver", url = "https://github.com/codehaus-plexus/plexus-archiver").apache(), LibraryLicense(name = "plexus-classworlds", attachedTo = "intellij.maven.server.m30.impl", version = "2.4", url = "https://github.com/codehaus-plexus/plexus-classworlds").apache(), LibraryLicense(name = "Plexus Utils", libraryName = "plexus-utils", url = "https://plexus.codehaus.org/plexus-utils").apache(), LibraryLicense(name = "PLY", attachedTo = "intellij.python", version = "3.7", url = "https://www.dabeaz.com/ply/").newBsd(), LibraryLicense(name = "pockets", attachedTo = "intellij.python", version = "0.9.1", url = "https://pockets.readthedocs.io/", licenseUrl = "https://github.com/RobRuana/pockets/blob/master/LICENSE").newBsd(), LibraryLicense(name = "Protocol Buffers", libraryName = "protobuf", url = "https://developers.google.com/protocol-buffers", licenseUrl = "https://github.com/google/protobuf/blob/master/LICENSE").newBsd(), LibraryLicense(name = "Protocol Buffers", libraryName = "protobuf-java6", url = "https://developers.google.com/protocol-buffers", licenseUrl = "https://github.com/protocolbuffers/protobuf/blob/v3.5.1/LICENSE").newBsd(), LibraryLicense(name = "Proxy Vole (JetBrains's fork)", libraryName = "proxy-vole", url = "https://github.com/JetBrains/intellij-deps-proxy-vole", licenseUrl = "https://github.com/MarkusBernhardt/proxy-vole/blob/master/LICENSE.md").apache(), LibraryLicense(name = "pty4j", libraryName = "pty4j", url = "https://github.com/JetBrains/pty4j").eplV1(), LibraryLicense(name = "PureJavaComm", libraryName = "pty4j", transitiveDependency = true, version = "0.0.11.1", url = "https://github.com/nyholku/purejavacomm", licenseUrl = "https://github.com/nyholku/purejavacomm/blob/master/LICENSE.txt").newBsd(), LibraryLicense(name = "pycodestyle", attachedTo = "intellij.python", version = "2.8.0", url = "https://pycodestyle.pycqa.org/", licenseUrl = "https://github.com/PyCQA/pycodestyle/blob/main/LICENSE").mit(), LibraryLicense(name = "pyparsing", attachedTo = "intellij.python", version = "1.5.6", url = "https://github.com/pyparsing/pyparsing/", licenseUrl = "https://github.com/pyparsing/pyparsing/blob/master/LICENSE").mit(), LibraryLicense(name = "qdox-java-parser", libraryName = "qdox-java-parser", url = "https://github.com/paul-hammant/qdox").apache(), LibraryLicense(name = "R8 DEX shrinker", libraryName = "jb-r8", url = "https://r8.googlesource.com/r8").newBsd(), LibraryLicense(name = "Relax NG Object Model", libraryName = "rngom-20051226-patched.jar", url = "https://github.com/kohsuke/rngom", version = LibraryLicense.CUSTOM_REVISION).mit(), LibraryLicense(name = "Rhino JavaScript Engine", libraryName = "rhino", license = "MPL 1.1", url = "https://www.mozilla.org/rhino/", licenseUrl = "https://www.mozilla.org/MPL/MPL-1.1.html"), LibraryLicense(name = "Roboto", attachedTo = "intellij.platform.resources", version = "1.100141", url = "https://github.com/googlefonts/roboto", licenseUrl = "https://github.com/google/roboto/blob/master/LICENSE").apache(), LibraryLicense(name = "roman", attachedTo = "intellij.python", version = "1.4.0", url = "https://docutils.sourceforge.io/docutils/utils/roman.py", license = "Python 2.1.1 license", licenseUrl = "https://www.python.org/download/releases/2.1.1/license/"), LibraryLicense(libraryName = "sa-jdwp", license = "GPL 2.0 + Classpath", url = "https://github.com/JetBrains/jdk-sa-jdwp", licenseUrl = "https://raw.githubusercontent.com/JetBrains/jdk-sa-jdwp/master/LICENSE.txt"), LibraryLicense(libraryName = "Saxon-6.5.5", version = "6.5.5", license = "Mozilla Public License", url = "https://saxon.sourceforge.net/", licenseUrl = "https://www.mozilla.org/MPL/"), LibraryLicense(libraryName = "Saxon-9HE", version = "9", license = "Mozilla Public License", url = "https://saxon.sourceforge.net/", licenseUrl = "https://www.mozilla.org/MPL/"), LibraryLicense(name = "setuptools", attachedTo = "intellij.python", version = "44.1.1", url = "https://setuptools.pypa.io/", licenseUrl = "https://github.com/pypa/setuptools/blob/main/LICENSE").mit(), LibraryLicense(name = "six.py", attachedTo = "intellij.python", version = "1.9.0", url = "https://six.readthedocs.io/", licenseUrl = "https://github.com/benjaminp/six/blob/master/LICENSE").mit(), LibraryLicense(libraryName = "Slf4j", url = "https://slf4j.org/", licenseUrl = "https://slf4j.org/license.html").mit(), LibraryLicense(libraryName = "slf4j-jdk14", url = "https://slf4j.org/", licenseUrl = "https://slf4j.org/license.html").mit(), LibraryLicense(name = "SnakeYAML", libraryName = "snakeyaml", url = "https://bitbucket.org/asomov/snakeyaml").apache(), LibraryLicense(name = "snakeyaml-engine", libraryName = "snakeyaml-engine", url = "https://bitbucket.org/asomov/snakeyaml-engine/src").apache(), LibraryLicense(name = "Sonatype Nexus: Indexer", attachedTo = "intellij.maven.server.m3.common", version = "3.0.4", additionalLibraryNames = listOf("org.sonatype.nexus:nexus-indexer:3.0.4", "org.sonatype.nexus:nexus-indexer-artifact:1.0.1"), url = "https://nexus.sonatype.org/").eplV1(), LibraryLicense(name = "Sonatype Nexus: Indexer", libraryName = "nexus-indexer-1.2.3.jar", version = "1.2.3", url = "https://nexus.sonatype.org/").eplV1(), LibraryLicense(name = "SourceCodePro", attachedTo = "intellij.platform.resources", version = "2.010", license = "OFL", url = "https://github.com/adobe-fonts/source-code-pro", licenseUrl = "https://github.com/adobe-fonts/source-code-pro/blob/master/LICENSE.md"), LibraryLicense(name = "Spantable", libraryName = "spantable", version = "patched", license = "LGPL 2.1", licenseUrl = "https://www.gnu.org/licenses/lgpl.html", url = "https://android.googlesource.com/platform/prebuilts/tools/+/master/common/spantable/"), LibraryLicense(name = "sphinxcontrib-napoleon", attachedTo = "intellij.python", version = "0.7", url = "https://sphinxcontrib-napoleon.readthedocs.io/", licenseUrl = "https://github.com/sphinx-contrib/napoleon/blob/master/LICENSE").simplifiedBsd(), LibraryLicense(name = "SQLite Inspector Proto", libraryName = "sqlite-inspector-proto", url = "https://source.android.com").apache(), LibraryLicense(name = "ssh-nio-fs", libraryName = "ssh-nio-fs", url = "https://github.com/JetBrains/intellij-deps-ssh-nio-fs", licenseUrl = "https://github.com/JetBrains/intellij-deps-ssh-nio-fs/blob/master/LICENSE").mit(), LibraryLicense(name = "SSHJ", libraryName = "SSHJ", licenseUrl = "https://github.com/hierynomus/sshj/blob/master/LICENSE", url = "https://github.com/hierynomus/sshj").apache(), LibraryLicense(name = "StreamEx", libraryName = "StreamEx", url = "https://github.com/amaembo/streamex").apache(), LibraryLicense(name = "Studio Protobuf", libraryName = "studio-proto", license = "protobuf", url = "https://github.com/protocolbuffers/protobuf", licenseUrl = "https://github.com/protocolbuffers/protobuf/blob/master/LICENSE"), LibraryLicense(name = "swingx", libraryName = "swingx", license = "LGPL 2.1", url = "https://java.net/downloads/swingx/", licenseUrl = "https://www.opensource.org/licenses/lgpl-2.1.php"), // for tensorflow-lite-metadata module library in android.sdktools.mlkit-common LibraryLicense(name = "TensorFlow Lite Metadata Library", libraryName = "tensorflow-lite-metadata", url = "https://tensorflow.org/lite").apache(), LibraryLicense(libraryName = "TestNG", url = "https://testng.org/doc/", licenseUrl = "https://github.com/cbeust/testng/blob/master/LICENSE.txt").apache(), LibraryLicense(name = "Thrift", libraryName = "libthrift", url = "https://thrift.apache.org/").apache(), LibraryLicense(name = "thriftpy2", attachedTo = "intellij.python", version = "0.4.13", url = "https://github.com/Thriftpy/thriftpy2/", licenseUrl = "https://github.com/Thriftpy/thriftpy2/blob/master/LICENSE").mit(), // for traceprocessor-proto module library in intellij.android.profilersAndroid LibraryLicense(name = "TraceProcessor Daemon Protos", libraryName = "traceprocessor-proto", url = "https://source.android.com").apache(), LibraryLicense(name = "Transport Pipeline", libraryName = "transport-proto", url = "https://source.android.com").apache(), LibraryLicense(name = "Trove4j (JetBrains's fork)", libraryName = "Trove4j", license = "LGPL", url = "https://github.com/JetBrains/intellij-deps-trove4j", licenseUrl = "https://github.com/JetBrains/intellij-deps-trove4j/blob/master/LICENSE.txt"), LibraryLicense(name = "TwelveMonkeys ImageIO", libraryName = "imageio-tiff", url = "https://github.com/haraldk/TwelveMonkeys", licenseUrl = "https://github.com/haraldk/TwelveMonkeys#license").newBsd(), LibraryLicense(name = "Typeshed", attachedTo = "intellij.python", version = LibraryLicense.CUSTOM_REVISION, url = "https://github.com/python/typeshed", licenseUrl = "https://github.com/python/typeshed/blob/master/LICENSE").apache(), LibraryLicense(name = "unit-api", libraryName = "javax.measure:unit-api:1.0", url = "https://github.com/unitsofmeasurement/unit-api", licenseUrl = "https://github.com/unitsofmeasurement/unit-api/blob/master/LICENSE").newBsd(), LibraryLicense(name = "uom-lib-common", libraryName = "tech.uom.lib:uom-lib-common:1.1", url = "https://github.com/unitsofmeasurement/uom-lib", licenseUrl = "https://github.com/unitsofmeasurement/uom-lib/blob/master/LICENSE").newBsd(), LibraryLicense(libraryName = "Velocity", url = "https://velocity.apache.org/").apache(), LibraryLicense(name = "virtualenv", attachedTo = "intellij.python", version = "20.13.0", url = "https://virtualenv.pypa.io/", licenseUrl = "https://github.com/pypa/virtualenv/blob/main/LICENSE").mit(), LibraryLicense(name = "Visual Studio Code", attachedTo = "intellij.textmate", version = "1.33.1", url = "https://github.com/Microsoft/vscode/", licenseUrl = "https://github.com/Microsoft/vscode-react-native/blob/master/LICENSE.txt").mit(), LibraryLicense(name = "weberknecht", libraryName = "weberknecht-0.1.5.jar", version = "0.1.5", url = "https://github.com/pelotoncycle/weberknecht").apache(), LibraryLicense(libraryName = "winp", url = "https://github.com/kohsuke/winp").mit(), // for workmanager-inspector-proto module library in intellij.android.app-inspection.inspectors.workmanager.model LibraryLicense(name = "WorkManager Inspector Proto", libraryName = "workmanager-inspector-proto", url = "https://source.android.com").apache(), LibraryLicense(name = "Xalan", libraryName = "Xalan-2.7.2", url = "https://xalan.apache.org/xalan-j/", licenseUrl = "https://xalan.apache.org/xalan-j/#license").apache(), LibraryLicense(libraryName = "Xerces", url = "https://xerces.apache.org/xerces2-j/", licenseUrl = "https://xerces.apache.org/xerces2-j/").apache(), LibraryLicense(name = "Xerial SQLite JDBC", libraryName = "sqlite", url = "https://github.com/xerial/sqlite-jdbc").apache(), LibraryLicense(name = "xml-apis-ext", libraryName = "xml-apis-ext", url = "https://xerces.apache.org/xml-commons/components/external").apache(), LibraryLicense(name = "xml-resolver", libraryName = "xml-resolver", url = "https://xml.apache.org/commons/components/resolver/").apache(), LibraryLicense(name = "XMLBeans", libraryName = "XmlBeans", url = "https://xmlbeans.apache.org/", licenseUrl = "https://svn.jetbrains.org/idea/Trunk/bundled/WebServices/resources/lib/xmlbeans-2.3.0/xmlbeans.LICENSE").apache(), LibraryLicense(name = "XmlRPC", libraryName = "XmlRPC", url = "https://ws.apache.org/xmlrpc/xmlrpc2/", licenseUrl = "https://ws.apache.org/xmlrpc/xmlrpc2/license.html").apache(), LibraryLicense(name = "XSLT Debugger RMI Stubs", libraryName = "RMI Stubs", url = "https://confluence.jetbrains.com/display/CONTEST/XSLT-Debugger", version = LibraryLicense.CUSTOM_REVISION).apache(), LibraryLicense(name = "XStream", libraryName = "XStream", url = "https://x-stream.github.io/", licenseUrl = "https://x-stream.github.io/license.html").newBsd(), LibraryLicense(name = "XZ for Java", libraryName = "xz", license = "Public Domain", url = "https://tukaani.org/xz/java.html", licenseUrl = "https://git.tukaani.org/?p=xz-java.git;a=blob;f=COPYING;h=8dd17645c4610c3d5eed9bcdd2699ecfac00406b;hb=refs/heads/master"), LibraryLicense(name = "zip-signer", libraryName = "zip-signer", url = "https://github.com/JetBrains/marketplace-zip-signer").apache(), LibraryLicense(name = "zstd-jni", libraryName = "zstd-jni", url = "https://github.com/luben/zstd-jni", license = "BSD", licenseUrl = "https://github.com/luben/zstd-jni/blob/master/LICENSE"), jetbrainsLibrary("change-reminder-prediction-model"), jetbrainsLibrary("cloud-config-client"), jetbrainsLibrary("completion-log-events"), jetbrainsLibrary("completion-ranking-cpp-exp"), jetbrainsLibrary("completion-ranking-dart-exp"), jetbrainsLibrary("completion-ranking-go-exp"), jetbrainsLibrary("completion-ranking-java"), jetbrainsLibrary("completion-ranking-java-exp"), jetbrainsLibrary("completion-ranking-java-exp2"), jetbrainsLibrary("completion-ranking-js-exp"), jetbrainsLibrary("completion-ranking-kotlin"), jetbrainsLibrary("completion-ranking-kotlin-exp"), jetbrainsLibrary("completion-ranking-php-exp"), jetbrainsLibrary("completion-ranking-python"), jetbrainsLibrary("completion-ranking-python-exp"), jetbrainsLibrary("completion-ranking-ruby-exp"), jetbrainsLibrary("completion-ranking-rust-exp"), jetbrainsLibrary("completion-ranking-scala-exp"), jetbrainsLibrary("completion-ranking-swift-exp"), jetbrainsLibrary("completion-ranking-typescript-exp"), jetbrainsLibrary("debugger-memory-agent"), jetbrainsLibrary("file-prediction-model"), jetbrainsLibrary("find-action-model"), jetbrainsLibrary("find-action-model-experimental"), jetbrainsLibrary("find-file-model"), jetbrainsLibrary("fixed.kotlin-jps-plugin-classpath"), jetbrainsLibrary("git-learning-project"), jetbrainsLibrary("intellij-coverage"), jetbrainsLibrary("intellij-test-discovery"), jetbrainsLibrary("io.ktor.network.jvm"), jetbrainsLibrary("jetbrains.markdown.jvm"), jetbrainsLibrary("jetbrains.research.refactorinsight.kotlin.impl"), jetbrainsLibrary("jshell-frontend"), jetbrainsLibrary("jvm-native-trusted-roots"), jetbrainsLibrary("kotlin-gradle-plugin-idea"), jetbrainsLibrary("kotlin-gradle-plugin-idea-proto"), jetbrainsLibrary("kotlin-script-runtime"), jetbrainsLibrary("kotlin-test"), jetbrainsLibrary("kotlin-tooling-core"), jetbrainsLibrary("kotlinc.allopen-compiler-plugin"), jetbrainsLibrary("kotlinc.analysis-api-providers"), jetbrainsLibrary("kotlinc.analysis-project-structure"), jetbrainsLibrary("kotlinc.android-extensions-compiler-plugin"), jetbrainsLibrary("kotlinc.high-level-api"), jetbrainsLibrary("kotlinc.high-level-api-fe10"), jetbrainsLibrary("kotlinc.high-level-api-fir"), jetbrainsLibrary("kotlinc.high-level-api-fir-tests"), jetbrainsLibrary("kotlinc.high-level-api-impl-base"), jetbrainsLibrary("kotlinc.high-level-api-impl-base-tests"), jetbrainsLibrary("kotlinc.incremental-compilation-impl-tests"), jetbrainsLibrary("kotlinc.kotlin-backend-native"), jetbrainsLibrary("kotlinc.kotlin-build-common-tests"), jetbrainsLibrary("kotlinc.kotlin-compiler-cli"), jetbrainsLibrary("kotlinc.kotlin-compiler-common"), jetbrainsLibrary("kotlinc.kotlin-compiler-fe10"), jetbrainsLibrary("kotlinc.kotlin-compiler-fir"), jetbrainsLibrary("kotlinc.kotlin-compiler-ir"), jetbrainsLibrary("kotlinc.kotlin-compiler-tests"), jetbrainsLibrary("kotlinc.kotlin-dist"), jetbrainsLibrary("kotlinc.kotlin-gradle-statistics"), jetbrainsLibrary("kotlinc.kotlin-jps-common"), jetbrainsLibrary("kotlinc.kotlin-jps-plugin-classpath"), jetbrainsLibrary("kotlinc.kotlin-reflect"), jetbrainsLibrary("kotlinc.kotlin-script-runtime"), jetbrainsLibrary("kotlinc.kotlin-scripting-common"), jetbrainsLibrary("kotlinc.kotlin-scripting-compiler-impl"), jetbrainsLibrary("kotlinc.kotlin-scripting-jvm"), jetbrainsLibrary("kotlinc.kotlin-stdlib"), jetbrainsLibrary("kotlinc.kotlin-stdlib-minimal-for-test"), jetbrainsLibrary("kotlinc.kotlinx-serialization-compiler-plugin"), jetbrainsLibrary("kotlinc.lombok-compiler-plugin"), jetbrainsLibrary("kotlinc.low-level-api-fir"), jetbrainsLibrary("kotlinc.noarg-compiler-plugin"), jetbrainsLibrary("kotlinc.parcelize-compiler-plugin"), jetbrainsLibrary("kotlinc.sam-with-receiver-compiler-plugin"), jetbrainsLibrary("kotlinc.symbol-light-classes"), jetbrainsLibrary("kotlinx-collections-immutable-jvm"), jetbrainsLibrary("kotlinx.kotlinx-serialization-compiler-plugin-for-compilation"), jetbrainsLibrary("ml-completion-prev-exprs-models"), jetbrainsLibrary("rd-core"), jetbrainsLibrary("rd-framework"), jetbrainsLibrary("rd-swing"), jetbrainsLibrary("rd-text"), jetbrainsLibrary("tcServiceMessages"), jetbrainsLibrary("tips-idea-ce"), jetbrainsLibrary("tips-pycharm-community"), ) }
apache-2.0
aa96474286fd273852c95525d890bf72
83.987472
162
0.638068
4.101748
false
false
false
false
onoderis/failchat
src/main/kotlin/failchat/github/Version.kt
2
962
package failchat.github import java.util.regex.Pattern class Version(val major: Int, val minor: Int, val micro: Int) : Comparable<Version> { companion object { val versionPattern: Pattern = Pattern.compile("""v(\d+)\.(\d+)\.(\d+)""") fun parse(stringVersion: String): Version { val matcher = versionPattern.matcher(stringVersion) if (!matcher.matches()) throw IllegalArgumentException("Invalid version format: '$stringVersion'") return Version(matcher.group(1).toInt(), matcher.group(2).toInt(), matcher.group(3).toInt()) } } override fun compareTo(other: Version): Int { var comparison: Int = major.compareTo(other.major) if (comparison != 0) return comparison comparison = minor.compareTo(other.minor) if (comparison != 0) return comparison return micro.compareTo(other.micro) } override fun toString() = "v$major.$minor.$micro" }
gpl-3.0
7e485832bf1ebce8d7591a4f2156d191
32.172414
110
0.64553
4.294643
false
false
false
false
k9mail/k-9
backend/imap/src/main/java/com/fsck/k9/backend/imap/ImapSync.kt
1
27726
package com.fsck.k9.backend.imap import com.fsck.k9.backend.api.BackendFolder import com.fsck.k9.backend.api.BackendFolder.MoreMessages import com.fsck.k9.backend.api.BackendStorage import com.fsck.k9.backend.api.SyncConfig import com.fsck.k9.backend.api.SyncConfig.ExpungePolicy import com.fsck.k9.backend.api.SyncListener import com.fsck.k9.helper.ExceptionHelper import com.fsck.k9.mail.AuthenticationFailedException import com.fsck.k9.mail.BodyFactory import com.fsck.k9.mail.DefaultBodyFactory import com.fsck.k9.mail.FetchProfile import com.fsck.k9.mail.Flag import com.fsck.k9.mail.MessageDownloadState import com.fsck.k9.mail.internet.MessageExtractor import com.fsck.k9.mail.store.imap.FetchListener import com.fsck.k9.mail.store.imap.ImapFolder import com.fsck.k9.mail.store.imap.ImapMessage import com.fsck.k9.mail.store.imap.ImapStore import com.fsck.k9.mail.store.imap.OpenMode import java.util.Collections import java.util.Date import java.util.concurrent.atomic.AtomicInteger import kotlin.math.max import timber.log.Timber internal class ImapSync( private val accountName: String, private val backendStorage: BackendStorage, private val imapStore: ImapStore ) { fun sync(folder: String, syncConfig: SyncConfig, listener: SyncListener) { synchronizeMailboxSynchronous(folder, syncConfig, listener) } private fun synchronizeMailboxSynchronous(folder: String, syncConfig: SyncConfig, listener: SyncListener) { Timber.i("Synchronizing folder %s:%s", accountName, folder) var remoteFolder: ImapFolder? = null var backendFolder: BackendFolder? = null var newHighestKnownUid: Long = 0 try { Timber.v("SYNC: About to get local folder %s", folder) backendFolder = backendStorage.getFolder(folder) listener.syncStarted(folder) Timber.v("SYNC: About to get remote folder %s", folder) remoteFolder = imapStore.getFolder(folder) /* * Synchronization process: * Open the folder Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash) Get the message count Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount) See if we have each message locally, if not fetch it's flags and envelope Get and update the unread count for the folder Update the remote flags of any messages we have locally with an internal date newer than the remote message. Get the current flags for any messages we have locally but did not just download Update local flags For any message we have locally but not remotely, delete the local message to keep cache clean. Download larger parts of any new messages. (Optional) Download small attachments in the background. */ /* * Open the remote folder. This pre-loads certain metadata like message count. */ Timber.v("SYNC: About to open remote folder %s", folder) if (syncConfig.expungePolicy === ExpungePolicy.ON_POLL) { Timber.d("SYNC: Expunging folder %s:%s", accountName, folder) remoteFolder.expunge() } remoteFolder.open(OpenMode.READ_ONLY) listener.syncAuthenticationSuccess() val uidValidity = remoteFolder.getUidValidity() val oldUidValidity = backendFolder.getFolderExtraNumber(EXTRA_UID_VALIDITY) if (oldUidValidity == null && uidValidity != null) { Timber.d("SYNC: Saving UIDVALIDITY for %s", folder) backendFolder.setFolderExtraNumber(EXTRA_UID_VALIDITY, uidValidity) } else if (oldUidValidity != null && oldUidValidity != uidValidity) { Timber.d("SYNC: UIDVALIDITY for %s changed; clearing local message cache", folder) backendFolder.clearAllMessages() backendFolder.setFolderExtraNumber(EXTRA_UID_VALIDITY, uidValidity!!) backendFolder.setFolderExtraNumber(EXTRA_HIGHEST_KNOWN_UID, 0) } /* * Get the message list from the local store and create an index of * the uids within the list. */ val highestKnownUid = backendFolder.getFolderExtraNumber(EXTRA_HIGHEST_KNOWN_UID) ?: 0 var localUidMap: Map<String, Long?>? = backendFolder.getAllMessagesAndEffectiveDates() /* * Get the remote message count. */ val remoteMessageCount = remoteFolder.messageCount var visibleLimit = backendFolder.visibleLimit if (visibleLimit < 0) { visibleLimit = syncConfig.defaultVisibleLimit } val remoteMessages = mutableListOf<ImapMessage>() val remoteUidMap = mutableMapOf<String, ImapMessage>() Timber.v("SYNC: Remote message count for folder %s is %d", folder, remoteMessageCount) val earliestDate = syncConfig.earliestPollDate val earliestTimestamp = earliestDate?.time ?: 0L var remoteStart = 1 if (remoteMessageCount > 0) { /* Message numbers start at 1. */ remoteStart = if (visibleLimit > 0) { max(0, remoteMessageCount - visibleLimit) + 1 } else { 1 } Timber.v( "SYNC: About to get messages %d through %d for folder %s", remoteStart, remoteMessageCount, folder ) val headerProgress = AtomicInteger(0) listener.syncHeadersStarted(folder) val remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteMessageCount, earliestDate, null) val messageCount = remoteMessageArray.size for (thisMess in remoteMessageArray) { headerProgress.incrementAndGet() listener.syncHeadersProgress(folder, headerProgress.get(), messageCount) val uid = thisMess.uid.toLong() if (uid > highestKnownUid && uid > newHighestKnownUid) { newHighestKnownUid = uid } val localMessageTimestamp = localUidMap!![thisMess.uid] if (localMessageTimestamp == null || localMessageTimestamp >= earliestTimestamp) { remoteMessages.add(thisMess) remoteUidMap[thisMess.uid] = thisMess } } Timber.v("SYNC: Got %d messages for folder %s", remoteUidMap.size, folder) listener.syncHeadersFinished(folder, headerProgress.get(), remoteUidMap.size) } else if (remoteMessageCount < 0) { throw Exception("Message count $remoteMessageCount for folder $folder") } /* * Remove any messages that are in the local store but no longer on the remote store or are too old */ var moreMessages = backendFolder.getMoreMessages() if (syncConfig.syncRemoteDeletions) { val destroyMessageUids = mutableListOf<String>() for (localMessageUid in localUidMap!!.keys) { if (remoteUidMap[localMessageUid] == null) { destroyMessageUids.add(localMessageUid) } } if (destroyMessageUids.isNotEmpty()) { moreMessages = MoreMessages.UNKNOWN backendFolder.destroyMessages(destroyMessageUids) for (uid in destroyMessageUids) { listener.syncRemovedMessage(folder, uid) } } } @Suppress("UNUSED_VALUE") // free memory early? (better break up the method!) localUidMap = null if (moreMessages === MoreMessages.UNKNOWN) { updateMoreMessages(remoteFolder, backendFolder, earliestDate, remoteStart) } /* * Now we download the actual content of messages. */ downloadMessages( syncConfig, remoteFolder, backendFolder, remoteMessages, highestKnownUid, listener ) listener.folderStatusChanged(folder) /* Notify listeners that we're finally done. */ backendFolder.setLastChecked(System.currentTimeMillis()) backendFolder.setStatus(null) Timber.d("Done synchronizing folder %s:%s @ %tc", accountName, folder, System.currentTimeMillis()) listener.syncFinished(folder) Timber.i("Done synchronizing folder %s:%s", accountName, folder) } catch (e: AuthenticationFailedException) { listener.syncFailed(folder, "Authentication failure", e) } catch (e: Exception) { Timber.e(e, "synchronizeMailbox") // If we don't set the last checked, it can try too often during // failure conditions val rootMessage = ExceptionHelper.getRootCauseMessage(e) if (backendFolder != null) { try { backendFolder.setStatus(rootMessage) backendFolder.setLastChecked(System.currentTimeMillis()) } catch (e: Exception) { Timber.e(e, "Could not set last checked on folder %s:%s", accountName, folder) } } listener.syncFailed(folder, rootMessage, e) Timber.e( "Failed synchronizing folder %s:%s @ %tc", accountName, folder, System.currentTimeMillis() ) } finally { if (newHighestKnownUid > 0 && backendFolder != null) { Timber.v("Saving new highest known UID: %d", newHighestKnownUid) backendFolder.setFolderExtraNumber(EXTRA_HIGHEST_KNOWN_UID, newHighestKnownUid) } remoteFolder?.close() } } fun downloadMessage(syncConfig: SyncConfig, folderServerId: String, messageServerId: String) { val backendFolder = backendStorage.getFolder(folderServerId) val remoteFolder = imapStore.getFolder(folderServerId) try { remoteFolder.open(OpenMode.READ_ONLY) val remoteMessage = remoteFolder.getMessage(messageServerId) downloadMessages( syncConfig, remoteFolder, backendFolder, listOf(remoteMessage), null, SimpleSyncListener() ) } finally { remoteFolder.close() } } /** * Fetches the messages described by inputMessages from the remote store and writes them to local storage. * * @param remoteFolder * The remote folder to download messages from. * @param backendFolder * The [BackendFolder] instance corresponding to the remote folder. * @param inputMessages * A list of messages objects that store the UIDs of which messages to download. */ private fun downloadMessages( syncConfig: SyncConfig, remoteFolder: ImapFolder, backendFolder: BackendFolder, inputMessages: List<ImapMessage>, highestKnownUid: Long?, listener: SyncListener ) { val folder = remoteFolder.serverId val syncFlagMessages = mutableListOf<ImapMessage>() var unsyncedMessages = mutableListOf<ImapMessage>() val downloadedMessageCount = AtomicInteger(0) val messages = inputMessages.toMutableList() for (message in messages) { evaluateMessageForDownload( message, backendFolder, unsyncedMessages, syncFlagMessages ) } val progress = AtomicInteger(0) val todo = unsyncedMessages.size + syncFlagMessages.size listener.syncProgress(folder, progress.get(), todo) Timber.d("SYNC: Have %d unsynced messages", unsyncedMessages.size) messages.clear() val largeMessages = mutableListOf<ImapMessage>() val smallMessages = mutableListOf<ImapMessage>() if (unsyncedMessages.isNotEmpty()) { Collections.sort(unsyncedMessages, UidReverseComparator()) val visibleLimit = backendFolder.visibleLimit val listSize = unsyncedMessages.size if (visibleLimit in 1 until listSize) { unsyncedMessages = unsyncedMessages.subList(0, visibleLimit) } Timber.d("SYNC: About to fetch %d unsynced messages for folder %s", unsyncedMessages.size, folder) fetchUnsyncedMessages( syncConfig, remoteFolder, unsyncedMessages, smallMessages, largeMessages, progress, todo, listener ) Timber.d("SYNC: Synced unsynced messages for folder %s", folder) } Timber.d( "SYNC: Have %d large messages and %d small messages out of %d unsynced messages", largeMessages.size, smallMessages.size, unsyncedMessages.size ) unsyncedMessages.clear() /* * Grab the content of the small messages first. This is going to * be very fast and at very worst will be a single up of a few bytes and a single * download of 625k. */ val maxDownloadSize = syncConfig.maximumAutoDownloadMessageSize // TODO: Only fetch small and large messages if we have some downloadSmallMessages( remoteFolder, backendFolder, smallMessages, progress, downloadedMessageCount, todo, highestKnownUid, listener ) smallMessages.clear() /* * Now do the large messages that require more round trips. */ downloadLargeMessages( remoteFolder, backendFolder, largeMessages, progress, downloadedMessageCount, todo, highestKnownUid, listener, maxDownloadSize ) largeMessages.clear() /* * Refresh the flags for any messages in the local store that we didn't just * download. */ refreshLocalMessageFlags(syncConfig, remoteFolder, backendFolder, syncFlagMessages, progress, todo, listener) Timber.d("SYNC: Synced remote messages for folder %s, %d new messages", folder, downloadedMessageCount.get()) } private fun evaluateMessageForDownload( message: ImapMessage, backendFolder: BackendFolder, unsyncedMessages: MutableList<ImapMessage>, syncFlagMessages: MutableList<ImapMessage> ) { val messageServerId = message.uid if (message.isSet(Flag.DELETED)) { Timber.v("Message with uid %s is marked as deleted", messageServerId) syncFlagMessages.add(message) return } val messagePresentLocally = backendFolder.isMessagePresent(messageServerId) if (!messagePresentLocally) { Timber.v("Message with uid %s has not yet been downloaded", messageServerId) unsyncedMessages.add(message) return } val messageFlags = backendFolder.getMessageFlags(messageServerId) if (!messageFlags.contains(Flag.DELETED)) { Timber.v("Message with uid %s is present in the local store", messageServerId) if (!messageFlags.contains(Flag.X_DOWNLOADED_FULL) && !messageFlags.contains(Flag.X_DOWNLOADED_PARTIAL)) { Timber.v("Message with uid %s is not downloaded, even partially; trying again", messageServerId) unsyncedMessages.add(message) } else { syncFlagMessages.add(message) } } else { Timber.v("Local copy of message with uid %s is marked as deleted", messageServerId) } } private fun isOldMessage(messageServerId: String, highestKnownUid: Long?): Boolean { if (highestKnownUid == null) return false try { val messageUid = messageServerId.toLong() return messageUid <= highestKnownUid } catch (e: NumberFormatException) { Timber.w(e, "Couldn't parse UID: %s", messageServerId) } return false } private fun fetchUnsyncedMessages( syncConfig: SyncConfig, remoteFolder: ImapFolder, unsyncedMessages: List<ImapMessage>, smallMessages: MutableList<ImapMessage>, largeMessages: MutableList<ImapMessage>, progress: AtomicInteger, todo: Int, listener: SyncListener ) { val folder = remoteFolder.serverId val fetchProfile = FetchProfile().apply { add(FetchProfile.Item.FLAGS) add(FetchProfile.Item.ENVELOPE) } remoteFolder.fetch( unsyncedMessages, fetchProfile, object : FetchListener { override fun onFetchResponse(message: ImapMessage, isFirstResponse: Boolean) { try { if (message.isSet(Flag.DELETED)) { Timber.v( "Newly downloaded message %s:%s:%s was marked deleted on server, skipping", accountName, folder, message.uid ) if (isFirstResponse) { progress.incrementAndGet() } // TODO: This might be the source of poll count errors in the UI. Is todo always the same as ofTotal listener.syncProgress(folder, progress.get(), todo) return } if (syncConfig.maximumAutoDownloadMessageSize > 0 && message.size > syncConfig.maximumAutoDownloadMessageSize ) { largeMessages.add(message) } else { smallMessages.add(message) } } catch (e: Exception) { Timber.e(e, "Error while storing downloaded message.") } } }, syncConfig.maximumAutoDownloadMessageSize ) } private fun downloadSmallMessages( remoteFolder: ImapFolder, backendFolder: BackendFolder, smallMessages: List<ImapMessage>, progress: AtomicInteger, downloadedMessageCount: AtomicInteger, todo: Int, highestKnownUid: Long?, listener: SyncListener ) { val folder = remoteFolder.serverId val fetchProfile = FetchProfile().apply { add(FetchProfile.Item.BODY) } Timber.d("SYNC: Fetching %d small messages for folder %s", smallMessages.size, folder) remoteFolder.fetch( smallMessages, fetchProfile, object : FetchListener { override fun onFetchResponse(message: ImapMessage, isFirstResponse: Boolean) { try { // Store the updated message locally backendFolder.saveMessage(message, MessageDownloadState.FULL) if (isFirstResponse) { progress.incrementAndGet() downloadedMessageCount.incrementAndGet() } val messageServerId = message.uid Timber.v( "About to notify listeners that we got a new small message %s:%s:%s", accountName, folder, messageServerId ) // Update the listener with what we've found listener.syncProgress(folder, progress.get(), todo) val isOldMessage = isOldMessage(messageServerId, highestKnownUid) listener.syncNewMessage(folder, messageServerId, isOldMessage) } catch (e: Exception) { Timber.e(e, "SYNC: fetch small messages") } } }, -1 ) Timber.d("SYNC: Done fetching small messages for folder %s", folder) } private fun downloadLargeMessages( remoteFolder: ImapFolder, backendFolder: BackendFolder, largeMessages: List<ImapMessage>, progress: AtomicInteger, downloadedMessageCount: AtomicInteger, todo: Int, highestKnownUid: Long?, listener: SyncListener, maxDownloadSize: Int ) { val folder = remoteFolder.serverId val fetchProfile = FetchProfile().apply { add(FetchProfile.Item.STRUCTURE) } Timber.d("SYNC: Fetching large messages for folder %s", folder) remoteFolder.fetch(largeMessages, fetchProfile, null, maxDownloadSize) for (message in largeMessages) { if (message.body == null) { downloadSaneBody(remoteFolder, backendFolder, message, maxDownloadSize) } else { downloadPartial(remoteFolder, backendFolder, message, maxDownloadSize) } val messageServerId = message.uid Timber.v( "About to notify listeners that we got a new large message %s:%s:%s", accountName, folder, messageServerId ) // Update the listener with what we've found progress.incrementAndGet() downloadedMessageCount.incrementAndGet() listener.syncProgress(folder, progress.get(), todo) val isOldMessage = isOldMessage(messageServerId, highestKnownUid) listener.syncNewMessage(folder, messageServerId, isOldMessage) } Timber.d("SYNC: Done fetching large messages for folder %s", folder) } private fun refreshLocalMessageFlags( syncConfig: SyncConfig, remoteFolder: ImapFolder, backendFolder: BackendFolder, syncFlagMessages: List<ImapMessage>, progress: AtomicInteger, todo: Int, listener: SyncListener ) { val folder = remoteFolder.serverId Timber.d("SYNC: About to sync flags for %d remote messages for folder %s", syncFlagMessages.size, folder) val fetchProfile = FetchProfile() fetchProfile.add(FetchProfile.Item.FLAGS) val undeletedMessages = mutableListOf<ImapMessage>() for (message in syncFlagMessages) { if (!message.isSet(Flag.DELETED)) { undeletedMessages.add(message) } } val maxDownloadSize = syncConfig.maximumAutoDownloadMessageSize remoteFolder.fetch(undeletedMessages, fetchProfile, null, maxDownloadSize) for (remoteMessage in syncFlagMessages) { val messageChanged = syncFlags(syncConfig, backendFolder, remoteMessage) if (messageChanged) { listener.syncFlagChanged(folder, remoteMessage.uid) } progress.incrementAndGet() listener.syncProgress(folder, progress.get(), todo) } } private fun downloadSaneBody( remoteFolder: ImapFolder, backendFolder: BackendFolder, message: ImapMessage, maxDownloadSize: Int ) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ val fetchProfile = FetchProfile() fetchProfile.add(FetchProfile.Item.BODY_SANE) /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(listOf(message), fetchProfile, null, maxDownloadSize) // Store the updated message locally backendFolder.saveMessage(message, MessageDownloadState.PARTIAL) } private fun downloadPartial( remoteFolder: ImapFolder, backendFolder: BackendFolder, message: ImapMessage, maxDownloadSize: Int ) { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ val viewables = MessageExtractor.collectTextParts(message) /* * Now download the parts we're interested in storing. */ val bodyFactory: BodyFactory = DefaultBodyFactory() for (part in viewables) { remoteFolder.fetchPart(message, part, bodyFactory, maxDownloadSize) } // Store the updated message locally backendFolder.saveMessage(message, MessageDownloadState.PARTIAL) } private fun syncFlags(syncConfig: SyncConfig, backendFolder: BackendFolder, remoteMessage: ImapMessage): Boolean { val messageServerId = remoteMessage.uid if (!backendFolder.isMessagePresent(messageServerId)) return false val localMessageFlags = backendFolder.getMessageFlags(messageServerId) if (localMessageFlags.contains(Flag.DELETED)) return false var messageChanged = false if (remoteMessage.isSet(Flag.DELETED)) { if (syncConfig.syncRemoteDeletions) { backendFolder.setMessageFlag(messageServerId, Flag.DELETED, true) messageChanged = true } } else { for (flag in syncConfig.syncFlags) { if (remoteMessage.isSet(flag) != localMessageFlags.contains(flag)) { backendFolder.setMessageFlag(messageServerId, flag, remoteMessage.isSet(flag)) messageChanged = true } } } return messageChanged } private fun updateMoreMessages( remoteFolder: ImapFolder, backendFolder: BackendFolder, earliestDate: Date?, remoteStart: Int ) { if (remoteStart == 1) { backendFolder.setMoreMessages(MoreMessages.FALSE) } else { val moreMessagesAvailable = remoteFolder.areMoreMessagesAvailable(remoteStart, earliestDate) val newMoreMessages = if (moreMessagesAvailable) MoreMessages.TRUE else MoreMessages.FALSE backendFolder.setMoreMessages(newMoreMessages) } } companion object { private const val EXTRA_UID_VALIDITY = "imapUidValidity" private const val EXTRA_HIGHEST_KNOWN_UID = "imapHighestKnownUid" } }
apache-2.0
30cac8495fb7a20acb03a31956176836
37.669456
128
0.595254
5.105137
false
false
false
false
ligi/PassAndroid
android/src/main/java/org/ligi/passandroid/model/pass/PassLocation.kt
1
491
package org.ligi.passandroid.model.pass import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class PassLocation { var name: String? = null var lat: Double = 0.toDouble() var lon: Double = 0.toDouble() fun getNameWithFallback(pass: Pass) = if (name.isNullOrBlank()) { // fallback for passes with locations without description - e.g. AirBerlin pass.description } else { name } fun getCommaSeparated() = "$lat,$lon" }
gpl-3.0
532bcecee9efb49ad684dd7478ffafd8
22.380952
82
0.663951
4.057851
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/BaseSlider.kt
1
6752
package org.hexworks.zircon.internal.component.impl import org.hexworks.cobalt.databinding.api.event.ObservableValueChanged import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.cobalt.events.api.Subscription import org.hexworks.cobalt.logging.api.LoggerFactory import org.hexworks.zircon.api.builder.component.ComponentStyleSetBuilder import org.hexworks.zircon.api.builder.graphics.StyleSetBuilder import org.hexworks.zircon.api.color.TileColor import org.hexworks.zircon.api.component.ColorTheme import org.hexworks.zircon.api.component.Slider import org.hexworks.zircon.api.component.data.ComponentMetadata import org.hexworks.zircon.api.component.data.ComponentState import org.hexworks.zircon.api.component.renderer.ComponentRenderingStrategy import org.hexworks.zircon.api.extensions.abbreviate import org.hexworks.zircon.api.extensions.whenEnabledRespondWith import org.hexworks.zircon.api.uievent.* import kotlin.math.roundToInt import kotlin.math.truncate abstract class BaseSlider( final override val minValue: Int, final override val maxValue: Int, final override val numberOfSteps: Int, componentMetadata: ComponentMetadata, renderer: ComponentRenderingStrategy<Slider> ) : Slider, DefaultComponent( metadata = componentMetadata, renderer = renderer ) { private val range: Int = maxValue - minValue protected val valuePerStep: Double = range.toDouble() / numberOfSteps.toDouble() final override val currentValueProperty = minValue.toProperty() override var currentValue: Int by currentValueProperty.asDelegate() final override val currentStepProperty = 0.toProperty() override var currentStep: Int by currentStepProperty.asDelegate() init { currentValueProperty.onChange { computeCurrentStep(it.newValue) } disabledProperty.onChange { componentState = if (it.newValue) { LOGGER.debug("Disabling Slider (id=${id.abbreviate()}, disabled=$isDisabled).") ComponentState.DISABLED } else { LOGGER.debug("Enabling Slider (id=${id.abbreviate()}, disabled=$isDisabled).") ComponentState.DEFAULT } } } private fun computeCurrentStep(newValue: Int) { val actualValue = when { newValue > maxValue -> maxValue newValue < minValue -> minValue else -> newValue } val actualStep = actualValue.toDouble() / valuePerStep val roundedStep = truncate(actualStep) currentStep = roundedStep.toInt() } override fun incrementCurrentValue() { if (currentValue < maxValue) { currentValue++ } } override fun decrementCurrentValue() { if (currentValue > minValue) { currentValue-- } } override fun incrementCurrentStep() { if (currentStep + 1 < numberOfSteps) { setValueToClosestOfStep(currentStep + 1) } } override fun decrementCurrentStep() { if (currentStep - 1 > 0) { setValueToClosestOfStep(currentStep - 1) } } protected fun addToCurrentValue(value: Int) { if (currentValue + value <= maxValue) { currentValue += value } else { currentValue = maxValue } } protected fun subtractToCurrentValue(value: Int) { if (currentValue - value > minValue) { currentValue -= value } else { currentValue = minValue } } private fun setValueToClosestOfStep(step: Int) { val actualStep = when { step < 0 -> 0 step > numberOfSteps -> numberOfSteps else -> step } val calculatedValue = (actualStep * valuePerStep) + minValue currentValue = calculatedValue.roundToInt() } abstract fun getMousePosition(event: MouseEvent): Int override fun mousePressed(event: MouseEvent, phase: UIEventPhase) = whenEnabledRespondWith { if (phase == UIEventPhase.TARGET) { LOGGER.debug("Gutter (id=${id.abbreviate()}, disabled=$isDisabled) was mouse pressed.") componentState = ComponentState.ACTIVE setValueToClosestOfStep(getMousePosition(event)) Processed } else Pass } override fun mouseDragged(event: MouseEvent, phase: UIEventPhase) = whenEnabledRespondWith { if (phase == UIEventPhase.TARGET) { LOGGER.debug("Gutter (id=${id.abbreviate()}, disabled=$isDisabled) was mouse pressed.") componentState = ComponentState.ACTIVE setValueToClosestOfStep(getMousePosition(event)) Processed } else Pass } abstract override fun keyPressed(event: KeyboardEvent, phase: UIEventPhase): UIEventResponse override fun activated() = whenEnabledRespondWith { if (isDisabled) { LOGGER.warn("Trying to activate disabled Gutter (id=${id.abbreviate()}. Request dropped.") Pass } else { LOGGER.debug("Gutter (id=${id.abbreviate()}, disabled=$isDisabled) was activated.") componentState = ComponentState.HIGHLIGHTED Processed } } override fun convertColorTheme(colorTheme: ColorTheme) = ComponentStyleSetBuilder.newBuilder() .withDefaultStyle( StyleSetBuilder.newBuilder() .withForegroundColor(colorTheme.primaryForegroundColor) .withBackgroundColor(TileColor.transparent()) .build() ) .withHighlightedStyle( StyleSetBuilder.newBuilder() .withForegroundColor(colorTheme.primaryBackgroundColor) .withBackgroundColor(colorTheme.accentColor) .build() ) .withDisabledStyle( StyleSetBuilder.newBuilder() .withForegroundColor(colorTheme.secondaryForegroundColor) .withBackgroundColor(colorTheme.secondaryBackgroundColor) .build() ) .withFocusedStyle( StyleSetBuilder.newBuilder() .withForegroundColor(colorTheme.primaryBackgroundColor) .withBackgroundColor(colorTheme.primaryForegroundColor) .build() ) .build() override fun onValueChange(fn: (ObservableValueChanged<Int>) -> Unit): Subscription { return currentValueProperty.onChange(fn) } override fun onStepChange(fn: (ObservableValueChanged<Int>) -> Unit): Subscription { return currentStepProperty.onChange(fn) } companion object { val LOGGER = LoggerFactory.getLogger(Slider::class) } }
apache-2.0
ba6283b44ff8bc896470957292a1ee25
34.914894
102
0.656991
5.181888
false
false
false
false
hpost/kommon
app/src/main/java/cc/femto/kommon/ui/widget/WrapContentViewPager.kt
1
1011
package cc.femto.kommon.ui.widget import android.content.Context import android.support.v4.view.ViewPager import android.util.AttributeSet /** * ViewPager that wraps it's height around the tallest child view */ class WrapContentViewPager : ViewPager { constructor(context: Context) : super(context) { } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var heightMeasureSpec = heightMeasureSpec var height = 0 for (i in 0 until childCount) { val child = getChildAt(i) child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) val h = child.measuredHeight if (h > height) { height = h } } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) super.onMeasure(widthMeasureSpec, heightMeasureSpec) } }
apache-2.0
8e03855c98edb719c13f65334f30e933
28.735294
100
0.670623
4.791469
false
false
false
false
JoeSteven/HuaBan
app/src/main/java/com/joe/zatuji/module/detail/PicDetailAdapter.kt
1
2410
package com.joe.zatuji.module.detail import android.content.Context import android.support.v4.view.PagerAdapter import android.view.View import android.view.ViewGroup import com.github.chrisbanes.photoview.PhotoView import com.joe.zatuji.R import com.joe.zatuji.extension.loadDetail import com.joe.zatuji.repo.bean.IDetailPicture import com.joey.cheetah.core.ktextension.gone import com.joey.cheetah.core.ktextension.visible import kotlinx.android.synthetic.main.item_pic_detail_viewpager.view.* /** * Created by joe on 16/7/2. */ class PicDetailAdapter(private val context: Context) : PagerAdapter() { private var mListener: OnItemClickListener? = null var items:List<IDetailPicture>?= null set(value) { field = value notifyDataSetChanged() } override fun getCount(): Int { return items?.size ?: 0 } override fun isViewFromObject(view: View, obj: Any): Boolean { return view == obj } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as View) } override fun instantiateItem(container: ViewGroup, position: Int): Any { val view = View.inflate(context, R.layout.item_pic_detail_viewpager, null) container.addView(view) val ivDetail = view.findViewById<View>(R.id.iv_pic_gif) as PhotoView ivDetail.minimumScale = 1f val item = items!![position] view.pbLoading.visible() ivDetail.loadDetail(item, { view.pbLoading.gone() }, { view.pbLoading.gone() }) ivDetail.setOnPhotoTapListener { _, _, _ -> mListener?.onItemClicked(position, item) } ivDetail.setOnOutsidePhotoTapListener { mListener?.onItemClicked(position, item) } if (item.isRecommend()) { view.tvDesc.text = item.getPicDesc() view.tvUser.text = "——${item.userNick()} 推荐" view.rvDesc.visible() } else { view.rvDesc.gone() } return view } fun getItem(position: Int): IDetailPicture { return items!![position] } fun setOnItemClickListener(mListener: OnItemClickListener): PicDetailAdapter { this.mListener = mListener return this; } interface OnItemClickListener { fun onItemClicked(position: Int, picBean: IDetailPicture) } }
apache-2.0
6954f827d4193fa69450095f590633a2
31.026667
94
0.660283
4.170139
false
false
false
false
akakim/akakim.github.io
Android/KotlinRepository/QSalesPrototypeKotilnVersion/main/java/tripath/com/samplekapp/StaticValues.kt
1
1532
package tripath.com.samplekapp import android.os.Build /** * Created by SSLAB on 2017-07-26. */ class StaticValues{ companion object { const val basicURL = "http://qsales.autoground.tripath.work" const val SHOW_DIALOG_MESSAGE = 100 const val HIDE_DIALOG_MESSAGE = 101 const val SHOW_DILATING_DIALOG_MESSAGE = 101; const val REMOVE_DILATING_DIALOG_MESSAGE = 102; const val JAVA_SCRIPT_CALLBACK = 200 const val JAVA_SCRIPT_BACK_CALLBACK = 200 const val ON_PAGE_FINISHED = 201 const val SPLASHE_ANIMATION_MESSAGE = 1 const val SHARED_FCM_TOKEN = "FCM_TOKEN" const val ADVISOR_SEQUENCE = "advisorSeq" const val CHATROOM_AUTH_CODE = "chatroomAuthorizationCode" const val MESSAGE = "message" const val USER_CACHE = "userCache" const val SYSTEM_CACHE = "systemCache" const val AUTO_LOGIN = "autoLogin" const val ID = "id" const val PASSWORD = "password" const val FCM_TOKEN = "fcm_token" const val ITEM_LIST_FRAGMENT = "ItemListFragment" const val SYSTEM_SETTING = 999 const val REGISTRATION_READY = "registrationReady" const val REGISTRATION_GENERATING = "registrationGenerating" const val REGISTRATION_COMPLETE = "registrationComplete" const val REFRESH_CHATROOMS = "refreshChatRooms" var IS_LOLLIPOP = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP } } // const val SHOW_DIALOG_MESSAGE = 1;
gpl-3.0
5a92502706f15069c941e11c1180d5e0
26.854545
81
0.6547
4.031579
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/viewmodel/accounts/PostSignupInterstitialViewModel.kt
1
2726
package org.wordpress.android.viewmodel.accounts import androidx.lifecycle.ViewModel import org.wordpress.android.analytics.AnalyticsTracker.Stat.WELCOME_NO_SITES_INTERSTITIAL_ADD_SELF_HOSTED_SITE_TAPPED import org.wordpress.android.analytics.AnalyticsTracker.Stat.WELCOME_NO_SITES_INTERSTITIAL_CREATE_NEW_SITE_TAPPED import org.wordpress.android.analytics.AnalyticsTracker.Stat.WELCOME_NO_SITES_INTERSTITIAL_DISMISSED import org.wordpress.android.analytics.AnalyticsTracker.Stat.WELCOME_NO_SITES_INTERSTITIAL_SHOWN import org.wordpress.android.ui.accounts.UnifiedLoginTracker import org.wordpress.android.ui.accounts.UnifiedLoginTracker.Click import org.wordpress.android.ui.accounts.UnifiedLoginTracker.Step.SUCCESS import org.wordpress.android.ui.prefs.AppPrefsWrapper import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.viewmodel.SingleLiveEvent import org.wordpress.android.viewmodel.accounts.PostSignupInterstitialViewModel.NavigationAction.DISMISS import org.wordpress.android.viewmodel.accounts.PostSignupInterstitialViewModel.NavigationAction.START_SITE_CONNECTION_FLOW import org.wordpress.android.viewmodel.accounts.PostSignupInterstitialViewModel.NavigationAction.START_SITE_CREATION_FLOW import javax.inject.Inject class PostSignupInterstitialViewModel @Inject constructor( private val appPrefs: AppPrefsWrapper, private val unifiedLoginTracker: UnifiedLoginTracker, private val analyticsTracker: AnalyticsTrackerWrapper ) : ViewModel() { val navigationAction: SingleLiveEvent<NavigationAction> = SingleLiveEvent() fun onInterstitialShown() { analyticsTracker.track(WELCOME_NO_SITES_INTERSTITIAL_SHOWN) unifiedLoginTracker.track(step = SUCCESS) appPrefs.shouldShowPostSignupInterstitial = false } fun onCreateNewSiteButtonPressed() { analyticsTracker.track(WELCOME_NO_SITES_INTERSTITIAL_CREATE_NEW_SITE_TAPPED) unifiedLoginTracker.trackClick(Click.CREATE_NEW_SITE) navigationAction.value = START_SITE_CREATION_FLOW } fun onAddSelfHostedSiteButtonPressed() { analyticsTracker.track(WELCOME_NO_SITES_INTERSTITIAL_ADD_SELF_HOSTED_SITE_TAPPED) unifiedLoginTracker.trackClick(Click.ADD_SELF_HOSTED_SITE) navigationAction.value = START_SITE_CONNECTION_FLOW } fun onDismissButtonPressed() = onDismiss() fun onBackButtonPressed() = onDismiss() private fun onDismiss() { unifiedLoginTracker.trackClick(Click.DISMISS) analyticsTracker.track(WELCOME_NO_SITES_INTERSTITIAL_DISMISSED) navigationAction.value = DISMISS } enum class NavigationAction { START_SITE_CREATION_FLOW, START_SITE_CONNECTION_FLOW, DISMISS } }
gpl-2.0
9365bcc32e58d0e5ed4ea38842b1aa52
47.678571
123
0.810345
4.425325
false
false
false
false
ingokegel/intellij-community
plugins/github/src/org/jetbrains/plugins/github/GHOpenInBrowserFromAnnotationActionGroup.kt
1
1626
// 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 org.jetbrains.plugins.github import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.components.service import com.intellij.openapi.vcs.annotate.FileAnnotation import com.intellij.openapi.vcs.annotate.UpToDateLineNumberListener import com.intellij.vcsUtil.VcsUtil import git4idea.GitUtil import git4idea.annotate.GitFileAnnotation import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager class GHOpenInBrowserFromAnnotationActionGroup(val annotation: FileAnnotation) : GHOpenInBrowserActionGroup(), UpToDateLineNumberListener { private var myLineNumber = -1 override fun getData(dataContext: DataContext): List<Data>? { if (myLineNumber < 0) return null if (annotation !is GitFileAnnotation) return null val project = annotation.project val virtualFile = annotation.file val filePath = VcsUtil.getFilePath(virtualFile) val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(filePath) ?: return null val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository) if (accessibleRepositories.isEmpty()) return null val revisionHash = annotation.getLineRevisionNumber(myLineNumber)?.asString() if (revisionHash == null) return null return accessibleRepositories.map { Data.Revision(project, it.ghRepositoryCoordinates, revisionHash) } } override fun consume(integer: Int) { myLineNumber = integer } }
apache-2.0
2acc4fb2ac919237d2af6fb51917bb2a
39.65
140
0.801353
4.699422
false
false
false
false
ChristopherGittner/OSMBugs
app/src/main/java/org/gittner/osmbugs/osmnotes/OsmNoteInfoWindow.kt
1
4813
package org.gittner.osmbugs.osmnotes import android.content.Intent import android.view.View import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.core.widget.doOnTextChanged import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import org.gittner.osmbugs.R import org.gittner.osmbugs.databinding.OsmNotesMarkerBinding import org.gittner.osmbugs.statics.Settings import org.gittner.osmbugs.ui.ErrorInfoWindow import org.gittner.osmbugs.ui.ErrorViewModel import org.joda.time.DateTimeZone import org.osmdroid.views.MapView class OsmNoteInfoWindow(map: MapView, viewModel: ErrorViewModel) : ErrorInfoWindow(R.layout.osm_notes_marker, map) { private val mBinding: OsmNotesMarkerBinding = OsmNotesMarkerBinding.bind(view) private val mViewModel = viewModel private var mNewState = OsmNote.STATE.OPEN private var mSettings = Settings.getInstance() private var mEditComment = false override fun onOpen(item: Any?) { super.onOpen(item) val error = (item as OsmNoteMarker).mError mNewState = error.State mEditComment = false mBinding.apply { setStateView(imgState) txtvDescription.text = error.Description imgSave.visibility = View.GONE imgSave.setOnClickListener { if (!mSettings.OsmNotes.IsLoggedIn()) { startLogin() return@setOnClickListener } MainScope().launch { progressbarSave.visibility = View.VISIBLE imgSave.visibility = View.GONE try { mViewModel.updateOsmNote(error, edtxtComment.text.toString(), mNewState) close() } catch (error: Exception) { Toast.makeText( mMapView.context, mMapView.context.getString(R.string.err_failed_to_update_error) .format(error.message), Toast.LENGTH_LONG ).show() return@launch } finally { progressbarSave.visibility = View.GONE imgSave.visibility = View.VISIBLE } } } imgState.setOnClickListener { stateViewClicked() mNewState = if (mNewState == OsmNote.STATE.OPEN) OsmNote.STATE.CLOSED else OsmNote.STATE.OPEN updateViews(error) } imgEditComment.setOnClickListener { mEditComment = true updateViews(error) } edtxtComment.doOnTextChanged { _, _, _, _ -> updateViews(error) } edtxtComment.text.clear() txtvUser.text = error.User txtvDate.text = error.Date.withZone(DateTimeZone.getDefault()).toString(mMapView.context.getString(R.string.datetime_format)) if (error.Comments.count() > 0) { val comments = ArrayList<OsmNote.OsmNoteComment>() error.Comments.reversed().forEach { comments.add(it) } val adapter = OsmNoteCommentsAdapter(mMapView.context, comments) lstvComments.adapter = adapter lstvComments.visibility = View.VISIBLE } else { lstvComments.visibility = View.GONE } } updateViews(error) } private fun startLogin() { AlertDialog.Builder(mMapView.context) .setTitle(R.string.dialog_osmnotes_login_required_title) .setMessage(R.string.dialog_osmnotes_login_required_message) .setCancelable(true) .setPositiveButton(R.string.dialog_osmnotes_login_required_positive) { _, _ -> mMapView.context.startActivity(Intent(mMapView.context, OsmNotesLoginActivity::class.java)) }.show() } private fun updateViews(error: OsmNote) { mBinding.apply { imgState.setImageDrawable(if (mNewState == OsmNote.STATE.OPEN) OsmNote.IcOpen else OsmNote.IcClosed) imgSave.visibility = if (error.State != mNewState || edtxtComment.text.toString() != "") View.VISIBLE else View.GONE edtxtComment.visibility = if ((error.State == OsmNote.STATE.OPEN && mEditComment) || (error.State == OsmNote.STATE.CLOSED && mNewState == OsmNote.STATE.OPEN)) View.VISIBLE else View.GONE imgEditComment.visibility = if (error.State == OsmNote.STATE.OPEN && !mEditComment) View.VISIBLE else View.GONE } } }
mit
ef18ccbec18623e529bbe811ee3b804a
34.659259
176
0.589445
4.977249
false
false
false
false
android/play-billing-samples
ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/SubscriptionContent.kt
1
1640
/* * Copyright 2019 Google LLC. 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.example.subscriptions.data import android.os.Parcelable import kotlinx.parcelize.Parcelize /** * SubscriptionContent is an immutable object that holds the various metadata associated with a Subscription. */ @Parcelize class SubscriptionContent( val title: String?, val subtitle: String?, val description: String? = null ) : Parcelable { // Builder for Subscription object. class Builder { private var title: String? = null private var subtitle: String? = null private var desc: String? = null fun title(title: String): Builder { this.title = title return this } fun subtitle(subtitle: String): Builder { this.subtitle = subtitle return this } fun description(desc: String?): Builder { this.desc = desc return this } fun build(): SubscriptionContent { return SubscriptionContent(title, subtitle, desc) } } }
apache-2.0
e3f53c3cb2ac8ee11955e50da8e0454d
28.285714
109
0.662195
4.712644
false
false
false
false
GunoH/intellij-community
platform/util/src/com/intellij/openapi/diagnostic/RollingFileHandler.kt
8
2961
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.diagnostic import java.io.BufferedOutputStream import java.io.IOException import java.io.OutputStream import java.nio.charset.StandardCharsets import java.nio.file.* import java.util.logging.Level import java.util.logging.LogRecord import java.util.logging.StreamHandler class RollingFileHandler @JvmOverloads constructor( val logPath: Path, val limit: Long, val count: Int, val append: Boolean, private val onRotate: Runnable? = null ) : StreamHandler() { @Volatile private lateinit var meter: MeteredOutputStream private class MeteredOutputStream(private val delegate: OutputStream, @Volatile var written: Long) : OutputStream() { override fun write(b: Int) { delegate.write(b) written++ } override fun write(b: ByteArray) { delegate.write(b) written += b.size } override fun write(b: ByteArray, off: Int, len: Int) { delegate.write(b, off, len) written += len } override fun close() = delegate.close() override fun flush() = delegate.flush() } init { encoding = StandardCharsets.UTF_8.name() open(append) } private fun open(append: Boolean) { Files.createDirectories(logPath.parent) val delegate = BufferedOutputStream(Files.newOutputStream(logPath, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) meter = MeteredOutputStream(delegate, if (append) Files.size(logPath) else 0) setOutputStream(meter) } override fun publish(record: LogRecord) { if (!isLoggable(record)) return super.publish(record) flush() if (limit > 0 && meter.written >= limit) { synchronized(this) { if (meter.written >= limit) { rotate() } } } } private fun rotate() { onRotate?.run() try { Files.deleteIfExists(logPathWithIndex(count)) for (i in count-1 downTo 1) { val path = logPathWithIndex(i) if (Files.exists(path)) { Files.move(path, logPathWithIndex(i+1), StandardCopyOption.ATOMIC_MOVE) } } } catch (e: IOException) { // rotate failed, keep writing to existing log super.publish(LogRecord(Level.SEVERE, "Log rotate failed: ${e.message}").also { it.thrown = e }) return } close() val e = try { Files.move(logPath, logPathWithIndex(1), StandardCopyOption.ATOMIC_MOVE) null } catch (e: IOException) { e } open(false) if (e != null) { super.publish(LogRecord(Level.SEVERE, "Log rotate failed: ${e.message}").also { it.thrown = e }) } } private fun logPathWithIndex(index: Int): Path { val pathString = logPath.toString() val extIndex = pathString.lastIndexOf('.') return Paths.get(pathString.substring(0, extIndex) + ".$index" + pathString.substring(extIndex)) } }
apache-2.0
57df91072fb1f6491120ca5ac8ff3cf0
26.416667
125
0.663289
4.023098
false
false
false
false