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
mua-uniandes/weekly-problems
codeforces/915/915c.kt
1
1331
//package codeforces import java.io.BufferedReader import java.io.InputStreamReader import kotlin.system.exitProcess fun main() { val In = BufferedReader(InputStreamReader(System.`in`)) val first: MutableList<Int> = In.readLine()!!.toCharArray().map { Character.getNumericValue(it) }.toMutableList() val b = In.readLine()!!.toCharArray().map { Character.getNumericValue(it) } val a: MutableList<Int> = first.sortedDescending().toMutableList() val countA = IntArray(10) { 0 } if (b.size > first.size) { for (i in a) print(i) println() } else { for(i in a) countA[i] ++ val res = mutableListOf<Int>() fun find(step : Int, found : Boolean): Unit { if(step == b.size) { for (i in res) print(i) println() exitProcess(0) } else { var start = if(!found) b[step] else 9 for (j in start downTo 0) if (countA[j] > 0) { res.add(j) countA[j]-- find(step+1, found or (j < b[step])) countA[j] ++ res.removeAt(res.size-1) } } } find(0, false) } }
gpl-3.0
a35e7fef5c753250a3906de3ef0554d6
31.463415
117
0.483095
4.212025
false
false
false
false
emce/smog
app/src/main/java/mobi/cwiklinski/smog/ui/activity/MainActivity.kt
1
6469
package mobi.cwiklinski.smog.ui.activity import android.content.Intent import android.content.res.Resources import android.graphics.Color import android.graphics.PorterDuff import android.graphics.drawable.LayerDrawable import android.os.Bundle import android.support.v4.view.MenuItemCompat import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.widget.ProgressBar import com.facebook.CallbackManager import com.facebook.FacebookSdk import com.facebook.share.model.SharePhoto import com.facebook.share.model.SharePhotoContent import com.facebook.share.widget.ShareDialog import com.joanzapata.iconify.IconDrawable import com.joanzapata.iconify.fonts.TypiconsIcons import kotlinx.android.synthetic.main.activity_main.* import lecho.lib.hellocharts.model.LineChartData import lecho.lib.hellocharts.model.Viewport import mobi.cwiklinski.bloodline.ui.extension.setToolbar import mobi.cwiklinski.smog.R import mobi.cwiklinski.smog.model.MainViewModel import mobi.cwiklinski.smog.service.ReadingService class MainActivity : MainViewModel.MainViewModelListener, AppCompatActivity() { var callbackManager = CallbackManager.Factory.create() var viewModel = MainViewModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setToolbar() ReadingService.refresh(this) FacebookSdk.sdkInitialize(applicationContext); viewModel.listener = this mainChart.isZoomEnabled = false viewModel.mainAmount0Text.subscribe() viewModel.mainAmount1Text.subscribe({ mainAmount1.text = it }) viewModel.mainAmount2Text.subscribe({ mainAmount2.text = it }) viewModel.mainAmount3Text.subscribe({ mainAmount3.text = it }) viewModel.mainAmount4Text.subscribe({ mainAmount4.text = it }) viewModel.mainTime0Text.subscribe({ mainTime0.text = it }) viewModel.mainTime1Text.subscribe({ mainTime1.text = it }) viewModel.mainTime2Text.subscribe({ mainTime2.text = it }) viewModel.mainTime3Text.subscribe({ mainTime3.text = it }) viewModel.mainTime4Text.subscribe({ mainTime4.text = it }) viewModel.progress0Color.subscribe({ setProgressColor(it, mainValue0) }) viewModel.progress1Color.subscribe({ setProgressColor(it, mainValue1) }) viewModel.progress2Color.subscribe({ setProgressColor(it, mainValue2) }) viewModel.progress3Color.subscribe({ setProgressColor(it, mainValue3) }) viewModel.progress4Color.subscribe({ setProgressColor(it, mainValue4) }) viewModel.progress0Value.subscribe({ mainValue0.progress = it }) viewModel.progress1Value.subscribe({ mainValue1.progress = it }) viewModel.progress2Value.subscribe({ mainValue2.progress = it }) viewModel.progress3Value.subscribe({ mainValue3.progress = it }) viewModel.progress4Value.subscribe({ mainValue4.progress = it }) viewModel.progress0Max.subscribe({ mainValue0.max = it }) viewModel.progress1Max.subscribe({ mainValue1.max = it }) viewModel.progress2Max.subscribe({ mainValue2.max = it }) viewModel.progress3Max.subscribe({ mainValue3.max = it }) viewModel.progress4Max.subscribe({ mainValue4.max = it }) viewModel.queryForData() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) callbackManager.onActivityResult(requestCode, resultCode, data) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { super.onCreateOptionsMenu(menu) var refresh = menu!!.add(R.id.menu_group_main, R.id.menu_refresh, 2, R.string.app_name) MenuItemCompat.setShowAsAction(refresh, MenuItemCompat.SHOW_AS_ACTION_ALWAYS) refresh.setIcon(IconDrawable(this, TypiconsIcons.typcn_arrow_sync_outline).actionBarSize().color(Color.WHITE)) var share = menu.add(R.id.menu_group_main, R.id.menu_share, 1, R.string.app_name) MenuItemCompat.setShowAsAction(share, MenuItemCompat.SHOW_AS_ACTION_ALWAYS) share.setIcon(IconDrawable(this, TypiconsIcons.typcn_export_outline).actionBarSize().color(Color.WHITE)) return true; } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item!!.itemId) { R.id.menu_refresh -> { ReadingService.refresh(this) return true } R.id.menu_share -> { mainRoot.isDrawingCacheEnabled = true var photo = SharePhoto.Builder().setBitmap(mainRoot.drawingCache!!).build() var content = SharePhotoContent.Builder().addPhoto(photo).build() if (ShareDialog.canShow(SharePhotoContent::class.java)) { ShareDialog(this).show(content) return true } return false } else -> return super.onOptionsItemSelected(item) } } override fun onGraphDataLoaded(chartData: LineChartData, min: Float?, max: Float?) { mainChart.lineChartData = chartData var v = Viewport(mainChart.maximumViewport); v.bottom = min!!.minus(5f) v.top = max!!.plus(5f) mainChart.maximumViewport = v mainChart.setCurrentViewportWithAnimation(v) } private fun setProgressColor(color: Int, progress: ProgressBar) { try { if (progress.progressDrawable!! is LayerDrawable) { var layerDrawable = progress.progressDrawable as LayerDrawable; var progressDrawable = layerDrawable.findDrawableByLayerId(android.R.id.progress) progressDrawable.setColorFilter(resources.getColor(color), PorterDuff.Mode.SRC_IN) } } catch (e : Resources.NotFoundException) { e.printStackTrace() } } }
apache-2.0
69f87b6bbe7386b2870d2e1bc73810b9
36.183908
118
0.651878
4.498609
false
false
false
false
toastkidjp/Jitte
lib/src/main/java/jp/toastkid/lib/view/TextViewHighlighter.kt
1
2079
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.lib.view import android.text.Spannable import android.text.SpannableString import android.text.style.BackgroundColorSpan import android.widget.TextView import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * @author toastkidjp */ class TextViewHighlighter(private val textView: TextView) { operator fun invoke(textToHighlight: String?) { if (textToHighlight.isNullOrBlank()) { textView.text = textView.text.toString() return } CoroutineScope(Dispatchers.Main).launch { val tvt = withContext(Dispatchers.Default) { textView.text.toString() } var ofe = withContext(Dispatchers.Default) { tvt.indexOf(textToHighlight, 0) } val wordToSpan = withContext(Dispatchers.Default) { SpannableString(textView.text) } var ofs = 0 while (ofs < tvt.length && ofe != -1) { ofe = tvt.indexOf(textToHighlight, ofs) if (ofe == -1) break else { // set color here withContext(Dispatchers.Default) { wordToSpan.setSpan( BackgroundColorSpan(-0x100), ofe, ofe + textToHighlight.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } textView.setText(wordToSpan, TextView.BufferType.SPANNABLE) } ofs = ofe + 1 } } } }
epl-1.0
eac79e3b0a1a9b4a53cc0904f7d3d2e5
33.098361
88
0.569024
5.021739
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/collection/StickyHeaderCollectionKComponent.kt
1
1663
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.samples.litho.kotlin.collection import android.graphics.Color import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.widget.collection.LazyList class StickyHeaderCollectionKComponent : KComponent() { override fun ComponentScope.render(): Component = LazyList { child(isSticky = true, component = Text("Sticky Title 1", backgroundColor = Color.WHITE)) children(items = (0..20), id = { it }) { Text("$it") } child(isSticky = true, component = Text("Sticky Title 2", backgroundColor = Color.WHITE)) children(items = (21..40), id = { it }) { Text("$it") } child(isSticky = false, component = Text("Not sticky Title 3", backgroundColor = Color.WHITE)) children(items = (41..60), id = { it }) { Text("$it") } child(isSticky = true, component = Text("Sticky Title 4", backgroundColor = Color.WHITE)) children(items = (61..80), id = { it }) { Text("$it") } } }
apache-2.0
e55806f04257d5966bdcddce81eaa768
42.763158
98
0.711966
3.968974
false
false
false
false
fnouama/intellij-community
platform/configuration-store-impl/src/SchemeManagerFactoryImpl.kt
2
4468
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.ide.impl.ProjectUtil import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.SettingsSavingComponent import com.intellij.openapi.components.impl.stores.StateStorageManager import com.intellij.openapi.components.stateStore import com.intellij.openapi.options.* import com.intellij.openapi.project.Project import com.intellij.util.SmartList import com.intellij.util.containers.ContainerUtil import com.intellij.util.lang.CompoundRuntimeException import java.io.File val ROOT_CONFIG: String = "\$ROOT_CONFIG$" public abstract class SchemeManagerFactoryBase : SchemesManagerFactory(), SettingsSavingComponent { private val managers = ContainerUtil.createLockFreeCopyOnWriteList<SchemeManagerImpl<Scheme, ExternalizableScheme>>() abstract val componentManager: ComponentManager override final fun <T : Scheme, E : ExternalizableScheme> createSchemesManager(directoryName: String, processor: SchemeProcessor<E>, roamingType: RoamingType): SchemesManager<T, E> { val storageManager = (componentManager.stateStore).stateStorageManager val path = checkPath(directoryName) val manager = SchemeManagerImpl<T, E>(path, processor, (storageManager as? StateStorageManagerImpl)?.streamProvider, pathToFile(path, storageManager), roamingType, componentManager) @Suppress("CAST_NEVER_SUCCEEDS") managers.add(manager as SchemeManagerImpl<Scheme, ExternalizableScheme>) return manager } open fun checkPath(originalPath: String): String { fun error(message: String) { // as error because it is not a new requirement if (ApplicationManager.getApplication().isUnitTestMode) throw AssertionError(message) else LOG.error(message) } when { originalPath.contains('\\') -> error("Path must be system-independent, use forward slash instead of backslash") originalPath.isEmpty() -> error("Path must not be empty") } return originalPath } abstract fun pathToFile(path: String, storageManager: StateStorageManager): File public fun process(processor: (SchemeManagerImpl<Scheme, ExternalizableScheme>) -> Unit) { for (manager in managers) { try { processor(manager) } catch (e: Throwable) { LOG.error("Cannot reload settings for ${manager.javaClass.name}", e) } } } override final fun save() { val errors = SmartList<Throwable>() for (registeredManager in managers) { try { registeredManager.save(errors) } catch (e: Throwable) { errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) } } private class ApplicationSchemeManagerFactory : SchemeManagerFactoryBase() { override val componentManager: ComponentManager get() = ApplicationManager.getApplication() override fun checkPath(originalPath: String): String { var path = super.checkPath(originalPath) if (path.startsWith(ROOT_CONFIG)) { path = path.substring(ROOT_CONFIG.length() + 1) val message = "Path must not contains ROOT_CONFIG macro, corrected: $path" if (ApplicationManager.getApplication().isUnitTestMode) throw AssertionError(message) else LOG.warn(message) } return path } override fun pathToFile(path: String, storageManager: StateStorageManager) = File(storageManager.expandMacros("$ROOT_CONFIG/$path")) } private class ProjectSchemeManagerFactory(private val project: Project) : SchemeManagerFactoryBase() { override val componentManager = project override fun pathToFile(path: String, storageManager: StateStorageManager) = File(project.basePath, if (ProjectUtil.isDirectoryBased(project)) "${Project.DIRECTORY_STORE_FOLDER}/$path" else ".$path") }
apache-2.0
ac98bb349e3dc72e1e50446930db50ba
39.261261
201
0.755595
4.825054
false
true
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandmenu/RewardsPage.kt
1
7662
package com.github.shynixn.blockball.core.logic.business.commandmenu import com.github.shynixn.blockball.api.BlockBallApi import com.github.shynixn.blockball.api.business.enumeration.* import com.github.shynixn.blockball.api.business.service.DependencyVaultService import com.github.shynixn.blockball.api.persistence.entity.Arena import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder import com.github.shynixn.blockball.api.persistence.entity.CommandMeta import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity import com.github.shynixn.blockball.core.logic.persistence.entity.CommandMetaEntity /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class RewardsPage : Page(SoundEffectPage.ID, MainSettingsPage.ID) { companion object { /** Id of the page. */ const val ID = 22 } /** * Returns the key of the command when this page should be executed. * * @return key */ override fun getCommandKey(): MenuPageKey { return MenuPageKey.REWARDSPAGE } /** * Executes actions for this page. * * @param cache cache */ override fun <P> execute(player: P, command: MenuCommand, cache: Array<Any?>, args: Array<String>): MenuCommandResult { val arena = cache[0] as Arena if (command == MenuCommand.REWARD_OPEN) { cache[4] = null cache[5] = null } else if (command == MenuCommand.REWARD_CALLBACK_MONEY && args.size >= 3 && args[2].toIntOrNull() != null) { val rewardedAction = RewardType.values()[args[2].toInt()] cache[5] = rewardedAction if (arena.meta.rewardMeta.moneyReward[rewardedAction] == null) { arena.meta.rewardMeta.moneyReward[rewardedAction] = 0 } cache[4] = arena.meta.rewardMeta.moneyReward[rewardedAction] } else if (command == MenuCommand.REWARD_CALLBACK_COMMAND && args.size >= 3 && args[2].toIntOrNull() != null) { val rewardedAction = RewardType.values()[args[2].toInt()] cache[5] = rewardedAction if (arena.meta.rewardMeta.commandReward[rewardedAction] == null) { val command2 = CommandMetaEntity() command2.command = "none" command2.mode = CommandMode.CONSOLE_SINGLE arena.meta.rewardMeta.commandReward[rewardedAction] = command2 } cache[4] = arena.meta.rewardMeta.commandReward[rewardedAction] } else if (command == MenuCommand.REWARD_CALLBACK_COMMANDMODE && args.size >= 3 && args[2].toIntOrNull() != null) { val selectedReward = cache[4] as CommandMeta selectedReward.mode = CommandMode.values()[args[2].toInt()] } else if (command == MenuCommand.REWARD_EDIT_MONEY && args.size >= 3 && args[2].toIntOrNull() != null) { arena.meta.rewardMeta.moneyReward[cache[5] as RewardType] = args[2].toInt() cache[4] = args[2].toInt() } else if (command == MenuCommand.REWARD_EDIT_COMMAND && args.size >= 3) { arena.meta.rewardMeta.commandReward[cache[5] as RewardType]!!.command = mergeArgs(2, args) } return super.execute(player, command, cache, args) } /** * Builds this page for the player. * * @return page */ override fun buildPage(cache: Array<Any?>): ChatBuilder? { val selectedReward = cache[4] val rewardedAction = cache[5] val builder = ChatBuilderEntity() try { BlockBallApi.resolve(DependencyVaultService::class.java) builder.component("- Money reward (Vault): ").builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_REWARDED_MONEY.command) .setHoverText("Opens the selectionbox for rewarded actions.") .builder().nextLine() } catch (e: Exception) { } builder.component("- Command reward: ").builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_REWARDED_COMMAND.command) .setHoverText("Opens the selectionbox for rewarded actions.") .builder().nextLine() if (selectedReward != null) { if (selectedReward is Int) { val vaultService: DependencyVaultService try { vaultService = BlockBallApi.resolve(DependencyVaultService::class.java) } catch (e: Exception) { return builder } builder.component("- Selected Money reward (Vault): " + (rewardedAction as RewardType).name).builder().nextLine() .component("- " + vaultService.getPluralCurrencyName() + ": " + ChatColor.WHITE + selectedReward).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.REWARD_EDIT_MONEY.command) .setHoverText("Changes the amount of money the players receive on the selected action.") .builder() } else if (selectedReward is CommandMeta) { builder.component("- Selected Command reward: " + (rewardedAction as RewardType).name).builder().nextLine() .component("- Command: " + selectedReward.command).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.REWARD_EDIT_COMMAND.command) .setHoverText("Changes the amount of money the players receive on the selected action.") .builder().nextLine() .component("- Mode: " + selectedReward.mode.name).builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_COMMANDMODES.command) .setHoverText("Opens the selectionbox for command modes.") .builder().nextLine()// } } else { builder.component("- Selected reward: none") } return builder } }
apache-2.0
f6ca74a1ec782231570fb632e5db7ebe
48.75974
129
0.646959
4.552585
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/proxy/BallCrossPlatformProxy.kt
1
4733
@file:Suppress("UNCHECKED_CAST") package com.github.shynixn.blockball.core.logic.business.proxy import com.github.shynixn.blockball.api.business.proxy.BallProxy import com.github.shynixn.blockball.api.business.service.EventService import com.github.shynixn.blockball.api.business.service.LoggingService import com.github.shynixn.blockball.api.business.service.ProxyService import com.github.shynixn.blockball.api.persistence.entity.BallMeta import com.github.shynixn.blockball.core.logic.persistence.event.BallDeathEventEntity import com.github.shynixn.blockball.core.logic.persistence.event.BallTeleportEventEntity class BallCrossPlatformProxy( override val meta: BallMeta, private val ballDesignEntity: BallDesignEntity, private val ballHitBoxEntity: BallHitboxEntity ) : BallProxy { private var allPlayerTracker: AllPlayerTracker = AllPlayerTracker( { ballHitBoxEntity.position }, { player -> ballDesignEntity.spawn(player, ballHitBoxEntity.position) ballHitBoxEntity.spawn(player, ballHitBoxEntity.position) }, { player -> ballDesignEntity.destroy(player) ballHitBoxEntity.destroy(player) }) /** * Logging dependency. */ lateinit var loggingService: LoggingService /** * Proxy dependency. */ var proxyService: ProxyService set(value) { this.allPlayerTracker.proxyService = value } get() { return allPlayerTracker.proxyService } /** * Event dependency. */ lateinit var eventService: EventService /** * Is the entity dead? */ override var isDead: Boolean = false /** * Entity id of the hitbox. */ override val hitBoxEntityId: Int get() { return ballHitBoxEntity.entityId } /** * Entity id of the design. */ override val designEntityId: Int get() { return ballDesignEntity.entityId } /** * Gets if the ball is on ground. */ override val isOnGround: Boolean get() { return ballHitBoxEntity.isOnGround } /** * Teleports the ball to the given [location]. */ override fun <L> teleport(location: L) { val ballTeleportEvent = BallTeleportEventEntity(this, location as Any) eventService.sendEvent(ballTeleportEvent) if (ballTeleportEvent.isCancelled) { return } ballHitBoxEntity.position = proxyService.toPosition(ballTeleportEvent.targetLocation) ballHitBoxEntity.requestTeleport = true } /** * Gets the location of the ball. */ override fun <L> getLocation(): L { return proxyService.toLocation(ballHitBoxEntity.position) } /** * Gets the velocity of the ball. */ override fun <V> getVelocity(): V { return proxyService.toVector(ballHitBoxEntity.motion) } /** * Rotation of the visible ball in euler angles. */ override fun <V> getRotation(): V { return proxyService.toVector(ballDesignEntity.rotation) } /** * Shoot the ball by the given player. * The calculated velocity can be manipulated by the BallKickEvent. * * @param player */ override fun <P> kickByPlayer(player: P) { require(player is Any) if (!meta.enabledKick) { return } ballHitBoxEntity.kickPlayer(player, meta.movementModifier.shotVelocity, false) } /** * Pass the ball by the given player. * The calculated velocity can be manipulated by the BallKickEvent * * @param player */ override fun <P> passByPlayer(player: P) { require(player is Any) if (!meta.enabledPass) { return } ballHitBoxEntity.kickPlayer(player, meta.movementModifier.passVelocity, true) } /** * Removes the ball. */ override fun remove() { if (isDead) { return } val ballDeathEvent = BallDeathEventEntity(this) eventService.sendEvent(ballDeathEvent) if (ballDeathEvent.isCancelled) { return } isDead = true allPlayerTracker.dispose() } /** * Runnable. Should not be called directly. */ override fun run() { if (isDead) { return } try { val players = allPlayerTracker.checkAndGet() ballHitBoxEntity.tick(players) ballDesignEntity.tick(players) } catch (e: Exception) { loggingService.warn("Entity ticking exception.", e) } } }
apache-2.0
f9f51d27f89e03fa5636ccaa56ddd94d
24.863388
93
0.619692
4.564127
false
false
false
false
michael-johansen/workshop-jb
src/v_collections/I_Partition_.kt
5
487
package v_collections fun example8() { val numbers = listOf(1, 3, -4, 2, -11) // The details (how multi-assignment works) were explained in the earlier 'Conventions' task val (positive, negative) = numbers.partition { it > 0 } positive == listOf(1, 3, 2) negative == listOf(-4, -11) } fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> { // Return customers who have more undelivered orders than delivered todoCollectionTask() }
mit
dadae5ed03fbb0a86407779152e62efe
29.4375
96
0.696099
4.058333
false
false
false
false
nlfiedler/mal
kotlin/src/mal/core.kt
1
9261
package mal import java.io.File val ns = hashMapOf( envPair("+", { a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger + y as MalInteger }) }), envPair("-", { a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger - y as MalInteger }) }), envPair("*", { a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger * y as MalInteger }) }), envPair("/", { a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger / y as MalInteger }) }), envPair("list", { a: ISeq -> MalList(a) }), envPair("list?", { a: ISeq -> if (a.first() is MalList) TRUE else FALSE }), envPair("empty?", { a: ISeq -> if (a.first() !is ISeq || !(a.first() as ISeq).seq().any()) TRUE else FALSE }), envPair("count", { a: ISeq -> if (a.first() is ISeq) MalInteger((a.first() as ISeq).count().toLong()) else MalInteger(0) }), envPair("=", { a: ISeq -> pairwiseEquals(a) }), envPair("<", { a: ISeq -> pairwiseCompare(a, { x, y -> x.value < y.value }) }), envPair("<=", { a: ISeq -> pairwiseCompare(a, { x, y -> x.value <= y.value }) }), envPair(">", { a: ISeq -> pairwiseCompare(a, { x, y -> x.value > y.value }) }), envPair(">=", { a: ISeq -> pairwiseCompare(a, { x, y -> x.value >= y.value }) }), envPair("pr-str", { a: ISeq -> MalString(a.seq().map({ it -> pr_str(it, print_readably = true) }).joinToString(" ")) }), envPair("str", { a: ISeq -> MalString(a.seq().map({ it -> pr_str(it, print_readably = false) }).joinToString("")) }), envPair("prn", { a: ISeq -> println(a.seq().map({ it -> pr_str(it, print_readably = true) }).joinToString(" ")) NIL }), envPair("println", { a: ISeq -> println(a.seq().map({ it -> pr_str(it, print_readably = false) }).joinToString(" ")) NIL }), envPair("read-string", { a: ISeq -> val string = a.first() as? MalString ?: throw MalException("slurp requires a string parameter") read_str(string.value) }), envPair("slurp", { a: ISeq -> val name = a.first() as? MalString ?: throw MalException("slurp requires a filename parameter") val text = File(name.value).readText() MalString(text) }), envPair("cons", { a: ISeq -> val list = a.nth(1) as? ISeq ?: throw MalException("cons requires a list as its second parameter") val mutableList = list.seq().toLinkedList() mutableList.addFirst(a.nth(0)) MalList(mutableList) }), envPair("concat", { a: ISeq -> MalList(a.seq().flatMap({ it -> (it as ISeq).seq() }).toLinkedList()) }), envPair("nth", { a: ISeq -> val list = a.nth(0) as? ISeq ?: throw MalException("nth requires a list as its first parameter") val index = a.nth(1) as? MalInteger ?: throw MalException("nth requires an integer as its second parameter") if (index.value >= list.count()) throw MalException("index out of bounds") list.nth(index.value.toInt()) }), envPair("first", { a: ISeq -> if (a.nth(0) == NIL) NIL else { val list = a.nth(0) as? ISeq ?: throw MalException("first requires a list parameter") if (list.seq().any()) list.first() else NIL } }), envPair("rest", { a: ISeq -> val list = a.nth(0) as? ISeq ?: throw MalException("rest requires a list parameter") MalList(list.rest()) }), envPair("throw", { a: ISeq -> val throwable = a.nth(0) throw MalCoreException(pr_str(throwable), throwable) }), envPair("apply", { a: ISeq -> val function = a.nth(0) as MalFunction val params = MalList() a.seq().drop(1).forEach({ it -> if (it is ISeq) { it.seq().forEach({ x -> params.conj_BANG(x) }) } else { params.conj_BANG(it) } }) function.apply(params) }), envPair("map", { a: ISeq -> val function = a.nth(0) as MalFunction MalList((a.nth(1) as ISeq).seq().map({ it -> val params = MalList() params.conj_BANG(it) function.apply(params) }).toLinkedList()) }), envPair("nil?", { a: ISeq -> if (a.nth(0) == NIL) TRUE else FALSE }), envPair("true?", { a: ISeq -> if (a.nth(0) == TRUE) TRUE else FALSE }), envPair("false?", { a: ISeq -> if (a.nth(0) == FALSE) TRUE else FALSE }), envPair("symbol?", { a: ISeq -> if (a.nth(0) is MalSymbol) TRUE else FALSE }), envPair("symbol", { a: ISeq -> MalSymbol((a.nth(0) as MalString).value) }), envPair("keyword", { a: ISeq -> val param = a.nth(0) if (param is MalKeyword) param else MalKeyword((a.nth(0) as MalString).value) }), envPair("keyword?", { a: ISeq -> if (a.nth(0) is MalKeyword) TRUE else FALSE }), envPair("vector", { a: ISeq -> MalVector(a) }), envPair("vector?", { a: ISeq -> if (a.nth(0) is MalVector) TRUE else FALSE }), envPair("hash-map", { a: ISeq -> val map = MalHashMap() pairwise(a).forEach({ it -> map.assoc_BANG(it.first as MalString, it.second) }) map }), envPair("map?", { a: ISeq -> if (a.nth(0) is MalHashMap) TRUE else FALSE }), envPair("assoc", { a: ISeq -> val map = MalHashMap(a.first() as MalHashMap) pairwise(a.rest()).forEach({ it -> map.assoc_BANG(it.first as MalString, it.second) }) map }), envPair("dissoc", { a: ISeq -> val map = MalHashMap(a.first() as MalHashMap) a.rest().seq().forEach({ it -> map.dissoc_BANG(it as MalString) }) map }), envPair("get", { a: ISeq -> val map = a.nth(0) as? MalHashMap val key = a.nth(1) as MalString map?.elements?.get(key) ?: NIL }), envPair("contains?", { a: ISeq -> val map = a.nth(0) as? MalHashMap val key = a.nth(1) as MalString if (map?.elements?.get(key) != null) TRUE else FALSE }), envPair("keys", { a: ISeq -> val map = a.nth(0) as MalHashMap // Another situation where kotlinc breaks if I don't add this unnecessary cast MalList(map.elements.keys.map({ it -> it as MalType }).asSequence().toLinkedList()) }), envPair("vals", { a: ISeq -> val map = a.nth(0) as MalHashMap MalList(map.elements.values.asSequence().toLinkedList()) }), envPair("count", { a: ISeq -> val seq = a.nth(0) as? ISeq if (seq != null) MalInteger(seq.count().toLong()) else ZERO }), envPair("sequential?", { a: ISeq -> if (a.nth(0) is ISeq) TRUE else FALSE }), envPair("with-meta", { a: ISeq -> val obj = a.nth(0) val metadata = a.nth(1) obj.with_meta(metadata) }), envPair("meta", { a: ISeq -> a.first().metadata }), envPair("conj", { a: ISeq -> (a.first() as ISeq).conj(a.rest()) }), envPair("atom", { a: ISeq -> MalAtom(a.first()) }), envPair("atom?", { a: ISeq -> if (a.first() is MalAtom) TRUE else FALSE }), envPair("deref", { a: ISeq -> (a.first() as MalAtom).value }), envPair("reset!", { a: ISeq -> val atom = a.nth(0) as MalAtom val value = a.nth(1) atom.value = value value }), envPair("swap!", { a: ISeq -> val atom = a.nth(0) as MalAtom val function = a.nth(1) as MalFunction val params = MalList() params.conj_BANG(atom.value) a.seq().drop(2).forEach({ it -> params.conj_BANG(it) }) val value = function.apply(params) atom.value = value value }), envPair("readline", { a: ISeq -> val prompt = a.first() as MalString try { MalString(readline(prompt.value)) } catch (e: java.io.IOException) { throw MalException(e.message) } catch (e: EofException) { NIL } }), envPair("time-ms", { a: ISeq -> MalInteger(System.currentTimeMillis()) }) ) private fun envPair(k: String, v: (ISeq) -> MalType): Pair<MalSymbol, MalType> = Pair(MalSymbol(k), MalFunction(v)) private fun pairwise(s: ISeq): List<Pair<MalType, MalType>> { val (keys, vals) = s.seq().withIndex().partition({ it -> it.index % 2 == 0 }) return keys.map({ it -> it.value }).zip(vals.map({ it -> it.value })) } private fun pairwiseCompare(s: ISeq, pred: (MalInteger, MalInteger) -> Boolean): MalConstant = if (pairwise(s).all({ it -> pred(it.first as MalInteger, it.second as MalInteger) })) TRUE else FALSE private fun pairwiseEquals(s: ISeq): MalConstant = if (pairwise(s).all({ it -> it.first == it.second })) TRUE else FALSE
mpl-2.0
34173f14540b41e8002242689e6f9ccc
42.478873
120
0.507721
3.734274
false
false
false
false
asarkar/spring
pinterest-client/src/test/kotlin/org/abhijitsarkar/spring/pinterest/PinterestDefaultImplSpec.kt
1
3535
package org.abhijitsarkar.spring.pinterest import io.kotlintest.specs.ShouldSpec import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.AccessTokenRequest import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.CreateBoardRequest import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.CreatePinRequest import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.DeleteBoardRequest import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.FindBoardRequest import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.FindUserRequest import org.abhijitsarkar.spring.pinterest.client.Pinterest.PinterestJsonFormat.FindUserResponse import org.abhijitsarkar.spring.pinterest.client.PinterestDefaultImpl import reactor.core.publisher.Mono import reactor.test.StepVerifier import java.io.File import java.time.Duration /** * @author Abhijit Sarkar */ class PinterestDefaultImplSpec : ShouldSpec() { val pinterest = PinterestDefaultImpl() // https://developers.pinterest.com/tools/access_token/ val accessToken = System.getenv("PINTEREST_ACCESS_TOKEN") init { should("get the access token") { val clientId = System.getenv("PINTEREST_CLIENT_ID") val clientSecret = System.getenv("PINTEREST_CLIENT_SECRET") val accessCode = System.getenv("PINTEREST_ACCESS_CODE") StepVerifier.create(pinterest.getAccessToken(AccessTokenRequest(clientId, clientSecret, accessCode))) .expectNextCount(1) .expectComplete() .verify(Duration.ofSeconds(3)) }.config(enabled = false) should("find board and delete it if exists, then create the board, then upload a pin") { val name = "test" val response = pinterest.findUser(FindUserRequest(accessToken)) .map(FindUserResponse::username) .flatMap { username -> pinterest.findBoard(FindBoardRequest(accessToken, name, username)) .hasElement() .defaultIfEmpty(false) .map { it.to(username) } } .flatMap { (found, username) -> Mono.just(found) .filter { it } .flatMap { fnd -> pinterest.deleteBoard(DeleteBoardRequest(accessToken, name, username)) .map { fnd.to(username) } } .defaultIfEmpty(found.to(username)) } .flatMap { (_, username) -> pinterest.createBoard(CreateBoardRequest(accessToken, name, username)) .map { it.to(username) } } .flatMap { (createBoardResponse, username) -> pinterest.createPin(CreatePinRequest(accessToken, createBoardResponse.name, File(javaClass.getResource("/pinterest-multi-client.jpg").toURI()), username = username)) } StepVerifier.create(response) .expectNextCount(1) .expectComplete() .verify(Duration.ofSeconds(30)) }.config(enabled = false) } }
gpl-3.0
dc7698de71ac1a30dd5d5f7dcd426b8e
48.111111
121
0.60396
5.057225
false
false
false
false
lewinskimaciej/planner
app/src/main/java/com/atc/planner/extension/ImageViewExtensions.kt
1
2686
package com.atc.planner.extension import android.net.Uri import android.support.annotation.IdRes import android.widget.ImageView import com.atc.planner.commons.GlideApp import com.bumptech.glide.load.engine.DiskCacheStrategy import jp.wasabeef.glide.transformations.BitmapTransformation import java.io.File fun ImageView.loadImage(url: String?, bitmapTransformation: BitmapTransformation? = null) { url?.let { if (bitmapTransformation != null) { GlideApp.with(this.context) .asBitmap() .transform(bitmapTransformation) .load(url) .skipMemoryCache(true) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .into(this) } else { GlideApp.with(this.context) .load(url) .skipMemoryCache(true) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .into(this) } } } fun ImageView.loadImage(url: String?, @IdRes error: Int?) { url?.let { if (error != null) { GlideApp.with(this.context) .load(url) .error(error) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .into(this) } } } fun ImageView.loadImage(file: File?) { file?.let { GlideApp.with(this.context) .load(file) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .into(this) } } fun ImageView.loadImage(file: File?, @IdRes error: Int?) { file?.let { if (error != null) { GlideApp.with(this.context) .load(file) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .error(error) .into(this) } } } fun ImageView.loadImage(uri: Uri?) { uri?.let { GlideApp.with(this.context) .load(uri) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .into(this) } } fun ImageView.loadImage(@IdRes drawable: Int?, @IdRes error: Int?) { drawable?.let { if (error != null) { GlideApp.with(this.context) .load(drawable) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .error(error) .into(this) } } } fun ImageView.loadImage(@IdRes drawable: Int?) { drawable?.let { GlideApp.with(this.context) .load(drawable) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .into(this) } }
mit
f8aede3c1344223d91d614618b44893a
28.195652
91
0.539836
4.695804
false
false
false
false
langara/USpek
ktjsreactsample/src/jsMain/kotlin/playground/example.kt
1
1916
package playground import kotlinx.coroutines.delay import pl.mareklangiewicz.uspek.* class MicroCalc(var result: Int) { fun add(x: Int) { result += x } fun multiplyBy(x: Int) { result *= x } } // lazy so private suspend infix fun String.lso(code: suspend () -> Unit) { delay(lsoDelayMs) so(code) } var lsoDelayMs = 100L suspend fun example() = suspek { "create SUT" lso { val sut = MicroCalc(10) "check add" lso { sut.add(5) sut.result eq 15 sut.add(100) sut.result eq 115 } "mutate SUT" lso { sut.add(1) "incorrectly check add - this should fail" lso { sut.add(5) sut.result eq 15 } } "check add again" lso { sut.add(5) sut.result eq 15 sut.add(100) sut.result eq 115 } testSomeAdding(sut) "mutate SUT and check multiplyBy" lso { sut.result = 3 sut.multiplyBy(3) sut.result eq 9 sut.multiplyBy(4) sut.result eq 36 testSomeAdding(sut) 1 eq 2 } "assure that SUT is intact by any of sub tests above" lso { sut.result eq 10 } } } private suspend fun testSomeAdding(calc: MicroCalc) { val start = calc.result "add 5 to $start" lso { calc.add(5) val afterAdd5 = start + 5 "result should be $afterAdd5" lso { calc.result eq afterAdd5 } "add 7 more" lso { calc.add(7) val afterAdd5Add7 = afterAdd5 + 7 "result should be $afterAdd5Add7" lso { calc.result eq afterAdd5Add7 } } } "subtract 3" lso { calc.add(-3) val afterSub3 = start - 3 "result should be $afterSub3" lso { calc.result eq afterSub3 } } }
apache-2.0
f322c5c2295044e85dfb67b711766bd5
20.52809
82
0.517745
3.642586
false
false
false
false
vovagrechka/k2php
k2php/src/org/jetbrains/kotlin/js/inline/clean/RedundantStatementElimination.kt
2
8430
/* * Copyright 2010-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.js.inline.clean import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.backend.ast.metadata.SideEffectKind import org.jetbrains.kotlin.js.backend.ast.metadata.isSuspend import org.jetbrains.kotlin.js.backend.ast.metadata.sideEffects import org.jetbrains.kotlin.js.backend.ast.metadata.synthetic import org.jetbrains.kotlin.js.inline.util.collectLocalVariables import org.jetbrains.kotlin.js.translate.utils.JsAstUtils class RedundantStatementElimination(private val root: JsFunction) { private val localVars = root.collectLocalVariables() private var hasChanges = false fun apply(): Boolean { process() return hasChanges } private fun process() { object : JsVisitorWithContextImpl() { override fun visit(x: JsExpressionStatement, ctx: JsContext<JsNode>): Boolean { if (!x.expression.isSuspend && (x.synthetic || x.expression.synthetic)) { val replacement = replace(x.expression) if (replacement.size != 1 || replacement[0] != x.expression) { hasChanges = true ctx.addPrevious(replacement.map { JsExpressionStatement(it).apply { synthetic = true } }) ctx.removeMe() } } return super.visit(x, ctx) } override fun visit(x: JsBinaryOperation, ctx: JsContext<JsNode>): Boolean { if (!x.isSuspend && x.operator == JsBinaryOperator.COMMA) { val expressions = replace(x.arg1) val replacement = if (expressions.isEmpty()) { x.arg2 } else { JsAstUtils.newSequence(expressions + x.arg2) } ctx.replaceMe(replacement) } return super.visit(x, ctx) } }.accept(root.body) } private fun replace(expression: JsExpression): List<JsExpression> { return when (expression) { is JsNameRef -> { if (expression.name in localVars) { listOf() } else if (expression.sideEffects != SideEffectKind.AFFECTS_STATE) { val qualifier = expression.qualifier if (qualifier != null) replace(qualifier) else listOf() } else { listOf(expression) } } is JsUnaryOperation -> { when (expression.operator!!) { JsUnaryOperator.BIT_NOT, JsUnaryOperator.NOT, JsUnaryOperator.TYPEOF, JsUnaryOperator.VOID, JsUnaryOperator.POS, JsUnaryOperator.NEG -> replace(expression.arg) JsUnaryOperator.DEC, JsUnaryOperator.INC, JsUnaryOperator.DELETE -> listOf(expression) } } is JsBinaryOperation -> { when (expression.operator) { JsBinaryOperator.BIT_AND, JsBinaryOperator.BIT_OR, JsBinaryOperator.BIT_XOR, JsBinaryOperator.COMMA, JsBinaryOperator.ADD, JsBinaryOperator.SUB, JsBinaryOperator.MUL, JsBinaryOperator.DIV, JsBinaryOperator.MOD, JsBinaryOperator.EQ, JsBinaryOperator.NEQ, JsBinaryOperator.REF_EQ, JsBinaryOperator.REF_NEQ, JsBinaryOperator.GT, JsBinaryOperator.GTE, JsBinaryOperator.LT, JsBinaryOperator.LTE, JsBinaryOperator.SHL, JsBinaryOperator.SHR, JsBinaryOperator.SHRU -> replace(expression.arg1) + replace(expression.arg2) JsBinaryOperator.AND, JsBinaryOperator.OR -> { val right = replace(expression.arg2) if (right.isEmpty()) replace(expression.arg1) else listOf(expression) } JsBinaryOperator.INOP, JsBinaryOperator.INSTANCEOF -> listOf(expression) JsBinaryOperator.ASG, JsBinaryOperator.ASG_ADD, JsBinaryOperator.ASG_SUB, JsBinaryOperator.ASG_MUL, JsBinaryOperator.ASG_DIV, JsBinaryOperator.ASG_MOD, JsBinaryOperator.ASG_BIT_AND, JsBinaryOperator.ASG_BIT_OR, JsBinaryOperator.ASG_BIT_XOR, JsBinaryOperator.ASG_SHL, JsBinaryOperator.ASG_SHR, JsBinaryOperator.ASG_SHRU, JsBinaryOperator.ASG_CONCAT, JsBinaryOperator.PHP_STRING_CONCAT -> listOf(expression) } } is JsInvocation -> { if (expression.sideEffects != SideEffectKind.AFFECTS_STATE) { replace(expression.qualifier) + replaceMany(expression.arguments) } else { listOf(expression) } } is JsNew -> { if (expression.sideEffects != SideEffectKind.AFFECTS_STATE) { replace(expression.constructorExpression) + replaceMany(expression.arguments) } else { listOf(expression) } } is JsConditional -> { val thenExpr = replace(expression.thenExpression) val elseExpr = replace(expression.elseExpression) // TODO: consider case like this one: cond ? se() + 1 : se() + 2 when { thenExpr.isEmpty() && elseExpr.isEmpty() -> replace(expression.testExpression) thenExpr.isEmpty() -> listOf(JsAstUtils.or(expression.testExpression, expression.elseExpression)) elseExpr.isEmpty() -> listOf(JsAstUtils.and(expression.testExpression, expression.thenExpression)) else -> listOf(expression) } } // Although it can be suspicious case, sometimes it really helps. // Consider the following case: `Kotlin.modules['foo'].bar()`, where `bar` is inlineable. Expression decomposer produces // var $tmp = Kotlin.modules['foo']; // $tmp.bar(); // Then, inlined body of `bar` never uses `$tmp`, therefore we can eliminate it, so `Kotlin.modules['foo']` remains. // It's good to eliminate such useless expression. is JsArrayAccess -> { if (expression.sideEffects != SideEffectKind.AFFECTS_STATE) { replace(expression.arrayExpression) + replace(expression.indexExpression) } else { listOf(expression) } } is JsLiteral.JsValueLiteral -> listOf() is JsArrayLiteral -> replaceMany(expression.expressions) is JsObjectLiteral -> expression.propertyInitializers.flatMap { replace(it.labelExpr) + replace(it.valueExpr) } is JsFunction -> if (expression.name == null) listOf() else listOf(expression) else -> listOf(expression) } } private fun replaceMany(expressions: List<JsExpression>) = expressions.flatMap { replace(it) } }
apache-2.0
55610abc846668a52bfb16aa7010a72e
40.527094
132
0.5414
5.219814
false
false
false
false
akvo/akvo-flow-mobile
app/src/main/java/org/akvo/flow/presentation/form/view/groups/QuestionGroupFragment.kt
1
3255
/* * 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.presentation.form.view.groups import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import org.akvo.flow.R import org.akvo.flow.presentation.form.view.groups.entity.ViewQuestionAnswer class QuestionGroupFragment : Fragment() { private lateinit var questionGroupTitle: String private lateinit var questionAnswers: ArrayList<ViewQuestionAnswer> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) questionGroupTitle = arguments!!.getString(QUESTION_GROUP_TITLE, "") questionAnswers = arguments!!.getParcelableArrayList(QUESTION_ANSWERS)?: arrayListOf() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.question_group_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.findViewById<RecyclerView>(R.id.questionsRv).apply { layoutManager = LinearLayoutManager(activity) recycledViewPool.setMaxRecycledViews( GroupQuestionsAdapter.ViewType.OPTION.ordinal, 0 ) recycledViewPool.setMaxRecycledViews( GroupQuestionsAdapter.ViewType.BARCODE.ordinal, 0 ) recycledViewPool.setMaxRecycledViews( GroupQuestionsAdapter.ViewType.CASCADE.ordinal, 0 ) adapter = GroupQuestionsAdapter<QuestionViewHolder<ViewQuestionAnswer>>(questionAnswers) } } companion object { private const val QUESTION_GROUP_TITLE = "group_title" private const val QUESTION_ANSWERS = "answers" @JvmStatic fun newInstance( questionGroupTitle: String, questionAnswers: ArrayList<ViewQuestionAnswer> ): QuestionGroupFragment { return QuestionGroupFragment().apply { arguments = Bundle().apply { putString(QUESTION_GROUP_TITLE, questionGroupTitle) putParcelableArrayList(QUESTION_ANSWERS, questionAnswers) } } } } }
gpl-3.0
6aec17bbda2f00b774ac72a582c9f552
35.988636
100
0.688172
5.015408
false
false
false
false
recurly/recurly-client-android
AndroidSdk/src/main/java/com/recurly/androidsdk/presentation/view/RecurlyUnifiedCreditCard.kt
1
20358
package com.recurly.androidsdk.presentation.view import android.content.Context import android.content.res.ColorStateList import android.graphics.Typeface import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import com.recurly.androidsdk.R import com.recurly.androidsdk.databinding.RecurlyUnifiedCreditCardBinding import android.text.InputFilter import android.text.InputFilter.LengthFilter import com.recurly.androidsdk.data.model.CreditCardData import com.recurly.androidsdk.data.model.CreditCardsParameters import com.recurly.androidsdk.domain.RecurlyDataFormatter import com.recurly.androidsdk.domain.RecurlyInputValidator class RecurlyUnifiedCreditCard @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private var textColor: Int private var errorTextColor: Int private var hintColor: Int private var boxColor: Int private var errorBoxColor: Int private var focusedBoxColor: Int private var cardType: String = "" private var correctCardInput = true private var correctExpirationInput = true private var correctCVVInput = true private var maxCVVLength: Int = 3 private var previousDateValue = "" private var binding: RecurlyUnifiedCreditCardBinding = RecurlyUnifiedCreditCardBinding.inflate(LayoutInflater.from(context), this) /** * All the color are initialized as Int, this is to make ir easier to handle the texts colors change */ init { layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) textColor = ContextCompat.getColor(context, R.color.recurly_black) errorTextColor = ContextCompat.getColor(context, R.color.recurly_error_red) boxColor = ContextCompat.getColor(context, R.color.recurly_gray_stroke) errorBoxColor = ContextCompat.getColor(context, R.color.recurly_error_red_blur) focusedBoxColor = ContextCompat.getColor(context, R.color.recurly_focused_blue) hintColor = ContextCompat.getColor(context, R.color.recurly_gray_stroke) cardNumberInputValidator() monthAndYearInputValidator() cvvInputValidator() } /** * This fun changes the placeholders texts according to the parameters received * @param creditCardNumber Placeholder text for Credit Card Number field * @param monthAndYear Placeholder text for MM/YY field * @param cvv Placeholder text for CVV field */ fun setPlaceholders(creditCardNumber: String, monthAndYear: String, cvv: String) { if (creditCardNumber.trim().isNotEmpty()) binding.recurlyTextEditCardNumber.hint = creditCardNumber if (monthAndYear.trim().isNotEmpty()) binding.recurlyTextEditCardExpiration.hint = creditCardNumber if (cvv.trim().isNotEmpty()) binding.recurlyTextEditCardCvv.hint = creditCardNumber } /** * This fun changes the placeholder color according to the parameter received * @param color you should sent the color like ContextCompat.getColor(context, R.color.your-color) */ fun setPlaceholderColor(color: Int) { if (RecurlyInputValidator.validateColor(color)) { hintColor = color val colorState: ColorStateList = RecurlyInputValidator.getColorState(color) binding.recurlyTextInputCardNumber.placeholderTextColor = colorState binding.recurlyTextInputCardExpiration.placeholderTextColor = colorState binding.recurlyTextInputCardCvv.placeholderTextColor = colorState } } /** * This fun changes the text color according to the parameter received * @param color you should sent the color like ContextCompat.getColor(context, R.color.your-color) */ fun setTextColor(color: Int) { if (RecurlyInputValidator.validateColor(color)) { textColor = color binding.recurlyTextEditCardNumber.setTextColor(color) binding.recurlyTextEditCardExpiration.setTextColor(color) binding.recurlyTextEditCardCvv.setTextColor(color) } } /** * This fun changes the error text color according to the parameter received * @param color you should sent the color like ContextCompat.getColor(context, R.color.your-color) */ fun setTextErrorColor(color: Int) { if (RecurlyInputValidator.validateColor(color)) errorTextColor = color } /** * This fun changes the font of the input fields according to the parameter received * @param newFont non null Typeface * @param style style as int */ fun setFont(newFont: Typeface, style: Int) { binding.recurlyTextEditCardExpiration.setTypeface(newFont, style) binding.recurlyTextEditCardNumber.setTypeface(newFont, style) binding.recurlyTextEditCardCvv.setTypeface(newFont, style) binding.recurlyTextInputCardCvv.typeface = newFont binding.recurlyTextInputCardNumber.typeface = newFont binding.recurlyTextInputCardExpiration.typeface = newFont } /** * This fun validates if all the input are complete and are valid, this means it follows a credit card * patter and respect the min and max digits value, it follows a MM/YY * valid date pattern, and it follows a cvv code digits length, if there are any errors the fields * will be highlighted red * @return Triple<Boolean = number validation,Boolean = expiration validation,Boolean = cvv validation>true if the inputs are correctly filled, false if they are not */ fun validateData(): Triple<Boolean, Boolean, Boolean> { correctCardInput = RecurlyInputValidator.verifyCardNumber( binding.recurlyTextEditCardNumber.text.toString(), cardType ) correctExpirationInput = RecurlyInputValidator.verifyDate(binding.recurlyTextEditCardExpiration.text.toString()) correctCVVInput = RecurlyInputValidator.verifyCVV( binding.recurlyTextEditCardCvv.text.toString(), cardType ) validateAndChangeColors(false) return Triple(correctCardInput, correctExpirationInput, correctCVVInput) } /** * This fun will highlight the Credit Card Number as it have an error, you can use this * for tokenization validations or if you need to highlight this field with an error */ fun setCreditCardNumberError() { correctCardInput = false validateAndChangeColors(false) } /** * This fun will highlight the CVV as it have an error, you can use this * for tokenization validations or if you need to highlight this field with an error */ fun setCvvError() { correctCVVInput = false validateAndChangeColors(false) } /** * This fun will highlight the Expiration Date MM/YY as it have an error, you can use this * for tokenization validations or if you need to highlight this field with an error */ fun setExpirationError() { correctExpirationInput = false validateAndChangeColors(false) } /** *This is an internal fun that validates the input as it is introduced for credit car number field, * it is separated in two parts: * If it is focused or not, and if it has text changes. * * When it has text changes calls to different input validators from RecurlyInputValidator * and according to the response of the input validator it replaces the text and * changes text color according if has errors or not * * When it changes the focus of the view it validates if the field is correctly filled, and then * saves the input data */ private fun cardNumberInputValidator() { binding.recurlyTextEditCardNumber.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { if (s != null) { if (s.toString().isNotEmpty()) { val oldValue = s.toString() val data = RecurlyInputValidator.validateCreditCardNumber( s.toString().replace(" ", "") ) correctCardInput = data.first cardType = data.second // We validate if the return info is not empty and if it is different from what // we send to the input validator so this way we make secure if the text is // a valid and has changed if (oldValue != data.third) { binding.recurlyTextEditCardNumber.removeTextChangedListener(this) s.replace(0, oldValue.length, data.third) binding.recurlyTextEditCardNumber.addTextChangedListener(this) if (cardType.isNotEmpty()) maxCVVLength = CreditCardsParameters.valueOf(cardType.uppercase()).cvvLength } CreditCardData.setCardNumber( RecurlyDataFormatter.getCardNumber( s.toString(), correctCardInput ) ) validateAndChangeColors(true) } else { cardType = "" maxCVVLength = 3 correctCardInput = true } changeCardIcon() } } }) binding.recurlyTextEditCardNumber.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) {//We only save the value of the field if it is valid and complete correctCardInput = RecurlyInputValidator.verifyCardNumber( binding.recurlyTextEditCardNumber.text.toString(), cardType ) || binding.recurlyTextEditCardNumber.text.toString().isEmpty() CreditCardData.setCardNumber( RecurlyDataFormatter.getCardNumber( binding.recurlyTextEditCardNumber.text.toString(), correctCardInput ) ) } validateAndChangeColors(hasFocus) } } /** * This is an internal fun that validates the input as it is introduced for the expiration date field, * it is separated in two parts: * If it is focused or not, and if it has text changes. * * When it has text changes calls to different input validators from RecurlyInputValidator * and according to the response of the input validator it replaces the text and * changes text color according if has errors or not * * When it changes the focus of the view it validates if the field is correctly filled, and then * saves the input data */ private fun monthAndYearInputValidator() { binding.recurlyTextEditCardExpiration.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { // we save the previous input to validate if it has changed and if it is correct if (s != null) previousDateValue = s.toString() } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { if (s != null) { val oldValue = s.toString() val data = RecurlyInputValidator.validateExpirationDate( RecurlyInputValidator.regexSpecialCharacters( s.toString(), "0-9/" ), previousDateValue ) binding.recurlyTextEditCardExpiration.removeTextChangedListener(this) s.replace(0, oldValue.length, data.second) binding.recurlyTextEditCardExpiration.addTextChangedListener(this) CreditCardData.setExpirationMonth( RecurlyDataFormatter.getExpirationMonth( s.toString(), data.first ) ) CreditCardData.setExpirationYear( RecurlyDataFormatter.getExpirationYear( s.toString(), data.first ) ) correctExpirationInput = data.first || s.toString().isEmpty() validateAndChangeColors(true) } } }) binding.recurlyTextEditCardExpiration.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) { // We save the data from month and year separately correctExpirationInput = RecurlyInputValidator.verifyDate( binding.recurlyTextEditCardExpiration.text.toString() ) || binding.recurlyTextEditCardExpiration.text.toString().isEmpty() CreditCardData.setExpirationMonth( RecurlyDataFormatter.getExpirationMonth( binding.recurlyTextEditCardExpiration.text.toString(), correctExpirationInput ) ) CreditCardData.setExpirationYear( RecurlyDataFormatter.getExpirationYear( binding.recurlyTextEditCardExpiration.text.toString(), correctExpirationInput ) ) } validateAndChangeColors(hasFocus) } } /** * This is an internal fun that validates the input as it is introduced in CVV code field, * it is separated in two parts: * If it is focused or not, and if it has text changes. * * When it has text changes calls to different input validators from RecurlyInputValidator * and according to the response of the input validator it replaces the text and * changes text color according if has errors or not * * When it changes the focus of the view it validates if the field is correctly filled, and then * saves the input data */ private fun cvvInputValidator() { binding.recurlyTextEditCardCvv.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { //According to the card type we change the max length of the cvv code if (cardType.isEmpty()) binding.recurlyTextEditCardCvv.filters = arrayOf<InputFilter>(LengthFilter(maxCVVLength)) else binding.recurlyTextEditCardCvv.filters = arrayOf<InputFilter>( LengthFilter( CreditCardsParameters.valueOf(cardType.uppercase()).cvvLength ) ) } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { if (s != null) { val oldValue = s.toString() correctCVVInput = true val formattedCVV = RecurlyInputValidator.regexSpecialCharacters( s.toString(), "0-9" ) binding.recurlyTextEditCardCvv.removeTextChangedListener(this) s.replace(0, oldValue.length, formattedCVV) binding.recurlyTextEditCardCvv.addTextChangedListener(this) validateAndChangeColors(true) correctCVVInput = formattedCVV.length == maxCVVLength || formattedCVV.isEmpty() CreditCardData.setCvvCode( RecurlyDataFormatter.getCvvCode( formattedCVV, correctCVVInput ) ) } } }) binding.recurlyTextEditCardCvv.setOnFocusChangeListener { v, hasFocus -> //Changes the cvv icon according to the card type if (hasFocus) { if (cardType == CreditCardsParameters.AMERICAN_EXPRESS.cardType) binding.recurlyImageUnifiedCardIcon.setImageDrawable( ContextCompat.getDrawable(context, R.drawable.ic_amex_cvv) ) else binding.recurlyImageUnifiedCardIcon.setImageDrawable( ContextCompat.getDrawable(context, R.drawable.ic_generic_cvv) ) } else { correctCVVInput = RecurlyInputValidator.verifyCVV( binding.recurlyTextEditCardCvv.text.toString(), cardType ) || binding.recurlyTextEditCardCvv.text.toString().isEmpty() CreditCardData.setCvvCode( RecurlyDataFormatter.getCvvCode( binding.recurlyTextEditCardCvv.text.toString(), correctCVVInput ) ) changeCardIcon() } validateAndChangeColors(hasFocus) } } /** * This fun changes the colors of the text input field or the background according to if there * are some kind of error or not */ private fun validateAndChangeColors(focused: Boolean) { if (!correctCardInput || !correctExpirationInput || !correctCVVInput) { binding.recurlyImageViewStrokeBackground.setImageDrawable( ContextCompat.getDrawable(context, R.drawable.unified_stroke_error) ) } else if (focused) { binding.recurlyImageViewStrokeBackground.setImageDrawable( ContextCompat.getDrawable(context, R.drawable.unified_stroke_focused) ) } else { binding.recurlyImageViewStrokeBackground.setImageDrawable( ContextCompat.getDrawable(context, R.drawable.unified_stroke_container) ) } if (correctCardInput) binding.recurlyTextEditCardNumber.setTextColor(textColor) else binding.recurlyTextEditCardNumber.setTextColor(errorTextColor) if (correctExpirationInput) binding.recurlyTextEditCardExpiration.setTextColor(textColor) else binding.recurlyTextEditCardExpiration.setTextColor(errorTextColor) if (correctCVVInput) binding.recurlyTextEditCardCvv.setTextColor(textColor) else binding.recurlyTextEditCardCvv.setTextColor(errorTextColor) } /** * This fun get as a parameter the card type from CreditCardData to change the credit card icon */ private fun changeCardIcon() { binding.recurlyImageUnifiedCardIcon.setImageDrawable( RecurlyDataFormatter.changeCardIcon(context, cardType) ) } }
mit
2bd6781e6e80ab754df5608597872143
42.551422
169
0.603645
5.681831
false
false
false
false
songzhw/Hello-kotlin
Advanced_hm/src/main/kotlin/ca/six/kjdemo/rxjava/GetImage_concat.kt
1
777
package ca.six.kjdemo.rxjava import io.reactivex.Observable import io.reactivex.schedulers.Schedulers var isMemoryCached = true; var isDiskCached = false; var isNetworkCached = false; var memoryCache = Observable.create<String> { if (isMemoryCached) { // if(memoryCache.isNotEmpty()) it.onNext("cache from memory") } else { it.onComplete() } } var diskCache = Observable.create<String> { if (isDiskCached) { it.onNext("cache from disk") } else { it.onComplete() } } var networkCache = Observable.just("Get data from server") fun getImage() { Observable.concat(memoryCache, diskCache, networkCache) .subscribe { it -> println("szw get value : $it") } } fun main() { getImage() }
apache-2.0
3905a6985e3c428161dd567046fbf879
19.473684
59
0.646075
3.790244
false
false
false
false
skyfe79/AndroidKommon
androidkommon/src/main/java/commons/Handler.kt
1
1088
package commons /** * Created by burt on 2016. 6. 9.. */ import android.os.Handler import android.os.Message fun Handler.post(action: () -> Unit): Boolean = post(Runnable(action)) fun Handler.postAtFrontOfQueue(action: () -> Unit): Boolean = postAtFrontOfQueue(Runnable(action)) fun Handler.postAtTime(timeAtMillis: Long, action: () -> Unit): Boolean = postAtTime(Runnable(action), timeAtMillis) fun Handler.postDelayed(delayTimeMillis: Long, action: () -> Unit): Boolean = postDelayed(Runnable(action), delayTimeMillis) fun handler(handleMessage: (Message) -> Boolean): Handler { return Handler { msg -> handleMessage(msg) } } /*************************************************************************************************** fun ex() { val h = handler { msg -> "do something"; true } h.post { println("Hello") } h.postAtFrontOfQueue { } h.postAtTime(1000L, { }) h.postAtTime(1000L) { } h.postDelayed(1000L) { } } **************************************************************************************************/
mit
c424ad728b5b39d6874bdd1ce23c009f
24.928571
124
0.538603
4.300395
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/scheduler/LanternTaskExecutorService.kt
1
7325
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:Suppress("UNCHECKED_CAST") package org.lanternpowered.server.scheduler import org.spongepowered.api.scheduler.ScheduledTask import org.spongepowered.api.scheduler.ScheduledTaskFuture import org.spongepowered.api.scheduler.Task import org.spongepowered.api.scheduler.TaskExecutorService import org.spongepowered.api.scheduler.TaskFuture import java.time.temporal.TemporalUnit import java.util.concurrent.AbstractExecutorService import java.util.concurrent.Callable import java.util.concurrent.Delayed import java.util.concurrent.Future import java.util.concurrent.FutureTask import java.util.concurrent.TimeUnit internal class LanternTaskExecutorService( private val taskBuilderProvider: () -> Task.Builder, private val scheduler: LanternScheduler ) : AbstractExecutorService(), TaskExecutorService { override fun shutdown() { // Since this class is delegating its work to SchedulerService // and we have no way to stopping execution without keeping // track of all the submitted tasks, it makes sense that // this ExecutionService cannot be shut down. // While it is technically possible to cancel all tasks for // a plugin through the SchedulerService, we have no way to // ensure those tasks were created through this interface. } override fun shutdownNow(): List<Runnable> = emptyList() override fun isShutdown(): Boolean = false override fun isTerminated(): Boolean = false override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean = false override fun execute(command: Runnable) { this.scheduler.submit(createTask(command).build()) } override fun submit(command: Runnable): TaskFuture<*> = submit<Any?>(command, null) override fun <T> submit(command: Callable<T>): TaskFuture<T> { val runnable = FutureTask(command) val task = this.createTask(runnable).build() return LanternTaskFuture<T, Future<*>>(this.scheduler.submit(task), runnable) } override fun <T> submit(command: Runnable, result: T?): TaskFuture<T> { val runnable = FutureTask(command, result as T) val task = this.createTask(runnable).build() return LanternTaskFuture<T, Future<*>>(this.scheduler.submit(task), runnable) } private fun submitScheduledTask(task: Task): LanternScheduledTask { return this.scheduler.submit(task) { executor, scheduledTask, runnable -> val delay = scheduledTask.task.delayNanos val interval = scheduledTask.task.intervalNanos if (interval != 0L) { executor.scheduleAtFixedRate(runnable, delay, interval, TimeUnit.NANOSECONDS) } else { executor.schedule(runnable, delay, TimeUnit.NANOSECONDS) } } } override fun schedule(command: Runnable, delay: Long, unit: TemporalUnit): ScheduledTaskFuture<*> { val task = this.createTask(command).delay(delay, unit).build() return LanternScheduledTaskFuture<Any>(submitScheduledTask(task)) } override fun schedule(command: Runnable, delay: Long, unit: TimeUnit): ScheduledTaskFuture<*> { val task = this.createTask(command).delay(delay, unit).build() return LanternScheduledTaskFuture<Any>(submitScheduledTask(task)) } override fun <V> schedule(callable: Callable<V>, delay: Long, unit: TemporalUnit): ScheduledTaskFuture<V> { val runnable = FutureTask(callable) val task = this.createTask(runnable).delay(delay, unit).build() return LanternScheduledTaskFuture(submitScheduledTask(task), runnable) } override fun <V> schedule(callable: Callable<V>, delay: Long, unit: TimeUnit): ScheduledTaskFuture<V> { val runnable = FutureTask(callable) val task = this.createTask(runnable).delay(delay, unit).build() return LanternScheduledTaskFuture(submitScheduledTask(task), runnable) } override fun scheduleAtFixedRate(command: Runnable, initialDelay: Long, period: Long, unit: TemporalUnit): ScheduledTaskFuture<*> { val task = this.createTask(command).delay(initialDelay, unit).interval(period, unit).build() return LanternScheduledTaskFuture<Any>(submitScheduledTask(task)) } override fun scheduleAtFixedRate(command: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledTaskFuture<*> { val task = this.createTask(command).delay(initialDelay, unit).interval(period, unit).build() return LanternScheduledTaskFuture<Any>(submitScheduledTask(task)) } private fun submitTaskWithFixedDelay(task: Task): LanternScheduledTask { return this.scheduler.submit(task) { executor, scheduledTask, runnable -> val delay = scheduledTask.task.delayNanos val interval = scheduledTask.task.intervalNanos executor.scheduleWithFixedDelay(runnable, delay, interval, TimeUnit.NANOSECONDS) } } override fun scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TemporalUnit): ScheduledTaskFuture<*> { val task = this.createTask(command).delay(initialDelay, unit).interval(delay, unit).build() return LanternScheduledTaskFuture<Any>(submitTaskWithFixedDelay(task)) } override fun scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit): ScheduledTaskFuture<*> { val task = this.createTask(command).delay(initialDelay, unit).interval(delay, unit).build() return LanternScheduledTaskFuture<Any>(submitTaskWithFixedDelay(task)) } private fun createTask(command: Runnable): Task.Builder = this.taskBuilderProvider().execute(command) private open class LanternTaskFuture<V, F : Future<*>>( val task: LanternScheduledTask, val resultFuture: Future<V> ) : TaskFuture<V> { val future: F get() = this.resultFuture as F override fun getTask(): ScheduledTask = this.task override fun cancel(mayInterruptIfRunning: Boolean): Boolean = this.task.cancel(mayInterruptIfRunning) override fun isCancelled(): Boolean = this.future.isCancelled override fun isDone(): Boolean = this.future.isDone override fun get(): V = this.resultFuture.get() override fun get(timeout: Long, unit: TimeUnit): V = this.resultFuture.get(timeout, unit) } private class LanternScheduledTaskFuture<V> : LanternTaskFuture<V, ScheduledTaskFuture<*>>, ScheduledTaskFuture<V> { constructor(task: LanternScheduledTask, resultFuture: Future<V>) : super(task, resultFuture) constructor(task: LanternScheduledTask) : super(task, task.future as Future<V>) override fun isPeriodic(): Boolean = this.future.isPeriodic override fun getDelay(unit: TimeUnit): Long = this.future.getDelay(unit) override fun compareTo(other: Delayed): Int = this.future.compareTo(other) override fun run() = this.future.run() } }
mit
c37196feb649f1064f7605fe34b9d3e1
45.955128
137
0.711809
4.665605
false
false
false
false
Lumeer/engine
lumeer-core/src/main/kotlin/io/lumeer/core/task/executor/operation/stage/SendSmtpEmailsStage.kt
2
3597
package io.lumeer.core.task.executor.operation.stage import io.lumeer.api.model.FileAttachment import io.lumeer.core.task.executor.ChangesTracker import io.lumeer.core.task.executor.operation.OperationExecutor import io.lumeer.core.task.executor.operation.SendSmtpEmailOperation import io.lumeer.core.util.EmailPart import io.lumeer.core.util.EmailService import java.net.URLConnection /* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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/>. */ class SendSmtpEmailsStage(executor: OperationExecutor) : Stage(executor) { override fun call(): ChangesTracker { if (operations.isEmpty()) { return ChangesTracker() } val sendSmtpEmailRequests = operations.orEmpty().filter { operation -> operation is SendSmtpEmailOperation && operation.isComplete } .map { operation -> (operation as SendSmtpEmailOperation) } sendSmtpEmailRequests.forEach { req -> val emailService = EmailService.fromSmtpConfiguration(req.entity.smtpConfiguration) val emailAttachments = mutableListOf<EmailPart>() if (req.entity.document != null) { emailAttachments.addAll( task.fileAttachmentAdapter.getAllFileAttachments( task.daoContextSnapshot.organization, task.daoContextSnapshot.project, req.entity.document.collectionId, req.entity.document.id, req.entity.attributeId, FileAttachment.AttachmentType.DOCUMENT ).map { attachment -> val bytes = task.fileAttachmentAdapter.readFileAttachment(attachment) URLConnection.getFileNameMap() EmailPart(attachment.fileName, getMimeType(attachment.fileName), bytes) } ) } if (req.entity.link != null) { emailAttachments.addAll( task.fileAttachmentAdapter.getAllFileAttachments( task.daoContextSnapshot.organization, task.daoContextSnapshot.project, req.entity.link.linkTypeId, req.entity.link.id, req.entity.attributeId, FileAttachment.AttachmentType.LINK ).map { attachment -> val bytes = task.fileAttachmentAdapter.readFileAttachment(attachment) EmailPart(attachment.fileName, getMimeType(attachment.fileName), bytes) } ) } emailService.sendEmail(req.entity.subject, req.entity.email, req.entity.body, req.entity.fromName, emailAttachments) } return changesTracker } private fun getMimeType(fileName: String): String = URLConnection.guessContentTypeFromName(fileName) ?: "application/octet-stream" }
gpl-3.0
d6f45e1610de12a81f0f9cf7ff18acc3
42.349398
138
0.656936
4.802403
false
false
false
false
mediathekview/MediathekView
src/main/java/mediathek/gui/dialog/about/AboutDialog.kt
1
818
package mediathek.gui.dialog.about import javafx.embed.swing.JFXPanel import javafx.scene.Scene import mediathek.javafx.tool.JavaFxUtils import mediathek.tool.EscapeKeyHandler import java.awt.BorderLayout import java.awt.Frame import javax.swing.JDialog import javax.swing.SwingUtilities class AboutDialog(owner: Frame?) : JDialog(owner, "Über dieses Programm", true) { init { defaultCloseOperation = DISPOSE_ON_CLOSE isResizable = false EscapeKeyHandler.installHandler(this) { dispose() } contentPane.layout = BorderLayout() val fxPanel = JFXPanel() contentPane.add(fxPanel, BorderLayout.CENTER) JavaFxUtils.invokeInFxThreadAndWait { fxPanel.scene = Scene(AboutController()) SwingUtilities.invokeLater { pack() } } } }
gpl-3.0
63169414d20279556fb19022cfd9feb0
31.72
81
0.717258
4.392473
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/data/api/model/Forum.kt
1
2177
package me.ykrank.s1next.data.api.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.google.common.base.Objects import com.github.ykrank.androidtools.ui.adapter.StableIdModel import com.github.ykrank.androidtools.ui.adapter.model.DiffSameItem import org.apache.commons.lang3.StringEscapeUtils import paperparcel.PaperParcel import paperparcel.PaperParcelable @JsonIgnoreProperties(ignoreUnknown = true) @PaperParcel class Forum : PaperParcelable, DiffSameItem, StableIdModel { @JsonProperty("fid") var id: String? = null @JsonProperty("name") var name: String? = null set(value) { // unescape some basic XML entities field = StringEscapeUtils.unescapeXml(value) } @JsonProperty("threads") var threads: Int = 0 @JsonProperty("todayposts") var todayPosts: Int = 0 constructor() {} override val stableId: Long get() = id?.toLongOrNull() ?: 0 override fun equals(o: Any?): Boolean { if (this === o) return true if (o == null || javaClass != o.javaClass) return false val forum = o as Forum? return Objects.equal(threads, forum!!.threads) && Objects.equal(todayPosts, forum.todayPosts) && Objects.equal(id, forum.id) && Objects.equal(name, forum.name) } override fun hashCode(): Int { return Objects.hashCode(id, name, threads, todayPosts) } override fun isSameItem(o: Any?): Boolean { if (this === o) return true if (o == null || javaClass != o.javaClass) return false val forum = o as Forum? return Objects.equal(id, forum!!.id) && Objects.equal(name, forum.name) } override fun toString(): String { return "Forum{" + "id='" + id + '\''.toString() + ", name='" + name + '\''.toString() + ", threads=" + threads + ", todayPosts=" + todayPosts + '}'.toString() } companion object { @JvmField val CREATOR = PaperParcelForum.CREATOR } }
apache-2.0
532fc2d98674acc510256493a5e48929
28.821918
79
0.617363
4.354
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/constants.kt
1
414
package net.ndrei.teslapoweredthingies const val MOD_ID = "@MOD-ID@" const val MOD_NAME = "@MOD-NAME@" const val MOD_VERSION = "@MOD-VERSION@" const val MOD_MC_VERSION = "@MOD-MC-VERSION@" const val MOD_DEPENDENCIES = "required-after:forgelin@[@FORGELIN-VERSION@,);required-after:forge@[@FORGE-VERSION@,);required-after:teslacorelib@[@TESLA-CORE-LIB-VERSION@,);" const val MOD_SIGN_FINGERPRINT = "@FINGERPRINT@"
mit
8165961067838a43cc8b4e7f261ca97f
45
173
0.736715
3.209302
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/Request.kt
3
8988
/* * 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 okhttp3 import java.net.URL import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.internal.EMPTY_REQUEST import okhttp3.internal.http.HttpMethod import okhttp3.internal.toImmutableMap /** * An HTTP request. Instances of this class are immutable if their [body] is null or itself * immutable. */ class Request internal constructor( @get:JvmName("url") val url: HttpUrl, @get:JvmName("method") val method: String, @get:JvmName("headers") val headers: Headers, @get:JvmName("body") val body: RequestBody?, internal val tags: Map<Class<*>, Any> ) { private var lazyCacheControl: CacheControl? = null val isHttps: Boolean get() = url.isHttps fun header(name: String): String? = headers[name] fun headers(name: String): List<String> = headers.values(name) /** * Returns the tag attached with `Object.class` as a key, or null if no tag is attached with * that key. * * Prior to OkHttp 3.11, this method never returned null if no tag was attached. Instead it * returned either this request, or the request upon which this request was derived with * [newBuilder]. */ fun tag(): Any? = tag(Any::class.java) /** * Returns the tag attached with [type] as a key, or null if no tag is attached with that * key. */ fun <T> tag(type: Class<out T>): T? = type.cast(tags[type]) fun newBuilder(): Builder = Builder(this) /** * Returns the cache control directives for this response. This is never null, even if this * response contains no `Cache-Control` header. */ @get:JvmName("cacheControl") val cacheControl: CacheControl get() { var result = lazyCacheControl if (result == null) { result = CacheControl.parse(headers) lazyCacheControl = result } return result } @JvmName("-deprecated_url") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "url"), level = DeprecationLevel.ERROR) fun url(): HttpUrl = url @JvmName("-deprecated_method") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "method"), level = DeprecationLevel.ERROR) fun method(): String = method @JvmName("-deprecated_headers") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "headers"), level = DeprecationLevel.ERROR) fun headers(): Headers = headers @JvmName("-deprecated_body") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "body"), level = DeprecationLevel.ERROR) fun body(): RequestBody? = body @JvmName("-deprecated_cacheControl") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "cacheControl"), level = DeprecationLevel.ERROR) fun cacheControl(): CacheControl = cacheControl override fun toString() = buildString { append("Request{method=") append(method) append(", url=") append(url) if (headers.size != 0) { append(", headers=[") headers.forEachIndexed { index, (name, value) -> if (index > 0) { append(", ") } append(name) append(':') append(value) } append(']') } if (tags.isNotEmpty()) { append(", tags=") append(tags) } append('}') } open class Builder { internal var url: HttpUrl? = null internal var method: String internal var headers: Headers.Builder internal var body: RequestBody? = null /** A mutable map of tags, or an immutable empty map if we don't have any. */ internal var tags: MutableMap<Class<*>, Any> = mutableMapOf() constructor() { this.method = "GET" this.headers = Headers.Builder() } internal constructor(request: Request) { this.url = request.url this.method = request.method this.body = request.body this.tags = if (request.tags.isEmpty()) { mutableMapOf() } else { request.tags.toMutableMap() } this.headers = request.headers.newBuilder() } open fun url(url: HttpUrl): Builder = apply { this.url = url } /** * Sets the URL target of this request. * * @throws IllegalArgumentException if [url] is not a valid HTTP or HTTPS URL. Avoid this * exception by calling [HttpUrl.parse]; it returns null for invalid URLs. */ open fun url(url: String): Builder { // Silently replace web socket URLs with HTTP URLs. val finalUrl: String = when { url.startsWith("ws:", ignoreCase = true) -> { "http:${url.substring(3)}" } url.startsWith("wss:", ignoreCase = true) -> { "https:${url.substring(4)}" } else -> url } return url(finalUrl.toHttpUrl()) } /** * Sets the URL target of this request. * * @throws IllegalArgumentException if the scheme of [url] is not `http` or `https`. */ open fun url(url: URL) = url(url.toString().toHttpUrl()) /** * Sets the header named [name] to [value]. If this request already has any headers * with that name, they are all replaced. */ open fun header(name: String, value: String) = apply { headers[name] = value } /** * Adds a header with [name] and [value]. Prefer this method for multiply-valued * headers like "Cookie". * * Note that for some headers including `Content-Length` and `Content-Encoding`, * OkHttp may replace [value] with a header derived from the request body. */ open fun addHeader(name: String, value: String) = apply { headers.add(name, value) } /** Removes all headers named [name] on this builder. */ open fun removeHeader(name: String) = apply { headers.removeAll(name) } /** Removes all headers on this builder and adds [headers]. */ open fun headers(headers: Headers) = apply { this.headers = headers.newBuilder() } /** * Sets this request's `Cache-Control` header, replacing any cache control headers already * present. If [cacheControl] doesn't define any directives, this clears this request's * cache-control headers. */ open fun cacheControl(cacheControl: CacheControl): Builder { val value = cacheControl.toString() return when { value.isEmpty() -> removeHeader("Cache-Control") else -> header("Cache-Control", value) } } open fun get() = method("GET", null) open fun head() = method("HEAD", null) open fun post(body: RequestBody) = method("POST", body) @JvmOverloads open fun delete(body: RequestBody? = EMPTY_REQUEST) = method("DELETE", body) open fun put(body: RequestBody) = method("PUT", body) open fun patch(body: RequestBody) = method("PATCH", body) open fun method(method: String, body: RequestBody?): Builder = apply { require(method.isNotEmpty()) { "method.isEmpty() == true" } if (body == null) { require(!HttpMethod.requiresRequestBody(method)) { "method $method must have a request body." } } else { require(HttpMethod.permitsRequestBody(method)) { "method $method must not have a request body." } } this.method = method this.body = body } /** Attaches [tag] to the request using `Object.class` as a key. */ open fun tag(tag: Any?): Builder = tag(Any::class.java, tag) /** * Attaches [tag] to the request using [type] as a key. Tags can be read from a * request using [Request.tag]. Use null to remove any existing tag assigned for [type]. * * Use this API to attach timing, debugging, or other application data to a request so that * you may read it in interceptors, event listeners, or callbacks. */ open fun <T> tag(type: Class<in T>, tag: T?) = apply { if (tag == null) { tags.remove(type) } else { if (tags.isEmpty()) { tags = mutableMapOf() } tags[type] = type.cast(tag)!! // Force-unwrap due to lack of contracts on Class#cast() } } open fun build(): Request { return Request( checkNotNull(url) { "url == null" }, method, headers.build(), body, tags.toImmutableMap() ) } } }
apache-2.0
9392e307d47755c62244e289ff6b037f
29.262626
95
0.624388
4.205896
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/BaseFragment.kt
1
3791
package org.videolan.vlc.gui import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ActionMode import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlinx.coroutines.Job import kotlinx.coroutines.delay import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.resources.AndroidDevices import org.videolan.resources.TAG_ITEM import org.videolan.vlc.R import org.videolan.vlc.gui.view.SwipeRefreshLayout abstract class BaseFragment : Fragment(), ActionMode.Callback { var actionMode: ActionMode? = null var fabPlay: FloatingActionButton? = null lateinit var swipeRefreshLayout: SwipeRefreshLayout open val hasTabs = false private var refreshJob : Job? = null set(value) { field?.cancel() field = value } open val subTitle: String? get() = null val menu: Menu? get() = (activity as? AudioPlayerContainerActivity)?.menu abstract fun getTitle(): String open fun onFabPlayClick(view: View) {} override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(!AndroidDevices.isAndroidTv) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.findViewById<SwipeRefreshLayout>(R.id.swipeLayout)?.let { swipeRefreshLayout = it it.setColorSchemeResources(R.color.orange700) } if (hasFAB()) fabPlay = requireActivity().findViewById(R.id.fab) } override fun onStart() { super.onStart() updateActionBar() setFabPlayVisibility(hasFAB()) fabPlay?.setOnClickListener { v -> onFabPlayClick(v) } } override fun onStop() { super.onStop() setFabPlayVisibility(false) } fun startActionMode() { val activity = activity as AppCompatActivity? ?: return actionMode = activity.startSupportActionMode(this) setFabPlayVisibility(false) } private fun updateActionBar() { val activity = activity as? AppCompatActivity ?: return activity.supportActionBar?.let { if (requireActivity() !is ContentActivity || (requireActivity() as ContentActivity).displayTitle) requireActivity().title = getTitle() it.subtitle = subTitle activity.invalidateOptionsMenu() } if (activity is ContentActivity) activity.setTabLayoutVisibility(hasTabs) } protected open fun hasFAB() = ::swipeRefreshLayout.isInitialized open fun setFabPlayVisibility(enable: Boolean) { fabPlay?.run { if (enable) show() else hide() } } protected fun showInfoDialog(item: MediaLibraryItem) { val i = Intent(activity, InfoActivity::class.java) i.putExtra(TAG_ITEM, item) startActivity(i) } protected fun setRefreshing(refreshing: Boolean, action: ((loading: Boolean) -> Unit)? = null) { refreshJob = lifecycleScope.launchWhenStarted { if (refreshing) delay(300L) swipeRefreshLayout.isRefreshing = refreshing (activity as? MainActivity)?.refreshing = refreshing action?.invoke(refreshing) } } fun stopActionMode() { actionMode?.let { it.finish() setFabPlayVisibility(true) } } fun invalidateActionMode() { actionMode?.invalidate() } override fun onPrepareActionMode(mode: ActionMode, menu: Menu) = false }
gpl-2.0
2ecdfc4d0877eb2069b62f092f77ab14
31.135593
146
0.677394
5.001319
false
false
false
false
clangen/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/framework/MixinSet.kt
1
1894
package io.casey.musikcube.remote.framework import android.os.Bundle class MixinSet: MixinBase() { private val components: MutableMap<Class<out IMixin>, IMixin> = mutableMapOf() private var bundle = Bundle() fun <T> add(mixin: IMixin): T { components[mixin.javaClass] = mixin when (state) { State.Created -> mixin.onCreate(bundle) State.Started -> { mixin.onCreate(bundle) mixin.onStart() } State.Resumed -> { mixin.onCreate(bundle) mixin.onStart() mixin.onResume() } State.Paused -> { mixin.onCreate(bundle) mixin.onStart() } else -> { } } @Suppress("unchecked_cast") return mixin as T } @Suppress("unchecked_cast") fun <T: IMixin> get(cls: Class<out T>): T? = components[cls] as T? override fun onCreate(bundle: Bundle) { super.onCreate(bundle) this.bundle = bundle components.values.forEach { it.onCreate(bundle) } } override fun onStart() { super.onStart() components.values.forEach { it.onStart() } } override fun onResume() { super.onResume() components.values.forEach { it.onResume() } } override fun onPause() { super.onPause() components.values.forEach { it.onPause() } } override fun onStop() { super.onStop() components.values.forEach { it.onStop() } } override fun onSaveInstanceState(bundle: Bundle) { super.onSaveInstanceState(bundle) components.values.forEach { it.onSaveInstanceState(bundle) } } override fun onDestroy() { super.onDestroy() components.values.forEach { it.onDestroy() } } }
bsd-3-clause
6dfeb2713243cb741373f48e039c0961
24.608108
82
0.548574
4.541966
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/dmzz.kt
1
5193
package cc.aoeiuv020.panovel.api.site /** * TODO: 等网站恢复正常了再测试, * Created by AoEiuV020 on 2017.11.30-17:49:36. */ /* class Dmzz : JsoupNovelContext() { override val enabled: Boolean get() = false override val site = NovelSite( name = "动漫之家", baseUrl = "http://q.dmzj.com", logo = "http://m.dmzj.com/images/head_logo.gif" ) override fun connectByNovelName(name: String): Connection { val key = URLEncoder.encode(name, "UTF-8") return connect("http://s.acg.dmzj.com/lnovelsum/search.php?s=$key") } override fun searchNovelName(name: String): List<NovelItem> { val arr: List<DmzzNovelItem> = response(connect(absUrl(name)).ignoreContentType(true)).body().let { js -> val json = js.dropWhile { it != '[' } .dropLastWhile { it != ']' } Gson().fromJson(json, object : TypeToken<List<DmzzNovelItem>>() {}.type) } return arr.map { dmzz -> NovelItem(this, dmzz.fullName, dmzz.author, // 相对路径,"../"开头,jsoup没有自动处理这样的的, // TODO: URL有处理,待测试, dmzz.lnovelUrl.removePrefix("..")) } } data class DmzzNovelItem( @SerializedName("author") val author: String, //仁木英之 @SerializedName("image_url") val imageUrl: String, //http://xs.dmzj.com/img/webpic/11/0005O.jpg @SerializedName("full_name") val fullName: String, //仆仆仙人千岁少女 @SerializedName("lnovel_name") val lnovelName: String, //仆仆仙人千岁少女 @SerializedName("fullc_name") val fullcName: String, //第一卷 @SerializedName("last_chapter_name") val lastChapterName: String, //第一卷 @SerializedName("lnovel_url") val lnovelUrl: String, //../4/index.shtml @SerializedName("last_chapter_url") val lastChapterUrl: String, ///../4/28/141.shtml @SerializedName("m_image_url") val mImageUrl: String, //http://xs.dmzj.com/img/webpic/4/pupuxianrenqiansuishaonv.jpg @SerializedName("m_intro") val mIntro: String?, //  一日,神仙降临在我眼前。却是个辛辣又大胆的千岁……美少女?! ... @SerializedName("description") val description: String?, @SerializedName("status") val status: String //[<span class="red1_font12">完</span>] ) override fun check(url: String): Boolean { return super.check(url) || URL(url).host == "s.acg.dmzj.com" } override val detailPageTemplate: String get() = "/%s/index.shtml" @SuppressWarnings("SimpleDateFormat") override fun getNovelDetail(root: Document): NovelDetail { val con = root.requireElement(query = "body > div.main > div > div.pic > div ") val img = root.requireElement(query = "#cover_pic", name = TAG_IMAGE) { it.src() } val name = con.requireElement(query = "> h3", name = TAG_NOVEL_NAME) { it.text() } val (author) = con.requireElement(query = "> p:nth-child(2)", name = TAG_AUTHOR_NAME) { it.text().pick("作者:(\\S*)") } val update = con.getElement(query = "> p:nth-child(5)") { val (updateString) = it.text().pick("更新:(.*)") val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") sdf.parse(updateString) } val intro = "" val bookId = findBookId(root.location()) return NovelDetail(NovelItem(this, name, author, bookId), img, update, intro, bookId) } override fun getNovelChaptersAsc(root: Document): List<NovelChapter> { val regex = Regex(".*chapter_list\\[\\d*\\]\\[\\d*\\] = '<a href=\"([^\"]*)\".*>(.*)</a>'.*;.*") return root.requireElement(query = "#list_block > script", name = TAG_CHAPTER_LINK) { it.html().lines().filter { it.matches(regex) }.map { val (url, name) = it.pick(regex.toPattern()) NovelChapter(name, url) } } } override fun getNovelText(root: Document): List<String> { val textListSplitWhitespace = root.requireElement(query = "head > script:nth-child(10)", name = TAG_CONTENT) { val (json) = it.html().pick("var g_chapter_pages_url = (\\[.*\\]);") val urlList: List<String> = Gson().fromJson(json, object : TypeToken<List<String>>() {}.type) urlList.map { val url = if (it.isEmpty()) { root.location() } else { absUrl(it) } parse(url).requireElements(query = "p") .dropLastWhile { it.className() == "zlist" } .flatMap { // 有的只有一个p, // http://q.dmzj.com/2013/7335/54663.shtml it.textListSplitWhitespace() } }.reduce { acc, list -> acc + list } } return textListSplitWhitespace } } */
gpl-3.0
73171052823350e52ca082f1da7daffd
42.517544
128
0.54868
3.629115
false
false
false
false
dafi/photoshelf
core/src/main/java/com/ternaryop/photoshelf/fragment/BottomMenuSheetDialogFragment.kt
1
2501
package com.ternaryop.photoshelf.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.TextView import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.google.android.material.navigation.NavigationView import com.ternaryop.photoshelf.core.R interface BottomMenuListener { val title: String? val menuId: Int fun setupMenu(menu: Menu, sheet: BottomSheetDialogFragment) fun onItemSelected(item: MenuItem, sheet: BottomSheetDialogFragment) } class BottomMenuSheetDialogFragment : BottomSheetDialogFragment() { var menuListener: BottomMenuListener? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater .inflate(R.layout.fragment_bottom_menu, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) menuListener?.also { listener -> setupTitle(view, listener) setupSubtitle(view) setupNavigationView(view, listener) } } private fun setupTitle( view: View, listener: BottomMenuListener ) { val title = view.findViewById<TextView>(R.id.title) title.text = listener.title ?: arguments?.getString(ARG_TITLE) ?: "" } private fun setupSubtitle(view: View) { val subtitle = arguments?.getString(ARG_SUBTITLE) val subtitleView = view.findViewById<TextView>(R.id.subtitle) if (subtitle == null) { subtitleView.visibility = View.GONE } else { subtitleView.visibility = View.VISIBLE subtitleView.text = subtitle } } private fun setupNavigationView( view: View, listener: BottomMenuListener ) { val navigationView = view.findViewById<NavigationView>(R.id.navigation_view) navigationView.inflateMenu(listener.menuId) listener.setupMenu(navigationView.menu, this) navigationView.setNavigationItemSelectedListener { menu -> listener.onItemSelected(menu, this) dismiss() true } } companion object { const val ARG_TITLE = "bottom.menu.sheet.title" const val ARG_SUBTITLE = "bottom.menu.sheet.subtitle" } }
mit
a7f676cc96efb76b6e09c22b341436ba
31.907895
116
0.687325
4.818882
false
false
false
false
free5ty1e/primestationone-control-android
app/src/main/java/com/chrisprime/primestationonecontrol/utilities/FileUtilities.kt
1
4627
package com.chrisprime.primestationonecontrol.utilities import android.content.Context import com.chrisprime.primestationonecontrol.PrimeStationOneControlApplication import com.chrisprime.primestationonecontrol.events.PrimeStationsListUpdatedEvent import com.chrisprime.primestationonecontrol.model.PrimeStationOne import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.io.File import java.io.FileInputStream import java.io.FileWriter import java.io.IOException import java.lang.reflect.Type import java.util.ArrayList import timber.log.Timber /** * Created by cpaian on 7/23/15. */ object FileUtilities { fun getPrimeStationStorageFolder(context: Context, ip: String?): File { var ipNonNull = ip if (ip == null) { ipNonNull = "" } val folder = File(context.filesDir.toString() + File.separator + PrimeStationOne.PRIMESTATION_DATA_STORAGE_PREFIX + ipNonNull) //Also, create this particular folder location in case it does not yet exist! //noinspection ResultOfMethodCallIgnored folder.mkdirs() return folder } fun createAndSaveFile(context: Context, filename: String, json: String) { try { Timber.d(".createAndSaveFile($filename)") val file = File(getPrimeStationStorageFolder(context, null), filename) val fileWriter = FileWriter(file) fileWriter.write(json) fileWriter.flush() fileWriter.close() } catch (e: IOException) { Timber.e(e, ".createAndSaveFile($filename) failure: $e") } } fun readJsonData(file: File): String { var json = "" try { val `is` = FileInputStream(file) val size = `is`.available() val buffer = ByteArray(size) `is`.read(buffer) `is`.close() json = String(buffer) } catch (e: IOException) { Timber.w(e, ".readJsonData() failure: " + e) } return json } fun readJsonPrimestationList(context: Context): List<PrimeStationOne>? { val json = readJsonData(File(getPrimeStationStorageFolder(context, null), PrimeStationOne.FOUND_PRIMESTATIONS_JSON_FILENAME)) Timber.d("Read found primestations from JSON file:\n" + json) val listType = object : TypeToken<ArrayList<PrimeStationOne>>() { }.type return Gson().fromJson<List<PrimeStationOne>>(json, listType) } fun readJsonCurrentPrimestation(context: Context): PrimeStationOne? { val json = readJsonData(File(getPrimeStationStorageFolder(context, null), PrimeStationOne.CURRENT_PRIMESTATION_JSON_FILENAME)) Timber.d("Read current primestation from JSON file:\n" + json) return Gson().fromJson(json, PrimeStationOne::class.java) } fun storeFoundPrimeStationsJson(context: Context, primeStationOneList: List<PrimeStationOne>) { //Store found primestations as JSON file val jsonString = Gson().toJson(primeStationOneList) Timber.d("bundled found primestations into JSON string:\n" + jsonString) createAndSaveFile(context, PrimeStationOne.FOUND_PRIMESTATIONS_JSON_FILENAME, jsonString) PrimeStationOneControlApplication.eventBus.post(PrimeStationsListUpdatedEvent()) } fun storeCurrentPrimeStationToJson(context: Context, primeStationOne: PrimeStationOne) { //Store current primestation as JSON file val jsonString = Gson().toJson(primeStationOne) Timber.d("bundled current primestation into JSON string:\n" + jsonString) createAndSaveFile(context, PrimeStationOne.CURRENT_PRIMESTATION_JSON_FILENAME, jsonString) //ALSO find current primestation in json list of found primestations, and update its info in case user switches to another primestation val primeStationOneList: MutableList<PrimeStationOne>? = readJsonPrimestationList(context)?.toMutableList() if (primeStationOneList == null) { Timber.w(".storeCurrentPrimeStationToJson(): PrimeStationOne List is null, cannot proceed!") } else { if (primeStationOneList.size > 0) { for (i in 0..primeStationOneList.size - 1) { var ps1 = primeStationOneList[i] if (primeStationOne.ipAddress == ps1.ipAddress) { primeStationOneList[i] = primeStationOne } } } storeFoundPrimeStationsJson(context, primeStationOneList) } } }
mit
859b6347c8795af7ab979cdc3c342f9a
38.547009
143
0.66609
4.683198
false
false
false
false
googlecodelabs/kotlin-coroutines
coroutines-codelab/start/src/test/java/com/example/android/kotlincoroutines/main/utils/LiveDataTestExtensions.kt
2
1920
/* * Copyright (C) 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 * * 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.android.kotlincoroutines.main.utils import androidx.lifecycle.LiveData import androidx.lifecycle.Observer /** * Represents a list of capture values from a LiveData. */ class LiveDataValueCapture<T> { val lock = Any() private val _values = mutableListOf<T?>() val values: List<T?> get() = synchronized(lock) { _values.toList() // copy to avoid returning reference to mutable list } fun addValue(value: T?) = synchronized(lock) { _values += value } } /** * Extension function to capture all values that are emitted to a LiveData<T> during the execution of * `captureBlock`. * * @param captureBlock a lambda that will */ inline fun <T> LiveData<T>.captureValues(block: LiveDataValueCapture<T>.() -> Unit) { val capture = LiveDataValueCapture<T>() val observer = Observer<T> { capture.addValue(it) } observeForever(observer) try { capture.block() } finally { removeObserver(observer) } } /** * Get the current value from a LiveData without needing to register an observer. */ fun <T> LiveData<T>.getValueForTest(): T? { var value: T? = null var observer = Observer<T> { value = it } observeForever(observer) removeObserver(observer) return value }
apache-2.0
00be347ed0b8b472d85c86592878fa72
26.428571
101
0.677083
4.067797
false
false
false
false
edvin/tornadofx-samples
workspace/src/main/kotlin/no/tornado/fxsample/workspace/controller.kt
1
917
package no.tornado.fxsample.workspace import tornadofx.* import java.io.File import java.nio.charset.Charset /** * Created by miguelius on 04/09/2017. */ class EditorController : Controller() { /** * random quotes from resource quotes.txt */ private val quotes = File(javaClass.getResource("quotes.txt").toURI()).readLines(Charset.forName("UTF-8")) /** * the list of open text editors */ val editorModelList = mutableListOf<TextEditorFragment>().asObservable() fun newEditor(): TextEditorFragment { val newFile = DocumentViewModel() newFile.title.value = "New file ${editorModelList.size}" newFile.commit() val editor = TextEditorFragment(newFile) editorModelList.add(editor) return editor } /** * provides a random quote */ fun quote(): String = quotes[(Math.random() * quotes.size).toInt()] }
apache-2.0
657a8be2cc7239e0ca058ede8807228c
22.512821
110
0.651036
4.325472
false
false
false
false
Orchextra/orchextra-android-sdk
core/src/main/java/com/gigigo/orchextra/core/domain/interactor/UpdateDevice.kt
1
2709
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.core.domain.interactor import com.gigigo.orchextra.core.domain.datasources.DbDataSource import com.gigigo.orchextra.core.domain.datasources.NetworkDataSource import com.gigigo.orchextra.core.domain.entities.EMPTY_CRM import com.gigigo.orchextra.core.domain.entities.OxDevice import com.gigigo.orchextra.core.domain.entities.TokenData import com.gigigo.orchextra.core.domain.exceptions.NetworkException import com.gigigo.orchextra.core.domain.exceptions.OxException import com.gigigo.orchextra.core.domain.executor.PostExecutionThread import com.gigigo.orchextra.core.domain.executor.PostExecutionThreadImp import com.gigigo.orchextra.core.domain.executor.ThreadExecutor import com.gigigo.orchextra.core.domain.executor.ThreadExecutorImp class UpdateDevice(threadExecutor: ThreadExecutor, postExecutionThread: PostExecutionThread, private val networkDataSource: NetworkDataSource, private val dbDataSource: DbDataSource) : Interactor<OxDevice>(threadExecutor, postExecutionThread) { private var tags: List<String>? = null private var businessUnits: List<String>? = null fun update(tags: List<String>? = null, businessUnits: List<String>? = null, onSuccess: (OxDevice) -> Unit = onSuccessStub, onError: (OxException) -> Unit = onErrorStub) { this.tags = tags this.businessUnits = businessUnits executeInteractor(onSuccess, onError) } override fun run() = try { val currentDevice = dbDataSource.getDevice().copy(tags = tags, businessUnits = businessUnits) val updatedDevice = networkDataSource.updateTokenData( TokenData(crm = EMPTY_CRM, device = currentDevice)).device dbDataSource.saveDevice(updatedDevice) notifySuccess(updatedDevice) } catch (error: NetworkException) { notifyError(error) } companion object Factory { fun create(networkDataSource: NetworkDataSource, dbDataSource: DbDataSource): UpdateDevice = UpdateDevice(ThreadExecutorImp, PostExecutionThreadImp, networkDataSource, dbDataSource) } }
apache-2.0
5ae6b3fec0dbc37c4d44a46a354a16bf
38.275362
97
0.768549
4.355305
false
false
false
false
kazy1991/PrefEditor
prefeditor/src/main/java/com/github/kazy1991/prefeditor/view/fragment/PrefListFragment.kt
1
2331
package com.github.kazy1991.prefeditor.view.fragment import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.kazy1991.prefeditor.R import com.github.kazy1991.prefeditor.contract.PrefListContract import com.github.kazy1991.prefeditor.presenter.PrefListPresenter import com.github.kazy1991.prefeditor.view.recyclerview.adapter.PrefListAdapter import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import kotlinx.android.synthetic.main.fragment_pref_list.* class PrefListFragment : Fragment(), PrefListContract.View { override val fragmentManagerProxy: FragmentManager get() = childFragmentManager override val valueClickSubject: Flowable<Triple<Int, String, String>> get() = adapter.valueClickSubject.toFlowable(BackpressureStrategy.LATEST) private val prefName: String get() = arguments.getString(ARGS_PREF_NAME) private val adapter = PrefListAdapter() private lateinit var presenter: PrefListPresenter override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_pref_list, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) recyclerView.adapter = adapter presenter = PrefListPresenter(this, context, prefName).apply { onAttach() } } override fun onDestroyView() { super.onDestroyView() presenter.onDetach() } override fun clearList() { adapter.clear() } override fun updateKeyValueList(list: List<Pair<String, String>>) { adapter.list.addAll(list) adapter.notifyDataSetChanged() } override fun onItemUpdate(position: Int, key: String, newValue: String) { adapter.updateItem(position, key, newValue) } companion object { val ARGS_PREF_NAME = "args_pref_name" fun newInstance(prefName: String): PrefListFragment { return PrefListFragment().also { it.arguments = Bundle().apply { putString(ARGS_PREF_NAME, prefName) } } } } }
mit
d24c4d600c7d3dd0e5f022a2962e7961
33.279412
117
0.726727
4.662
false
false
false
false
shlusiak/Freebloks-Android
game/src/main/java/de/saschahlusiak/freebloks/network/message/MessageServerStatus.kt
1
7267
package de.saschahlusiak.freebloks.network.message import de.saschahlusiak.freebloks.model.GameMode import de.saschahlusiak.freebloks.model.Shape import de.saschahlusiak.freebloks.network.Message import de.saschahlusiak.freebloks.network.MessageType import de.saschahlusiak.freebloks.utils.getArray import de.saschahlusiak.freebloks.utils.put import java.io.Serializable import java.nio.ByteBuffer data class MessageServerStatus( val player: Int, // int8 val computer: Int, // int8 val clients: Int, // int8 val width: Int, // int8 val height: Int, // int8 val gameMode: GameMode, // int8 // since 1.5, optional // a map of player number to client number, or -1 if played by computer val clientForPlayer: Array<Int?>, // int8[4] // names for each client. we don't have names for players, unfortunately. val clientNames: Array<String?>, // uint8[8][16] // since 1.6, optional // the version of this header val version: Int = VERSION_MAX, // int8 // the client should reject any version that is below this val minVersion: Int = VERSION_MAX, // int8 val stoneNumbers: IntArray = IntArray(21) { 1 } // int8[21] ) : Message(MessageType.ServerStatus, HEADER_SIZE_1_6), Serializable { init { assert(player in 0..4) { "Invalid number of players $player"} assert(computer in 0..4) { "Invalid number of computers $computer"} assert(clients in 0..8) { "Invalid number of clients $clients"} assert(clientForPlayer.size == 4) { "Invalid player size ${clientForPlayer.size}"} assert(clientNames.size == 8) { "Invalid clientNames size ${clientNames.size}"} assert(stoneNumbers.size == Shape.COUNT) { "Invalid stoneNumbers size ${stoneNumbers.size}"} } override fun write(buffer: ByteBuffer) { super.write(buffer) buffer.put(player.toByte()) buffer.put(computer.toByte()) buffer.put(clients.toByte()) buffer.put(width.toByte()) buffer.put(height.toByte()) // legacy stone numbers buffer.put(byteArrayOf(1, 1, 1, 1, 1)) buffer.put(gameMode.ordinal.toByte()) clientForPlayer.forEach { buffer.put(it?.toByte() ?: -1) } clientNames.forEach { name -> val bytes = name?.toByteArray() ?: ByteArray(0) buffer.put(bytes, 16) } buffer.put(version.toByte()) buffer.put(minVersion.toByte()) stoneNumbers.forEach { buffer.put(it.toByte()) } } /** * Note, we only support minimum version 3 as of 1.1.6 */ fun isAtLeastVersion(version: Int): Boolean { if (version <= 3) return true return this.version >= version } // TODO: make this nullable fun getClient(player: Int) = clientForPlayer[player] ?: -1 fun isClient(player: Int) = getClient(player) != -1 fun isComputer(player: Int) = !isClient(player) /** * @return the name of the client of null if unset */ fun getClientName(client: Int): String? { if (client < 0) return null return clientNames[client] } /** * @return the name of the client playing the given player, or null if unset */ fun getPlayerName(player: Int): String? { if (player < 0) return null val client = clientForPlayer[player] ?: return null return clientNames[client] } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MessageServerStatus if (player != other.player) return false if (computer != other.computer) return false if (clients != other.clients) return false if (width != other.width) return false if (height != other.height) return false if (gameMode != other.gameMode) return false if (!clientForPlayer.contentEquals(other.clientForPlayer)) return false if (!clientNames.contentEquals(other.clientNames)) return false if (version != other.version) return false if (minVersion != other.minVersion) return false if (!stoneNumbers.contentEquals(other.stoneNumbers)) return false return true } override fun hashCode(): Int { var result = player result = 31 * result + computer result = 31 * result + clients result = 31 * result + width result = 31 * result + height result = 31 * result + gameMode.hashCode() result = 31 * result + clientForPlayer.contentHashCode() result = 31 * result + clientNames.contentHashCode() result = 31 * result + version result = 31 * result + minVersion result = 31 * result + stoneNumbers.contentHashCode() return result } companion object { // highest version we understand. private const val VERSION_MAX = 3 // the original header size, 11 bytes private const val HEADER_SIZE_1_0 = 6 + 5 // the size of version 2 header in bytes, 143 bytes private const val HEADER_SIZE_1_5 = HEADER_SIZE_1_0 + 4 + 8 * 16 // the size of version 3 header in bytes, 166 bytes private const val HEADER_SIZE_1_6 = HEADER_SIZE_1_5 + 2 + 21 fun from(buffer: ByteBuffer): MessageServerStatus { // we only support header version 3 in the Android version assert(buffer.remaining() >= HEADER_SIZE_1_6) { "Message too small, expected 166 bytes but got ${buffer.remaining()}" } // original data val player = buffer.get().toInt() val computer = buffer.get().toInt() val clients = buffer.get().toInt() val width = buffer.get().toInt() val height = buffer.get().toInt() // consume deprecated stoneNumbers Array(5) { buffer.get() } val gameMode = GameMode.from(buffer.get().toInt()) // start of 1.5 data val clientForPlayer = Array(4) { buffer.get().toInt().takeIf { it >= 0 } } val clientNames = Array(8) { val bytes = buffer.getArray(16) val length = bytes.indexOfFirst { it == 0.toByte() } if (length <= 0) null else String(bytes, 0, length, Charsets.UTF_8) } // start of 1.6 data val version = buffer.get().toInt() val minVersion = buffer.get().toInt() val stoneNumbers = IntArray(Shape.COUNT) { buffer.get().toInt() } assert(minVersion <= VERSION_MAX) { "Unsupported version $minVersion" } return MessageServerStatus( player = player, computer = computer, clients = clients, width = width, height = height, gameMode = gameMode, clientForPlayer = clientForPlayer, clientNames = clientNames, version = version, minVersion = minVersion, stoneNumbers = stoneNumbers ) } } }
gpl-2.0
1edd02e4e10f0dd6bbfb9f7defd216cc
36.854167
131
0.593505
4.452819
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/history/db/HistoryEntryWithImageDao.kt
1
4458
package org.wikipedia.history.db import androidx.room.Dao import androidx.room.Query import androidx.room.RewriteQueriesToDropUnusedColumns import org.apache.commons.lang3.StringUtils import org.wikipedia.history.HistoryEntry import org.wikipedia.search.SearchResult import org.wikipedia.search.SearchResults import org.wikipedia.util.StringUtil import java.text.DateFormat import java.util.* @Dao interface HistoryEntryWithImageDao { // TODO: convert to PagingSource. // https://developer.android.com/topic/libraries/architecture/paging/v3-overview @Query("SELECT HistoryEntry.*, PageImage.imageName FROM HistoryEntry LEFT OUTER JOIN PageImage ON (HistoryEntry.namespace = PageImage.namespace AND HistoryEntry.apiTitle = PageImage.apiTitle AND HistoryEntry.lang = PageImage.lang) WHERE UPPER(HistoryEntry.displayTitle) LIKE UPPER(:term) ESCAPE '\\' ORDER BY timestamp DESC") @RewriteQueriesToDropUnusedColumns fun findEntriesBySearchTerm(term: String): List<HistoryEntryWithImage> // TODO: convert to PagingSource. @Query("SELECT HistoryEntry.*, PageImage.imageName FROM HistoryEntry LEFT OUTER JOIN PageImage ON (HistoryEntry.namespace = PageImage.namespace AND HistoryEntry.apiTitle = PageImage.apiTitle AND HistoryEntry.lang = PageImage.lang) WHERE source != :excludeSource1 AND source != :excludeSource2 AND source != :excludeSource3 AND timeSpentSec >= :minTimeSpent ORDER BY timestamp DESC LIMIT :limit") @RewriteQueriesToDropUnusedColumns fun findEntriesBy(excludeSource1: Int, excludeSource2: Int, excludeSource3: Int, minTimeSpent: Int, limit: Int): List<HistoryEntryWithImage> fun findHistoryItem(searchQuery: String): SearchResults { var normalizedQuery = StringUtils.stripAccents(searchQuery).lowercase(Locale.getDefault()) if (normalizedQuery.isEmpty()) { return SearchResults() } normalizedQuery = normalizedQuery.replace("\\", "\\\\") .replace("%", "\\%").replace("_", "\\_") val entries = findEntriesBySearchTerm("%$normalizedQuery%") .filter { StringUtil.fromHtml(it.displayTitle).toString().lowercase().contains(normalizedQuery) } return if (entries.isEmpty()) SearchResults() else SearchResults(entries.take(3).map { SearchResult(toHistoryEntry(it).title, SearchResult.SearchResultType.HISTORY) }.toMutableList()) } fun filterHistoryItems(searchQuery: String): List<Any> { val list = mutableListOf<Any>() val normalizedQuery = StringUtils.stripAccents(searchQuery).lowercase(Locale.getDefault()) .replace("\\", "\\\\") .replace("%", "\\%") .replace("_", "\\_") val entries = findEntriesBySearchTerm("%$normalizedQuery%") for (i in entries.indices) { // Check the previous item, see if the times differ enough // If they do, display the section header. // Always do it if this is the first item. // Check the previous item, see if the times differ enough // If they do, display the section header. // Always do it if this is the first item. val curTime: String = getDateString(entries[i].timestamp) val prevTime: String if (i > 0) { prevTime = getDateString(entries[i - 1].timestamp) if (curTime != prevTime) { list.add(curTime) } } else { list.add(curTime) } list.add(toHistoryEntry(entries[i])) } return list } fun findEntryForReadMore(age: Int, minTimeSpent: Int): List<HistoryEntry> { val entries = findEntriesBy(HistoryEntry.SOURCE_MAIN_PAGE, HistoryEntry.SOURCE_RANDOM, HistoryEntry.SOURCE_FEED_MAIN_PAGE, minTimeSpent, age + 1) return entries.map { toHistoryEntry(it) } } private fun toHistoryEntry(entryWithImage: HistoryEntryWithImage): HistoryEntry { val entry = HistoryEntry(entryWithImage.authority, entryWithImage.lang, entryWithImage.apiTitle, entryWithImage.displayTitle, 0, entryWithImage.namespace, entryWithImage.timestamp, entryWithImage.source, entryWithImage.timeSpentSec) entry.title.thumbUrl = entryWithImage.imageName return entry } private fun getDateString(date: Date): String { return DateFormat.getDateInstance().format(date) } }
apache-2.0
4360f220a0efeabd26c61c9a4f1f085f
47.989011
399
0.687977
4.742553
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/edit/preview/EditPreviewFragment.kt
1
8003
package org.wikipedia.edit.preview import android.content.Context import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebView import androidx.appcompat.app.AlertDialog import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.analytics.EditFunnel import org.wikipedia.bridge.CommunicationBridge import org.wikipedia.bridge.CommunicationBridge.CommunicationBridgeListener import org.wikipedia.bridge.JavaScriptActionHandler import org.wikipedia.databinding.FragmentPreviewEditBinding import org.wikipedia.dataclient.RestService import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.okhttp.OkHttpWebViewClient import org.wikipedia.edit.EditSectionActivity import org.wikipedia.history.HistoryEntry import org.wikipedia.json.JsonUtil import org.wikipedia.page.* import org.wikipedia.page.references.PageReferences import org.wikipedia.page.references.ReferenceDialog import org.wikipedia.util.DeviceUtil import org.wikipedia.util.UriUtil import org.wikipedia.views.ViewAnimations class EditPreviewFragment : Fragment(), CommunicationBridgeListener, ReferenceDialog.Callback { private var _binding: FragmentPreviewEditBinding? = null private val binding get() = _binding!! private lateinit var bridge: CommunicationBridge private lateinit var references: PageReferences private lateinit var funnel: EditFunnel private val bottomSheetPresenter = ExclusiveBottomSheetPresenter() val isActive get() = binding.editPreviewContainer.visibility == View.VISIBLE override lateinit var linkHandler: LinkHandler override val model = PageViewModel() override val webView get() = binding.editPreviewWebview override val isPreview = true override val toolbarMargin = 0 override val referencesGroup get() = references.referencesGroup override val selectedReferenceIndex get() = references.selectedIndex override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentPreviewEditBinding.inflate(layoutInflater, container, false) bridge = CommunicationBridge(this) val pageTitle = (requireActivity() as EditSectionActivity).pageTitle model.title = pageTitle model.curEntry = HistoryEntry(pageTitle, HistoryEntry.SOURCE_INTERNAL_LINK) funnel = WikipediaApp.instance.funnelManager.getEditFunnel(pageTitle) linkHandler = EditLinkHandler(requireContext()) initWebView() binding.editPreviewContainer.visibility = View.GONE return binding.root } /** * Fetches preview html from the modified wikitext text, and shows (fades in) the Preview fragment, * which includes edit summary tags. When the fade-in completes, the state of the * actionbar button(s) is updated, and the preview is shown. * @param title The PageTitle associated with the text being modified. * @param wikiText The text of the section to be shown in the Preview. */ fun showPreview(title: PageTitle, wikiText: String) { DeviceUtil.hideSoftKeyboard(requireActivity()) (requireActivity() as EditSectionActivity).showProgressBar(true) val url = ServiceFactory.getRestBasePath(model.title!!.wikiSite) + RestService.PAGE_HTML_PREVIEW_ENDPOINT + UriUtil.encodeURL(title.prefixedText) val postData = "wikitext=" + UriUtil.encodeURL(wikiText) binding.editPreviewWebview.postUrl(url, postData.toByteArray()) ViewAnimations.fadeIn(binding.editPreviewContainer) { requireActivity().invalidateOptionsMenu() } ViewAnimations.fadeOut(ActivityCompat.requireViewById(requireActivity(), R.id.edit_section_container)) } private fun initWebView() { binding.editPreviewWebview.webViewClient = object : OkHttpWebViewClient() { override val model get() = [email protected] override val linkHandler get() = [email protected] override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) if (!isAdded) { return } (requireActivity() as EditSectionActivity).showProgressBar(false) requireActivity().invalidateOptionsMenu() bridge.execute(JavaScriptActionHandler.setTopMargin(0)) } } bridge.addListener("setup") { _, _ -> } bridge.addListener("final_setup") { _, _ -> } bridge.addListener("link", linkHandler) bridge.addListener("image") { _, _ -> } bridge.addListener("media") { _, _ -> } bridge.addListener("reference") { _, messagePayload -> (JsonUtil.decodeFromString<PageReferences>(messagePayload.toString()))?.let { references = it if (references.referencesGroup.isNotEmpty()) { bottomSheetPresenter.show(childFragmentManager, ReferenceDialog()) } } } } override fun onDestroyView() { binding.editPreviewWebview.clearAllListeners() (binding.editPreviewWebview.parent as ViewGroup).removeView(binding.editPreviewWebview) bridge.cleanup() _binding = null super.onDestroyView() } /** * Hides (fades out) the Preview fragment. * When fade-out completes, the state of the actionbar button(s) is updated. */ fun hide(toView: View) { ViewAnimations.crossFade(binding.editPreviewContainer, toView) { requireActivity().invalidateOptionsMenu() } } inner class EditLinkHandler constructor(context: Context) : LinkHandler(context) { override fun onPageLinkClicked(anchor: String, linkText: String) { // TODO: also need to handle references, issues, disambig, ... in preview eventually } override fun onInternalLinkClicked(title: PageTitle) { showLeavingEditDialogue { startActivity( PageActivity.newIntentForCurrentTab( context, HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK), title ) ) } } override fun onExternalLinkClicked(uri: Uri) { showLeavingEditDialogue { UriUtil.handleExternalLink(context, uri) } } override fun onMediaLinkClicked(title: PageTitle) { // ignore } override fun onDiffLinkClicked(title: PageTitle, revisionId: Long) { // ignore } /** * Shows the user a dialogue asking them if they really meant to leave the edit * workflow, and warning them that their changes have not yet been saved. * * @param runnable The runnable that is run if the user chooses to leave. */ private fun showLeavingEditDialogue(runnable: Runnable) { // Ask the user if they really meant to leave the edit workflow val leavingEditDialog = AlertDialog.Builder(requireActivity()) .setMessage(R.string.dialog_message_leaving_edit) .setPositiveButton(R.string.dialog_message_leaving_edit_leave) { dialog, _: Int -> // They meant to leave; close dialogue and run specified action dialog.dismiss() runnable.run() } .setNegativeButton(R.string.dialog_message_leaving_edit_stay, null) .create() leavingEditDialog.show() } @Suppress("UNUSED_PARAMETER") override var wikiSite: WikiSite get() = model.title!!.wikiSite set(wikiSite) {} } }
apache-2.0
754adf80ee37c0c0c87552cf5bf51af4
41.569149
116
0.682994
5.090967
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/extension/model/api/mastodon/NotificationExtensions.kt
1
4306
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.extension.model.api.mastodon import org.mariotaku.ktextension.mapToArray import de.vanita5.microblog.library.mastodon.model.Notification import de.vanita5.microblog.library.mastodon.model.Relationship import de.vanita5.microblog.library.twitter.model.Activity import de.vanita5.twittnuker.extension.model.toLite import de.vanita5.twittnuker.extension.model.toSummaryLine import de.vanita5.twittnuker.extension.model.updateActivityFilterInfo import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableActivity import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.UserKey fun Notification.toParcelable(details: AccountDetails, relationships: Map<String, Relationship>?): ParcelableActivity { return toParcelable(details.key, relationships).apply { account_color = details.color } } fun Notification.toParcelable(accountKey: UserKey, relationships: Map<String, Relationship>?): ParcelableActivity { val result = ParcelableActivity() result.account_key = accountKey result.id = "$id-$id" result.timestamp = createdAt.time result.min_position = id result.max_position = id result.min_sort_position = result.timestamp result.max_sort_position = result.timestamp result.sources = toSources(accountKey, relationships) result.user_key = result.sources?.singleOrNull()?.key ?: UserKey("multiple", null) val status = this.status when (type) { Notification.Type.MENTION -> { if (status == null) { result.action = Activity.Action.INVALID return result } result.action = Activity.Action.MENTION status.applyTo(accountKey, result) } Notification.Type.REBLOG -> { if (status == null) { result.action = Activity.Action.INVALID return result } result.action = Activity.Action.RETWEET val parcelableStatus = status.toParcelable(accountKey) result.target_objects = ParcelableActivity.RelatedObject.statuses(parcelableStatus) result.summary_line = arrayOf(parcelableStatus.toSummaryLine()) } Notification.Type.FAVOURITE -> { if (status == null) { result.action = Activity.Action.INVALID return result } result.action = Activity.Action.FAVORITE val parcelableStatus = status.toParcelable(accountKey) result.targets = ParcelableActivity.RelatedObject.statuses(parcelableStatus) result.summary_line = arrayOf(parcelableStatus.toSummaryLine()) } Notification.Type.FOLLOW -> { result.action = Activity.Action.FOLLOW } else -> { result.action = type } } result.sources_lite = result.sources?.mapToArray { it.toLite() } result.source_keys = result.sources_lite?.mapToArray { it.key } result.updateActivityFilterInfo() return result } private fun Notification.toSources(accountKey: UserKey, relationships: Map<String, Relationship>?): Array<ParcelableUser>? { val account = this.account ?: return null val relationship = relationships?.get(account.id) return arrayOf(account.toParcelable(accountKey, relationship = relationship)) }
gpl-3.0
037b0e36ca696265b8f1536ca2aca957
38.504587
99
0.697167
4.532632
false
false
false
false
UnsignedInt8/d.Wallet-Core
android/lib/src/test/java/dWallet/u8/PeerTests.kt
1
3725
package dwallet.u8 import dwallet.core.bitcoin.p2p.Node import dwallet.core.bitcoin.protocol.messages.Version import dwallet.core.bitcoin.protocol.structures.* import dwallet.core.extensions.hexToByteArray import dwallet.core.extensions.toInt32LEBytes import dwallet.core.infrastructure.SocketEx import dwallet.core.utils.BloomFilter3 import dwallet.core.utils.MerkleTree import kotlinx.coroutines.experimental.* import org.junit.Test /** * Created by unsignedint8 on 8/16/17. */ class PeerTests { @Test fun testVersion() = runBlocking { val host = "localhost" val s = SocketEx() if (!s.connectAsync(host, 19000).await()) return@runBlocking val service = byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0) val ver3 = Version(services = service, toAddr = NetworkAddress("::0", 0, addTimestamp = false), fromAddr = NetworkAddress("::0", 0, services = service, addTimestamp = false), nonce = 7284544412836900411, ua = "/zz/", startHeight = 1) // println(ver3.toBytes().toHexString()) val m3 = Message(Message.Magic.Bitcoin.testnet, "version", ver3.toBytes()) // println(m3.toBytes().toHexString()) s.writeAsync(m3.toBytes()).await() val data = s.readAsync().await() val m4 = Message.fromBytes(data!!) val v4 = Version.fromBytes(m4.payload) assert(v4.ua.contains("satoshi", ignoreCase = true)) } @Test fun testNodeVersion() { var gotcount = 0 val host = "localhost"// "120.77.42.241" val port = 19000 val magic = Message.Magic.Bitcoin.regtest.toInt32LEBytes() val node = Node(Message.Magic.Bitcoin.main.toInt32LEBytes()) node.magic = magic node.initBloomFilter(listOf("bc7662ecd3c4e0024d00e8647fb9ff6539a7b379".hexToByteArray()), 0.0001, nFlags = BloomFilter3.BloomUpdate.UPDATE_ALL) node.onHeaders { _, headers -> println(headers.size) println(headers.first().preBlockHash) if (gotcount++ == 2) return@onHeaders node.sendGetHeaders(listOf(headers.last().preBlockHash)) } node.onInv { _, invs -> println("inv ${invs.size} ${invs.all { it.type == InvTypes.MSG_BLOCK }}") println(invs.first().hash) node.sendGetMerkleblocks(invs.map { it.hash }) // node.sendGetData(invs.takeLast(5)) } node.onTx { sender, tx -> println(tx.id) } node.onReject { _, reject -> println("${reject.message} ${reject.reason}") } node.onVerack { _, _ -> node.sendGetBlocks() } node.onBlock { sender, block -> if (!block.isValidMerkleRoot()) { println("block " + block.hash + " " + block.isValidMerkleRoot() + " " + block.txs.size) println(block.merkleRootHash) println(MerkleTree.generateRootHash(block.txs.map { it.id })) println(block.txs.map { it.id }) } } node.onMerkleblock { _, block -> if (block.hash == "64fe9831db78b5c3454ebcf24000d82ddfad7d010a62c2a425fa4797f18504fc") { println("here !!!") node.sendGetMerkleblocks(listOf(block.preBlockHash)) } if (block.hash == "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206") println("merkleblock: ${block.hash}") if (block.flags.isNotEmpty()) println("flags: " + block.flags) println(block.preBlockHash + " ") } async(CommonPool) { node.connectAsync(host, port).await() println("socket port: ${node.localPort}") } runBlocking { delay(5 * 1000) } } }
gpl-3.0
9a50220327d72bc50fe39010a0f2b7c1
34.485714
241
0.611812
3.592093
false
true
false
false
Xenoage/Zong
utils-kotlin/src/com/xenoage/utils/document/io/SupportedFormats.kt
1
1282
package com.xenoage.utils.document.io import com.xenoage.utils.document.Document import kotlin.coroutines.experimental.EmptyCoroutineContext.get /** * This base class provides a list of all formats which can be used * for loading or saving a document. */ abstract class SupportedFormats<T : Document> { /** The list of supported formats */ abstract val formats: List<FileFormat<T>> /** A list of the supported formats for reading */ val readFormats = formats.filter { it.input != null } /** A list of the supported formats for reading */ val writeFormats = formats.filter { it.output != null } /** The default format for reading files */ abstract val readDefaultFormat: FileFormat<T> /** The default format for writing files */ abstract val writeDefaultFormat: FileFormat<T> /** Gets the format with the given ID. */ fun getByID(id: String) = formats.find { it.id == id } ?: throw IllegalArgumentException("Format with ID \"$id\" does not exist") /** * Gets the format of the file with the given name, guessed by its extension. * If this is not possible, the default read format is returned. */ fun getFormatByExtension(filename: String) = formats.find { it.allExtensions.find { filename.endsWith(it, true) } != null } ?: readDefaultFormat }
agpl-3.0
ead5f02c790c13709fdc2b648d034a9d
31.871795
78
0.723869
3.884848
false
false
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/util/gpx/model/GpxSchema.kt
1
1189
package com.peterlaurence.trekme.util.gpx.model /** * The GPX schema, compliant with the Topografix GPX 1.1 * * @author peterLaurence on 30/12/17. * @see [Topografix GPX 1.1](http://www.topografix.com/GPX/1/1/) */ /* Root tag */ const val TAG_GPX = "gpx" /* Gpx attributes and nodes nodes */ const val ATTR_VERSION = "version" const val ATTR_CREATOR = "creator" const val TAG_TRACK = "trk" const val TAG_ROUTE = "rte" const val TAG_WAYPOINT = "wpt" /* Track nodes */ const val TAG_NAME = "name" const val TAG_SEGMENT = "trkseg" const val TAG_EXTENSIONS = "extensions" /* Track segment nodes */ const val TAG_POINT = "trkpt" /* Track point (but oddly called WayPoint in the GPX1.1 documentation) attributes and nodes */ const val ATTR_LAT = "lat" const val ATTR_LON = "lon" const val TAG_ELEVATION = "ele" const val TAG_TIME = "time" /* Track custom extensions nodes and attributes */ const val TAG_TRACK_STATISTICS = "statistics" const val ATTR_TRK_STAT_DIST = "distance" const val ATTR_TRK_STAT_ELE_DIFF_MAX = "eleDiffMax" const val ATTR_TRK_STAT_ELE_UP_STACK = "eleUpStack" const val ATTR_TRK_STAT_ELE_DOWN_STACK = "eleDownStack" const val ATTR_TRK_STAT_DURATION = "duration"
gpl-3.0
1e9ae0348a6451db19fb450adb3be705
29.487179
94
0.715728
2.950372
false
false
false
false
hannesa2/owncloud-android
owncloudData/src/main/java/com/owncloud/android/data/preferences/datasources/implementation/SharedPreferencesProviderImpl.kt
2
2324
/** * ownCloud Android client application * * @author Abel García de Prada * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * 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.owncloud.android.data.preferences.datasources.implementation import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import com.owncloud.android.data.preferences.datasources.SharedPreferencesProvider class SharedPreferencesProviderImpl( context: Context ) : SharedPreferencesProvider { // TODO: Move to Androidx Preferences or DataStore private val sharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) private val editor = sharedPreferences.edit() override fun putString(key: String, value: String) = editor.putString(key, value).apply() override fun getString(key: String, defaultValue: String?) = sharedPreferences.getString(key, defaultValue) override fun putInt(key: String, value: Int) = editor.putInt(key, value).apply() override fun getInt(key: String, defaultValue: Int) = sharedPreferences.getInt(key, defaultValue) override fun putLong(key: String, value: Long) = editor.putLong(key, value).apply() override fun getLong(key: String, defaultValue: Long) = sharedPreferences.getLong(key, defaultValue) override fun putBoolean(key: String, value: Boolean) = editor.putBoolean(key, value).apply() override fun getBoolean(key: String, defaultValue: Boolean) = sharedPreferences.getBoolean(key, defaultValue) override fun containsPreference(key: String) = sharedPreferences.contains(key) override fun removePreference(key: String) = editor.remove(key).apply() override fun contains(key: String) = sharedPreferences.contains(key) }
gpl-2.0
89031945aeac13d37180fd45f90f989d
43.673077
113
0.769264
4.6
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/toolchain/wsl/RsWslToolchainFlavor.kt
2
2991
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.toolchain.wsl import com.intellij.execution.wsl.WSLDistribution import com.intellij.execution.wsl.WSLUtil import com.intellij.execution.wsl.WslDistributionManager import com.intellij.execution.wsl.WslPath import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.NlsContexts.ProgressTitle import com.intellij.util.io.isDirectory import org.rust.cargo.toolchain.flavors.RsToolchainFlavor import org.rust.ide.experiments.RsExperiments.WSL_TOOLCHAIN import org.rust.openapiext.computeWithCancelableProgress import org.rust.openapiext.isDispatchThread import org.rust.openapiext.isFeatureEnabled import org.rust.stdext.resolveOrNull import java.nio.file.Path class RsWslToolchainFlavor : RsToolchainFlavor() { override fun getHomePathCandidates(): Sequence<Path> = sequence { val distributions = compute("Getting installed distributions...") { WslDistributionManager.getInstance().installedDistributions } for (distro in distributions) { yieldAll(distro.getHomePathCandidates()) } } override fun isApplicable(): Boolean = WSLUtil.isSystemCompatible() && isFeatureEnabled(WSL_TOOLCHAIN) override fun isValidToolchainPath(path: Path): Boolean = WslPath.isWslUncPath(path.toString()) && super.isValidToolchainPath(path) override fun hasExecutable(path: Path, toolName: String): Boolean = path.hasExecutableOnWsl(toolName) override fun pathToExecutable(path: Path, toolName: String): Path = path.pathToExecutableOnWsl(toolName) } fun WSLDistribution.getHomePathCandidates(): Sequence<Path> = sequence { @Suppress("UnstableApiUsage") val root = uncRootPath val environment = compute("Getting environment variables...") { environment } if (environment != null) { val home = environment["HOME"] val remoteCargoPath = home?.let { "$it/.cargo/bin" } val localCargoPath = remoteCargoPath?.let { root.resolve(it) } if (localCargoPath?.isDirectory() == true) { yield(localCargoPath) } val sysPath = environment["PATH"] for (remotePath in sysPath.orEmpty().split(":")) { if (remotePath.isEmpty()) continue val localPath = root.resolveOrNull(remotePath) ?: continue if (!localPath.isDirectory()) continue yield(localPath) } } for (remotePath in listOf("/usr/local/bin", "/usr/bin")) { val localPath = root.resolve(remotePath) if (!localPath.isDirectory()) continue yield(localPath) } } private fun <T> compute( @Suppress("UnstableApiUsage") @ProgressTitle title: String, getter: () -> T ): T = if (isDispatchThread) { val project = ProjectManager.getInstance().defaultProject project.computeWithCancelableProgress(title, getter) } else { getter() }
mit
90ca251ce66d7bb16671ed2346a1a1f5
35.925926
108
0.711802
4.531818
false
false
false
false
androidx/androidx
wear/watchface/watchface-guava/src/main/java/androidx/wear/watchface/ListenableCanvasRenderer.kt
3
5857
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface import android.view.SurfaceHolder import androidx.annotation.IntRange import androidx.annotation.UiThread import androidx.annotation.WorkerThread import androidx.wear.watchface.Renderer.SharedAssets import androidx.wear.watchface.style.CurrentUserStyleRepository import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.SettableFuture import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume /** * [ListenableFuture]-based compatibility wrapper around [Renderer.CanvasRenderer]'s suspending * methods. */ @Deprecated(message = "Use ListenableCanvasRenderer2 instead") @Suppress("Deprecation") public abstract class ListenableCanvasRenderer @JvmOverloads constructor( surfaceHolder: SurfaceHolder, currentUserStyleRepository: CurrentUserStyleRepository, watchState: WatchState, @CanvasType private val canvasType: Int, @IntRange(from = 0, to = 60000) interactiveDrawModeUpdateDelayMillis: Long, clearWithBackgroundTintBeforeRenderingHighlightLayer: Boolean = false ) : Renderer.CanvasRenderer( surfaceHolder, currentUserStyleRepository, watchState, canvasType, interactiveDrawModeUpdateDelayMillis, clearWithBackgroundTintBeforeRenderingHighlightLayer ) { /** * Perform UiThread specific initialization. Will be called once during initialization * before any subsequent calls to [render]. Note cancellation of the returned future is not * supported. * * @return A ListenableFuture<Unit> which is resolved when UiThread has completed. Rendering * will be blocked until this has resolved. */ @UiThread @Suppress("AsyncSuffixFuture") // This is the guava wrapper for a suspend function public open fun initFuture(): ListenableFuture<Unit> { return SettableFuture.create<Unit>().apply { set(Unit) } } override suspend fun init(): Unit = suspendCancellableCoroutine { val future = initFuture() future.addListener( { it.resume(future.get()) }, { runnable -> runnable.run() } ) } } /** * [ListenableFuture]-based compatibility wrapper around * [Renderer.CanvasRenderer2]'s suspending methods. */ public abstract class ListenableCanvasRenderer2<SharedAssetsT> @JvmOverloads constructor( surfaceHolder: SurfaceHolder, currentUserStyleRepository: CurrentUserStyleRepository, watchState: WatchState, @CanvasType private val canvasType: Int, @IntRange(from = 0, to = 60000) interactiveDrawModeUpdateDelayMillis: Long, clearWithBackgroundTintBeforeRenderingHighlightLayer: Boolean = false ) : Renderer.CanvasRenderer2<SharedAssetsT>( surfaceHolder, currentUserStyleRepository, watchState, canvasType, interactiveDrawModeUpdateDelayMillis, clearWithBackgroundTintBeforeRenderingHighlightLayer ) where SharedAssetsT : SharedAssets { /** * Perform UiThread specific initialization. Will be called once during initialization * before any subsequent calls to [render]. Note cancellation of the returned future is not * supported. * * @return A ListenableFuture<Unit> which is resolved when UiThread has completed. Rendering * will be blocked until this has resolved. */ @UiThread @Suppress("AsyncSuffixFuture") // This is the guava wrapper for a suspend function public open fun initFuture(): ListenableFuture<Unit> { return SettableFuture.create<Unit>().apply { set(Unit) } } final override suspend fun init(): Unit = suspendCancellableCoroutine { val future = initFuture() future.addListener( { it.resume(future.get()) }, { runnable -> runnable.run() } ) } /** * When editing multiple [WatchFaceService] instances and hence Renderers can exist * concurrently (e.g. a headless instance and an interactive instance) and using * [SharedAssets] allows memory to be saved by sharing immutable data (e.g. Bitmaps, * shaders, etc...) between them. * * To take advantage of SharedAssets, override this method. The constructed SharedAssets are * passed into the [render] as an argument (NB you'll have to cast this to your type). * * When all instances using SharedAssets have been closed, [SharedAssets.onDestroy] will be * called. * * Note that while SharedAssets are constructed on a background thread, they'll typically be * used on the main thread and subsequently destroyed there. * * @return A [ListenableFuture] for the [SharedAssetsT] that will be passed into [render] and * [renderHighlightLayer] */ @WorkerThread @Suppress("AsyncSuffixFuture") // This is the guava wrapper for a suspend function public abstract fun createSharedAssetsFuture(): ListenableFuture<SharedAssetsT> final override suspend fun createSharedAssets(): SharedAssetsT = suspendCancellableCoroutine { val future = createSharedAssetsFuture() future.addListener( { it.resume(future.get()) }, { runnable -> runnable.run() } ) } }
apache-2.0
cdb98f6ea2313aa9be966052f24ecb06
38.053333
98
0.723749
4.888982
false
false
false
false
androidx/androidx
tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/LazyBeyondBoundsModifier.kt
3
7029
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.foundation.lazy import androidx.compose.foundation.gestures.Orientation import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.layout.BeyondBoundsLayout import androidx.compose.ui.layout.BeyondBoundsLayout.BeyondBoundsScope import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Above import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.After import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Before import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Below import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Left import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Right import androidx.compose.ui.layout.ModifierLocalBeyondBoundsLayout import androidx.compose.ui.modifier.ModifierLocalProvider import androidx.compose.ui.modifier.ProvidableModifierLocal import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.LayoutDirection.Ltr import androidx.compose.ui.unit.LayoutDirection.Rtl import androidx.tv.foundation.lazy.LazyListBeyondBoundsInfo.Interval import androidx.tv.foundation.lazy.list.TvLazyListState /** * This modifier is used to measure and place additional items when the lazyList receives a * request to layout items beyond the visible bounds. */ @Suppress("ComposableModifierFactory") @Composable internal fun Modifier.lazyListBeyondBoundsModifier( state: TvLazyListState, beyondBoundsInfo: LazyListBeyondBoundsInfo, reverseLayout: Boolean, orientation: Orientation ): Modifier { val layoutDirection = LocalLayoutDirection.current return this then remember( state, beyondBoundsInfo, reverseLayout, layoutDirection, orientation ) { LazyListBeyondBoundsModifierLocal( state, beyondBoundsInfo, reverseLayout, layoutDirection, orientation ) } } private class LazyListBeyondBoundsModifierLocal( private val state: TvLazyListState, private val beyondBoundsInfo: LazyListBeyondBoundsInfo, private val reverseLayout: Boolean, private val layoutDirection: LayoutDirection, private val orientation: Orientation ) : ModifierLocalProvider<BeyondBoundsLayout?>, BeyondBoundsLayout { override val key: ProvidableModifierLocal<BeyondBoundsLayout?> get() = ModifierLocalBeyondBoundsLayout override val value: BeyondBoundsLayout get() = this override fun <T> layout( direction: BeyondBoundsLayout.LayoutDirection, block: BeyondBoundsScope.() -> T? ): T? { // We use a new interval each time because this function is re-entrant. var interval = beyondBoundsInfo.addInterval( state.firstVisibleItemIndex, state.layoutInfo.visibleItemsInfo.last().index ) var found: T? = null while (found == null && interval.hasMoreContent(direction)) { // Add one extra beyond bounds item. interval = addNextInterval(interval, direction).also { beyondBoundsInfo.removeInterval(interval) } state.remeasurement?.forceRemeasure() // When we invoke this block, the beyond bounds items are present. found = block.invoke( object : BeyondBoundsScope { override val hasMoreContent: Boolean get() = interval.hasMoreContent(direction) } ) } // Dispose the items that are beyond the visible bounds. beyondBoundsInfo.removeInterval(interval) state.remeasurement?.forceRemeasure() return found } private fun addNextInterval( currentInterval: Interval, direction: BeyondBoundsLayout.LayoutDirection ): Interval { var start = currentInterval.start var end = currentInterval.end when (direction) { Before -> start-- After -> end++ Above -> if (reverseLayout) end++ else start-- Below -> if (reverseLayout) start-- else end++ Left -> when (layoutDirection) { Ltr -> if (reverseLayout) end++ else start-- Rtl -> if (reverseLayout) start-- else end++ } Right -> when (layoutDirection) { Ltr -> if (reverseLayout) start-- else end++ Rtl -> if (reverseLayout) end++ else start-- } else -> unsupportedDirection() } return beyondBoundsInfo.addInterval(start, end) } private fun Interval.hasMoreContent(direction: BeyondBoundsLayout.LayoutDirection): Boolean { fun hasMoreItemsBefore() = start > 0 fun hasMoreItemsAfter() = end < state.layoutInfo.totalItemsCount - 1 if (direction.isOppositeToOrientation()) return false return when (direction) { Before -> hasMoreItemsBefore() After -> hasMoreItemsAfter() Above -> if (reverseLayout) hasMoreItemsAfter() else hasMoreItemsBefore() Below -> if (reverseLayout) hasMoreItemsBefore() else hasMoreItemsAfter() Left -> when (layoutDirection) { Ltr -> if (reverseLayout) hasMoreItemsAfter() else hasMoreItemsBefore() Rtl -> if (reverseLayout) hasMoreItemsBefore() else hasMoreItemsAfter() } Right -> when (layoutDirection) { Ltr -> if (reverseLayout) hasMoreItemsBefore() else hasMoreItemsAfter() Rtl -> if (reverseLayout) hasMoreItemsAfter() else hasMoreItemsBefore() } else -> unsupportedDirection() } } private fun BeyondBoundsLayout.LayoutDirection.isOppositeToOrientation(): Boolean { return when (this) { Above, Below -> orientation == Orientation.Horizontal Left, Right -> orientation == Orientation.Vertical Before, After -> false else -> unsupportedDirection() } } } private fun unsupportedDirection(): Nothing = error( "Lazy list does not support beyond bounds layout for the specified direction" )
apache-2.0
7262bb4c854f74107cd4919e8f0b743e
39.396552
97
0.686157
5.436195
false
false
false
false
Omico/CurrentActivity
ui/common/theme/src/main/kotlin/me/omico/currentactivity/ui/theme/Theme.kt
1
3249
/* * This file is part of CurrentActivity. * * Copyright (C) 2022 Omico * * CurrentActivity 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. * * CurrentActivity 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 CurrentActivity. If not, see <https://www.gnu.org/licenses/>. */ package me.omico.currentactivity.ui.theme import android.os.Build import androidx.annotation.ChecksSdkIntAtLeast import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import com.example.myapplication.ui.theme.Typography import com.google.accompanist.systemuicontroller.SystemUiController import com.google.accompanist.systemuicontroller.rememberSystemUiController private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80, ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40, /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun CurrentActivityTheme( darkTheme: Boolean = isSystemInDarkTheme(), systemUiController: SystemUiController = rememberSystemUiController(), dynamicColor: Boolean = true, content: @Composable () -> Unit, ) { val colorScheme = when { dynamicColor && isDynamicColorSupported -> when { darkTheme -> dynamicDarkColorScheme(LocalContext.current) else -> dynamicLightColorScheme(LocalContext.current) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { systemUiController.setSystemBarsColor( color = Color.Transparent, darkIcons = !darkTheme, isNavigationBarContrastEnforced = false, ) } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content, ) } val isDynamicColorSupported: Boolean @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S) get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
gpl-3.0
2feee7a566c0958a1ed96bf8cc3bacdd
33.56383
75
0.736227
4.628205
false
false
false
false
codebutler/odyssey
retrograde-app-tv/src/main/java/com/codebutler/retrograde/app/feature/game/GameLauncherActivity.kt
1
1806
package com.codebutler.retrograde.app.feature.game import android.content.Context import android.content.Intent import android.os.Bundle import androidx.work.WorkManager import com.codebutler.retrograde.lib.android.RetrogradeActivity import com.codebutler.retrograde.lib.game.GameSaveWorker import com.codebutler.retrograde.lib.library.db.entity.Game /** * Used as entry to point to [GameActivity], which runs in a separate process. * Ensures that [GameSaveWorker] runs in main process only. */ class GameLauncherActivity : RetrogradeActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { val gameIntent = Intent(this, GameActivity::class.java) gameIntent.putExtras(intent.extras!!) startActivityForResult(gameIntent, REQUEST_CODE_GAME) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_GAME && resultCode == RESULT_OK && data != null) { val gameId = data.getIntExtra(GameActivity.EXTRA_GAME_ID, -1) val saveFile = data.getStringExtra(GameActivity.EXTRA_SAVE_FILE) if (gameId != -1 && saveFile != null) { WorkManager.getInstance().enqueue(GameSaveWorker.newRequest(gameId, saveFile)) } } setResult(resultCode) finish() } companion object { private const val REQUEST_CODE_GAME = 1000 fun newIntent(context: Context, game: Game) = Intent(context, GameLauncherActivity::class.java).apply { putExtra(GameActivity.EXTRA_GAME_ID, game.id) } } }
gpl-3.0
4d8cfc5ff9e699cf3f2470b2d903328d
37.425532
94
0.674972
4.526316
false
false
false
false
bjzhou/Coolapk
app/src/main/kotlin/bjzhou/coolapk/app/ui/adapters/UpgradeAdapter.kt
1
5071
package bjzhou.coolapk.app.ui.adapters import android.app.DownloadManager import android.net.Uri import android.support.v4.app.FragmentActivity import android.support.v7.widget.RecyclerView import android.text.TextUtils import android.view.View import android.view.ViewGroup import android.widget.Button import bjzhou.coolapk.app.App import bjzhou.coolapk.app.R import bjzhou.coolapk.app.model.Apk import bjzhou.coolapk.app.model.UpgradeApkExtend import bjzhou.coolapk.app.net.ApkDownloader import bjzhou.coolapk.app.net.DownloadStatus import bjzhou.coolapk.app.util.Settings import bjzhou.coolapk.app.util.Utils import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.list_item_upgrade_app.view.* import java.io.File import java.util.* /** * Created by bjzhou on 14-8-13. */ class UpgradeAdapter(private val mActivity: FragmentActivity) : RecyclerView.Adapter<UpgradeAdapter.ViewHolder>() { private var mUpgradeList: List<UpgradeApkExtend> = ArrayList() private var mObserveMap = HashMap<Apk, Disposable>() private val mButtonMap = WeakHashMap<Apk, Button>() override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): UpgradeAdapter.ViewHolder { val convertView = mActivity.layoutInflater.inflate(R.layout.list_item_upgrade_app, viewGroup, false) return ViewHolder(convertView) } override fun onBindViewHolder(holder: UpgradeAdapter.ViewHolder, position: Int) { val upgradeApk = mUpgradeList[position] holder.titleView.text = upgradeApk.title ?: upgradeApk.apk.title ?: "null" holder.infoView.text = upgradeApk.info ?: upgradeApk.apk.info ?: "null" holder.logoView.setImageDrawable(upgradeApk.logo) val changelog = upgradeApk.apk.changelog if (!TextUtils.isEmpty(changelog)) { holder.changelogView.text = changelog holder.changelogView.visibility = View.VISIBLE } else { holder.changelogView.visibility = View.GONE } holder.upgradeButton.tag = 0 holder.upgradeButton.text = "升级" holder.upgradeButton.tag = upgradeApk.apk mButtonMap.put(upgradeApk.apk, holder.upgradeButton) } override fun getItemId(position: Int): Long { return mUpgradeList[position].apk.id.toLong() } override fun getItemCount(): Int { return mUpgradeList.size } fun setUpgradeList(upgradeList: List<UpgradeApkExtend>) { mUpgradeList = upgradeList for (upgradeApk in mUpgradeList) { mObserveMap.put(upgradeApk.apk, observeApk(upgradeApk.apk)) } } private fun observeApk(apk: Apk): Disposable { return ApkDownloader.instance.observeDownloadStatus(apk) .subscribe { val button = mButtonMap[apk] if (button != null && button.tag as Apk == apk) { button.post { if (it.status == DownloadStatus.STATUS_NOT_STARTED) { button.text = "升级" } else if (it.status == DownloadManager.STATUS_FAILED) { button.text = "下载失败,点击重试" } else if (it.status == DownloadManager.STATUS_SUCCESSFUL) { button.text = "下载完成" } else { button.text = it.percent.toString() + "%" } } } } } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal var logoView = itemView.list_item_icon internal var titleView = itemView.list_item_title internal var infoView = itemView.list_item_info internal var changelogView = itemView.list_item_description internal var upgradeButton = itemView.list_item_upgrade init { upgradeButton.setOnClickListener { if (adapterPosition == RecyclerView.NO_POSITION) return@setOnClickListener val apkExtend = mUpgradeList[adapterPosition] val status = ApkDownloader.instance.getDownloadStatus(apkExtend.apk) if (status.status == DownloadManager.STATUS_SUCCESSFUL) { val file = File(Settings.instance.downloadDir, apkExtend.apk.filename) val pkgInfo = App.context.packageManager.getPackageArchiveInfo(file.absolutePath, 0) if (file.exists() && pkgInfo != null) { Utils.installApk(Uri.fromFile(file)) } } else if (status.status == DownloadStatus.STATUS_NOT_STARTED || status.status == DownloadManager.STATUS_FAILED) { ApkDownloader.instance.download(apkExtend.apk) mObserveMap.put(apkExtend.apk, observeApk(apkExtend.apk)) } } } } companion object { private val TAG = "UpgradeAdapter" } }
gpl-2.0
dad9d38b0deb90c3884bc04340ba7931
40.991667
130
0.632467
4.593437
false
false
false
false
0x1bad1d3a/Kaku
app/src/main/java/ca/fuwafuwa/kaku/Dialogs/TutorialExplainDialogFragment.kt
2
1411
package ca.fuwafuwa.kaku.Dialogs import android.app.AlertDialog import android.app.Dialog import android.os.Bundle import androidx.fragment.app.DialogFragment class TutorialExplainDialogFragment : DialogFragment() { private lateinit var mTitle : String private lateinit var mMessage : String override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { mTitle = arguments?.getString(ARG_TITLE)!! mMessage = arguments?.getString(ARG_MESSAGE)!! return activity?.let { val builder = AlertDialog.Builder(it) builder.setTitle(mTitle) .setMessage(mMessage) .setPositiveButton("OK") { _, _ -> run { } } builder.create() } ?: throw IllegalStateException("Activity cannot be null") } companion object { private val ARG_TITLE = "arg_title" private val ARG_MESSAGE = "arg_message" fun newInstance(title: String, message: String) : TutorialExplainDialogFragment { val dialog = TutorialExplainDialogFragment() val args = Bundle() args.putString(ARG_TITLE, title) args.putString(ARG_MESSAGE, message) dialog.arguments = args return dialog } } }
bsd-3-clause
d268f20db6d813262772a6c654485544
26.153846
87
0.576187
5.385496
false
false
false
false
Etik-Tak/backend
src/main/kotlin/dk/etiktak/backend/model/product/Product.kt
1
4796
// Copyright (c) 2017, Daniel Andersen ([email protected]) // All rights reserved. // // 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. // 3. The name of the author may not be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * Represents a product. Actual information is aggregrated from the contributions. */ package dk.etiktak.backend.model.product import dk.etiktak.backend.model.BaseModel import dk.etiktak.backend.model.company.Company import dk.etiktak.backend.model.recommendation.ProductRecommendation import org.springframework.format.annotation.DateTimeFormat import java.util.* import javax.persistence.* import javax.validation.constraints.NotNull @Entity(name = "products") class Product : BaseModel() { enum class BarcodeType { EAN_13, UPC, UNKNOWN } @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "product_id") var id: Long = 0 @Column(name = "uuid", nullable = false, unique = true) var uuid: String = "" @Column(name = "barcode") var barcode: String = "" @Column(name = "barcode_type") var barcodeType = BarcodeType.UNKNOWN @Column(name = "name") var name: String = "" @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name="product_productCategory", joinColumns=arrayOf(JoinColumn(name="product_id", referencedColumnName="product_id")), inverseJoinColumns=arrayOf(JoinColumn(name="product_category_id", referencedColumnName="product_category_id"))) @Column(name = "product_categories") var productCategories: MutableSet<ProductCategory> = HashSet() @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name="product_productLabel", joinColumns=arrayOf(JoinColumn(name="product_id", referencedColumnName="product_id")), inverseJoinColumns=arrayOf(JoinColumn(name="product_label_id", referencedColumnName="product_label_id"))) @Column(name = "product_labels") var productLabels: MutableSet<ProductLabel> = HashSet() @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name="product_productTag", joinColumns=arrayOf(JoinColumn(name="product_id", referencedColumnName="product_id")), inverseJoinColumns=arrayOf(JoinColumn(name="product_tag_id", referencedColumnName="product_tag_id"))) @Column(name = "product_tags") var productTags: MutableSet<ProductTag> = HashSet() @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name="product_company", joinColumns=arrayOf(JoinColumn(name="product_id", referencedColumnName="product_id")), inverseJoinColumns=arrayOf(JoinColumn(name="company_id", referencedColumnName="company_id"))) @Column(name = "companies") var companies: MutableSet<Company> = HashSet() @NotNull @OneToMany(mappedBy = "product", fetch = FetchType.LAZY) var productScans: MutableList<ProductScan> = ArrayList() @OneToMany(mappedBy = "product", fetch = FetchType.LAZY) var recommendations: MutableList<ProductRecommendation> = ArrayList() @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") var creationTime = Date() @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") var modificationTime = Date() @PreUpdate fun preUpdate() { modificationTime = Date() } @PrePersist fun prePersist() { val now = Date() creationTime = now modificationTime = now } }
bsd-3-clause
ceedccca9dfd86822ae95e42fe1a201e
37.685484
123
0.710384
4.432532
false
false
false
false
valery-labuzhsky/EditorTools
IDEA/src/main/java/ksp/kos/ideaplugin/expressions/Atom.kt
2
1271
package ksp.kos.ideaplugin.expressions import ksp.kos.ideaplugin.psi.* /** * Created on 28/01/16. * * @author ptasha */ abstract class Atom : Expression() { open val isAddition: Boolean get() = false companion object { @Throws(SyntaxException::class) fun parse(expr: KerboScriptExpr): Atom = Expression.parse(expr) as? Atom ?: throw SyntaxException("Atom is expected: found " + expr + ": " + expr.text) @JvmStatic @Throws(SyntaxException::class) fun parse(atom: KerboScriptAtom): Atom { val identifier = atom.children.firstOrNull { it is KerboScriptIdent } val expr = atom.expr return when { identifier != null -> Variable(identifier.text) atom.node.findChildByType(KerboScriptTypes.BRACKETOPEN) != null -> { Escaped(parse(expr)) } expr is KerboScriptNumber -> Number(expr) expr is KerboScriptSciNumber -> Number(expr) else -> throw SyntaxException("Invalid atom: " + atom.text) } } @JvmStatic fun toAtom(expression: Expression?): Atom = expression as? Atom ?: Escaped(expression) } }
gpl-3.0
df7aebf9675f3b51989a4298960b1d31
30.775
94
0.576711
4.475352
false
false
false
false
y2k/JoyReactor
android/src/main/kotlin/y2k/joyreactor/common/ViewBinding.kt
1
11549
package y2k.joyreactor.common import android.app.Activity import android.app.Dialog import android.app.ProgressDialog import android.content.Context import android.graphics.Color import android.net.Uri import android.support.design.widget.Snackbar import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.RecyclerView import android.text.Editable import android.view.View import android.view.ViewGroup import android.widget.* import y2k.joyreactor.App import y2k.joyreactor.R import y2k.joyreactor.model.Group import y2k.joyreactor.model.Image import y2k.joyreactor.widget.* import java.io.File /** * Created by y2k on 2/23/16. */ fun View.command(command: () -> Unit) = setOnClickListener { command() } fun View.command(id: Int, command: () -> Unit): View { findViewById(id).setOnClickListener { command() } return this } fun bindingBuilder(root: View, init: BindingBuilder.() -> Unit): View { BindingBuilder(ViewGroupResolver(root), root.context).init() return root } fun bindingBuilder(root: ViewResolver, init: BindingBuilder.() -> Unit) { BindingBuilder(root).init() } fun bindingBuilder(root: Activity, init: BindingBuilder.() -> Unit) { BindingBuilder(ActivityViewResolver(root), root).init() } private class ViewGroupResolver(private val view: View) : ViewResolver { override fun <T> find(id: Int): T? { return view.findOrNull<T>(id) } } private class ActivityViewResolver(val activity: Activity) : ViewResolver { override fun <T> find(id: Int): T? { return activity.findOrNull<T>(id) } } class BindingBuilder(root: ViewResolver, val context: Context = App.instance) { val resolvers = arrayListOf(root) fun blockProgressDialog(property: ObservableProperty<Boolean>) { val dialog = ProgressDialog(context).apply { setMessage(context.getString(R.string.please_wait)) setCancelable(false) } property.subscribe { if (it) dialog.show() else dialog.hide() } } fun snackbar(viewId: Int, stringRes: Int, property: ObservableProperty<Boolean>) { val snackbar = Snackbar.make(find(viewId), stringRes, Snackbar.LENGTH_INDEFINITE) snackbar.setActionTextColor(Color.WHITE) property.subscribe { if (it) snackbar.show() else snackbar.dismiss() } } fun blockDialog(dialog: Dialog, property: ObservableProperty<Boolean>) { property.subscribe { dialog.setCancelable(!it) } } fun menu(menuId: Int, init: MenuBinding.() -> Unit) { MenuBinding(menuId, resolvers).init() } fun spinnerTemp(id: Int, property: ObservableProperty<Group.Quality>) { val view = find<Spinner>(id) property.subscribe { view.setSelection(it.ordinal) } view.onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { property += Group.Quality.valueOf(Group.Quality.values()[position].name) } } } fun spinner(id: Int, property: ObservableProperty<Int>) { val view = find<Spinner>(id) property.subscribe { view.setSelection(it) } view.onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { property += position } } } fun animator(id: Int, property: ObservableProperty<Boolean>) { animator(id, property) { if (it) 1 else (0) } } fun <T> animator(id: Int, property: ObservableProperty<T>, convert: (T) -> Int) { val view = find<ViewAnimator>(id) property.subscribe { view.displayedChild = convert(it) } } fun progressBar(id: Int, property: ObservableProperty<Float>) { val view = find<ProgressBar>(id) property.subscribe { view.progress = it.toInt() } } fun ratingBar(id: Int, property: ObservableProperty<Float>) { val view = find<RatingBar>(id) property.subscribe { view.rating = it } } fun webImageView(id: Int, property: ObservableProperty<Image?>) { val view = find<WebImageView>(id) property.subscribe { view.image = it } } fun muteVideoView(id: Int, property: ObservableProperty<File?>) { val view = find<MuteVideoView>(id) property.subscribe { it?.let { view.play(it) } } } fun viewResolver(id: Int) { resolvers.add(find<ViewResolver>(id)) } fun refreshLayout(id: Int, init: SwipeRefreshLayoutBinding.() -> Unit) { SwipeRefreshLayoutBinding(find<SwipeRefreshLayout>(id)).init() } fun view(id: Int, init: ViewBinding.() -> Unit) { ViewBinding(find<View>(id)).init() } fun command(id: Int, f: () -> Unit) { find<View>(id).setOnClickListener { f() } } fun <T> action(property: ObservableProperty<T>, f: (T) -> Unit) { property.subscribe(f) } fun <T> recyclerView(id: Int, property: ObservableProperty<out List<T>>, init: DslRecyclerView<T>.() -> Unit) { val view = find<RecyclerView>(id) val dsl = DslRecyclerView<T>() dsl.init() // TODO: разобраться с конвертирование view.adapter = dsl.build().apply { property.subscribe { update(it as List<T>) } } } fun <T> textView(id: Int, property: ObservableProperty<T>) { val view = find<TextView>(id) property.subscribe { if (view.text.toString() != it.toString()) view.text = it.toString() } } fun fixedAspectPanel(id: Int, property: ObservableProperty<Float>) { val view = find<FixedAspectPanel>(id) property.subscribe { view.aspect = it } } fun progressImageView(id: Int, property: ObservableProperty<File?>) { val view = find<ProgressImageView>(id) property.subscribe { view.setImage(it) } } fun imageView(id: Int, property: ObservableProperty<File?>) { val view = find<ImageView>(id) property.subscribe { view.setImageURI(it?.let { Uri.fromFile(it) }) } } fun tagsView(id: Int, property: ObservableProperty<List<String>>) { val view = find<TagsView>(id) property.subscribe { view.tags = it } } fun editText(id: Int, property: ObservableProperty<String>) { val view = find<EditText>(id) property.subscribe { if (view.text.toString() != it) view.setText(it) } view.addTextChangedListener(object : TextWatcherAdapter() { override fun afterTextChanged(s: Editable?) { property += "" + s } }) } fun <T> visibility(id: Int, property: ObservableProperty<T>, converter: (T) -> Boolean) { val view = find<View>(id) property.subscribe { view.visibility = if (converter(it)) View.VISIBLE else View.GONE } } fun visibility(id: Int, property: ObservableProperty<Boolean>, invert: Boolean = false) { val view = find<View>(id) property.subscribe { if (invert) view.visibility = if (it) View.GONE else View.VISIBLE else view.visibility = if (it) View.VISIBLE else View.GONE } } fun <T : Any> find(id: Int): T { return resolvers.mapNotNull { it.find<T>(id) }.first() } fun <T> bind(id: Int, property: ObservableProperty<T>) { val view = find<BindableComponent<T>>(id) property.subscribe { view.value += it } } fun command(id: Int, command: String, f: () -> Unit) { val view = find<View>(id) view.javaClass.getMethod(toSetterName(command), Function0::class.java).invoke(view, f) } fun <T> command(id: Int, command: String, f: (T) -> Unit) { val view = find<View>(id) view.javaClass.getMethod(toSetterName(command), Function1::class.java).invoke(view, f) } private fun toSetterName(prop: String) = "set${prop.substring(0, 1).toUpperCase()}${prop.substring(1)}" } interface BindableComponent<T> { val value: ObservableProperty<T> } class MenuBinding(menuId: Int, resolvers: List<ViewResolver>) { private val menu = MenuHolder(menuId) init { val activity = resolvers .filterIsInstance(ActivityViewResolver::class.java) .map { it.activity as BaseActivity } .first() activity.menuHolder = menu } fun command(id: Int, command: () -> Unit) { menu.addAction(id, command) } } class SwipeRefreshLayoutBinding(private val view: SwipeRefreshLayout) { fun isRefreshing(property: ObservableProperty<Boolean>) { property.subscribe { view.post { view.isRefreshing = it } } } fun command(func: () -> Unit) { view.setOnRefreshListener(func) } } class DslRecyclerView<T> { private lateinit var createVH: (ViewGroup, Int) -> ListViewHolder<T> private var getItemId: ((T) -> Long)? = null private var viewTypeFactory: (ItemViewTypeProperties<T>) -> Int = { 0 } fun itemViewType(f: (ItemViewTypeProperties<T>) -> Int) { viewTypeFactory = f } fun itemId(getItemId: (T) -> Long) { this.getItemId = getItemId } fun viewHolderWithType(createVH: (ViewGroup, Int) -> ListViewHolder<T>) { this.createVH = createVH } fun component(f: (ViewGroup) -> View) { viewHolder { BindableListViewHolder(f(it)) } } fun viewHolder(createVH: (ViewGroup) -> ListViewHolder<T>) { this.createVH = { v, i -> createVH(v) } } fun build(): ListAdapter<T, ListViewHolder<T>> { return object : ListAdapter<T, ListViewHolder<T>>() { init { setHasStableIds(getItemId != null) } override fun getItemViewType(position: Int): Int { return viewTypeFactory(ItemViewTypeProperties(items[position], items, position)) } override fun getItemId(position: Int): Long { return getItemId?.invoke(items[position]) ?: 0L } override fun onBindViewHolder(holder: ListViewHolder<T>, position: Int) { holder.update(items[position]) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder<T>? { return createVH(parent, viewType) } } } class ItemViewTypeProperties<T>(val value: T, val items: List<T>, val position: Int) } class BindableListViewHolder<T>(view: View) : ListViewHolder<T>(view) { @Suppress("UNCHECKED_CAST") val component = view as BindableComponent<T> init { view.layoutParams = ViewGroup.MarginLayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } override fun update(item: T) { component.value += item } } abstract class ListViewHolder<T>(view: View) : RecyclerView.ViewHolder(view) { abstract fun update(item: T) } class ViewBinding(private val view: View) { fun visibility(property: ObservableProperty<Boolean>) { property.subscribe { view.visibility = if (it) View.VISIBLE else View.GONE } } } interface ViewResolver { fun <T> find(id: Int): T? }
gpl-2.0
19036eae262c0bed97a0f974458ee1fc
30.569863
115
0.634699
4.10913
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/users/dto/UsersUserMin.kt
1
2325
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.users.dto import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import kotlin.Boolean import kotlin.Int import kotlin.String /** * @param id - User ID * @param deactivated - Returns if a profile is deleted or blocked * @param firstName - User first name * @param hidden - Returns if a profile is hidden. * @param lastName - User last name * @param canAccessClosed * @param isClosed */ data class UsersUserMin( @SerializedName("id") val id: UserId, @SerializedName("deactivated") val deactivated: String? = null, @SerializedName("first_name") val firstName: String? = null, @SerializedName("hidden") val hidden: Int? = null, @SerializedName("last_name") val lastName: String? = null, @SerializedName("can_access_closed") val canAccessClosed: Boolean? = null, @SerializedName("is_closed") val isClosed: Boolean? = null )
mit
5c5d75c7ab08b9520ca8c05d693ee768
37.75
81
0.685161
4.411765
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/utils/SystemUiUtils.kt
1
5783
package com.reactnativenavigation.utils import android.app.Activity import android.graphics.Color import android.graphics.Rect import android.os.Build import android.view.View import android.view.Window import androidx.annotation.ColorInt import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import kotlin.math.abs import kotlin.math.ceil object SystemUiUtils { private const val STATUS_BAR_HEIGHT_M = 24 private const val STATUS_BAR_HEIGHT_L = 25 internal const val STATUS_BAR_HEIGHT_TRANSLUCENCY = 0.65f private var statusBarHeight = -1 var navigationBarDefaultColor = -1 private set @JvmStatic fun getStatusBarHeight(activity: Activity?): Int { val res = if (statusBarHeight > 0) { statusBarHeight } else { statusBarHeight = activity?.let { val rectangle = Rect() val window: Window = activity.window window.decorView.getWindowVisibleDisplayFrame(rectangle) val statusBarHeight: Int = rectangle.top val contentView = window.findViewById<View>(Window.ID_ANDROID_CONTENT) contentView?.let { val contentViewTop = contentView.top abs(contentViewTop - statusBarHeight) } } ?: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) STATUS_BAR_HEIGHT_M else STATUS_BAR_HEIGHT_L statusBarHeight } return res } @JvmStatic fun saveStatusBarHeight(height: Int) { statusBarHeight = height } @JvmStatic fun getStatusBarHeightDp(activity: Activity?): Int { return UiUtils.pxToDp(activity, getStatusBarHeight(activity).toFloat()) .toInt() } @JvmStatic fun hideNavigationBar(window: Window?, view: View) { window?.let { WindowCompat.setDecorFitsSystemWindows(window, false) WindowInsetsControllerCompat(window, view).let { controller -> controller.hide(WindowInsetsCompat.Type.navigationBars()) controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } } } @JvmStatic fun showNavigationBar(window: Window?, view: View) { window?.let { WindowCompat.setDecorFitsSystemWindows(window, true) WindowInsetsControllerCompat(window, view).show(WindowInsetsCompat.Type.navigationBars()) } } @JvmStatic fun setStatusBarColorScheme(window: Window?, view: View, isDark: Boolean) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return window?.let { WindowInsetsControllerCompat(window, view).isAppearanceLightStatusBars = isDark // Workaround: on devices with api 30 status bar icons flickers or get hidden when removing view //turns out it is a bug on such devices, fixed by using system flags until it is fixed. var flags = view.systemUiVisibility flags = if (isDark) { flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() } view.systemUiVisibility = flags } } @JvmStatic fun setStatusBarTranslucent(window: Window?) { window?.let { setStatusBarColor(window, window.statusBarColor, true) } } @JvmStatic fun isTranslucent(window: Window?): Boolean { return window?.let { Color.alpha(it.statusBarColor) < 255 } ?: false } @JvmStatic fun clearStatusBarTranslucency(window: Window?) { window?.let { setStatusBarColor(it, it.statusBarColor, false) } } @JvmStatic fun setStatusBarColor( window: Window?, @ColorInt color: Int, translucent: Boolean ) { val opaqueColor = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Color.BLACK }else{ val colorAlpha = Color.alpha(color) val alpha = if (translucent && colorAlpha == 255) STATUS_BAR_HEIGHT_TRANSLUCENCY else colorAlpha/255.0f val red: Int = Color.red(color) val green: Int = Color.green(color) val blue: Int = Color.blue(color) Color.argb(ceil(alpha * 255).toInt(), red, green, blue) } window?.statusBarColor = opaqueColor } @JvmStatic fun hideStatusBar(window: Window?, view: View) { window?.let { WindowCompat.setDecorFitsSystemWindows(window, false) WindowInsetsControllerCompat(window, view).let { controller -> controller.hide(WindowInsetsCompat.Type.statusBars()) controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } } } @JvmStatic fun showStatusBar(window: Window?, view: View) { window?.let { WindowCompat.setDecorFitsSystemWindows(window, true) WindowInsetsControllerCompat(window, view).show(WindowInsetsCompat.Type.statusBars()) } } @JvmStatic fun setNavigationBarBackgroundColor(window: Window?, color: Int, lightColor: Boolean) { window?.let { if (navigationBarDefaultColor == -1) { navigationBarDefaultColor = window.navigationBarColor } WindowInsetsControllerCompat(window, window.decorView).let { controller -> controller.isAppearanceLightNavigationBars = lightColor } window.navigationBarColor = color } } }
mit
c4ecb1c524febb1294a53ee5c0129802
33.224852
115
0.630296
5.028696
false
false
false
false
caot/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/DebugProcessImpl.kt
4
9141
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.execution.ExecutionResult import com.intellij.execution.process.ProcessHandler import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Url import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.socketConnection.ConnectionStatus import com.intellij.util.io.socketConnection.SocketConnectionListener import com.intellij.xdebugger.DefaultDebugProcessHandler import com.intellij.xdebugger.XDebugProcess import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.breakpoints.XBreakpoint import com.intellij.xdebugger.breakpoints.XBreakpointHandler import com.intellij.xdebugger.breakpoints.XLineBreakpoint import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider import com.intellij.xdebugger.frame.XSuspendContext import com.intellij.xdebugger.stepping.XSmartStepIntoHandler import org.jetbrains.concurrency.AsyncFunction import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.connection.VmConnection import org.jetbrains.debugger.frame.SuspendContextImpl import java.util.concurrent.ConcurrentMap import java.util.concurrent.atomic.AtomicBoolean import kotlin.properties.Delegates public abstract class DebugProcessImpl<C : VmConnection<*>>(session: XDebugSession, public val connection: C, private val editorsProvider: XDebuggerEditorsProvider, private val smartStepIntoHandler: XSmartStepIntoHandler<*>?, protected val executionResult: ExecutionResult?) : XDebugProcess(session) { protected val repeatStepInto: AtomicBoolean = AtomicBoolean() volatile protected var lastStep: StepAction? = null volatile protected var lastCallFrame: CallFrame? = null volatile protected var isForceStep: Boolean = false volatile protected var disableDoNotStepIntoLibraries: Boolean = false protected val urlToFileCache: ConcurrentMap<Url, VirtualFile> = ContainerUtil.newConcurrentMap<Url, VirtualFile>() private var processBreakpointConditionsAtIdeSide = false private val _breakpointHandlers: Array<XBreakpointHandler<*>> by Delegates.lazy { createBreakpointHandlers() } init { connection.addListener(object : SocketConnectionListener { override fun statusChanged(status: ConnectionStatus) { if (status === ConnectionStatus.DISCONNECTED || status === ConnectionStatus.DETACHED) { if (status === ConnectionStatus.DETACHED) { if (getRealProcessHandler() != null) { // here must we must use effective process handler getProcessHandler().detachProcess() } } getSession().stop() } else { getSession().rebuildViews() } } }) } protected final fun getRealProcessHandler(): ProcessHandler? = executionResult?.getProcessHandler() override final fun getSmartStepIntoHandler() = smartStepIntoHandler override final fun getBreakpointHandlers() = _breakpointHandlers override final fun getEditorsProvider() = editorsProvider public fun setProcessBreakpointConditionsAtIdeSide(value: Boolean) { processBreakpointConditionsAtIdeSide = value } public fun getVm(): Vm? = connection.getVm() protected abstract fun createBreakpointHandlers(): Array<XBreakpointHandler<*>> private fun updateLastCallFrame() { lastCallFrame = getVm()?.getSuspendContextManager()?.getContext()?.getTopFrame() } override final fun checkCanPerformCommands() = getVm() != null override final fun isValuesCustomSorted() = true override final fun startStepOver() { updateLastCallFrame() continueVm(StepAction.OVER) } override final fun startForceStepInto() { isForceStep = true startStepInto() } override final fun startStepInto() { updateLastCallFrame() continueVm(StepAction.IN) } override final fun startStepOut() { if (isVmStepOutCorrect()) { lastCallFrame = null } else { updateLastCallFrame() } continueVm(StepAction.OUT) } // some VM (firefox for example) doesn't implement step out correctly, so, we need to fix it protected open fun isVmStepOutCorrect(): Boolean = true override final fun resume() { continueVm(StepAction.CONTINUE) } protected final fun continueVm(stepAction: StepAction) { val suspendContextManager = getVm()!!.getSuspendContextManager() if (stepAction === StepAction.CONTINUE) { if (suspendContextManager.getContext() == null) { // on resumed we ask session to resume, and session then call our "resume", but we have already resumed, so, we don't need to send "continue" message return } lastStep = null lastCallFrame = null urlToFileCache.clear() disableDoNotStepIntoLibraries = false } else { lastStep = stepAction } suspendContextManager.continueVm(stepAction, 1) } protected final fun setOverlay() { getVm()!!.getSuspendContextManager().setOverlayMessage("Paused in debugger") } protected final fun processBreakpoint(suspendContext: SuspendContext, breakpoint: XBreakpoint<*>, xSuspendContext: SuspendContextImpl) { val condition = breakpoint.getConditionExpression()?.getExpression() if (!processBreakpointConditionsAtIdeSide || condition == null) { processBreakpointLogExpressionAndSuspend(breakpoint, xSuspendContext, suspendContext) } else { xSuspendContext.evaluateExpression(condition) .done(object : ContextDependentAsyncResultConsumer<String>(suspendContext) { override fun consume(evaluationResult: String, vm: Vm) { if ("false" == evaluationResult) { resume() } else { processBreakpointLogExpressionAndSuspend(breakpoint, xSuspendContext, suspendContext) } } }) .rejected(object : ContextDependentAsyncResultConsumer<Throwable>(suspendContext) { override fun consume(failure: Throwable, vm: Vm) { processBreakpointLogExpressionAndSuspend(breakpoint, xSuspendContext, suspendContext) } }) } } private fun processBreakpointLogExpressionAndSuspend(breakpoint: XBreakpoint<*>, xSuspendContext: SuspendContextImpl, suspendContext: SuspendContext) { val logExpression = breakpoint.getLogExpressionObject()?.getExpression() if (logExpression == null) { breakpointReached(breakpoint, null, xSuspendContext) } else { xSuspendContext.evaluateExpression(logExpression) .done(object : ContextDependentAsyncResultConsumer<String>(suspendContext) { override fun consume(logResult: String, vm: Vm) { breakpointReached(breakpoint, logResult, xSuspendContext) } }) .rejected(object : ContextDependentAsyncResultConsumer<Throwable>(suspendContext) { override fun consume(logResult: Throwable, vm: Vm) { breakpointReached(breakpoint, "Failed to evaluate expression: " + logExpression, xSuspendContext) } }) } } private fun breakpointReached(breakpoint: XBreakpoint<*>, evaluatedLogExpression: String?, suspendContext: XSuspendContext) { if (getSession().breakpointReached(breakpoint, evaluatedLogExpression, suspendContext)) { setOverlay() } else { resume() } } override final fun startPausing() { connection.getVm().getSuspendContextManager().suspend().rejected(RejectErrorReporter(getSession(), "Cannot pause")) } override final fun getCurrentStateMessage() = connection.getState().getMessage() override final fun getCurrentStateHyperlinkListener() = connection.getState().getMessageLinkListener() override fun doGetProcessHandler() = executionResult?.getProcessHandler() ?: object : DefaultDebugProcessHandler() { override fun isSilentlyDestroyOnClose() = true } public fun saveResolvedFile(url: Url, file: VirtualFile) { urlToFileCache.putIfAbsent(url, file) } public abstract fun getLocationsForBreakpoint(breakpoint: XLineBreakpoint<*>, onlySourceMappedBreakpoints: Boolean): List<Location> } public inline fun asyncPromise(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) task: () -> Promise<Void>): AsyncFunction<Void, Void> = object : AsyncFunction<Void, Void> { override fun `fun`(aVoid: Void?) = task() }
apache-2.0
8c755cfd9e06b4b7e5677320c4dbd305
38.747826
169
0.719615
5.268588
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/achievement/ui/resolver/AchievementResourceResolver.kt
2
5673
package org.stepik.android.view.achievement.ui.resolver import android.content.Context import org.stepic.droid.R import org.stepic.droid.di.AppSingleton import org.stepik.android.domain.achievement.model.AchievementItem import org.stepic.droid.util.liftM2 import javax.inject.Inject @AppSingleton class AchievementResourceResolver @Inject constructor( private val context: Context ) { companion object { private const val KIND_STEPS_SOLVED = "steps_solved" private const val KIND_STEPS_SOLVED_STREAK = "steps_solved_streak" private const val KIND_STEPS_SOLVED_CHOICE = "steps_solved_choice" private const val KIND_STEPS_SOLVED_CODE = "steps_solved_code" private const val KIND_STEPS_SOLVED_NUMBER = "steps_solved_number" private const val KIND_CODE_QUIZZES_SOLVED_PYTHON = "code_quizzes_solved_python" private const val KIND_CODE_QUIZZES_SOLVED_CPP = "code_quizzes_solved_cpp" private const val KIND_CODE_QUIZZES_SOLVED_JAVA = "code_quizzes_solved_java" private const val KIND_ACTIVE_DAYS_STREAK = "active_days_streak" private const val KIND_CERTIFICATES_REGULAR_COUNT = "certificates_regular_count" private const val KIND_CERTIFICATES_DISTINCTION_COUNT = "certificates_distinction_count" private const val KIND_COURSE_REVIEWS_COUNT = "course_reviews_count" } private val kindToTitleResId = mapOf( KIND_STEPS_SOLVED to R.string.achievement_steps_solved_title, KIND_STEPS_SOLVED_STREAK to R.string.achievement_steps_solved_streak_title, KIND_STEPS_SOLVED_CHOICE to R.string.achievement_steps_solved_choice_title, KIND_STEPS_SOLVED_CODE to R.string.achievement_steps_solved_code_title, KIND_STEPS_SOLVED_NUMBER to R.string.achievement_steps_solved_number_title, KIND_CODE_QUIZZES_SOLVED_PYTHON to R.string.achievement_code_quizzes_solved_python_title, KIND_CODE_QUIZZES_SOLVED_CPP to R.string.achievement_code_quizzes_solved_cpp_title, KIND_CODE_QUIZZES_SOLVED_JAVA to R.string.achievement_code_quizzes_solved_java_title, KIND_ACTIVE_DAYS_STREAK to R.string.achievement_active_days_streak_title, KIND_CERTIFICATES_REGULAR_COUNT to R.string.achievement_certificates_regular_count_title, KIND_CERTIFICATES_DISTINCTION_COUNT to R.string.achievement_certificates_distinction_count_title, KIND_COURSE_REVIEWS_COUNT to R.string.achievement_course_reviews_count_title ) private val kindToDescriptionResID = mapOf( KIND_STEPS_SOLVED to R.string.achievement_steps_solved_description, KIND_STEPS_SOLVED_STREAK to R.string.achievement_steps_solved_streak_description, KIND_STEPS_SOLVED_CHOICE to R.string.achievement_steps_solved_choice_description, KIND_STEPS_SOLVED_CODE to R.string.achievement_steps_solved_code_description, KIND_STEPS_SOLVED_NUMBER to R.string.achievement_steps_solved_number_description, KIND_CODE_QUIZZES_SOLVED_PYTHON to R.string.achievement_code_quizzes_solved_python_description, KIND_CODE_QUIZZES_SOLVED_CPP to R.string.achievement_code_quizzes_solved_cpp_description, KIND_CODE_QUIZZES_SOLVED_JAVA to R.string.achievement_code_quizzes_solved_java_description, KIND_ACTIVE_DAYS_STREAK to R.string.achievement_active_days_streak_description, KIND_CERTIFICATES_REGULAR_COUNT to R.string.achievement_certificates_regular_count_description, KIND_CERTIFICATES_DISTINCTION_COUNT to R.string.achievement_certificates_distinction_count_description, KIND_COURSE_REVIEWS_COUNT to R.string.achievement_course_reviews_count_description ) private val kindToPluralResID = mapOf( KIND_STEPS_SOLVED to R.plurals.task, KIND_STEPS_SOLVED_STREAK to R.plurals.task, KIND_STEPS_SOLVED_CHOICE to R.plurals.task, KIND_STEPS_SOLVED_CODE to R.plurals.task, KIND_STEPS_SOLVED_NUMBER to R.plurals.task, KIND_CODE_QUIZZES_SOLVED_PYTHON to R.plurals.problem, KIND_CODE_QUIZZES_SOLVED_CPP to R.plurals.problem, KIND_CODE_QUIZZES_SOLVED_JAVA to R.plurals.problem, KIND_ACTIVE_DAYS_STREAK to R.plurals.day, KIND_CERTIFICATES_REGULAR_COUNT to R.plurals.certificate, KIND_CERTIFICATES_DISTINCTION_COUNT to R.plurals.certificate, KIND_COURSE_REVIEWS_COUNT to R.plurals.course_review ) fun resolveTitleForKind(kind: String): String = context.getString(kindToTitleResId[kind] ?: R.string.achievement_unknown_title) fun resolveDescription(achievementItem: AchievementItem): String = kindToPluralResID[achievementItem.kind].liftM2(kindToDescriptionResID[achievementItem.kind]) { plural, description -> context.getString(description, context.resources.getQuantityString(plural, achievementItem.targetScore, achievementItem.targetScore)) } ?: context.getString(R.string.achievement_unknown_description) fun resolveAchievementIcon(achievementItem: AchievementItem, size: Int): String = when { achievementItem.isLocked || achievementItem.currentLevel == 0 -> "file:///android_asset/images/vector/achievements/ic_empty_achievement.svg" achievementItem.uploadcareUUID != null -> "https://ucarecdn.com/${achievementItem.uploadcareUUID}/-/resize/${size}x$size/" else -> "file:///android_asset/images/vector/achievements/${achievementItem.kind}/${achievementItem.currentLevel}.svg" } }
apache-2.0
ac600f05a6bbe6b2282d0f302ece97e1
58.726316
145
0.718139
3.896291
false
false
false
false
Bios-Marcel/ServerBrowser
src/main/kotlin/com/msc/serverbrowser/gui/views/FilesView.kt
1
4256
package com.msc.serverbrowser.gui.views import com.msc.serverbrowser.Client import javafx.beans.property.BooleanProperty import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleStringProperty import javafx.beans.property.StringProperty import javafx.event.ActionEvent import javafx.event.EventHandler import javafx.geometry.Pos import javafx.scene.control.Button import javafx.scene.control.ButtonBar import javafx.scene.control.CheckBox import javafx.scene.control.Tab import javafx.scene.control.TabPane import javafx.scene.control.TabPane.TabClosingPolicy import javafx.scene.control.TextField import javafx.scene.layout.HBox import javafx.scene.layout.Priority import javafx.scene.layout.VBox import javafx.scene.web.WebView /** * View for interacting with SA-MP files. * * * Contains: * * * chatlog viewer * * * * @author Marcel * @since 14.01.2018 */ class FilesView{ /** * Root-container of this view. */ val rootPane: TabPane private val chatLogTextArea: WebView = WebView() private val clearLogsButton: Button private val loadLogsButton: Button /** * @return [.showTimesIfAvailableProperty] */ val showTimesIfAvailableProperty: BooleanProperty = SimpleBooleanProperty(false) /** * @return [.showColorsProperty] */ val showColorsProperty: BooleanProperty = SimpleBooleanProperty(false) /** * @return [.showColorsAsTextProperty] */ val showColorsAsTextProperty: BooleanProperty = SimpleBooleanProperty(false) /** * @return [.lineFilterProperty] */ val lineFilterProperty: StringProperty = SimpleStringProperty("") /** * Initializes the whole view. */ init { clearLogsButton = Button(Client.getString("clear")) loadLogsButton = Button(Client.getString("reload")) val buttonBar = ButtonBar() buttonBar.buttons.addAll(loadLogsButton, clearLogsButton) val showTimesCheckBox = CheckBox(Client.getString("showTimestamps")) showTimesIfAvailableProperty.bind(showTimesCheckBox.selectedProperty()) setupCheckBox(showTimesCheckBox) val showColorsCheckBox = CheckBox(Client.getString("showChatlogColors")) showColorsProperty.bind(showColorsCheckBox.selectedProperty()) setupCheckBox(showColorsCheckBox) val showColorsAsTextCheckBox = CheckBox(Client.getString("showChatlogColorsAsText")) showColorsAsTextProperty.bind(showColorsAsTextCheckBox.selectedProperty()) setupCheckBox(showColorsAsTextCheckBox) val filterTextField = TextField() filterTextField.promptText = Client.getString("enterFilterValue") lineFilterProperty.bind(filterTextField.textProperty()) val optionCheckBoxes = HBox(5.0, showColorsCheckBox, showTimesCheckBox, showColorsAsTextCheckBox, filterTextField) val chatLogsTabContent = VBox(5.0, chatLogTextArea, optionCheckBoxes, buttonBar) VBox.setVgrow(chatLogTextArea, Priority.ALWAYS) val chatLogsTab = Tab(Client.getString("chatlogs"), chatLogsTabContent) rootPane = TabPane(chatLogsTab) rootPane.tabClosingPolicy = TabClosingPolicy.UNAVAILABLE } /** * Adjusts the layout properties for a [CheckBox]. * * @param showColorsAsTextCheckBox [CheckBox] to adjust the properties for */ private fun setupCheckBox(showColorsAsTextCheckBox: CheckBox) { showColorsAsTextCheckBox.alignment = Pos.CENTER showColorsAsTextCheckBox.maxHeight = java.lang.Double.MAX_VALUE } /** * @param eventHandler the [ActionEvent] handler to be set */ fun setClearChatLogsButtonAction(eventHandler: EventHandler<ActionEvent>) { clearLogsButton.onAction = eventHandler } /** * @param eventHandler the [ActionEvent] handler to be set */ fun setLoadChatLogsButtonAction(eventHandler: EventHandler<ActionEvent>) { loadLogsButton.onAction = eventHandler } /** * Sets the text inside of the [.chatLogTextArea]. * * @param content the content to be set */ fun setChatLogTextAreaContent(content: String) { chatLogTextArea.engine.loadContent(content, "text/html") } }
mpl-2.0
585cf0a40c6ad429589227079b91b9ad
30.761194
122
0.725799
4.636166
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/components/Button.kt
1
15336
package eu.kanade.presentation.components import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.VectorConverter import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.interaction.FocusInteraction import androidx.compose.foundation.interaction.HoverInteraction import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.ColorScheme import androidx.compose.material3.ElevatedButton import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ProvideTextStyle import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import eu.kanade.presentation.util.animateElevation import androidx.compose.material3.ButtonDefaults as M3ButtonDefaults /** * TextButton with additional onLongClick functionality. * * @see androidx.compose.material3.TextButton */ @Composable fun TextButton( onClick: () -> Unit, modifier: Modifier = Modifier, onLongClick: (() -> Unit)? = null, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, elevation: ButtonElevation? = null, shape: Shape = M3ButtonDefaults.textShape, border: BorderStroke? = null, colors: ButtonColors = ButtonColors( containerColor = Color.Transparent, contentColor = MaterialTheme.colorScheme.primary, disabledContainerColor = Color.Transparent, disabledContentColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f), ), contentPadding: PaddingValues = M3ButtonDefaults.TextButtonContentPadding, content: @Composable RowScope.() -> Unit, ) = Button( onClick = onClick, modifier = modifier, onLongClick = onLongClick, enabled = enabled, interactionSource = interactionSource, elevation = elevation, shape = shape, border = border, colors = colors, contentPadding = contentPadding, content = content, ) /** * Button with additional onLongClick functionality. * * @see androidx.compose.material3.TextButton */ @Composable fun Button( onClick: () -> Unit, modifier: Modifier = Modifier, onLongClick: (() -> Unit)? = null, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, elevation: ButtonElevation? = ButtonDefaults.buttonElevation(), shape: Shape = M3ButtonDefaults.textShape, border: BorderStroke? = null, colors: ButtonColors = ButtonDefaults.buttonColors(), contentPadding: PaddingValues = M3ButtonDefaults.ContentPadding, content: @Composable RowScope.() -> Unit, ) { val containerColor = colors.containerColor(enabled).value val contentColor = colors.contentColor(enabled).value val shadowElevation = elevation?.shadowElevation(enabled, interactionSource)?.value ?: 0.dp val tonalElevation = elevation?.tonalElevation(enabled, interactionSource)?.value ?: 0.dp Surface( onClick = onClick, modifier = modifier, onLongClick = onLongClick, shape = shape, color = containerColor, contentColor = contentColor, tonalElevation = tonalElevation, shadowElevation = shadowElevation, border = border, interactionSource = interactionSource, enabled = enabled, ) { CompositionLocalProvider(LocalContentColor provides contentColor) { ProvideTextStyle(value = MaterialTheme.typography.labelLarge) { Row( Modifier.defaultMinSize( minWidth = M3ButtonDefaults.MinWidth, minHeight = M3ButtonDefaults.MinHeight, ) .padding(contentPadding), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content, ) } } } } object ButtonDefaults { /** * Creates a [ButtonColors] that represents the default container and content colors used in a * [Button]. * * @param containerColor the container color of this [Button] when enabled. * @param contentColor the content color of this [Button] when enabled. * @param disabledContainerColor the container color of this [Button] when not enabled. * @param disabledContentColor the content color of this [Button] when not enabled. */ @Composable fun buttonColors( containerColor: Color = MaterialTheme.colorScheme.primary, contentColor: Color = MaterialTheme.colorScheme.onPrimary, disabledContainerColor: Color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.12f), disabledContentColor: Color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f), ): ButtonColors = ButtonColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor, ) /** * Creates a [ButtonElevation] that will animate between the provided values according to the * Material specification for a [Button]. * * @param defaultElevation the elevation used when the [Button] is enabled, and has no other * [Interaction]s. * @param pressedElevation the elevation used when this [Button] is enabled and pressed. * @param focusedElevation the elevation used when the [Button] is enabled and focused. * @param hoveredElevation the elevation used when the [Button] is enabled and hovered. * @param disabledElevation the elevation used when the [Button] is not enabled. */ @Composable fun buttonElevation( defaultElevation: Dp = 0.dp, pressedElevation: Dp = 0.dp, focusedElevation: Dp = 0.dp, hoveredElevation: Dp = 1.dp, disabledElevation: Dp = 0.dp, ): ButtonElevation = ButtonElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, disabledElevation = disabledElevation, ) } /** * Represents the elevation for a button in different states. * * - See [M3ButtonDefaults.buttonElevation] for the default elevation used in a [Button]. * - See [M3ButtonDefaults.elevatedButtonElevation] for the default elevation used in a * [ElevatedButton]. */ @Stable class ButtonElevation internal constructor( private val defaultElevation: Dp, private val pressedElevation: Dp, private val focusedElevation: Dp, private val hoveredElevation: Dp, private val disabledElevation: Dp, ) { /** * Represents the tonal elevation used in a button, depending on its [enabled] state and * [interactionSource]. This should typically be the same value as the [shadowElevation]. * * Tonal elevation is used to apply a color shift to the surface to give the it higher emphasis. * When surface's color is [ColorScheme.surface], a higher elevation will result in a darker * color in light theme and lighter color in dark theme. * * See [shadowElevation] which controls the elevation of the shadow drawn around the button. * * @param enabled whether the button is enabled * @param interactionSource the [InteractionSource] for this button */ @Composable internal fun tonalElevation(enabled: Boolean, interactionSource: InteractionSource): State<Dp> { return animateElevation(enabled = enabled, interactionSource = interactionSource) } /** * Represents the shadow elevation used in a button, depending on its [enabled] state and * [interactionSource]. This should typically be the same value as the [tonalElevation]. * * Shadow elevation is used to apply a shadow around the button to give it higher emphasis. * * See [tonalElevation] which controls the elevation with a color shift to the surface. * * @param enabled whether the button is enabled * @param interactionSource the [InteractionSource] for this button */ @Composable internal fun shadowElevation( enabled: Boolean, interactionSource: InteractionSource, ): State<Dp> { return animateElevation(enabled = enabled, interactionSource = interactionSource) } @Composable private fun animateElevation( enabled: Boolean, interactionSource: InteractionSource, ): State<Dp> { val interactions = remember { mutableStateListOf<Interaction>() } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is HoverInteraction.Enter -> { interactions.add(interaction) } is HoverInteraction.Exit -> { interactions.remove(interaction.enter) } is FocusInteraction.Focus -> { interactions.add(interaction) } is FocusInteraction.Unfocus -> { interactions.remove(interaction.focus) } is PressInteraction.Press -> { interactions.add(interaction) } is PressInteraction.Release -> { interactions.remove(interaction.press) } is PressInteraction.Cancel -> { interactions.remove(interaction.press) } } } } val interaction = interactions.lastOrNull() val target = if (!enabled) { disabledElevation } else { when (interaction) { is PressInteraction.Press -> pressedElevation is HoverInteraction.Enter -> hoveredElevation is FocusInteraction.Focus -> focusedElevation else -> defaultElevation } } val animatable = remember { Animatable(target, Dp.VectorConverter) } if (!enabled) { // No transition when moving to a disabled state LaunchedEffect(target) { animatable.snapTo(target) } } else { LaunchedEffect(target) { val lastInteraction = when (animatable.targetValue) { pressedElevation -> PressInteraction.Press(Offset.Zero) hoveredElevation -> HoverInteraction.Enter() focusedElevation -> FocusInteraction.Focus() else -> null } animatable.animateElevation( from = lastInteraction, to = interaction, target = target, ) } } return animatable.asState() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is ButtonElevation) return false if (defaultElevation != other.defaultElevation) return false if (pressedElevation != other.pressedElevation) return false if (focusedElevation != other.focusedElevation) return false if (hoveredElevation != other.hoveredElevation) return false if (disabledElevation != other.disabledElevation) return false return true } override fun hashCode(): Int { var result = defaultElevation.hashCode() result = 31 * result + pressedElevation.hashCode() result = 31 * result + focusedElevation.hashCode() result = 31 * result + hoveredElevation.hashCode() result = 31 * result + disabledElevation.hashCode() return result } } /** * Represents the container and content colors used in a button in different states. * * - See [M3ButtonDefaults.buttonColors] for the default colors used in a [Button]. * - See [M3ButtonDefaults.elevatedButtonColors] for the default colors used in a [ElevatedButton]. * - See [M3ButtonDefaults.textButtonColors] for the default colors used in a [TextButton]. */ @Immutable class ButtonColors internal constructor( private val containerColor: Color, private val contentColor: Color, private val disabledContainerColor: Color, private val disabledContentColor: Color, ) { /** * Represents the container color for this button, depending on [enabled]. * * @param enabled whether the button is enabled */ @Composable internal fun containerColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) containerColor else disabledContainerColor) } /** * Represents the content color for this button, depending on [enabled]. * * @param enabled whether the button is enabled */ @Composable internal fun contentColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) contentColor else disabledContentColor) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is ButtonColors) return false if (containerColor != other.containerColor) return false if (contentColor != other.contentColor) return false if (disabledContainerColor != other.disabledContainerColor) return false if (disabledContentColor != other.disabledContentColor) return false return true } override fun hashCode(): Int { var result = containerColor.hashCode() result = 31 * result + contentColor.hashCode() result = 31 * result + disabledContainerColor.hashCode() result = 31 * result + disabledContentColor.hashCode() return result } }
apache-2.0
c5beb975a57090256a8115eb66313a88
38.73057
100
0.672992
5.424832
false
false
false
false
apollostack/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/file/OperationBuilder.kt
1
6893
package com.apollographql.apollo3.compiler.codegen.file import com.apollographql.apollo3.api.Mutation import com.apollographql.apollo3.api.Query import com.apollographql.apollo3.api.QueryDocumentMinifier import com.apollographql.apollo3.api.Subscription import com.apollographql.apollo3.compiler.applyIf import com.apollographql.apollo3.compiler.codegen.CgContext import com.apollographql.apollo3.compiler.codegen.CgFile import com.apollographql.apollo3.compiler.codegen.CgFileBuilder import com.apollographql.apollo3.compiler.codegen.Identifier.OPERATION_DOCUMENT import com.apollographql.apollo3.compiler.codegen.Identifier.OPERATION_ID import com.apollographql.apollo3.compiler.codegen.Identifier.OPERATION_NAME import com.apollographql.apollo3.compiler.codegen.Identifier.document import com.apollographql.apollo3.compiler.codegen.Identifier.id import com.apollographql.apollo3.compiler.codegen.Identifier.name import com.apollographql.apollo3.compiler.codegen.helpers.makeDataClass import com.apollographql.apollo3.compiler.codegen.helpers.maybeAddDescription import com.apollographql.apollo3.compiler.codegen.helpers.toNamedType import com.apollographql.apollo3.compiler.codegen.helpers.toParameterSpec import com.apollographql.apollo3.compiler.codegen.model.ModelBuilder import com.apollographql.apollo3.compiler.unified.ir.IrOperation import com.apollographql.apollo3.compiler.unified.ir.IrOperationType import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.asTypeName class OperationBuilder( private val context: CgContext, private val generateFilterNotNull: Boolean, private val operationId: String, private val generateQueryDocument: Boolean, private val operation: IrOperation, ): CgFileBuilder { private val layout = context.layout private val packageName = layout.operationPackageName(operation.filePath) private val simpleName = layout.operationName(operation) private val dataSuperClassName = when (operation.operationType) { IrOperationType.Query -> Query.Data::class IrOperationType.Mutation -> Mutation.Data::class IrOperationType.Subscription -> Subscription.Data::class }.asClassName() val modelBuilders = operation.modelGroups.flatMap { it.models }.map { ModelBuilder( context = context, model = it, superClassName = if (it.id == operation.dataModelId) dataSuperClassName else null, path = listOf(packageName, simpleName) ) } override fun prepare() { context.resolver.registerOperation( operation.name, ClassName(packageName, simpleName) ) modelBuilders.forEach { it.prepare() } } override fun build(): CgFile { return CgFile( packageName = packageName, fileName = simpleName, typeSpecs = listOf(typeSpec()) ) } fun typeSpec(): TypeSpec { return TypeSpec.classBuilder(layout.operationName(operation)) .addSuperinterface(superInterfaceType()) .maybeAddDescription(operation.description) .makeDataClass(operation.variables.map { it.toNamedType().toParameterSpec(context) }) .addFunction(operationIdFunSpec()) .addFunction(queryDocumentFunSpec(generateQueryDocument)) .addFunction(nameFunSpec()) .addFunction(serializeVariablesFunSpec()) .addFunction(adapterFunSpec()) .addFunction(responseFieldsFunSpec()) .addTypes(dataTypeSpecs()) .addType(companionTypeSpec()) .build() .maybeAddFilterNotNull(generateFilterNotNull) } private fun serializeVariablesFunSpec(): FunSpec = serializeVariablesFunSpec( adapterClassName = context.resolver.resolveOperationVariablesAdapter(operation.name), emptyMessage = "This operation doesn't have any variable" ) private fun adapterFunSpec(): FunSpec { return adapterFunSpec( adapterTypeName = context.resolver.resolveModelAdapter(operation.dataModelId), adaptedTypeName = context.resolver.resolveModel(operation.dataModelId) ) } private fun dataTypeSpecs(): List<TypeSpec> { return modelBuilders.map { it.build() } } private fun superInterfaceType(): TypeName { return when (operation.operationType) { IrOperationType.Query -> Query::class.asTypeName() IrOperationType.Mutation -> Mutation::class.asTypeName() IrOperationType.Subscription -> Subscription::class.asTypeName() }.parameterizedBy( context.resolver.resolveModel(operation.dataModelId) ) } private fun operationIdFunSpec() = FunSpec.builder(id) .addModifiers(KModifier.OVERRIDE) .returns(String::class) .addStatement("return $OPERATION_ID") .build() private fun queryDocumentFunSpec(generateQueryDocument: Boolean) = FunSpec.builder(document) .addModifiers(KModifier.OVERRIDE) .returns(String::class) .apply { if (generateQueryDocument) { addStatement("return $OPERATION_DOCUMENT") } else { addStatement("error(\"The query document was removed from this operation. Use generateQueryDocument = true if you need it\"") } } .build() private fun nameFunSpec() = FunSpec.builder(name) .addModifiers(KModifier.OVERRIDE) .returns(String::class) .addStatement("return OPERATION_NAME") .build() private fun companionTypeSpec(): TypeSpec { return TypeSpec.companionObjectBuilder() .addProperty(PropertySpec.builder(OPERATION_ID, String::class) .addModifiers(KModifier.CONST) .initializer("%S", operationId) .build() ) .applyIf(generateQueryDocument) { addProperty(PropertySpec.builder(OPERATION_DOCUMENT, String::class) .addModifiers(KModifier.CONST) .initializer("%S", QueryDocumentMinifier.minify(operation.sourceWithFragments)) .addKdoc(""" The minimized GraphQL document being sent to the server to save a few bytes. The un-minimized version is: """.trimIndent() + operation.sourceWithFragments ) .build() ) } .addProperty(PropertySpec .builder(OPERATION_NAME, String::class) .addModifiers(KModifier.CONST) .initializer("%S", operation.name) .build() ) .build() } private fun responseFieldsFunSpec(): FunSpec { return responseFieldsFunSpec( context.resolver.resolveOperationResponseFields(operation.name) ) } }
mit
e97846e6e1d700f99deb4d59771ab0e6
36.666667
135
0.727695
4.734203
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/syntax/solver/FirstsetSolver.kt
1
2774
package com.bajdcc.LALR1.syntax.solver import com.bajdcc.LALR1.syntax.ISyntaxComponentVisitor import com.bajdcc.LALR1.syntax.exp.* import com.bajdcc.LALR1.syntax.rule.RuleItem import com.bajdcc.util.VisitBag /** * 求解一个产生式的First集合 * * @author bajdcc */ class FirstsetSolver : ISyntaxComponentVisitor { /** * 终结符表 */ private val setTokens = mutableSetOf<TokenExp>() /** * 非终结符表 */ private val setRules = mutableSetOf<RuleExp>() /** * 产生式推导的串长度是否可能为零 */ private var bZero = true /** * 求解 * * @param target 目标产生式对象 * @return 产生式是否合法 */ fun solve(target: RuleItem): Boolean { if (bZero) { return false } target.setFirstSetTokens = setTokens.toMutableSet() target.setFirstSetRules = setRules.toMutableSet() return true } override fun visitBegin(node: TokenExp, bag: VisitBag) { bag.visitChildren = false bag.visitEnd = false setTokens.add(node) if (bZero) { bZero = false } } override fun visitBegin(node: RuleExp, bag: VisitBag) { bag.visitChildren = false bag.visitEnd = false setRules.add(node) if (bZero) { bZero = false } } override fun visitBegin(node: SequenceExp, bag: VisitBag) { bag.visitChildren = false bag.visitEnd = false var zero = false for (exp in node.arrExpressions) { exp.visit(this) zero = bZero if (!zero) { break } } bZero = zero } override fun visitBegin(node: BranchExp, bag: VisitBag) { bag.visitChildren = false bag.visitEnd = false var zero = false for (exp in node.arrExpressions) { exp.visit(this) if (bZero) { zero = bZero } } bZero = zero } override fun visitBegin(node: OptionExp, bag: VisitBag) { bag.visitChildren = false bag.visitEnd = false node.expression.visit(this) bZero = true } override fun visitBegin(node: PropertyExp, bag: VisitBag) { bag.visitChildren = false bag.visitEnd = false node.expression.visit(this) bZero = false } override fun visitEnd(node: TokenExp) { } override fun visitEnd(node: RuleExp) { } override fun visitEnd(node: SequenceExp) { } override fun visitEnd(node: BranchExp) { } override fun visitEnd(node: OptionExp) { } override fun visitEnd(node: PropertyExp) { } }
mit
e7107f26c7550a4074e7d49036579a49
20.055118
63
0.564697
3.99701
false
false
false
false
DanilaFe/abacus
core/src/main/kotlin/org/nwapw/abacus/context/PluginEvaluationContext.kt
1
1933
package org.nwapw.abacus.context import org.nwapw.abacus.Abacus import org.nwapw.abacus.number.NumberInterface import org.nwapw.abacus.plugin.NumberImplementation import org.nwapw.abacus.tree.nodes.TreeNode /** * An evaluation context with limited mutability. * * An evaluation context that is mutable but in a limited way, that is, not allowing the modifications * of variables whose changes might cause issues outside of the function. An example of this would be * the modification of the [numberImplementation], which would cause code paths such as the parsing * of NumberNodes to produce a different type of number than if the function did not run, whcih is unacceptable. * * @param parent the parent of this context. * @param numberImplementation the number implementation used in this context. * @param abacus the abacus instance used. */ abstract class PluginEvaluationContext(parent: EvaluationContext? = null, numberImplementation: NumberImplementation? = null, abacus: Abacus? = null) : EvaluationContext(parent, numberImplementation, abacus) { /** * Sets a variable to a certain [value]. * @param name the name of the variable. * @param value the value of the variable. */ fun setVariable(name: String, value: NumberInterface) { variableMap[name] = value } /** * Set a definition to a certain [value]. * @param name the name of the definition. * @param value the value of the definition. */ fun setDefinition(name: String, value: TreeNode) { definitionMap[name] = value } /** * Clears the variables defined in this context. */ fun clearVariables(){ variableMap.clear() } /** * Clears the definitions defined in this context. */ fun clearDefinitions(){ definitionMap.clear() } }
mit
934fad5d736432082d87127c94ee7ad3
32.344828
112
0.675116
4.373303
false
false
false
false
ThoseGrapefruits/intellij-rust
src/main/kotlin/org/rust/lang/module/RustModuleType.kt
1
839
package org.rust.lang.module import com.intellij.icons.AllIcons import com.intellij.openapi.module.ModuleType import com.intellij.openapi.module.ModuleTypeManager import org.rust.lang.icons.RustIcons import javax.swing.Icon class RustModuleType : ModuleType<RustModuleBuilder>(RustModuleType.MODULE_TYPE_ID) { override fun createModuleBuilder(): RustModuleBuilder = RustModuleBuilder() override fun getName(): String = "Rust Module" override fun getDescription(): String = "Rust Module" override fun getBigIcon(): Icon = RustIcons.RUST override fun getNodeIcon(isOpened: Boolean): Icon = AllIcons.Nodes.Module companion object { val MODULE_TYPE_ID = "RUST_MODULE" val INSTANCE by lazy { ModuleTypeManager.getInstance().findByID(MODULE_TYPE_ID) as RustModuleType } } }
mit
50db0ae71e9b665b660835b0223539fc
31.269231
86
0.741359
4.369792
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/ParagraphBuilder.kt
1
1885
package org.hexworks.zircon.api.builder.component import org.hexworks.zircon.api.component.Paragraph import org.hexworks.zircon.api.component.builder.base.ComponentWithTextBuilder import org.hexworks.zircon.api.graphics.TextWrap import org.hexworks.zircon.internal.component.impl.DefaultParagraph import org.hexworks.zircon.internal.component.renderer.DefaultParagraphRenderer import org.hexworks.zircon.internal.component.renderer.TypingEffectPostProcessor import org.hexworks.zircon.internal.dsl.ZirconDsl import kotlin.jvm.JvmStatic @Suppress("UNCHECKED_CAST") @ZirconDsl class ParagraphBuilder private constructor() : ComponentWithTextBuilder<Paragraph, ParagraphBuilder>( initialRenderer = DefaultParagraphRenderer(), initialText = "" ) { var textWrap: TextWrap = TextWrap.WORD_WRAP set(value) { field = value componentRenderer = DefaultParagraphRenderer(value) } var typingEffectSpeedInMs: Long = 0 fun withTextWrap(textWrap: TextWrap) = also { this.textWrap = textWrap } fun withTypingEffect(typingEffectSpeedInMs: Long) = also { this.typingEffectSpeedInMs = typingEffectSpeedInMs } override fun build(): Paragraph { props.postProcessors = props.postProcessors + if (typingEffectSpeedInMs > 0) { listOf(TypingEffectPostProcessor(typingEffectSpeedInMs)) } else { listOf() } return DefaultParagraph( componentMetadata = createMetadata(), renderingStrategy = createRenderingStrategy(), initialText = text, ).attachListeners() } override fun createCopy() = newBuilder() .withProps(props.copy()) .withText(text) .withTypingEffect(typingEffectSpeedInMs) companion object { @JvmStatic fun newBuilder() = ParagraphBuilder() } }
apache-2.0
51f18d5a3ee2238f65cfbb46ead73985
31.5
101
0.710345
4.677419
false
false
false
false
DuncanCasteleyn/DiscordModBot
src/main/kotlin/be/duncanc/discordmodbot/bot/sequences/AddWarnPoints.kt
1
15269
/* * Copyright 2018 Duncan Casteleyn * * 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 be.duncanc.discordmodbot.bot.sequences import be.duncanc.discordmodbot.bot.commands.CommandModule import be.duncanc.discordmodbot.bot.services.GuildLogger import be.duncanc.discordmodbot.bot.services.MuteRole import be.duncanc.discordmodbot.bot.utils.messageTimeFormat import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername import be.duncanc.discordmodbot.data.entities.GuildWarnPoints import be.duncanc.discordmodbot.data.entities.GuildWarnPointsSettings import be.duncanc.discordmodbot.data.entities.UserWarnPoints import be.duncanc.discordmodbot.data.repositories.jpa.GuildWarnPointsRepository import be.duncanc.discordmodbot.data.repositories.jpa.GuildWarnPointsSettingsRepository import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.MessageBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.* import net.dv8tion.jda.api.events.message.MessageReceivedEvent import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import org.springframework.transaction.annotation.Transactional import java.awt.Color import java.time.OffsetDateTime import java.util.* import java.util.concurrent.TimeUnit @Component class AddWarnPoints( val guildWarnPointsRepository: GuildWarnPointsRepository, val guildWarnPointsSettingsRepository: GuildWarnPointsSettingsRepository, val muteRole: MuteRole ) : CommandModule( arrayOf("AddWarnPoints", "AddPoints", "Warn"), "Mention a user", "This command is used to add points to a user, the user will be informed about this", requiredPermissions = arrayOf(Permission.KICK_MEMBERS), ignoreWhitelist = true ) { companion object { val illegalStateException = IllegalStateException("The announcement channel needs to be configured by a server administrator") val LOG: Logger = LoggerFactory.getLogger(AddWarnPoints::class.java) const val reasonSizeLimit = 1024 } override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) { val guildId = event.guild.idLong val guildWarnPointsSettings = guildWarnPointsSettingsRepository.findById(guildId) .orElse(GuildWarnPointsSettings(guildId, announceChannelId = -1)) if (command.equals("Warn", true) && !guildWarnPointsSettings.overrideWarnCommand ) { return } val userId = event.message.contentRaw.substring(command.length + 2).trimStart('<', '@', '!').trimEnd('>').toLong() event.jda.retrieveUserById(userId).queue( { targetUser -> val member = event.guild.getMember(targetUser) if (member == null || event.member?.canInteract(member) == true) { event.author.openPrivateChannel().queue { event.jda.addEventListener( AddPointsSequence( event.author, it, targetUser, event.guild ) ) } } else { event.channel.sendMessage("${event.author.asMention} You can't interact with this member.") .queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } } }, { t -> LOG.error( "Bot " + event.jda.selfUser.toString() + " on channel " + (if (event.channelType == ChannelType.TEXT) event.guild.toString() + " " else "") + event.channel.name + " failed executing " + event.message.contentStripped + " command from user " + event.author.toString(), t ) val exceptionMessage = MessageBuilder().append("${event.author.asMention} Cannot complete action due to an error; see the message below for details.") .appendCodeBlock(t.javaClass.simpleName + ": " + t.message, "text").build() event.channel.sendMessage(exceptionMessage).queue { it.delete().queueAfter(5, TimeUnit.MINUTES) } } ) } @Transactional inner class AddPointsSequence( user: User, channel: MessageChannel, private val targetUser: User, private val guild: Guild ) : Sequence( user, channel ), MessageSequence { private var reason: String? = null private var points: Int? = null private var expireDate: OffsetDateTime? = null init { channel.sendMessage("Please enter the reason for giving the user points.").queue() } override fun onMessageReceivedDuringSequence(event: MessageReceivedEvent) { val guildId = guild.idLong val guildPointsSettings = guildWarnPointsSettingsRepository.findById(guildId).orElseThrow { throw illegalStateException } if (guildPointsSettings.announceChannelId.let { event.jda.getTextChannelById(it) == null } ) { throw illegalStateException } when { reason == null -> { val contentDisplay = event.message.contentDisplay if (contentDisplay.length > reasonSizeLimit) { throw IllegalArgumentException("Reasons cannot exceed $reasonSizeLimit characters") } reason = contentDisplay if (guildPointsSettings.maxPointsPerReason == 1) { points = guildPointsSettings.maxPointsPerReason askForExpireTime() } else { channel.sendMessage("Please enter the amount of points to assign. Your server administrator(s) has/have set a maximum of " + guildPointsSettings.maxPointsPerReason + " per reason") .queue { super.addMessageToCleaner(it) } } } points == null -> { val inputPoints = event.message.contentRaw.toInt() if (inputPoints > guildPointsSettings.maxPointsPerReason) { throw IllegalArgumentException("This amount is above the maximum per reason") } points = inputPoints askForExpireTime() } expireDate == null -> { val days = event.message.contentRaw.toLong() expireDate = OffsetDateTime.now().plusDays(days) val muteText = try { muteRole.getMuteRole(guild) "" } catch (e: java.lang.IllegalStateException) { " (Not configured)" } if (!guild.isMember(user)) { processSequence(event, guildPointsSettings) return } channel.sendMessage("Should an action be performed with this warn?\n0. None\n1. Mute$muteText\n2. Kick") .queue() } else -> { processSequence(event, guildPointsSettings) } } } private fun askForExpireTime() { channel.sendMessage("In how much days should these point(s) expire?").queue() } private fun processSequence(event: MessageReceivedEvent, guildPointsSettings: GuildWarnPointsSettings) { val action = event.message.contentRaw.toByte() val guildWarnPoints = guildWarnPointsRepository.findById( GuildWarnPoints.GuildWarnPointsId( targetUser.idLong, guild.idLong ) ).orElse(GuildWarnPoints(targetUser.idLong, guild.idLong)) val userWarnPoints = UserWarnPoints( points = points!!, creatorId = user.idLong, reason = reason!!, expireDate = expireDate!! ) guildWarnPoints.points.add(userWarnPoints) guildWarnPointsRepository.save(guildWarnPoints) performChecks(guildWarnPoints, guildPointsSettings, targetUser, guild) val moderator = guild.getMember(user)!! logAddPoints(moderator, targetUser, reason!!, points!!, userWarnPoints.id, expireDate!!, action) val member = guild.getMember(targetUser) if (member != null) { informUserAndModerator( moderator, member, reason!!, guildWarnPoints.filterExpiredPoints().size, event.privateChannel, action ) when (action) { 1.toByte() -> guild.addRoleToMember( member, muteRole.getMuteRole(guild) ).reason(reason).queue() 2.toByte() -> { guild.kick(member).reason(reason).queue() } } } super.destroy() } } private fun performChecks( guildWarnPoints: GuildWarnPoints, guildWarnPointsSettings: GuildWarnPointsSettings, user: User, guild: Guild ) { var points = 0 val activatePoints = guildWarnPoints.points.asSequence().filter { it.expireDate.isAfter(OffsetDateTime.now()) } .toCollection(mutableSetOf()) activatePoints.forEach { points += it.points } if (points >= guildWarnPointsSettings.announcePointsSummaryLimit) { val messageBuilder = MessageBuilder().append("@everyone ") .append(user.asMention) .append(" has reached the limit of points set by your server administrator.\n\n") .append("Summary of active points:") activatePoints.forEach { messageBuilder.append("\n\n").append(it.points).append(" point(s) added by ") .append(guild.getMemberById(it.creatorId)?.nicknameAndUsername) .append(" on ").append(it.creationDate.format(messageTimeFormat)).append('\n') .append("Reason: ").append(it.reason) .append("\nExpires on: ").append(it.expireDate.format(messageTimeFormat)) } messageBuilder.buildAll(MessageBuilder.SplitPolicy.NEWLINE).forEach { guild.getTextChannelById(guildWarnPointsSettings.announceChannelId)?.sendMessage(it)?.queue() } } } private fun logAddPoints( moderator: Member, toInform: User, reason: String, amount: Int, id: UUID, dateTime: OffsetDateTime, action: Byte ) { val guild = moderator.guild val guildLogger = toInform.jda.registeredListeners.firstOrNull { it is GuildLogger } as GuildLogger? if (guildLogger != null) { val logEmbed = EmbedBuilder() .setColor(Color.YELLOW) .setTitle("Warn points added to user") .addField("UUID", id.toString(), false) .addField("User", guild.getMember(toInform)?.nicknameAndUsername ?: toInform.name, true) .addField("Moderator", moderator.nicknameAndUsername, true) .addField("Amount", amount.toString(), false) .addField("Reason", reason, false) .addField("Expires", dateTime.format(messageTimeFormat), false) when (action) { 1.toByte() -> logEmbed.addField("Punishment", "Mute", false) 2.toByte() -> logEmbed.addField("Punishment", "Kick", false) } guildLogger.log(logEmbed, toInform, guild, null, GuildLogger.LogTypeAction.MODERATOR) } } private fun informUserAndModerator( moderator: Member, toInform: Member, reason: String, amountOfWarnings: Int, moderatorPrivateChannel: PrivateChannel, action: Byte ) { val noteMessage = if (amountOfWarnings <= 1) { "Please watch your behavior in our server." } else { "You have received $amountOfWarnings warnings in recent history. Please watch your behaviour in our server." } val userWarning = EmbedBuilder() .setColor(Color.YELLOW) .setAuthor(moderator.nicknameAndUsername, null, moderator.user.effectiveAvatarUrl) .setTitle("${moderator.guild.name}: You have been warned by ${moderator.nicknameAndUsername}", null) .addField("Reason", reason, false) .addField("Note", noteMessage, false) when (action) { 1.toByte() -> userWarning.addField("Punishment", "Mute", false) 2.toByte() -> userWarning.addField("Punishment", "Kick", false) } toInform.user.openPrivateChannel().queue( { privateChannelUserToWarn -> privateChannelUserToWarn.sendMessageEmbeds(userWarning.build()).queue( { onSuccessfulInformUser(moderatorPrivateChannel, toInform, userWarning.build()) } ) { throwable -> onFailToInformUser(moderatorPrivateChannel, toInform, throwable) } } ) { throwable -> onFailToInformUser(moderatorPrivateChannel, toInform, throwable) } } private fun onSuccessfulInformUser( privateChannel: PrivateChannel, toInform: Member, informationMessage: MessageEmbed ) { val creatorMessage = MessageBuilder() .append("Added warn points to ").append(toInform.toString()) .append(".\n\nThe following message was sent to the user:") .setEmbeds(informationMessage) .build() privateChannel.sendMessage(creatorMessage).queue() } private fun onFailToInformUser(privateChannel: PrivateChannel, toInform: Member, throwable: Throwable) { val creatorMessage = MessageBuilder() .append("Added warn points to ").append(toInform.toString()) .append(".\n\nWas unable to send a DM to the user please inform the user manually.\n") .append(throwable.javaClass.simpleName).append(": ").append(throwable.message) .build() privateChannel.sendMessage(creatorMessage).queue() } }
apache-2.0
894ed5804f891085251c357cee50d712
43.646199
286
0.594669
5.125545
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/Shapes.kt
1
2640
package org.hexworks.zircon.api import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.shape.* import kotlin.jvm.JvmStatic /** * This object is a facade for the various [ShapeFactory] implementations. */ object Shapes { /** * Creates the points for a filled rectangle. * * For example, calling this method with size being the size of a grid and top-left * value being the terminals top-left (0x0) corner will create a shape which when drawn * will fill the whole grid. * **Note that** all resulting shapes will be offset to the top left (0x0) position! * @see [Shape.offsetToDefaultPosition] for more info! */ @JvmStatic fun buildFilledRectangle( topLeft: Position, size: Size ) = FilledRectangleFactory.createShape(RectangleParameters(topLeft, size)) /** * Creates the points for the outline of a triangle. The outline will go through positions * `p1` to `p2` to `p3` and back to `p1` from there. * * *Note that** all resulting shapes will be offset to the top left (0x0) position! * @see [Shape.offsetToDefaultPosition] for more info! */ @JvmStatic fun buildTriangle( p1: Position, p2: Position, p3: Position ) = TriangleFactory.createShape(TriangleParameters(p1, p2, p3)) /** * Creates the points for the outline of a rectangle. * * For example, calling this method with size being the size of a grid and top-left * value being the terminals top-left (0x0) corner will create a shape which when drawn * will outline the borders of the grid. * **Note that** all resulting shapes will be offset to the top left (0x0) position! * @see [Shape.offsetToDefaultPosition] for more info! */ @JvmStatic fun buildRectangle( topLeft: Position, size: Size ) = RectangleFactory.createShape(RectangleParameters(topLeft, size)) @JvmStatic fun buildLine(fromPoint: Position, toPoint: Position) = LineFactory.createShape(LineParameters(fromPoint, toPoint)) /** * Creates the points for a filled triangle. The triangle will be delimited by * positions `p1` to `p2` to `p3` and back to `p1` from there. * * *Note that** all resulting shapes will be offset to the top left (0x0) position! * @see [Shape.offsetToDefaultPosition] for more info! */ @JvmStatic fun buildFilledTriangle( p1: Position, p2: Position, p3: Position ) = FilledTriangleFactory.createShape(TriangleParameters(p1, p2, p3)) }
apache-2.0
07628a26af9f481795b42bf766c35cc7
35.164384
119
0.674621
3.958021
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/neuralnetwork/preset/SimpleRecurrentSpec.kt
1
2765
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.neuralnetwork.preset import com.kotlinnlp.simplednn.core.functionalities.activations.ELU import com.kotlinnlp.simplednn.core.functionalities.activations.Softmax import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.neuralnetwork.preset.SimpleRecurrentNeuralNetwork import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertEquals import kotlin.test.assertNull /** * */ class SimpleRecurrentSpec : Spek({ describe("a SimpleRecurrent Neural Netowork") { val hiddenActivation = ELU() val outputActivation = Softmax() val network = SimpleRecurrentNeuralNetwork( inputSize = 3, hiddenSize = 5, hiddenActivation = hiddenActivation, outputSize = 4, outputActivation = outputActivation) context("initialization") { context("input layer configuration") { val inputLayerConfig = network.layersConfiguration[0] it("should have the expected size") { assertEquals(3, inputLayerConfig.size) } it("should have a null activation function") { assertNull(inputLayerConfig.activationFunction) } it("should have a null connection type") { assertNull(inputLayerConfig.connectionType) } } context("hidden layer configuration") { val hiddenLayerConfig = network.layersConfiguration[1] it("should have the expected size") { assertEquals(5, hiddenLayerConfig.size) } it("should have the expected activation function") { assertEquals(hiddenActivation, hiddenLayerConfig.activationFunction) } it("should a Feedforward connection type") { assertEquals(LayerType.Connection.SimpleRecurrent, hiddenLayerConfig.connectionType) } } context("output layer configuration") { val outputLayerConfig = network.layersConfiguration[2] it("should have the expected size") { assertEquals(4, outputLayerConfig.size) } it("should have the expected activation function") { assertEquals(outputActivation, outputLayerConfig.activationFunction) } it("should a Feedforward connection type") { assertEquals(LayerType.Connection.Feedforward, outputLayerConfig.connectionType) } } } } })
mpl-2.0
d295e5581fce9f0f0b1a0a013f5d0a51
30.067416
94
0.678481
4.859402
false
true
false
false
mdaniel/intellij-community
platform/ide-core/src/com/intellij/ide/plugins/advertiser/data.kt
1
1656
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package com.intellij.ide.plugins.advertiser import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.NlsSafe import kotlinx.serialization.Serializable @Serializable data class PluginData( val pluginIdString: String = "", @NlsSafe val nullablePluginName: String? = null, val isBundled: Boolean = false, val isFromCustomRepository: Boolean = false, ) : Comparable<PluginData> { val pluginId: PluginId get() = PluginId.getId(pluginIdString) val pluginName: String get() = nullablePluginName ?: pluginIdString constructor(descriptor: PluginDescriptor) : this( descriptor.pluginId.idString, descriptor.name, descriptor.isBundled, ) override fun compareTo(other: PluginData): Int { return if (isBundled && !other.isBundled) -1 else if (!isBundled && other.isBundled) 1 else Comparing.compare(pluginIdString, other.pluginIdString) } } @Serializable data class FeaturePluginData( val displayName: String = "", val pluginData: PluginData = PluginData() ) @Serializable data class PluginDataSet(val dataSet: Set<PluginData> = emptySet()) @Serializable data class PluginFeatureMap( val featureMap: Map<String, PluginDataSet> = emptyMap(), val lastUpdateTime: Long = 0L, ) { fun get(implementationName: String): Set<PluginData> = featureMap.get(implementationName)?.dataSet ?: emptySet() }
apache-2.0
59075a86953ab7581d80f536e3b7f09a
29.666667
120
0.761473
4.335079
false
false
false
false
android/nowinandroid
feature/interests/src/main/java/com/google/samples/apps/nowinandroid/feature/interests/InterestsScreen.kt
1
7697
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.feature.interests import androidx.compose.foundation.layout.Column import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaBackground import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaLoadingWheel import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTab import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTabRow import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.domain.model.FollowableAuthor import com.google.samples.apps.nowinandroid.core.domain.model.FollowableTopic import com.google.samples.apps.nowinandroid.core.model.data.previewAuthors import com.google.samples.apps.nowinandroid.core.model.data.previewTopics import com.google.samples.apps.nowinandroid.core.ui.DevicePreviews import com.google.samples.apps.nowinandroid.core.ui.TrackDisposableJank @OptIn(ExperimentalLifecycleComposeApi::class) @Composable internal fun InterestsRoute( navigateToAuthor: (String) -> Unit, navigateToTopic: (String) -> Unit, modifier: Modifier = Modifier, viewModel: InterestsViewModel = hiltViewModel() ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() val tabState by viewModel.tabState.collectAsStateWithLifecycle() InterestsScreen( uiState = uiState, tabState = tabState, followTopic = viewModel::followTopic, followAuthor = viewModel::followAuthor, navigateToAuthor = navigateToAuthor, navigateToTopic = navigateToTopic, switchTab = viewModel::switchTab, modifier = modifier ) TrackDisposableJank(tabState) { metricsHolder -> metricsHolder.state?.putState("Interests:TabState", "currentIndex:${tabState.currentIndex}") onDispose { metricsHolder.state?.removeState("Interests:TabState") } } } @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun InterestsScreen( uiState: InterestsUiState, tabState: InterestsTabState, followAuthor: (String, Boolean) -> Unit, followTopic: (String, Boolean) -> Unit, navigateToAuthor: (String) -> Unit, navigateToTopic: (String) -> Unit, switchTab: (Int) -> Unit, modifier: Modifier = Modifier, ) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally ) { when (uiState) { InterestsUiState.Loading -> NiaLoadingWheel( modifier = modifier, contentDesc = stringResource(id = R.string.interests_loading), ) is InterestsUiState.Interests -> InterestsContent( tabState = tabState, switchTab = switchTab, uiState = uiState, navigateToTopic = navigateToTopic, followTopic = followTopic, navigateToAuthor = navigateToAuthor, followAuthor = followAuthor ) is InterestsUiState.Empty -> InterestsEmptyScreen() } } } @Composable private fun InterestsContent( tabState: InterestsTabState, switchTab: (Int) -> Unit, uiState: InterestsUiState.Interests, navigateToTopic: (String) -> Unit, followTopic: (String, Boolean) -> Unit, navigateToAuthor: (String) -> Unit, followAuthor: (String, Boolean) -> Unit, modifier: Modifier = Modifier ) { Column(modifier) { NiaTabRow(selectedTabIndex = tabState.currentIndex) { tabState.titles.forEachIndexed { index, titleId -> NiaTab( selected = index == tabState.currentIndex, onClick = { switchTab(index) }, text = { Text(text = stringResource(id = titleId)) } ) } } when (tabState.currentIndex) { 0 -> { TopicsTabContent( topics = uiState.topics, onTopicClick = navigateToTopic, onFollowButtonClick = followTopic, ) } 1 -> { AuthorsTabContent( authors = uiState.authors, onAuthorClick = navigateToAuthor, onFollowButtonClick = followAuthor, ) } } } } @Composable private fun InterestsEmptyScreen() { Text(text = stringResource(id = R.string.interests_empty_header)) } @DevicePreviews @Composable fun InterestsScreenPopulated() { NiaTheme { NiaBackground { InterestsScreen( uiState = InterestsUiState.Interests( authors = previewAuthors.map { FollowableAuthor(it, false) }, topics = previewTopics.map { FollowableTopic(it, false) } ), tabState = InterestsTabState( titles = listOf(R.string.interests_topics, R.string.interests_people), currentIndex = 0 ), followAuthor = { _, _ -> }, followTopic = { _, _ -> }, navigateToAuthor = {}, navigateToTopic = {}, switchTab = {} ) } } } @DevicePreviews @Composable fun InterestsScreenLoading() { NiaTheme { NiaBackground { InterestsScreen( uiState = InterestsUiState.Loading, tabState = InterestsTabState( titles = listOf(R.string.interests_topics, R.string.interests_people), currentIndex = 0 ), followAuthor = { _, _ -> }, followTopic = { _, _ -> }, navigateToAuthor = {}, navigateToTopic = {}, switchTab = {}, ) } } } @DevicePreviews @Composable fun InterestsScreenEmpty() { NiaTheme { NiaBackground { InterestsScreen( uiState = InterestsUiState.Empty, tabState = InterestsTabState( titles = listOf(R.string.interests_topics, R.string.interests_people), currentIndex = 0 ), followAuthor = { _, _ -> }, followTopic = { _, _ -> }, navigateToAuthor = {}, navigateToTopic = {}, switchTab = {} ) } } }
apache-2.0
fbb9f89c472dc5e23d13e984ec2af41b
34.146119
100
0.618683
4.825705
false
false
false
false
InsideZhou/Instep
dao/src/main/kotlin/instep/dao/sql/impl/DefaultTableDeletePlan.kt
1
1360
package instep.dao.sql.impl import instep.dao.DaoException import instep.dao.sql.Condition import instep.dao.sql.Table import instep.dao.sql.TableDeletePlan open class DefaultTableDeletePlan(val table: Table) : TableDeletePlan, AbstractTablePlan<TableDeletePlan>() { override var where: Condition = Condition.empty private var pkValue: Any? = null override fun whereKey(key: Any): TableDeletePlan { if (null == table.primaryKey) throw DaoException("Table ${table.tableName} should has primary key") pkValue = key return this } @Suppress("DuplicatedCode") override val statement: String get() { var txt = "DELETE FROM ${table.tableName}" if (where.text.isBlank() && null == pkValue) return txt txt += " WHERE ${where.text}" if (null == pkValue) return txt if (where.text.isNotBlank()) { txt += " AND " } val column = table.primaryKey!! txt += "${column.name}=${table.dialect.placeholderForParameter(column)}" return txt } override val parameters: List<Any?> get() { val result = mutableListOf<Any?>() where.let { result.addAll(it.parameters) } pkValue?.let { result.add(it) } return result } }
bsd-2-clause
b320131a6208421f7dd28247733398be
27.957447
109
0.6
4.387097
false
false
false
false
JavaEden/Orchid-Core
integrations/OrchidGithub/src/main/kotlin/com/eden/orchid/github/menu/GithubMenuItem.kt
2
3030
package com.eden.orchid.github.menu import com.caseyjbrooks.clog.Clog import com.eden.common.util.EdenUtils import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.OrchidFlags import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.resources.resource.StringResource import com.eden.orchid.api.theme.menus.MenuItem import com.eden.orchid.api.theme.menus.OrchidMenuFactory import com.eden.orchid.api.theme.pages.OrchidExternalPage import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.api.theme.pages.OrchidReference import okhttp3.OkHttpClient import okhttp3.Request import org.json.JSONObject class GithubMenuItem : OrchidMenuFactory("github") { @Option lateinit var githubProject: String @Option lateinit var title: String val githubToken: String? get() { return OrchidFlags.getInstance().getFlagValue("githubToken") } override fun getMenuItems( context: OrchidContext, page: OrchidPage ): List<MenuItem> { val githubPage = loadGithubPage(context, context.resolve(OkHttpClient::class.java)) return if (githubPage.first && githubPage.second != null) { listOf(MenuItem.Builder(context) { page(githubPage.second) if([email protected]()) { title([email protected]) } }.build()) } else { emptyList() } } private fun loadGithubPage(context: OrchidContext, client: OkHttpClient): Pair<Boolean, OrchidPage?> { try { val request = Request.Builder().url("https://api.github.com/repos/$githubProject").get() if (!EdenUtils.isEmpty(githubToken)) { request.header("Authorization", "token $githubToken") } val response = client.newCall(request.build()).execute() val bodyString = response.body!!.string() if (response.isSuccessful) { val jsonBody = JSONObject(bodyString) val name = jsonBody.getString("name") val url = jsonBody.getString("html_url") val description = jsonBody.getString("description") val starCount = jsonBody.getInt("stargazers_count") val pageRef = OrchidReference.fromUrl(context, name, url) val pageRes = StringResource(pageRef, description) val page = OrchidExternalPage(pageRes, "githubProject", "") page.description = """ |<span class="stars"> | <span class="icon"><i class="fas fa-star"></i></span> | <span>$starCount</span> |</span> """.trimMargin() return Pair(true, page) } else { Clog.e("{}", bodyString) } } catch (e: Exception) { } return Pair(false, null) } }
mit
63208c93f8cf596ff34a8a9d9ea6fb1c
33.044944
106
0.606601
4.640123
false
false
false
false
GunoH/intellij-community
python/testSrc/com/jetbrains/python/ui/ManualPathEntryDialogTest.kt
4
3062
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ui import com.intellij.execution.Platform import com.jetbrains.python.ui.targetPathEditor.ManualPathEntryDialog import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class ManualPathEntryDialogTest { @Parameterized.Parameter(0) @JvmField var path: String? = null @Parameterized.Parameter(1) @JvmField var platform: Platform? = null @Parameterized.Parameter(2) @JvmField var isAbsolute: Boolean = false @Test fun `test isAbsolutePath`() { Assert.assertEquals(ManualPathEntryDialog.isAbsolutePath(path!!, platform!!), isAbsolute) } companion object { @Parameterized.Parameters(name = "[{1}] Path ''{0}'' is absolute == {2}") @JvmStatic fun data() = arrayOf( // Unix absolute paths arrayOf("/", Platform.UNIX, true), arrayOf("/opt", Platform.UNIX, true), arrayOf("/opt/", Platform.UNIX, true), arrayOf("/opt/project", Platform.UNIX, true), arrayOf("/opt/project/", Platform.UNIX, true), arrayOf("//", Platform.UNIX, true), arrayOf("/opt//project", Platform.UNIX, true), arrayOf("/opt//project//", Platform.UNIX, true), // Unix relative paths arrayOf(".", Platform.UNIX, false), arrayOf("./", Platform.UNIX, false), arrayOf("opt/", Platform.UNIX, false), arrayOf("opt/project", Platform.UNIX, false), arrayOf("opt/project/", Platform.UNIX, false), arrayOf("./opt/", Platform.UNIX, false), arrayOf("./opt/project", Platform.UNIX, false), arrayOf("./opt/project/", Platform.UNIX, false), // Windows absolute paths arrayOf("C:\\", Platform.WINDOWS, true), arrayOf("C:/", Platform.WINDOWS, true), arrayOf("c:\\", Platform.WINDOWS, true), arrayOf("c:/", Platform.WINDOWS, true), arrayOf("C:/opt/", Platform.WINDOWS, true), arrayOf("C:/opt/project", Platform.WINDOWS, true), arrayOf("C:/opt/project/", Platform.WINDOWS, true), arrayOf("C:\\opt\\", Platform.WINDOWS, true), arrayOf("C:\\opt\\project", Platform.WINDOWS, true), arrayOf("C:\\opt\\project\\", Platform.WINDOWS, true), // Windows relative paths arrayOf("opt/", Platform.WINDOWS, false), arrayOf("opt/project", Platform.WINDOWS, false), arrayOf("opt/project/", Platform.WINDOWS, false), arrayOf("./opt/", Platform.WINDOWS, false), arrayOf("./opt/project", Platform.WINDOWS, false), arrayOf("./opt/project/", Platform.WINDOWS, false), arrayOf("opt\\", Platform.WINDOWS, false), arrayOf("opt\\project", Platform.WINDOWS, false), arrayOf("opt\\project\\", Platform.WINDOWS, false), arrayOf(".\\opt\\", Platform.WINDOWS, false), arrayOf(".\\opt\\project", Platform.WINDOWS, false), arrayOf(".\\opt\\project\\", Platform.WINDOWS, false), ) } }
apache-2.0
d27c08e4ef123945eaaac761ccff9a6c
36.814815
140
0.653168
4.088117
false
false
false
false
GunoH/intellij-community
jvm/jvm-analysis-api/src/com/intellij/codeInspection/analysisUastUtil.kt
2
1676
// 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.codeInspection import com.intellij.psi.LambdaUtil import com.intellij.psi.PsiType import com.intellij.psi.util.InheritanceUtil import org.jetbrains.uast.* fun ULambdaExpression.getReturnType(): PsiType? { val lambdaType = functionalInterfaceType ?: getExpressionType() ?: uastParent?.let { when (it) { is UVariable -> it.type // in Kotlin local functions looks like lambda stored in variable is UCallExpression -> it.getParameterForArgument(this)?.type else -> null } } return LambdaUtil.getFunctionalInterfaceReturnType(lambdaType) } fun UAnnotated.findAnnotations(vararg fqNames: String) = uAnnotations.filter { ann -> fqNames.contains(ann.qualifiedName) } /** * Gets all classes in this file, including inner classes. */ fun UFile.allClasses() = classes.toTypedArray() + classes.flatMap { it.allInnerClasses().toList() } fun UClass.allInnerClasses(): Array<UClass> = innerClasses + innerClasses.flatMap { it.allInnerClasses().toList() } fun UClass.isAnonymousOrLocal(): Boolean = this is UAnonymousClass || isLocal() fun UClass.isLocal(): Boolean { val parent = uastParent if (parent is UDeclarationsExpression && parent.uastParent is UBlockExpression) return true return if (parent is UClass) parent.isLocal() else false } fun PsiType.isInheritorOf(vararg baseClassNames: String) = baseClassNames.any { InheritanceUtil.isInheritor(this, it) }
apache-2.0
2c9aa23d33592cf49565c97182a23d59
42
123
0.698687
4.761364
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/markingUtils.kt
3
6950
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.pullUp import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiverOrThis import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.types.Variance private var KtElement.newFqName: FqName? by CopyablePsiUserDataProperty(Key.create("NEW_FQ_NAME")) private var KtElement.replaceWithTargetThis: Boolean? by CopyablePsiUserDataProperty(Key.create("REPLACE_WITH_TARGET_THIS")) private var KtElement.newTypeText: ((TypeSubstitutor) -> String?)? by CopyablePsiUserDataProperty(Key.create("NEW_TYPE_TEXT")) fun markElements( declaration: KtNamedDeclaration, context: BindingContext, sourceClassDescriptor: ClassDescriptor, targetClassDescriptor: ClassDescriptor? ): List<KtElement> { val affectedElements = ArrayList<KtElement>() declaration.accept( object : KtVisitorVoid() { private fun visitSuperOrThis(expression: KtInstanceExpressionWithLabel) { if (targetClassDescriptor == null) return val callee = expression.getQualifiedExpressionForReceiver()?.selectorExpression?.getCalleeExpressionIfAny() ?: return val calleeTarget = callee.getResolvedCall(context)?.resultingDescriptor ?: return if ((calleeTarget as? CallableMemberDescriptor)?.kind != CallableMemberDescriptor.Kind.DECLARATION) return if (calleeTarget.containingDeclaration == targetClassDescriptor) { expression.replaceWithTargetThis = true affectedElements.add(expression) } } override fun visitElement(element: PsiElement) { element.allChildren.forEach { it.accept(this) } } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val resolvedCall = expression.getResolvedCall(context) ?: return val receiver = resolvedCall.getExplicitReceiverValue() ?: resolvedCall.extensionReceiver ?: resolvedCall.dispatchReceiver ?: return val implicitThis = receiver.type.constructor.declarationDescriptor as? ClassDescriptor ?: return if (implicitThis.isCompanionObject && DescriptorUtils.isAncestor(sourceClassDescriptor, implicitThis, true) ) { val qualifierFqName = implicitThis.importableFqName ?: return expression.newFqName = FqName("${qualifierFqName.asString()}.${expression.getReferencedName()}") affectedElements.add(expression) } } override fun visitThisExpression(expression: KtThisExpression) { visitSuperOrThis(expression) } override fun visitSuperExpression(expression: KtSuperExpression) { visitSuperOrThis(expression) } override fun visitTypeReference(typeReference: KtTypeReference) { val oldType = context[BindingContext.TYPE, typeReference] ?: return typeReference.newTypeText = f@{ substitutor -> substitutor.substitute(oldType, Variance.INVARIANT)?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } } affectedElements.add(typeReference) } } ) return affectedElements } fun applyMarking( declaration: KtNamedDeclaration, substitutor: TypeSubstitutor, targetClassDescriptor: ClassDescriptor ) { val psiFactory = KtPsiFactory(declaration) val targetThis = psiFactory.createExpression("this@${targetClassDescriptor.name.asString().quoteIfNeeded()}") val shorteningOptionsForThis = ShortenReferences.Options(removeThisLabels = true, removeThis = true) declaration.accept( object : KtVisitorVoid() { private fun visitSuperOrThis(expression: KtInstanceExpressionWithLabel) { expression.replaceWithTargetThis?.let { expression.replaceWithTargetThis = null val newThisExpression = expression.replace(targetThis) as KtExpression newThisExpression.getQualifiedExpressionForReceiverOrThis().addToShorteningWaitSet(shorteningOptionsForThis) } } override fun visitElement(element: PsiElement) { for (it in element.allChildren.toList()) { it.accept(this) } } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { expression.newFqName?.let { expression.newFqName = null expression.mainReference.bindToFqName(it) } } override fun visitThisExpression(expression: KtThisExpression) { this.visitSuperOrThis(expression) } override fun visitSuperExpression(expression: KtSuperExpression) { this.visitSuperOrThis(expression) } override fun visitTypeReference(typeReference: KtTypeReference) { typeReference.newTypeText?.let f@{ typeReference.newTypeText = null val newTypeText = it(substitutor) ?: return@f (typeReference.replace(psiFactory.createType(newTypeText)) as KtElement).addToShorteningWaitSet() } } } ) } fun clearMarking(markedElements: List<KtElement>) { markedElements.forEach { it.newFqName = null it.newTypeText = null it.replaceWithTargetThis = null } }
apache-2.0
028154da8e18ab969484c01c3cb32777
43.845161
158
0.683741
5.811037
false
false
false
false
jk1/intellij-community
platform/script-debugger/debugger-ui/src/DebugProcessImpl.kt
3
9423
// 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.debugger import com.intellij.execution.DefaultExecutionResult import com.intellij.execution.ExecutionResult import com.intellij.execution.process.ProcessHandler import com.intellij.openapi.application.runReadAction import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Url import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.socketConnection.ConnectionStatus import com.intellij.xdebugger.DefaultDebugProcessHandler import com.intellij.xdebugger.XDebugProcess import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.breakpoints.XBreakpointHandler import com.intellij.xdebugger.breakpoints.XLineBreakpoint import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider import com.intellij.xdebugger.frame.XSuspendContext import com.intellij.xdebugger.impl.XDebugSessionImpl import com.intellij.xdebugger.stepping.XSmartStepIntoHandler import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.connection.RemoteVmConnection import org.jetbrains.debugger.connection.VmConnection import java.util.concurrent.ConcurrentMap import java.util.concurrent.atomic.AtomicBoolean import javax.swing.event.HyperlinkListener interface MultiVmDebugProcess { val mainVm: Vm? val activeOrMainVm: Vm? val collectVMs: List<Vm> get() { val mainVm = mainVm ?: return emptyList() val result = mutableListOf<Vm>() fun addRecursively(vm: Vm) { if (vm.attachStateManager.isAttached) { result.add(vm) vm.childVMs.forEach { addRecursively(it) } } } addRecursively(mainVm) return result } } abstract class DebugProcessImpl<out C : VmConnection<*>>(session: XDebugSession, val connection: C, private val editorsProvider: XDebuggerEditorsProvider, private val smartStepIntoHandler: XSmartStepIntoHandler<*>? = null, protected val executionResult: ExecutionResult? = null) : XDebugProcess(session), MultiVmDebugProcess { protected val repeatStepInto: AtomicBoolean = AtomicBoolean() @Volatile var lastStep: StepAction? = null @Volatile protected var lastCallFrame: CallFrame? = null @Volatile protected var isForceStep: Boolean = false @Volatile protected var disableDoNotStepIntoLibraries: Boolean = false protected val urlToFileCache: ConcurrentMap<Url, VirtualFile> = ContainerUtil.newConcurrentMap<Url, VirtualFile>() var processBreakpointConditionsAtIdeSide: Boolean = false private val connectedListenerAdded = AtomicBoolean() private val breakpointsInitiated = AtomicBoolean() private val _breakpointHandlers: Array<XBreakpointHandler<*>> by lazy(LazyThreadSafetyMode.NONE) { createBreakpointHandlers() } protected val realProcessHandler: ProcessHandler? get() = executionResult?.processHandler override final fun getSmartStepIntoHandler(): XSmartStepIntoHandler<*>? = smartStepIntoHandler override final fun getBreakpointHandlers(): Array<out XBreakpointHandler<*>> = when (connection.state.status) { ConnectionStatus.DISCONNECTED, ConnectionStatus.DETACHED, ConnectionStatus.CONNECTION_FAILED -> XBreakpointHandler.EMPTY_ARRAY else -> _breakpointHandlers } override final fun getEditorsProvider(): XDebuggerEditorsProvider = editorsProvider val vm: Vm? get() = connection.vm override final val mainVm: Vm? get() = connection.vm override final val activeOrMainVm: Vm? get() = (session.suspendContext?.activeExecutionStack as? ExecutionStackView)?.suspendContext?.vm ?: mainVm init { if (session is XDebugSessionImpl && executionResult is DefaultExecutionResult) { session.addRestartActions(*executionResult.restartActions) } connection.stateChanged { when (it.status) { ConnectionStatus.DISCONNECTED, ConnectionStatus.DETACHED -> { if (it.status == ConnectionStatus.DETACHED) { if (realProcessHandler != null) { // here must we must use effective process handler processHandler.detachProcess() } } getSession().stop() } ConnectionStatus.CONNECTION_FAILED -> { getSession().reportError(it.message) getSession().stop() } else -> getSession().rebuildViews() } } } protected abstract fun createBreakpointHandlers(): Array<XBreakpointHandler<*>> private fun updateLastCallFrame(vm: Vm) { lastCallFrame = vm.suspendContextManager.context?.topFrame } override final fun checkCanPerformCommands(): Boolean = activeOrMainVm != null override final fun isValuesCustomSorted(): Boolean = true override final fun startStepOver(context: XSuspendContext?) { val vm = context.vm updateLastCallFrame(vm) continueVm(vm, StepAction.OVER) } val XSuspendContext?.vm: Vm get() = (this as? SuspendContextView)?.activeVm ?: mainVm!! override final fun startForceStepInto(context: XSuspendContext?) { isForceStep = true startStepInto(context) } override final fun startStepInto(context: XSuspendContext?) { val vm = context.vm updateLastCallFrame(vm) continueVm(vm, StepAction.IN) } override final fun startStepOut(context: XSuspendContext?) { val vm = context.vm if (isVmStepOutCorrect()) { lastCallFrame = null } else { updateLastCallFrame(vm) } continueVm(vm, StepAction.OUT) } // some VM (firefox for example) doesn't implement step out correctly, so, we need to fix it protected open fun isVmStepOutCorrect(): Boolean = true override fun resume(context: XSuspendContext?) { continueVm(context.vm, StepAction.CONTINUE) } open fun resume(vm: Vm) { continueVm(vm, StepAction.CONTINUE) } @Suppress("unused") @Deprecated("Pass vm explicitly", ReplaceWith("continueVm(vm!!, stepAction)")) protected open fun continueVm(stepAction: StepAction): Promise<*>? = continueVm(activeOrMainVm!!, stepAction) /** * You can override this method to avoid SuspendContextManager implementation, but it is not recommended. */ protected open fun continueVm(vm: Vm, stepAction: StepAction): Promise<*>? { val suspendContextManager = vm.suspendContextManager if (stepAction === StepAction.CONTINUE) { if (suspendContextManager.context == null) { // on resumed we ask session to resume, and session then call our "resume", but we have already resumed, so, we don't need to send "continue" message return null } lastStep = null lastCallFrame = null urlToFileCache.clear() disableDoNotStepIntoLibraries = false } else { lastStep = stepAction } return suspendContextManager.continueVm(stepAction) } protected fun setOverlay(context: SuspendContext<*>) { val vm = mainVm if (context.vm == vm) { vm.suspendContextManager.setOverlayMessage("Paused in debugger") } } override final fun startPausing() { activeOrMainVm!!.suspendContextManager.suspend() .onError(RejectErrorReporter(session, "Cannot pause")) } override final fun getCurrentStateMessage(): String = connection.state.message override final fun getCurrentStateHyperlinkListener(): HyperlinkListener? = connection.state.messageLinkListener override fun doGetProcessHandler(): ProcessHandler = executionResult?.processHandler ?: object : DefaultDebugProcessHandler() { override fun isSilentlyDestroyOnClose() = true } fun saveResolvedFile(url: Url, file: VirtualFile) { urlToFileCache.putIfAbsent(url, file) } // go plugin compatibility @Suppress("unused") open fun getLocationsForBreakpoint(breakpoint: XLineBreakpoint<*>): List<Location> = getLocationsForBreakpoint(activeOrMainVm!!, breakpoint) open fun getLocationsForBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>): List<Location> = throw UnsupportedOperationException() override fun isLibraryFrameFilterSupported(): Boolean = true // todo make final (go plugin compatibility) override fun checkCanInitBreakpoints(): Boolean { if (connection.state.status == ConnectionStatus.CONNECTED) { return true } if (connectedListenerAdded.compareAndSet(false, true)) { connection.stateChanged { if (it.status == ConnectionStatus.CONNECTED) { initBreakpoints() } } } return false } protected fun initBreakpoints() { if (breakpointsInitiated.compareAndSet(false, true)) { doInitBreakpoints() } } protected open fun doInitBreakpoints() { mainVm?.let(::beforeInitBreakpoints) runReadAction { session.initBreakpoints() } } protected open fun beforeInitBreakpoints(vm: Vm) { } protected fun addChildVm(vm: Vm, childConnection: RemoteVmConnection<*>) { mainVm?.childVMs?.add(vm) childConnection.stateChanged { if (it.status == ConnectionStatus.CONNECTION_FAILED || it.status == ConnectionStatus.DISCONNECTED || it.status == ConnectionStatus.DETACHED) { mainVm?.childVMs?.remove(vm) } } mainVm?.debugListener?.childVmAdded(vm) } }
apache-2.0
6561c3b3a8f8338dfbd7297c05f372bd
35.103448
178
0.718455
4.956865
false
false
false
false
EvidentSolutions/fab
src/main/kotlin/fi/evident/fab/proq2/GlobalPresetParameters.kt
1
6100
package fi.evident.fab.proq2 import fi.evident.fab.assertContains import fi.evident.fab.dB import fi.evident.fab.proq2.GlobalPresetParameters.Analyzer.Flag import java.io.IOException class GlobalPresetParameters { class ProcessMode private constructor( private val mode: Float, // affects only linear phase mode private val phase: ProcessMode.Phase) { enum class Phase constructor(private val value: Float) { Low(0f), Medium(1f), High(2f), VeryHigh(3f), Max(4f); @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { writer.writeFloat(value) } } @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { writer.writeFloat(mode) phase.write(writer) } companion object { @Suppress("unused") fun zeroLatency(): ProcessMode { return ProcessMode(0f, Phase.Medium) } @Suppress("unused") fun naturalPhase(): ProcessMode { return ProcessMode(1f, Phase.Medium) } fun linearPhase(phase: Phase): ProcessMode { return ProcessMode(2f, phase) } } } enum class ChannelMode constructor(private val value: Float) { LeftRight(0f), MidSide(1f); @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { writer.writeFloat(value) } } /** * @param db - Infinity to +36 dB , 0 = 0 dB * @param scale 0 to 2, 1 = 100%, 2 = 200% */ class Gain(private val db: dB, private val scale: dB) { init { (-1.0..1.0).assertContains(db, "Gain db") (0.0..2.0).assertContains(scale, "Gain scale") } @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { writer.writeFloat(scale.toFloat()) writer.writeFloat(db.toFloat()) } } /** * @param value -1 .. 1 where 0 is middle */ class OutputPan(private val value: Float) { init { (-1f..1f).assertContains(value, "Pan") } @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { writer.writeFloat(value) } } class Analyzer { enum class Range constructor(private val value: Float) { dB60(0f), dB90(1f), db120(2f); @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { writer.writeFloat(value) } } enum class Resolution constructor(private val value: Float) { Low(0f), Medium(1f), High(2f), Maximum(3f); @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { writer.writeFloat(value) } } enum class Speed constructor(private val value: Float) { VerySlow(0f), Slow(1f), Medium(2f), Fast(3f), VeryFast(4f); @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { writer.writeFloat(value) } } enum class Tilt constructor(private val value: Float) { dB_oct0(0f), dB_oct1point5(1f), dB_oct3(2f), dB_oct4point5(3f), dB_oct6(4f); @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { writer.writeFloat(value) } } enum class Flag { TRUE, FALSE; @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { val integer = when (this) { TRUE -> 1 FALSE -> 0 } writer.writeFloat(integer.toFloat()) } } private val pre = Flag.TRUE private val post = Flag.TRUE private val sideChain = Flag.TRUE private val range = Range.dB90 private val resolution = Resolution.Medium private val speed = Speed.Medium private val tilt = Tilt.dB_oct4point5 private val freeze = Flag.FALSE private val spectrumGrab = Flag.TRUE @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { pre.write(writer) post.write(writer) sideChain.write(writer) range.write(writer) resolution.write(writer) speed.write(writer) tilt.write(writer) freeze.write(writer) spectrumGrab.write(writer) } } private val processMode = ProcessMode.linearPhase(ProcessMode.Phase.Medium) private val channelMode = ChannelMode.LeftRight private val gain = Gain(0.0, 1.0) private val pan = OutputPan(0f) private val bypass = Flag.FALSE private val phaseInvert = Flag.FALSE private val autoGain = false private val analyzer = Analyzer() private val unknown1 = 2f private val midiLearn = Flag.FALSE private val unknown2 = -1f // solo band ?? private val unknown3 = 0f @Throws(IOException::class) fun write(writer: LittleEndianBinaryStreamWriter) { processMode.write(writer) channelMode.write(writer) gain.write(writer) pan.write(writer) bypass.write(writer) phaseInvert.write(writer) // Enabled value actually seems to be 2 writer.writeFloat((if (autoGain) 2 else 0).toFloat()) analyzer.write(writer) writer.writeFloat(unknown1) midiLearn.write(writer) writer.writeFloat(unknown2) writer.writeFloat(unknown3) } }
mit
e89eb8fd07ac535cb17c0d71b144cd1e
26.111111
79
0.554426
4.391649
false
false
false
false
carrotengineer/Warren
src/main/kotlin/engineer/carrot/warren/warren/ssl/WrappedSSLSocketFactory.kt
2
3477
package engineer.carrot.warren.warren.ssl import engineer.carrot.warren.warren.loggerFor import java.security.KeyManagementException import java.security.KeyStore import java.security.NoSuchAlgorithmException import java.security.SecureRandom import javax.net.ssl.* class WrappedSSLSocketFactory(private val fingerprints: Set<String>?) { val LOGGER = loggerFor<WrappedSSLSocketFactory>() private fun createDangerZoneSocketFactory(): SSLSocketFactory { val tm = arrayOf<TrustManager>(DangerZoneTrustAllX509TrustManager()) val context: SSLContext try { context = SSLContext.getInstance("TLS") } catch (e: NoSuchAlgorithmException) { throw RuntimeException("failed to create danger zone SSL Context for WrappedSSLSocketFactory: {}", e) } try { context.init(arrayOfNulls<KeyManager>(0), tm, SecureRandom()) } catch (e: KeyManagementException) { throw RuntimeException("failed to initialise danger zone custom SSL Context for WrappedSSLSocketFactory: {}", e) } return context.socketFactory } private fun createFingerprintsSocketFactory(fingerprints: Set<String>): SSLSocketFactory { val tm = arrayOf<TrustManager>(SHA256SignaturesX509TrustManager(fingerprints)) val context: SSLContext try { context = SSLContext.getInstance("TLS") } catch (e: NoSuchAlgorithmException) { throw RuntimeException("failed to create fingerprints SSL Context for WrappedSSLSocketFactory: {}", e) } try { context.init(arrayOfNulls<KeyManager>(0), tm, SecureRandom()) } catch (e: KeyManagementException) { throw RuntimeException("failed to initialise fingerprints custom SSL Context for WrappedSSLSocketFactory: {}", e) } return context.socketFactory } fun createDefaultFactory(sslParameters: SSLParameters, context: SSLContext): SSLSocketFactory { val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) val keyStore: KeyStore? = null trustManagerFactory.init(keyStore) context.init(arrayOfNulls<KeyManager>(0), trustManagerFactory.trustManagers, SecureRandom()) context.supportedSSLParameters.endpointIdentificationAlgorithm = sslParameters.endpointIdentificationAlgorithm context.supportedSSLParameters.cipherSuites = sslParameters.cipherSuites context.defaultSSLParameters.endpointIdentificationAlgorithm = sslParameters.endpointIdentificationAlgorithm context.defaultSSLParameters.cipherSuites = sslParameters.cipherSuites return context.socketFactory } fun createSocket(host: String, port: Int): SSLSocket { val context = SSLContext.getInstance("TLS") val sslParameters = SSLParameters() sslParameters.cipherSuites = SSLContext.getDefault().defaultSSLParameters.cipherSuites.filterNot { it.contains("_DHE_") }.toTypedArray() val factory: SSLSocketFactory = if (fingerprints == null) { createDefaultFactory(sslParameters, context) } else if (fingerprints.isEmpty()) { createDangerZoneSocketFactory() } else { createFingerprintsSocketFactory(fingerprints) } val socket = factory.createSocket(host, port) as SSLSocket socket.sslParameters = sslParameters return socket } }
isc
b86339a78fa5da4971506c59d28a8c29
39.430233
144
0.712683
5.484227
false
false
false
false
beyondeye/graphkool
graphkool-dataloader/src/main/kotlin/com/beyondeye/graphkool/dataloader/DataLoader.kt
1
8391
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package com.beyondeye.graphkool.dataloader import io.vertx.core.CompositeFuture import io.vertx.core.Future import io.vertx.core.json.JsonObject import java.util.Collections import java.util.LinkedHashMap import java.util.Objects import java.util.concurrent.atomic.AtomicInteger import java.util.stream.Collectors /** * Data loader is a utility class that allows batch loading of data that is identified by a set of unique keys. For * each key that is loaded a separate [Future] is returned, that completes as the batch function completes. * Besides individual futures a [CompositeFuture] of the batch is available as well. * * * With batching enabled the execution will start after calling [DataLoader.dispatch], causing the queue of * loaded keys to be sent to the batch function, clears the queue, and returns the [CompositeFuture]. * * * As batch functions are executed the resulting futures are cached using a cache implementation of choice, so they * will only execute once. Individual cache keys can be cleared, so they will be re-fetched when referred to again. * It is also possible to clear the cache entirely, and prime it with values before they are used. * * * Both caching and batching can be disabled. Configuration of the data loader is done by providing a * [DataLoaderOptions] instance on creation. * @param <K> type parameter indicating the type of the data load keys * * * @param <V> type parameter indicating the type of the data that is returned * * * * * @author [Arnold Schrijver](https://github.com/aschrijver/) </V></K> */ class DataLoader<K:Any, V> /** * Creates a new data loader with the provided batch load function and options. * @param batchLoadFunction the batch load function to use * * * @param options the batch load options */ (private val batchLoadFunction: BatchLoader<K>, options: DataLoaderOptions?) { private val loaderOptions: DataLoaderOptions private val futureCache: CacheMap<Any, Future<V>> private val loaderQueue: LinkedHashMap<K, Future<V>> /** * Creates a new data loader with the provided batch load function, and default options. * @param batchLoadFunction the batch load function to use */ constructor(batchLoadFunction: BatchLoader<K>) : this(batchLoadFunction, null) { } init { Objects.requireNonNull(batchLoadFunction, "Batch load function cannot be null") this.loaderOptions = options ?: DataLoaderOptions() this.futureCache = if (loaderOptions.cacheMap().isPresent) loaderOptions.cacheMap().get() as CacheMap<Any, Future<V>> else CacheMap.simpleMap<Any, V>() this.loaderQueue = LinkedHashMap<K, Future<V>>() } /** * Requests to load the data with the specified key asynchronously, and returns a future of the resulting value. * * * If batching is enabled (the default), you'll have to call [DataLoader.dispatch] at a later stage to * start batch execution. If you forget this call the future will never be completed (unless already completed, * and returned from cache). * @param key the key to load * * * @return the future of the value */ fun load(key: K): Future<V> { Objects.requireNonNull(key, "Key cannot be null") val cacheKey = getCacheKey(key) if (loaderOptions.cachingEnabled() && futureCache.containsKey(cacheKey)) { return futureCache[cacheKey] ?: Future.failedFuture("key not found") } val future = Future.future<V>() if (loaderOptions.batchingEnabled()) { loaderQueue.put(key, future) } else { val compositeFuture = batchLoadFunction.load(setOf(key)) if (compositeFuture.succeeded()) { future.complete(compositeFuture.result().resultAt<V>(0)) } else { future.fail(compositeFuture.cause()) } } if (loaderOptions.cachingEnabled()) { futureCache[cacheKey] = future } return future } /** * Requests to load the list of data provided by the specified keys asynchronously, and returns a composite future * of the resulting values. * * * If batching is enabled (the default), you'll have to call [DataLoader.dispatch] at a later stage to * start batch execution. If you forget this call the future will never be completed (unless already completed, * and returned from cache). * @param keys the list of keys to load * * * @return the composite future of the list of values */ fun loadMany(keys: List<K>): CompositeFuture { return CompositeFuture.all(keys.map { this.load(it) }) } /** * Dispatches the queued load requests to the batch execution function and returns a composite future of the result. * * * If batching is disabled, or there are no queued requests, then a succeeded composite future is returned. * @return the composite future of the queued load requests */ fun dispatch(): CompositeFuture { if (!loaderOptions.batchingEnabled() || loaderQueue.size == 0) { return CompositeFuture.all(emptyList<Future<*>>()) } val batch = batchLoadFunction.load(loaderQueue.keys) val index = AtomicInteger(0) loaderQueue.forEach { key, future -> if (batch.succeeded(index.get())) { future.complete(batch.resultAt<V>(index.get())) } else { future.fail(batch.cause(index.get())) } index.incrementAndGet() } loaderQueue.clear() return batch } /** * Clears the future with the specified key from the cache, if caching is enabled, so it will be re-fetched * on the next load request. * @param key the key to remove * * * @return the data loader for fluent coding */ fun clear(key: K): DataLoader<K, V> { val cacheKey = getCacheKey(key) futureCache.delete(cacheKey) return this } /** * Clears the entire cache map of the loader. * @return the data loader for fluent coding */ fun clearAll(): DataLoader<K, V> { futureCache.clear() return this } /** * Primes the cache with the given key and value. * @param key the key * * * @param value the value * * * @return the data loader for fluent coding */ fun prime(key: K, value: V): DataLoader<K, V> { val cacheKey = getCacheKey(key) if (!futureCache.containsKey(cacheKey)) { futureCache[cacheKey] = Future.succeededFuture(value) } return this } /** * Primes the cache with the given key and error. * @param key the key * * * @param error the exception to prime instead of a value * * * @return the data loader for fluent coding */ fun prime(key: K, error: Exception): DataLoader<K, V> { val cacheKey = getCacheKey(key) if (!futureCache.containsKey(cacheKey)) { futureCache[cacheKey] = Future.failedFuture<V>(error) } return this } /** * Gets the object that is used in the internal cache map as key, by applying the cache key function to * the provided key. * * * If no cache key function is present in [DataLoaderOptions], then the returned value equals the input key. * @param key the input key * * * @return the cache key after the input is transformed with the cache key function */ fun getCacheKey(key: K): Any { return loaderOptions.cacheKeyFunction()?.let { cacheKeyFn-> (key as? JsonObject)?.let { cacheKeyFn.getKey(it) } }?:key } }
apache-2.0
fb75208337a2871f94a03a6a045bf242
34.405063
159
0.653557
4.31858
false
false
false
false
emoji-gen/Emoji-Android
app/src/main/java/moe/pine/emoji/components/generator/EmojiRegisterComponent.kt
1
1133
package moe.pine.emoji.components.generator import kotlinx.android.synthetic.main.dialog_register.view.* import moe.pine.emoji.task.RegisterAndSaveTask import moe.pine.emoji.util.hideSoftInput import moe.pine.emoji.view.generator.RegisterDialogView import moe.pine.emoji.view.generator.binding.emojiName import moe.pine.emoji.view.generator.binding.team /** * Component for emoji register * Created by pine on May 14, 2017. */ class EmojiRegisterComponent( val view: RegisterDialogView ) { fun onFinishInflate() { this.view.button_generator_register_button.setOnClickListener { this.register() } } private fun register() { this.view.hideSoftInput() val fragment = this.view.fragment ?: return val team = this.view.team ?: return val arguments = RegisterAndSaveTask.Arguments( team = team, emojiName = this.view.emojiName, previewUri = this.view.previewUri, downloadUri = this.view.downloadUri ) val task = RegisterAndSaveTask(fragment, arguments) task.execute() } }
mit
31c6742cddd4d3d39aa11dcffa4f180b
30.5
89
0.681377
4.275472
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/spvc/src/templates/kotlin/spvc/SpvcTypes.kt
3
13185
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package spvc import org.lwjgl.generator.* val SpvId = typedef(unsigned_int, "SpvId") /* spirv.h */ val SpvAccessQualifier = "SpvAccessQualifier".enumType val SpvBuiltIn = "SpvBuiltIn".enumType val SpvCapability = "SpvCapability".enumType val SpvDecoration = "SpvDecoration".enumType val SpvDim = "SpvDim".enumType val SpvExecutionMode = "SpvExecutionMode".enumType val SpvExecutionModel = "SpvExecutionModel".enumType val SpvImageFormat = "SpvImageFormat".enumType val SpvStorageClass = "SpvStorageClass".enumType /* spirv_cross_c.h */ val spvc_compiler = "spvc_compiler".handle val spvc_compiler_options = "spvc_compiler_options".handle val spvc_constant = "spvc_constant".handle val spvc_context = "spvc_context".handle val spvc_parsed_ir = "spvc_parsed_ir".handle val spvc_resources = "spvc_resources".handle val spvc_set = "spvc_set".handle val spvc_type = "spvc_type".handle val spvc_bool = typedef(IntegerType("unsigned char", PrimitiveMapping.BOOLEAN, unsigned = true), "spvc_bool") val spvc_constant_id = typedef(SpvId, "spvc_constant_id") val spvc_type_id = typedef(SpvId, "spvc_type_id") val spvc_variable_id = typedef(SpvId, "spvc_variable_id") val spvc_backend = "spvc_backend".enumType val spvc_basetype = "spvc_basetype".enumType val spvc_builtin_resource_type = "spvc_builtin_resource_type".enumType val spvc_capture_mode = "spvc_capture_mode".enumType val spvc_compiler_option = "spvc_compiler_option".enumType val spvc_hlsl_binding_flags = "spvc_hlsl_binding_flags".enumType val spvc_msl_chroma_location = "spvc_msl_chroma_location".enumType val spvc_msl_component_swizzle = "spvc_msl_component_swizzle".enumType val spvc_msl_format_resolution = "spvc_msl_format_resolution".enumType val spvc_msl_sampler_address = "spvc_msl_sampler_address".enumType val spvc_msl_sampler_border_color = "spvc_msl_sampler_border_color".enumType val spvc_msl_sampler_compare_func = "spvc_msl_sampler_compare_func".enumType val spvc_msl_sampler_coord = "spvc_msl_sampler_coord".enumType val spvc_msl_sampler_filter = "spvc_msl_sampler_filter".enumType val spvc_msl_sampler_mip_filter = "spvc_msl_sampler_mip_filter".enumType val spvc_msl_sampler_ycbcr_model_conversion = "spvc_msl_sampler_ycbcr_model_conversion".enumType val spvc_msl_sampler_ycbcr_range = "spvc_msl_sampler_ycbcr_range".enumType val spvc_msl_vertex_format = "spvc_msl_vertex_format".enumType val spvc_resource_type = "spvc_resource_type".enumType val spvc_result = "spvc_result".enumType val spvc_reflected_resource = struct(Module.SPVC, "SpvcReflectedResource", nativeName = "spvc_reflected_resource") { spvc_variable_id("id", "Resources are identified with their SPIR-V ID. This is the ID of the OpVariable.") spvc_type_id( "base_type_id", """ The base type of the declared resource. This type is the base type which ignores pointers and arrays of the {@code type_id}. This is mostly useful to parse decorations of the underlying type. {@code base_type_id} can also be obtained with {@code get_type(get_type(type_id).self)}. """ ) spvc_type_id( "type_id", """ The type ID of the variable which includes arrays and all type modifications. This type ID is not suitable for parsing {@code OpMemberDecoration} of a struct and other decorations in general since these modifications typically happen on the {@code base_type_id}. """ ) charUTF8.const.p( "name", """ The declared name ({@code OpName}) of the resource. For Buffer blocks, the name actually reflects the externally visible {@code Block} name. This name can be retrieved again by using either {@code get_name(id)} or {@code get_name(base_type_id)} depending if it's a buffer block or not. This name can be an empty string in which case {@code get_fallback_name(id)} can be used which obtains a suitable fallback identifier for an ID. """ ) } val spvc_reflected_builtin_resource = struct(Module.SPVC, "SpvcReflectedBuiltinResource", nativeName = "spvc_reflected_builtin_resource") { SpvBuiltIn( "builtin", """ This is mostly here to support reflection of builtins such as {@code Position/PointSize/CullDistance/ClipDistance}. This needs to be different from {@code Resource} since we can collect builtins from blocks. A builtin present here does not necessarily mean it's considered an active builtin, since variable ID "activeness" is only tracked on {@code OpVariable} level, not {@code Block} members. For that, #compiler_update_active_builtins() -&gt; #compiler_has_active_builtin() can be used to further refine the reflection. """ ) spvc_type_id( "value_type_id", """ This is the actual value type of the builtin. Typically {@code float4}, {@code float}, {@code array<float, N>} for the {@code gl_PerVertex} builtins. If the builtin is a control point, the control point array type will be stripped away here as appropriate. """ ) spvc_reflected_resource( "resource", """ This refers to the base resource which contains the builtin. If resource is a {@code Block}, it can hold multiple builtins, or it might not be a block. For advanced reflection scenarios, all information in builtin/{@code value_type_id} can be deduced, it's just more convenient this way. """ ) } val spvc_entry_point = struct(Module.SPVC, "SpvcEntryPoint", nativeName = "spvc_entry_point") { SpvExecutionModel("execution_model", "") charUTF8.const.p("name", "") } val spvc_combined_image_sampler = struct(Module.SPVC, "SpvcCombinedImageSampler", nativeName = "spvc_combined_image_sampler") { spvc_variable_id("combined_id", "the ID of the {@code sampler2D} variable") spvc_variable_id("image_id", "the ID of the {@code texture2D} variable") spvc_variable_id("sampler_id", "the ID of the {@code sampler} variable") } val spvc_specialization_constant = struct(Module.SPVC, "SpvcSpecializationConstant", nativeName = "spvc_specialization_constant") { spvc_constant_id("id", "the ID of the specialization constant") unsigned_int("constant_id", "the constant ID of the constant, used in Vulkan during pipeline creation") } val spvc_buffer_range = struct(Module.SPVC, "SpvcBufferRange", nativeName = "spvc_buffer_range") { unsigned_int("index", "") size_t("offset", "") size_t("range", "") } val spvc_hlsl_root_constants = struct(Module.SPVC, "SpvcHlslRootConstants", nativeName = "spvc_hlsl_root_constants") { documentation = """ Specifying a root constant (d3d12) or push constant range (vulkan). {@code start} and {@code end} denotes the range of the root constant in bytes. Both values need to be multiple of 4. """ unsigned_int("start", "") unsigned_int("end", "") unsigned_int("binding", "") unsigned_int("space", "") } val spvc_hlsl_vertex_attribute_remap = struct(Module.SPVC, "SpvcHlslVertexAttributeRemap", nativeName = "spvc_hlsl_vertex_attribute_remap") { documentation = "Interface which remaps vertex inputs to a fixed semantic name to make linking easier." unsigned_int("location", "") charUTF8.const.p("semantic", "") } val spvc_msl_vertex_attribute = struct(Module.SPVC, "SpvcMslVertexAttribute", nativeName = "spvc_msl_vertex_attribute") { documentation = """ Defines MSL characteristics of a vertex attribute at a particular location. After compilation, it is possible to query whether or not this location was used. Deprecated; use ##SpvcMslShaderInterfaceVar. """ unsigned_int("location", "") unsigned_int("msl_buffer", "Obsolete, do not use. Only lingers on for ABI compatibility.") unsigned_int("msl_offset", "Obsolete, do not use. Only lingers on for ABI compatibility.") unsigned_int("msl_stride", "Obsolete, do not use. Only lingers on for ABI compatibility.") spvc_bool("per_instance", "Obsolete, do not use. Only lingers on for ABI compatibility.") spvc_msl_vertex_format("format", "") SpvBuiltIn("builtin", "") } val spvc_msl_shader_interface_var = struct(Module.SPVC, "SpvcMslShaderInterfaceVar", nativeName = "spvc_msl_shader_interface_var") { documentation = """ Defines MSL characteristics of an input variable at a particular location. After compilation, it is possible to query whether or not this location was used. If {@code vecsize} is nonzero, it must be greater than or equal to the {@code vecsize} declared in the shader, or behavior is undefined. """ unsigned("location", "") spvc_msl_vertex_format("format", "") SpvBuiltIn("builtin", "") unsigned("vecsize", "") } val spvc_msl_shader_input = typedef(spvc_msl_shader_interface_var, "spvc_msl_shader_input", "SpvcMslShaderInput") val spvc_msl_resource_binding = struct(Module.SPVC, "SpvcMslResourceBinding", nativeName = "spvc_msl_resource_binding") { documentation = """ Matches the binding index of a MSL resource for a binding within a descriptor set. Taken together, the {@code stage}, {@code desc_set} and {@code binding} combine to form a reference to a resource descriptor used in a particular shading stage. If using MSL 2.0 argument buffers, the descriptor set is not marked as a discrete descriptor set, and (for iOS only) the resource is not a storage image ({@code sampled != 2}), the binding reference we remap to will become an {@code [[id(N)]]} attribute within the "descriptor set" argument buffer structure. For resources which are bound in the "classic" MSL 1.0 way or discrete descriptors, the remap will become a {@code [[buffer(N)]]}, {@code [[texture(N)]]} or {@code [[sampler(N)]]} depending on the resource types used. """ SpvExecutionModel("stage", "") unsigned_int("desc_set", "") unsigned_int("binding", "") unsigned_int("msl_buffer", "") unsigned_int("msl_texture", "") unsigned_int("msl_sampler", "") } val spvc_msl_constexpr_sampler = struct(Module.SPVC, "SpvcMslConstexprSampler", nativeName = "spvc_msl_constexpr_sampler") { spvc_msl_sampler_coord("coord", "") spvc_msl_sampler_filter("min_filter", "") spvc_msl_sampler_filter("mag_filter", "") spvc_msl_sampler_mip_filter("mip_filter", "") spvc_msl_sampler_address("s_address", "") spvc_msl_sampler_address("t_address", "") spvc_msl_sampler_address("r_address", "") spvc_msl_sampler_compare_func("compare_func", "") spvc_msl_sampler_border_color("border_color", "") float("lod_clamp_min", "") float("lod_clamp_max", "") int("max_anisotropy", "") spvc_bool("compare_enable", "") spvc_bool("lod_clamp_enable", "") spvc_bool("anisotropy_enable", "") } val spvc_msl_sampler_ycbcr_conversion = struct(Module.SPVC, "SpvcMslSamplerYcbcrConversion", nativeName = "spvc_msl_sampler_ycbcr_conversion") { documentation = "Maps to the sampler Y'CbCr conversion-related portions of {@code MSLConstexprSampler}." unsigned_int("planes", "") spvc_msl_format_resolution("resolution", "") spvc_msl_sampler_filter("chroma_filter", "") spvc_msl_chroma_location("x_chroma_offset", "") spvc_msl_chroma_location("y_chroma_offset", "") spvc_msl_component_swizzle("swizzle", "")[4] spvc_msl_sampler_ycbcr_model_conversion("ycbcr_model", "") spvc_msl_sampler_ycbcr_range("ycbcr_range", "") unsigned_int("bpc", "") } val spvc_hlsl_resource_binding_mapping = struct(Module.SPVC, "SpvcHLSLResourceBindingMapping", nativeName = "spvc_hlsl_resource_binding_mapping") { unsigned("register_space", "") unsigned("register_binding", "") } val spvc_hlsl_resource_binding = struct(Module.SPVC, "SpvcHLSLResourceBinding", nativeName = "spvc_hlsl_resource_binding") { SpvExecutionModel("stage", "") unsigned("desc_set", "") unsigned("binding", "") spvc_hlsl_resource_binding_mapping("cbv", "") spvc_hlsl_resource_binding_mapping("uav", "") spvc_hlsl_resource_binding_mapping("srv", "") spvc_hlsl_resource_binding_mapping("sampler", "") } val spvc_error_callback = Module.SPVC.callback { void( "SpvcErrorCallback", "Get notified in a callback when an error triggers. Useful for debugging.", opaque_p("userdata", ""), charUTF8.const.p("error", ""), nativeType = "spvc_error_callback" ) { documentation = "Instances of this interface may be passed to the #context_set_error_callback() method." additionalCode = """ /** * Converts the specified {@code spvc_error_callback} argument to a String. * * <p>This method may only be used inside a {@code SpvcErrorCallback} invocation.</p> * * @param error the error argument to decode * * @return the error message as a String */ public static String getError(long error) { return memUTF8(error); } """ } }
bsd-3-clause
73719404df933817f3536e01ba208b08
43.846939
159
0.689875
3.573171
false
false
false
false
xingyuli/swordess-location
src/main/kotlin/org/swordess/common/location/impl/LocationImpl.kt
1
2286
/* * The MIT License (MIT) * * Copyright (c) 2016 Vic Lau * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.swordess.common.location.impl import org.swordess.common.location.Location import org.swordess.common.location.Place import java.util.HashMap class LocationImpl : Location { private val countryCodeToCountries: MutableMap<String, Place.Country> = HashMap() lateinit var defaultCountryCode: String constructor(addressFiles: Set<String>) { addressFiles.forEach { PlaceParser.parse(it).forEach { countryCodeToCountries[it.code] = it } } } override fun findCountry(): Place.Country? = defaultCountry() override fun findState(stateCode: String): Place.State? = findCountry()?.states?.firstOrNull { stateCode == it.code } override fun findCity(stateCode: String, cityCode: String): Place.City? = findState(stateCode)?.cities?.firstOrNull { cityCode == it.code } override fun findRegion(stateCode: String, cityCode: String, regionCode: String): Place.Region? = findCity(stateCode, cityCode)?.regions?.firstOrNull { regionCode == it.code } private fun defaultCountry(): Place.Country? = countryCodeToCountries[defaultCountryCode] }
mit
1c155e95ef4ab72ff171cab260941b5f
39.839286
101
0.735346
4.430233
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/imports/internal/TrackerImportConflictParser.kt
1
6320
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.imports.internal import dagger.Reusable import javax.inject.Inject import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore import org.hisp.dhis.android.core.dataelement.DataElement import org.hisp.dhis.android.core.imports.TrackerImportConflict import org.hisp.dhis.android.core.imports.internal.conflicts.* import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttribute import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueCollectionRepository import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueCollectionRepository @Reusable internal class TrackerImportConflictParser @Inject constructor( attributeStore: IdentifiableObjectStore<TrackedEntityAttribute>, dataElementStore: IdentifiableObjectStore<DataElement>, private val trackedEntityAttributeValueRepository: TrackedEntityAttributeValueCollectionRepository, private val trackedEntityInstanceDataValueRepository: TrackedEntityDataValueCollectionRepository ) { private val context = TrackerImportConflictItemContext(attributeStore, dataElementStore) private val commonConflicts = listOf( LackingEnrollmentCascadeDeleteAuthorityConflict, LackingTEICascadeDeleteAuthorityConflict, TrackedEntityInstanceNotFoundConflict, EventNotFoundConflict, EventHasInvalidProgramConflict, EventHasInvalidProgramStageConflict, EnrollmentNotFoundConflict, EnrollmentHasInvalidProgramConflict, FileResourceAlreadyAssignedConflict, FileResourceReferenceNotFoundConflict ) private val trackedEntityInstanceConflicts: List<TrackerImportConflictItem> = commonConflicts + listOf( InvalidAttributeValueTypeConflict, MissingAttributeConflict, BadAttributePatternConflict, NonUniqueAttributeConflict, InvalidTrackedEntityTypeConflict ) private val enrollmentConflicts: List<TrackerImportConflictItem> = commonConflicts + listOf( InvalidAttributeValueTypeConflict, MissingAttributeConflict, BadAttributePatternConflict, NonUniqueAttributeConflict ) private val eventConflicts: List<TrackerImportConflictItem> = commonConflicts + listOf( InvalidDataValueConflict, MissingDataElementConflict ) fun getTrackedEntityInstanceConflict( conflict: ImportConflict, conflictBuilder: TrackerImportConflict.Builder ): TrackerImportConflict { return evaluateConflicts(conflict, conflictBuilder, trackedEntityInstanceConflicts) } fun getEnrollmentConflict( conflict: ImportConflict, conflictBuilder: TrackerImportConflict.Builder ): TrackerImportConflict { return evaluateConflicts(conflict, conflictBuilder, enrollmentConflicts) } fun getEventConflict( conflict: ImportConflict, conflictBuilder: TrackerImportConflict.Builder ): TrackerImportConflict { return evaluateConflicts(conflict, conflictBuilder, eventConflicts) } private fun evaluateConflicts( conflict: ImportConflict, conflictBuilder: TrackerImportConflict.Builder, conflictTypes: List<TrackerImportConflictItem> ): TrackerImportConflict { val conflictType = conflictTypes.find { it.matches(conflict) } if (conflictType != null) { conflictBuilder .errorCode(conflictType.errorCode) .displayDescription(conflictType.getDisplayDescription(conflict, context)) .trackedEntityAttribute(conflictType.getTrackedEntityAttribute(conflict)) .dataElement(conflictType.getDataElement(conflict)) } else { conflictBuilder .displayDescription(conflict.value()) } return conflictBuilder .conflict(conflict.value()) .value(getConflictValue(conflictBuilder)) .build() } private fun getConflictValue(conflictBuilder: TrackerImportConflict.Builder): String? { val auxConflict = conflictBuilder.build() return if (auxConflict.dataElement() != null && auxConflict.event() != null) { trackedEntityInstanceDataValueRepository .value(auxConflict.event(), auxConflict.dataElement()) .blockingGet()?.value() } else if (auxConflict.trackedEntityAttribute() != null && auxConflict.trackedEntityInstance() != null) { trackedEntityAttributeValueRepository .value(auxConflict.trackedEntityAttribute(), auxConflict.trackedEntityInstance()) .blockingGet()?.value() } else { null } } }
bsd-3-clause
a19572a13a356a7718f982600051bb97
43.195804
113
0.744937
5.500435
false
false
false
false
fyookball/electrum
android/app/src/main/java/org/electroncash/electroncash3/Requests.kt
1
7237
package org.electroncash.electroncash3 import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.View import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.observe import com.chaquo.python.PyObject import kotlinx.android.synthetic.main.amount_box.* import kotlinx.android.synthetic.main.main.* import kotlinx.android.synthetic.main.request_detail.* import kotlinx.android.synthetic.main.requests.* class RequestsFragment : Fragment(R.layout.requests), MainFragment { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { setupVerticalList(rvRequests) rvRequests.adapter = RequestsAdapter(activity!!) TriggerLiveData().apply { addSource(daemonUpdate) addSource(settings.getString("base_unit")) }.observe(viewLifecycleOwner, { refresh() }) btnAdd.setOnClickListener { newRequest(activity!!) } } fun refresh() { val wallet = daemonModel.wallet (rvRequests.adapter as RequestsAdapter).submitList( if (wallet == null) null else RequestsList(wallet)) } } fun newRequest(activity: FragmentActivity) { try { val address = daemonModel.wallet!!.callAttr("get_unused_address") ?: throw ToastException(R.string.no_more) showDialog(activity, RequestDialog(address.callAttr("to_storage_string").toString())) } catch (e: ToastException) { e.show() } } class RequestsList(wallet: PyObject) : AbstractList<RequestModel>() { val requests = wallet.callAttr("get_sorted_requests", daemonModel.config).asList() override val size: Int get() = requests.size override fun get(index: Int) = RequestModel(requests.get(index)) } class RequestsAdapter(val activity: FragmentActivity) : BoundAdapter<RequestModel>(R.layout.request_list) { override fun onBindViewHolder(holder: BoundViewHolder<RequestModel>, position: Int) { super.onBindViewHolder(holder, position) holder.itemView.setOnClickListener { showDialog(activity, RequestDialog(holder.item.address)) } } } class RequestModel(val request: PyObject) { val address = getField("address").toString() val amount = formatSatoshis(getField("amount").toLong()) val timestamp = libUtil.callAttr("format_time", getField("time")).toString() val description = getField("memo").toString() val status = formatStatus(getField("status").toInt()) private fun formatStatus(status: Int): Any { return app.resources.getStringArray(R.array.payment_status)[status] } private fun getField(key: String): PyObject { return request.callAttr("get", key)!! } } class RequestDialog() : AlertDialogFragment() { val wallet by lazy { daemonModel.wallet!! } init { if (wallet.callAttr("is_watching_only").toBoolean()) { throw ToastException(R.string.this_wallet_is) } } val address by lazy { clsAddress.callAttr("from_string", arguments!!.getString("address")) } val existingRequest by lazy { wallet.callAttr("get_payment_request", address, daemonModel.config) } constructor(address: String): this() { arguments = Bundle().apply { putString("address", address) } } override fun onBuildDialog(builder: AlertDialog.Builder) { with (builder) { setView(R.layout.request_detail) setNegativeButton(android.R.string.cancel, null) setPositiveButton(android.R.string.ok, null) if (existingRequest != null) { setNeutralButton(R.string.delete, null) } } } override fun onShowDialog() { btnCopy.setOnClickListener { copyToClipboard(getUri(), R.string.request_uri) } tvAddress.text = address.callAttr("to_ui_string").toString() tvUnit.text = unitName val tw = object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable?) { updateUI() } } for (et in listOf(etAmount, etDescription)) { et.addTextChangedListener(tw) } fiatUpdate.observe(this, { updateUI() }) dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { onOK() } if (existingRequest != null) { dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener { showDialog(this, RequestDeleteDialog(address)) } } } override fun onFirstShowDialog() { val request = existingRequest if (request != null) { val model = RequestModel(request) etAmount.setText(model.amount) etDescription.setText(model.description) } // We don't <requestFocus/> in the layout file, because it's also included by the // Send dialog, where the initial focus should be on the address box. etAmount.requestFocus() } private fun updateUI() { showQR(imgQR, getUri()) amountBoxUpdate(dialog) } private fun getUri(): String { var amount: Long? = null try { amount = amountBoxGet(dialog) } catch (e: ToastException) {} return libWeb.callAttr("create_URI", address, amount, description).toString() } private fun onOK() { try { val amount = amountBoxGet(dialog) wallet.callAttr( "add_payment_request", wallet.callAttr("make_payment_request", address, amount, description), daemonModel.config) } catch (e: ToastException) { e.show() } daemonUpdate.setValue(Unit) dismiss() // If the dialog was opened from the Transactions screen, we should now switch to // the Requests screen so the user can verify that the request has been saved. (activity as MainActivity).navBottom.selectedItemId = R.id.navRequests } val description get() = etDescription.text.toString() } class RequestDeleteDialog() : AlertDialogFragment() { constructor(addr: PyObject) : this() { arguments = Bundle().apply { putString("address", addr.callAttr("to_storage_string").toString()) } } override fun onBuildDialog(builder: AlertDialog.Builder) { builder.setTitle(R.string.confirm_delete) .setMessage(R.string.are_you_sure_you_wish_to_proceed) .setPositiveButton(R.string.delete) { _, _ -> daemonModel.wallet!!.callAttr("remove_payment_request", makeAddress(arguments!!.getString("address")!!), daemonModel.config) daemonUpdate.setValue(Unit) (targetFragment as RequestDialog).dismiss() } .setNegativeButton(android.R.string.cancel, null) } }
mit
a02240db197094c99e199f46f5a60ac2
33.626794
99
0.638386
4.624281
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/fir-fe10-binding/src/org/jetbrains/kotlin/idea/fir/fe10/KtSymbolBasedResolutionFacade.kt
2
4611
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.fir.fe10 import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.analyzer.ResolverForProject import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.caches.resolve.PlatformAnalysisSettings import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.fir.fe10.binding.KtSymbolBasedBindingContext import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.diagnostics.BindingContextSuppressCache import org.jetbrains.kotlin.resolve.diagnostics.KotlinSuppressCache import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.safeAs class KtSymbolBasedResolutionFacade( override val project: Project, val context: FE10BindingContext ) : ResolutionFacade { override fun analyze(element: KtElement, bodyResolveMode: BodyResolveMode): BindingContext = KtSymbolBasedBindingContext(context) override fun analyze(elements: Collection<KtElement>, bodyResolveMode: BodyResolveMode): BindingContext = KtSymbolBasedBindingContext(context) override fun analyzeWithAllCompilerChecks(elements: Collection<KtElement>, callback: DiagnosticSink.DiagnosticsCallback?): AnalysisResult { return AnalysisResult.success(KtSymbolBasedBindingContext(context), context.moduleDescriptor) } override fun resolveToDescriptor(declaration: KtDeclaration, bodyResolveMode: BodyResolveMode): DeclarationDescriptor { val ktSymbol = context.withAnalysisSession { declaration.getSymbol() } return ktSymbol.toDeclarationDescriptor(context) } override val moduleDescriptor: ModuleDescriptor get() = context.moduleDescriptor @FrontendInternals override fun <T : Any> getFrontendService(serviceClass: Class<T>): T { TODO("Not yet implemented") } @FrontendInternals override fun <T : Any> getFrontendService(element: PsiElement, serviceClass: Class<T>): T { TODO("Not yet implemented") } @FrontendInternals override fun <T : Any> getFrontendService(moduleDescriptor: ModuleDescriptor, serviceClass: Class<T>): T { TODO("Not yet implemented") } override fun <T : Any> getIdeService(serviceClass: Class<T>): T { TODO("Not yet implemented") } @FrontendInternals override fun <T : Any> tryGetFrontendService(element: PsiElement, serviceClass: Class<T>): T? { TODO("Not yet implemented") } override fun getResolverForProject(): ResolverForProject<out ModuleInfo> { TODO("Not yet implemented") } } class KtSymbolBasedKotlinCacheServiceImpl(val project: Project) : KotlinCacheService { override fun getResolutionFacadeWithForcedPlatform(elements: List<KtElement>, platform: TargetPlatform): ResolutionFacade { TODO("Not yet implemented") } override fun getResolutionFacade(element: KtElement): ResolutionFacade { return getResolutionFacade(listOf(element)) } override fun getResolutionFacade(elements: List<KtElement>): ResolutionFacade = KtSymbolBasedResolutionFacade(project, FE10BindingContextImpl(project, elements.first())) override fun getResolutionFacadeByFile(file: PsiFile, platform: TargetPlatform): ResolutionFacade? = file.safeAs<KtFile>()?.let { KtSymbolBasedResolutionFacade(project, FE10BindingContextImpl(project, it)) } override fun getSuppressionCache(): KotlinSuppressCache { return BindingContextSuppressCache(BindingContext.EMPTY) } override fun getResolutionFacadeByModuleInfo(moduleInfo: ModuleInfo, platform: TargetPlatform): ResolutionFacade = TODO("Not yet implemented") override fun getResolutionFacadeByModuleInfo(moduleInfo: ModuleInfo, settings: PlatformAnalysisSettings): ResolutionFacade? { TODO("Not yet implemented") } }
apache-2.0
5deb3439b19d6c0c0b787560228acb04
41.703704
143
0.779874
5.318339
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinSealedInheritorsInJavaInspection.kt
2
2339
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.* import com.intellij.psi.impl.source.PsiClassReferenceType import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.descriptors.isSealed import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.memberInfo.getClassDescriptorIfAny class KotlinSealedInheritorsInJavaInspection : LocalInspectionTool() { companion object { private fun PsiClass.listSealedParentReferences(): List<PsiReference> { if (this is PsiAnonymousClass && baseClassType.isKotlinSealed()) return listOf(baseClassReference) val sealedBaseClasses = extendsList?.listSealedMembers() val sealedBaseInterfaces = implementsList?.listSealedMembers() return sealedBaseClasses.orEmpty() + sealedBaseInterfaces.orEmpty() } private fun PsiReferenceList.listSealedMembers(): List<PsiReference> = referencedTypes .filter { it.isKotlinSealed() } .mapNotNull { it as? PsiClassReferenceType } .map { it.reference } private fun PsiClassType.isKotlinSealed(): Boolean = resolve()?.isKotlinSealed() == true private fun PsiClass.isKotlinSealed(): Boolean { return this is KtLightClass && (getClassDescriptorIfAny()?.isSealed() ?: false) } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : JavaElementVisitor() { override fun visitClass(aClass: PsiClass) { if (aClass is PsiTypeParameter) return aClass.listSealedParentReferences().forEach { holder.registerProblem( it, KotlinBundle.message("inheritance.of.kotlin.sealed", 0.takeIf { aClass.isInterface } ?: 1), ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) } } } } }
apache-2.0
9eb005579f8566c8c203e20f72b7097b
43.150943
158
0.692604
5.352403
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantIfInspection.kt
4
4935
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.CodeInsightUtil import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.intentions.negate import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* class RedundantIfInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return ifExpressionVisitor { expression -> if (expression.condition == null) return@ifExpressionVisitor val (redundancyType, branchType) = RedundancyType.of(expression) if (redundancyType == RedundancyType.NONE) return@ifExpressionVisitor holder.registerProblem( expression, KotlinBundle.message("redundant.if.statement"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, RemoveRedundantIf(redundancyType, branchType) ) } } private sealed class BranchType { object Simple : BranchType() object Return : BranchType() data class LabeledReturn(val label: String) : BranchType() class Assign(val lvalue: KtExpression) : BranchType() { override fun equals(other: Any?) = other is Assign && lvalue.text == other.lvalue.text override fun hashCode() = lvalue.text.hashCode() } } private enum class RedundancyType { NONE, THEN_TRUE, ELSE_TRUE; companion object { internal fun of(expression: KtIfExpression): Pair<RedundancyType, BranchType> { val (thenReturn, thenType) = expression.then.getBranchExpression() ?: return NONE to BranchType.Simple val (elseReturn, elseType) = expression.`else`.getBranchExpression() ?: return NONE to BranchType.Simple return when { thenType != elseType -> NONE to BranchType.Simple KtPsiUtil.isTrueConstant(thenReturn) && KtPsiUtil.isFalseConstant(elseReturn) -> THEN_TRUE to thenType KtPsiUtil.isFalseConstant(thenReturn) && KtPsiUtil.isTrueConstant(elseReturn) -> ELSE_TRUE to thenType else -> NONE to BranchType.Simple } } private fun KtExpression?.getBranchExpression(): Pair<KtExpression?, BranchType>? { return when (this) { is KtReturnExpression -> { val branchType = labeledExpression?.let { BranchType.LabeledReturn(it.text) } ?: BranchType.Return returnedExpression to branchType } is KtBlockExpression -> statements.singleOrNull()?.getBranchExpression() is KtBinaryExpression -> if (operationToken == KtTokens.EQ && left != null) right to BranchType.Assign(left!!) else null is KtExpression -> this to BranchType.Simple else -> null } } } } private class RemoveRedundantIf(private val redundancyType: RedundancyType, @SafeFieldForPreview // may refer to PsiElement of original file but we are only reading from it private val branchType: BranchType) : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.redundant.if.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as KtIfExpression val condition = when (redundancyType) { RedundancyType.NONE -> return RedundancyType.THEN_TRUE -> element.condition!! RedundancyType.ELSE_TRUE -> element.condition!!.negate() } val factory = KtPsiFactory(element) element.replace( when (branchType) { is BranchType.Return -> factory.createExpressionByPattern("return $0", condition) is BranchType.LabeledReturn -> factory.createExpressionByPattern("return${branchType.label} $0", condition) is BranchType.Assign -> factory.createExpressionByPattern("$0 = $1", branchType.lvalue, condition) else -> condition } ) } } }
apache-2.0
22a4798b16548eb3f32d46c3c97c14c2
45.121495
158
0.624113
5.588901
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/usecases/itemtracker_dynamodb/src/main/kotlin/com/aws/rest/App.kt
1
3265
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.aws.rest import kotlinx.coroutines.runBlocking import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.CrossOrigin import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import java.io.IOException @SpringBootApplication open class App fun main(args: Array<String>) { runApplication<App>(*args) } @CrossOrigin(origins = ["*"]) @RestController class MessageResource { @Autowired private lateinit var dbService: DynamoDBService @Autowired private lateinit var sendMsg: SendMessage // Add a new item to the Amazon DynamoDB database. @PostMapping("api/items") fun addItems(@RequestBody payLoad: Map<String, Any>): String = runBlocking { val nameVal = "user" val guideVal = payLoad.get("guide").toString() val descriptionVal = payLoad.get("description").toString() val statusVal = payLoad.get("status").toString() // Create a Work Item object. val myWork = WorkItem() myWork.guide = guideVal myWork.description = descriptionVal myWork.status = statusVal myWork.name = nameVal val id = dbService.putItemInTable(myWork) return@runBlocking "Item $id added successfully!" } // Retrieve items. @GetMapping("api/items") fun getItems(@RequestParam(required = false) archived: String?): MutableList<WorkItem> = runBlocking { val list: MutableList<WorkItem> if (archived == "false") { list = dbService.getOpenItems(false) } else if (archived == "true") { list = dbService.getOpenItems(true) } else { list = dbService.getAllItems() } return@runBlocking list } // Flip an item from Active to Archive. @PutMapping("api/items/{id}:archive") @ResponseStatus(value = HttpStatus.NO_CONTENT) fun modUser(@PathVariable id: String) = runBlocking { dbService.archiveItemEC(id) return@runBlocking } @PostMapping("api/items:report") @ResponseStatus(value = HttpStatus.NO_CONTENT) fun sendReport(@RequestBody body: Map<String, String>) = runBlocking { val email = body.get("email") val xml = dbService.getOpenReport(false) try { if (email != null) { sendMsg.send(email, xml) } } catch (e: IOException) { e.stackTrace } return@runBlocking } }
apache-2.0
3727b9de512e87873d88f310735b3ccc
32.368421
106
0.673201
4.40027
false
false
false
false
facebook/redex
test/instr/ClassMergingKotlinCoroutinesTest.kt
1
847
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.redextest import kotlin.sequences.sequence import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope internal abstract class Base() { open abstract fun fibonacciSeq(x: Int): Sequence<Int> } internal class A : Base() { override fun fibonacciSeq(x: Int): Sequence<Int> = sequence { var b = 1 var a = x yield(5) while (true) { yield(a + b) val tmp = a + b a = b b = tmp } } } class ClassMergingKotlinCoroutinesTest { fun main(args: Array<String>) { val a = A() a.fibonacciSeq(0).take(5).toList() CoroutineScope(CoroutineName("Parent")) } }
mit
166b88623205ba2a1c0869b6008f3d56
18.697674
66
0.66588
3.682609
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/s3/src/main/kotlin/com/kotlin/s3/DeleteBucketPolicy.kt
1
1632
// snippet-sourcedescription:[DeleteBucketPolicy.kt demonstrates how to delete a policy from an Amazon Simple Storage Service (Amazon S3) bucket.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon S3] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.s3 // snippet-start:[s3.kotlin.delete_bucket_policy.import] import aws.sdk.kotlin.services.s3.S3Client import aws.sdk.kotlin.services.s3.model.DeleteBucketPolicyRequest import kotlin.system.exitProcess // snippet-end:[s3.kotlin.delete_bucket_policy.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <bucketName> Where: bucketName - The Amazon S3 bucket from which to delete the policy. """ if (args.size != 1) { println(usage) exitProcess(0) } val bucketName = args[0] deleteS3BucketPolicy(bucketName) } // snippet-start:[s3.kotlin.delete_bucket_policy.main] suspend fun deleteS3BucketPolicy(bucketName: String?) { val request = DeleteBucketPolicyRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.deleteBucketPolicy(request) println("Done!") } } // snippet-end:[s3.kotlin.delete_bucket_policy.main]
apache-2.0
3527dafec3194014e0ffde3313b6d8fe
26.631579
146
0.685049
3.692308
false
false
false
false
MGaetan89/ShowsRage
app/src/main/kotlin/com/mgaetan89/showsrage/widget/HistoryWidgetFactory.kt
1
2396
package com.mgaetan89.showsrage.widget import android.content.Context import android.view.View import android.widget.RemoteViews import com.mgaetan89.showsrage.R import com.mgaetan89.showsrage.extension.saveHistory import com.mgaetan89.showsrage.extension.toLocale import com.mgaetan89.showsrage.extension.toRelativeDate import com.mgaetan89.showsrage.helper.ImageLoader import com.mgaetan89.showsrage.model.History import com.mgaetan89.showsrage.network.SickRageApi import com.mgaetan89.showsrage.presenter.HistoryPresenter import io.realm.Realm class HistoryWidgetFactory(context: Context) : ListWidgetFactory<History>(context) { override fun getViewAt(position: Int): RemoteViews { val history = this.getItem(position) val presenter = HistoryPresenter(history) val logoUrl = presenter.getPosterUrl() val views = RemoteViews(this.context.packageName, this.itemLayout) views.setTextViewText(R.id.episode_date, if (history != null) this.getEpisodeDate(history) else "") views.setContentDescription(R.id.episode_logo, presenter.getShowName()) views.setTextViewText(R.id.episode_title, this.getEpisodeTitle(presenter)) if (logoUrl.isEmpty()) { views.setViewVisibility(R.id.episode_logo, View.INVISIBLE) } else { ImageLoader.load(this.context, views, R.id.episode_logo, logoUrl, true) views.setViewVisibility(R.id.episode_logo, View.VISIBLE) } return views } override fun getItems(): List<History> { SickRageApi.instance.services?.getHistory()?.data?.let { histories -> Realm.getDefaultInstance().use { it.saveHistory(histories) } return histories } return emptyList() } private fun getEpisodeDate(history: History): String { val status = history.getStatusTranslationResource() val statusString = if (status != 0) { this.context.getString(status) } else { history.status } var text = this.context.getString(R.string.spaced_texts, statusString, history.date.toRelativeDate("yyyy-MM-dd hh:mm", 0).toString().toLowerCase()) if ("subtitled".equals(history.status, true)) { val language = history.resource?.toLocale()?.displayLanguage if (!language.isNullOrEmpty()) { text += " [$language]" } } return text } internal fun getEpisodeTitle(presenter: HistoryPresenter) = this.context.getString(R.string.show_name_episode, presenter.getShowName(), presenter.getSeason(), presenter.getEpisode()) }
apache-2.0
106fd5e6f39c7e80c1f8d22a35c74fb9
31.821918
149
0.76419
3.680492
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/overwrite/OverwriteModifiersInspection.kt
1
3801
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.overwrite import com.demonwav.mcdev.platform.mixin.util.mixinTargets import com.demonwav.mcdev.platform.mixin.util.resolveFirstOverwriteTarget import com.demonwav.mcdev.util.findKeyword import com.demonwav.mcdev.util.ifEmpty import com.demonwav.mcdev.util.isAccessModifier import com.intellij.codeInsight.intention.AddAnnotationFix import com.intellij.codeInsight.intention.QuickFixFactory import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier import com.intellij.psi.util.PsiUtil class OverwriteModifiersInspection : OverwriteInspection() { override fun getStaticDescription() = "Validates the modifiers of @Overwrite methods" override fun visitOverwrite(holder: ProblemsHolder, method: PsiMethod, overwrite: PsiAnnotation) { val psiClass = method.containingClass ?: return val targetClasses = psiClass.mixinTargets.ifEmpty { return } val target = resolveFirstOverwriteTarget(targetClasses, method)?.modifierList ?: return val nameIdentifier = method.nameIdentifier ?: return val modifierList = method.modifierList // Check access modifiers val targetAccessLevel = PsiUtil.getAccessLevel(target) val currentAccessLevel = PsiUtil.getAccessLevel(modifierList) if (currentAccessLevel < targetAccessLevel) { val targetModifier = PsiUtil.getAccessModifier(targetAccessLevel) val currentModifier = PsiUtil.getAccessModifier(currentAccessLevel) holder.registerProblem( modifierList.findKeyword(currentModifier) ?: nameIdentifier, "$currentModifier @Overwrite cannot reduce visibility of " + "${PsiUtil.getAccessModifier(targetAccessLevel)} target method", QuickFixFactory.getInstance().createModifierListFix(modifierList, targetModifier, true, false) ) } for (modifier in PsiModifier.MODIFIERS) { if (isAccessModifier(modifier)) { // Access modifiers are already checked above continue } val targetModifier = target.hasModifierProperty(modifier) val overwriteModifier = modifierList.hasModifierProperty(modifier) if (targetModifier != overwriteModifier) { val marker: PsiElement val message = if (targetModifier) { marker = nameIdentifier "Method must be '$modifier'" } else { marker = modifierList.findKeyword(modifier) ?: nameIdentifier "'$modifier' modifier does not match target method" } holder.registerProblem( marker, message, QuickFixFactory.getInstance().createModifierListFix(modifierList, modifier, targetModifier, false) ) } } for (annotation in target.annotations) { val qualifiedName = annotation.qualifiedName ?: continue val overwriteAnnotation = modifierList.findAnnotation(qualifiedName) if (overwriteAnnotation == null) { holder.registerProblem( nameIdentifier, "Missing @${annotation.nameReferenceElement?.text} annotation", AddAnnotationFix(qualifiedName, method, annotation.parameterList.attributes) ) } // TODO: Check if attributes are specified correctly? } } }
mit
26d02dabeda55f6ce56d95b4e47965ec
40.769231
118
0.669824
5.681614
false
false
false
false
Werb/MoreType
app/src/main/java/com/werb/moretype/diff/DiffDataCallback.kt
1
1469
package com.werb.moretype.diff import com.werb.library.link.XDiffCallback import com.werb.moretype.anim.AnimType import com.werb.moretype.complete.Complete import com.werb.moretype.main.MainCard /** * Created by wanbo on 2017/12/19. */ class DiffDataCallback(oldItem: List<Any>, newItem: List<Any>) : XDiffCallback(oldItem, newItem) { override fun getOldListSize(): Int = oldItem.size override fun getNewListSize(): Int = newItem.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val old = oldItem[oldItemPosition] val new = newItem[newItemPosition] if (old is Complete && new is Complete) { return old.name == new.name } else if (old is AnimType && new is AnimType) { return old.title == new.title } else if (old is MainCard && new is MainCard) { return old.cardTitle == new.cardTitle } return false } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val old = oldItem[oldItemPosition] val new = newItem[newItemPosition] if (old is Complete && new is Complete) { return old.desc == new.desc } else if (old is AnimType && new is AnimType) { return old.thumb == new.thumb } else if (old is MainCard && new is MainCard) { return old.cardDesc == new.cardDesc } return false } }
apache-2.0
0cc0054629518e87b25cf56ef522e33d
32.409091
98
0.643295
4.307918
false
false
false
false
avram/zandy
src/main/java/com/gimranov/zandy/app/data/DatabaseAccess.kt
1
1935
package com.gimranov.zandy.app.data import android.database.Cursor import com.gimranov.zandy.app.Query object DatabaseAccess { val TAG = this.javaClass.simpleName private val sortOptions = arrayOf("item_year, item_title COLLATE NOCASE", "item_creator COLLATE NOCASE, item_year", "item_title COLLATE NOCASE, item_year", "timestamp ASC, item_title COLLATE NOCASE") fun collections(db: Database): Cursor? { val args = arrayOf("false") return db.query("collections", Database.COLLCOLS, "collection_parent=?", args, null, null, "collection_name", null) } fun collectionsForParent(db: Database, parent: ItemCollection): Cursor? { val args = arrayOf(parent.key) return db.query("collections", Database.COLLCOLS, "collection_parent=?", args, null, null, "collection_name", null) } fun items(db: Database, parent: ItemCollection?, sortRule: String?): Cursor? { val sortClause = sortRule ?: sortOptions[0] when (parent) { null -> Query().query(db) else -> { val args = arrayOf(parent.dbId) return db.rawQuery("SELECT item_title, item_type, item_content, etag, dirty, items._id, item_key, item_year, item_creator, timestamp, item_children FROM items, itemtocollections WHERE items._id = item_id AND collection_id=? ORDER BY $sortClause", args) } } return Query().query(db) } fun items(db: Database, query: String, sortRule: String?): Cursor? { val sortClause = sortRule ?: sortOptions[0] val args = arrayOf("%$query%", "%$query%") return db.rawQuery("SELECT item_title, item_type, item_content, etag, dirty, _id, item_key, item_year, item_creator, timestamp, item_children FROM items WHERE item_title LIKE ? OR item_creator LIKE ? ORDER BY $sortClause", args) } }
agpl-3.0
e8ea3cc64bcb75f95d4047046d0063f7
42.022222
263
0.634625
4.03125
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/jsonHelpers/adapters/UTCDateAdapter.kt
2
2254
package org.stepic.droid.jsonHelpers.adapters import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonParseException import com.google.gson.JsonPrimitive import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import org.jetbrains.annotations.Contract import java.lang.reflect.Type import java.text.ParseException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone class UTCDateAdapter : JsonSerializer<Date>, JsonDeserializer<Date> { companion object { private const val UTC_ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" private const val UTC_ISO_FORMAT_SIMPLE = "yyyy-MM-dd'T'HH:mm:ss" private const val UTC_ISO_FORMAT_SIMPLE_LENGTH = UTC_ISO_FORMAT_SIMPLE.length - 2 // exclude 2 single quotes around T private fun createDateFormat(pattern: String): SimpleDateFormat = SimpleDateFormat(pattern, Locale.getDefault()) .apply { timeZone = TimeZone.getTimeZone("UTC") } } private val serializeDateFormat = createDateFormat(UTC_ISO_FORMAT) private val deserializeDateFormat = createDateFormat(UTC_ISO_FORMAT_SIMPLE) override fun serialize(date: Date, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement = synchronized(serializeDateFormat) { JsonPrimitive(serializeDateFormat.format(date)) } override fun deserialize(jsonElement: JsonElement, typeOfT: Type?, context: JsonDeserializationContext?): Date = try { synchronized(deserializeDateFormat) { deserializeDateFormat.parse(jsonElement.asString.take(UTC_ISO_FORMAT_SIMPLE_LENGTH)) } } catch (e: ParseException) { throw JsonParseException(e) } @Contract("null -> null; !null -> !null", pure = true) fun dateToString(date: Date?): String? = date?.let { serialize(date, null, null).asString } @Contract("null -> null; !null -> !null", pure = true) fun stringToDate(date: String?): Date? = date?.let { deserialize(JsonPrimitive(date), null, null) } }
apache-2.0
73c9757d309efc18836e473becae1357
40
125
0.703194
4.445759
false
false
false
false
silvertern/nox
src/main/kotlin/nox/platform/gradlize/impl/BundleUniverseImpl.kt
1
1833
/* * Copyright (c) Oleg Sklyar 2017. License: MIT */ package nox.platform.gradlize.impl import com.google.common.collect.Maps import com.google.common.collect.Sets import nox.core.Version import nox.platform.gradlize.Bundle import nox.platform.gradlize.BundleUniverse import nox.platform.gradlize.Duplicates import java.util.SortedMap import java.util.SortedSet internal class BundleUniverseImpl(private val duplicates: Duplicates) : BundleUniverse { private val bundleVersions = mutableMapOf<String, SortedSet<Version>>() private val pkgImplBundles = mutableMapOf<String, SortedMap<Version, Bundle>>() override fun bundleNames(): Set<String> { return bundleVersions.keys } override fun bundleVersions(bundleName: String): SortedSet<Version> { val res = bundleVersions[bundleName] ?: return sortedSetOf() return Sets.newTreeSet(res) // copy } override fun packageNames(): Set<String> { return pkgImplBundles.keys } override fun packageVersionsWithExportingBundles(pkgName: String): SortedMap<Version, Bundle> { val res = pkgImplBundles[pkgName] ?: return sortedMapOf() return Maps.newTreeMap(res) // copy } override fun with(bundle: Bundle): BundleUniverse { if (!bundleVersions.containsKey(bundle.name)) { bundleVersions.put(bundle.name, sortedSetOf()) } val versions = bundleVersions[bundle.name]!! check(duplicates.permitted() || !versions.contains(bundle.version)) { "Bundle %s already exists".format(bundle) } versions.add(bundle.version) for (expPkg in bundle.exportedPackages) { if (!pkgImplBundles.containsKey(expPkg.name)) { pkgImplBundles.put(expPkg.name, sortedMapOf()) } val pkgVersions = pkgImplBundles[expPkg.name]!! // overwrites already present bundle for the same package version pkgVersions.put(expPkg.version, bundle) } return this } }
mit
c03b124dd4a84a9bc455d85601e80373
30.067797
96
0.759956
3.680723
false
false
false
false
customerly/Customerly-Android-SDK
customerly-android-sdk/src/main/java/io/customerly/utils/ggkext/Ext_Closeable.kt
1
1303
package io.customerly.utils.ggkext import java.io.Closeable /* * Copyright (C) 2017 Customerly * * 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. */ /** * Created by Gianni on 16/04/18. * Project: Customerly-KAndroid-SDK */ internal inline fun <T : Closeable?, R> T.useSkipExeption(block: (T) -> R): R? { var exception: Throwable? = null try { return block(this) } catch (e: Throwable) { exception = e return null } finally { when { this == null -> {} exception == null -> close() else -> try { close() } catch (closeException: Throwable) { // cause.addSuppressed(closeException) // ignored here } } } }
apache-2.0
3ba687484d2d3e72628ee82bb0bad045
28.636364
80
0.607828
4.2443
false
false
false
false
maiktheknife/KittyCat
app/src/main/kotlin/net/kivitro/kittycat/view/adapter/KittyAdapter.kt
1
2159
package net.kivitro.kittycat.view.adapter import android.graphics.drawable.BitmapDrawable import android.support.v4.content.ContextCompat import android.support.v7.graphics.Palette import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import net.kivitro.kittycat.R import net.kivitro.kittycat.loadUrl import net.kivitro.kittycat.model.Cat import net.kivitro.kittycat.presenter.MainPresenter import timber.log.Timber /** * Created by Max on 08.03.2016. */ class KittyAdapter(val presenter: MainPresenter) : RecyclerView.Adapter<KittyAdapter.KittyHolder>() { private var cats: MutableList<Cat> = arrayListOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KittyHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cat, parent, false) return KittyHolder(view, object : KittyHolder.KittyActions { override fun onKittyClicked(view: View, pos: Int) { presenter.onKittyClicked(view, cats[pos]) } }) } override fun getItemCount() = cats.size override fun onBindViewHolder(holder: KittyHolder, position: Int) { val context = holder.itemView.context val cat = cats[position] holder.id.text = cat.id holder.image.loadUrl(cat.url!!, callback = { val bitmap = ((holder.image.drawable) as BitmapDrawable).bitmap Palette.from(bitmap).generate { palette -> val color = palette.getMutedColor(ContextCompat.getColor(context, R.color.colorPrimary)) holder.id.setTextColor(color) } }) } fun addItems(catss: List<Cat>) { Timber.d("addItems: ${cats.size} -> ${catss.size}") cats.clear() cats.addAll(catss) notifyDataSetChanged() } class KittyHolder(view: View, callback: KittyActions) : RecyclerView.ViewHolder(view) { interface KittyActions { fun onKittyClicked(view: View, pos: Int) } val image = view.findViewById<ImageView>(R.id.cat_row_image) val id = view.findViewById<TextView>(R.id.cat_row_id) init { view.setOnClickListener { _ -> callback.onKittyClicked(itemView, adapterPosition) } } } }
mit
6fb177962dba3309777bb6f0f9db243f
30.304348
101
0.756832
3.476651
false
false
false
false
googlemaps/android-places-demos
demo-kotlin/app/src/gms/java/com/example/placesdemo/MainActivity.kt
1
3173
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.placesdemo import android.content.Intent import android.os.Bundle import android.widget.ArrayAdapter import android.widget.Button import android.widget.Spinner import android.widget.Toast import androidx.annotation.IdRes import androidx.annotation.StyleRes import androidx.appcompat.app.AppCompatActivity import com.example.placesdemo.programmatic_autocomplete.ProgrammaticAutocompleteToolbarActivity import com.google.android.libraries.places.api.Places class MainActivity : AppCompatActivity() { private lateinit var widgetThemeSpinner: Spinner override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val apiKey = BuildConfig.PLACES_API_KEY if (apiKey.isEmpty()) { Toast.makeText(this, getString(R.string.error_api_key), Toast.LENGTH_LONG).show() return } // Setup Places Client if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) } setLaunchActivityClickListener(R.id.programmatic_autocomplete_button, ProgrammaticAutocompleteToolbarActivity::class.java) setLaunchActivityClickListener(R.id.autocomplete_button, AutocompleteTestActivity::class.java) setLaunchActivityClickListener(R.id.place_and_photo_button, PlaceAndPhotoTestActivity::class.java) setLaunchActivityClickListener(R.id.current_place_button, CurrentPlaceTestActivity::class.java) widgetThemeSpinner = findViewById(R.id.theme_spinner) widgetThemeSpinner.adapter = ArrayAdapter( /* context= */ this, android.R.layout.simple_list_item_1, listOf("Default", "\uD83D\uDCA9 brown", "\uD83E\uDD2E green", "\uD83D\uDE08 purple") ) } private fun setLaunchActivityClickListener(@IdRes onClickResId: Int, activityClassToLaunch: Class<out AppCompatActivity>) { findViewById<Button>(onClickResId).setOnClickListener { val intent = Intent(this@MainActivity, activityClassToLaunch) intent.putExtra(THEME_RES_ID_EXTRA, selectedTheme) startActivity(intent) } } @get:StyleRes private val selectedTheme: Int get() { return when (widgetThemeSpinner.selectedItemPosition) { 1 -> R.style.Brown 2 -> R.style.Green 3 -> R.style.Purple else -> 0 } } companion object { const val THEME_RES_ID_EXTRA = "widget_theme" } }
apache-2.0
9d6d41abd7537f428e3e3cff42e53bec
37.240964
130
0.702175
4.500709
false
false
false
false
leafclick/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator25.kt
1
3503
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.transformations.immutable.hasImmutableAnnotation import org.jetbrains.plugins.groovy.transformations.immutable.isImmutable import org.jetbrains.plugins.groovy.transformations.impl.namedVariant.collectAllParamsFromNamedVariantMethod import org.jetbrains.plugins.groovy.transformations.impl.namedVariant.collectNamedParams /** * Check features introduced in groovy 2.5 */ class GroovyAnnotator25(private val holder: AnnotationHolder) : GroovyElementVisitor() { override fun visitMethod(method: GrMethod) { collectAllParamsFromNamedVariantMethod(method).groupBy { it.first }.filter { it.value.size > 1 }.forEach { (name, parameters) -> val parametersList = parameters.joinToString { "'${it.second.name}'" } val duplicatingParameters = parameters.drop(1).map { (_, parameter) -> parameter } for (parameter in duplicatingParameters) { val nameIdentifier = parameter.nameIdentifier ?: continue holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("duplicating.named.parameter", name, parametersList)).range(nameIdentifier).create() } } super.visitMethod(method) } override fun visitField(field: GrField) { super.visitField(field) immutableCheck(field) } private fun immutableCheck(field: GrField) { val containingClass = field.containingClass ?: return if (!field.hasModifierProperty(PsiModifier.STATIC) && hasImmutableAnnotation(containingClass) && !isImmutable(field)) { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("field.should.be.immutable", field.name)).range(field.nameIdentifierGroovy).create() } } override fun visitCallExpression(callExpression: GrCallExpression) { checkRequiredNamedArguments(callExpression) super.visitCallExpression(callExpression) } private fun checkRequiredNamedArguments(callExpression: GrCallExpression) { if (!PsiUtil.isCompileStatic(callExpression)) return val namedArguments = callExpression.namedArguments.mapNotNull { it.labelName }.toSet() if (namedArguments.isEmpty()) return val resolveResult = callExpression.advancedResolve() val method = resolveResult.element as? PsiMethod ?: return val parameters = method.parameterList.parameters val mapParameter = parameters.firstOrNull() ?: return val requiredNamedParams = collectNamedParams(mapParameter).filter { it.required } for (namedParam in requiredNamedParams) { if (!namedArguments.contains(namedParam.name)) { val message = GroovyBundle.message("missing.required.named.parameter", namedParam.name) holder.newAnnotation(HighlightSeverity.ERROR, message).create() } } } }
apache-2.0
6b000a521b8d6b46333e6f774a8b9ba0
46.351351
159
0.782187
4.683155
false
false
false
false
stefanosiano/PowerfulImageView
powerfulimageview/src/main/java/com/stefanosiano/powerful_libraries/imageview/blur/algorithms/GaussianAlgorithms.kt
1
2125
package com.stefanosiano.powerful_libraries.imageview.blur.algorithms import android.graphics.Bitmap import com.stefanosiano.powerful_libraries.imageview.blur.BlurOptions import kotlin.math.exp import kotlin.math.sqrt /** * Class that performs the gaussian blur with 3x3 coefficient matrix. * Changing radius will repeat the process radius times. */ internal class Gaussian3x3BlurAlgorithm : BaseConvolveBlurAlgorithm() { @Suppress("MagicNumber") override fun getFilter() = floatArrayOf(0.1968f, 0.6064f, 0.1968f) } /** * Class that performs the gaussian blur with 5x5 coefficient matrix. * Changing radius will repeat the process radius times. */ internal class Gaussian5x5BlurAlgorithm : BaseConvolveBlurAlgorithm() { @Suppress("MagicNumber") override fun getFilter() = floatArrayOf(0.0545f, 0.2442f, 0.4026f, 0.2442f, 0.0545f) } /** * Class that performs the gaussian blur with any kind of radius. * Increasing radius will change the coefficients used and increase the radius of the blur, * resulting in the image more blurry, but slower. */ internal class GaussianBlurAlgorithm : BaseConvolveBlurAlgorithm() { private var radius: Int = 0 init { radius = 0 } override fun getFilter(): FloatArray { val filter = FloatArray(radius * 2 + 1) val sigma = (radius * 2 + 2) / 6.toFloat() val coefficient = 1 / sqrt(2.0 * Math.PI * sigma.toDouble() * sigma.toDouble()) val exponent = -1 / (2f * sigma * sigma).toDouble() var sum = 0f for (i in filter.indices) { val x = (i - radius).toDouble() val value = (coefficient * exp(exponent * x * x)).toFloat() filter[i] = value sum += value } if (sum != 0f) sum = 1 / sum return filter.map { it * sum }.toFloatArray() } @Throws(RenderscriptException::class) override fun blur(original: Bitmap, radius: Int, options: BlurOptions): Bitmap? { if (radius == 0) { return original } this.radius = radius return super.blur(original, 1, options) } }
mit
f9e28c4828ffcfe8e789ffd3f5865e16
29.797101
91
0.658824
3.870674
false
false
false
false
leafclick/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/dotnet/DotnetIconsClasses.kt
1
1848
// 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.intellij.build.images.sync.dotnet import org.jetbrains.intellij.build.images.IconsClassGenerator import org.jetbrains.intellij.build.images.IconsClassInfo import org.jetbrains.intellij.build.images.IconsClasses import org.jetbrains.jps.model.module.JpsModule import java.io.File internal class DotnetIconsClasses(override val homePath: String) : IconsClasses() { override val modules: List<JpsModule> get() = super.modules.filter { it.name == "rider-icons" } override fun generator(home: File, modules: List<JpsModule>) = object : IconsClassGenerator(home, modules) { override fun getIconsClassInfo(module: JpsModule): List<IconsClassInfo> { val info = super.getIconsClassInfo(module) return splitRiderAndReSharper(info.single()) } override fun appendInnerClass(className: String, answer: StringBuilder, body: String, level: Int) { when (className) { // inline redundant classes ReSharperIcons.Resharper and RiderIcons.Rider "Rider", "Resharper" -> append(answer, body, 0) else -> super.appendInnerClass(className, answer, body, level) } } } private fun splitRiderAndReSharper(info: IconsClassInfo): List<IconsClassInfo> { val rider = extract("rider/", "RiderIcons", info) val reSharper = extract("resharper/", "ReSharperIcons", info) return listOf(rider, reSharper) } private fun extract(imageIdPrefix: String, className: String, info: IconsClassInfo) = IconsClassInfo( info.customLoad, info.packageName, className, info.outFile.parent.resolve("$className.java"), info.images.filter { it.id.startsWith(imageIdPrefix) } ) }
apache-2.0
ce5735c0cf1275e1a1f75a93d093e637
41.022727
140
0.72132
4.143498
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/constraints/BaseConstrainedExecution.kt
1
2853
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.application.constraints import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint import com.intellij.openapi.diagnostic.Logger import kotlinx.coroutines.Runnable import java.util.function.BooleanSupplier /** * This class is responsible for running a task in a proper context defined using various builder methods of this class and it's * implementations, like [com.intellij.openapi.application.AppUIExecutor.later], or generic [withConstraint]. * * ## Implementation notes: ## * * The [scheduleWithinConstraints] starts checking the list of constraints, one by one, rescheduling and restarting itself * for each unsatisfied constraint until at some point *all* of the constraints are satisfied *at once*. * * This ultimately ends up with [ContextConstraint.schedule] being called one by one for every constraint that needs to be scheduled. * Finally, the runnable is called, executing the task in the properly arranged context. * * @author eldar * @author peter */ abstract class BaseConstrainedExecution<E : ConstrainedExecution<E>>(protected val constraints: Array<ContextConstraint>) : ConstrainedExecution<E>, ConstrainedExecutionScheduler { protected abstract fun cloneWith(constraints: Array<ContextConstraint>): E override fun withConstraint(constraint: ContextConstraint): E = cloneWith(constraints + constraint) override fun asExecutor() = ConstrainedTaskExecutor(this, composeCancellationCondition(), composeExpiration()) override fun asCoroutineDispatcher() = createConstrainedCoroutineDispatcher(this, composeCancellationCondition(), composeExpiration()) protected open fun composeExpiration(): Expiration? = null protected open fun composeCancellationCondition(): BooleanSupplier? = null override fun scheduleWithinConstraints(runnable: Runnable, condition: BooleanSupplier?) { val attemptChain = mutableListOf<ContextConstraint>() fun inner() { if (attemptChain.size > 3000) { val lastCauses = attemptChain.takeLast(15) LOG.error("Too many reschedule requests, probably constraints can't be satisfied all together: " + lastCauses.joinToString()) } if (condition?.asBoolean == false) return for (constraint in constraints) { if (!constraint.isCorrectContext()) { return constraint.schedule(Runnable { LOG.assertTrue(constraint.isCorrectContext()) attemptChain.add(constraint) inner() }) } } runnable.run() } inner() } companion object { private val LOG = Logger.getInstance("#com.intellij.openapi.application.constraints.ConstrainedExecution") } }
apache-2.0
00cf2d6e52ccb8a3a5024a4362fc6e48
44.301587
140
0.754294
5.040636
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/classstore/ClassStore.kt
1
6347
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.classstore import com.intellij.diagnostic.hprof.parser.HProfEventBasedParser import com.intellij.diagnostic.hprof.parser.Type import com.intellij.diagnostic.hprof.visitors.CollectStringValuesVisitor import com.intellij.diagnostic.hprof.visitors.CreateClassStoreVisitor import gnu.trove.TLongObjectHashMap import java.util.function.LongUnaryOperator class ClassStore(private val classes: TLongObjectHashMap<ClassDefinition>) { private val stringToClassDefinition = HashMap<String, ClassDefinition>() private val classDefinitionToShortPrettyName = HashSet<ClassDefinition>() val softReferenceClass: ClassDefinition val weakReferenceClass: ClassDefinition val classClass: ClassDefinition private val primitiveArrayToClassDefinition = HashMap<Type, ClassDefinition>() init { fun getClashedNameWithIndex(classDefinition: ClassDefinition, index: Int): String { if (classDefinition.name.endsWith(';')) return "${classDefinition.name.removeSuffix(";")}!$index;" else return "${classDefinition.name}!$index" } val clashedClassNames = mutableSetOf<String>() classes.forEachValue { classDefinition -> val className = classDefinition.name var clashed = false if (clashedClassNames.contains(className)) { clashed = true } else { val clashedClass = stringToClassDefinition.remove(className) // If there is more than one class with this name, rename first class too. if (clashedClass != null) { clashed = true val newDefinition = clashedClass.copyWithName(getClashedNameWithIndex(clashedClass, 1)) stringToClassDefinition[newDefinition.name] = newDefinition classes.put(clashedClass.id, newDefinition) clashedClassNames.add(className) } } if (clashed) { var i = 2 var newName: String do { newName = getClashedNameWithIndex(classDefinition, i) i++ } while (stringToClassDefinition.containsKey(newName)) val newClassDefinition = classDefinition.copyWithName(newName) stringToClassDefinition[newName] = newClassDefinition classes.put(classDefinition.id, newClassDefinition) } else { stringToClassDefinition[classDefinition.name] = classDefinition } true } clashedClassNames.forEach { assert(!stringToClassDefinition.contains(it)) } // Every heap dump should have definitions of Soft/WeakReference and java.lang.Class softReferenceClass = stringToClassDefinition["java.lang.ref.SoftReference"]!! weakReferenceClass = stringToClassDefinition["java.lang.ref.WeakReference"]!! classClass = stringToClassDefinition["java.lang.Class"]!! Type.values().forEach { type -> if (type == Type.OBJECT) { return@forEach } stringToClassDefinition[type.getClassNameOfPrimitiveArray()]?.let { classDefinition -> primitiveArrayToClassDefinition.put(type, classDefinition) } } val shortNameToClassDefinition = HashMap<String, ClassDefinition?>() classes.forEachValue { if (it.name.contains('$')) return@forEachValue true val prettyName = it.prettyName val shortPrettyName = prettyName.substringAfterLast('.') if (shortNameToClassDefinition.containsKey(shortPrettyName)) { val prevClassDefinition = shortNameToClassDefinition[shortPrettyName] if (prevClassDefinition != null) { shortNameToClassDefinition[shortPrettyName] = null } } else { shortNameToClassDefinition[shortPrettyName] = it } true } shortNameToClassDefinition.forEach { (_, classDef) -> if (classDef == null) return@forEach classDefinitionToShortPrettyName.add(classDef) } } operator fun get(id: Int): ClassDefinition { return classes[id.toLong()]!! } operator fun get(id: Long): ClassDefinition { return classes[id]!! } operator fun get(name: String): ClassDefinition { return stringToClassDefinition[name]!! } fun getClassIfExists(name: String): ClassDefinition? { return stringToClassDefinition[name] } fun containsClass(name: String) = stringToClassDefinition.containsKey(name) fun getClassForPrimitiveArray(t: Type): ClassDefinition? { return primitiveArrayToClassDefinition[t] } fun size() = classes.size() fun isSoftOrWeakReferenceClass(classDefinition: ClassDefinition): Boolean { return classDefinition == softReferenceClass || classDefinition == weakReferenceClass } fun forEachClass(func: (ClassDefinition) -> Unit) { classes.forEachValue { func(it) true } } fun createStoreWithRemappedIDs(remappingFunction: LongUnaryOperator): ClassStore { fun map(id: Long): Long = remappingFunction.applyAsLong(id) val newClasses = TLongObjectHashMap<ClassDefinition>() classes.forEachValue { newClasses.put(map(it.id), it.copyWithRemappedIDs(remappingFunction)) true } return ClassStore(newClasses) } fun getShortPrettyNameForClass(classDefinition: ClassDefinition): String { if (classDefinition.name.contains('$')) { val outerClass = stringToClassDefinition[classDefinition.name.substringBefore('$')] if (outerClass != null) { if (classDefinitionToShortPrettyName.contains(outerClass)) { return classDefinition.prettyName.substringAfterLast('.') } } } else if (classDefinitionToShortPrettyName.contains(classDefinition)) { return classDefinition.prettyName.substringAfterLast('.') } return classDefinition.prettyName } }
apache-2.0
dec27e85723592e88fb56ecb3f2771a3
34.657303
97
0.711517
4.63962
false
false
false
false