content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package com.google.idea.gn import com.google.idea.gn.parser.GnParser import com.google.idea.gn.psi.GnFile import com.google.idea.gn.psi.Types import com.intellij.lang.ASTNode import com.intellij.lang.ParserDefinition import com.intellij.lang.PsiParser import com.intellij.lexer.Lexer import com.intellij.openapi.project.Project import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.TokenType import com.intellij.psi.tree.IFileElementType import com.intellij.psi.tree.TokenSet class GnParserDefinition : ParserDefinition { override fun createLexer(project: Project): Lexer { return GnLexerAdapter() } override fun createParser(project: Project): PsiParser { return GnParser() } override fun getFileNodeType(): IFileElementType { return FILE } override fun getCommentTokens(): TokenSet { return COMMENTS } override fun getWhitespaceTokens(): TokenSet { return WHITE_SPACES } override fun getStringLiteralElements(): TokenSet { return TokenSet.EMPTY } override fun createElement(node: ASTNode): PsiElement { return Types.Factory.createElement(node) } override fun createFile(viewProvider: FileViewProvider): PsiFile { return GnFile(viewProvider) } companion object { val WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE) val COMMENTS = TokenSet.create(Types.COMMENT) val STRING_EXPR = TokenSet.create(Types.QUOTE, Types.STRING_LITERAL) val FILE = IFileElementType(GnLanguage) } }
src/main/java/com/google/idea/gn/GnParserDefinition.kt
4032724573
package com.like.common.view.chart.horizontalScrollLineFillChartView.core import android.content.Context import android.graphics.Canvas import android.graphics.LinearGradient import android.graphics.Paint import android.graphics.Shader import android.view.View import com.like.common.view.chart.horizontalScrollLineFillChartView.entity.LineData class LineFillChartView(context: Context) : View(context) { private val mDataList: MutableList<LineData> = arrayListOf() private val mConfig: LineFillChartConfig = LineFillChartConfig(context) private lateinit var mDrawHelper: DrawHelper private val mGradientPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val mPointPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val mPointFillPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val mGradientBottomPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val mXAxisPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val mTextPaint = Paint(Paint.ANTI_ALIAS_FLAG) init { setBackgroundColor(LineFillChartConfig.DEFAULT_BG_COLOR) mGradientPaint.style = Paint.Style.FILL mPointPaint.style = Paint.Style.STROKE mPointPaint.color = LineFillChartConfig.DEFAULT_POINT_BORDER_COLOR mPointPaint.strokeWidth = mConfig.pointBorderWidth mPointFillPaint.style = Paint.Style.FILL mPointFillPaint.color = LineFillChartConfig.DEFAULT_POINT_FILL_COLOR mGradientBottomPaint.style = Paint.Style.FILL mGradientBottomPaint.color = LineFillChartConfig.DEFAULT_GRADIENT_BOTTOM_BG_COLOR mXAxisPaint.style = Paint.Style.STROKE mXAxisPaint.color = LineFillChartConfig.DEFAULT_X_AXIS_BORDER_COLOR } fun setData(lineDataList: List<LineData>, showPointCount: Int = 3) { if (showPointCount <= 0) { throw IllegalArgumentException("showPointCount 参数必须大于0") } mDataList.clear() if (lineDataList.isNotEmpty()) { mDataList.addAll(lineDataList) mConfig.setData(lineDataList, showPointCount) } requestLayout() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { setMeasuredDimension(mConfig.totalWidth.toInt(), mConfig.totalHeight.toInt()) } override fun onDraw(canvas: Canvas) { if (mDataList.isNotEmpty()) { mDrawHelper = DrawHelper(canvas, mConfig) mGradientPaint.shader = LinearGradient(0f, mConfig.totalGradientAndSpacingTopHeight, 0f, mConfig.linearGradientY1, LineFillChartConfig.DEFAULT_COLORS, LineFillChartConfig.DEFAULT_COLORS_POSITIONS, Shader.TileMode.CLAMP) // 画折线图,并填充 for (index in 0 until mConfig.pathList.size) { mDrawHelper.drawPath(index, mGradientPaint) } // 画渐变色块以下间隔的背景 mDrawHelper.drawGradientBottomRect(mGradientBottomPaint) // 画x轴线 mDrawHelper.drawXAxis(mXAxisPaint) mXAxisPaint.color = LineFillChartConfig.DEFAULT_X_AXIS_SCALE_COLOR for (index in 0 until mConfig.pointList.size) { // 画点圆 mDrawHelper.drawPoint(index, mPointFillPaint) mDrawHelper.drawPoint(index, mPointPaint) // 画x轴刻度线 mDrawHelper.drawXAxisScale(index, mXAxisPaint) // 画x轴文本 mTextPaint.textSize = mConfig.xAxisTextSize mTextPaint.color = LineFillChartConfig.DEFAULT_X_AXIS_TEXT_COLOR mDrawHelper.drawXAxisText(index, mTextPaint) // 画点的数值 mTextPaint.textSize = mConfig.pointTextSize mTextPaint.color = LineFillChartConfig.DEFAULT_POINT_TEXT_COLOR mDrawHelper.drawPointText(index, mTextPaint) } } } }
common/src/main/java/com/like/common/view/chart/horizontalScrollLineFillChartView/core/LineFillChartView.kt
2524436794
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.sqldelight.core import com.alecstrong.sql.psi.core.DialectPreset import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile interface SqlDelightProjectService { var dialectPreset: DialectPreset fun module(vFile: VirtualFile): Module? fun fileIndex(module: Module): SqlDelightFileIndex fun resetIndex() companion object { fun getInstance(project: Project): SqlDelightProjectService { return ServiceManager.getService(project, SqlDelightProjectService::class.java)!! } } }
sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/core/SqlDelightProjectService.kt
2899517417
package com.gmail.blueboxware.libgdxplugin.inspections.kotlin import com.gmail.blueboxware.libgdxplugin.message import com.gmail.blueboxware.libgdxplugin.utils.compat.getCalleeExpressionIfAny import com.gmail.blueboxware.libgdxplugin.utils.compat.isGetter import com.gmail.blueboxware.libgdxplugin.utils.isSetLogLevel import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReference import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.psi.* /* * Copyright 2016 Blue Box Ware * * 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. */ class KotlinLogLevelInspection : LibGDXKotlinBaseInspection() { override fun getStaticDescription() = message("log.level.html.description") override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() { override fun visitCallExpression(expression: KtCallExpression) { val refs = expression.calleeExpression?.references ?: return for (ref in refs) { val target = ref.resolve() ?: continue if (target is PsiMethod) { val clazz = target.containingClass ?: continue val methodName = expression.calleeExpression?.text ?: continue if (isSetLogLevel(clazz, methodName)) { val argument = expression.valueArgumentList?.arguments?.firstOrNull()?.getArgumentExpression() ?: return if (isLogLevelArgument(argument)) { holder.registerProblem(expression, message("log.level.problem.descriptor")) } } } } } override fun visitQualifiedExpression(expression: KtQualifiedExpression) { (expression.context as? KtBinaryExpression)?.let { context -> val operator = (context.operationToken as? KtSingleValueToken)?.value ?: return if (operator != "=") return val refs = expression.selectorExpression?.references ?: return for (ref in refs) { if ((ref as? SyntheticPropertyAccessorReference)?.isGetter() == false) { val target = ref.resolve() if (target is PsiMethod) { val clazz = target.containingClass ?: continue val methodName = target.name if (isSetLogLevel(clazz, methodName)) { val argument = context.right ?: continue if (isLogLevelArgument(argument)) { holder.registerProblem(context, message("log.level.problem.descriptor")) } } } } } } } } } private fun isLogLevelArgument(expression: KtExpression?): Boolean { if (expression is KtConstantExpression && (expression.text == "3" || expression.text == "4")) { return true } else if (expression is KtDotQualifiedExpression) { val refs = expression.getCalleeExpressionIfAny()?.references ?: return false for (ref in refs) { val target = ref.resolve()?.getKotlinFqName()?.asString() ?: continue if ( target == "com.badlogic.gdx.Application.LOG_DEBUG" || target == "com.badlogic.gdx.Application.LOG_INFO" || target == "com.badlogic.gdx.utils.Logger.DEBUG" || target == "com.badlogic.gdx.utils.Logger.INFO" ) { return true } } } return false }
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/kotlin/KotlinLogLevelInspection.kt
1846599948
package com.example.arturo.mycomics.ui.comics.views.viewholders import android.content.Context import android.support.v7.widget.RecyclerView import android.view.View import com.example.arturo.mycomics.ui.comics.models.ComicModel import com.example.arturo.mycomics.ui.comics.views.listeners.OnComicClickedListener import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.comic_list_content.view.* class ComicViewHolder(val comicView: View) : RecyclerView.ViewHolder(comicView) { fun bind(model: ComicModel, context: Context, onComicClickedListener: OnComicClickedListener?) { itemView.title!!.text = model.title Picasso.with(context).load(model.thumbnailUrl).fit().centerCrop().into( itemView.thumbnail) comicView.setOnClickListener { onComicClickedListener!!.onComicClicked(model) } } }
app/src/main/java/com/example/arturo/mycomics/ui/comics/views/viewholders/ComicViewHolder.kt
4076935028
package i_introduction._6_Data_Classes import util.* fun todoTask7(): Nothing = TODO( """ Convert 'JavaCode7.Person' class to Kotlin. Then add an annotation `data` to the resulting class. This annotation means the compiler will generate a bunch of useful methods in this class: `equals`/`hashCode`, `toString` and some others. The `task7` function should return a list of persons. """, documentation = doc7(), references = { JavaCode7.Person("Alice", 29) } ) data class Person(val name: String, val age: Int) fun task7(): List<Person> { return listOf(Person("Alice", 29), Person("Bob", 31)) }
src/i_introduction/_6_Data_Classes/DataClasses.kt
3703649565
package com.uphyca.creditcardedittext import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.uphyca.creditcardedittext.library_test.R class CreditCardDateActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_credit_card_date) } }
library-test/src/main/java/com/uphyca/creditcardedittext/CreditCardDateActivity.kt
9117481
package me.proxer.library.api.messenger import me.proxer.library.ProxerCall import me.proxer.library.api.Endpoint import me.proxer.library.api.messenger.ConferenceModificationEndpoint.ConferenceModification.BLOCK import me.proxer.library.api.messenger.ConferenceModificationEndpoint.ConferenceModification.FAVOUR import me.proxer.library.api.messenger.ConferenceModificationEndpoint.ConferenceModification.READ import me.proxer.library.api.messenger.ConferenceModificationEndpoint.ConferenceModification.UNBLOCK import me.proxer.library.api.messenger.ConferenceModificationEndpoint.ConferenceModification.UNFAVOUR import me.proxer.library.api.messenger.ConferenceModificationEndpoint.ConferenceModification.UNREAD /** * Endpoint for modifying a conference in various ways. * * Possible modifications are: * - Mark as read * - Mark as unread * - Block * - Unblock * - Mark as favourite * - Unmark as favourite * * @author Ruben Gees */ class ConferenceModificationEndpoint internal constructor( private val internalApi: InternalApi, private val id: String, private val modification: ConferenceModification ) : Endpoint<Unit> { override fun build(): ProxerCall<Unit> { return when (modification) { READ -> internalApi.markConferenceAsRead(id) UNREAD -> internalApi.unmarkConferenceAsRead(id) BLOCK -> internalApi.markConferenceAsBlocked(id) UNBLOCK -> internalApi.unmarkConferenceAsBlocked(id) FAVOUR -> internalApi.markConferenceAsFavorite(id) UNFAVOUR -> internalApi.unmarkConferenceAsFavorite(id) } } internal enum class ConferenceModification { READ, UNREAD, BLOCK, UNBLOCK, FAVOUR, UNFAVOUR } }
library/src/main/kotlin/me/proxer/library/api/messenger/ConferenceModificationEndpoint.kt
3452269620
package org.nield.kotlinstatistics class OpenDoubleRange( start: Double, endExclusive: Double ) { private val _start = start private val _endExclusive = endExclusive val start: Double get() = _start val endExclusive: Double get() = _endExclusive fun lessThanOrEquals(a: Double, b: Double): Boolean = a <= b operator fun contains(value: Double): Boolean = value >= _start && value < _endExclusive fun isEmpty(): Boolean = !(_start <= _endExclusive) override fun equals(other: Any?): Boolean { return other is OpenDoubleRange && (isEmpty() && other.isEmpty() || _start == other._start && _endExclusive == other._endExclusive) } override fun hashCode(): Int { return if (isEmpty()) -1 else 31 * _start.hashCode() + _endExclusive.hashCode() } override fun toString(): String = "$_start..<$_endExclusive" } infix fun Double.openRange(double: Double) = OpenDoubleRange(this, double)
src/main/kotlin/org/nield/kotlinstatistics/Ranges.kt
2073068122
/* Copyright (C) 2013-2020 Expedia Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.hotels.styx.executors import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.hotels.styx.ExecutorFactory import com.hotels.styx.NettyExecutor import com.hotels.styx.config.schema.SchemaDsl import com.hotels.styx.infrastructure.configuration.json.ObjectMappers import com.hotels.styx.infrastructure.configuration.yaml.JsonNodeConfig class NettyExecutorFactory : ExecutorFactory { private fun parseConfig(configuration: JsonNode) = JsonNodeConfig(configuration).`as`(NettyExecutorConfig::class.java) override fun create(name: String, configuration: JsonNode): NettyExecutor { val config = parseConfig(configuration) return NettyExecutor.create(config.namePattern, config.threads) } companion object { @JvmField val SCHEMA = SchemaDsl.`object`( SchemaDsl.field("threads", SchemaDsl.integer()), SchemaDsl.field("namePattern", SchemaDsl.string()) ) } } private val mapper = ObjectMappers.addStyxMixins(ObjectMapper(YAMLFactory())) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true) internal data class NettyExecutorConfig( val threads: Int = 0, val namePattern: String = "netty-executor") { fun asJsonNode(): JsonNode = mapper.readTree(mapper.writeValueAsString(this)) }
components/proxy/src/main/kotlin/com/hotels/styx/executors/NettyExecutorFactory.kt
2335957863
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.android.sync.bean /** * Page */ class Page { var id: String? = null var name: String? = null var lastModified: String? = null override fun toString(): String { return "Page{" + "id='" + id + '\''.toString() + ", name='" + name + '\''.toString() + ", lastModified='" + lastModified + '\''.toString() + '}'.toString() } }
app/src/main/java/org/xwiki/android/sync/bean/Page.kt
1458210150
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2021 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package com.google.android.libraries.pcc.chronicle.api.policy.builder import com.google.android.libraries.pcc.chronicle.api.dataTypeDescriptor import com.google.android.libraries.pcc.chronicle.api.policy.StorageMedium import com.google.android.libraries.pcc.chronicle.api.policy.contextrules.All import com.google.android.libraries.pcc.chronicle.api.policy.contextrules.PolicyContextRule import com.google.android.libraries.pcc.chronicle.util.TypedMap import com.google.common.truth.Truth.assertThat import java.time.Duration import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class PolicyBuilderTest { /** Test object that always evaluates to false, regardless of the context. */ object TestContextRule : PolicyContextRule { override val name: String = "TestContextRule" override val operands: List<PolicyContextRule> = emptyList() override fun invoke(context: TypedMap): Boolean = false } @Test fun minimal() { val actual = policy("MyPolicy", "Analytics") assertThat(actual.name).isEqualTo("MyPolicy") assertThat(actual.egressType).isEqualTo("Analytics") assertThat(actual.description).isEqualTo("") assertThat(actual.allowedContext).isEqualTo(All) assertThat(actual.configs).isEmpty() assertThat(actual.targets).isEmpty() } @Test fun withDescription() { val actual = policy("MyPolicy", "Analytics") { description = "This is my description." } assertThat(actual.name).isEqualTo("MyPolicy") assertThat(actual.egressType).isEqualTo("Analytics") assertThat(actual.description).isEqualTo("This is my description.") assertThat(actual.allowedContext).isEqualTo(All) assertThat(actual.configs).isEmpty() assertThat(actual.targets).isEmpty() } @Test fun withAllowedContext() { val actual = policy("MyPolicy", "Analytics") { allowedContext = TestContextRule } assertThat(actual.name).isEqualTo("MyPolicy") assertThat(actual.egressType).isEqualTo("Analytics") assertThat(actual.description).isEqualTo("") assertThat(actual.allowedContext).isEqualTo(TestContextRule) assertThat(actual.configs).isEmpty() assertThat(actual.targets).isEmpty() } @Test fun withTargets() { val actual = policy("MyPolicy", "Analytics") { target(dataTypeDescriptor = FOO_DTD, maxAge = Duration.ofMinutes(15)) { retention(StorageMedium.RAM) } target( dataTypeDescriptor = dataTypeDescriptor("Bar", Unit::class), maxAge = Duration.ofDays(2) ) { retention(StorageMedium.DISK, encryptionRequired = true) } } assertThat(actual.name).isEqualTo("MyPolicy") assertThat(actual.egressType).isEqualTo("Analytics") assertThat(actual.description).isEqualTo("") assertThat(actual.allowedContext).isEqualTo(All) assertThat(actual.configs).isEmpty() assertThat(actual.targets) .containsExactly( target(FOO_DTD, maxAge = Duration.ofMinutes(15)) { retention(StorageMedium.RAM) }, target(BAR_DTD, maxAge = Duration.ofDays(2)) { retention(StorageMedium.DISK, encryptionRequired = true) } ) } @Test fun withConfigs() { val actual = policy("MyPolicy", "Analytics") { config("DiskStorage") { "engine" to "innoDB" } config("Cache") { "maxItems" to "15" } } assertThat(actual.name).isEqualTo("MyPolicy") assertThat(actual.egressType).isEqualTo("Analytics") assertThat(actual.description).isEqualTo("") assertThat(actual.allowedContext).isEqualTo(All) assertThat(actual.configs) .containsExactly( "DiskStorage", PolicyConfigBuilder().apply { "engine" to "innoDB" }.build(), "Cache", PolicyConfigBuilder().apply { "maxItems" to "15" }.build() ) assertThat(actual.targets).isEmpty() } @Test fun copyConstructor_deepCopiesPolicyBuilder() { val pb1 = PolicyBuilder("name", "egress").apply { description = "base" target(TEST_PERSON_GENERATED_DTD, Duration.ZERO) {} configs["base"] = mapOf("base" to "base") } val pb2 = PolicyBuilder(pb1).apply { description = "pb2" allowedContext = TestContextRule target(FOO_DTD, Duration.ZERO) {} configs["base"] = mapOf("mod" to "mod") } // `pb1` must not be modified by changes to copy assertThat(pb1.description).isEqualTo("base") assertThat(pb1.allowedContext).isEqualTo(All) assertThat(pb1.targets).hasSize(1) assertThat(pb1.configs["base"]).isEqualTo(mapOf("base" to "base")) // Confirm changes to `pb2` assertThat(pb2.allowedContext).isEqualTo(TestContextRule) assertThat(pb2.targets).hasSize(2) // The `configs` of `pb2` must be modified. assertThat(pb2.configs["base"]).isEqualTo(mapOf("mod" to "mod")) } companion object { private val FOO_DTD = dataTypeDescriptor("Foo", Unit::class) private val BAR_DTD = dataTypeDescriptor("Bar", Unit::class) } }
javatests/com/google/android/libraries/pcc/chronicle/api/policy/builder/PolicyBuilderTest.kt
2546898613
package com.adgvcxz.rxtheme import android.view.View import io.reactivex.Observable import io.reactivex.functions.Consumer /** * zhaowei * Created by zhaowei on 2017/7/10. */ fun View.background(): Consumer<Int> { return Consumer { this.setBackgroundColor(it) } } fun themeBackground(): Consumer<Pair<Array<out View>, Int>> { return Consumer { it.first.forEach { view -> view.setBackgroundColor(it.second) } } } fun <T> Observable<T>.toThemeObservable(views: Array<out View>): Observable<Pair<Array<out View>, T>> { return this.distinctUntilChanged() .map { views.to(it) } }
rxtheme/src/main/java/com/adgvcxz/rxtheme/ThemeExt.kt
2496242418
package com.tenkiv.tekdaqc.communication.message import com.tenkiv.tekdaqc.communication.ascii.message.parsing.ASCIIDigitalOutputDataMessage import com.tenkiv.tekdaqc.communication.ascii.message.parsing.ASCIIMessageUtils import com.tenkiv.tekdaqc.communication.data_points.AnalogInputCountData import com.tenkiv.tekdaqc.communication.data_points.DigitalInputData import com.tenkiv.tekdaqc.communication.data_points.PWMInputData import com.tenkiv.tekdaqc.hardware.AAnalogInput import com.tenkiv.tekdaqc.hardware.ATekdaqc import com.tenkiv.tekdaqc.hardware.DigitalInput import com.tenkiv.tekdaqc.hardware.IInputOutputHardware import org.tenkiv.coral.ValueInstant import tec.units.indriya.ComparableQuantity import tec.units.indriya.quantity.Quantities import tec.units.indriya.unit.Units import java.time.Instant import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.Executor import java.util.concurrent.Executors import javax.measure.quantity.ElectricPotential /** * Class responsible for broadcasting messages received from Tekdaqcs. * <br></br>**This class is thread safe.** * @author Tenkiv ([email protected]) * * * @since v1.0.0.0 */ class MessageBroadcaster { /** * Map of all registered all-channel listeners. */ private val mFullListeners = ConcurrentHashMap<ATekdaqc, MutableList<IMessageListener>>() /** * Map of all registered network listeners. */ private val mNetworkListeners = ConcurrentHashMap<ATekdaqc, MutableList<INetworkListener>>() /** * Map of all registered count listeners. */ private val mAnalogCountListeners = ConcurrentHashMap<ATekdaqc, MutableMap<Int, MutableList<ICountListener>>>() /** * Map of all registered voltage listeners. */ private val mAnalogVoltageListeners = ConcurrentHashMap<ATekdaqc, MutableMap<Int, MutableList<IVoltageListener>>>() /** * Map of all registered digital listeners. */ private val mDigitalChannelListeners = ConcurrentHashMap<ATekdaqc, MutableMap<Int, MutableList<IDigitalChannelListener>>>() /** * Map of all registered PWM Input listeners. */ private val mPWMChannelListeners = ConcurrentHashMap<ATekdaqc, MutableMap<Int, MutableList<IPWMChannelListener>>>() /** * Map of prioritized listeners. */ private val mQueueListeners = ConcurrentHashMap<ATekdaqc, IMessageListener>() /** * Executor for handling callbacks to listeners. */ private var mCallbackThreadpool: Executor = Executors.newCachedThreadPool() /** * Sets the [Executor] that manages callbacks to [IMessageListener]s, [ICountListener]s, * and [IDigitalChannelListener]s. * @param callbackExecutor The new [Executor]. */ fun setCallbackExecutor(callbackExecutor: Executor) { mCallbackThreadpool = callbackExecutor } internal fun commandQueueAddListener(tekdaqc: ATekdaqc, listener: IMessageListener) { mQueueListeners.put(tekdaqc, listener) } internal fun commandQueueRemoveListener(tekdaqc: ATekdaqc) { mQueueListeners.remove(tekdaqc) } /** * Register an object for message broadcasts for a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to register for. * * * @param listener [IMessageListener] Listener instance to receive the broadcasts. */ fun addMessageListener(tekdaqc: ATekdaqc, listener: IMessageListener) { val listeners: MutableList<IMessageListener> = mFullListeners.computeIfAbsent(tekdaqc, { ArrayList() }) synchronized(listeners) { if (!listeners.contains(listener)) { listeners.add(listener) } } } /** * Register an object for network message broadcasts for a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to register for. * * * @param listener [IMessageListener] Listener instance to receive the broadcasts. */ fun addNetworkListener(tekdaqc: ATekdaqc, listener: INetworkListener) { val listeners: MutableList<INetworkListener> = mNetworkListeners.computeIfAbsent(tekdaqc, { ArrayList() }) synchronized(listeners) { if (!listeners.contains(listener)) { listeners.add(listener) } } } /** * Un-register an object for network message broadcasts for a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for. * * * @param listener [IMessageListener] Listener instance to remove from broadcasts. */ fun removeNetworkListener(tekdaqc: ATekdaqc, listener: INetworkListener) { val listeners = mNetworkListeners[tekdaqc] if (listeners != null) { synchronized(listeners) { listeners.remove(listener) if (listeners.size == 0) { mNetworkListeners.remove(tekdaqc) } } } } /** * Register an object for PWM broadcasts for a specific channel on a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to register for. * * * @param input [DigitalInput] Physical number of the channel to listen for. * * * @param listener [IPWMChannelListener] Listener instance to receive the broadcasts. */ fun addPWMChannelListener(tekdaqc: ATekdaqc, input: DigitalInput, listener: IPWMChannelListener) { val listeners: MutableMap<Int, MutableList<IPWMChannelListener>> = mPWMChannelListeners.computeIfAbsent(tekdaqc, { ConcurrentHashMap() }) synchronized(listeners) { val listenerList: MutableList<IPWMChannelListener> = listeners.getOrPut(input.channelNumber, { ArrayList<IPWMChannelListener>() }) if (!listenerList.contains(listener)) { listenerList.add(listener) } } } /** * Un-register an object from PWM broadcasts for a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for. * * * @param input [DigitalInput] The input to unregister from * * * @param listener [IPWMChannelListener] Listener instance to remove from broadcasts. */ fun removePWMChannelListener(tekdaqc: ATekdaqc, input: DigitalInput, listener: IPWMChannelListener) { unregisterInputListener(tekdaqc, input, listener, mPWMChannelListeners) } /** * Register an object for message broadcasts for a specific channel on a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to register for. * * * @param input [AAnalogInput] Physical number of the channel to listen for. * * * @param listener [ICountListener] Listener instance to receive the broadcasts. */ fun addAnalogChannelListener(tekdaqc: ATekdaqc, input: AAnalogInput, listener: ICountListener) { val listeners: MutableMap<Int, MutableList<ICountListener>> = mAnalogCountListeners.computeIfAbsent(tekdaqc, { ConcurrentHashMap() }) synchronized(listeners) { val listenerList: MutableList<ICountListener> = listeners.getOrPut(input.channelNumber, { ArrayList() }) if (!listenerList.contains(listener)) { listenerList.add(listener) } } } /** * Register an object for message broadcasts for a specific channel on a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to register for. * * * @param input [AAnalogInput] Physical number of the channel to listen for. * * * @param listener [IVoltageListener] Listener instance to receive the broadcasts. */ fun addAnalogVoltageListener(tekdaqc: ATekdaqc, input: AAnalogInput, listener: IVoltageListener) { val listeners: MutableMap<Int, MutableList<IVoltageListener>> = mAnalogVoltageListeners.computeIfAbsent(tekdaqc, { ConcurrentHashMap() }) synchronized(listeners) { val listenerList: MutableList<IVoltageListener> = listeners.getOrPut(input.channelNumber, { ArrayList() }) if (!listenerList.contains(listener)) { listenerList.add(listener) } } } /** * Register an object for message broadcasts for a specific channel on a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to register for. * * * @param input [DigitalInput] Physical number of the channel to listen for. * * * @param listener [IDigitalChannelListener] Listener instance to receive the broadcasts. */ fun addDigitalChannelListener(tekdaqc: ATekdaqc, input: DigitalInput, listener: IDigitalChannelListener) { val listeners: MutableMap<Int, MutableList<IDigitalChannelListener>> = mDigitalChannelListeners.computeIfAbsent(tekdaqc, { ConcurrentHashMap() }) synchronized(listeners) { val listenerList: MutableList<IDigitalChannelListener> = listeners.getOrPut(input.channelNumber, { ArrayList() }) if (!listenerList.contains(listener)) { listenerList.add(listener) } } } /** * Un-register an object from message broadcasts for a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for. * * * @param listener [IMessageListener] Listener instance to remove from broadcasts. */ fun removeListener(tekdaqc: ATekdaqc, listener: IMessageListener) { val listeners = mFullListeners[tekdaqc] if (listeners != null) { synchronized(listeners) { listeners.remove(listener) if (listeners.size == 0) { mFullListeners.remove(tekdaqc) } } } } /** * Un-register an object from message broadcasts for a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for. * * * @param input [AAnalogInput] The input to unregister from * * * @param listener [ICountListener] Listener instance to remove from broadcasts. */ fun removeAnalogCountListener(tekdaqc: ATekdaqc, input: AAnalogInput, listener: ICountListener) { unregisterInputListener(tekdaqc, input, listener, mAnalogCountListeners) } /** * Un-register an object from message broadcasts for a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for. * * * @param input [AAnalogInput] The input to unregister from * * * @param listener [IVoltageListener] Listener instance to remove from broadcasts. */ fun removeAnalogVoltageListener(tekdaqc: ATekdaqc, input: AAnalogInput, listener: IVoltageListener) { unregisterInputListener(tekdaqc, input, listener, mAnalogVoltageListeners) } /** * Un-register an object from message broadcasts for a particular Tekdaqc. * @param tekdaqc [ATekdaqc] The Tekdaqc to un-register for. * * * @param input [DigitalInput] The input to unregister from * * * @param listener [IDigitalChannelListener] Listener instance to remove from broadcasts. */ fun removeDigitalChannelListener(tekdaqc: ATekdaqc, input: DigitalInput, listener: IDigitalChannelListener) { unregisterInputListener(tekdaqc, input, listener, mDigitalChannelListeners) } private fun <IT : IInputOutputHardware, LT> unregisterInputListener(tekdaqc: ATekdaqc, input: IT, listener: LT, listenerMap: MutableMap<ATekdaqc, MutableMap<Int, MutableList<LT>>>) { val listeners = listenerMap[tekdaqc]?.get(input.channelNumber) if (listeners != null) { synchronized(listeners) { listeners.remove(listener) if (listeners.size == 0) { listenerMap[tekdaqc]?.remove(input.channelNumber) } } } } /** * Broadcast a [ABoardMessage] to all registered listeners for the specified Tekdaqc. * @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for. * * * @param message [ABoardMessage] The message to broadcast. */ fun broadcastMessage(tekdaqc: ATekdaqc, message: ABoardMessage) { mCallbackThreadpool.execute(BroadcastRunnable(tekdaqc, message)) } /** * Broadcast a [ABoardMessage] to registered network listeners for the specified Tekdaqc. * @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for. * * * @param message [ABoardMessage] The message to broadcast. */ fun broadcastNetworkError(tekdaqc: ATekdaqc, message: ABoardMessage) { mCallbackThreadpool.execute(NetworkBroadcastRunnable(tekdaqc, message)) } /** * Broadcast a single [AnalogInputCountData] point to all registered listeners for the specified Tekdaqc. * @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for. * * * @param data [AnalogInputCountData] The data point to broadcast. */ fun broadcastAnalogInputDataPoint(tekdaqc: ATekdaqc, data: AnalogInputCountData) { val listeners = mFullListeners[tekdaqc] if (listeners != null) { synchronized(listeners) { listeners.forEach { listener -> listener.onAnalogInputDataReceived(tekdaqc, data) } } } if (mAnalogCountListeners.containsKey(tekdaqc)) { if (mAnalogCountListeners[tekdaqc]?.containsKey(data.physicalInput) == true) { val channelListeners = mAnalogCountListeners[tekdaqc]?.get(data.physicalInput) channelListeners?.let { synchronized(it) { channelListeners.forEach { listener -> listener.onAnalogDataReceived(tekdaqc.getAnalogInput(data.physicalInput), data.data) } } } } } if (mAnalogVoltageListeners.containsKey(tekdaqc)) { if (mAnalogVoltageListeners[tekdaqc]?.containsKey(data.physicalInput) == true) { val channelListeners = mAnalogVoltageListeners[tekdaqc]?.get(data.physicalInput) channelListeners?.let { synchronized(it) { val quant = Quantities.getQuantity( tekdaqc.convertAnalogInputDataToVoltage( data, tekdaqc.analogScale), Units.VOLT) channelListeners.forEach { listener -> listener.onVoltageDataReceived( tekdaqc.getAnalogInput(data.physicalInput), ValueInstant<ComparableQuantity<ElectricPotential>>( quant, Instant.ofEpochMilli(data.timestamp))) } } } } } } /** * Broadcast a single [DigitalInputData] point to all registered listeners for the specified Tekdaqc. * @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for. * * * @param data [DigitalInputData] The data point to broadcast. */ fun broadcastDigitalInputDataPoint(tekdaqc: ATekdaqc, data: DigitalInputData) { val listeners = mFullListeners[tekdaqc] listeners?.let { synchronized(it) { for (listener in listeners) { listener.onDigitalInputDataReceived(tekdaqc, data) } } } if (mDigitalChannelListeners.containsKey(tekdaqc)) { if (mDigitalChannelListeners[tekdaqc]?.containsKey(data.physicalInput) == true) { val channelListeners = mDigitalChannelListeners[tekdaqc]?.get(data.physicalInput) channelListeners?.let { synchronized(it) { channelListeners.forEach { listener -> listener.onDigitalDataReceived(tekdaqc.getDigitalInput(data.physicalInput), data) } } } } } } /** * Broadcast a single [DigitalInputData] point to all registered listeners for the specified Tekdaqc. * @param tekdaqc [ATekdaqc] The serial number string of the Tekdaqc to broadcast for. * * * @param data [DigitalInputData] The data point to broadcast. */ fun broadcastPWMInputDataPoint(tekdaqc: ATekdaqc, data: PWMInputData) { if (mPWMChannelListeners.containsKey(tekdaqc)) { if (mPWMChannelListeners[tekdaqc]?.containsKey(data.physicalInput) == true) { val channelListeners = mPWMChannelListeners[tekdaqc]?.get(data.physicalInput) channelListeners?.let { synchronized(it) { channelListeners.forEach { listener -> listener.onPWMDataReceived(tekdaqc.getDigitalInput(data.physicalInput), data) } } } } } } /** * Class that wraps callbacks from the [com.tenkiv.tekdaqc.communication.ascii.executors.ASCIIParsingExecutor] * so that they are called back in a different thread. */ private inner class BroadcastRunnable(internal val mTekdaqc: ATekdaqc, internal val mMessage: ABoardMessage) : Runnable { override fun run() { if (mMessage.type == ASCIIMessageUtils.MESSAGE_TYPE.STATUS) { mQueueListeners[mTekdaqc]?.onStatusMessageReceived(mTekdaqc, mMessage) } else if (mMessage.type == ASCIIMessageUtils.MESSAGE_TYPE.ERROR) { mQueueListeners[mTekdaqc]?.onStatusMessageReceived(mTekdaqc, mMessage) } val listeners = mFullListeners[mTekdaqc] if (listeners != null) { synchronized(listeners) { for (listener in listeners) { when (mMessage.type) { ASCIIMessageUtils.MESSAGE_TYPE.DEBUG -> listener.onDebugMessageReceived(mTekdaqc, mMessage) ASCIIMessageUtils.MESSAGE_TYPE.STATUS -> listener.onStatusMessageReceived(mTekdaqc, mMessage) ASCIIMessageUtils.MESSAGE_TYPE.ERROR -> listener.onErrorMessageReceived(mTekdaqc, mMessage) ASCIIMessageUtils.MESSAGE_TYPE.COMMAND_DATA -> listener.onCommandDataMessageReceived(mTekdaqc, mMessage) ASCIIMessageUtils.MESSAGE_TYPE.DIGITAL_OUTPUT_DATA -> { listener.onDigitalOutputDataReceived( mTekdaqc, (mMessage as ASCIIDigitalOutputDataMessage).digitalOutputArray) System.err.println("Unknown message type with serial: " + mTekdaqc.serialNumber) } else -> System.err.println("Unknown message type with serial: " + mTekdaqc.serialNumber) } } } } } } private inner class NetworkBroadcastRunnable( internal val mTekdaqc: ATekdaqc, internal val mMessage: ABoardMessage) : Runnable { override fun run() { val listeners = mNetworkListeners[mTekdaqc] listeners?.forEach { listener -> listener.onNetworkConditionDetected(mTekdaqc, mMessage) } } } }
src/main/java/com/tenkiv/tekdaqc/communication/message/MessageBroadcaster.kt
838951617
@file:Suppress( names = "NOTHING_TO_INLINE" ) package com.jakewharton.rxbinding2.support.v4.view import android.support.v4.view.ViewPager import com.jakewharton.rxbinding2.InitialValueObservable import io.reactivex.Observable import io.reactivex.functions.Consumer import kotlin.Int import kotlin.Suppress /** * Create an observable of scroll state change events on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ inline fun ViewPager.pageScrollStateChanges(): Observable<Int> = RxViewPager.pageScrollStateChanges(this) /** * Create an observable of page selected events on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ inline fun ViewPager.pageSelections(): InitialValueObservable<Int> = RxViewPager.pageSelections(this) /** * An action which sets the current item of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ inline fun ViewPager.currentItem(): Consumer<in Int> = RxViewPager.currentItem(this)
rxbinding-support-v4-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/support/v4/view/RxViewPager.kt
3848135507
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.app import com.almasb.fxgl.ui.DialogBox import com.almasb.fxgl.ui.DialogService import javafx.beans.property.ReadOnlyDoubleProperty import javafx.scene.Node import javafx.scene.control.Button import java.util.function.Consumer import java.util.function.Predicate /** * * @author Almas Baimagambetov ([email protected]) */ object MockDialogService : DialogService() { override fun showErrorBox(error: Throwable?) { } override fun showErrorBox(errorMessage: String?, callback: Runnable?) { } override fun showConfirmationBox(message: String?, resultCallback: Consumer<Boolean>?) { } override fun <T : Any?> showChoiceBox(message: String?, resultCallback: Consumer<T>?, firstOption: T, vararg options: T) { } override fun showInputBoxWithCancel(message: String?, filter: Predicate<String>?, resultCallback: Consumer<String>?) { } override fun showBox(message: String?, content: Node?, vararg buttons: Button?) { } override fun showMessageBox(message: String?) { } override fun showMessageBox(message: String?, callback: Runnable?) { } override fun showProgressBox(message: String?): DialogBox { return object : DialogBox { override fun close() { } } } override fun showProgressBox(message: String?, progress: ReadOnlyDoubleProperty?, callback: Runnable?) { } override fun showInputBox(message: String?, resultCallback: Consumer<String>?) { } override fun showInputBox(message: String?, filter: Predicate<String>?, resultCallback: Consumer<String>?) { } }
fxgl/src/test/kotlin/com/almasb/fxgl/app/MockDialogService.kt
4201460154
package io.github.manamiproject.manami.gui.dashboard import io.github.manamiproject.manami.app.lists.AnimeEntry import io.github.manamiproject.manami.app.lists.Link import io.github.manamiproject.manami.gui.components.numberTile import io.github.manamiproject.manami.gui.events.* import io.github.manamiproject.modb.core.config.Hostname import javafx.beans.property.SimpleStringProperty import javafx.geometry.Pos.CENTER import javafx.scene.paint.Color.* import tornadofx.View import tornadofx.gridpane import tornadofx.row import kotlin.collections.Collection import kotlin.collections.component1 import kotlin.collections.component2 import kotlin.collections.filter import kotlin.collections.forEach import kotlin.collections.groupBy import kotlin.collections.mutableMapOf import kotlin.collections.set import kotlin.math.roundToInt class DashboardView: View() { private val animeListEntriesProperty = SimpleStringProperty("0") private val watchListEntriesProperty = SimpleStringProperty("0") private val ignoreListEntriesProperty = SimpleStringProperty("0") private val metaDataProviderEntriesInLists = mutableMapOf<Hostname, Int>() private val metaDataProviderTotalNumberOfEntries = mutableMapOf<Hostname, Int>() private val metaDataProviderSeenStringProperties = mutableMapOf<Hostname, SimpleStringProperty>().apply { put("myanimelist.net", SimpleStringProperty("0")) put("kitsu.io", SimpleStringProperty("0")) put("anime-planet.com", SimpleStringProperty("0")) put("notify.moe", SimpleStringProperty("0")) put("anilist.co", SimpleStringProperty("0")) put("anidb.net", SimpleStringProperty("0")) put("anisearch.com", SimpleStringProperty("0")) put("livechart.me", SimpleStringProperty("0")) } init { subscribe<AddAnimeListEntryGuiEvent> { event -> val newValue = animeListEntriesProperty.get().toInt() + event.entries.size animeListEntriesProperty.set(newValue.toString()) addNumberOfEntriesToPercentageTile(event.entries) } subscribe<RemoveAnimeListEntryGuiEvent> { event -> val newValue = animeListEntriesProperty.get().toInt() - event.entries.size animeListEntriesProperty.set(newValue.toString()) removeNumberOfEntriesToPercentageTile(event.entries) } subscribe<AddWatchListEntryGuiEvent> { event -> val newValue = watchListEntriesProperty.get().toInt() + event.entries.size watchListEntriesProperty.set(newValue.toString()) addNumberOfEntriesToPercentageTile(event.entries) } subscribe<RemoveWatchListEntryGuiEvent> { event -> val newValue = watchListEntriesProperty.get().toInt() - event.entries.size watchListEntriesProperty.set(newValue.toString()) removeNumberOfEntriesToPercentageTile(event.entries) } subscribe<AddIgnoreListEntryGuiEvent> { event -> val newValue = ignoreListEntriesProperty.get().toInt() + event.entries.size ignoreListEntriesProperty.set(newValue.toString()) addNumberOfEntriesToPercentageTile(event.entries) } subscribe<RemoveIgnoreListEntryGuiEvent> { event -> val newValue = ignoreListEntriesProperty.get().toInt() - event.entries.size ignoreListEntriesProperty.set(newValue.toString()) removeNumberOfEntriesToPercentageTile(event.entries) } subscribe<NumberOfEntriesPerMetaDataProviderGuiEvent> { event -> metaDataProviderTotalNumberOfEntries.putAll(event.entries) updateStringProperties() } } override val root = gridpane { hgap = 50.0 vgap = 50.0 alignment = CENTER row { alignment = CENTER numberTile { title = "AnimeList" color = MEDIUMSEAGREEN valueProperty = animeListEntriesProperty } numberTile { title = "WatchList" color = CORNFLOWERBLUE valueProperty = watchListEntriesProperty } numberTile { title = "IgnoreList" color = INDIANRED valueProperty = ignoreListEntriesProperty } } row { numberTile { title = "myanimelist.net" color = SLATEGRAY valueProperty = metaDataProviderSeenStringProperties["myanimelist.net"]!! } numberTile { title = "anime-planet.com" color = SLATEGRAY valueProperty = metaDataProviderSeenStringProperties["anime-planet.com"]!! } numberTile { title = "kitsu.io" color = SLATEGRAY valueProperty = metaDataProviderSeenStringProperties["kitsu.io"]!! } } row { numberTile { title = "anisearch.com" color = SLATEGRAY valueProperty = metaDataProviderSeenStringProperties["anisearch.com"]!! } numberTile { title = "anilist.co" color = SLATEGRAY valueProperty = metaDataProviderSeenStringProperties["anilist.co"]!! } numberTile { title = "notify.moe" color = SLATEGRAY valueProperty = metaDataProviderSeenStringProperties["notify.moe"]!! } } row { numberTile { title = "anidb.net" color = SLATEGRAY valueProperty = metaDataProviderSeenStringProperties["anidb.net"]!! } numberTile { title = "livechart.me" color = SLATEGRAY valueProperty = metaDataProviderSeenStringProperties["livechart.me"]!! } } } @Synchronized private fun addNumberOfEntriesToPercentageTile(entries: Collection<AnimeEntry>) { entries.filter { it.link is Link }.groupBy { it.link.asLink().uri.host }.forEach { (key, value) -> metaDataProviderEntriesInLists[key] = (metaDataProviderEntriesInLists[key] ?: 0) + value.size } updateStringProperties() } @Synchronized private fun removeNumberOfEntriesToPercentageTile(entries: Collection<AnimeEntry>) { entries.filter { it.link is Link }.groupBy { it.link.asLink().uri.host }.forEach { (key, value) -> metaDataProviderEntriesInLists[key] = (metaDataProviderEntriesInLists[key] ?: 0) - value.size } updateStringProperties() } @Synchronized private fun updateStringProperties() { metaDataProviderSeenStringProperties.keys.forEach { val inList = metaDataProviderEntriesInLists[it] ?: 0 val totalNumber = metaDataProviderTotalNumberOfEntries[it] ?: 0 val progressValue = when { inList == 0 && totalNumber == 0 -> "0" inList == 0 && totalNumber > 0 -> "$totalNumber" inList > 0 && totalNumber == 0 -> "$inList / ?" else -> { val difference = totalNumber - inList val percent = (inList.toDouble() / totalNumber.toDouble() * 100.0).roundToInt() "$totalNumber - $inList = $difference ($percent%)" } } metaDataProviderSeenStringProperties[it]!!.set(progressValue) } } }
manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/dashboard/DashboardView.kt
1792706648
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.locks.bukkit.messages import com.rpkit.core.bukkit.message.BukkitMessages import com.rpkit.core.message.ParameterizedMessage import com.rpkit.core.message.to import com.rpkit.locks.bukkit.RPKLocksBukkit import org.bukkit.Material class LocksMessages(plugin: RPKLocksBukkit) : BukkitMessages(plugin) { class BlockLockedMessage(private val message: ParameterizedMessage) { fun withParameters(blockType: Material) = message.withParameters( "block" to blockType.toString().lowercase().replace('_', ' ') ) } val blockLocked = getParameterized("block-locked").let(::BlockLockedMessage) val craftingNoKeys = get("crafting-no-keys") val keyringInvalidItem = get("keyring-invalid-item") val lockSuccessful = get("lock-successful") val lockInvalidAlreadyLocked = get("lock-invalid-already-locked") val unlockSuccessful = get("unlock-successful") val unlockInvalidNoKey = get("unlock-invalid-no-key") val unlockInvalidNotLocked = get("unlock-invalid-not-locked") val getKeyInvalidNotLocked = get("get-key-invalid-not-locked") val getKeySuccessful = get("get-key-successful") val getKeyValid = get("get-key-valid") val unlockValid = get("unlock-valid") val copyKeyInvalidNoKeyInHand = get("copy-key-invalid-no-key-in-hand") val copyKeyInvalidNoMaterial = get("copy-key-invalid-no-material") val copyKeyValid = get("copy-key-valid") val notFromConsole = get("not-from-console") val noCharacter = get("no-character") val noMinecraftProfile = get("no-minecraft-profile") val noPermissionCopyKey = get("no-permission-copy-key") val noPermissionGetKey = get("no-permission-get-key") val noPermissionKeyring = get("no-permission-keyring") val noPermissionUnlock = get("no-permission-unlock") val noMinecraftProfileService = get("no-minecraft-profile-service") val noCharacterService = get("no-character-service") val noLockService = get("no-lock-service") val noKeyringService = get("no-keyring-service") }
bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/messages/LocksMessages.kt
352830747
package tech.summerly.quiet.data.netease.result import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * author : SUMMERLY * e-mail : [email protected] * time : 2017/8/24 * desc : */ data class LoginResultBean( @SerializedName("loginType") @Expose val loginType: Long? = null, @SerializedName("code") @Expose val code: Long, @SerializedName("profile") @Expose val profile: Profile? = null // @SerializedName("account") // @Expose // var account: Account? = null, // @SerializedName("bindings") // @Expose // var bindings: List<Binding>? = null ) { data class Profile( @SerializedName("followed") @Expose val followed: Boolean? = null, @SerializedName("userId") @Expose val userId: Long, @SerializedName("nickname") @Expose val nickname: String, @SerializedName("avatarUrl") @Expose val avatarUrl: String? = null, @SerializedName("backgroundUrl") @Expose val backgroundUrl: String? = null // @SerializedName("avatarImgId") // @Expose // var avatarImgId: Long? = null, // @SerializedName("backgroundImgId") // @Expose // var backgroundImgId: Long? = null, // @SerializedName("detailDescription") // @Expose // var detailDescription: String? = null, // // @SerializedName("djStatus") // @Expose // var djStatus: Long? = null, // @SerializedName("accountStatus") // @Expose // var accountStatus: Long? = null, // @SerializedName("defaultAvatar") // @Expose // var defaultAvatar: Boolean? = null, // @SerializedName("gender") // @Expose // var gender: Long? = null, // @SerializedName("birthday") // @Expose // var birthday: Long? = null, // @SerializedName("city") // @Expose // var city: Long? = null, // @SerializedName("province") // @Expose // var province: Long? = null, // @SerializedName("mutual") // @Expose // var mutual: Boolean? = null, // @SerializedName("remarkName") // @Expose // var remarkName: Any? = null, // @SerializedName("experts") // @Expose // var experts: Experts? = null, // @SerializedName("expertTags") // @Expose // var expertTags: Any? = null, // @SerializedName("userType") // @Expose // var userType: Long? = null, // @SerializedName("vipType") // @Expose // var vipType: Long? = null, // @SerializedName("authStatus") // @Expose // var authStatus: Long? = null, // @SerializedName("description") // @Expose // var description: String? = null, // @SerializedName("avatarImgIdStr") // @Expose // var avatarImgIdStr: String? = null, // @SerializedName("backgroundImgIdStr") // @Expose // var backgroundImgIdStr: String? = null, // @SerializedName("signature") // @Expose // var signature: String? = null, // @SerializedName("authority") // @Expose // var authority: Long? = null ) //data class Account( // // @SerializedName("id") // @Expose // var id: Long? = null, // @SerializedName("userName") // @Expose // var userName: String? = null, // @SerializedName("type") // @Expose // var type: Long? = null, // @SerializedName("status") // @Expose // var status: Long? = null, // @SerializedName("whitelistAuthority") // @Expose // var whitelistAuthority: Long? = null, // @SerializedName("createTime") // @Expose // var createTime: Long? = null, // @SerializedName("salt") // @Expose // var salt: String? = null, // @SerializedName("tokenVersion") // @Expose // var tokenVersion: Long? = null, // @SerializedName("ban") // @Expose // var ban: Long? = null, // @SerializedName("baoyueVersion") // @Expose // var baoyueVersion: Long? = null, // @SerializedName("donateVersion") // @Expose // var donateVersion: Long? = null, // @SerializedName("vipType") // @Expose // var vipType: Long? = null, // @SerializedName("viptypeVersion") // @Expose // var viptypeVersion: Long? = null, // @SerializedName("anonimousUser") // @Expose // var anonimousUser: Boolean? = null // //) //class Binding { // // @SerializedName("expiresIn") // @Expose // var expiresIn: Long? = null // @SerializedName("refreshTime") // @Expose // var refreshTime: Long? = null // @SerializedName("url") // @Expose // var url: String? = null // @SerializedName("userId") // @Expose // var userId: Long? = null // @SerializedName("tokenJsonStr") // @Expose // var tokenJsonStr: String? = null // @SerializedName("expired") // @Expose // var expired: Boolean? = null // @SerializedName("id") // @Expose // var id: Long? = null // @SerializedName("type") // @Expose // var type: Long? = null // //} }
app/src/main/java/tech/summerly/quiet/data/netease/result/LoginResultBean.kt
8951066
package io.github.manamiproject.manami.app.inconsistencies.lists.metadata import io.github.manamiproject.manami.app.cache.* import io.github.manamiproject.manami.app.cache.TestAnimeCache import io.github.manamiproject.manami.app.inconsistencies.InconsistenciesSearchConfig import io.github.manamiproject.manami.app.lists.Link import io.github.manamiproject.manami.app.lists.ignorelist.IgnoreListEntry import io.github.manamiproject.manami.app.lists.watchlist.WatchListEntry import io.github.manamiproject.manami.app.state.State import io.github.manamiproject.manami.app.state.TestState import io.github.manamiproject.modb.core.collections.SortedList import io.github.manamiproject.modb.core.models.Anime import io.github.manamiproject.modb.core.models.Anime.Status.FINISHED import io.github.manamiproject.modb.core.models.Anime.Type.TV import io.github.manamiproject.modb.core.models.AnimeSeason import io.github.manamiproject.modb.core.models.AnimeSeason.Season.FALL import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import java.net.URI internal class MetaDataInconsistencyHandlerTest { @Nested inner class IsExecutableTests { @Test fun `is executable if the config explicitly activates the option`() { // given val inconsistencyHandler = MetaDataInconsistencyHandler( state = TestState, cache = TestAnimeCache, ) val isExecutableConfig = InconsistenciesSearchConfig( checkMetaData = true, ) // when val result = inconsistencyHandler.isExecutable(isExecutableConfig) // then assertThat(result).isTrue() } @Test fun `is not executable if the config doesn't explicitly activates the option`() { // given val inconsistencyHandler = MetaDataInconsistencyHandler( state = TestState, cache = TestAnimeCache, ) val isNotExecutableConfig = InconsistenciesSearchConfig( checkMetaData = false, ) // when val result = inconsistencyHandler.isExecutable(isNotExecutableConfig) // then assertThat(result).isFalse() } } @Nested inner class CalculateWorkloadTests { @Test fun `workload is computed by size of watch- and ignoreList`() { // given val testState = object: State by TestState { override fun watchList(): Set<WatchListEntry> = setOf( WatchListEntry( link = Link("https://myanimelist.net/anime/5114"), title = "Fullmetal Alchemist: Brotherhood", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1223/96541t.jpg"), ) ) override fun ignoreList(): Set<IgnoreListEntry> = setOf( IgnoreListEntry( link = Link("https://myanimelist.net/anime/31139"), title = "Ame-iro Cocoa: Rainy Color e Youkoso!", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1065/111717t.jpg"), ), IgnoreListEntry( link = Link("https://myanimelist.net/anime/37747"), title = "Ame-iro Cocoa: Side G", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1394/111379t.jpg"), ) ) } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, ) // when val result = inconsistencyHandler.calculateWorkload() // then assertThat(result).isEqualTo(3) } } @Nested inner class ExecuteTests { @Nested inner class WatchListTests { @Test fun `entries without cache entry cannot appear in result`() { // given val testState = object: State by TestState { override fun watchList(): Set<WatchListEntry> = setOf( WatchListEntry( link = Link("https://myanimelist.net/anime/10001"), title = "Dead entry", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) override fun ignoreList(): Set<IgnoreListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = DeadEntry() } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults).isEmpty() assertThat(result.ignoreListResults).isEmpty() } @Test fun `do not include entry if current entry and entry from cache have different links`() { // given val testState = object: State by TestState { override fun watchList(): Set<WatchListEntry> = setOf( WatchListEntry( link = Link("https://myanimelist.net/anime/10001"), title = "Dead entry", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) override fun ignoreList(): Set<IgnoreListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = PresentValue( Anime( sources = SortedList( URI("https://myanimelist.net/anime/31646"), ), _title = "3-gatsu no Lion", type = TV, episodes = 22, status = FINISHED, animeSeason = AnimeSeason( season = FALL, year = 2016, ), relatedAnime = SortedList( URI("https://myanimelist.net/anime/28789"), URI("https://myanimelist.net/anime/34611"), URI("https://myanimelist.net/anime/34647"), URI("https://myanimelist.net/anime/35180"), URI("https://myanimelist.net/anime/38154"), ), ) ) } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults).isEmpty() assertThat(result.ignoreListResults).isEmpty() } @Test fun `do not include entry if current entry and entry from cache do not differ`() { // given val testState = object: State by TestState { override fun watchList(): Set<WatchListEntry> = setOf( WatchListEntry( link = Link("https://myanimelist.net/anime/31646"), title = "3-gatsu no Lion", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) override fun ignoreList(): Set<IgnoreListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = PresentValue( Anime( sources = SortedList( URI("https://myanimelist.net/anime/31646"), ), _title = "3-gatsu no Lion", type = TV, episodes = 22, status = FINISHED, thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), animeSeason = AnimeSeason( season = FALL, year = 2016, ), relatedAnime = SortedList( URI("https://myanimelist.net/anime/28789"), URI("https://myanimelist.net/anime/34611"), URI("https://myanimelist.net/anime/34647"), URI("https://myanimelist.net/anime/35180"), URI("https://myanimelist.net/anime/38154"), ), ) ) } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults).isEmpty() assertThat(result.ignoreListResults).isEmpty() } @Test fun `include entry if title differ`() { // given val testState = object: State by TestState { override fun watchList(): Set<WatchListEntry> = setOf( WatchListEntry( link = Link("https://myanimelist.net/anime/31646"), title = "sangatsu no Lion", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) override fun ignoreList(): Set<IgnoreListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = PresentValue( Anime( sources = SortedList( URI("https://myanimelist.net/anime/31646"), ), _title = "3-gatsu no Lion", type = TV, episodes = 22, status = FINISHED, thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), animeSeason = AnimeSeason( season = FALL, year = 2016, ), relatedAnime = SortedList( URI("https://myanimelist.net/anime/28789"), URI("https://myanimelist.net/anime/34611"), URI("https://myanimelist.net/anime/34647"), URI("https://myanimelist.net/anime/35180"), URI("https://myanimelist.net/anime/38154"), ), ) ) } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults.size).isOne() val entry = result.watchListResults.first() assertThat(entry.currentEntry).isEqualTo( WatchListEntry( link = Link("https://myanimelist.net/anime/31646"), title = "sangatsu no Lion", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) assertThat(entry.newEntry).isEqualTo( WatchListEntry( link = Link("https://myanimelist.net/anime/31646"), title = "3-gatsu no Lion", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) assertThat(result.ignoreListResults).isEmpty() } @Test fun `include entry if thumbnails differ`() { // given val testState = object: State by TestState { override fun watchList(): Set<WatchListEntry> = setOf( WatchListEntry( link = Link("https://myanimelist.net/anime/31646"), title = "3-gatsu no Lion", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) override fun ignoreList(): Set<IgnoreListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = PresentValue( Anime( sources = SortedList( URI("https://myanimelist.net/anime/31646"), ), _title = "3-gatsu no Lion", type = TV, episodes = 22, status = FINISHED, thumbnail = URI("https://cdn.myanimelist.net/images/anime/6/82898t.jpg"), animeSeason = AnimeSeason( season = FALL, year = 2016, ), relatedAnime = SortedList( URI("https://myanimelist.net/anime/28789"), URI("https://myanimelist.net/anime/34611"), URI("https://myanimelist.net/anime/34647"), URI("https://myanimelist.net/anime/35180"), URI("https://myanimelist.net/anime/38154"), ), ) ) } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults.size).isOne() val entry = result.watchListResults.first() assertThat(entry.currentEntry).isEqualTo( WatchListEntry( link = Link("https://myanimelist.net/anime/31646"), title = "3-gatsu no Lion", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) assertThat(entry.newEntry).isEqualTo( WatchListEntry( link = Link("https://myanimelist.net/anime/31646"), title = "3-gatsu no Lion", thumbnail = URI("https://cdn.myanimelist.net/images/anime/6/82898t.jpg"), ) ) assertThat(result.ignoreListResults).isEmpty() } } @Nested inner class IgnoreListTests { @Test fun `entries without cache entry cannot appear in result`() { // given val testState = object: State by TestState { override fun ignoreList(): Set<IgnoreListEntry> = setOf( IgnoreListEntry( link = Link("https://myanimelist.net/anime/28981"), title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) override fun watchList(): Set<WatchListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = DeadEntry() } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults).isEmpty() assertThat(result.ignoreListResults).isEmpty() } @Test fun `do not include entry if current entry and entry from cache have different links`() { // given val testState = object: State by TestState { override fun ignoreList(): Set<IgnoreListEntry> = setOf( IgnoreListEntry( link = Link("https://myanimelist.net/anime/10001"), title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) override fun watchList(): Set<WatchListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = PresentValue( Anime( sources = SortedList( URI("https://myanimelist.net/anime/28981"), ), _title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults).isEmpty() assertThat(result.ignoreListResults).isEmpty() } @Test fun `do not include entry if current entry and entry from cache do not differ`() { // given val testState = object: State by TestState { override fun ignoreList(): Set<IgnoreListEntry> = setOf( IgnoreListEntry( link = Link("https://myanimelist.net/anime/28981"), title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) override fun watchList(): Set<WatchListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = PresentValue( Anime( sources = SortedList( URI("https://myanimelist.net/anime/28981"), ), _title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults).isEmpty() assertThat(result.ignoreListResults).isEmpty() } @Test fun `include entry if title differ`() { // given val testState = object: State by TestState { override fun ignoreList(): Set<IgnoreListEntry> = setOf( IgnoreListEntry( link = Link("https://myanimelist.net/anime/28981"), title = "Ameiro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) override fun watchList(): Set<WatchListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = PresentValue( Anime( sources = SortedList( URI("https://myanimelist.net/anime/28981"), ), _title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults).isEmpty() assertThat(result.ignoreListResults.size).isOne() val entry = result.ignoreListResults.first() assertThat(entry.currentEntry).isEqualTo( IgnoreListEntry( link = Link("https://myanimelist.net/anime/28981"), title = "Ameiro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) assertThat(entry.newEntry).isEqualTo( IgnoreListEntry( link = Link("https://myanimelist.net/anime/28981"), title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) } @Test fun `include entry if thumbnails differ`() { // given val testState = object: State by TestState { override fun ignoreList(): Set<IgnoreListEntry> = setOf( IgnoreListEntry( link = Link("https://myanimelist.net/anime/28981"), title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) override fun watchList(): Set<WatchListEntry> = emptySet() } val testCache = object: AnimeCache by TestAnimeCache { override fun fetch(key: URI): CacheEntry<Anime> = PresentValue( Anime( sources = SortedList( URI("https://myanimelist.net/anime/28981"), ), _title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) } val inconsistencyHandler = MetaDataInconsistencyHandler( state = testState, cache = testCache, ) // when val result = inconsistencyHandler.execute() // then assertThat(result.watchListResults).isEmpty() assertThat(result.ignoreListResults.size).isOne() val entry = result.ignoreListResults.first() assertThat(entry.currentEntry).isEqualTo( IgnoreListEntry( link = Link("https://myanimelist.net/anime/28981"), title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/qm_50.gif"), ) ) assertThat(entry.newEntry).isEqualTo( IgnoreListEntry( link = Link("https://myanimelist.net/anime/28981"), title = "Ame-iro Cocoa", thumbnail = URI("https://cdn.myanimelist.net/images/anime/1957/111714t.jpg"), ) ) } } } }
manami-app/src/test/kotlin/io/github/manamiproject/manami/app/inconsistencies/lists/metadata/MetaDataInconsistencyHandlerTest.kt
2620924589
package jp.takuji31.koreference.type import android.content.SharedPreferences /** * Created by takuji on 2015/08/14. */ interface LongPreference : Preference<Long> { override fun get(pref: SharedPreferences, key: String, default: Long): Long { return pref.getLong(key, default) } override fun set(editor: SharedPreferences.Editor, key: String, value: Long) { editor.putLong(key, value) } }
koreference/src/main/java/jp/takuji31/koreference/type/LongPreference.kt
1984254883
package org.droidplanner.android.fragments.widget import android.app.DialogFragment import android.app.FragmentManager import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.content.LocalBroadcastManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import org.droidplanner.android.R import org.droidplanner.android.fragments.SettingsFragment import org.droidplanner.android.utils.prefs.DroidPlannerPrefs /** * Created by Fredia Huya-Kouadio on 10/18/15. */ class WidgetsListPrefFragment : DialogFragment() { override fun onCreate(savedInstanceState: Bundle?){ super.onCreate(savedInstanceState) setStyle(DialogFragment.STYLE_NO_FRAME, R.style.CustomDialogTheme) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_widgets_list_pref, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val widgetsListPref = view.findViewById(R.id.widgets_list_pref) as ListView? widgetsListPref?.adapter = WidgetsAdapter(activity.applicationContext, fragmentManager) } class WidgetsAdapter(context: Context, val fm : FragmentManager) : ArrayAdapter<TowerWidgets>(context, 0, TowerWidgets.values()){ val appPrefs = DroidPlannerPrefs(context) val lbm = LocalBroadcastManager.getInstance(context) override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val towerWidget = getItem(position) val view = convertView ?: LayoutInflater.from(parent.context).inflate(R.layout.list_widgets_list_pref_item, parent, false) var viewHolder = view.tag as ViewHolder? if(viewHolder == null){ viewHolder = ViewHolder(view.findViewById(R.id.widget_pref_icon) as ImageView?, view.findViewById(R.id.widget_check) as CheckBox?, view.findViewById(R.id.widget_pref_title) as TextView?, view.findViewById(R.id.widget_pref_summary) as TextView?, view.findViewById(R.id.widget_pref_info)) } viewHolder.prefIcon?.visibility = if(towerWidget.hasPreferences()) View.VISIBLE else View.INVISIBLE viewHolder.prefIcon?.setOnClickListener { towerWidget.getPrefFragment()?.show(fm, "Widget pref dialog") } viewHolder.prefTitle?.setText(towerWidget.labelResId) viewHolder.prefSummary?.setText(towerWidget.descriptionResId) viewHolder.prefCheck?.setOnCheckedChangeListener(null) viewHolder.prefCheck?.isChecked = appPrefs.isWidgetEnabled(towerWidget) viewHolder.prefCheck?.setOnCheckedChangeListener { compoundButton, b -> appPrefs.enableWidget(towerWidget, b) lbm.sendBroadcast(Intent(SettingsFragment.ACTION_WIDGET_PREFERENCE_UPDATED) .putExtra(SettingsFragment.EXTRA_ADD_WIDGET, b) .putExtra(SettingsFragment.EXTRA_WIDGET_PREF_KEY, towerWidget.prefKey)) } viewHolder.prefInfo?.setOnClickListener { viewHolder?.prefCheck?.toggle() } view.tag = viewHolder return view } class ViewHolder(val prefIcon: ImageView?, val prefCheck: CheckBox?, val prefTitle : TextView?, val prefSummary: TextView?, val prefInfo: View?) } }
Android/src/org/droidplanner/android/fragments/widget/WidgetsListPrefFragment.kt
2754927259
package com.beust.kobalt import com.beust.kobalt.api.Kobalt import org.testng.annotations.BeforeSuite open class KobaltTest: BaseTest() { companion object { @BeforeSuite fun bs() { Kobalt.INJECTOR = com.google.inject.Guice.createInjector(TestModule()) } } }
src/test/kotlin/com/beust/kobalt/KobaltTest.kt
297298725
package `is`.xyz.mpv.config import `is`.xyz.mpv.R import android.content.Context import android.preference.DialogPreference import android.util.AttributeSet import android.view.View import android.widget.EditText import java.io.File class ConfigEditDialog @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.dialogPreferenceStyle, defStyleRes: Int = 0 ): DialogPreference(context, attrs, defStyleAttr, defStyleRes) { private var configFile: File init { isPersistent = false dialogLayoutResource = R.layout.conf_editor // determine where the file to be edited is located val styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.ConfigEditDialog) val filename = styledAttrs.getString(R.styleable.ConfigEditDialog_filename) configFile = File("${context.filesDir.path}/${filename}") styledAttrs.recycle() } private lateinit var myView: View override fun onBindDialogView(view: View) { super.onBindDialogView(view) myView = view val editText = view.findViewById<EditText>(R.id.editText) if (configFile.exists()) editText.setText(configFile.readText()) } override fun onDialogClosed(positiveResult: Boolean) { super.onDialogClosed(positiveResult) // save values only if user presses OK if (!positiveResult) return val content = myView.findViewById<EditText>(R.id.editText).text.toString() if (content == "") configFile.delete() else configFile.writeText(content) } }
app/src/main/java/is/xyz/mpv/config/ConfigEditDialog.kt
2585059571
/* 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 chattime.common import java.util.* fun Random.nextInt(origin: Int, bound: Int): Int = ints(1, origin, bound).findFirst().asInt fun Random.nextInt(range: IntRange): Int = nextInt(range.start, range.endInclusive + 1)
src/main/kotlin/chattime/common/Extensions.kt
9516579
package com.wayfair.userlist.data data class UsersListDataModel( val usersList: MutableList<UserDataModel> ) { data class UserDataModel( val login: String = "", val id: Int = 0, val node_id: String = "", val avatar_url: String = "", val url: String = "", val html_url: String = "", val type: String = "", val site_admin: Boolean = false ) }
android/anko_blogpost/Userlist/app/src/main/java/com/wayfair/userlist/data/UsersListDataModel.kt
2048948239
package azagroup.kotlin.css import java.io.File import java.util.ArrayList // CSS Selector Reference // http://www.w3schools.com/cssref/css_selectors.asp @Suppress("unused") class Stylesheet( callback: (Stylesheet.()->Unit)? = null ) : ASelector { var selector: Selector? = null var atRule: String? = null val properties = ArrayList<Property>(2) val children = ArrayList<Stylesheet>() init { callback?.invoke(this) } fun include(stylesheet: Stylesheet): Stylesheet { children.add(stylesheet) return this } override fun custom(selector: String, _spaceBefore: Boolean, _spaceAfter: Boolean, body: (Stylesheet.() -> Unit)?): Selector { val stylesheet = Stylesheet() val sel = Selector(stylesheet) sel.custom(selector, _spaceBefore, _spaceAfter) stylesheet.selector = sel include(stylesheet) body?.invoke(stylesheet) return sel } fun getProperty(name: String) = properties.find { it.name == name } fun setProperty(name: String, value: Any?) { properties.add(Property(name, value)) } fun moveDataTo(stylesheet: Stylesheet) { stylesheet.properties.addAll(properties) properties.clear() stylesheet.children.addAll(children) children.clear() } fun render() = buildString { render(this) } fun renderTo(sb: StringBuilder) = render(sb) fun renderToFile(file: File) { file.delete() file.writeText(render()) // "writeText" is a really clever helper } fun renderToFile(path: String) = renderToFile(File(path)) private fun render(sb: StringBuilder, selectorPrefix: CharSequence = "", _spaceBefore: Boolean = true) { val selector = selector val atRule = atRule if (atRule != null) sb.append(atRule).append('{') if (properties.isNotEmpty()) { val selectorStr = selector?.toString(selectorPrefix, _spaceBefore) val hasSelector = !selectorStr.isNullOrEmpty() if (hasSelector) sb.append(selectorStr).append('{') val lastIdx = properties.lastIndex properties.forEachIndexed { i, property -> val value = property.value if (value != null) sb.run { append(property.name) append(":") append(if (value is Number) cssDecimalFormat.format(value.toFloat()) else value) if (i < lastIdx) append(";") } else if (i == lastIdx && sb.last() == ';') sb.setLength(sb.length-1) } if (hasSelector) sb.append("}") } for (child in children) { val rows = selector?.rows if (rows != null && rows.isNotEmpty()) rows.forEach { child.render(sb, it.toString(selectorPrefix, _spaceBefore), it.spaceAfter) } else child.render(sb, selectorPrefix) } if (atRule != null) sb.append('}') } override fun toString() = "Stylesheet(sel:$selector; props:${properties.size}; childs:${children.size})" class Property( val name: String, val value: Any? ) { override fun toString() = "$name:$value" } // // AT-RULES // fun at(rule: Any, body: (Stylesheet.()->Unit)? = null): Stylesheet { val stylesheet = Stylesheet(body) stylesheet.selector = Selector.createEmpty(stylesheet) stylesheet.atRule = "@$rule" include(stylesheet) return stylesheet } fun media(vararg conditions: Any, body: (Stylesheet.()->Unit)? = null) = at("media (${conditions.joinToString(") and (")})", body) // // MAIN COMMANDS // operator fun CharSequence.invoke(body: Stylesheet.()->Unit) = toSelector().invoke(body) fun CharSequence.custom(selector: String, _spaceBefore: Boolean = true, _spaceAfter: Boolean = true, body: (Stylesheet.()->Unit)? = null): Selector { return when (this) { is ASelector -> custom(selector, _spaceBefore, _spaceAfter, body) else -> toSelector().custom(selector, _spaceBefore, _spaceAfter, body) } } fun CharSequence.pseudo(selector: String, body: (Stylesheet.()->Unit)? = null): Selector { return when (this) { is ASelector -> pseudo(selector, body) else -> toSelector().pseudo(selector, body) } } fun CharSequence.pseudoFn(selector: String, body: (Stylesheet.()->Unit)? = null): Selector { return when (this) { is ASelector -> pseudoFn(selector, body) else -> toSelector().pseudoFn(selector, body) } } infix fun CharSequence.and(obj: CharSequence): Selector { val sel = toSelector() when (obj) { is Selector -> { for (row in obj.rows) sel.rows.add(row) return sel } is Stylesheet -> { val selector = obj.selector!! selector.rows.addAll(0, sel.rows) return selector } else -> return and(obj.toSelector()) } } private fun CharSequence.toSelector() = when (this) { is Selector -> this is Stylesheet -> this.selector!! else -> when (this[0]) { '.' -> [email protected](this.drop(1)) '#' -> [email protected](this.drop(1)) '@' -> [email protected](this.drop(1)).selector!! else -> [email protected](this.toString()) } } // // TRAVERSING // val CharSequence.children: Selector get() = custom(" ", false, false) val CharSequence.child: Selector get() = custom(">", false, false) val CharSequence.next: Selector get() = custom("+", false, false) val CharSequence.nextAll: Selector get() = custom("~", false, false) operator fun CharSequence.div(obj: CharSequence) = child.append(obj.toSelector()) operator fun CharSequence.mod(obj: CharSequence) = next.append(obj.toSelector()) operator fun CharSequence.minus(obj: CharSequence) = nextAll.append(obj.toSelector()) operator fun CharSequence.rangeTo(obj: CharSequence) = children.append(obj.toSelector()) // // ATTRIBUTES // /* TODO: Escape and add braces ? https://mathiasbynens.be/notes/css-escapes http://stackoverflow.com/questions/13987979/how-to-properly-escape-attribute-values-in-css-js-selector-attr-value https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape */ fun CharSequence.attr(attrName: Any, body: (Stylesheet.()->Unit)? = null): Selector { return when (this) { is ASelector -> custom("[$attrName]", false, true, body) else -> toSelector().attr(attrName, body) } } fun CharSequence.attr(attrName: Any, attrValue: Any, body: (Stylesheet.()->Unit)? = null): Selector { return when (this) { is ASelector -> custom("[$attrName=${escapeAttrValue(attrValue.toString())}]", false, true, body) else -> toSelector().attr(attrName, attrValue, body) } } fun CharSequence.attr(attrName: Any, attrValue: Any, attrFiler: AttrFilter, body: (Stylesheet.()->Unit)? = null): Selector { return when (this) { is ASelector -> custom("[$attrName$attrFiler=${escapeAttrValue(attrValue.toString())}]", false, true, body) else -> toSelector().attr(attrName, attrValue, attrFiler, body) } } operator fun CharSequence.get(attrName: Any, body: (Stylesheet.()->Unit)? = null) = attr(attrName, body) operator fun CharSequence.get(attrName: Any, attrValue: Any, body: (Stylesheet.()->Unit)? = null) = attr(attrName, attrValue, body) operator fun CharSequence.get(attrName: Any, attrFiler: AttrFilter, attrValue: Any, body: (Stylesheet.()->Unit)? = null) = attr(attrName, attrValue, attrFiler, body) private fun escapeAttrValue(str: String): String { // http://stackoverflow.com/questions/5578845/css-attribute-selectors-the-rules-on-quotes-or-none val isIdentifier = str.all { it >= '0' && it <= '9' || it >= 'a' && it <= 'z' || it >= 'A' && it <= 'Z' || it == '-' || it == '_' } return if (isIdentifier) str else "\"${str.replace("\"", "\\\"")}\"" } // // CLASSES AND IDs // fun CharSequence.c(selector: Any, body: (Stylesheet.()->Unit)? = null) = custom(".$selector", false, true, body) fun CharSequence.id(selector: Any, body: (Stylesheet.()->Unit)? = null) = custom("#$selector", false, true, body) // // TAGS // val CharSequence.any: Selector get() = custom("*") val CharSequence.a: Selector get() = custom("a") // Defines a hyperlink. val CharSequence.abbr: Selector get() = custom("abbr") // Defines an abbreviation or an acronym. val CharSequence.acronym: Selector get() = custom("acronym") // Defines an acronym. Not supported in HTML5. Use <abbr> instead. val CharSequence.address: Selector get() = custom("address") // Defines contact information for the author/owner of a document. val CharSequence.applet: Selector get() = custom("applet") // Defines an embedded applet. Not supported in HTML5. Use <embed> or <object> instead. val CharSequence.area: Selector get() = custom("area") // Defines an area inside an image-map. val CharSequence.article: Selector get() = custom("article") // Defines an article. val CharSequence.aside: Selector get() = custom("aside") // Defines content aside from the page content. val CharSequence.audio: Selector get() = custom("audio") // Defines sound content. val CharSequence.b: Selector get() = custom("b") // Defines bold text. val CharSequence.base: Selector get() = custom("base") // Specifies the base URL/target for all relative URLs in a document. val CharSequence.basefont: Selector get() = custom("basefont") // Specifies a default color, size, and font for all text in a document. Not supported in HTML5. Use CSS instead. val CharSequence.bdi: Selector get() = custom("bdi") // Isolates a part of text that might be formatted in a different direction from other text outside it. val CharSequence.bdo: Selector get() = custom("bdo") // Overrides the current text direction. val CharSequence.big: Selector get() = custom("big") // Defines big text. Not supported in HTML5. Use CSS instead. val CharSequence.blockquote: Selector get() = custom("blockquote") // Defines a section that is quoted from another source. val CharSequence.body: Selector get() = custom("body") // Defines the document's body. val CharSequence.br: Selector get() = custom("br") // Defines a single line break. val CharSequence.button: Selector get() = custom("button") // Defines a clickable button. val CharSequence.canvas: Selector get() = custom("canvas") // Used to draw graphics, on the fly, via scripting (usually JavaScript). val CharSequence.caption: Selector get() = custom("caption") // Defines a table caption. val CharSequence.center: Selector get() = custom("center") // Defines centered text. Not supported in HTML5. Use CSS instead. val CharSequence.cite: Selector get() = custom("cite") // Defines the title of a work. val CharSequence.code: Selector get() = custom("code") // Defines a piece of computer code. val CharSequence.col: Selector get() = custom("col") // Specifies column properties for each column within a <colgroup> element. val CharSequence.colgroup: Selector get() = custom("colgroup") // Specifies a group of one or more columns in a table for formatting. val CharSequence.datalist: Selector get() = custom("datalist") // Specifies a list of pre-defined options for input controls. val CharSequence.dd: Selector get() = custom("dd") // Defines a description/value of a term in a description list. val CharSequence.del: Selector get() = custom("del") // Defines text that has been deleted from a document. val CharSequence.details: Selector get() = custom("details") // Defines additional details that the user can view or hide. val CharSequence.dfn: Selector get() = custom("dfn") // Represents the defining instance of a term. val CharSequence.dialog: Selector get() = custom("dialog") // Defines a dialog box or window. val CharSequence.dir: Selector get() = custom("dir") // Defines a directory list. Not supported in HTML5. Use <ul> instead. val CharSequence.div: Selector get() = custom("div") // Defines a section in a document. val CharSequence.dl: Selector get() = custom("dl") // Defines a description list. val CharSequence.dt: Selector get() = custom("dt") // Defines a term/name in a description list. val CharSequence.em: Selector get() = custom("em") // Defines emphasized text. val CharSequence.embed: Selector get() = custom("embed") // Defines a container for an external (non-HTML) application. val CharSequence.fieldset: Selector get() = custom("fieldset") // Groups related elements in a form. val CharSequence.figcaption: Selector get() = custom("figcaption") // Defines a caption for a <figure> element. val CharSequence.figure: Selector get() = custom("figure") // Specifies self-contained content. val CharSequence.font: Selector get() = custom("font") // Defines font, color, and size for text. Not supported in HTML5. Use CSS instead. val CharSequence.footer: Selector get() = custom("footer") // Defines a footer for a document or section. val CharSequence.form: Selector get() = custom("form") // Defines an HTML form for user input. val CharSequence.frame: Selector get() = custom("frame") // Defines a window (a frame) in a frameset. Not supported in HTML5. val CharSequence.frameset: Selector get() = custom("frameset") // Defines a set of frames. Not supported in HTML5. val CharSequence.h1: Selector get() = custom("h1") // Defines HTML headings. val CharSequence.h2: Selector get() = custom("h2") // Defines HTML headings. val CharSequence.h3: Selector get() = custom("h3") // Defines HTML headings. val CharSequence.h4: Selector get() = custom("h4") // Defines HTML headings. val CharSequence.h5: Selector get() = custom("h5") // Defines HTML headings. val CharSequence.h6: Selector get() = custom("h6") // Defines HTML headings. val CharSequence.head: Selector get() = custom("head") // Defines information about the document. val CharSequence.header: Selector get() = custom("header") // Defines a header for a document or section. val CharSequence.hr: Selector get() = custom("hr") // Defines a thematic change in the content. val CharSequence.html: Selector get() = custom("html") // Defines the root of an HTML document. val CharSequence.i: Selector get() = custom("i") // Defines a part of text in an alternate voice or mood. val CharSequence.iframe: Selector get() = custom("iframe") // Defines an inline frame. val CharSequence.img: Selector get() = custom("img") // Defines an image. val CharSequence.input: Selector get() = custom("input") // Defines an input control. val CharSequence.ins: Selector get() = custom("ins") // Defines a text that has been inserted into a document. val CharSequence.kbd: Selector get() = custom("kbd") // Defines keyboard input. val CharSequence.keygen: Selector get() = custom("keygen") // Defines a key-pair generator field (for forms). val CharSequence.label: Selector get() = custom("label") // Defines a label for an <input> element. val CharSequence.legend: Selector get() = custom("legend") // Defines a caption for a <fieldset> element. val CharSequence.li: Selector get() = custom("li") // Defines a list item. val CharSequence.link: Selector get() = custom("link") // Defines the relationship between a document and an external resource (most used to link to style sheets). val CharSequence.main: Selector get() = custom("main") // Specifies the main content of a document. val CharSequence.map: Selector get() = custom("map") // Defines a client-side image-map. val CharSequence.mark: Selector get() = custom("mark") // Defines marked/highlighted text. val CharSequence.menu: Selector get() = custom("menu") // Defines a list/menu of commands. val CharSequence.menuitem: Selector get() = custom("menuitem") // Defines a command/menu item that the user can invoke from a popup menu. val CharSequence.meta: Selector get() = custom("meta") // Defines metadata about an HTML document. val CharSequence.meter: Selector get() = custom("meter") // Defines a scalar measurement within a known range (a gauge). val CharSequence.nav: Selector get() = custom("nav") // Defines navigation links. val CharSequence.noframes: Selector get() = custom("noframes") // Defines an alternate content for users that do not support frames. Not supported in HTML5. val CharSequence.noscript: Selector get() = custom("noscript") // Defines an alternate content for users that do not support client-side scripts. val CharSequence.`object`: Selector get() = custom("object") // Defines an embedded object. val CharSequence.ol: Selector get() = custom("ol") // Defines an ordered list. val CharSequence.optgroup: Selector get() = custom("optgroup") // Defines a group of related options in a drop-down list. val CharSequence.option: Selector get() = custom("option") // Defines an option in a drop-down list. val CharSequence.output: Selector get() = custom("output") // Defines the result of a calculation. val CharSequence.p: Selector get() = custom("p") // Defines a paragraph. val CharSequence.param: Selector get() = custom("param") // Defines a parameter for an object. val CharSequence.pre: Selector get() = custom("pre") // Defines preformatted text. val CharSequence.progress: Selector get() = custom("progress") // Represents the progress of a task. val CharSequence.q: Selector get() = custom("q") // Defines a short quotation. val CharSequence.rp: Selector get() = custom("rp") // Defines what to show in browsers that do not support ruby annotations. val CharSequence.rt: Selector get() = custom("rt") // Defines an explanation/pronunciation of characters (for East Asian typography). val CharSequence.ruby: Selector get() = custom("ruby") // Defines a ruby annotation (for East Asian typography). val CharSequence.s: Selector get() = custom("s") // Defines text that is no longer correct. val CharSequence.samp: Selector get() = custom("samp") // Defines sample output from a computer program. val CharSequence.script: Selector get() = custom("script") // Defines a client-side script. val CharSequence.section: Selector get() = custom("section") // Defines a section in a document. val CharSequence.select: Selector get() = custom("select") // Defines a drop-down list. val CharSequence.small: Selector get() = custom("small") // Defines smaller text. val CharSequence.source: Selector get() = custom("source") // Defines multiple media resources for media elements (<video> and <audio>). val CharSequence.span: Selector get() = custom("span") // Defines a section in a document. val CharSequence.strike: Selector get() = custom("strike") // Defines strikethrough text. Not supported in HTML5. Use <del> or <s> instead. val CharSequence.strong: Selector get() = custom("strong") // Defines important text. val CharSequence.style: Selector get() = custom("style") // Defines style information for a document. val CharSequence.sub: Selector get() = custom("sub") // Defines subscripted text. val CharSequence.summary: Selector get() = custom("summary") // Defines a visible heading for a <details> element. val CharSequence.sup: Selector get() = custom("sup") // Defines superscripted text. val CharSequence.table: Selector get() = custom("table") // Defines a table. val CharSequence.tbody: Selector get() = custom("tbody") // Groups the body content in a table. val CharSequence.td: Selector get() = custom("td") // Defines a cell in a table. val CharSequence.textarea: Selector get() = custom("textarea") // Defines a multiline input control (text area). val CharSequence.tfoot: Selector get() = custom("tfoot") // Groups the footer content in a table. val CharSequence.th: Selector get() = custom("th") // Defines a header cell in a table. val CharSequence.thead: Selector get() = custom("thead") // Groups the header content in a table. val CharSequence.time: Selector get() = custom("time") // Defines a date/time. val CharSequence.title: Selector get() = custom("title") // Defines a title for the document. val CharSequence.tr: Selector get() = custom("tr") // Defines a row in a table. val CharSequence.track: Selector get() = custom("track") // Defines text tracks for media elements (<video> and <audio>). val CharSequence.tt: Selector get() = custom("tt") // Defines teletype text. Not supported in HTML5. Use CSS instead. val CharSequence.u: Selector get() = custom("u") // Defines text that should be stylistically different from normal text. val CharSequence.ul: Selector get() = custom("ul") // Defines an unordered list. val CharSequence.`var`: Selector get() = custom("var") // Defines a variable. val CharSequence.video: Selector get() = custom("video") // Defines a video or movie. val CharSequence.wbr: Selector get() = custom("wbr") // Defines a possible line-break. // // PSEUDO CLASSES AND ELEMENTS // val CharSequence.active: Selector get() = pseudo(":active") // (CSS1) Selects the active link val CharSequence.after: Selector get() = pseudo(":after") // (CSS2) Insert something after the content of each <p> element val CharSequence.before: Selector get() = pseudo(":before") // (CSS2) Insert something before the content of each <p> element val CharSequence.checked: Selector get() = pseudo(":checked") // (CSS3) Selects every checked <input> element val CharSequence.disabled: Selector get() = pseudo(":disabled") // (CSS3) Selects every disabled <input> element val CharSequence.empty: Selector get() = pseudo(":empty") // (CSS3) Selects every <p> element that has no children (including text nodes) val CharSequence.enabled: Selector get() = pseudo(":enabled") // (CSS3) Selects every enabled <input> element val CharSequence.firstChild: Selector get() = pseudo(":first-child") // (CSS2) Selects every <p> element that is the first child of its parent val CharSequence.firstLetter: Selector get() = pseudo(":first-letter") // (CSS1) Selects the first letter of every <p> element val CharSequence.firstLine: Selector get() = pseudo(":first-line") // (CSS1) Selects the first line of every <p> element val CharSequence.firstOfType: Selector get() = pseudo(":first-of-type") // (CSS3) Selects every <p> element that is the first <p> element of its parent val CharSequence.focus: Selector get() = pseudo(":focus") // (CSS2) Selects the input element which has focus val CharSequence.hover: Selector get() = pseudo(":hover") // (CSS1) Selects links on mouse over val CharSequence.inRange: Selector get() = pseudo(":in-range") // (CSS3) Selects input elements with a value within a specified range val CharSequence.invalid: Selector get() = pseudo(":invalid") // (CSS3) Selects all input elements with an invalid value val CharSequence.lastChild: Selector get() = pseudo(":last-child") // (CSS3) Selects every <p> element that is the last child of its parent val CharSequence.lastOfType: Selector get() = pseudo(":last-of-type") // (CSS3) Selects every <p> element that is the last <p> element of its parent val CharSequence.onlyChild: Selector get() = pseudo(":only-child") // (CSS3) Selects every <p> element that is the only child of its parent val CharSequence.onlyOfType: Selector get() = pseudo(":only-of-type") // (CSS3) Selects every <p> element that is the only <p> element of its parent val CharSequence.optional: Selector get() = pseudo(":optional") // (CSS3) Selects input elements with no "required" attribute val CharSequence.outOfRange: Selector get() = pseudo(":out-of-range") // (CSS3) Selects input elements with a value outside a specified range val CharSequence.readOnly: Selector get() = pseudo(":read-only") // (CSS3) Selects input elements with the "readonly" attribute specified val CharSequence.readWrite: Selector get() = pseudo(":read-write") // (CSS3) Selects input elements with the "readonly" attribute NOT specified val CharSequence.required: Selector get() = pseudo(":required") // (CSS3) Selects input elements with the "required" attribute specified val CharSequence.root: Selector get() = pseudo(":root") // (CSS3) Selects the document's root element val CharSequence.selection: Selector get() = pseudo(":selection") // (Was drafted for CSS3, but removed before the Recommendation status) Selects the portion of an element that is selected by a user val CharSequence.target: Selector get() = pseudo(":target") // (CSS3) Selects the current active #news element (clicked on a URL containing that anchor name) val CharSequence.unvisited: Selector get() = pseudo(":link") // (CSS1) Selects all unvisited links val CharSequence.valid: Selector get() = pseudo(":valid") // (CSS3) Selects all input elements with a valid value val CharSequence.visited: Selector get() = pseudo(":visited") // (CSS1) Selects all visited links fun CharSequence.lang(language: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":lang($language)", body) // (CSS2) Selects every <p> element with a lang attribute equal to "it" (Italian) fun CharSequence.not(selector: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":not($selector)", body) // (CSS3) Selects every element that is not a <p> element fun CharSequence.nthChild(n: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":nth-child($n)", body) // (CSS3) Selects every <p> element that is the second child of its parent fun CharSequence.nthLastChild(n: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":nth-last-child($n)", body) // (CSS3) Selects every <p> element that is the second child of its parent, counting from the last child fun CharSequence.nthLastOfType(n: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":nth-last-of-type($n)", body) // (CSS3) Selects every <p> element that is the second <p> element of its parent, counting from the last child fun CharSequence.nthOfType(n: Any, body: (Stylesheet.()->Unit)? = null) = pseudoFn(":nth-of-type($n)", body) // (CSS3) Selects every <p> element that is the second <p> element of its parent }
main/azagroup/kotlin/css/Stylesheet.kt
3203943684
@file:JvmName("RxSwipeDismissBehavior") @file:JvmMultifileClass package com.jakewharton.rxbinding4.material import android.view.View import androidx.annotation.CheckResult import androidx.coordinatorlayout.widget.CoordinatorLayout.LayoutParams import com.google.android.material.behavior.SwipeDismissBehavior import com.google.android.material.behavior.SwipeDismissBehavior.OnDismissListener import com.jakewharton.rxbinding4.internal.checkMainThread import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Observer import io.reactivex.rxjava3.android.MainThreadDisposable /** * Create an observable which emits the dismiss events from `view` on * [SwipeDismissBehavior]. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ @CheckResult fun View.dismisses(): Observable<View> { return SwipeDismissBehaviorObservable(this) } private class SwipeDismissBehaviorObservable( private val view: View ) : Observable<View>() { override fun subscribeActual(observer: Observer<in View>) { if (!checkMainThread(observer)) { return } val params = view.layoutParams as? LayoutParams ?: throw IllegalArgumentException("The view is not in a Coordinator Layout.") val behavior = params.behavior as SwipeDismissBehavior<*>? ?: throw IllegalStateException("There's no behavior set on this view.") val listener = Listener(behavior, observer) observer.onSubscribe(listener) behavior.setListener(listener) } private class Listener( private val swipeDismissBehavior: SwipeDismissBehavior<*>, private val observer: Observer<in View> ) : MainThreadDisposable(), OnDismissListener { override fun onDismiss(view: View) { if (!isDisposed) { observer.onNext(view) } } override fun onDragStateChanged(state: Int) {} override fun onDispose() { swipeDismissBehavior.setListener(null) } } }
rxbinding-material/src/main/java/com/jakewharton/rxbinding4/material/SwipeDismissBehaviorObservable.kt
496668543
package com.sleazyweasel.eboshi import org.eclipse.jetty.http.HttpStatus import org.jose4j.jwt.consumer.InvalidJwtException import spark.Request import spark.Response import javax.inject.Inject class AccountRoutes @Inject constructor(accountDataAccess: AccountDataAccess, auth: Auth) { val create = { input: JsonApiRequest, response: Response -> val submittedUserAttributes = input.data.attributes val user = Account(submittedUserAttributes) val (hashed, salt) = auth.encrypt(user.password!!) val userReadyToSave = Account(submittedUserAttributes .plus(listOf("crypted_password" to hashed, "password_salt" to salt)) .minus("password")) val savedUser = accountDataAccess.insert(userReadyToSave) response.status(HttpStatus.CREATED_201) mapOf("data" to Account(savedUser.data.minus(listOf("crypted_password", "password_salt"))).toJsonApiObject()) } val auth = { input: JsonApiRequest, response: Response -> val authData = AuthData(input.data.attributes) val account = accountDataAccess.getByEmail(authData.email!!) if (auth.verify(authData.password, account.crypted_password)) { val token = auth.generateToken(account) mapOf("data" to AuthData(mapOf("email" to authData.email, "token" to token)).toJsonApiObject()) } else { response.status(HttpStatus.UNAUTHORIZED_401) mapOf("errors" to listOf(JsonApiError("Invalid authentication credentials"))) } } val get = { request: Request, response: Response -> val authHeader = request.headers("Authorization") val token = authHeader.substringAfter("Bearer ") val email: String try { email = auth.validateToken(token) val account = accountDataAccess.getByEmail(email) mapOf("data" to account.toJsonApiObject()) } catch(e: InvalidJwtException) { response.status(HttpStatus.UNAUTHORIZED_401) mapOf("errors" to listOf(JsonApiError("Invalid authentication token"))) } } }
kotlin_spark/src/main/java/com/sleazyweasel/eboshi/AccountRoutes.kt
2235084650
package net.perfectdreams.loritta.morenitta.website.routes.api.v1.twitch import com.github.salomonbrys.kotson.jsonObject import net.perfectdreams.loritta.morenitta.website.utils.WebsiteUtils import net.perfectdreams.loritta.morenitta.utils.gson import net.perfectdreams.loritta.morenitta.website.LoriWebCode import net.perfectdreams.loritta.morenitta.website.WebsiteAPIException import io.ktor.server.application.ApplicationCall import io.ktor.http.HttpStatusCode import mu.KotlinLogging import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.sequins.ktor.BaseRoute import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson class GetTwitchInfoRoute(val loritta: LorittaBot) : BaseRoute("/api/v1/twitch/channel") { companion object { private val logger = KotlinLogging.logger {} } override suspend fun onRequest(call: ApplicationCall) { val id = call.parameters["id"]?.toLongOrNull() val login = call.parameters["login"] if (id != null) { val payload = loritta.twitch.getUserLoginById(id) ?: throw WebsiteAPIException( HttpStatusCode.NotFound, WebsiteUtils.createErrorPayload( loritta, LoriWebCode.ITEM_NOT_FOUND, "Streamer not found" ) ) call.respondJson(gson.toJsonTree(payload)) } else if (login != null) { val payload = loritta.twitch.getUserLogin(login) ?: throw WebsiteAPIException( HttpStatusCode.NotFound, WebsiteUtils.createErrorPayload( loritta, LoriWebCode.ITEM_NOT_FOUND, "Streamer not found" ) ) call.respondJson(gson.toJsonTree(payload)) } else { call.respondJson(jsonObject(), HttpStatusCode.NotImplemented) } } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/twitch/GetTwitchInfoRoute.kt
41840602
import java.util.* class FastDoublingFibo { private val hm = HashMap<Integer, Integer>() private fun fib(n: Int): Int { if (n <= 2) return 1 var ans = 0 if (hm.get(n) != null) { ans = hm.get(n) return ans } val half = n / 2 val a = fib(half + 1) val b = fib(half) if (n % 2 == 1) ans = a * a + b * b else ans = 2 * a * b - b * b hm.put(n, ans) return ans } fun main(args: Array<String>) { val sc = Scanner(System.`in`) System.out.print("Enter n(0 to exit): ") var n = sc.nextInt() while (n != 0) { val ans = fib(n) System.out.println(ans) System.out.print("Enter n(0 to exit): ") n = sc.nextInt() } } }
Kotlin/FastDoublingFibo.kt
2278866551
package net.perfectdreams.loritta.cinnamon.discord.interactions.components import dev.kord.common.entity.ComponentType import dev.kord.common.entity.DiscordChatComponent import dev.kord.common.entity.DiscordPartialEmoji import dev.kord.common.entity.Snowflake import dev.kord.common.entity.optional.optional import dev.kord.common.entity.optional.value import dev.kord.core.entity.User import net.perfectdreams.discordinteraktions.common.builder.message.actionRow import net.perfectdreams.discordinteraktions.common.builder.message.create.InteractionOrFollowupMessageCreateBuilder import net.perfectdreams.discordinteraktions.common.builder.message.modify.InteractionOrFollowupMessageModifyBuilder import net.perfectdreams.discordinteraktions.common.components.ComponentContext import net.perfectdreams.discordinteraktions.common.requests.InteractionRequestState import net.perfectdreams.discordinteraktions.platforms.kord.utils.runIfNotMissing import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.i18n.I18nKeysData import net.perfectdreams.loritta.cinnamon.discord.interactions.InteractionContext import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.mentionUser import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled import net.perfectdreams.loritta.cinnamon.discord.interactions.components.data.SingleUserComponentData import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentDataUtils import net.perfectdreams.loritta.cinnamon.discord.utils.LoadingEmojis import net.perfectdreams.loritta.common.emotes.DiscordEmote import net.perfectdreams.loritta.common.locale.BaseLocale open class ComponentContext( loritta: LorittaBot, i18nContext: I18nContext, locale: BaseLocale, user: User, override val interaKTionsContext: ComponentContext ) : InteractionContext(loritta, i18nContext, locale, user, interaKTionsContext) { val data: String get() = interaKTionsContext.data val dataOrNull: String? get() = interaKTionsContext.dataOrNull suspend fun deferUpdateMessage() = interaKTionsContext.deferUpdateMessage() suspend inline fun updateMessage(block: InteractionOrFollowupMessageModifyBuilder.() -> (Unit)) = interaKTionsContext.updateMessage(block) /** * Checks if the [user] has the same user ID present in the [data]. * * If it isn't equal, the context will run [block] * * @see SingleUserComponentData * @see failEphemerally */ fun requireUserToMatch(data: SingleUserComponentData, block: () -> (Unit)) { if (data.userId != user.id) block.invoke() } /** * Checks if the [user] has the same user ID present in the [data]. * * If it isn't equal, the context will [fail] or [failEphemerally], depending if the command was deferred ephemerally or not. * * If the command still haven't been replied or deferred, the command will default to a ephemeral fail. * * @see SingleUserComponentData * @see requireUserToMatch */ fun requireUserToMatchOrContextuallyFail(data: SingleUserComponentData) = requireUserToMatch(data) { val b: InteractionOrFollowupMessageCreateBuilder.() -> Unit = { styled( i18nContext.get( I18nKeysData.Commands.YouArentTheUserSingleUser( mentionUser(data.userId, false) ) ), Emotes.LoriRage ) } // We also check for "Deferred Update Message" because we can actually reply with an ephemeral message even if it was marked as a update message if (interaKTionsContext.wasInitiallyDeferredEphemerally || interaKTionsContext.bridge.state.value == InteractionRequestState.NOT_REPLIED_YET || interaKTionsContext.bridge.state.value == InteractionRequestState.DEFERRED_UPDATE_MESSAGE) failEphemerally(b) else fail(b) } /** * Checks if the [user] has the same user ID present in the [data]. * * If it isn't equal, the context will [failEphemerally], halting execution. * * @see SingleUserComponentData * @see failEphemerally */ fun requireUserToMatchOrFail(data: SingleUserComponentData) = requireUserToMatch(data) { fail { styled( i18nContext.get( I18nKeysData.Commands.YouArentTheUserSingleUser( mentionUser(data.userId, false) ) ), Emotes.LoriRage ) } } /** * Checks if the [user] has the same user ID present in the [data]. * * If it isn't equal, the context will [failEphemerally], halting execution. * * @see SingleUserComponentData * @see failEphemerally */ fun requireUserToMatchOrFailEphemerally(data: SingleUserComponentData) = requireUserToMatch(data) { failEphemerally { styled( i18nContext.get( I18nKeysData.Commands.YouArentTheUserSingleUser( mentionUser(data.userId, false) ) ), Emotes.LoriRage ) } } /** * Decodes the [data] to [T]. * * @see ComponentDataUtils * @see failEphemerally * @see requireUserToMatchOrFailEphemerally */ inline fun <reified T> decodeDataFromComponent(): T { return ComponentDataUtils.decode<T>(data) } /** * Decodes the [data] and checks if the [user] has the same user ID present in the [data]. * * If it isn't equal, the context will [fail] or [failEphemerally], depending on the current request state, halting execution. * * @see SingleUserComponentData * @see ComponentDataUtils * @see failEphemerally * @see requireUserToMatchOrFailEphemerally */ inline fun <reified T : SingleUserComponentData> decodeDataFromComponentAndRequireUserToMatch(): T { val data = ComponentDataUtils.decode<T>(data) requireUserToMatchOrContextuallyFail(data) return data } /** * Decodes the [data] or pulls it from the database if needed and checks if the [user] has the same user ID present in the [data]. * * If the data is not present on the database, null will be returned. * * If it isn't equal, the context will [fail] or [failEphemerally], depending on the current request state, halting execution. * * @see SingleUserComponentData * @see ComponentDataUtils * @see failEphemerally * @see requireUserToMatchOrFailEphemerally * @see decodeDataFromComponentAndRequireUserToMatch */ suspend inline fun <reified T : SingleUserComponentData> decodeDataFromComponentOrFromDatabaseIfPresentAndRequireUserToMatch(): T? { val data = loritta.decodeDataFromComponentOrFromDatabase<T>(data) ?: return null requireUserToMatchOrContextuallyFail(data) return data } /** * Decodes the [data] or pulls it from the database if needed. * * If the data is not present on the database, the context will [fail] or [failEphemerally] with the [block] message, depending on the current request state, halting execution. * * @see SingleUserComponentData * @see ComponentDataUtils * @see failEphemerally */ suspend inline fun <reified T> decodeDataFromComponentOrFromDatabase( block: InteractionOrFollowupMessageCreateBuilder.() -> (Unit) = { styled( i18nContext.get(I18nKeysData.Commands.InteractionDataIsMissingFromDatabaseGeneric), Emotes.LoriSleeping ) } ): T { return loritta.decodeDataFromComponentOrFromDatabase<T>(data) ?: if (interaKTionsContext.wasInitiallyDeferredEphemerally || interaKTionsContext.bridge.state.value == InteractionRequestState.NOT_REPLIED_YET) failEphemerally(block) else fail(block) } /** * Updates the current message to disable all components in the message that the component is attached to, and sets the message content * to "Loading...". * * On the component that the user clicked, the text in it will be replaced with "Loading..." * * **This should not be used if you are planning to send a follow-up message, only for when you are going to update the message where the component is attached to!** * * **This should not be used for components that can be used by multiple users!** (If it doesn't use [SingleUserComponentData], then you shouldn't use this!) * * **This should only be used after you validated that the user can use the component!** (Example: After checking with [decodeDataFromComponentAndRequireUserToMatch]) */ suspend fun updateMessageSetLoadingState( updateMessageContent: Boolean = true, disableComponents: Boolean = true, loadingEmoji: DiscordEmote = LoadingEmojis.random() ) { updateMessage { if (updateMessageContent) styled( i18nContext.get(I18nKeysData.Website.Dashboard.Loading), loadingEmoji ) if (disableComponents) disableComponents(loadingEmoji, this) } } /** * Disables all components in the message that the component is attached to on the [builder]. * * On the component that the user clicked, the text in it will be replaced with "Loading..." */ fun disableComponents(loadingEmoji: DiscordEmote, builder: InteractionOrFollowupMessageModifyBuilder) { // The message property isn't null in a component interaction interaKTionsContext.discordInteraction.message.value!!.components.value!!.forEach { it as DiscordChatComponent // Here only a DiscordChatComponent can exist if (it.type == ComponentType.ActionRow) { builder.actionRow { it.components.value!!.forEach { it as DiscordChatComponent // Again, only a DiscordChatComponent can exist here when (it.type) { ComponentType.ActionRow -> error("This shouldn't exist here!") ComponentType.Button -> { interactionButton( it.style.value!!, // The style shouldn't be null if it is a button generateDisabledComponentId() ) { disabled = true label = it.label.value // We want to get the *raw* custom ID, not the one that was already processed by Discord InteraKTions if (interaKTionsContext.discordInteraction.data.customId.value == it.customId.value) emoji = DiscordPartialEmoji( Snowflake(loadingEmoji.id), loadingEmoji.name, animated = loadingEmoji.animated.optional() ) else emoji = it.emoji.value } } ComponentType.SelectMenu -> { selectMenu(generateDisabledComponentId()) { val minValues = it.minValues.value ?: 1 val maxValues = it.maxValues.value ?: 1 this.disabled = true runIfNotMissing(it.placeholder) { this.placeholder = it } runIfNotMissing(it.options) { optionList -> if (optionList != null) { if (minValues == 1 && maxValues == 1) { // We will use our own custom "Loading" option, sweet! option(i18nContext.get(I18nKeysData.Website.Dashboard.Loading), "loading_psst_hey_u_are_cute_uwu") { // heh easter egg this.emoji = DiscordPartialEmoji( Snowflake(loadingEmoji.id), loadingEmoji.name, animated = loadingEmoji.animated.optional() ) this.default = true } } else { // If not, we will insert the current options as is, to avoiding shifting the content around optionList.forEach { option(it.label, it.value) { runIfNotMissing(it.description) { this.description = it } runIfNotMissing(it.emoji) { this.emoji = it } // We need to get the current values list from the interaction itself, to avoid the user changing the select menu value, then when Loritta updates the message // the selection is *gone* this.default = it.value in (interaKTionsContext.discordInteraction.data.values.value ?: emptyList()) } } } } } this.allowedValues = minValues..maxValues } } ComponentType.TextInput -> error("This shouldn't exist here!") is ComponentType.Unknown -> error("This shouldn't exist here!") } } } } } } /** * Disables all components in the message that the component is attached to on the [builder]. */ fun disableComponents(builder: InteractionOrFollowupMessageModifyBuilder) { // The message property isn't null in a component interaction interaKTionsContext.discordInteraction.message.value!!.components.value!!.forEach { it as DiscordChatComponent // Here only a DiscordChatComponent can exist if (it.type == ComponentType.ActionRow) { builder.actionRow { it.components.value!!.forEach { it as DiscordChatComponent // Again, only a DiscordChatComponent can exist here when (it.type) { ComponentType.ActionRow -> error("This shouldn't exist here!") ComponentType.Button -> { interactionButton( it.style.value!!, // The style shouldn't be null if it is a button generateDisabledComponentId() ) { disabled = true label = it.label.value emoji = it.emoji.value } } ComponentType.SelectMenu -> { selectMenu(generateDisabledComponentId()) { val minValues = it.minValues.value ?: 1 val maxValues = it.maxValues.value ?: 1 this.disabled = true runIfNotMissing(it.placeholder) { this.placeholder = it } runIfNotMissing(it.options) { optionList -> optionList?.forEach { option(it.label, it.value) { runIfNotMissing(it.description) { this.description = it } runIfNotMissing(it.emoji) { this.emoji = it } // We need to get the current values list from the interaction itself, to avoid the user changing the select menu value, then when Loritta updates the message // the selection is *gone* this.default = it.value in (interaKTionsContext.discordInteraction.data.values.value ?: emptyList()) } } } this.allowedValues = minValues..maxValues } } ComponentType.TextInput -> error("This shouldn't exist here!") is ComponentType.Unknown -> error("This shouldn't exist here!") } } } } } } /** * Decodes the [data] or pulls it from the database if needed and checks if the [user] has the same user ID present in the [data]. * * If the data is not present on the database, the context will [fail] or [failEphemerally] with the [block] message, depending on the current request state, halting execution. * * If it isn't equal, the context will [fail] or [failEphemerally], depending on the current request state, halting execution. * * @see SingleUserComponentData * @see ComponentDataUtils * @see failEphemerally * @see requireUserToMatchOrFailEphemerally * @see decodeDataFromComponentAndRequireUserToMatch */ suspend inline fun <reified T : SingleUserComponentData> decodeDataFromComponentOrFromDatabaseAndRequireUserToMatch( block: InteractionOrFollowupMessageCreateBuilder.() -> (Unit) = { styled( i18nContext.get(I18nKeysData.Commands.InteractionDataIsMissingFromDatabaseGeneric), Emotes.LoriSleeping ) } ): T { return decodeDataFromComponentOrFromDatabaseIfPresentAndRequireUserToMatch() ?: if (interaKTionsContext.wasInitiallyDeferredEphemerally || interaKTionsContext.bridge.state.value == InteractionRequestState.NOT_REPLIED_YET) failEphemerally(block) else fail(block) } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/components/ComponentContext.kt
783162636
package de.maibornwolff.codecharta.importer.sonar import de.maibornwolff.codecharta.importer.sonar.model.Component import de.maibornwolff.codecharta.importer.sonar.model.Qualifier import org.hamcrest.CoreMatchers.`is` import org.junit.Assert.assertThat import org.junit.Test import java.net.URL class SonarCodeURLLinkerTest { @Test @Throws(Exception::class) fun should_createUrlString() { // given val baseUrl = URL("https://sonarcloud.io") val component = Component( "", "com.adobe%3Aas3corelib%3Asrc%2Fcom%2Fadobe%2Fair%2Fcrypto%2FEncryptionKeyGenerator.as", "", "", Qualifier.FIL ) // when val urlString = SonarCodeURLLinker(baseUrl).createUrlString(component) // then assertThat( urlString, `is`("https://sonarcloud.io/code?id=com.adobe%3Aas3corelib%3Asrc%2Fcom%2Fadobe%2Fair%2Fcrypto%2FEncryptionKeyGenerator.as") ) } }
analysis/import/SonarImporter/src/test/kotlin/de/maibornwolff/codecharta/importer/sonar/SonarCodeURLLinkerTest.kt
462337642
package net.perfectdreams.loritta.morenitta.utils data class ClusterOfflineException(val id: Int, val name: String) : RuntimeException("Cluster $id ($name) is offline")
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/ClusterOfflineException.kt
3533825392
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.gradle.extension.tasks import com.fasterxml.jackson.module.kotlin.readValue import com.netflix.spinnaker.gradle.extension.PluginObjectMapper import com.netflix.spinnaker.gradle.extension.Plugins import com.netflix.spinnaker.gradle.extension.Plugins.CHECKSUM_BUNDLE_TASK_NAME import com.netflix.spinnaker.gradle.extension.compatibility.CompatibilityTestResult import com.netflix.spinnaker.gradle.extension.compatibility.CompatibilityTestTask import com.netflix.spinnaker.gradle.extension.extensions.SpinnakerBundleExtension import com.netflix.spinnaker.gradle.extension.extensions.SpinnakerPluginExtension import com.netflix.spinnaker.gradle.extension.getParent import groovy.json.JsonOutput import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import java.io.File import java.lang.IllegalStateException import java.time.Instant /** * TODO(rz): Need to expose release state to the world. */ open class CreatePluginInfoTask : DefaultTask() { @Internal override fun getGroup(): String = Plugins.GROUP @Internal val rootProjectVersion: String = project.version.toString() @TaskAction fun doAction() { val allPluginExts = project .subprojects .mapNotNull { it.extensions.findByType(SpinnakerPluginExtension::class.java) } .toMutableList() val bundleExt = project.extensions.findByType(SpinnakerBundleExtension::class.java) ?: throw IllegalStateException("A 'spinnakerBundle' configuration block is required") val requires = allPluginExts.map { it.requires ?: "${it.serviceName}>=0.0.0" } .let { if (Plugins.hasDeckPlugin(project)) { it + "deck>=0.0.0" } else { it } } .joinToString(",") val compatibility = project .subprojects .flatMap { it.tasks.withType(CompatibilityTestTask::class.java) } .map { it.result.get().asFile } .filter { it.exists() } .map { PluginObjectMapper.mapper.readValue<CompatibilityTestResult>(it.readBytes()) } val pluginInfo = mapOf( "id" to bundleExt.pluginId, "description" to bundleExt.description, "provider" to bundleExt.provider, "releases" to listOf( mapOf( "version" to if (isVersionSpecified(bundleExt.version)) bundleExt.version else rootProjectVersion, "date" to Instant.now().toString(), "requires" to requires, "sha512sum" to getChecksum(), "preferred" to false, "compatibility" to compatibility ) ) ) // TODO(rz): Is it bad to put the plugin-info into the distributions build dir? File(project.buildDir, "distributions/plugin-info.json").writeText( JsonOutput.prettyPrint(JsonOutput.toJson(pluginInfo)) ) } private fun isVersionSpecified(version: String): Boolean { return version.isNotBlank() && version != Project.DEFAULT_VERSION } private fun getChecksum(): String { return project.tasks .getByName(CHECKSUM_BUNDLE_TASK_NAME) .outputs .files .files .first() .listFiles() .first() .readText() } }
spinnaker-extensions/src/main/kotlin/com/netflix/spinnaker/gradle/extension/tasks/CreatePluginInfoTask.kt
2354336141
package com.oukingtim.web import com.baomidou.mybatisplus.mapper.EntityWrapper import com.oukingtim.domain.TbTodo import com.oukingtim.service.TbTodoService import com.oukingtim.util.ShiroUtils import com.oukingtim.web.vm.ResultVM import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController /** * Created by oukingtim */ @RestController @RequestMapping("/sys/todo") class TbTodoController : BaseController<TbTodoService, TbTodo>(){ @GetMapping("/getlist") fun getList(): ResultVM { val tbTodo = TbTodo() tbTodo.createUserId=ShiroUtils.getUserId() val list = service!!.selectList(EntityWrapper(tbTodo)) return ResultVM.ok(list) } }
king-admin-kotlin/src/main/kotlin/com/oukingtim/web/TbTodoController.kt
567123436
package com.lasthopesoftware.bluewater.client.playback.engine.GivenAHaltedPlaylistEngine.AndAPlaylistIsPreparing import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryStorage import com.lasthopesoftware.bluewater.client.browsing.library.access.ISpecificLibraryProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine.Companion.createEngine import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement import com.lasthopesoftware.bluewater.client.playback.file.PositionedFile import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import com.namehillsoftware.handoff.promises.Promise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.joda.time.Duration import org.junit.BeforeClass import org.junit.Test class WhenATrackIsSwitched { companion object { private var nextSwitchedFile: PositionedFile? = null @BeforeClass @JvmStatic fun before() { val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider() val library = Library() library.setId(1) val libraryProvider = mockk<ISpecificLibraryProvider>() every { libraryProvider.library } returns (Promise(library)) val libraryStorage = mockk<ILibraryStorage>() every { libraryStorage.saveLibrary(any()) } returns Promise(library) val playbackEngine = FuturePromise( createEngine( PreparedPlaybackQueueResourceManagement( fakePlaybackPreparerProvider ) { 1 }, listOf(CompletingFileQueueProvider()), NowPlayingRepository(libraryProvider, libraryStorage), PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f)) ) ).get() playbackEngine?.startPlaylist( mutableListOf( ServiceFile(1), ServiceFile(2), ServiceFile(3), ServiceFile(4), ServiceFile(5) ), 0, Duration.ZERO ) val futurePositionedFile = FuturePromise( playbackEngine!!.changePosition(3, Duration.ZERO) ) fakePlaybackPreparerProvider.deferredResolution.resolve() nextSwitchedFile = futurePositionedFile.get() } } @Test fun thenTheNextFileChangeIsTheSwitchedToTheCorrectTrackPosition() { assertThat(nextSwitchedFile!!.playlistPosition).isEqualTo(3) } }
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAHaltedPlaylistEngine/AndAPlaylistIsPreparing/WhenATrackIsSwitched.kt
807992324
// Copyright Kevin D.Hall 2018 package com.khallware.api.util import java.math.BigDecimal data class Tag(val id: Int, val name: String, val user: Int = 1, val group: Int = 2) { } data class Bookmark(val id: Int, val name: String, val url: String, val rating: String = "good", val numtags: Int = -1, val user: Int = 1, val group: Int = 2) { } data class Location(val id: Int, val name: String, val lat: BigDecimal, val lon: BigDecimal, val address: String, val desc: String, val numtags: Int) { } data class Contact(val id: Int, val name: String, val uid: String, val email: String, val phone: String, val title: String, val address: String, val organization: String, val vcard: String, val desc: String, val numtags: Int) { } data class Event(val id: Int, val name: String, val uid: String, val duration: Int, val start: Int, val end: Int, val ics: String, val desc: String, val numtags: Int) { } data class Photo(val id: Int, val name: String, val path: String, val md5sum: String, val desc: String, val numtags: Int = -1, val user: Int = 1, val group: Int = 2) { } data class FileItem(val id: Int, val name: String, val ext: String, val md5sum: String, val desc: String, val mime: String, val path: String, val numtags: Int, val user: Int = 1, val group: Int = 2) { } data class Sound(val id: Int, val name: String, val path: String, val md5sum: String, val desc: String, val title: String, val artist: String, val genre: String, val album: String, val publisher: String, val numtags: Int, val user: Int = 1, val group: Int = 2) { } data class Video(val id: Int, val name: String, val path: String, val md5sum: String, val desc: String, val numtags: Int, val user: Int = 1, val group: Int = 2) { }
tools/src/main/kotlin/com/khallware/api/util/domain.kt
2810356366
package glass.phil.auto.moshi fun String.removeAll(char: Char) = filterNot { it == char }
processor/src/main/kotlin/glass/phil/auto/moshi/Strings.kt
594265509
package me.ycdev.android.devtools.root.cmd import android.content.Context import me.ycdev.android.devtools.root.RootCommandBuilder import timber.log.Timber class AppsKillerCmd(cxt: Context, private val pkgList: List<String>) : RootCmdBase(cxt) { override fun run() { if (pkgList.isEmpty()) { Timber.tag(TAG).w("no apps to kill") return } val cmds = RootCommandBuilder.forceStopPackage(context, pkgList) RootCmdBase.Companion.runSuCommand(cmds, "u:r:system_app:s0") } companion object { private const val TAG = "AppsKillerCmd" } }
app/src/main/java/me/ycdev/android/devtools/root/cmd/AppsKillerCmd.kt
1893452742
/* * Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * Copyright (C) 2014-2015 Ericsson * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.lttng.kernel.trace.layout /** * Interface to define "concepts" present in the Linux kernel (represented by * its tracepoints), that can then be exposed by different tracers under * different names. */ interface LttngKernelEventLayout { // ------------------------------------------------------------------------ // Common definitions // ------------------------------------------------------------------------ companion object { /** * Whenever a process appears for the first time in a trace, we assume it * starts inside this system call. (The syscall prefix is defined by the * implementer of this interface.) */ const val INITIAL_SYSCALL_NAME = "clone" } // ------------------------------------------------------------------------ // Event names // ------------------------------------------------------------------------ val eventIrqHandlerEntry: String val eventIrqHandlerExit: String val eventSoftIrqEntry: String val eventSoftIrqExit: String val eventSoftIrqRaise: String val eventSchedSwitch: String val eventSchedPiSetPrio: String val eventsSchedWakeup: Collection<String> val eventSchedProcessFork: String val eventSchedProcessExit: String val eventSchedProcessFree: String /** Optional event used by some tracers to deliver an initial state. */ val eventStatedumpProcessState: String? /** System call entry prefix, something like "sys_open" or just "sys". */ val eventSyscallEntryPrefix: String /** System call compatibility layer entry prefix, something like "compat_sys". */ val eventCompatSyscallEntryPrefix: String /** System call exit prefix, something like "sys_exit". */ val eventSyscallExitPrefix: String /** System call compatibility layer exit prefix, something like "compat_syscall_exit". */ val eventCompatSyscallExitPrefix: String val eventSchedProcessExec: String val eventSchedProcessWakeup: String val eventSchedProcessWakeupNew: String val eventSchedProcessWaking: String val eventSchedMigrateTask: String val eventHRTimerStart: String val eventHRTimerCancel: String val eventHRTimerExpireEntry: String val eventHRTimerExpireExit: String val eventKmemPageAlloc: String val eventKmemPageFree: String val ipiIrqVectorsEntries: Collection<String> val ipiIrqVectorsExits: Collection<String> // ------------------------------------------------------------------------ // Event field names // ------------------------------------------------------------------------ val fieldIrq: String val fieldVec: String val fieldTid: String val fieldPrevTid: String val fieldPrevState: String val fieldNextComm: String val fieldNextTid: String val fieldChildComm: String val fieldParentTid: String val fieldChildTid: String val fieldComm: String val fieldName: String val fieldStatus: String val fieldPrevComm: String val fieldFilename: String val fieldPrio: String val fieldNewPrio: String val fieldPrevPrio: String val fieldNextPrio: String val fieldHRtimer: String val fieldHRtimerExpires: String val fieldHRtimerSoftexpires: String val fieldHRtimerFunction: String val fieldHRtimerNow: String val fieldSyscallRet: String val fieldTargetCpu: String val fieldDestCpu: String // ------------------------------------------------------------------------ // I/O events and fields // ------------------------------------------------------------------------ val eventBlockRqInsert: String val eventBlockRqIssue: String val eventBlockRqComplete: String val eventBlockBioFrontmerge: String val eventBlockBioBackmerge: String val eventBlockRqMerge: String val eventStatedumpBlockDevice: String? val fieldBlockDeviceId: String val fieldBlockSector: String val fieldBlockNrSector: String val fieldBlockRwbs: String val fieldBlockRqSector: String val fieldBlockNextRqSector: String val fieldDiskname: String val fieldIPIVector: String val fieldOrder: String? // ------------------------------------------------------------------------ // Network events and fields // ------------------------------------------------------------------------ val eventsNetworkSend: Collection<String> val eventsNetworkReceive: Collection<String> val fieldPathTcpSeq: Collection<String> val fieldPathTcpAckSeq: Collection<String> val fieldPathTcpFlags: Collection<String> // ------------------------------------------------------------------------ // VirtualMachine events : kvm entry/exit events // ------------------------------------------------------------------------ val eventsKVMEntry: Collection<String> val eventsKVMExit: Collection<String> }
jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/trace/layout/LttngKernelEventLayout.kt
3484371078
/* * Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * Copyright (C) 2015 Ericsson * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.lttng.kernel.analysis.os.handlers import ca.polymtl.dorsal.libdelorean.IStateSystemWriter import com.efficios.jabberwocky.lttng.kernel.analysis.os.StateValues import com.efficios.jabberwocky.lttng.kernel.trace.layout.LttngKernelEventLayout import com.efficios.jabberwocky.trace.event.FieldValue.IntegerValue import com.efficios.jabberwocky.trace.event.TraceEvent class SoftIrqEntryHandler(layout: LttngKernelEventLayout) : KernelEventHandler(layout) { override fun handleEvent(ss: IStateSystemWriter, event: TraceEvent) { val cpu = event.cpu val timestamp = event.timestamp val softIrqId = (event.fields[layout.fieldVec] as IntegerValue).value.toInt() val cpuNode = ss.getCPUNode(cpu) val currentThreadNode = ss.getCurrentThreadNode(cpu) /* Mark this SoftIRQ as active in the resource tree. */ ss.modifyAttribute(timestamp, StateValues.CPU_STATUS_SOFTIRQ_VALUE, ss.getQuarkRelativeAndAdd(ss.getNodeSoftIRQs(cpu), softIrqId.toString())) /* Change the status of the running process to interrupted */ currentThreadNode?.let { ss.modifyAttribute(timestamp, StateValues.PROCESS_STATUS_INTERRUPTED_VALUE, it) } /* Change the status of the CPU to interrupted */ ss.modifyAttribute(timestamp, StateValues.CPU_STATUS_SOFTIRQ_VALUE, cpuNode) } }
jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/analysis/os/handlers/SoftIrqEntryHandler.kt
3649906157
package org.mozilla.focus.settings import android.content.Context import android.util.AttributeSet import android.widget.TextView import androidx.core.view.isVisible import androidx.preference.PreferenceViewHolder import androidx.preference.SwitchPreferenceCompat import mozilla.components.browser.state.state.SessionState import org.mozilla.focus.R import org.mozilla.focus.ext.components import org.mozilla.focus.state.AppAction abstract class LearnMoreSwitchPreference(context: Context, attrs: AttributeSet?) : SwitchPreferenceCompat(context, attrs) { init { layoutResource = R.layout.preference_switch_learn_more } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) getDescription()?.let { val summaryView = holder.findViewById(android.R.id.summary) as TextView summaryView.text = it summaryView.isVisible = true } val learnMoreLink = holder.findViewById(R.id.link) as TextView learnMoreLink.setOnClickListener { val tabId = context.components.tabsUseCases.addTab( getLearnMoreUrl(), source = SessionState.Source.Internal.Menu, selectTab = true, private = true, ) context.components.appStore.dispatch( AppAction.OpenTab(tabId), ) } val backgroundDrawableArray = context.obtainStyledAttributes(intArrayOf(R.attr.selectableItemBackground)) val backgroundDrawable = backgroundDrawableArray.getDrawable(0) backgroundDrawableArray.recycle() learnMoreLink.background = backgroundDrawable } open fun getDescription(): String? = null abstract fun getLearnMoreUrl(): String }
app/src/main/java/org/mozilla/focus/settings/LearnMoreSwitchPreference.kt
3072279764
/* * Copyright 2017 Fantasy Fang * * 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.fantasy1022.fancytrendapp.common import android.content.Context import android.content.SharedPreferences /** * Created by fantasy_apple on 2017/4/3. */ class SPUtils(context: Context) { private val sp: SharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE) private val editor: SharedPreferences.Editor init { editor = sp.edit() editor.apply() } fun putString(key: String, value: String?) { editor.putString(key, value).apply() } fun getString(key: String, defaultValue: String): String { return sp.getString(key, defaultValue) } fun putInt(key: String, value: Int) { editor.putInt(key, value).apply() } fun getInt(key: String, defaultValue: Int): Int { return sp.getInt(key, defaultValue) } }
app/src/main/java/com/fantasy1022/fancytrendapp/common/SPUtils.kt
1724622332
package i_introduction._4_Lambdas import util.TODO import util.doc4 fun example() { val sum = { x: Int, y: Int -> x + y } val square: (Int) -> Int = { x -> x * x } sum(1, square(2)) == 5 } fun todoTask4(collection: Collection<Int>): Nothing = TODO( """ Task 4. Rewrite 'JavaCode4.task4()' in Kotlin using lambdas. You can find the appropriate function to call on 'collection' through IntelliJ IDEA's code completion feature. (Don't use the class 'Iterables'). """, documentation = doc4(), references = { JavaCode4().task4(collection) }) fun task4(collection: Collection<Int>): Boolean = todoTask4(collection)
src/i_introduction/_4_Lambdas/Lambdas.kt
8416777
package me.proxer.library.api.notifications import me.proxer.library.ProxerCall import me.proxer.library.entity.notifications.NewsArticle import me.proxer.library.entity.notifications.Notification import me.proxer.library.entity.notifications.NotificationInfo import me.proxer.library.enums.NotificationFilter import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Query /** * @author Ruben Gees */ internal interface InternalApi { @GET("notifications/news") fun news( @Query("p") page: Int?, @Query("limit") limit: Int?, @Query("set_read") markAsRead: Boolean? ): ProxerCall<List<NewsArticle>> @GET("notifications/notifications") fun notifications( @Query("p") page: Int?, @Query("limit") limit: Int?, @Query("set_read") markAsRead: Boolean?, @Query("filter") filter: NotificationFilter? ): ProxerCall<List<Notification>> @GET("notifications/count") fun notificationInfo(): ProxerCall<NotificationInfo> @FormUrlEncoded @POST("notifications/delete") fun deleteNotification(@Field("nid") id: String?): ProxerCall<Unit?> }
library/src/main/kotlin/me/proxer/library/api/notifications/InternalApi.kt
3838533253
package hr.caellian.math.matrix import hr.caellian.math.internal.Inverse import hr.caellian.math.vector.Vector import hr.caellian.math.vector.VectorN /** * Abstract Matrix class defining number matrix specific behaviour. * * @since 3.0.0 * @author Caellian */ abstract class MatrixN<T : Number> : Matrix<T>() { /** * @return this matrix. */ operator fun unaryPlus() = this /** * @return new matrix with negated values. */ abstract operator fun unaryMinus(): MatrixN<T> /** * Performs matrix addition and returns resulting matrix. * In order to add to matrices together, they must be of same size. * * @param other matrix to add to this one. * @return resulting of matrix addition. */ abstract operator fun plus(other: MatrixN<T>): MatrixN<T> /** * Performs matrix subtraction and returns resulting matrix. * In order to subtract one matrix from another, matrices must be of same size. * * @param other matrix to subtract from this one. * @return resulting of matrix subtraction. */ abstract operator fun minus(other: MatrixN<T>): MatrixN<T> /** * Performs matrix multiplication on this matrix. * Returns C from 'C = A×B' where A is this matrix and B is the other / argument matrix. * * @param other matrix to multiply this matrix with. * @return result of matrix multiplication. */ abstract operator fun times(other: MatrixN<T>): MatrixN<T> /** * Performs matrix multiplication on this matrix. * Returns C from 'C = A×B' where A is this matrix and B is the other / argument vector. * * @param other vector to multiply this matrix with. * @return result of matrix multiplication. */ abstract operator fun times(other: VectorN<T>): Vector<T> /** * Performs scalar multiplication on this matrix and returns resulting matrix. * * @param scalar scalar to multiply every member of this matrix with. * @return result of scalar matrix multiplication. */ abstract operator fun times(scalar: T): MatrixN<T> /** * @return inverse matrix. */ override operator fun not(): Matrix<T> = inverse() /** * Multiplies all entries of a row with given scalar. * * @param row row to multiply. * @param multiplier scalar to multiply rows entries with. * @return resulting matrix. */ abstract fun multiplyRow(row: Int, multiplier: T): MatrixN<T> /** * Multiplies all entries of a column with given scalar. * * @param column column to multiply. * @param multiplier scalar to multiply column entries with. * @return resulting matrix. */ abstract fun multiplyColumn(column: Int, multiplier: T): MatrixN<T> /** * Adds one row from matrix to another. * * @param from row to add to another row. * @param to row to add another row to; data will be stored on this row. * @param multiplier scalar to multiply all members of added row with on addition. It equals to 1 by default. * @return new matrix. */ abstract fun addRows(from: Int, to: Int, multiplier: T? = null): MatrixN<T> /** * Adds one column from matrix to another. * * @param from column to add to another column. * @param to column to add another column to; data will be stored on this column. * @param multiplier scalar to multiply all members of added column with on addition. It equals to 1 by default. * @return new matrix. */ abstract fun addColumns(from: Int, to: Int, multiplier: T? = null): MatrixN<T> /** * @return inverse matrix. */ fun inverse(singularityThreshold: Double = 1e-11): MatrixN<T> { @Suppress("UNCHECKED_CAST") return withData( Inverse.inverseMatrix(toArray() as Array<Array<Double>>, singularityThreshold) as Array<Array<T>>) as MatrixN<T> } /** * This method replaces data of this matrix with LU decomposition data. * * @return self. */ fun inverseUnsafe(singularityThreshold: Double = 1e-11): MatrixN<T> { @Suppress("UNCHECKED_CAST") return withData(Inverse.inverseMatrix(wrapped as Array<Array<Double>>, singularityThreshold) as Array<Array<T>>) as MatrixN<T> } }
src/main/kotlin/hr/caellian/math/matrix/MatrixN.kt
2021770018
package org.gravidence.gravifon.util import kotlinx.datetime.Clock import kotlinx.datetime.Instant import mu.KotlinLogging import kotlin.time.Duration private val logger = KotlinLogging.logger {} class Stopwatch { private var elapsed: Duration = Duration.ZERO private var spanStart: Instant? = null @Synchronized fun count() { // start new cycle only if measurement is NOT in progress already if (spanStart == null) { spanStart = Clock.System.now().also { logger.trace { "Open stopwatch span at $it" } } } } @Synchronized fun pause(): Duration { // update state only if measurement is in progress spanStart?.let { start -> // update elapsed counter val spanEnd = Clock.System.now().also { end -> logger.trace { "Close stopwatch span at $end" } } elapsed += spanEnd.minus(start) // reset span to mark end of a measurement cycle spanStart = null } return elapsed() } @Synchronized fun stop(): Duration { // finish up measurement process and keep keep total duration val duration = pause() // reset elapsed counter elapsed = Duration.ZERO return duration } fun elapsed(): Duration { return elapsed.also { logger.trace { "Elapsed time is $it" } } } }
gravifon/src/main/kotlin/org/gravidence/gravifon/util/Stopwatch.kt
1820867983
package app.lawnchair.ui.util import android.content.Context import android.view.View import androidx.compose.runtime.Composable import androidx.compose.runtime.RememberObserver import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.recyclerview.widget.RecyclerView class ViewPool<T>( private val context: Context, private val factory: (Context) -> T ) : RecyclerView.RecycledViewPool() where T : View, T : ViewPool.Recyclable { private fun getOrCreateHolder(): RecyclerView.ViewHolder { return getRecycledView(RecyclerView.INVALID_TYPE) ?: ViewHolder(factory(context)) } @Composable fun rememberView(): T { val observer = remember { getOrCreateHolder() } @Suppress("UNCHECKED_CAST") return observer.itemView as T } private inner class ViewHolder(private val view: T) : RecyclerView.ViewHolder(view), RememberObserver { override fun onRemembered() { } override fun onForgotten() { putRecycledView(this) view.onRecycled() } override fun onAbandoned() { putRecycledView(this) view.onRecycled() } } interface Recyclable { fun onRecycled() } } @Composable fun <T> rememberViewPool(factory: (Context) -> T): ViewPool<T> where T : View, T : ViewPool.Recyclable { val context = LocalContext.current return remember(factory) { ViewPool(context, factory) } }
lawnchair/src/app/lawnchair/ui/util/ViewPool.kt
2546625236
package com.savrov.loadingbutton import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("com.savrov.loadingbutton", appContext.packageName) } }
app/src/androidTest/java/com/savrov/loadingbutton/ExampleInstrumentedTest.kt
1402043378
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistMediaUiApi::class) package com.google.android.horologist.media.ui.screens.entity import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MusicNote import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.wear.compose.material.rememberScalingLazyListState import com.google.android.horologist.base.ui.util.rememberVectorPainter import com.google.android.horologist.compose.tools.WearPreviewDevices import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi import com.google.android.horologist.media.ui.state.model.DownloadMediaUiModel import com.google.android.horologist.media.ui.state.model.PlaylistUiModel @WearPreviewDevices @Composable fun PlaylistDownloadScreenPreviewLoading() { PlaylistDownloadScreen( playlistName = "Playlist name", playlistDownloadScreenState = PlaylistDownloadScreenState.Loading(), onDownloadButtonClick = { }, onCancelDownloadButtonClick = { }, onDownloadItemClick = { }, onDownloadItemInProgressClick = { }, onShuffleButtonClick = { }, onPlayButtonClick = { }, scalingLazyListState = rememberScalingLazyListState() ) } @WearPreviewDevices @Composable fun PlaylistDownloadScreenPreviewLoadedNoneDownloaded() { PlaylistDownloadScreen( playlistName = "Playlist name", playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded( playlistModel = playlistUiModel, downloadMediaList = notDownloaded ), onDownloadButtonClick = { }, onCancelDownloadButtonClick = { }, onDownloadItemClick = { }, onDownloadItemInProgressClick = { }, onShuffleButtonClick = { }, onPlayButtonClick = { }, scalingLazyListState = rememberScalingLazyListState(), downloadItemArtworkPlaceholder = rememberVectorPainter( image = Icons.Default.MusicNote, tintColor = Color.Blue ) ) } @WearPreviewDevices @Composable fun PlaylistDownloadScreenPreviewLoadedNoneDownloadedDownloading() { PlaylistDownloadScreen( playlistName = "Playlist name", playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded( playlistModel = playlistUiModel, downloadMediaList = notDownloadedAndDownloading ), onDownloadButtonClick = { }, onCancelDownloadButtonClick = { }, onDownloadItemClick = { }, onDownloadItemInProgressClick = { }, onShuffleButtonClick = { }, onPlayButtonClick = { }, scalingLazyListState = rememberScalingLazyListState(), downloadItemArtworkPlaceholder = rememberVectorPainter( image = Icons.Default.MusicNote, tintColor = Color.Blue ) ) } @WearPreviewDevices @Composable fun PlaylistDownloadScreenPreviewLoadedPartiallyDownloaded() { PlaylistDownloadScreen( playlistName = "Playlist name", playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded( playlistModel = playlistUiModel, downloadMediaList = downloadedNotDownloaded ), onDownloadButtonClick = { }, onCancelDownloadButtonClick = { }, onDownloadItemClick = { }, onDownloadItemInProgressClick = { }, onShuffleButtonClick = { }, onPlayButtonClick = { }, scalingLazyListState = rememberScalingLazyListState(), downloadItemArtworkPlaceholder = rememberVectorPainter( image = Icons.Default.MusicNote, tintColor = Color.Blue ) ) } @WearPreviewDevices @Composable fun PlaylistDownloadScreenPreviewLoadedPartiallyDownloadedDownloadingUnknownSize() { PlaylistDownloadScreen( playlistName = "Playlist name", playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded( playlistModel = playlistUiModel, downloadMediaList = downloadedAndDownloadingUnknown ), onDownloadButtonClick = { }, onCancelDownloadButtonClick = { }, onDownloadItemClick = { }, onDownloadItemInProgressClick = { }, onShuffleButtonClick = { }, onPlayButtonClick = { }, scalingLazyListState = rememberScalingLazyListState(), downloadItemArtworkPlaceholder = rememberVectorPainter( image = Icons.Default.MusicNote, tintColor = Color.Blue ) ) } @WearPreviewDevices @Composable fun PlaylistDownloadScreenPreviewLoadedPartiallyDownloadedDownloadingWaiting() { PlaylistDownloadScreen( playlistName = "Playlist name", playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded( playlistModel = playlistUiModel, downloadMediaList = downloadedAndDownloadingWaiting ), onDownloadButtonClick = { }, onCancelDownloadButtonClick = { }, onDownloadItemClick = { }, onDownloadItemInProgressClick = { }, onShuffleButtonClick = { }, onPlayButtonClick = { }, scalingLazyListState = rememberScalingLazyListState(), downloadItemArtworkPlaceholder = rememberVectorPainter( image = Icons.Default.MusicNote, tintColor = Color.Blue ) ) } @WearPreviewDevices @Composable fun PlaylistDownloadScreenPreviewLoadedFullyDownloaded() { PlaylistDownloadScreen( playlistName = "Playlist name", playlistDownloadScreenState = createPlaylistDownloadScreenStateLoaded( playlistModel = playlistUiModel, downloadMediaList = downloaded ), onDownloadButtonClick = { }, onCancelDownloadButtonClick = { }, onDownloadItemClick = { }, onDownloadItemInProgressClick = { }, onShuffleButtonClick = { }, onPlayButtonClick = { }, scalingLazyListState = rememberScalingLazyListState(), downloadItemArtworkPlaceholder = rememberVectorPainter( image = Icons.Default.MusicNote, tintColor = Color.Blue ) ) } @WearPreviewDevices @Composable fun PlaylistDownloadScreenPreviewFailed() { PlaylistDownloadScreen( playlistName = "Playlist name", playlistDownloadScreenState = PlaylistDownloadScreenState.Failed(), onDownloadButtonClick = { }, onCancelDownloadButtonClick = { }, onDownloadItemClick = { }, onDownloadItemInProgressClick = { }, onShuffleButtonClick = { }, onPlayButtonClick = { }, scalingLazyListState = rememberScalingLazyListState() ) } private val playlistUiModel = PlaylistUiModel( id = "id", title = "Playlist name" ) private val notDownloaded = listOf( DownloadMediaUiModel.NotDownloaded( id = "id", title = "Song name", artist = "Artist name", artworkUri = "artworkUri" ), DownloadMediaUiModel.NotDownloaded( id = "id 2", title = "Song name 2", artist = "Artist name 2", artworkUri = "artworkUri" ) ) private val notDownloadedAndDownloading = listOf( DownloadMediaUiModel.NotDownloaded( id = "id", title = "Song name", artist = "Artist name", artworkUri = "artworkUri" ), DownloadMediaUiModel.Downloading( id = "id 2", title = "Song name 2", progress = DownloadMediaUiModel.Progress.InProgress(78f), size = DownloadMediaUiModel.Size.Known(sizeInBytes = 123456L), artworkUri = "artworkUri" ) ) private val downloadedAndDownloadingUnknown = listOf( DownloadMediaUiModel.Downloaded( id = "id", title = "Song name", artist = "Artist name", artworkUri = "artworkUri" ), DownloadMediaUiModel.Downloading( id = "id 2", title = "Song name 2", progress = DownloadMediaUiModel.Progress.InProgress(78f), size = DownloadMediaUiModel.Size.Unknown, artworkUri = "artworkUri" ) ) private val downloadedAndDownloadingWaiting = listOf( DownloadMediaUiModel.Downloaded( id = "id", title = "Song name", artist = "Artist name", artworkUri = "artworkUri" ), DownloadMediaUiModel.Downloading( id = "id 2", title = "Song name 2", progress = DownloadMediaUiModel.Progress.Waiting, size = DownloadMediaUiModel.Size.Unknown, artworkUri = "artworkUri" ) ) private val downloadedNotDownloaded = listOf( DownloadMediaUiModel.Downloaded( id = "id", title = "Song name", artist = "Artist name", artworkUri = "artworkUri" ), DownloadMediaUiModel.NotDownloaded( id = "id 2", title = "Song name 2", artist = "Artist name 2", artworkUri = "artworkUri" ) ) private val downloaded = listOf( DownloadMediaUiModel.Downloaded( id = "id", title = "Song name", artist = "Artist name", artworkUri = "artworkUri" ), DownloadMediaUiModel.Downloaded( id = "id 2", title = "Song name 2", artist = "Artist name 2", artworkUri = "artworkUri" ) )
media-ui/src/debug/java/com/google/android/horologist/media/ui/screens/entity/PlaylistDownloadScreenPreview.kt
3436505413
/* * Copyright 2017-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.core.context import org.koin.core.Koin import org.koin.core.KoinApplication import org.koin.core.error.KoinAppAlreadyStartedException import org.koin.core.module.Module import org.koin.dsl.KoinAppDeclaration /** * Global context - current Koin Application available globally * * Support to help inject automatically instances once KoinApp has been started * * @author Arnaud Giuliani */ object GlobalContext : KoinContext { private var _koin: Koin? = null override fun get(): Koin = _koin ?: error("KoinApplication has not been started") override fun getOrNull(): Koin? = _koin override fun register(koinApplication: KoinApplication) { if (_koin != null) { throw KoinAppAlreadyStartedException("A Koin Application has already been started") } _koin = koinApplication.koin } override fun stop() = synchronized(this) { _koin?.close() _koin = null } /** * Start a Koin Application as StandAlone */ fun startKoin(koinContext: KoinContext = GlobalContext, koinApplication: KoinApplication): KoinApplication = synchronized(this) { koinContext.register(koinApplication) koinApplication.createEagerInstances() return koinApplication } /** * Start a Koin Application as StandAlone */ fun startKoin(koinContext: KoinContext = GlobalContext, appDeclaration: KoinAppDeclaration): KoinApplication = synchronized(this) { val koinApplication = KoinApplication.init() koinContext.register(koinApplication) appDeclaration(koinApplication) koinApplication.createEagerInstances() return koinApplication } /** * Stop current StandAlone Koin application */ fun stopKoin() = stop() /** * load Koin module in global Koin context */ fun loadKoinModules(module: Module) = synchronized(this) { get().loadModules(listOf(module)) } /** * load Koin modules in global Koin context */ fun loadKoinModules(modules: List<Module>) = synchronized(this) { get().loadModules(modules) } /** * unload Koin modules from global Koin context */ fun unloadKoinModules(module: Module) = synchronized(this) { get().unloadModules(listOf(module)) } /** * unload Koin modules from global Koin context */ fun unloadKoinModules(modules: List<Module>) = synchronized(this) { get().unloadModules(modules) } }
koin-projects/koin-core/src/main/kotlin/org/koin/core/context/GlobalContext.kt
2537842054
package org.koin.androidx.scope import androidx.lifecycle.ViewModel import org.koin.core.scope.Scope class ScopeHandlerViewModel : ViewModel() { var scope: Scope? = null override fun onCleared() { super.onCleared() scope?.apply { logger.debug("Closing scope $scope") close() } scope = null } }
koin-projects/koin-androidx-scope/src/main/java/org/koin/androidx/scope/ScopeHandlerViewModel.kt
307612347
package com.supercilex.robotscouter.feature.trash import android.content.DialogInterface import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.core.os.bundleOf import androidx.fragment.app.FragmentManager import com.supercilex.robotscouter.core.data.emptyTrash import com.supercilex.robotscouter.core.ui.DialogFragmentBase import com.supercilex.robotscouter.core.unsafeLazy internal class EmptyTrashDialog : DialogFragmentBase(), DialogInterface.OnClickListener { private val ids by unsafeLazy { requireArguments().getStringArray(IDS_KEY).orEmpty().toList() } private val emptyAll by unsafeLazy { requireArguments().getBoolean(EMPTY_ALL_KEY) } override fun onCreateDialog(savedInstanceState: Bundle?) = AlertDialog.Builder(requireContext()) .setTitle(R.string.trash_empty_dialog_title) .setMessage(resources.getQuantityString( R.plurals.trash_empty_dialog_message, ids.size, ids.size)) .setPositiveButton(R.string.trash_empty_dialog_action, this) .setNegativeButton(android.R.string.cancel, null) .create() override fun onClick(dialog: DialogInterface, which: Int) { (requireParentFragment() as TrashFragment) .onEmptyTrashConfirmed(ids, emptyTrash(ids.takeUnless { emptyAll })) } companion object { private const val TAG = "EmptyTrashDialog" private const val IDS_KEY = "ids" private const val EMPTY_ALL_KEY = "empty_all" fun show(manager: FragmentManager, ids: List<String>, emptyAll: Boolean) { require(ids.isNotEmpty()) EmptyTrashDialog().apply { arguments = bundleOf(IDS_KEY to ids.toTypedArray(), EMPTY_ALL_KEY to emptyAll) }.show(manager, TAG) } } }
feature/trash/src/main/java/com/supercilex/robotscouter/feature/trash/EmptyTrashDialog.kt
1393538374
/* * Copyright 2019 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.favorites.tracker import com.github.vase4kin.teamcityapp.base.tracker.ViewTracker /** * Favorites tracker */ interface FavoritesTracker : ViewTracker { /** * Track user opens buildtype from favorites list */ fun trackUserOpensBuildType() companion object { /** * Event */ const val EVENT_USER_OPENS_BUILD_TYPE = "favorites_open_build_type" } }
app/src/main/java/com/github/vase4kin/teamcityapp/favorites/tracker/FavoritesTracker.kt
1450695234
package io.jentz.winter.compiler import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.ParameterizedTypeName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.asClassName import io.jentz.winter.inject.ApplicationScope import java.text.SimpleDateFormat import java.util.* import javax.inject.Singleton const val OPTION_GENERATED_COMPONENT_PACKAGE = "winterGeneratedComponentPackage" val GENERATED_ANNOTATION_LEGACY_INTERFACE_NAME = ClassName("javax.annotation", "Generated") val GENERATED_ANNOTATION_JDK9_INTERFACE_NAME = ClassName("javax.annotation.processing", "Generated") val SINGLETON_ANNOTATION_CLASS_NAME = Singleton::class.asClassName() val APPLICATION_SCOPE_CLASS_NAME = ApplicationScope::class.asClassName() val ISO8601_FORMAT = SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") } // see https://kotlinlang.org/docs/reference/java-interop.html#mapped-types val mappedTypes: Map<TypeName, TypeName> = mapOf( ClassName("java.lang", "Object") to ClassName("kotlin", "Any"), ClassName("java.lang", "Cloneable") to ClassName("kotlin", "Cloneable"), ClassName("java.lang", "Comparable") to ClassName("kotlin", "Comparable"), ClassName("java.lang", "Enum") to ClassName("kotlin", "Enum"), ClassName("java.lang", "Annotation") to ClassName("kotlin", "Annotation"), ClassName("java.lang", "Deprecated") to ClassName("kotlin", "Deprecated"), ClassName("java.lang", "CharSequence") to ClassName("kotlin", "CharSequence"), ClassName("java.lang", "String") to ClassName("kotlin", "String"), ClassName("java.lang", "Number") to ClassName("kotlin", "Number"), ClassName("java.lang", "Throwable") to ClassName("kotlin", "Throwable"), ClassName("java.lang", "Byte") to ClassName("kotlin", "Byte"), ClassName("java.lang", "Short") to ClassName("kotlin", "Short"), ClassName("java.lang", "Integer") to ClassName("kotlin", "Int"), ClassName("java.lang", "Long") to ClassName("kotlin", "Long"), ClassName("java.lang", "Character") to ClassName("kotlin", "Char"), ClassName("java.lang", "Float") to ClassName("kotlin", "Float"), ClassName("java.lang", "Double") to ClassName("kotlin", "Double"), ClassName("java.lang", "Boolean") to ClassName("kotlin", "Boolean"), // collections ClassName("java.util", "Iterator") to Iterator::class.asClassName(), ClassName("java.lang", "Iterable") to Iterable::class.asClassName(), ClassName("java.util", "Collection") to Collection::class.asClassName(), ClassName("java.util", "Set") to Set::class.asClassName(), ClassName("java.util", "List") to List::class.asClassName(), ClassName("java.util", "ListIterator") to ListIterator::class.asClassName(), ClassName("java.util", "Map") to Map::class.asClassName(), ClassName("java.util", "Map", "Entry") to Map.Entry::class.asClassName() ) val TypeName.kotlinTypeName: TypeName get() { if (this is ParameterizedTypeName) { val raw = rawType.kotlinTypeName if (raw !is ClassName) return this // should never happen return raw.parameterizedBy(typeArguments.map { it.kotlinTypeName }) } return mappedTypes.getOrDefault(this, this) } val notNullAnnotations = setOf( "org.jetbrains.annotations.NotNull", "javax.validation.constraints.NotNull", "edu.umd.cs.findbugs.annotations.NonNull", "javax.annotation.Nonnull", "lombok.NonNull", "android.support.annotation.NonNull", "org.eclipse.jdt.annotation.NonNull" )
winter-compiler/src/main/java/io/jentz/winter/compiler/commons.kt
2253517385
object Versions { const val androidGradle = "7.3.1" const val glide = "4.8.0" const val kotlin = "1.7.10" const val rxjava2 = "2.2.11" const val rxandroid2 = "2.1.1" } object Libs { const val androidGradlePlugin = "com.android.tools.build:gradle:${Versions.androidGradle}" const val kotlinGradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}" const val rxJava2 = "io.reactivex.rxjava2:rxjava:${Versions.rxjava2}" const val rxAndroid2 = "io.reactivex.rxjava2:rxandroid:${Versions.rxandroid2}" const val glide = "com.github.bumptech.glide:glide:${Versions.glide}" const val glideCompiler = "com.github.bumptech.glide:compiler:${Versions.glide}" }
buildSrc/src/main/java/Dependecies.kt
3567612187
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 app.tivi.data.mappers import app.tivi.data.entities.ShowStatus import com.uwetrottmann.trakt5.enums.Status import javax.inject.Inject import javax.inject.Singleton @Singleton class TraktStatusToShowStatus @Inject constructor() : Mapper<Status, ShowStatus> { override suspend fun map(from: Status) = when (from) { Status.ENDED -> ShowStatus.ENDED Status.RETURNING -> ShowStatus.RETURNING Status.CANCELED -> ShowStatus.CANCELED Status.IN_PRODUCTION -> ShowStatus.IN_PRODUCTION } }
data/src/main/java/app/tivi/data/mappers/TraktStatusToShowStatus.kt
2428904490
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.stt.gui.jfx.binding import javafx.beans.property.SimpleObjectProperty import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.BDDMockito.given import org.mockito.Mockito.mock import org.stt.model.TimeTrackingItem import org.stt.persistence.ItemReader import org.stt.query.TimeTrackingItemQueries import java.time.Duration import java.time.LocalDate import java.util.* import javax.inject.Provider /** * * @author dante */ class ReportBindingTest { private var sut: ReportBinding? = null private val reportStart = SimpleObjectProperty<LocalDate>() private val reportEnd = SimpleObjectProperty<LocalDate>() private var readerProvider: Provider<ItemReader>? = null private val itemReader = mock(ItemReader::class.java) @Before fun setup() { readerProvider = Provider { itemReader } sut = ReportBinding(reportStart, reportEnd, TimeTrackingItemQueries(readerProvider!!, Optional.empty())) } @Test fun shouldReturnEmptyReportIfStartIsNull() { // GIVEN reportEnd.set(LocalDate.now()) // WHEN val result = sut!!.value // THEN assertThat(result.start).isNull() assertThat(result.end).isNull() assertThat(result.reportingItems).isEmpty() assertThat(result.uncoveredDuration).isEqualTo(Duration.ZERO) } @Test fun shouldReturnEmptyReportIfEndIsNull() { // GIVEN reportStart.set(LocalDate.now()) // WHEN val result = sut!!.value // THEN assertThat(result.start).isNull() assertThat(result.end).isNull() assertThat(result.reportingItems).isEmpty() assertThat(result.uncoveredDuration).isEqualTo(Duration.ZERO) } @Test fun shouldReadItemsIfStartAndEndAreSet() { // GIVEN val start = LocalDate.now() reportStart.set(start) val end = start.plusDays(1) reportEnd.set(end) val item = TimeTrackingItem("none", start.atStartOfDay(), end.atStartOfDay()) given<TimeTrackingItem>(itemReader.read()).willReturn(item, null) // WHEN val result = sut!!.value // THEN assertThat(result.start).isEqualTo(start.atStartOfDay()) assertThat(result.end).isEqualTo(end.atStartOfDay()) assertThat(result.reportingItems).isNotEmpty assertThat(result.uncoveredDuration).isEqualTo(Duration.ZERO) } }
src/test/kotlin/org/stt/gui/jfx/binding/ReportBindingTest.kt
92371358
package com.alphago.moneypacket.fragments import android.os.Build import android.os.Bundle import android.preference.Preference import android.preference.PreferenceFragment import android.preference.PreferenceManager import android.widget.Toast import com.alphago.moneypacket.R /** * Created by Zhongyi on 2/4/16. */ class CommentSettingsFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.comment_preferences) setPrefListeners() } private fun setPrefListeners() { // val listenerEnable = findPreference(getString(R.string.dont_show_again)) // listenerEnable.onPreferenceClickListener = Preference.OnPreferenceClickListener { preference-> // preference. // true // } val updatePref = findPreference("pref_comment_switch") if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { updatePref.isEnabled = false } Toast.makeText(activity, "该功能尚处于实验中,只能自动填充感谢语,无法直接发送.", Toast.LENGTH_LONG).show() val commentWordsPref = findPreference("pref_comment_words") val summary = resources.getString(R.string.pref_comment_words_summary) val value = PreferenceManager.getDefaultSharedPreferences(activity).getString("pref_comment_words", "") if (value!!.length > 0) commentWordsPref.summary = summary + ":" + value commentWordsPref.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { preference, o -> val summary = resources.getString(R.string.pref_comment_words_summary) if (o != null && o.toString().length > 0) { preference.summary = summary + ":" + o.toString() } else { preference.summary = summary } true } } }
moneyGiftAssistant/src/main/java/com/alphago/moneypacket/fragments/CommentSettingsFragment.kt
145311674
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions class SetImmutableIntentionTest : RsIntentionTestBase(SetImmutableIntention()) { fun testSetMutableVariable() = doAvailableTest( """ fn main() { let var: &mut i3/*caret*/2 = 52; } """, """ fn main() { let var: &i3/*caret*/2 = 52; } """ ) fun testSetMutableParameter() = doAvailableTest( """ fn func(param: &mut i3/*caret*/2) {} """, """ fn func(param: &i3/*caret*/2) {} """ ) }
src/test/kotlin/org/rust/ide/intentions/SetImmutableIntentionTest.kt
2519151424
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.impl import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.intellij.psi.tree.TokenSet.orSet import org.rust.lang.core.psi.RS_OPERATORS import org.rust.lang.core.psi.RsAttr import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.RsStmt import org.rust.lang.core.psi.ext.RsItemElement import org.rust.lang.core.psi.ext.RsMod import com.intellij.psi.tree.TokenSet.create as ts val SPECIAL_MACRO_ARGS = ts(FORMAT_MACRO_ARGUMENT, LOG_MACRO_ARGUMENT, TRY_MACRO_ARGUMENT, VEC_MACRO_ARGUMENT, ASSERT_MACRO_ARGUMENT) val NO_SPACE_AROUND_OPS = ts(COLONCOLON, DOT, DOTDOT) val SPACE_AROUND_OPS = TokenSet.andNot(RS_OPERATORS, NO_SPACE_AROUND_OPS) val UNARY_OPS = ts(MINUS, MUL, EXCL, AND, ANDAND) val PAREN_DELIMITED_BLOCKS = orSet(ts(VALUE_PARAMETER_LIST, PAREN_EXPR, TUPLE_EXPR, TUPLE_TYPE, VALUE_ARGUMENT_LIST, PAT_TUP, TUPLE_FIELDS), SPECIAL_MACRO_ARGS) val PAREN_LISTS = orSet(PAREN_DELIMITED_BLOCKS, ts(PAT_ENUM)) val BRACK_DELIMITED_BLOCKS = orSet(ts(ARRAY_TYPE, ARRAY_EXPR), SPECIAL_MACRO_ARGS) val BRACK_LISTS = orSet(BRACK_DELIMITED_BLOCKS, ts(INDEX_EXPR)) val BLOCK_LIKE = ts(BLOCK, BLOCK_FIELDS, STRUCT_LITERAL_BODY, MATCH_BODY, ENUM_BODY, MEMBERS) val BRACE_LISTS = orSet(ts(USE_GLOB_LIST), SPECIAL_MACRO_ARGS) val BRACE_DELIMITED_BLOCKS = orSet(BLOCK_LIKE, BRACE_LISTS) val ANGLE_DELIMITED_BLOCKS = ts(TYPE_PARAMETER_LIST, TYPE_ARGUMENT_LIST, FOR_LIFETIMES) val ANGLE_LISTS = orSet(ANGLE_DELIMITED_BLOCKS, ts(TYPE_QUAL)) val ATTRS = ts(OUTER_ATTR, INNER_ATTR) val MOD_ITEMS = ts(FOREIGN_MOD_ITEM, MOD_ITEM) val DELIMITED_BLOCKS = orSet(BRACE_DELIMITED_BLOCKS, BRACK_DELIMITED_BLOCKS, PAREN_DELIMITED_BLOCKS, ANGLE_DELIMITED_BLOCKS) val FLAT_BRACE_BLOCKS = orSet(MOD_ITEMS, ts(PAT_STRUCT)) val TYPES = ts(ARRAY_TYPE, REF_LIKE_TYPE, FN_POINTER_TYPE, TUPLE_TYPE, BASE_TYPE, FOR_IN_TYPE) val FN_DECLS = ts(FUNCTION, FN_POINTER_TYPE, LAMBDA_EXPR) val ONE_LINE_ITEMS = ts(USE_ITEM, CONSTANT, MOD_DECL_ITEM, EXTERN_CRATE_ITEM, TYPE_ALIAS, INNER_ATTR) val PsiElement.isTopLevelItem: Boolean get() = (this is RsItemElement || this is RsAttr) && parent is RsMod val PsiElement.isStmtOrExpr: Boolean get() = this is RsStmt || this is RsExpr val ASTNode.isDelimitedBlock: Boolean get() = elementType in DELIMITED_BLOCKS val ASTNode.isFlatBraceBlock: Boolean get() = elementType in FLAT_BRACE_BLOCKS /** * A flat block is a Rust PSI element which does not denote separate PSI * element for its _block_ part (e.g. `{...}`), for example [MOD_ITEM]. */ val ASTNode.isFlatBlock: Boolean get() = isFlatBraceBlock || elementType == PAT_ENUM fun ASTNode.isBlockDelim(parent: ASTNode?): Boolean { if (parent == null) return false val parentType = parent.elementType return when (elementType) { LBRACE, RBRACE -> parentType in BRACE_DELIMITED_BLOCKS || parent.isFlatBraceBlock LBRACK, RBRACK -> parentType in BRACK_LISTS LPAREN, RPAREN -> parentType in PAREN_LISTS || parentType == PAT_ENUM LT, GT -> parentType in ANGLE_LISTS OR -> parentType == VALUE_PARAMETER_LIST && parent.treeParent?.elementType == LAMBDA_EXPR else -> false } } fun ASTNode?.isWhitespaceOrEmpty() = this == null || textLength == 0 || elementType == WHITE_SPACE fun ASTNode.treeNonWSPrev(): ASTNode? { var current = this.treePrev while (current?.elementType == WHITE_SPACE) { current = current?.treePrev } return current } fun ASTNode.treeNonWSNext(): ASTNode? { var current = this.treeNext while (current?.elementType == WHITE_SPACE) { current = current?.treeNext } return current } data class CommaList(val listElement: IElementType, val openingBrace: IElementType, val closingBrace: IElementType) { val needsSpaceBeforeClosingBrace: Boolean get() = closingBrace == RBRACE && listElement != USE_GLOB_LIST companion object { fun forElement(elementType: IElementType): CommaList? { return ALL.find { it.listElement == elementType } } private val ALL = listOf( CommaList(BLOCK_FIELDS, LBRACE, RBRACE), CommaList(STRUCT_LITERAL_BODY, LBRACE, RBRACE), CommaList(ENUM_BODY, LBRACE, RBRACE), CommaList(USE_GLOB_LIST, LBRACE, RBRACE), CommaList(TUPLE_FIELDS, LPAREN, RPAREN), CommaList(VALUE_PARAMETER_LIST, LPAREN, RPAREN), CommaList(VALUE_ARGUMENT_LIST, LPAREN, RPAREN) ) } }
src/main/kotlin/org/rust/ide/formatter/impl/utils.kt
155526708
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.repository import android.net.Uri import com.moez.QKSMS.model.Contact import com.moez.QKSMS.model.ContactGroup import io.reactivex.Observable import io.reactivex.Single import io.realm.RealmResults interface ContactRepository { fun findContactUri(address: String): Single<Uri> fun getContacts(): RealmResults<Contact> fun getUnmanagedContact(lookupKey: String): Contact? fun getUnmanagedContacts(starred: Boolean = false): Observable<List<Contact>> fun getUnmanagedContactGroups(): Observable<List<ContactGroup>> fun setDefaultPhoneNumber(lookupKey: String, phoneNumberId: Long) }
domain/src/main/java/com/moez/QKSMS/repository/ContactRepository.kt
2427045039
package io.gitlab.arturbosch.detekt import io.gitlab.arturbosch.detekt.extensions.DetektExtension import org.gradle.api.DefaultTask import org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency import org.gradle.api.tasks.TaskAction /** * @author Artur Bosch */ open class DetektCreateBaselineTask : DefaultTask() { init { description = "Creates a detekt baseline on the given --baseline path." group = "verification" } private val createBaseline = "--create-baseline" @TaskAction fun baseline() { val detektExtension = project.extensions.getByName("detekt") as DetektExtension val configuration = project.buildscript.configurations.maybeCreate("detektBaseline") project.buildscript.dependencies.add(configuration.name, DefaultExternalModuleDependency( "io.gitlab.arturbosch.detekt", "detekt-cli", detektExtension.version)) project.javaexec { it.main = "io.gitlab.arturbosch.detekt.cli.Main" it.classpath = configuration it.args(detektExtension.profileArgumentsOrDefault(project).plus(createBaseline)) } } }
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/DetektCreateBaselineTask.kt
3121823634
package com.aajtech.mobile.goproshowcase import java.io.IOException import java.net.* import java.util.regex.Pattern /** * Created by pablo.biagioli on 7/20/16. */ object MagicPacket { private val TAG = "MagicPacket" val BROADCAST = "192.168.1.255" val PORT = 9 val SEPARATOR = ':' @Throws(UnknownHostException::class, SocketException::class, IOException::class, IllegalArgumentException::class) @JvmOverloads fun send(mac: String, ip: String, port: Int = PORT): String { // validate MAC and chop into array val hex = validateMac(mac) // convert to base16 bytes val macBytes = ByteArray(6) for (i in 0..5) { macBytes[i] = Integer.parseInt(hex[i], 16).toByte() } val bytes = ByteArray(102) // fill first 6 bytes for (i in 0..5) { bytes[i] = 0xff.toByte() } // fill remaining bytes with target MAC var i = 6 while (i < bytes.size) { System.arraycopy(macBytes, 0, bytes, i, macBytes.size) i += macBytes.size } // create socket to IP val address = InetAddress.getByName(ip) val packet = DatagramPacket(bytes, bytes.size, address, port) val socket = DatagramSocket() socket.send(packet) socket.close() return hex[0] + SEPARATOR + hex[1] + SEPARATOR + hex[2] + SEPARATOR + hex[3] + SEPARATOR + hex[4] + SEPARATOR + hex[5] } @Throws(IllegalArgumentException::class) fun cleanMac(mac: String): String { val hex = validateMac(mac) var sb = StringBuffer() var isMixedCase = false // check for mixed case for (i in 0..5) { sb.append(hex[i]) } val testMac = sb.toString() if (testMac.toLowerCase() == testMac == false && testMac.toUpperCase() == testMac == false) { isMixedCase = true } sb = StringBuffer() for (i in 0..5) { // convert mixed case to lower if (isMixedCase == true) { sb.append(hex[i].toLowerCase()) } else { sb.append(hex[i]) } if (i < 5) { sb.append(SEPARATOR) } } return sb.toString() } @Throws(IllegalArgumentException::class) private fun validateMac(mac: String): Array<String> { var mac = mac // error handle semi colons mac = mac.replace(";", ":") // attempt to assist the user a little var newMac = "" if (mac.matches("([a-zA-Z0-9]){12}".toRegex())) { // expand 12 chars into a valid mac address for (i in 0..mac.length - 1) { if (i > 1 && i % 2 == 0) { newMac += ":" } newMac += mac[i] } } else { newMac = mac } // regexp pattern match a valid MAC address val pat = Pattern.compile("((([0-9a-fA-F]){2}[-:]){5}([0-9a-fA-F]){2})") val m = pat.matcher(newMac) if (m.find()) { val result = m.group() return result.split("(\\:|\\-)".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() } else { throw IllegalArgumentException("Invalid MAC address") } } }
app/src/test/java/com/aajtech/mobile/goproshowcase/MagicPacket.kt
2483117280
package org.http4k.core import org.http4k.core.ContentType.Companion.TEXT_HTML import org.http4k.core.MultipartFormBody.Companion.DEFAULT_DISK_THRESHOLD import org.http4k.lens.Header.CONTENT_TYPE import org.http4k.lens.MultipartFormField import org.http4k.lens.MultipartFormFile import org.http4k.multipart.DiskLocation import org.http4k.multipart.MultipartFormBuilder import org.http4k.multipart.MultipartFormParser import org.http4k.multipart.Part import org.http4k.multipart.StreamingMultipartFormParts import java.io.ByteArrayInputStream import java.io.Closeable import java.nio.ByteBuffer import java.nio.charset.StandardCharsets.UTF_8 import java.util.* sealed class MultipartEntity : Closeable { abstract val name: String internal abstract fun applyTo(builder: MultipartFormBuilder): MultipartFormBuilder data class Field(override val name: String, val value: String, val headers: Headers = emptyList()) : MultipartEntity() { override fun close() = Unit override fun applyTo(builder: MultipartFormBuilder) = builder.field(name, value, headers) } data class File(override val name: String, val file: MultipartFormFile, val headers: Headers = emptyList()) : MultipartEntity() { override fun close() = file.content.close() override fun applyTo(builder: MultipartFormBuilder): MultipartFormBuilder = builder.file(name, file.filename, file.contentType.value, file.content, headers) } } fun HttpMessage.multipartIterator(): Iterator<MultipartEntity> { val boundary = CONTENT_TYPE(this)?.directives?.firstOrNull()?.second ?: "" return StreamingMultipartFormParts.parse(boundary.toByteArray(UTF_8), body.stream, UTF_8) .asSequence() .map { if (it.isFormField) MultipartEntity.Field(it.fieldName!!, it.contentsAsString, it.headers.toList()) else MultipartEntity.File(it.fieldName!!, MultipartFormFile(it.fileName!!, ContentType(it.contentType!!, TEXT_HTML.directives), it.inputStream), it.headers.toList()) }.iterator() } /** * Represents a Multi-part that is backed by a stream, which should be closed after handling the content. The gotchas * which apply to StreamBody also apply here.. **/ data class MultipartFormBody private constructor(internal val formParts: List<MultipartEntity>, val boundary: String = UUID.randomUUID().toString()) : Body, Closeable { override val length: Long? = null constructor(boundary: String = UUID.randomUUID().toString()) : this(emptyList(), boundary) override fun close() = formParts.forEach(MultipartEntity::close) fun file(name: String) = files(name).firstOrNull() fun files(name: String) = formParts.filter { it.name == name }.mapNotNull { it as? MultipartEntity.File }.map { it.file } fun field(name: String) = fields(name).firstOrNull() fun fields(name: String) = formParts.filter { it.name == name }.mapNotNull { it as? MultipartEntity.Field }.map { MultipartFormField(it.value, it.headers) } fun fieldValue(name: String) = fieldValues(name).firstOrNull() fun fieldValues(name: String) = formParts.filter { it.name == name }.mapNotNull { it as? MultipartEntity.Field }.map { it.value } @JvmName("plus") operator fun plus(field: Pair<String, String>) = copy(formParts = formParts + MultipartEntity.Field(field.first, field.second)) @JvmName("plusField") operator fun plus(field: Pair<String, MultipartFormField>) = copy(formParts = formParts + MultipartEntity.Field(field.first, field.second.value, field.second.headers)) @JvmName("plusFile") operator fun plus(field: Pair<String, MultipartFormFile>) = copy(formParts = formParts + MultipartEntity.File(field.first, field.second)) override val stream by lazy { formParts.fold(MultipartFormBuilder(boundary.toByteArray())) { memo, next -> next.applyTo(memo) }.stream() } override val payload: ByteBuffer by lazy { stream.use { ByteBuffer.wrap(it.readBytes()) } } override fun toString() = String(payload.array()) companion object { const val DEFAULT_DISK_THRESHOLD = 1000 * 1024 fun from(httpMessage: HttpMessage, diskThreshold: Int = DEFAULT_DISK_THRESHOLD, diskLocation: DiskLocation = DiskLocation.Temp()): MultipartFormBody { val boundary = CONTENT_TYPE(httpMessage)?.directives?.firstOrNull{ it.first == "boundary" }?.second ?: "" val inputStream = httpMessage.body.run { if (stream.available() > 0) stream else ByteArrayInputStream(payload.array()) } val form = StreamingMultipartFormParts.parse(boundary.toByteArray(UTF_8), inputStream, UTF_8) val parts = MultipartFormParser(UTF_8, diskThreshold, diskLocation).formParts(form).map { if (it.isFormField) MultipartEntity.Field(it.fieldName!!, it.string(diskThreshold), it.headers.toList()) else MultipartEntity.File(it.fieldName!!, MultipartFormFile(it.fileName!!, ContentType(it.contentType!!, TEXT_HTML.directives), it.newInputStream)) } return MultipartFormBody(parts, boundary) } } } internal fun Part.string(diskThreshold: Int = DEFAULT_DISK_THRESHOLD): String = when (this) { is Part.DiskBacked -> throw RuntimeException("Fields configured to not be greater than $diskThreshold bytes.") is Part.InMemory -> String(bytes, encoding) }
http4k-multipart/src/main/kotlin/org/http4k/core/MultipartFormBody.kt
997633669
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.moshi import kotlin.annotation.AnnotationRetention.RUNTIME import kotlin.annotation.AnnotationTarget.FUNCTION @Retention(RUNTIME) @Target(FUNCTION) public annotation class FromJson
moshi/src/main/java/com/squareup/moshi/FromJson.kt
3450483062
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.moshi import com.squareup.moshi.internal.knownNotNull import java.lang.reflect.Type /** * Converts maps with string keys to JSON objects. * * TODO: support maps with other key types and convert to/from strings. */ internal class MapJsonAdapter<K, V>(moshi: Moshi, keyType: Type, valueType: Type) : JsonAdapter<Map<K, V?>>() { private val keyAdapter: JsonAdapter<K> = moshi.adapter(keyType) private val valueAdapter: JsonAdapter<V> = moshi.adapter(valueType) override fun toJson(writer: JsonWriter, value: Map<K, V?>?) { writer.beginObject() // Never null because we wrap in nullSafe() for ((k, v) in knownNotNull(value)) { if (k == null) { throw JsonDataException("Map key is null at ${writer.path}") } writer.promoteValueToName() keyAdapter.toJson(writer, k) valueAdapter.toJson(writer, v) } writer.endObject() } override fun fromJson(reader: JsonReader): Map<K, V?> { val result = LinkedHashTreeMap<K, V?>() reader.beginObject() while (reader.hasNext()) { reader.promoteNameToValue() val name = keyAdapter.fromJson(reader) ?: throw JsonDataException("Map key is null at ${reader.path}") val value = valueAdapter.fromJson(reader) val replaced = result.put(name, value) if (replaced != null) { throw JsonDataException( "Map key '$name' has multiple values at path ${reader.path}: $replaced and $value" ) } } reader.endObject() return result } override fun toString() = "JsonAdapter($keyAdapter=$valueAdapter)" companion object Factory : JsonAdapter.Factory { override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? { if (annotations.isNotEmpty()) return null val rawType = type.rawType if (rawType != Map::class.java) return null val keyAndValue = Types.mapKeyAndValueTypes(type, rawType) return MapJsonAdapter<Any, Any>(moshi, keyAndValue[0], keyAndValue[1]).nullSafe() } } }
moshi/src/main/java/com/squareup/moshi/MapJsonAdapter.kt
2498503680
/* * Copyright (c) 2020. Rei Matsushita. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package me.rei_m.hyakuninisshu.domain.karuta.model import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class KarutaNoCollectionTest { private lateinit var karutaNoCollection: KarutaNoCollection @Before fun setUp() { karutaNoCollection = KarutaNoCollection( arrayListOf( KarutaNo(1), KarutaNo(2), KarutaNo(3) ) ) } @Test fun createInstance() { val expected = arrayListOf( KarutaNo(1), KarutaNo(2), KarutaNo(3) ) assertThat(karutaNoCollection.values).isEqualTo(expected) assertThat(karutaNoCollection.size).isEqualTo(3) } @Test fun asRandomized() { assertThat(karutaNoCollection.asRandomized).containsAll(karutaNoCollection.values) } @Test fun contains() { assertThat(karutaNoCollection.contains(KarutaNo(1))).isTrue } @Test fun notContains() { assertThat(karutaNoCollection.contains(KarutaNo(4))).isFalse } }
domain/src/test/java/me/rei_m/hyakuninisshu/domain/karuta/model/KarutaNoCollectionTest.kt
3297498169
package com.mifos.mifosxdroid.online.savingsaccountapproval import com.mifos.api.GenericResponse import com.mifos.mifosxdroid.base.MvpView /** * Created by Rajan Maurya on 09/06/16. */ interface SavingsAccountApprovalMvpView : MvpView { fun showUserInterface() fun showSavingAccountApprovedSuccessfully(genericResponse: GenericResponse?) fun showError(s: String?) }
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/savingsaccountapproval/SavingsAccountApprovalMvpView.kt
1777565950
package org.abhijitsarkar import org.abhijitsarkar.client.GitLabClient import org.abhijitsarkar.client.GitLabProperties import org.abhijitsarkar.domain.License import org.abhijitsarkar.service.GradleAgent import org.abhijitsarkar.service.JGitAgent import org.abhijitsarkar.service.ReportParser import org.springframework.boot.CommandLineRunner import org.springframework.boot.WebApplicationType import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.builder.SpringApplicationBuilder import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.ApplicationEventPublisher import reactor.core.publisher.Flux import reactor.core.scheduler.Schedulers import java.time.Duration /** * @author Abhijit Sarkar */ @SpringBootApplication @EnableConfigurationProperties(GitLabProperties::class, ApplicationProperties::class) class Application( val gitLabProperties: GitLabProperties, val applicationProperties: ApplicationProperties, val gitLabClient: GitLabClient, val jGitAgent: JGitAgent, val gradleAgent: GradleAgent, val reportParser: ReportParser, val eventPublisher: ApplicationEventPublisher ) : CommandLineRunner { override fun run(vararg args: String): Unit { // Immutable view val groups: Map<String, GitLabProperties.GroupProperties> = gitLabProperties.groups fun isNotExcluded(projectName: String, groupName: String) = gitLabProperties .groups[groupName] ?.excludedProjects ?.run { !containsKey(projectName) } ?: true fun isIncluded(projectName: String, groupName: String) = gitLabProperties .groups[groupName] ?.includedProjects ?.run { isEmpty() || containsKey(projectName) } ?: true Flux.fromIterable(groups.entries) .flatMap { gitLabClient.projects(it.toPair()) } .filter { val projectName = it.second.name val groupName = it.first isNotExcluded(projectName, groupName) && isIncluded(projectName, groupName) } .parallel() .runOn(Schedulers.parallel()) .flatMap { jGitAgent.clone(it.second, gitLabProperties.groups[it.first]) } .filter(gradleAgent::isGradleProject) .flatMap { gradleAgent.generateLicense(it, applicationProperties.gradle.options) } .flatMap(reportParser::parseReport) .sequential() .sort(compareBy({ it.first }, { it.second.valid }, { it.second.url })) .collectMultimap(Pair<String, License>::first, Pair<String, License>::second) .map(::LicenseGeneratedEvent) .doOnNext { eventPublisher.publishEvent(it) } .block(Duration.ofMinutes(applicationProperties.timeoutMinutes)) } companion object { @JvmStatic fun main(args: Array<String>) { SpringApplicationBuilder(Application::class.java) .web(WebApplicationType.NONE) .run(*args) } } }
license-report-kotlin/src/main/kotlin/org/abhijitsarkar/Application.kt
840895361
package cm.aptoide.aptoideviews.skeleton import android.graphics.Color import cm.aptoide.aptoideviews.skeleton.mask.Border import cm.aptoide.aptoideviews.skeleton.mask.Shape internal data class SkeletonViewPreferences( var shape: Shape = Shape.Rect(Color.parseColor("#EDEEF2"), 0), var border: Border = Border(0, Color.WHITE))
aptoide-views/src/main/java/cm/aptoide/aptoideviews/skeleton/SkeletonViewPreferences.kt
491367125
package cz.vhromada.catalog.gui.season import cz.vhromada.catalog.entity.Season import cz.vhromada.catalog.entity.Show import cz.vhromada.catalog.facade.EpisodeFacade import cz.vhromada.catalog.facade.SeasonFacade import cz.vhromada.catalog.gui.common.AbstractInfoDialog import cz.vhromada.catalog.gui.common.AbstractOverviewDataPanel import cz.vhromada.catalog.gui.episode.EpisodesPanel import javax.swing.JPanel import javax.swing.JTabbedPane /** * A class represents panel with seasons' data. * * @author Vladimir Hromada */ class SeasonsPanel( private val seasonFacade: SeasonFacade, private val episodeFacade: EpisodeFacade, private var show: Show) : AbstractOverviewDataPanel<Season>(SeasonsListDataModel(seasonFacade, show)) { /** * Sets a new value to show. * * @param show new value */ fun setShow(show: Show) { this.show = show } override fun newData() { error { "Creating new data is not allowed for seasons." } } override fun clearSelection() { error { "Clearing selection is not allowed for seasons." } } override fun save() { error { "Saving data is not allowed for seasons." } } override fun getInfoDialog(add: Boolean, data: Season?): AbstractInfoDialog<Season> { return if (add) SeasonInfoDialog() else SeasonInfoDialog(data!!) } override fun addData(data: Season) { seasonFacade.add(show, data) } override fun deleteData() { error { "Deleting data is not allowed for seasons." } } override fun updateData(data: Season) { seasonFacade.update(data) } override fun removeData(data: Season) { seasonFacade.remove(data) } override fun duplicatesData(data: Season) { seasonFacade.duplicate(data) } override fun moveUpData(data: Season) { seasonFacade.moveUp(data) } override fun moveDownData(data: Season) { seasonFacade.moveDown(data) } override fun getDataPanel(data: Season): JPanel { return SeasonDataPanel(data, episodeFacade) } override fun updateDataOnChange(dataPanel: JTabbedPane, data: Season) { val episodesPanel = EpisodesPanel(episodeFacade, data) episodesPanel.addPropertyChangeListener("update") { if (java.lang.Boolean.TRUE == it.newValue) { updateModel(data) episodesPanel.setSeason(data) firePropertyChange("update", false, true) } } dataPanel.add("Episodes", episodesPanel) } }
src/main/kotlin/cz/vhromada/catalog/gui/season/SeasonsPanel.kt
3749315306
/* * Copyright (C) 2013-2022 Federico Iosue ([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 it.feio.android.omninotes.utils import it.feio.android.omninotes.BaseAndroidTestCase import org.junit.Assert.assertTrue import org.junit.Test class StorageHelperTest : BaseAndroidTestCase() { @Test fun getOrCreateExternalStoragePublicDir() { val dir = StorageHelper.getOrCreateExternalStoragePublicDir() assertTrue(dir.canRead()) assertTrue(dir.canWrite()) } }
omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/StorageHelperTest.kt
2800536067
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.servicelayer import com.ichi2.anki.CrashReportService import com.ichi2.libanki.Card import com.ichi2.libanki.DB import com.ichi2.utils.Computation import timber.log.Timber /** * @return whether the task succeeded, and the array of cards affected. */ // This was converted from CollectionTask, we want a better name, but keep it until DismissNotes is removed fun <TTaskResult : Any, TProgress, TResult> AnkiTask<TProgress, TResult>.dismissNotes(cardIds: List<Long>, task: (Array<Card>) -> Computation<TTaskResult>): Computation<Pair<TTaskResult, Array<Card>>> { // query cards val cards = cardIds.map { cid -> col.getCard(cid) }.toTypedArray() try { col.db.database.beginTransaction() try { val result = task(cards) if (!result.succeeded()) { return Computation.err() } col.db.database.setTransactionSuccessful() // pass cards back so more actions can be performed by the caller // (querying the cards again is unnecessarily expensive) return Computation.ok(Pair(result.value, cards)) } finally { DB.safeEndInTransaction(col.db) } } catch (e: RuntimeException) { Timber.e(e, "doInBackgroundSuspendCard - RuntimeException on suspending card") CrashReportService.sendExceptionReport(e, "doInBackgroundSuspendCard") return Computation.err() } }
AnkiDroid/src/main/java/com/ichi2/anki/servicelayer/Utils.kt
1244499587
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.DetektVisitor import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import org.jetbrains.kotlin.psi.KtBreakExpression import org.jetbrains.kotlin.psi.KtContinueExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtLoopExpression /** * Loops which contain multiple `break` or `continue` statements are hard to read and understand. * To increase readability they should be refactored into simpler loops. * * <noncompliant> * val strs = listOf("foo, bar") * for (str in strs) { * if (str == "bar") { * break * } else { * continue * } * } * </noncompliant> * * @configuration maxJumpCount - maximum allowed jumps in a loop (default: `1`) * * @active since v1.2.0 */ class LoopWithTooManyJumpStatements(config: Config = Config.empty) : Rule(config) { override val issue = Issue(javaClass.simpleName, Severity.Style, "The loop contains more than one break or continue statement. " + "The code should be refactored to increase readability.", Debt.TEN_MINS) private val maxJumpCount = valueOrDefault(MAX_JUMP_COUNT, 1) override fun visitLoopExpression(loopExpression: KtLoopExpression) { if (countBreakAndReturnStatements(loopExpression.body) > maxJumpCount) { report(CodeSmell(issue, Entity.from(loopExpression), issue.description)) } super.visitLoopExpression(loopExpression) } private fun countBreakAndReturnStatements(body: KtExpression?) = body?.countBreakAndReturnStatementsInLoop() ?: 0 private fun KtElement.countBreakAndReturnStatementsInLoop(): Int { var count = 0 this.accept(object : DetektVisitor() { override fun visitKtElement(element: KtElement) { if (element is KtLoopExpression) { return } if (element is KtBreakExpression || element is KtContinueExpression) { count++ } element.children.forEach { it.accept(this) } } }) return count } companion object { const val MAX_JUMP_COUNT = "maxJumpCount" } }
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/LoopWithTooManyJumpStatements.kt
33934046
package uk.co.craigbass.pratura.http import org.jetbrains.ktor.host.* import org.jetbrains.ktor.netty.Netty import org.jetbrains.ktor.response.respondText import org.jetbrains.ktor.routing.* import java.util.concurrent.TimeUnit class WebServer { private val controllers: MutableList<Controller> = mutableListOf() private val server: ApplicationHost = embeddedServer(Netty, 8080) { routing { controllers.forEach { controller -> post(controller.path) { call.request .receiveContent() .inputStream() .bufferedReader() .use { call.respondText(controller.execute(it.readText())) } } } } } fun start() { server.start() } fun stop() { server.stop(0, 0, TimeUnit.SECONDS) } fun addController(controller: Controller) { controllers.add(controller) } interface Controller { val path: String fun execute(requestBody: String): String } }
src/main/kotlin/uk/co/craigbass/pratura/http/WebServer.kt
1904263518
/* * Copyright 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. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package org.jetbrains.anko import android.app.Fragment import android.content.Context import android.content.DialogInterface typealias AlertBuilderFactory<D> = (Context) -> AlertBuilder<D> inline fun <D : DialogInterface> AnkoContext<*>.alert( noinline factory: AlertBuilderFactory<D>, message: String, title: String? = null, noinline init: (AlertBuilder<D>.() -> Unit)? = null ) = ctx.alert(factory, message, title, init) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun <D : DialogInterface> Fragment.alert( noinline factory: AlertBuilderFactory<D>, message: String, title: String? = null, noinline init: (AlertBuilder<D>.() -> Unit)? = null ) = activity.alert(factory, message, title, init) fun <D : DialogInterface> Context.alert( factory: AlertBuilderFactory<D>, message: String, title: String? = null, init: (AlertBuilder<D>.() -> Unit)? = null ): AlertBuilder<D> { return factory(this).apply { if (title != null) { this.title = title } this.message = message if (init != null) init() } } inline fun <D : DialogInterface> AnkoContext<*>.alert( noinline factory: AlertBuilderFactory<D>, message: Int, title: Int? = null, noinline init: (AlertBuilder<D>.() -> Unit)? = null ) = ctx.alert(factory, message, title, init) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun <D : DialogInterface> Fragment.alert( noinline factory: AlertBuilderFactory<D>, message: Int, title: Int? = null, noinline init: (AlertBuilder<D>.() -> Unit)? = null ) = activity.alert(factory, message, title, init) fun <D : DialogInterface> Context.alert( factory: AlertBuilderFactory<D>, messageResource: Int, titleResource: Int? = null, init: (AlertBuilder<D>.() -> Unit)? = null ): AlertBuilder<D> { return factory(this).apply { if (titleResource != null) { this.titleResource = titleResource } this.messageResource = messageResource if (init != null) init() } } inline fun <D : DialogInterface> AnkoContext<*>.alert( noinline factory: AlertBuilderFactory<D>, noinline init: AlertBuilder<D>.() -> Unit ) = ctx.alert(factory, init) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun <D : DialogInterface> Fragment.alert( noinline factory: AlertBuilderFactory<D>, noinline init: AlertBuilder<D>.() -> Unit ) = activity.alert(factory, init) fun <D : DialogInterface> Context.alert( factory: AlertBuilderFactory<D>, init: AlertBuilder<D>.() -> Unit ): AlertBuilder<D> = factory(this).apply { init() }
anko/library/static/commons/src/main/java/dialogs/Dialogs.kt
289849627
package de.westnordost.streetcomplete.quests.toilet_availability import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN import de.westnordost.streetcomplete.ktx.toYesNo import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment class AddToiletAvailability : OsmFilterQuestType<Boolean>() { // only for malls, big stores and rest areas because users should not need to go inside a non-public // place to solve the quest. (Considering malls and department stores public enough) override val elementFilter = """ nodes, ways with ( (shop ~ mall|department_store and name) or highway ~ services|rest_area ) and !toilets """ override val commitMessage = "Add toilet availability" override val wikiLink = "Key:toilets" override val icon = R.drawable.ic_quest_toilets override val questTypeAchievements = listOf(CITIZEN) override fun getTitle(tags: Map<String, String>) = if (tags["highway"] == "rest_area" || tags["highway"] == "services") R.string.quest_toiletAvailability_rest_area_title else R.string.quest_toiletAvailability_name_title override fun createForm() = YesNoQuestAnswerFragment() override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { changes.add("toilets", answer.toYesNo()) } }
app/src/main/java/de/westnordost/streetcomplete/quests/toilet_availability/AddToiletAvailability.kt
3308941691
package coursework.kiulian.com.freerealestate.view.activities import android.Manifest import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Rect import android.os.Bundle import android.provider.MediaStore import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.widget.ArrayAdapter import android.widget.TextView import com.raizlabs.android.dbflow.kotlinextensions.* import coursework.kiulian.com.freerealestate.* import coursework.kiulian.com.freerealestate.R import coursework.kiulian.com.freerealestate.model.dbmodels.* import coursework.kiulian.com.freerealestate.view.custom.RoundedDrawable import coursework.kiulian.com.freerealestate.view.dialogs.DatePickDialog import coursework.kiulian.com.freerealestate.view.dialogs.ImagePickDialog import kotlinx.android.synthetic.main.activity_create_adv.* import org.parceler.Parcels import java.util.* import java.util.concurrent.ThreadLocalRandom class CreateAdvActivity : AppCompatActivity(), ImagePickDialog.OnAvatarPickListener { lateinit private var datePicker: DatePickDialog private var addedDates: ArrayList<Date> = arrayListOf() private var adv: AdvEntity? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_create_adv) toolbar.title = "Create advertisement" setSupportActionBar(toolbar) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) prepareViews() adv = Parcels.unwrap<AdvEntity>(intent.extras?.getParcelable(AdvEntity::class.java.simpleName)) loadEntities() setViews(adv) } private fun loadEntities() { adv?.load() adv?.let { it.contacts?.load() it.region?.load() it.house?.load() it.house?.facility?.load() it.house?.price?.load() } } private fun prepareViews() { val rect = Rect(0, 0, 1, 1) val image = Bitmap.createBitmap(rect.width(), rect.height(), Bitmap.Config.ARGB_8888) image.eraseColor(resources.getColor(R.color.grey_400)) val drawable = RoundedDrawable(image, 15, 0, RoundedDrawable.Type.centerCrop) adv_image.setImageDrawable(drawable) val types = arrayOf("Single room", "Flat", "House") val adapter_types = ArrayAdapter(this, android.R.layout.simple_spinner_item, types) adapter_types.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner_type.adapter = adapter_types val foods = arrayOf("Not provided", "Breakfast+Dinner", "3 times", "All inclusive") val adapter_foods = ArrayAdapter(this, android.R.layout.simple_spinner_item, foods) adapter_foods.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner_food.adapter = adapter_foods val districts = arrayOf("Center", "Sleeping district", "Suburb", "Countryside") val adapter_districts = ArrayAdapter(this, android.R.layout.simple_spinner_item, districts) adapter_districts.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner_district.adapter = adapter_districts val discounts = arrayOf("No discounts", "1 month+", "2 months+", "3 months+") val adapter_discounts = ArrayAdapter(this, android.R.layout.simple_spinner_item, discounts) adapter_discounts.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner_discount.adapter = adapter_discounts val payments = arrayOf("Cash", "Credit card", "PayPal", "Any") val adapter_payments = ArrayAdapter(this, android.R.layout.simple_spinner_item, payments) adapter_payments.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner_payment.adapter = adapter_payments house_text.setOnTouchListener { v, event -> if (v.id == R.id.house_text && house_text.lineCount > 3) { v.parent.requestDisallowInterceptTouchEvent(true) when (event.action and MotionEvent.ACTION_MASK) { MotionEvent.ACTION_UP -> v.parent.requestDisallowInterceptTouchEvent(false) } } false } upload_btn.setOnClickListener { ImagePickDialog(this) } datePicker = DatePickDialog.getInstance(addedDates) datePicker.setOnDateRangeListener(object : DatePickDialog.OnDateRangeListener { override fun onDateRangePicker(dates: List<Date>) { addedDates.addAll(dates) addDates(dates) } }) add_btn.setOnClickListener { datePicker.show(supportFragmentManager, "DatePicker") } } private fun setViews(adv: AdvEntity?) { if (adv == null) return adv.image?.let { adv_image.setImageBitmap(it) } toolbar.title = "Edit advertisement" adv_title.setText(adv.title) house_text.setText(adv.house.text) house_beds.setText(adv.house.beds.toString()) house_guests.setText(adv.house.guests.toString()) house_city.setText(adv.region.city) house_region.setText(adv.region.region) house_address.setText(adv.house.address) house_price.setText(adv.house.price.price.toString()) spinner_type.setSelection(when (adv.house.type) { HouseType.SINGLE_ROOM -> 1 HouseType.FLAT -> 2 HouseType.HOUSE -> 3 else -> 0 }) spinner_food.setSelection(when (adv.house.food) { Food.SELF -> 1 Food.PARTLY -> 2 Food.FULL -> 3 Food.UNLIMITED -> 4 else -> 0 }) spinner_district.setSelection(when (adv.house.district) { District.CENTER -> 1 District.SLEEPING_AREA -> 2 District.SUBURB -> 3 District.COUNTRYSIDE -> 4 else -> 0 }) spinner_discount.setSelection(when (adv.house.price.discount) { Discount.NONE -> 1 Discount.ONE_MONTH -> 2 Discount.TWO_MONTHS -> 3 Discount.THREE_MONTHS -> 4 else -> 0 }) spinner_payment.setSelection(when (adv.house.price.payment) { Payment.CASH -> 1 Payment.CREDIT_CARD -> 2 Payment.PAYPAL -> 3 else -> 0 }) cb_pets.isChecked = adv.house.facility.pets cb_smoking.isChecked = adv.house.facility.smoking // dates addDatesRange(adv.house.myDates) datePicker.datesRanges = adv.house.myDates } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_create_adv, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_done -> { validateInput() } android.R.id.home -> onBackPressed() } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { if (requestCode == ImagePickDialog.TAKE_PHOTO || requestCode == ImagePickDialog.PICK_IMAGE) { val encodedBitmap = getBitmapFromIntent(requestCode, data) encodedBitmap?.let { val drawable = RoundedDrawable(it, 15, 0, RoundedDrawable.Type.centerCrop) adv_image.setImageDrawable(drawable) upload_btn.visibility = View.GONE } } } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (grantResults[0] != PackageManager.PERMISSION_GRANTED) { AlertDialog.Builder(this) .setTitle("Permission needed") .setPositiveButton(android.R.string.ok, null) .show() } else { onMethodSelected(requestCode) } } override fun onMethodSelected(requestCode: Int) { if (requestPermission(requestCode, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA))) { if (requestCode == ImagePickDialog.TAKE_PHOTO) { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) startActivityForResult(intent, ImagePickDialog.TAKE_PHOTO) } else if (requestCode == ImagePickDialog.PICK_IMAGE) { val intent = Intent( Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) intent.type = "image/*" startActivityForResult(Intent.createChooser(intent, "Select File"), ImagePickDialog.PICK_IMAGE) } } } private fun validateInput() { if (house_beds.text.toString().isEmpty() || house_guests.text.toString().isEmpty() || adv_title.text.toString().isEmpty() || house_city.text.toString().isEmpty() || house_region.text.toString().isEmpty() || house_address.text.toString().isEmpty() || house_price.text.toString().isEmpty() || spinner_type.selectedItemPosition < 1) return if (adv == null) createAdvertisement() else updateAdvertisement() } private fun addDates(dates: List<Date>) { val viewGroup = layoutInflater.inflate(R.layout.dates, null) viewGroup.tag = dates viewGroup.findViewById(R.id.close_btn).setOnClickListener { addedDates.removeAll(viewGroup.tag as List<*>) freedates_layout.removeView(it.parent as View) } val from = Calendar.getInstance() from.time = dates[0] val to = Calendar.getInstance() to.time = dates[dates.size - 1] (viewGroup.findViewById(R.id.date_arrival) as TextView) .text = "${from?.get(Calendar.MONTH)}.${from?.get(Calendar.DAY_OF_MONTH)}.${from?.get(Calendar.YEAR)}" (viewGroup.findViewById(R.id.date_leaving) as TextView) .text = "${to?.get(Calendar.MONTH)}.${to?.get(Calendar.DAY_OF_MONTH)}.${to?.get(Calendar.YEAR)}" freedates_layout.addView(viewGroup) } private fun addDatesRange(dateRagnges: List<DateEntity>) { for (range in dateRagnges) { val viewGroup = layoutInflater.inflate(R.layout.dates, null) viewGroup.tag = range viewGroup.findViewById(R.id.close_btn).setOnClickListener { val date = viewGroup.tag as DateEntity adv?.house?.myDates?.remove(date) val deleted = date.delete() Log.i("DELETED", "$deleted") freedates_layout.removeView(it.parent as View) } val from = Calendar.getInstance() from.time = range.start val to = Calendar.getInstance() to.time = range.end (viewGroup.findViewById(R.id.date_arrival) as TextView) .text = "${from?.get(Calendar.MONTH)}.${from?.get(Calendar.DAY_OF_MONTH)}.${from?.get(Calendar.YEAR)}" (viewGroup.findViewById(R.id.date_leaving) as TextView) .text = "${to?.get(Calendar.MONTH)}.${to?.get(Calendar.DAY_OF_MONTH)}.${to?.get(Calendar.YEAR)}" freedates_layout.addView(viewGroup) } } private fun getDateRanges(house: HouseEntity): ArrayList<DateEntity> { val dateRanges: ArrayList<DateEntity> = arrayListOf() var i = 0 while (i < addedDates.size - 1) { val dateRange = DateEntity() dateRange.house = house dateRange.start = Date(addedDates[i].time) do { i++ val temp1 = Calendar.getInstance() temp1.time = addedDates[i - 1] temp1.add(Calendar.DAY_OF_MONTH, 1) val temp2 = Calendar.getInstance() temp2.time = addedDates[i] if (i == addedDates.size - 1) { dateRange.end = Date(addedDates[i].time) dateRanges.add(dateRange) return dateRanges } } while (temp1.time == temp2.time) dateRange.end = Date(addedDates[i - 1].time) dateRanges.add(dateRange) } return dateRanges } // TODO: replace to AdvModule private fun updateAdvertisement() { adv?.house?.price?.apply { price = house_price.text.toString().toInt() payment = when (spinner_payment.selectedItemPosition) { 1 -> Payment.CASH 2 -> Payment.CREDIT_CARD 3 -> Payment.PAYPAL else -> Payment.ANY } discount = when (spinner_discount.selectedItemPosition) { 2 -> Discount.ONE_MONTH 3 -> Discount.TWO_MONTHS 4 -> Discount.THREE_MONTHS else -> Discount.NONE } } adv?.house?.price?.async()?.update() adv?.region?.apply { city = house_city.text.toString().trim() region = house_region.text.toString().trim() cityCode = ThreadLocalRandom.current().nextInt(100, 1000).toString() } adv?.region?.async()?.update() adv?.house?.facility?.apply { pets = cb_pets.isChecked smoking = cb_smoking.isChecked } adv?.house?.facility?.async()?.update() adv?.house?.apply { type = when (spinner_type.selectedItemPosition) { 1 -> HouseType.SINGLE_ROOM 2 -> HouseType.FLAT 3 -> HouseType.HOUSE else -> null } address = house_address.text.toString().trim() text = house_text.text.toString().trim() guests = house_guests.text.toString().toInt() beds = house_beds.text.toString().toInt() food = when (spinner_food.selectedItemPosition) { 2 -> Food.PARTLY 3 -> Food.FULL 4 -> Food.UNLIMITED else -> Food.SELF } district = when (spinner_district.selectedItemPosition) { 1 -> District.CENTER 2 -> District.SLEEPING_AREA 3 -> District.SUBURB 4 -> District.COUNTRYSIDE else -> District.UNKNOWN } val dates = getDateRanges(this) dates.forEach { it.save() } } adv?.house?.async()?.update() adv?.apply { title = adv_title.text.toString().trim() if (upload_btn.visibility == View.GONE) image = (adv_image.drawable as? RoundedDrawable)?.bitmap } adv?.async()?.update { //TODO: EventBus setResult(Activity.RESULT_OK) finish() } } private fun createAdvertisement() { val prefs = getSharedPreferences(USER_PREF, Context.MODE_PRIVATE) val id = prefs.getInt(USER_ID, -1) val contactsModel = select.from(ContactsEntity::class) .where(ContactsEntity_Table.id.eq(id)) .list[0] val priceModel = PriceEntity().apply { price = house_price.text.toString().toInt() payment = when (spinner_payment.selectedItemPosition) { 1 -> Payment.CASH 2 -> Payment.CREDIT_CARD 3 -> Payment.PAYPAL else -> Payment.ANY } discount = when (spinner_discount.selectedItemPosition) { 2 -> Discount.ONE_MONTH 3 -> Discount.TWO_MONTHS 4 -> Discount.THREE_MONTHS else -> Discount.NONE } } priceModel.async().save { val regionModel = RegionEntity().apply { city = house_city.text.toString().trim() region = house_region.text.toString().trim() cityCode = ThreadLocalRandom.current().nextInt(100, 1000).toString() } regionModel.async().save { val facilityModel = FacilityEntity().apply { pets = cb_pets.isChecked smoking = cb_smoking.isChecked } facilityModel.async().save { val houseModel = HouseEntity().apply { type = when (spinner_type.selectedItemPosition) { 1 -> HouseType.SINGLE_ROOM 2 -> HouseType.FLAT 3 -> HouseType.HOUSE else -> null } address = house_address.text.toString().trim() text = house_text.text.toString().trim() guests = house_guests.text.toString().toInt() beds = house_beds.text.toString().toInt() food = when (spinner_food.selectedItemPosition) { 2 -> Food.PARTLY 3 -> Food.FULL 4 -> Food.UNLIMITED else -> Food.SELF } district = when (spinner_district.selectedItemPosition) { 1 -> District.CENTER 2 -> District.SLEEPING_AREA 3 -> District.SUBURB 4 -> District.COUNTRYSIDE else -> District.UNKNOWN } price = priceModel facility = facilityModel freeDates = getDateRanges(this) } houseModel.async().save { val adv = AdvEntity().apply { title = adv_title.text.toString().trim() contacts = contactsModel house = houseModel createdAt = Calendar.getInstance().time region = regionModel if (upload_btn.visibility == View.GONE) image = (adv_image.drawable as? RoundedDrawable)?.bitmap } adv.async().save { //TODO: EventBus setResult(Activity.RESULT_OK) finish() } } } } } } }
app/src/main/java/coursework/kiulian/com/freerealestate/view/activities/CreateAdvActivity.kt
819390266
package org.wordpress.android.fluxc.list import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import org.junit.Before import org.junit.Test import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId import org.wordpress.android.fluxc.model.list.datasource.InternalPagedListDataSource import org.wordpress.android.fluxc.model.list.datasource.ListItemDataSourceInterface import kotlin.test.assertEquals private const val NUMBER_OF_ITEMS = 71 private const val IS_LIST_FULLY_FETCHED = false private val testListDescriptor = TestListDescriptor() private val testStartAndEndPosition = Pair(5, 10) internal class InternalPagedListDataSourceTest { private val remoteItemIds = mock<List<RemoteId>>() private val mockIdentifiers = mock<List<TestListIdentifier>>() private val mockItemDataSource = mock<ListItemDataSourceInterface<TestListDescriptor, TestListIdentifier, String>>() @Before fun setup() { whenever(remoteItemIds.size).thenReturn(NUMBER_OF_ITEMS) whenever(mockIdentifiers.size).thenReturn(NUMBER_OF_ITEMS) val mockSublist = mock<List<TestListIdentifier>>() whenever(mockIdentifiers.subList(any(), any())).thenReturn(mockSublist) whenever( mockItemDataSource.getItemIdentifiers( listDescriptor = testListDescriptor, remoteItemIds = remoteItemIds, isListFullyFetched = IS_LIST_FULLY_FETCHED ) ).thenReturn(mockIdentifiers) } /** * Tests that item identifiers are cached when a new instance of [InternalPagedListDataSource] is created. * * Caching the item identifiers is how we ensure that this component will provide consistent data to * `PositionalDataSource` so it's very important that we have this test. Since we don't have access to * `InternalPagedListDataSource.itemIdentifiers` private property, we have to test the internal implementation * which is more likely to break. However, in this specific case, we DO want the test to break if the internal * implementation changes. */ @Test fun `init calls getItemIdentifiers`() { createInternalPagedListDataSource(mockItemDataSource) verify(mockItemDataSource).getItemIdentifiers(eq(testListDescriptor), any(), any()) } @Test fun `total size uses getItemIdentifiers' size`() { val internalDataSource = createInternalPagedListDataSource(mockItemDataSource) assertEquals( NUMBER_OF_ITEMS, internalDataSource.totalSize, "InternalPagedListDataSource should not change the" + "number of items in a list and should propagate that to its ListItemDataSourceInterface" ) } @Test fun `getItemsInRange creates the correct sublist of the identifiers`() { val internalDataSource = createInternalPagedListDataSource(mockItemDataSource) val (startPosition, endPosition) = testStartAndEndPosition internalDataSource.getItemsInRange(startPosition, endPosition) verify(mockIdentifiers).subList(startPosition, endPosition) } @Test fun `getItemsInRange propagates the call to getItemsAndFetchIfNecessary correctly`() { val internalDataSource = createInternalPagedListDataSource(dataSource = mockItemDataSource) val (startPosition, endPosition) = testStartAndEndPosition internalDataSource.getItemsInRange(startPosition, endPosition) verify(mockItemDataSource).getItemsAndFetchIfNecessary(eq(testListDescriptor), any()) } private fun createInternalPagedListDataSource( dataSource: TestListItemDataSource ): TestInternalPagedListDataSource { return InternalPagedListDataSource( listDescriptor = testListDescriptor, remoteItemIds = remoteItemIds, isListFullyFetched = IS_LIST_FULLY_FETCHED, itemDataSource = dataSource ) } }
example/src/test/java/org/wordpress/android/fluxc/list/InternalPagedListDataSourceTest.kt
1180289380
package com.boardgamegeek.entities data class GamePollEntity(val results: List<GamePollResultEntity>) { val modalValue: String by lazy { results.maxByOrNull { it.numberOfVotes }?.value ?: "" } val totalVotes: Int by lazy { results.sumOf { it.numberOfVotes } } fun calculateScore(): Double { if (totalVotes == 0) return 0.0 val totalLevel = results.sumOf { it.numberOfVotes * ((it.level - 1) % 5 + 1) } return totalLevel.toDouble() / totalVotes } }
app/src/main/java/com/boardgamegeek/entities/GamePollEntity.kt
901911224
package ii_collections import java.util.* /* * This part of workshop was inspired by: * https://github.com/goldmansachs/gs-collections-kata */ /* * There are many operations that help to transform one collection into another, starting with 'to' */ fun example0(list: List<Int>) { list.toSet() list.toCollection(HashSet()) } fun Shop.getSetOfCustomers(): Set<Customer> { return this.customers.toSet() }
Others/Kotlin/kotlin-koans/src/ii_collections/n13Introduction.kt
962162251
/* * Copyright (C) 2018 Tobias Raatiniemi * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.raatiniemi.worker.domain.repository import me.raatiniemi.worker.domain.model.Project import me.raatiniemi.worker.domain.model.TimeInterval import me.raatiniemi.worker.util.Optional import java.util.concurrent.atomic.AtomicLong class TimeIntervalInMemoryRepository : TimeIntervalRepository { private val incrementedId = AtomicLong() private val timeIntervals = mutableListOf<TimeInterval>() override fun findAll(project: Project, milliseconds: Long): List<TimeInterval> { return timeIntervals.filter { it.projectId == project.id && it.startInMilliseconds >= milliseconds } } override fun findById(id: Long): Optional<TimeInterval> { val timeInterval = timeIntervals.firstOrNull { it.id == id } return Optional.ofNullable(timeInterval) } override fun findActiveByProjectId(projectId: Long): Optional<TimeInterval> { val timeInterval = timeIntervals.firstOrNull { it.projectId == projectId && it.isActive } return Optional.ofNullable(timeInterval) } override fun add(timeInterval: TimeInterval): Optional<TimeInterval> { val id = incrementedId.incrementAndGet() val value = timeInterval.copy(id = id) timeIntervals.add(value) return Optional.of(value) } override fun update(timeInterval: TimeInterval): Optional<TimeInterval> { val existingTimeInterval = timeIntervals.firstOrNull { it.id == timeInterval.id } ?: return Optional.empty() val index = timeIntervals.indexOf(existingTimeInterval) timeIntervals[index] = timeInterval return Optional.of(timeInterval) } override fun update(timeIntervals: List<TimeInterval>): List<TimeInterval> { return timeIntervals.filter { existingTimeInterval(it) } .map { update(it) } .filter { it.isPresent } .map { it.get() } } private fun existingTimeInterval(timeInterval: TimeInterval): Boolean { val id = timeInterval.id ?: return false return findById(id).isPresent } override fun remove(id: Long) { timeIntervals.removeIf { it.id == id } } override fun remove(timeIntervals: List<TimeInterval>) { timeIntervals.mapNotNull { it.id } .forEach { remove(it) } } }
core-test/src/main/java/me/raatiniemi/worker/domain/repository/TimeIntervalInMemoryRepository.kt
3333431132
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.loadtest.frontend import org.wfanet.measurement.common.commandLineMain import org.wfanet.measurement.storage.forwarded.ForwardedStorageFromFlags import picocli.CommandLine /** Implementation of [FrontendSimulatorRunner] using Fake Storage Service. */ @CommandLine.Command( name = "ForwardedStorageFrontendSimulatorRunnerDaemon", description = ["Daemon for ForwardedStorageFrontendSimulatorRunner."], mixinStandardHelpOptions = true, showDefaultValues = true ) class ForwardedStorageFrontendSimulatorRunner : FrontendSimulatorRunner() { @CommandLine.Mixin private lateinit var forwardedStorageFlags: ForwardedStorageFromFlags.Flags override fun run() { run(ForwardedStorageFromFlags(forwardedStorageFlags, flags.tlsFlags).storageClient) } } fun main(args: Array<String>) = commandLineMain(ForwardedStorageFrontendSimulatorRunner(), args)
src/main/kotlin/org/wfanet/measurement/loadtest/frontend/ForwardedStorageFrontendSimulatorRunner.kt
3500173684
/* * Copyright (C) 2017 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.provider.helper import android.content.ContentValues import android.content.Context import android.database.Cursor import net.simonvt.cathode.api.entity.Show import net.simonvt.cathode.common.database.DatabaseUtils import net.simonvt.cathode.common.database.getBoolean import net.simonvt.cathode.common.database.getInt import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.common.util.TextUtils import net.simonvt.cathode.provider.DatabaseContract import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns import net.simonvt.cathode.provider.DatabaseContract.ShowColumns import net.simonvt.cathode.provider.ProviderSchematic import net.simonvt.cathode.provider.ProviderSchematic.Episodes import net.simonvt.cathode.provider.ProviderSchematic.Shows import net.simonvt.cathode.provider.query import net.simonvt.cathode.provider.update import net.simonvt.cathode.settings.FirstAiredOffsetPreference import javax.inject.Inject import javax.inject.Singleton @Singleton class ShowDatabaseHelper @Inject constructor(private val context: Context) { fun getId(traktId: Long): Long { synchronized(LOCK_ID) { val c = context.contentResolver.query( Shows.SHOWS, arrayOf(ShowColumns.ID), ShowColumns.TRAKT_ID + "=?", arrayOf(traktId.toString()) ) val id = if (c.moveToFirst()) c.getLong(ShowColumns.ID) else -1L c.close() return id } } fun getIdFromTmdb(tmdbId: Int): Long { synchronized(LOCK_ID) { val c = context.contentResolver.query( Shows.SHOWS, arrayOf(ShowColumns.ID), ShowColumns.TMDB_ID + "=?", arrayOf(tmdbId.toString()) ) val id = if (c.moveToFirst()) c.getLong(ShowColumns.ID) else -1L c.close() return id } } fun getTraktId(showId: Long): Long { val c = context.contentResolver.query( Shows.withId(showId), arrayOf(ShowColumns.TRAKT_ID) ) val traktId = if (c.moveToFirst()) c.getLong(ShowColumns.TRAKT_ID) else -1L c.close() return traktId } fun getTmdbId(showId: Long): Int { val c = context.contentResolver.query( Shows.withId(showId), arrayOf(ShowColumns.TMDB_ID) ) val tmdbId = if (c.moveToFirst()) c.getInt(ShowColumns.TMDB_ID) else -1 c.close() return tmdbId } class IdResult(var showId: Long, var didCreate: Boolean) fun getIdOrCreate(traktId: Long): IdResult { synchronized(LOCK_ID) { var id = getId(traktId) if (id == -1L) { id = create(traktId) return IdResult(id, true) } else { return IdResult(id, false) } } } private fun create(traktId: Long): Long { val values = ContentValues() values.put(ShowColumns.TRAKT_ID, traktId) values.put(ShowColumns.NEEDS_SYNC, true) return Shows.getShowId(context.contentResolver.insert(Shows.SHOWS, values)!!) } fun fullUpdate(show: Show): Long { val result = getIdOrCreate(show.ids.trakt!!) val id = result.showId val values = getValues(show) values.put(ShowColumns.NEEDS_SYNC, false) values.put(ShowColumns.LAST_SYNC, System.currentTimeMillis()) context.contentResolver.update(Shows.withId(id), values) if (show.genres != null) { insertShowGenres(id, show.genres!!) } return id } /** * Creates the show if it does not exist. */ fun partialUpdate(show: Show): Long { val result = getIdOrCreate(show.ids.trakt!!) val id = result.showId val values = getPartialValues(show) context.contentResolver.update(Shows.withId(id), values) if (show.genres != null) { insertShowGenres(id, show.genres!!) } return id } fun getNextEpisodeId(showId: Long): Long { var lastWatchedSeason = -1 var lastWatchedEpisode = -1 val lastWatchedCursor = context.contentResolver.query( Episodes.fromShow(showId), arrayOf(EpisodeColumns.ID, EpisodeColumns.SEASON, EpisodeColumns.EPISODE), EpisodeColumns.WATCHED + "=1", null, EpisodeColumns.SEASON + " DESC, " + EpisodeColumns.EPISODE + " DESC LIMIT 1" ) if (lastWatchedCursor!!.moveToFirst()) { lastWatchedSeason = lastWatchedCursor.getInt(EpisodeColumns.SEASON) lastWatchedEpisode = lastWatchedCursor.getInt(EpisodeColumns.EPISODE) } lastWatchedCursor.close() val nextEpisode = context.contentResolver.query( Episodes.fromShow(showId), arrayOf(EpisodeColumns.ID), EpisodeColumns.SEASON + ">0 AND (" + EpisodeColumns.SEASON + ">? OR (" + EpisodeColumns.SEASON + "=? AND " + EpisodeColumns.EPISODE + ">?)) AND " + EpisodeColumns.FIRST_AIRED + " NOT NULL", arrayOf( lastWatchedSeason.toString(), lastWatchedSeason.toString(), lastWatchedEpisode.toString() ), EpisodeColumns.SEASON + " ASC, " + EpisodeColumns.EPISODE + " ASC LIMIT 1" ) var nextEpisodeId = -1L if (nextEpisode!!.moveToFirst()) { nextEpisodeId = nextEpisode.getLong(EpisodeColumns.ID) } nextEpisode.close() return nextEpisodeId } fun needsSync(showId: Long): Boolean { var show: Cursor? = null try { show = context.contentResolver.query( Shows.withId(showId), arrayOf(ShowColumns.NEEDS_SYNC) ) return if (show.moveToFirst()) show.getBoolean(ShowColumns.NEEDS_SYNC) else false } finally { show?.close() } } fun lastSync(showId: Long): Long { var show: Cursor? = null try { show = context.contentResolver.query( Shows.withId(showId), arrayOf(ShowColumns.LAST_SYNC) ) return if (show.moveToFirst()) show.getLong(ShowColumns.LAST_SYNC) else 0L } finally { show?.close() } } fun markPending(showId: Long) { val values = ContentValues() values.put(ShowColumns.NEEDS_SYNC, true) context.contentResolver.update(Shows.withId(showId), values, null, null) } fun isUpdated(traktId: Long, lastUpdated: Long): Boolean { var show: Cursor? = null try { show = context.contentResolver.query( Shows.SHOWS, arrayOf(ShowColumns.LAST_UPDATED), ShowColumns.TRAKT_ID + "=?", arrayOf(traktId.toString()) ) if (show.moveToFirst()) { val showLastUpdated = show.getLong(ShowColumns.LAST_UPDATED) return lastUpdated > showLastUpdated } return false } finally { show?.close() } } private fun insertShowGenres(showId: Long, genres: List<String>) { context.contentResolver.delete(ProviderSchematic.ShowGenres.fromShow(showId), null, null) for (genre in genres) { val values = ContentValues() values.put(DatabaseContract.ShowGenreColumns.SHOW_ID, showId) values.put(DatabaseContract.ShowGenreColumns.GENRE, TextUtils.upperCaseFirstLetter(genre)) context.contentResolver.insert(ProviderSchematic.ShowGenres.fromShow(showId), values) } } fun addToHistory(showId: Long, watchedAt: Long) { val values = ContentValues() values.put(EpisodeColumns.WATCHED, true) val firstAiredOffset = FirstAiredOffsetPreference.getInstance().offsetMillis val millis = System.currentTimeMillis() - firstAiredOffset context.contentResolver.update( Episodes.fromShow(showId), values, EpisodeColumns.FIRST_AIRED + "<?", arrayOf(millis.toString()) ) if (watchedAt == WATCHED_RELEASE) { values.clear() val episodes = context.contentResolver.query( Episodes.fromShow(showId), arrayOf(EpisodeColumns.ID, EpisodeColumns.FIRST_AIRED), EpisodeColumns.WATCHED + " AND " + EpisodeColumns.FIRST_AIRED + ">" + EpisodeColumns.LAST_WATCHED_AT ) while (episodes.moveToNext()) { val episodeId = episodes.getLong(EpisodeColumns.ID) val firstAired = episodes.getLong(EpisodeColumns.FIRST_AIRED) values.put(EpisodeColumns.LAST_WATCHED_AT, firstAired) context.contentResolver.update(Episodes.withId(episodeId), values, null, null) } episodes.close() } else { values.clear() values.put(EpisodeColumns.LAST_WATCHED_AT, watchedAt) context.contentResolver.update( Episodes.fromShow(showId), values, EpisodeColumns.WATCHED + " AND " + EpisodeColumns.LAST_WATCHED_AT + "<?", arrayOf(watchedAt.toString()) ) } } fun removeFromHistory(showId: Long) { val values = ContentValues() values.put(EpisodeColumns.WATCHED, false) values.put(EpisodeColumns.LAST_WATCHED_AT, 0) context.contentResolver.update(Episodes.fromShow(showId), null, null, null) } @JvmOverloads fun setIsInWatchlist(showId: Long, inWatchlist: Boolean, listedAt: Long = 0) { val values = ContentValues() values.put(ShowColumns.IN_WATCHLIST, inWatchlist) values.put(ShowColumns.LISTED_AT, listedAt) context.contentResolver.update(Shows.withId(showId), values, null, null) } fun setIsInCollection(traktId: Long, inCollection: Boolean) { val showId = getId(traktId) val values = ContentValues() values.put(EpisodeColumns.IN_COLLECTION, inCollection) val firstAiredOffset = FirstAiredOffsetPreference.getInstance().offsetMillis val millis = System.currentTimeMillis() - firstAiredOffset context.contentResolver.update( Episodes.fromShow(showId), values, EpisodeColumns.FIRST_AIRED + "<?", arrayOf(millis.toString()) ) } private fun getPartialValues(show: Show): ContentValues { val values = ContentValues() values.put(ShowColumns.TITLE, show.title) values.put(ShowColumns.TITLE_NO_ARTICLE, DatabaseUtils.removeLeadingArticle(show.title)) values.put(ShowColumns.TRAKT_ID, show.ids.trakt) values.put(ShowColumns.SLUG, show.ids.slug) values.put(ShowColumns.IMDB_ID, show.ids.imdb) values.put(ShowColumns.TVDB_ID, show.ids.tvdb) values.put(ShowColumns.TMDB_ID, show.ids.tmdb) values.put(ShowColumns.TVRAGE_ID, show.ids.tvrage) return values } private fun getValues(show: Show): ContentValues { val values = ContentValues() values.put(ShowColumns.TITLE, show.title) values.put(ShowColumns.TITLE_NO_ARTICLE, DatabaseUtils.removeLeadingArticle(show.title)) values.put(ShowColumns.YEAR, show.year) values.put(ShowColumns.FIRST_AIRED, show.first_aired?.timeInMillis) values.put(ShowColumns.COUNTRY, show.country) values.put(ShowColumns.OVERVIEW, show.overview) values.put(ShowColumns.RUNTIME, show.runtime) values.put(ShowColumns.NETWORK, show.network) values.put(ShowColumns.AIR_DAY, show.airs?.day) values.put(ShowColumns.AIR_TIME, show.airs?.time) values.put(ShowColumns.AIR_TIMEZONE, show.airs?.timezone) values.put(ShowColumns.CERTIFICATION, show.certification) values.put(ShowColumns.TRAILER, show.trailer) values.put(ShowColumns.HOMEPAGE, show.homepage) values.put(ShowColumns.STATUS, show.status?.toString()) values.put(ShowColumns.TRAKT_ID, show.ids.trakt) values.put(ShowColumns.SLUG, show.ids.slug) values.put(ShowColumns.IMDB_ID, show.ids.imdb) values.put(ShowColumns.TVDB_ID, show.ids.tvdb) values.put(ShowColumns.TMDB_ID, show.ids.tmdb) values.put(ShowColumns.TVRAGE_ID, show.ids.tvrage) values.put(ShowColumns.LAST_UPDATED, show.updated_at?.timeInMillis) values.put(ShowColumns.RATING, show.rating) values.put(ShowColumns.VOTES, show.votes) return values } companion object { const val WATCHED_RELEASE = -1L private val LOCK_ID = Any() } }
cathode-provider/src/main/java/net/simonvt/cathode/provider/helper/ShowDatabaseHelper.kt
1334469953
package nl.hannahsten.texifyidea.structure.latex import com.intellij.navigation.ItemPresentation import nl.hannahsten.texifyidea.TexifyIcons import nl.hannahsten.texifyidea.psi.LatexCommands class LatexPairedDelimiterPresentation(newCommand: LatexCommands) : ItemPresentation { private val newCommandName: String private val locationString: String init { // Get command name. val required = newCommand.requiredParameters newCommandName = if (required.size > 0) { required.first() } else "" locationString = if (required.size >= 3) { when (newCommand.name) { "\\DeclarePairedDelimiterXPP" -> (1..4).joinToString(" ") { required[it] } else -> "${required[1]} ${required[2]}" } } else "" } override fun getPresentableText() = newCommandName override fun getLocationString() = locationString override fun getIcon(b: Boolean) = TexifyIcons.DOT_COMMAND }
src/nl/hannahsten/texifyidea/structure/latex/LatexPairedDelimiterPresentation.kt
995069291
package com.zhufucdev.pctope.utils import android.view.View import com.zhufucdev.pctope.R import org.json.JSONException import org.json.JSONObject import java.io.File import java.nio.charset.Charset /** * Created by zhufu on 7/30/17. */ class PackVersionDecisions(private val path: File) { var name: String? = null private set var description: String? = null private set init { if (File("$path/manifest.json").exists()) readManifest() } val packVersion: String get() { if (!path.exists()) return "E:file not found." if (path.isDirectory) { val manifest = File("$path/manifest.json") var v = "" v = if (manifest.exists()) { if (name != null && description != null) { if (File("$path/pack_icon.png").exists()) "full" else "broken" } else "broken" } else { if (File("$path/pack.png").exists()) "full" else "broken" } fun check(folder: File): Boolean { if (!folder.exists()) { return false } val list = folder.list() ?: return false if (list.count { it.endsWith(".png") } >= 10) { return true } return false } fun checkIfAny(vararg folders: Pair<String, String>): String { for (pair in folders) { if (check(File(pair.first))) { return "Found:$v ${pair.second} pack." } } return "E:nothing found." } return checkIfAny( "$path/textures/blocks" to "PE", "$path/assets/minecraft/textures/blocks" to "PC", "$path/textures/items" to "PE", "$path/assets/minecraft/textures/items" to "PC" ) } else return "E:File isn't a directory." } fun getIfIsResourcePack(testVersion: String): Boolean { if (path.isDirectory) if (testVersion == "PE" || testVersion == "ALL") { val test = File("$path/textures").listFiles() if (test != null) for (f in test) if (f.isDirectory) return true } if (testVersion == "PC" || testVersion == "ALL") { val test = File("$path/assets/minecraft/textures").listFiles() if (test != null) for (f in test) if (f.isDirectory) return true } return false } fun getInMinecraftVer(v: View): String? { val metaFile = File("$path/pack.mcmeta") if (metaFile.exists()) { val content = metaFile.readText(Charset.defaultCharset()) //Find version code val posStart = content.indexOf(':', content.indexOf("pack_format")) val posEnd = content.indexOf(',', posStart) val startToEnd = content.substring(posStart, posEnd) for (i in startToEnd.indices) { val now = startToEnd[i] if (now.code in 48..57) { return when (now.code - 48) { 1 -> v.resources.getString(R.string.type_before_1_9) 2 -> v.resources.getString(R.string.type_1_9_1_10) 3 -> v.resources.getString(R.string.type_after_1_11) else -> null } } } } return null } private fun readManifest() { val manifest = File("$path/manifest.json") if (manifest.exists()) { val intro = manifest.readText(Charset.defaultCharset()) try { val jsonObjectOut = JSONObject(intro) val jsonObjectIn = jsonObjectOut.getJSONObject("header") name = jsonObjectIn.getString("name") description = jsonObjectIn.getString("description") } catch (e: JSONException) { e.printStackTrace() } } } }
app/src/main/java/com/zhufucdev/pctope/utils/PackVersionDecisions.kt
3945894997
/* * Copyright 2022 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.sample.cast.refplayer import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.cast.framework.CastContext import com.google.android.gms.cast.framework.SessionManagerListener import com.google.android.gms.cast.framework.CastSession import android.view.MenuItem import com.google.android.gms.cast.framework.IntroductoryOverlay import com.google.android.gms.cast.framework.CastStateListener import android.os.Bundle import com.google.android.gms.cast.framework.CastState import android.view.View import android.content.Intent import android.net.Uri import android.os.Handler import android.os.Looper import android.util.Log import android.view.Menu import com.google.android.gms.cast.framework.CastButtonFactory import android.view.KeyEvent import androidx.appcompat.widget.Toolbar import com.google.sample.cast.refplayer.queue.ui.QueueListViewActivity import com.google.sample.cast.refplayer.settings.CastPreference import java.util.concurrent.Executor import java.util.concurrent.ExecutorService import java.util.concurrent.Executors /** * The main activity that displays the list of videos. */ class VideoBrowserActivity : AppCompatActivity() { private var mCastContext: CastContext? = null private val mSessionManagerListener: SessionManagerListener<CastSession> = MySessionManagerListener() private var mCastSession: CastSession? = null private var mediaRouteMenuItem: MenuItem? = null private var mQueueMenuItem: MenuItem? = null private var mToolbar: Toolbar? = null private var mIntroductoryOverlay: IntroductoryOverlay? = null private var mCastStateListener: CastStateListener? = null private val castExecutor: Executor = Executors.newSingleThreadExecutor(); private inner class MySessionManagerListener : SessionManagerListener<CastSession> { override fun onSessionEnded(session: CastSession, error: Int) { if (session === mCastSession) { mCastSession = null } invalidateOptionsMenu() } override fun onSessionResumed(session: CastSession, wasSuspended: Boolean) { mCastSession = session invalidateOptionsMenu() } override fun onSessionStarted(session: CastSession, sessionId: String) { mCastSession = session invalidateOptionsMenu() } override fun onSessionStarting(session: CastSession) {} override fun onSessionStartFailed(session: CastSession, error: Int) {} override fun onSessionEnding(session: CastSession) {} override fun onSessionResuming(session: CastSession, sessionId: String) {} override fun onSessionResumeFailed(session: CastSession, error: Int) {} override fun onSessionSuspended(session: CastSession, reason: Int) {} } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.video_browser) setupActionBar() mCastStateListener = CastStateListener { newState -> if (newState != CastState.NO_DEVICES_AVAILABLE) { showIntroductoryOverlay() } } mCastContext = CastContext.getSharedInstance(this,castExecutor).result } private fun setupActionBar() { mToolbar = findViewById<View>(R.id.toolbar) as Toolbar setSupportActionBar(mToolbar) } private fun intentToJoin() { val intent = intent val intentToJoinUri = Uri.parse("https://castvideos.com/cast/join") Log.i(TAG, "URI passed: $intentToJoinUri") if (intent.data != null && intent.data == intentToJoinUri) { mCastContext!!.sessionManager.startSession(intent) Log.i(TAG, "Uri Joined: $intentToJoinUri") } } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.browse, menu) mediaRouteMenuItem = CastButtonFactory.setUpMediaRouteButton( applicationContext, menu, R.id.media_route_menu_item ) mQueueMenuItem = menu.findItem(R.id.action_show_queue) showIntroductoryOverlay() return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { menu.findItem(R.id.action_show_queue).isVisible = mCastSession != null && mCastSession!!.isConnected return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val intent: Intent if (item.itemId == R.id.action_settings) { intent = Intent(this@VideoBrowserActivity, CastPreference::class.java) startActivity(intent) } else if (item.itemId == R.id.action_show_queue) { intent = Intent(this@VideoBrowserActivity, QueueListViewActivity::class.java) startActivity(intent) } return true } override fun dispatchKeyEvent(event: KeyEvent): Boolean { return (mCastContext!!.onDispatchVolumeKeyEventBeforeJellyBean(event) || super.dispatchKeyEvent(event)) } override fun onResume() { mCastContext!!.addCastStateListener(mCastStateListener!!) mCastContext!!.sessionManager.addSessionManagerListener( mSessionManagerListener, CastSession::class.java ) intentToJoin() if (mCastSession == null) { mCastSession = CastContext.getSharedInstance(this,castExecutor).result.sessionManager .currentCastSession } if (mQueueMenuItem != null) { mQueueMenuItem!!.isVisible = mCastSession != null && mCastSession!!.isConnected } super.onResume() } override fun onPause() { mCastContext!!.removeCastStateListener(mCastStateListener!!) mCastContext!!.sessionManager.removeSessionManagerListener( mSessionManagerListener, CastSession::class.java ) super.onPause() } private fun showIntroductoryOverlay() { if (mIntroductoryOverlay != null) { mIntroductoryOverlay!!.remove() } if (mediaRouteMenuItem != null && mediaRouteMenuItem!!.isVisible) { Handler(Looper.getMainLooper()).post { mIntroductoryOverlay = IntroductoryOverlay.Builder( this@VideoBrowserActivity, mediaRouteMenuItem!! ) .setTitleText(getString(R.string.introducing_cast)) .setOverlayColor(R.color.primary) .setSingleTime() .setOnOverlayDismissedListener { mIntroductoryOverlay = null } .build() mIntroductoryOverlay!!.show() } } } companion object { private const val TAG = "VideoBrowserActivity" } }
app-kotlin/src/main/kotlin/com/google/sample/cast/refplayer/VideoBrowserActivity.kt
4019378064
package voice.settings.views import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.BugReport import androidx.compose.material.icons.outlined.Close import androidx.compose.material.icons.outlined.GridView import androidx.compose.material.icons.outlined.HelpOutline import androidx.compose.material.icons.outlined.Language import androidx.compose.material.icons.outlined.Lightbulb import androidx.compose.material.icons.outlined.ViewList import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.Scaffold import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.squareup.anvil.annotations.ContributesTo import voice.common.AppScope import voice.common.compose.VoiceTheme import voice.common.compose.rememberScoped import voice.common.rootComponentAs import voice.settings.R import voice.settings.SettingsListener import voice.settings.SettingsViewModel import voice.settings.SettingsViewState @Composable @Preview fun SettingsPreview() { val viewState = SettingsViewState( useDarkTheme = false, showDarkThemePref = true, resumeOnReplug = true, seekTimeInSeconds = 42, autoRewindInSeconds = 12, dialog = null, appVersion = "1.2.3", useGrid = true, ) VoiceTheme { Settings( viewState, object : SettingsListener { override fun close() {} override fun toggleResumeOnReplug() {} override fun toggleDarkTheme() {} override fun seekAmountChanged(seconds: Int) {} override fun onSeekAmountRowClicked() {} override fun autoRewindAmountChanged(seconds: Int) {} override fun onAutoRewindRowClicked() {} override fun dismissDialog() {} override fun openTranslations() {} override fun getSupport() {} override fun suggestIdea() {} override fun openBugReport() {} override fun toggleGrid() {} }, ) } } @Composable private fun Settings(viewState: SettingsViewState, listener: SettingsListener) { val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { TopAppBar( scrollBehavior = scrollBehavior, title = { Text(stringResource(R.string.action_settings)) }, navigationIcon = { IconButton( onClick = { listener.close() }, ) { Icon( imageVector = Icons.Outlined.Close, contentDescription = stringResource(R.string.close), ) } }, ) }, ) { contentPadding -> Box(Modifier.padding(contentPadding)) { Column(Modifier.padding(vertical = 8.dp)) { if (viewState.showDarkThemePref) { DarkThemeRow(viewState.useDarkTheme, listener::toggleDarkTheme) } ListItem( modifier = Modifier.clickable { listener.toggleGrid() }, leadingContent = { val imageVector = if (viewState.useGrid) { Icons.Outlined.GridView } else { Icons.Outlined.ViewList } Icon(imageVector, stringResource(R.string.pref_use_grid)) }, headlineText = { Text(stringResource(R.string.pref_use_grid)) }, trailingContent = { Switch( checked = viewState.useGrid, onCheckedChange = { listener.toggleGrid() }, ) }, ) ResumeOnReplugRow(viewState.resumeOnReplug, listener::toggleResumeOnReplug) SeekTimeRow(viewState.seekTimeInSeconds) { listener.onSeekAmountRowClicked() } AutoRewindRow(viewState.autoRewindInSeconds) { listener.onAutoRewindRowClicked() } ListItem( modifier = Modifier.clickable { listener.suggestIdea() }, leadingContent = { Icon(Icons.Outlined.Lightbulb, stringResource(R.string.pref_suggest_idea)) }, headlineText = { Text(stringResource(R.string.pref_suggest_idea)) }, ) ListItem( modifier = Modifier.clickable { listener.getSupport() }, leadingContent = { Icon(Icons.Outlined.HelpOutline, stringResource(R.string.pref_get_support)) }, headlineText = { Text(stringResource(R.string.pref_get_support)) }, ) ListItem( modifier = Modifier.clickable { listener.openBugReport() }, leadingContent = { Icon(Icons.Outlined.BugReport, stringResource(R.string.pref_report_issue)) }, headlineText = { Text(stringResource(R.string.pref_report_issue)) }, ) ListItem( modifier = Modifier.clickable { listener.openTranslations() }, leadingContent = { Icon(Icons.Outlined.Language, stringResource(R.string.pref_help_translating)) }, headlineText = { Text(stringResource(R.string.pref_help_translating)) }, ) AppVersion(appVersion = viewState.appVersion) Dialog(viewState, listener) } } } } @ContributesTo(AppScope::class) interface SettingsComponent { val settingsViewModel: SettingsViewModel } @Composable fun Settings() { val viewModel = rememberScoped { rootComponentAs<SettingsComponent>().settingsViewModel } val viewState = viewModel.viewState() Settings(viewState, viewModel) } @Composable private fun Dialog( viewState: SettingsViewState, listener: SettingsListener, ) { val dialog = viewState.dialog ?: return when (dialog) { SettingsViewState.Dialog.AutoRewindAmount -> { AutoRewindAmountDialog( currentSeconds = viewState.autoRewindInSeconds, onSecondsConfirmed = listener::autoRewindAmountChanged, onDismiss = listener::dismissDialog, ) } SettingsViewState.Dialog.SeekTime -> { SeekAmountDialog( currentSeconds = viewState.seekTimeInSeconds, onSecondsConfirmed = listener::seekAmountChanged, onDismiss = listener::dismissDialog, ) } } }
settings/src/main/kotlin/voice/settings/views/Settings.kt
3710509565
package com.duopoints.android.ui.views.settings import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.CompoundButton import android.widget.FrameLayout import com.duopoints.android.R import com.duopoints.android.logistics.Pers import com.duopoints.android.utils.logging.LogLevel import com.duopoints.android.utils.logging.log import kotlinx.android.synthetic.main.settings_view_checkbox.view.* import kotlinx.android.synthetic.main.settings_view_text_container.view.* class SettingsSwitch @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr), CompoundButton.OnCheckedChangeListener { private var settingKey: String? = null init { init(attrs) } private fun init(attrs: AttributeSet?) { var title: String? = null var subtitle: String? = null var hideSubtitle = false var defaultChecked = false attrs?.let { val ta = context.obtainStyledAttributes(attrs, R.styleable.SettingsSwitch, 0, 0) try { settingKey = ta.getString(R.styleable.SettingsSwitch_switch_setting_key) title = ta.getString(R.styleable.SettingsSwitch_switch_title) subtitle = ta.getString(R.styleable.SettingsSwitch_switch_subtitle) hideSubtitle = ta.getBoolean(R.styleable.SettingsSwitch_switch_hide_subtitle, false) defaultChecked = ta.getBoolean(R.styleable.SettingsSwitch_switch_default, false) } finally { ta.recycle() } } inflate(context, R.layout.settings_view_checkbox, this) settingTitle.text = title settingSubtitle.text = subtitle if (hideSubtitle) { settingSubtitle.visibility = View.GONE } if (!isInEditMode) { if (settingKey != null) { settingCheckbox.isChecked = Pers.get(settingKey!!, defaultChecked) settingCheckbox.setOnCheckedChangeListener(this) } else { settingCheckbox.isChecked = defaultChecked javaClass.log(LogLevel.WARN, "Setting Key not give! Warning") } } else { settingCheckbox.isChecked = defaultChecked } } fun manualChange(isChecked: Boolean) { settingCheckbox.isChecked = isChecked } fun externalSetting(isChecked: Boolean, onClickListener: OnClickListener) { manualChange(isChecked) settingCheckbox.setOnClickListener(onClickListener) this.setOnClickListener(onClickListener) } override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) { settingKey?.let { Pers.put(it, isChecked) } } }
app/src/main/java/com/duopoints/android/ui/views/settings/SettingsSwitch.kt
1272247971
package org.metplus.cruncher.web.controller.canned import org.metplus.cruncher.canned.rating.CompareResumeWithJobCanned import org.metplus.cruncher.canned.resume.MatchWithJobCanned import org.metplus.cruncher.rating.CompareResumeWithJobObserver import org.metplus.cruncher.resume.DownloadResume import org.metplus.cruncher.resume.DownloadResumeObserver import org.metplus.cruncher.resume.MatchWithJobObserver import org.metplus.cruncher.resume.ReCrunchAllResumes import org.metplus.cruncher.resume.ReCrunchAllResumesObserver import org.metplus.cruncher.resume.Resume import org.metplus.cruncher.resume.ResumeFile import org.metplus.cruncher.resume.UploadResume import org.metplus.cruncher.resume.UploadResumeObserver import org.metplus.cruncher.web.controller.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.util.FileCopyUtils 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.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.RestController import org.springframework.web.multipart.MultipartFile import java.io.ByteArrayOutputStream import javax.servlet.http.HttpServletResponse @RestController @RequestMapping(value = [ "/api/v99999/resume" ]) class ResumeCannedController( @Autowired private val uploadResume: UploadResume, @Autowired private val downloadResume: DownloadResume, @Autowired private val matchWithJob: MatchWithJobCanned, @Autowired private val reCrunchAllResumes: ReCrunchAllResumes, @Autowired private val compareResumeWithJob: CompareResumeWithJobCanned ) { @PostMapping("upload") @ResponseBody fun uploadResumeEndpoint(@RequestParam("userId") id: String, @RequestParam("name") name: String, @RequestParam("file") file: MultipartFile): CruncherResponse { return uploadResume.process(id, name, file.inputStream, file.size, observer = object : UploadResumeObserver<CruncherResponse> { override fun onException(exception: Exception, resume: Resume): CruncherResponse { return CruncherResponse( resultCode = ResultCodes.FATAL_ERROR, message = "Exception happened while uploading the resume" ) } override fun onSuccess(resume: Resume): CruncherResponse { return CruncherResponse( resultCode = ResultCodes.SUCCESS, message = "Resume upload successful" ) } override fun onEmptyFile(resume: Resume): CruncherResponse { return CruncherResponse( resultCode = ResultCodes.FATAL_ERROR, message = "Resume is empty" ) } }) as CruncherResponse } @GetMapping("{userId}") @ResponseBody fun downloadResumeEndpoint(@PathVariable("userId") id: String, response: HttpServletResponse): CruncherResponse? { return downloadResume.process(id, observer = object : DownloadResumeObserver<CruncherResponse?> { override fun onError(userId: String, exception: Exception): CruncherResponse { return CruncherResponse( resultCode = ResultCodes.FATAL_ERROR, message = "Exception happened while uploading the resume" ) } override fun onSuccess(resume: Resume, resumeFile: ResumeFile): CruncherResponse? { val outputFile = ByteArrayOutputStream() var data = resumeFile.fileStream.read() while (data >= 0) { outputFile.write(data.toChar().toInt()) data = resumeFile.fileStream.read() } outputFile.flush() response.contentType = "application/octet-stream" response.setHeader("Content-Disposition", "inline; filename=\"" + resumeFile.filename + "\"") FileCopyUtils.copy(outputFile.toByteArray(), response.outputStream) response.setContentLength(outputFile.size()) response.flushBuffer() return null } override fun onResumeNotFound(userId: String): CruncherResponse { return CruncherResponse( resultCode = ResultCodes.FATAL_ERROR, message = "Resume is empty" ) } }) } @GetMapping("/match/{jobId}") @ResponseBody fun downloadResumeEndpoint(@PathVariable("jobId") id: String): ResponseEntity<CruncherResponse> { return matchWithJob.process(jobId = id, observer = object : MatchWithJobObserver<ResponseEntity<CruncherResponse>> { override fun noMatchFound(jobId: String, matchers: Map<String, List<Resume>>): ResponseEntity<CruncherResponse> { return ResponseEntity(ResumeMatchedAnswer( resultCode = ResultCodes.SUCCESS, message = "Job with id '$jobId' was not matches", resumes = matchers.toAllCrunchedResumesAnswer() ), HttpStatus.OK) } override fun jobNotFound(jobId: String): ResponseEntity<CruncherResponse> { return ResponseEntity(CruncherResponse( resultCode = ResultCodes.JOB_NOT_FOUND, message = "Job with id '$jobId' was not found" ), HttpStatus.NOT_FOUND) } override fun success(matchedResumes: Map<String, List<Resume>>): ResponseEntity<CruncherResponse> { return ResponseEntity(ResumeMatchedAnswer( resultCode = ResultCodes.SUCCESS, message = "Job matches ${matchedResumes.size} resumes", resumes = matchedResumes.toAllCrunchedResumesAnswer() ), HttpStatus.OK) } }) } @GetMapping("{resumeId}/compare/{jobId}") @ResponseBody fun compare(@PathVariable("resumeId") resumeId: String, @PathVariable("jobId") jobId: String): ResponseEntity<CruncherResponse> { return compareResumeWithJob.process(resumeId, jobId, object : CompareResumeWithJobObserver<ResponseEntity<CruncherResponse>> { override fun onJobNotFound(jobId: String): ResponseEntity<CruncherResponse> { return ResponseEntity.ok(CruncherResponse( resultCode = ResultCodes.JOB_NOT_FOUND, message = "Job $jobId was not found")) } override fun onResumeNotFound(resumeId: String): ResponseEntity<CruncherResponse> { return ResponseEntity(CruncherResponse( resultCode = ResultCodes.RESUME_NOT_FOUND, message = "Resume $resumeId was not found"), HttpStatus.NOT_FOUND) } override fun onSuccess(starsRating: Double): ResponseEntity<CruncherResponse> { return ResponseEntity.ok(ComparisonMatchAnswer( message = "Job and Resume match", stars = mapOf("naiveBayes" to starsRating) )) } }) } @GetMapping("/reindex") @ResponseBody fun reindex(): CruncherResponse { return reCrunchAllResumes.process(object : ReCrunchAllResumesObserver<CruncherResponse> { override fun onSuccess(numberScheduled: Int): CruncherResponse { return CruncherResponse( resultCode = ResultCodes.SUCCESS, message = "Going to reindex $numberScheduled resumes" ) } }) } }
web/src/main/kotlin/org/metplus/cruncher/web/controller/canned/ResumeCannedController.kt
2439596872
package com.quickblox.sample.pushnotifications.kotlin.activities import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.quickblox.auth.session.QBSettings import com.quickblox.sample.pushnotifications.kotlin.BuildConfig import com.quickblox.sample.pushnotifications.kotlin.R class AppInfoActivity : BaseActivity() { private lateinit var appVersionTextView: TextView private lateinit var sdkVersionTextView: TextView private lateinit var appIDTextView: TextView private lateinit var authKeyTextView: TextView private lateinit var authSecretTextView: TextView private lateinit var accountKeyTextView: TextView private lateinit var apiDomainTextView: TextView private lateinit var chatDomainTextView: TextView private lateinit var appQAVersionTextView: TextView companion object { fun start(context: Context) = context.startActivity(Intent(context, AppInfoActivity::class.java)) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_appinfo) initUI() fillUI() } private fun initUI() { appVersionTextView = findViewById(R.id.text_app_version) sdkVersionTextView = findViewById(R.id.text_sdk_version) appIDTextView = findViewById(R.id.text_app_id) authKeyTextView = findViewById(R.id.text_auth_key) authSecretTextView = findViewById(R.id.text_auth_secret) accountKeyTextView = findViewById(R.id.text_account_key) apiDomainTextView = findViewById(R.id.text_api_domain) chatDomainTextView = findViewById(R.id.text_chat_domain) appQAVersionTextView = findViewById(R.id.text_qa_version) } private fun fillUI() { supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = getString(R.string.appinfo_title) appVersionTextView.text = BuildConfig.VERSION_NAME sdkVersionTextView.text = com.quickblox.BuildConfig.VERSION_NAME appIDTextView.text = QBSettings.getInstance().applicationId authKeyTextView.text = QBSettings.getInstance().authorizationKey authSecretTextView.text = QBSettings.getInstance().authorizationSecret accountKeyTextView.text = QBSettings.getInstance().accountKey apiDomainTextView.text = QBSettings.getInstance().serverApiDomain chatDomainTextView.text = QBSettings.getInstance().chatEndpoint if (BuildConfig.IS_QA) { val appVersion = BuildConfig.VERSION_NAME val versionQACode = BuildConfig.VERSION_QA_CODE.toString() val qaVersion = "$appVersion.$versionQACode" val spannable = SpannableString(qaVersion) spannable.setSpan(ForegroundColorSpan(Color.RED), appVersion.length + 1, qaVersion.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) appQAVersionTextView.setText(spannable, TextView.BufferType.SPANNABLE) appQAVersionTextView.visibility = View.VISIBLE findViewById<View>(R.id.text_qa_version_title).visibility = View.VISIBLE } } }
sample-pushnotifications-kotlin/app/src/main/java/com/quickblox/sample/pushnotifications/kotlin/activities/AppInfoActivity.kt
3908014757
package tv.superawesome.demoapp.util import android.graphics.Color import kotlin.math.abs object TestColors { val bannerYellow = Color.valueOf(0.96862745f, 0.8862745f, 0.41960785f) val ksfYellow = Color.valueOf(0.8784314f, 0.8784314f, 0.8784314f) val vastYellow = Color.valueOf(0.9647059f, 0.90588236f, 0.46666667f) val vpaidYellow = Color.valueOf(0.96862745f, 0.8862745f, 0.4627451f) fun checkApproximatelyEqual(givenColor: Color?, targetColor: Color?): Boolean { if (givenColor == null || targetColor == null) return false val threshold = 0.10 return abs(givenColor.red() - targetColor.red()) <= threshold && abs(givenColor.red() - targetColor.red()) <= threshold && abs(givenColor.red() - targetColor.red()) <= threshold } }
app/src/androidTest/java/tv/superawesome/demoapp/util/TestColors.kt
897608827
package de.thm.arsnova.service.wsgateway.management import org.springframework.boot.actuate.endpoint.annotation.Endpoint import org.springframework.boot.actuate.endpoint.annotation.ReadOperation import org.springframework.stereotype.Component import org.springframework.web.socket.config.WebSocketMessageBrokerStats @Component @Endpoint(id = "websocket-stats") class WebsocketStatsEndpoint(private val webSocketMessageBrokerStats: WebSocketMessageBrokerStats) { @ReadOperation fun readStats(): WebSocketMessageBrokerStats { return webSocketMessageBrokerStats } }
websocket/src/main/kotlin/de/thm/arsnova/service/wsgateway/management/WebsocketStatsEndpoint.kt
2274744586
/* * ************************************************************************* * SwipeDragItemTouchHelperCallback.java * ************************************************************************** * Copyright © 2015-2017 VLC authors and VideoLAN * Author: Geoffrey Métais * * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * *************************************************************************** */ package org.videolan.vlc.gui.helpers import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import org.videolan.vlc.interfaces.SwipeDragHelperAdapter class SwipeDragItemTouchHelperCallback(private val mAdapter: SwipeDragHelperAdapter, private val longPressDragEnable: Boolean = false) : ItemTouchHelper.Callback() { private var dragFrom = -1 private var dragTo = -1 override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN val swipeFlags = ItemTouchHelper.START or ItemTouchHelper.END return makeMovementFlags(dragFlags, swipeFlags) } override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { mAdapter.onItemMove(viewHolder.layoutPosition, target.layoutPosition) val fromPosition = viewHolder.layoutPosition val toPosition = target.layoutPosition if (dragFrom == -1) { dragFrom = fromPosition } dragTo = toPosition return true } override fun isLongPressDragEnabled(): Boolean { return longPressDragEnable } override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) { if (dragFrom != -1 && dragTo != -1 && dragFrom != dragTo) { mAdapter.onItemMoved(dragFrom, dragTo) } dragTo = -1 dragFrom = dragTo super.clearView(recyclerView, viewHolder) } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { mAdapter.onItemDismiss(viewHolder.layoutPosition) } }
application/vlc-android/src/org/videolan/vlc/gui/helpers/SwipeDragItemTouchHelperCallback.kt
3161050388
package net.milosvasic.pussycat.logging enum class LOG_TYPE { VERBOSE, DEBUG, INFORMATION, WARNING, ERROR }
Pussycat/src/main/kotlin/net/milosvasic/pussycat/logging/LOG_TYPE.kt
1496256837
/* * ************************************************************************ * ExampleInstrumentedTest.kt * ************************************************************************* * Copyright © 2020 VLC authors and VideoLAN * Author: Nicolas POMEPUY * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.vlc.mediadb import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("org.videolan.vlc.mediadb.test", appContext.packageName) } }
application/mediadb/src/androidTest/java/org/videolan/vlc/mediadb/ExampleInstrumentedTest.kt
929798140
/* * Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.asynchronous.services import android.app.PendingIntent import android.app.PendingIntent.FLAG_UPDATE_CURRENT import android.content.* import android.net.Uri import android.os.AsyncTask import android.os.Build.VERSION.SDK_INT import android.os.Build.VERSION_CODES.O import android.os.IBinder import android.widget.RemoteViews import androidx.annotation.StringRes import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.preference.PreferenceManager import com.amaze.filemanager.R import com.amaze.filemanager.application.AppConfig import com.amaze.filemanager.asynchronous.management.ServiceWatcherUtil import com.amaze.filemanager.filesystem.FileUtil import com.amaze.filemanager.filesystem.HybridFileParcelable import com.amaze.filemanager.filesystem.files.FileUtils import com.amaze.filemanager.filesystem.files.GenericCopyUtil import com.amaze.filemanager.ui.activities.MainActivity import com.amaze.filemanager.ui.notifications.NotificationConstants import com.amaze.filemanager.utils.DatapointParcelable import com.amaze.filemanager.utils.ObtainableServiceBinder import com.amaze.filemanager.utils.ProgressHandler import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.* import java.nio.file.Files import java.nio.file.Paths import java.nio.file.attribute.BasicFileAttributes import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipException import java.util.zip.ZipOutputStream @Suppress("TooManyFunctions") // Hack. class ZipService : AbstractProgressiveService() { private val log: Logger = LoggerFactory.getLogger(ZipService::class.java) private val mBinder: IBinder = ObtainableServiceBinder(this) private lateinit var asyncTask: CompressAsyncTask private lateinit var mNotifyManager: NotificationManagerCompat private lateinit var mBuilder: NotificationCompat.Builder private lateinit var progressListener: ProgressListener private val progressHandler = ProgressHandler() // list of data packages, to initiate chart in process viewer fragment private val dataPackages = ArrayList<DatapointParcelable>() private var accentColor = 0 private var sharedPreferences: SharedPreferences? = null private var customSmallContentViews: RemoteViews? = null private var customBigContentViews: RemoteViews? = null override fun onCreate() { super.onCreate() registerReceiver(receiver1, IntentFilter(KEY_COMPRESS_BROADCAST_CANCEL)) } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { val mZipPath = intent.getStringExtra(KEY_COMPRESS_PATH) val baseFiles: ArrayList<HybridFileParcelable> = intent.getParcelableArrayListExtra(KEY_COMPRESS_FILES)!! val zipFile = File(mZipPath) mNotifyManager = NotificationManagerCompat.from(applicationContext) if (!zipFile.exists()) { try { zipFile.createNewFile() } catch (e: IOException) { log.warn("failed to create zip file", e) } } sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) accentColor = (application as AppConfig) .utilsProvider .colorPreference .getCurrentUserColorPreferences(this, sharedPreferences).accent val notificationIntent = Intent(this, MainActivity::class.java) .putExtra(MainActivity.KEY_INTENT_PROCESS_VIEWER, true) val pendingIntent = PendingIntent.getActivity( this, 0, notificationIntent, getPendingIntentFlag(0) ) customSmallContentViews = RemoteViews(packageName, R.layout.notification_service_small) customBigContentViews = RemoteViews(packageName, R.layout.notification_service_big) val stopIntent = Intent(KEY_COMPRESS_BROADCAST_CANCEL) val stopPendingIntent = PendingIntent.getBroadcast( applicationContext, 1234, stopIntent, getPendingIntentFlag(FLAG_UPDATE_CURRENT) ) val action = NotificationCompat.Action( R.drawable.ic_zip_box_grey, getString(R.string.stop_ftp), stopPendingIntent ) mBuilder = NotificationCompat.Builder(this, NotificationConstants.CHANNEL_NORMAL_ID) .setSmallIcon(R.drawable.ic_zip_box_grey) .setContentIntent(pendingIntent) .setCustomContentView(customSmallContentViews) .setCustomBigContentView(customBigContentViews) .setCustomHeadsUpContentView(customSmallContentViews) .setStyle(NotificationCompat.DecoratedCustomViewStyle()) .addAction(action) .setOngoing(true) .setColor(accentColor) NotificationConstants.setMetadata(this, mBuilder, NotificationConstants.TYPE_NORMAL) startForeground(NotificationConstants.ZIP_ID, mBuilder.build()) initNotificationViews() super.onStartCommand(intent, flags, startId) super.progressHalted() asyncTask = CompressAsyncTask(this, baseFiles, mZipPath!!) asyncTask.execute() // If we get killed, after returning from here, restart return START_NOT_STICKY } override fun getNotificationManager(): NotificationManagerCompat = mNotifyManager override fun getNotificationBuilder(): NotificationCompat.Builder = mBuilder override fun getNotificationId(): Int = NotificationConstants.ZIP_ID @StringRes override fun getTitle(move: Boolean): Int = R.string.compressing override fun getNotificationCustomViewSmall(): RemoteViews = customSmallContentViews!! override fun getNotificationCustomViewBig(): RemoteViews = customBigContentViews!! override fun getProgressListener(): ProgressListener = progressListener override fun setProgressListener(progressListener: ProgressListener) { this.progressListener = progressListener } override fun getDataPackages(): ArrayList<DatapointParcelable> = dataPackages override fun getProgressHandler(): ProgressHandler = progressHandler override fun clearDataPackages() = dataPackages.clear() inner class CompressAsyncTask( private val zipService: ZipService, private val baseFiles: ArrayList<HybridFileParcelable>, private val zipPath: String ) : AsyncTask<Void, Void?, Void?>() { private lateinit var zos: ZipOutputStream private lateinit var watcherUtil: ServiceWatcherUtil private var totalBytes = 0L override fun doInBackground(vararg p1: Void): Void? { // setting up service watchers and initial data packages // finding total size on background thread (this is necessary condition for SMB!) totalBytes = FileUtils.getTotalBytes(baseFiles, zipService.applicationContext) progressHandler.sourceSize = baseFiles.size progressHandler.totalSize = totalBytes progressHandler.setProgressListener { speed: Long -> publishResults(speed, false, false) } zipService.addFirstDatapoint( baseFiles[0].getName(applicationContext), baseFiles.size, totalBytes, false ) execute( zipService.applicationContext, FileUtils.hybridListToFileArrayList(baseFiles), zipPath ) return null } override fun onCancelled() { super.onCancelled() progressHandler.cancelled = true val zipFile = File(zipPath) if (zipFile.exists()) zipFile.delete() } public override fun onPostExecute(a: Void?) { watcherUtil.stopWatch() val intent = Intent(MainActivity.KEY_INTENT_LOAD_LIST) .putExtra(MainActivity.KEY_INTENT_LOAD_LIST_FILE, zipPath) zipService.sendBroadcast(intent) zipService.stopSelf() } /** * Main logic for zipping specified files. */ fun execute(context: Context, baseFiles: ArrayList<File>, zipPath: String?) { val out: OutputStream? val zipDirectory = File(zipPath) watcherUtil = ServiceWatcherUtil(progressHandler) watcherUtil.watch(this@ZipService) try { out = FileUtil.getOutputStream(zipDirectory, context) zos = ZipOutputStream(BufferedOutputStream(out)) for ((fileProgress, file) in baseFiles.withIndex()) { if (isCancelled) return progressHandler.fileName = file.name progressHandler.sourceFilesProcessed = fileProgress + 1 compressFile(file, "") } } catch (e: IOException) { log.warn("failed to zip file", e) } finally { try { zos.flush() zos.close() context.sendBroadcast( Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) .setData(Uri.fromFile(zipDirectory)) ) } catch (e: IOException) { log.warn("failed to close zip streams", e) } } } @Throws(IOException::class, NullPointerException::class, ZipException::class) private fun compressFile(file: File, path: String) { if (progressHandler.cancelled) return if (!file.isDirectory) { zos.putNextEntry(createZipEntry(file, path)) val buf = ByteArray(GenericCopyUtil.DEFAULT_BUFFER_SIZE) var len: Int BufferedInputStream(FileInputStream(file)).use { `in` -> while (`in`.read(buf).also { len = it } > 0) { if (!progressHandler.cancelled) { zos.write(buf, 0, len) ServiceWatcherUtil.position += len.toLong() } else break } } return } file.listFiles()?.forEach { compressFile(it, "${createZipEntryPrefixWith(path)}${file.name}") } } } private fun createZipEntryPrefixWith(path: String): String = if (path.isEmpty()) { path } else { "$path/" } private fun createZipEntry(file: File, path: String): ZipEntry = ZipEntry("${createZipEntryPrefixWith(path)}${file.name}").apply { if (SDK_INT >= O) { val attrs = Files.readAttributes( Paths.get(file.absolutePath), BasicFileAttributes::class.java ) setCreationTime(attrs.creationTime()) .setLastAccessTime(attrs.lastAccessTime()) .lastModifiedTime = attrs.lastModifiedTime() } else { time = file.lastModified() } } /* * Class used for the client Binder. Because we know this service always runs in the same process * as its clients, we don't need to deal with IPC. */ private val receiver1: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { progressHandler.cancelled = true } } override fun onBind(arg0: Intent): IBinder = mBinder override fun onDestroy() { super.onDestroy() unregisterReceiver(receiver1) } companion object { const val KEY_COMPRESS_PATH = "zip_path" const val KEY_COMPRESS_FILES = "zip_files" const val KEY_COMPRESS_BROADCAST_CANCEL = "zip_cancel" } }
app/src/main/java/com/amaze/filemanager/asynchronous/services/ZipService.kt
3918840526
/* * 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 chrislo27.discordbot import chrislo27.discordbot.cmd.CommandHandler import chrislo27.discordbot.tick.TickManager import chrislo27.discordbot.util.IPermission import sx.blah.discord.api.ClientBuilder import sx.blah.discord.api.IDiscordClient import sx.blah.discord.handle.obj.IGuild import sx.blah.discord.handle.obj.IUser @WillHandleEvents abstract class Bot<SELF : Bot<SELF>>(builder: ClientBuilder) { lateinit var tickManager: TickManager<SELF> protected set val client: IDiscordClient = builder.build() abstract val commandHandler: CommandHandler<SELF> abstract fun getPrefix(guild: IGuild?): String abstract fun getEmbeddedPrefix(guild: IGuild?): String? abstract fun getPermission(user: IUser, guild: IGuild?): IPermission abstract fun setPermission(user: IUser, perm: IPermission?): Unit abstract fun tickUpdate(): Unit abstract fun onLogin(): Unit abstract fun onLogout(): Unit } /** * Indicates that the class can handle events and will automatically be registered as an event listener */ @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS) annotation class WillHandleEvents
src/chrislo27/discordbot/Bot.kt
1812439984