repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
3sidedcube/react-native-navigation
lib/android/app/src/test/java/com/reactnativenavigation/viewcontrollers/fakes/FakeParentController.kt
1
1420
package com.reactnativenavigation.viewcontrollers.fakes import android.app.Activity import androidx.coordinatorlayout.widget.CoordinatorLayout import com.reactnativenavigation.options.Options import com.reactnativenavigation.viewcontrollers.viewcontroller.Presenter import com.reactnativenavigation.utils.CompatUtils import com.reactnativenavigation.viewcontrollers.child.ChildControllersRegistry import com.reactnativenavigation.viewcontrollers.parent.ParentController import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController import org.mockito.Mockito.mock class FakeParentController @JvmOverloads constructor( activity: Activity, childRegistry: ChildControllersRegistry, private val child: ViewController<*>, id: String = "Parent" + CompatUtils.generateViewId(), presenter: Presenter = mock(Presenter::class.java), initialOptions: Options = Options.EMPTY ) : ParentController<CoordinatorLayout>(activity, childRegistry, id, presenter, initialOptions) { init { child.parentController = this } override fun getCurrentChild(): ViewController<*> = child override fun createView() = CoordinatorLayout(activity).apply { addView(child.view) } override fun getChildControllers() = listOf(child) override fun sendOnNavigationButtonPressed(buttonId: String?) = child.sendOnNavigationButtonPressed(buttonId) }
mit
48b7349c54caaa153716f30f3bae6ae0
42.060606
113
0.793662
5.440613
false
false
false
false
jwren/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/InsertAction.kt
3
1444
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.ui.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopupFactory import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile internal class InsertAction: DumbAwareAction() { override fun actionPerformed(event: AnActionEvent) { val dataContext = event.dataContext val popup = JBPopupFactory.getInstance().createActionGroupPopup( MarkdownBundle.message("action.Markdown.Insert.text"), insertGroup, dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false, MarkdownActionPlaces.INSERT_POPUP ) popup.showInBestPositionFor(dataContext) } override fun update(event: AnActionEvent) { val editor = MarkdownActionUtil.findMarkdownTextEditor(event) event.presentation.isEnabledAndVisible = editor != null || event.getData(PlatformDataKeys.PSI_FILE) is MarkdownFile } companion object { private val insertGroup get() = requireNotNull(ActionUtil.getActionGroup("Markdown.InsertGroup")) } }
apache-2.0
8ab034632d9a532742d14e50a770a723
40.257143
158
0.788089
4.813333
false
false
false
false
smmribeiro/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/project/path/WorkingDirectoryField.kt
1
9051
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.service.ui.project.path import com.intellij.ide.wizard.getCanonicalPath import com.intellij.ide.wizard.getPresentablePath import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.externalSystem.service.ui.completion.JTextCompletionContributor import com.intellij.openapi.externalSystem.service.ui.completion.JTextCompletionContributor.CompletionType import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionInfo import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionPopup import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionPopup.UpdatePopupType.SHOW_IF_HAS_VARIANCES import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.observable.properties.map import com.intellij.openapi.observable.util.bind import com.intellij.openapi.project.Project import com.intellij.openapi.ui.addKeyboardAction import com.intellij.openapi.ui.getKeyStrokes import com.intellij.openapi.ui.isTextUnderMouse import com.intellij.openapi.ui.BrowseFolderRunnable import com.intellij.openapi.ui.TextComponentAccessor import com.intellij.openapi.util.RecursionManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.fields.ExtendableTextField import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.plaf.basic.BasicTextUI import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter import javax.swing.text.Highlighter class WorkingDirectoryField( project: Project, private val workingDirectoryInfo: WorkingDirectoryInfo ) : ExtendableTextField() { private val propertyGraph = PropertyGraph(isBlockPropagation = false) private val modeProperty = propertyGraph.graphProperty { Mode.NAME } private val textProperty = propertyGraph.graphProperty { "" } private val workingDirectoryProperty = propertyGraph.graphProperty { "" } private val projectNameProperty = propertyGraph.graphProperty { "" } var mode by modeProperty var workingDirectory by workingDirectoryProperty var projectName by projectNameProperty private val externalProjects = workingDirectoryInfo.externalProjects private var highlightTag: Any? = null private val highlightRecursionGuard = RecursionManager.createGuard<WorkingDirectoryField>(WorkingDirectoryField::class.java.name) init { val text by textProperty.map { it.trim() } workingDirectoryProperty.dependsOn(textProperty) { when (mode) { Mode.PATH -> getCanonicalPath(text) Mode.NAME -> resolveProjectPathByName(text) ?: text } } projectNameProperty.dependsOn(textProperty) { when (mode) { Mode.PATH -> resolveProjectNameByPath(getCanonicalPath(text)) ?: text Mode.NAME -> text } } textProperty.dependsOn(modeProperty) { when (mode) { Mode.PATH -> getPresentablePath(workingDirectory) Mode.NAME -> projectName } } textProperty.dependsOn(workingDirectoryProperty) { when (mode) { Mode.PATH -> getPresentablePath(workingDirectory) Mode.NAME -> resolveProjectNameByPath(workingDirectory) ?: getPresentablePath(workingDirectory) } } textProperty.dependsOn(projectNameProperty) { when (mode) { Mode.PATH -> resolveProjectPathByName(projectName) ?: projectName Mode.NAME -> projectName } } modeProperty.dependsOn(workingDirectoryProperty) { when { workingDirectory.isEmpty() -> Mode.NAME resolveProjectNameByPath(workingDirectory) != null -> mode else -> Mode.PATH } } modeProperty.dependsOn(projectNameProperty) { when { projectName.isEmpty() -> Mode.NAME resolveProjectPathByName(projectName) != null -> mode else -> Mode.PATH } } bind(textProperty) } private fun resolveProjectPathByName(projectName: String) = resolveValueByKey(projectName, externalProjects, { name }, { path }) private fun resolveProjectNameByPath(workingDirectory: String) = resolveValueByKey(workingDirectory, externalProjects, { path }, { name }) private fun <E> resolveValueByKey( key: String, entries: List<E>, getKey: E.() -> String, getValue: E.() -> String ): String? { if (key.isNotEmpty()) { val entry = entries.asSequence() .filter { it.getKey().startsWith(key) } .sortedBy { it.getKey().length } .firstOrNull() if (entry != null) { val suffix = entry.getKey().removePrefix(key) if (entry.getValue().endsWith(suffix)) { return entry.getValue().removeSuffix(suffix) } } val parentEntry = entries.asSequence() .filter { key.startsWith(it.getKey()) } .sortedByDescending { it.getKey().length } .firstOrNull() if (parentEntry != null) { val suffix = key.removePrefix(parentEntry.getKey()) return parentEntry.getValue() + suffix } } return null } init { addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (isTextUnderMouse(e)) { mode = Mode.PATH } } }) addKeyboardAction(getKeyStrokes("CollapseRegion", "CollapseRegionRecursively", "CollapseAllRegions")) { mode = Mode.NAME } addKeyboardAction(getKeyStrokes("ExpandRegion", "ExpandRegionRecursively", "ExpandAllRegions")) { mode = Mode.PATH } } init { addHighlighterListener { updateHighlight() } textProperty.afterChange { updateHighlight() } modeProperty.afterChange { updateHighlight() } updateHighlight() } private fun updateHighlight() { highlightRecursionGuard.doPreventingRecursion(this, false) { if (highlightTag != null) { highlighter.removeHighlight(highlightTag) foreground = null } if (mode == Mode.NAME) { val textAttributes = EditorColors.FOLDED_TEXT_ATTRIBUTES.defaultAttributes val painter = DefaultHighlightPainter(textAttributes.backgroundColor) highlightTag = highlighter.addHighlight(0, text.length, painter) foreground = textAttributes.foregroundColor } } } private fun addHighlighterListener(listener: () -> Unit) { highlighter = object : BasicTextUI.BasicHighlighter() { override fun changeHighlight(tag: Any, p0: Int, p1: Int) = super.changeHighlight(tag, p0, p1) .also { listener() } override fun removeHighlight(tag: Any) = super.removeHighlight(tag) .also { listener() } override fun removeAllHighlights() = super.removeAllHighlights() .also { listener() } override fun addHighlight(p0: Int, p1: Int, p: Highlighter.HighlightPainter) = super.addHighlight(p0, p1, p) .also { listener() } } } init { val fileBrowseAccessor = object : TextComponentAccessor<WorkingDirectoryField> { override fun getText(component: WorkingDirectoryField) = workingDirectory override fun setText(component: WorkingDirectoryField, text: String) { workingDirectory = text } } val browseFolderRunnable = object : BrowseFolderRunnable<WorkingDirectoryField>( workingDirectoryInfo.fileChooserTitle, workingDirectoryInfo.fileChooserDescription, project, workingDirectoryInfo.fileChooserDescriptor, this, fileBrowseAccessor ) { override fun chosenFileToResultingText(chosenFile: VirtualFile): String { return ExternalSystemApiUtil.getLocalFileSystemPath(chosenFile) } } addBrowseExtension(browseFolderRunnable, null) } init { val textCompletionContributor = JTextCompletionContributor.create<WorkingDirectoryField>(CompletionType.REPLACE) { textToComplete -> when (mode) { Mode.NAME -> { externalProjects .map { it.name } .map { TextCompletionInfo(it) } } Mode.PATH -> { val pathToComplete = getCanonicalPath(textToComplete, removeLastSlash = false) externalProjects .filter { it.path.startsWith(pathToComplete) } .map { it.path.substring(pathToComplete.length) } .map { textToComplete + FileUtil.toSystemDependentName(it) } .map { TextCompletionInfo(it) } } } } val textCompletionPopup = TextCompletionPopup(project, this, textCompletionContributor) modeProperty.afterChange { textCompletionPopup.updatePopup(SHOW_IF_HAS_VARIANCES) } } enum class Mode { PATH, NAME } }
apache-2.0
5ea222b97a6f64c9a2294f65f3b6fad2
35.208
158
0.70843
4.824627
false
false
false
false
NlRVANA/Unity
app/src/main/java/com/zwq65/unity/data/network/retrofit/callback/ExceptionHandler.kt
1
2853
package com.zwq65.unity.data.network.retrofit.callback import android.net.ParseException import com.google.gson.JsonParseException import org.json.JSONException import retrofit2.HttpException import java.net.ConnectException import java.net.SocketTimeoutException /** * ================================================ * api交互异常处理统一返回[ApiException] * * * Created by NIRVANA on 2018/02/05. * Contact with <[email protected]> * ================================================ */ internal object ExceptionHandler { private const val UNAUTHORIZED = 401 private const val FORBIDDEN = 403 private const val NOT_FOUND = 404 private const val REQUEST_TIMEOUT = 408 private const val INTERNAL_SERVER_ERROR = 500 private const val BAD_GATEWAY = 502 private const val SERVICE_UNAVAILABLE = 503 private const val GATEWAY_TIMEOUT = 504 fun handleException(e: Throwable): ApiException { val ex: ApiException if (e is HttpException) { ex = ApiException(e, Error.HTTP_ERROR.toString()) when (e.code()) { UNAUTHORIZED, FORBIDDEN, NOT_FOUND, REQUEST_TIMEOUT, GATEWAY_TIMEOUT, INTERNAL_SERVER_ERROR, BAD_GATEWAY, SERVICE_UNAVAILABLE -> //均视为网络错误 ex.message = "网络异常" else -> ex.message = "网络异常" } return ex } else if (e is JsonParseException || e is JSONException || e is ParseException) { ex = ApiException(e, Error.PARSE_ERROR.toString()) //均视为解析错误 ex.message = "解析异常" return ex } else if (e is ConnectException) { ex = ApiException(e, Error.NETWORK_ERROR.toString()) ex.message = "网络异常:连接失败" return ex } else if (e is SocketTimeoutException) { ex = ApiException(e, Error.NETWORK_ERROR.toString()) ex.message = "网络异常:连接超时" return ex } else if (e is ServerException) { //服务器返回的错误 ex = ApiException(e, e.code) ex.message = e.message return ex } else { ex = ApiException(e, Error.UNKNOWN.toString()) //未知错误 ex.message = "未知异常" return ex } } object Error { /** * 未知错误 */ internal const val UNKNOWN = 1000 /** * 解析错误 */ internal const val PARSE_ERROR = 1001 /** * 网络错误 */ internal const val NETWORK_ERROR = 1002 /** * 协议出错 */ internal const val HTTP_ERROR = 1003 } }
apache-2.0
e507f718ecb9e6158b7e4ecb464e6290
29.123596
144
0.544573
4.559524
false
false
false
false
dcz-switcher/niortbus
app/src/main/java/com/niortreactnative/fragments/LineListFragment.kt
1
1940
package com.niortreactnative.fragments import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.niortreactnative.R import com.niortreactnative.adapters.Line import com.niortreactnative.adapters.LineListAdapter import com.niortreactnative.interfaces.AdapterCallback import kotlinx.android.synthetic.main.fragment_line_list.* /** * A simple [Fragment] subclass. */ class LineListFragment : Fragment(), AdapterCallback{ private val TAG = "LineListFragment" private lateinit var _view:View lateinit var mCallback:OnLineSelectedListener interface OnLineSelectedListener { fun onLineSelected(line:Line) } override fun onAttach(context: Context?) { super.onAttach(context) if (context !is OnLineSelectedListener) { Log.e(TAG, "Failed cast :-(") throw ClassCastException(context.toString() + " must implement OnLineSelecteeListener") } else { mCallback = context } } override fun onAdapterCallback(line:Line) { mCallback.onLineSelected(line) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { _view = inflater!!.inflate(R.layout.fragment_line_list, container, false) return _view } override fun onResume() { super.onResume() Log.d(TAG, "on resume") populateLineList() addListeners() } private fun populateLineList (){ line_list.layoutManager = LinearLayoutManager(context) line_list.adapter = LineListAdapter(this) } private fun addListeners() { } }// Required empty public constructor
mit
97305c0090c78b105b46d4e8b9511ac6
21.298851
99
0.691237
4.743276
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/db/model/ChatRoomEntity.kt
2
2144
package chat.rocket.android.db.model import androidx.room.Embedded import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import androidx.room.TypeConverters import chat.rocket.android.emoji.internal.db.StringListConverter @Entity(tableName = "chatrooms", indices = [ Index(value = ["userId"]), Index(value = ["ownerId"]), Index(value = ["subscriptionId"], unique = true), Index(value = ["updatedAt"]), Index(value = ["lastMessageUserId"]) ], foreignKeys = [ ForeignKey(entity = UserEntity::class, parentColumns = ["id"], childColumns = ["ownerId"]), ForeignKey(entity = UserEntity::class, parentColumns = ["id"], childColumns = ["userId"]), ForeignKey(entity = UserEntity::class, parentColumns = ["id"], childColumns = ["lastMessageUserId"]) ] ) @TypeConverters(StringListConverter::class) data class ChatRoomEntity( @PrimaryKey var id: String, var subscriptionId: String, var parentId: String?, var type: String, var name: String, var fullname: String? = null, var userId: String? = null, var ownerId: String? = null, var readonly: Boolean? = false, var isDefault: Boolean? = false, var favorite: Boolean? = false, var topic: String? = null, var announcement: String? = null, var description: String? = null, var open: Boolean? = true, var alert: Boolean? = false, var unread: Long? = 0, var userMentions: Long? = 0, var groupMentions: Long? = 0, var updatedAt: Long? = -1, var timestamp: Long? = -1, var lastSeen: Long? = -1, var lastMessageText: String? = null, var lastMessageUserId: String? = null, var lastMessageTimestamp: Long? = null, var broadcast: Boolean? = false, var muted: List<String>? = null ) data class ChatRoom( @Embedded var chatRoom: ChatRoomEntity, var username: String?, var userFullname: String?, var status: String?, var lastMessageUserName: String?, var lastMessageUserFullName: String? )
mit
7a23b4f8ad1d702a708d45fb8d436a73
33.031746
112
0.650187
4.270916
false
false
false
false
encodeering/conflate
modules/conflate-epic/src/main/kotlin/com/encodeering/conflate/experimental/epic/Epic.kt
1
3137
package com.encodeering.conflate.experimental.epic import com.encodeering.conflate.experimental.api.Action import com.encodeering.conflate.experimental.api.Middleware import com.encodeering.conflate.experimental.epic.Story.Aspect import com.encodeering.conflate.experimental.epic.Story.Happening import com.encodeering.conflate.experimental.epic.rx.async import com.encodeering.conflate.experimental.epic.rx.await import com.encodeering.conflate.experimental.epic.rx.combine import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import kotlin.coroutines.experimental.CoroutineContext import kotlin.coroutines.experimental.EmptyCoroutineContext /** * @author Michael Clausen - [email protected] */ class Epic<State> ( private val context : CoroutineContext, vararg stories : Story<State> ) : Middleware<State> { constructor (vararg stories : Story<State>) : this (EmptyCoroutineContext, * stories) val daemons by lazy { stories.filter { it.endless } } val visuals by lazy { stories.filterNot { it.endless } } override fun interceptor (connection : Middleware.Connection<State>) : Middleware.Interceptor { return object : Middleware.Interceptor { val daemons by lazy { [email protected] (this::raconteur) } val visuals get () = [email protected] (this::raconteur) fun raconteur (story : Story<State>) : Raconteur<State> { val forward : suspend (Happening) -> Happening = { when (it) { is Happening.Next -> connection.next (it.action) is Happening.Initial -> connection.initial (it.action) } it } val aspects = PublishSubject.create<Aspect<Action, State>> ()!! return Raconteur (aspects, story.embellish (aspects).async (forward, context)) } suspend override fun dispatch (action : Action) { val aspect = Aspect (action, connection.state) daemons.run { tell (aspect, finish = false) } visuals.run { map { it.happenings }.combine ().doOnSubscribe { tell (aspect, finish = true) } }.await () } } } private fun Iterable<Raconteur<State>>.tell (aspect : Aspect<Action, State>, finish : Boolean) { forEach { try { it.tell (aspect) } catch (e : Exception) { it.abort (e) } finally { if (finish) it.finish () } } } private class Raconteur<in State> (private val aspects : Subject<Aspect<Action, State>>, val happenings : Observable<Happening>) { fun tell (aspect : Aspect<Action, State>) = aspects.onNext (aspect) fun abort (e : Exception) = aspects.onError (e) fun finish () = aspects.onComplete () } }
apache-2.0
19fb64ceae84aa7b16f58b01482fb59f
37.728395
134
0.601211
4.599707
false
false
false
false
tmarsteel/kotlin-prolog
core/src/main/kotlin/com/github/prologdb/runtime/term/PrologDictionary.kt
1
6769
package com.github.prologdb.runtime.term import com.github.prologdb.runtime.NullSourceInformation import com.github.prologdb.runtime.PrologSourceInformation import com.github.prologdb.runtime.RandomVariableScope import com.github.prologdb.runtime.unification.Unification import com.github.prologdb.runtime.unification.VariableDiscrepancyException import com.github.prologdb.runtime.util.OperatorRegistry @PrologTypeName("dict") class PrologDictionary(givenPairs: Map<Atom, Term>, givenTail: Term? = null) : Term { val tail: Variable? val pairs: Map<Atom, Term> init { if (givenTail !is Variable? && givenTail !is PrologDictionary?) { throw IllegalArgumentException("The tail must be a dict, variable or absent") } if (givenTail is PrologDictionary) { val combinedPairs = givenPairs as? MutableMap ?: givenPairs.toMutableMap() var pivot: Term? = givenTail while (pivot is PrologDictionary) { pivot.pairs.forEach { combinedPairs.putIfAbsent(it.key, it.value) } pivot = pivot.tail } pairs = combinedPairs tail = pivot as Variable? } else { pairs = givenPairs tail = givenTail as Variable? } } override fun unify(rhs: Term, randomVarsScope: RandomVariableScope): Unification? { if (rhs is Variable) return rhs.unify(this, randomVarsScope) if (rhs !is PrologDictionary) return Unification.FALSE val carryUnification = Unification() val commonKeys = this.pairs.keys.intersect(rhs.pairs.keys) if (this.pairs.size > commonKeys.size) { // LHS has more pairs than are common; those will have to go into RHSs tail if (rhs.tail == null) { // impossible => no unification return Unification.FALSE } else { val subDict = PrologDictionary(pairs.filterKeys { it !in commonKeys }) try { carryUnification.variableValues.incorporate( rhs.tail.unify(subDict, randomVarsScope).variableValues ) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } } else if (rhs.tail != null) { try { carryUnification.variableValues.incorporate( rhs.tail.unify(EMPTY, randomVarsScope).variableValues ) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } if (rhs.pairs.size > commonKeys.size) { // RHS has more pairs than are common; those will have to go into this' tail if (this.tail == null) { // impossible => no unification return Unification.FALSE } else { val subDict = PrologDictionary(rhs.pairs.filterKeys { it !in commonKeys }) try { carryUnification.variableValues.incorporate( this.tail.unify(subDict, randomVarsScope).variableValues ) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } } else if (this.tail != null) { try { carryUnification.variableValues.incorporate( this.tail.unify(EMPTY, randomVarsScope).variableValues ) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } for (commonKey in commonKeys) { val thisValue = this.pairs[commonKey]!! val rhsValue = rhs.pairs[commonKey]!! val keyUnification = thisValue.unify(rhsValue, randomVarsScope) if (keyUnification == null) { // common key did not unify => we're done return Unification.FALSE } try { carryUnification.variableValues.incorporate(keyUnification.variableValues) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } return carryUnification } override val variables: Set<Variable> by lazy { var variables = pairs.values.flatMap { it.variables } val tail = this.tail // invoke override getter only once if (tail != null) { if (variables !is MutableList) variables = variables.toMutableList() variables.add(tail) } variables.toSet() } override fun substituteVariables(mapper: (Variable) -> Term): PrologDictionary { return PrologDictionary(pairs.mapValues { it.value.substituteVariables(mapper) }, tail?.substituteVariables(mapper)).also { it.sourceInformation = this.sourceInformation } } override fun compareTo(other: Term): Int { if (other is Variable || other is PrologNumber || other is PrologString || other is Atom || other is PrologList) { // these are by category lesser than compound terms return 1 } // dicts are not compared by content, neither against predicates nor against other dicts return 0 } override fun toString(): String { var str = pairs.entries .joinToString( separator = ", ", transform = { it.key.toString() + ": " + it.value.toString() } ) if (tail != null) { str += "|$tail" } return "{$str}" } override fun toStringUsingOperatorNotations(operators: OperatorRegistry): String { var str = pairs.entries .joinToString( separator = ", ", transform = { it.key.toStringUsingOperatorNotations(operators) + ": " + it.value.toStringUsingOperatorNotations(operators) } ) if (tail != null) { str += "|${tail.toStringUsingOperatorNotations(operators)}" } return "{$str}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PrologDictionary) return false if (tail != other.tail) return false if (pairs != other.pairs) return false return true } override fun hashCode(): Int { var result = tail?.hashCode() ?: 0 result = 31 * result + pairs.hashCode() return result } companion object { val EMPTY = PrologDictionary(emptyMap()) } override var sourceInformation: PrologSourceInformation = NullSourceInformation }
mit
25ca8209c762d69f97d307785f3b5597
34.255208
140
0.579997
5.179036
false
false
false
false
google/private-compute-libraries
javatests/com/google/android/libraries/pcc/chronicle/analysis/impl/ManagementStrategyValidationTest.kt
1
7570
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.analysis.impl import com.google.android.libraries.pcc.chronicle.api.Connection import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider import com.google.android.libraries.pcc.chronicle.api.ConnectionRequest import com.google.android.libraries.pcc.chronicle.api.DataType import com.google.android.libraries.pcc.chronicle.api.DeletionTrigger import com.google.android.libraries.pcc.chronicle.api.ManagedDataType import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy import com.google.android.libraries.pcc.chronicle.api.StorageMedia import com.google.android.libraries.pcc.chronicle.api.Trigger 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.builder.PolicyCheck import com.google.android.libraries.pcc.chronicle.api.policy.builder.deletionTriggers import com.google.android.libraries.pcc.chronicle.api.policy.builder.policy import com.google.android.libraries.pcc.chronicle.api.policy.builder.target 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 ManagementStrategyValidationTest { @Test fun policy_verifyManagementStrategies() { val policy = policy("MyPolicy", "SomeKindaEgress") { target(FOO_DTD, maxAge = Duration.ofMillis(Long.MAX_VALUE)) { retention(StorageMedium.DISK) deletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg") } target(BAR_DTD, maxAge = Duration.ofMinutes(5)) { retention(StorageMedium.RAM) } // Baz won't be used. target(BAZ_DTD, maxAge = Duration.ofMillis(1)) { retention(StorageMedium.RAM, encryptionRequired = true) } } val connectionProviders = listOf( makeConnectionProvider( ManagedDataType( descriptor = dataTypeDescriptor(name = "Foo", Unit::class), managementStrategy = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.LOCAL_DISK, ttl = null, deletionTriggers = setOf( DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg"), DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "optional_trigger"), ) ), connectionTypes = emptySet() ) ), makeConnectionProvider( ManagedDataType( descriptor = dataTypeDescriptor(name = "Bar", Unit::class), managementStrategy = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.MEMORY, ttl = Duration.ofMinutes(5) ), connectionTypes = emptySet() ) ) ) assertThat(policy.verifyManagementStrategies(connectionProviders)).isEmpty() } @Test fun policyTarget_verifyRetentionSatisfiedBy_valid() { val dataType = ManagedDataType( descriptor = FOO_DTD, managementStrategy = ManagementStrategy.Stored( encrypted = true, media = StorageMedia.MEMORY, ttl = Duration.ofMinutes(5) ), connectionTypes = emptySet() ) assertThat(FOO_TARGET.verifyRetentionSatisfiedBy(dataType)).isEmpty() } @Test fun policyTarget_verifyRetentionSatisfiedBy_invalid() { val dataType = ManagedDataType( descriptor = FOO_DTD, managementStrategy = ManagementStrategy.Stored( encrypted = true, media = StorageMedia.LOCAL_DISK, ttl = Duration.ofMinutes(5) ), connectionTypes = emptySet() ) assertThat(FOO_TARGET.verifyRetentionSatisfiedBy(dataType)).hasSize(1) } @Test fun satifiesDeletion_whenPassthru_alwaysTrue() { val strategy = ManagementStrategy.PassThru FOO_TARGET.deletionTriggers().forEach { assertThat(strategy.satisfies(it)).isTrue() } } @Test fun satifiesDeletion_whenStored_passesWithCorrectTriggers() { val strategy = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.MEMORY, ttl = Duration.ofMinutes(5), deletionTriggers = setOf( DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg1"), DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg2"), DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "optional_trigger"), ) ) FOO_TARGET.deletionTriggers().forEach { assertThat(strategy.satisfies(it)).isTrue() } } @Test fun satifiesDeletion_whenStored_failsWithoutTrigger() { val dataType = ManagedDataType( descriptor = FOO_DTD, managementStrategy = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.MEMORY, ttl = Duration.ofMinutes(5), deletionTriggers = setOf( DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "optional_trigger"), ) ), connectionTypes = emptySet() ) FOO_TARGET.deletionTriggers().forEach { assertThat(dataType.managementStrategy.satisfies(it)).isFalse() } assertThat(FOO_TARGET.verifyDeletionTriggersSatisfiedBy(dataType)) .containsExactly( PolicyCheck( "h:${FOO_DTD.name} is DeletionTrigger(trigger=PACKAGE_UNINSTALLED, targetField=pkg1)" ), PolicyCheck( "h:${FOO_DTD.name} is DeletionTrigger(trigger=PACKAGE_UNINSTALLED, targetField=pkg2)" ) ) } @Test fun deletionTriggersParsed_Normally() { val triggers = FOO_TARGET.deletionTriggers() val expectedTriggers = setOf( DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg1"), DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg2") ) assertThat(triggers).isEqualTo(expectedTriggers) } private fun makeConnectionProvider(managedDataType: ManagedDataType): ConnectionProvider { return object : ConnectionProvider { override val dataType: DataType = managedDataType override fun getConnection(connectionRequest: ConnectionRequest<out Connection>): Connection = throw UnsupportedOperationException("Not used here") } } companion object { val FOO_DTD = dataTypeDescriptor("Foo", Unit::class) val BAR_DTD = dataTypeDescriptor("Bar", Unit::class) val BAZ_DTD = dataTypeDescriptor("Baz", Unit::class) val FOO_TARGET = target(FOO_DTD, maxAge = Duration.ofMinutes(5)) { retention(StorageMedium.RAM, false) deletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg1") deletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg2") } } }
apache-2.0
bfbe17480987ec07c8f255d0da82763c
34.046296
100
0.671466
4.785082
false
false
false
false
shymmq/librus-client-kotlin
app/src/test/kotlin/com/wabadaba/dziennik/InMemoryEntityStore.kt
1
2208
package com.wabadaba.dziennik import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.wabadaba.dziennik.ui.multiPutAll import io.reactivex.Observable import io.reactivex.Single import io.requery.Persistable import io.requery.reactivex.KotlinReactiveEntityStore import io.requery.reactivex.ReactiveResult import io.requery.reactivex.ReactiveScalar import kotlin.reflect.KClass import kotlin.reflect.full.superclasses @Suppress("UNCHECKED_CAST") class InMemoryEntityStore { companion object { fun getDatastore(): KotlinReactiveEntityStore<Persistable> { val multiMap = mutableMapOf<KClass<Persistable>, List<Persistable>>() return mock { on { upsert(any<List<Persistable>>()) } doAnswer { invocation -> val entities = invocation.getArgument<List<Persistable>>(0) if (entities.isNotEmpty()) { val kClass = entities.first()::class.superclasses[0] as KClass<Persistable> multiMap.multiPutAll(kClass, entities) } Single.just(entities) } on { select(any<KClass<Persistable>>()) } doAnswer { invocation -> val kClass = invocation.getArgument<KClass<Persistable>>(0) val res = multiMap[kClass] ?: emptyList() val resultMock = mock<ReactiveResult<Persistable>> { on { observable() } doReturn (Observable.fromIterable(res)) } mock { on { get() } doReturn resultMock } } on { delete(any<KClass<Persistable>>()) } doAnswer { invocation -> val kClass = invocation.getArgument<KClass<Persistable>>(0) multiMap.remove(kClass) val resultMock = mock<ReactiveScalar<Int>> { on { single() } doReturn (Single.just(0)) } mock { on { get() } doReturn resultMock } } } } } }
gpl-3.0
6dcb9e0b14f4c02fcdbc697a0ebe504b
41.480769
99
0.591033
5.146853
false
false
false
false
nhaarman/expect.kt
expect.kt/src/main/kotlin/com.nhaarman.expect/Fail.kt
1
1078
/* * Copyright 2017 Niek Haarman * * 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.nhaarman.expect fun fail(reason: String): Nothing = throw AssertionError(reason) fun fail(reason: String, message: (() -> Any?)? = null): Nothing { var m = reason message?.invoke()?.let { m = "$reason\n$it" } throw AssertionError(m) } fun fail(expected: Any?, actual: Any?, message: (() -> Any?)? = null): Nothing { val m = message?.invoke()?.let { "$it\n" } ?: "" throw AssertionError("${m}Expected: $expected but was: $actual\n") }
apache-2.0
f9618ea8d0ff35f296aa05c141ee7118
30.735294
80
0.678108
3.863799
false
false
false
false
Cardstock/Cardstock
src/main/kotlin/xyz/cardstock/cardstock/commands/GameChannelCommand.kt
1
1502
/* * 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 xyz.cardstock.cardstock.commands import org.kitteh.irc.client.library.element.Channel import org.kitteh.irc.client.library.element.User import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent import org.kitteh.irc.client.library.event.helper.ActorEvent import xyz.cardstock.cardstock.Cardstock import xyz.cardstock.cardstock.games.Game import xyz.cardstock.cardstock.players.Player /** * A command to be used during a game in a channel. */ abstract class GameChannelCommand<P : Player, G : Game<P>>(val cardstock: Cardstock, val mapper: (Channel) -> G?) : BaseCommand() { override fun run(event: ActorEvent<User>, callInfo: CallInfo, arguments: List<String>) { if (event !is ChannelMessageEvent) return val game = this.mapper(event.channel) val player = game?.getPlayer(event.actor, false) if (game == null || player == null) { event.actor.sendNotice("You are not in a game.") return } this.run(event, callInfo, game, player, arguments) } /** * Performs the action that this command is supposed to perform. Called every time that this command is used. */ abstract fun run(event: ChannelMessageEvent, callInfo: CallInfo, game: G, player: P, arguments: List<String>) }
mpl-2.0
8c8ed43ff58577337e02bebf1afe64e9
41.914286
131
0.709055
3.871134
false
false
false
false
etesync/android
app/src/main/java/com/etesync/syncadapter/AccountUpdateService.kt
1
2078
/* * Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ package com.etesync.syncadapter import android.app.Service import android.content.Intent import android.os.Binder import android.os.IBinder import java.lang.ref.WeakReference import java.util.* class AccountUpdateService : Service() { private val binder = InfoBinder() private val runningRefresh = HashSet<Long>() private val refreshingStatusListeners = LinkedList<WeakReference<RefreshingStatusListener>>() override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent != null) { val action = intent.action when (action) { } } return Service.START_NOT_STICKY } /* BOUND SERVICE PART for communicating with the activities */ override fun onBind(intent: Intent): IBinder? { return binder } interface RefreshingStatusListener { fun onDavRefreshStatusChanged(id: Long, refreshing: Boolean) } inner class InfoBinder : Binder() { fun isRefreshing(id: Long): Boolean { return runningRefresh.contains(id) } fun addRefreshingStatusListener(listener: RefreshingStatusListener, callImmediate: Boolean) { refreshingStatusListeners.add(WeakReference(listener)) if (callImmediate) for (id in runningRefresh) listener.onDavRefreshStatusChanged(id, true) } fun removeRefreshingStatusListener(listener: RefreshingStatusListener) { val iterator = refreshingStatusListeners.iterator() while (iterator.hasNext()) { val item = iterator.next().get() if (listener == item) iterator.remove() } } } }
gpl-3.0
bf2de0f3a8c51d1c407540e66e7286ab
27.819444
101
0.650602
4.964115
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryController.kt
2
10648
package eu.kanade.tachiyomi.ui.category import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.view.ActionMode import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.* import com.jakewharton.rxbinding.view.clicks import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.SelectableAdapter import eu.davidea.flexibleadapter.helpers.UndoHelper import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.util.toast import kotlinx.android.synthetic.main.categories_controller.* /** * Controller to manage the categories for the users' library. */ class CategoryController : NucleusController<CategoryPresenter>(), ActionMode.Callback, FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, CategoryAdapter.OnItemReleaseListener, CategoryCreateDialog.Listener, CategoryRenameDialog.Listener, UndoHelper.OnActionListener { /** * Object used to show ActionMode toolbar. */ private var actionMode: ActionMode? = null /** * Adapter containing category items. */ private var adapter: CategoryAdapter? = null /** * Undo helper used for restoring a deleted category. */ private var undoHelper: UndoHelper? = null /** * Creates the presenter for this controller. Not to be manually called. */ override fun createPresenter() = CategoryPresenter() /** * Returns the toolbar title to show when this controller is attached. */ override fun getTitle(): String? { return resources?.getString(R.string.action_edit_categories) } /** * Returns the view of this controller. * * @param inflater The layout inflater to create the view from XML. * @param container The parent view for this one. */ override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View { return inflater.inflate(R.layout.categories_controller, container, false) } /** * Called after view inflation. Used to initialize the view. * * @param view The view of this controller. */ override fun onViewCreated(view: View) { super.onViewCreated(view) adapter = CategoryAdapter(this@CategoryController) recycler.layoutManager = LinearLayoutManager(view.context) recycler.setHasFixedSize(true) recycler.adapter = adapter adapter?.isHandleDragEnabled = true adapter?.isPermanentDelete = false fab.clicks().subscribeUntilDestroy { CategoryCreateDialog(this@CategoryController).showDialog(router, null) } } /** * Called when the view is being destroyed. Used to release references and remove callbacks. * * @param view The view of this controller. */ override fun onDestroyView(view: View) { // Manually call callback to delete categories if required undoHelper?.onDeleteConfirmed(Snackbar.Callback.DISMISS_EVENT_MANUAL) undoHelper = null actionMode = null adapter = null super.onDestroyView(view) } /** * Called from the presenter when the categories are updated. * * @param categories The new list of categories to display. */ fun setCategories(categories: List<CategoryItem>) { actionMode?.finish() adapter?.updateDataSet(categories) if (categories.isNotEmpty()) { empty_view.hide() val selected = categories.filter { it.isSelected } if (selected.isNotEmpty()) { selected.forEach { onItemLongClick(categories.indexOf(it)) } } } else { empty_view.show(R.drawable.ic_shape_black_128dp, R.string.information_empty_category) } } /** * Called when action mode is first created. The menu supplied will be used to generate action * buttons for the action mode. * * @param mode ActionMode being created. * @param menu Menu used to populate action buttons. * @return true if the action mode should be created, false if entering this mode should be * aborted. */ override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { // Inflate menu. mode.menuInflater.inflate(R.menu.category_selection, menu) // Enable adapter multi selection. adapter?.mode = SelectableAdapter.Mode.MULTI return true } /** * Called to refresh an action mode's action menu whenever it is invalidated. * * @param mode ActionMode being prepared. * @param menu Menu used to populate action buttons. * @return true if the menu or action mode was updated, false otherwise. */ override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val adapter = adapter ?: return false val count = adapter.selectedItemCount mode.title = resources?.getString(R.string.label_selected, count) // Show edit button only when one item is selected val editItem = mode.menu.findItem(R.id.action_edit) editItem.isVisible = count == 1 return true } /** * Called to report a user click on an action button. * * @param mode The current ActionMode. * @param item The item that was clicked. * @return true if this callback handled the event, false if the standard MenuItem invocation * should continue. */ override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { val adapter = adapter ?: return false when (item.itemId) { R.id.action_delete -> { undoHelper = UndoHelper(adapter, this) undoHelper?.start(adapter.selectedPositions, view!!, R.string.snack_categories_deleted, R.string.action_undo, 3000) mode.finish() } R.id.action_edit -> { // Edit selected category if (adapter.selectedItemCount == 1) { val position = adapter.selectedPositions.first() val category = adapter.getItem(position)?.category if (category != null) { editCategory(category) } } } else -> return false } return true } /** * Called when an action mode is about to be exited and destroyed. * * @param mode The current ActionMode being destroyed. */ override fun onDestroyActionMode(mode: ActionMode) { // Reset adapter to single selection adapter?.mode = SelectableAdapter.Mode.IDLE adapter?.clearSelection() actionMode = null } /** * Called when an item in the list is clicked. * * @param position The position of the clicked item. * @return true if this click should enable selection mode. */ override fun onItemClick(position: Int): Boolean { // Check if action mode is initialized and selected item exist. if (actionMode != null && position != RecyclerView.NO_POSITION) { toggleSelection(position) return true } else { return false } } /** * Called when an item in the list is long clicked. * * @param position The position of the clicked item. */ override fun onItemLongClick(position: Int) { val activity = activity as? AppCompatActivity ?: return // Check if action mode is initialized. if (actionMode == null) { // Initialize action mode actionMode = activity.startSupportActionMode(this) } // Set item as selected toggleSelection(position) } /** * Toggle the selection state of an item. * If the item was the last one in the selection and is unselected, the ActionMode is finished. * * @param position The position of the item to toggle. */ private fun toggleSelection(position: Int) { val adapter = adapter ?: return //Mark the position selected adapter.toggleSelection(position) if (adapter.selectedItemCount == 0) { actionMode?.finish() } else { actionMode?.invalidate() } } /** * Called when an item is released from a drag. * * @param position The position of the released item. */ override fun onItemReleased(position: Int) { val adapter = adapter ?: return val categories = (0 until adapter.itemCount).mapNotNull { adapter.getItem(it)?.category } presenter.reorderCategories(categories) } /** * Called when the undo action is clicked in the snackbar. * * @param action The action performed. */ override fun onActionCanceled(action: Int, positions: MutableList<Int>?) { adapter?.restoreDeletedItems() undoHelper = null } /** * Called when the time to restore the items expires. * * @param action The action performed. * @param event The event that triggered the action */ override fun onActionConfirmed(action: Int, event: Int) { val adapter = adapter ?: return presenter.deleteCategories(adapter.deletedItems.map { it.category }) undoHelper = null } /** * Show a dialog to let the user change the category name. * * @param category The category to be edited. */ private fun editCategory(category: Category) { CategoryRenameDialog(this, category).showDialog(router) } /** * Renames the given category with the given name. * * @param category The category to rename. * @param name The new name of the category. */ override fun renameCategory(category: Category, name: String) { presenter.renameCategory(category, name) } /** * Creates a new category with the given name. * * @param name The name of the new category. */ override fun createCategory(name: String) { presenter.createCategory(name) } /** * Called from the presenter when a category with the given name already exists. */ fun onCategoryExistsError() { activity?.toast(R.string.error_category_exists) } }
apache-2.0
fbfabbb335b78e2c044fadfb74913f9b
31.96904
99
0.637209
4.913706
false
false
false
false
SourceUtils/hl2-utils
src/main/kotlin/com/timepath/hl2/DEMTest.kt
1
11484
package com.timepath.hl2 import com.timepath.Logger import com.timepath.hex.HexEditor import com.timepath.hl2.io.demo.HL2DEM import com.timepath.hl2.io.demo.Message import com.timepath.hl2.io.demo.MessageType import com.timepath.hl2.io.demo.Packet import com.timepath.plaf.x.filechooser.BaseFileChooser import com.timepath.plaf.x.filechooser.NativeFileChooser import com.timepath.steam.SteamUtils import com.timepath.with import org.jdesktop.swingx.JXFrame import org.jdesktop.swingx.JXTable import org.jdesktop.swingx.JXTree import org.jdesktop.swingx.decorator.AbstractHighlighter import org.jdesktop.swingx.decorator.ComponentAdapter import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.awt.* import java.awt.event.ActionListener import java.beans.PropertyVetoException import java.io.File import java.io.IOException import java.util.ArrayList import java.util.concurrent.ExecutionException import java.util.logging.Level import javax.swing.* import javax.swing.event.ListSelectionListener import javax.swing.event.TreeSelectionListener import javax.swing.table.AbstractTableModel import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import kotlin.platform.platformStatic public class DEMTest() : JPanel() { protected val menu: JMenuBar protected val hex: HexEditor protected val tabs: JTabbedPane protected val table: JXTable protected val tree: JXTree protected val tableModel: MessageModel init { tableModel = MessageModel() table = JXTable() with { setAutoCreateRowSorter(true) setColumnControlVisible(true) setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED) setModel(tableModel) setSelectionMode(ListSelectionModel.SINGLE_SELECTION) } tree = JXTree() with { setModel(DefaultTreeModel(DefaultMutableTreeNode("root"))) setRootVisible(false) setShowsRootHandles(true) } tabs = JTabbedPane() with { setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)) addTab("Hierarchy", JScrollPane(tree)) } hex = HexEditor() table.addHighlighter(object : AbstractHighlighter() { override fun doHighlight(component: Component, adapter: ComponentAdapter): Component { if (adapter.row >= 0 && tableModel.messages.size() > 0 && adapter.row < tableModel.messages.size()) { val msg = tableModel.messages[table.convertRowIndexToModel(adapter.row)] component.setBackground(when { adapter.isSelected() -> component.getBackground() else -> when { msg.incomplete -> Color.ORANGE else -> when (msg.type) { MessageType.Signon, MessageType.Packet -> Color.CYAN MessageType.UserCmd -> Color.GREEN MessageType.ConsoleCmd -> Color.PINK else -> Color.WHITE } } }) } return component } }) table.getSelectionModel().addListSelectionListener(ListSelectionListener { val row = table.getSelectedRow() if (row == -1) return@ListSelectionListener val frame = tableModel.messages[table.convertRowIndexToModel(row)] hex.setData(frame.data) val root = DefaultMutableTreeNode(frame) recurse(frame.meta, root) tree.setModel(DefaultTreeModel(DefaultMutableTreeNode() with { add(root) })) run { var i = -1 while (++i < tree.getRowCount()) { // Expand all val node = tree.getPathForRow(i).getLastPathComponent() as DefaultMutableTreeNode if (node.getLevel() < 3) tree.expandRow(i) } } }) tree.getSelectionModel().addTreeSelectionListener(TreeSelectionListener { val selectionPath = tree.getSelectionPath() ?: return@TreeSelectionListener val lastPathComponent = selectionPath.getLastPathComponent() val o = (lastPathComponent as DefaultMutableTreeNode).getUserObject() if (o is Packet) { try { val offsetBytes = o.offset / 8 val offsetBits = o.offset % 8 hex.seek((offsetBytes - (offsetBytes % 16)).toLong()) // Start of row hex.caretLocation = (offsetBytes.toLong()) hex.bitShift = (offsetBits) hex.update() } catch (e: PropertyVetoException) { e.printStackTrace() } } }) menu = JMenuBar() with { add(JMenu("File") with { setMnemonic('F') add(JMenuItem("Open") with { addActionListener(ActionListener { open() }) }) add(JMenuItem("Dump commands") with { addActionListener(ActionListener { showCommands() }) }) }) } setLayout(BorderLayout()) add(JSplitPane() with { setResizeWeight(1.0) setContinuousLayout(true) setOneTouchExpandable(true) setLeftComponent(JScrollPane(table)) setRightComponent(JSplitPane() with { setOrientation(JSplitPane.VERTICAL_SPLIT) setResizeWeight(1.0) setContinuousLayout(true) setOneTouchExpandable(true) setTopComponent(tabs) setRightComponent(hex) }) }) } protected fun recurse(iter: List<*>, parent: DefaultMutableTreeNode) { for (e in iter) { if (e !is Pair<*, *>) continue val v = e.second when (v) { is List<*> -> recurse(v, DefaultMutableTreeNode(e.first) with { parent.add(this) }) else -> parent.add(DefaultMutableTreeNode(e)) } } } protected fun open() { try { val fs = NativeFileChooser() .setTitle("Open DEM") .setDirectory(File(SteamUtils.getSteamApps(), "common/Team Fortress 2/tf/.")) .addFilter(BaseFileChooser.ExtensionFilter("Demo files", "dem")) .choose() ?: return object : SwingWorker<HL2DEM, Message>() { val listEvt = DefaultListModel<Pair<*, *>>() val listMsg = DefaultListModel<Pair<*, *>>() var incomplete = 0 override fun doInBackground(): HL2DEM { tableModel.messages.clear() val demo = HL2DEM.load(fs[0]) val frames = demo.frames // TODO: Stream publish(*frames.toTypedArray()) return demo } override fun process(chunks: List<Message>) { for (msg in chunks) { if (msg.incomplete) incomplete++ tableModel.messages.add(msg) when (msg.type) { MessageType.Packet, MessageType.Signon -> for ((k, v) in msg.meta) { if (k !is Packet) continue if (v !is List<*>) continue for (e in v) { if (e !is Pair<*, *>) continue when (k.type) { Packet.svc_GameEvent -> listEvt Packet.svc_UserMessage -> listMsg else -> null }?.addElement(e) } } } } tableModel.fireTableDataChanged() // FIXME } override fun done() { val demo = try { get() } catch (ignored: InterruptedException) { return } catch (e: ExecutionException) { LOG.log(Level.SEVERE, { null }, e) return } LOG.info({ "Total incomplete messages: ${incomplete} / ${demo.frames.size()}" }) while (tabs.getTabCount() > 1) tabs.remove(1) // Remove previous events and messages tabs.add("Events", JScrollPane(JList(listEvt)) with { getVerticalScrollBar().setUnitIncrement(16) }) tabs.add("Messages", JScrollPane(JList(listMsg)) with { getVerticalScrollBar().setUnitIncrement(16) }) table.setModel(tableModel) } }.execute() } catch (e: IOException) { LOG.log(Level.SEVERE, { null }, e) } } protected fun showCommands() { val sb = StringBuilder() for (m in tableModel.messages) { if (m.type != MessageType.ConsoleCmd) continue for (p in m.meta) { sb.append('\n').append(p.singletonOrEmptyList()) } } JOptionPane.showMessageDialog(this, JScrollPane(JTextArea(if (sb.length() > 0) sb.substring(1) else "")) with { setPreferredSize(Dimension(500, 500)) } ) } protected inner class MessageModel : AbstractTableModel() { val messages: MutableList<Message> = ArrayList() override fun getRowCount() = messages.size() protected val columns: Array<String> = arrayOf("Tick", "Type", "Size") protected val types: Array<Class<*>> = arrayOf(javaClass<Int>(), javaClass<Enum<*>>(), javaClass<Int>()) override fun getColumnCount() = columns.size() override fun getColumnName(columnIndex: Int) = columns[columnIndex] override fun getColumnClass(columnIndex: Int) = types[columnIndex] override fun isCellEditable(rowIndex: Int, columnIndex: Int) = false override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? { if (messages.isEmpty()) return null val m = messages[rowIndex] when (columnIndex) { 0 -> return m.tick 1 -> return m.type 2 -> return m.data?.capacity() } return null } } companion object { private val LOG = Logger() public platformStatic fun main(args: Array<String>) { EventQueue.invokeLater { JXFrame("netdecode") with { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) val demTest = DEMTest() setContentPane(demTest) setJMenuBar(demTest.menu) pack() setLocationRelativeTo(null) setVisible(true) } } } } }
artistic-2.0
1499e33c805767fdaaec86ca434deccd
39.153846
117
0.530738
5.356343
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hil/psi/impl/ILExpressionBase.kt
1
1911
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hil.psi.impl import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElementVisitor import org.intellij.plugins.hcl.psi.HCLElement import org.intellij.plugins.hil.psi.ILElementVisitor import org.intellij.plugins.hil.psi.ILExpression abstract class ILExpressionBase(node: ASTNode) : ASTWrapperPsiElement(node), ILExpression { override fun accept(visitor: PsiElementVisitor) { if (visitor is ILElementVisitor) { visitor.visitILExpression(this) } else { visitor.visitElement(this) } } open fun getTypeClass(): Class<out Any>? { return null } override fun toString(): String { val name = this.javaClass.simpleName val trimmed = StringUtil.trimEnd(name, "Impl") if (trimmed.startsWith("ILBinary")) return "ILBinaryExpression" if ("ILLiteralExpression" == trimmed || "ILParameterListExpression" == trimmed) return StringUtil.trimEnd(trimmed, "Expression") return trimmed } } fun ILExpression.getHCLHost(): HCLElement? { val host = InjectedLanguageManager.getInstance(this.project).getInjectionHost(this) return if (host is HCLElement) host else null }
apache-2.0
5c015a9ca01b9df13bd01290faf6d8c2
34.388889
132
0.758765
4.172489
false
false
false
false
eugeis/ee
ee-design_swagger/src/main/kotlin/ee/design/swagger/SwaggerToDesign.kt
1
10980
package ee.design.swagger import ee.common.ext.* import ee.design.DslTypes import ee.design.Module import ee.lang.* import ee.lang.gen.kt.toDslDoc import io.swagger.models.* import io.swagger.models.parameters.Parameter import io.swagger.models.parameters.RefParameter import io.swagger.models.parameters.SerializableParameter import io.swagger.models.properties.* import io.swagger.parser.SwaggerParser import org.slf4j.LoggerFactory import java.nio.file.Path import java.util.* private val log = LoggerFactory.getLogger("SwaggerToDesign") class SwaggerToDesign( private val pathsToEntityNames: MutableMap<String, String> = mutableMapOf(), private val namesToTypeName: MutableMap<String, String> = mutableMapOf(), private val ignoreTypes: MutableSet<String> = mutableSetOf()) { fun toDslTypes(swaggerFile: Path): DslTypes = SwaggerToDesignExecutor(swaggerFile, namesToTypeName, ignoreTypes).toDslTypes() } private class SwaggerToDesignExecutor( swaggerFile: Path, private val namesToTypeName: MutableMap<String, String> = mutableMapOf(), private val ignoreTypes: MutableSet<String> = mutableSetOf()) { private val log = LoggerFactory.getLogger(javaClass) private val primitiveTypes = mapOf("integer" to "n.Int", "string" to "n.String") private val typeToPrimitive = mutableMapOf<String, String>() private val swagger = SwaggerParser().read(swaggerFile.toString()) private val typesToFill = TreeMap<String, String>() fun toDslTypes(): DslTypes { extractTypeDefsFromPrimitiveAliases().forEach { it.value.toDslValues(it.key.toDslTypeName()) } return DslTypes(name = swagger.info?.title ?: "", desc = "", types = typesToFill) } private fun extractTypeDefsFromPrimitiveAliases(): Map<String, io.swagger.models.Model> { val ret = mutableMapOf<String, io.swagger.models.Model>() swagger.definitions?.entries?.forEach { (defName, def) -> if (!ignoreTypes.contains(defName)) { if (def is ModelImpl && def.isPrimitive()) { typeToPrimitive[defName] = primitiveTypes[def.type]!! typeToPrimitive[defName.toDslTypeName()] = primitiveTypes[def.type]!! } else { ret[defName] = def } } else { log.debug("ignore type ") } } return ret } private fun Model.isPrimitive() = this is ModelImpl && (enum == null || enum.isEmpty()) && primitiveTypes.containsKey(type) private fun Swagger.toModule(): Module { return Module { name("Shared") definitions?.forEach { defName, def -> values(def.toValues(defName)) } }.init() } private fun Map<String, Property>?.toDslProperties(): String { return (this != null).ifElse( { this!!.entries.joinToString(nL, nL) { it.value.toDslProp(it.key) } }, { "" }) } private fun io.swagger.models.properties.Property.toDslProp(name: String): String { val nameCamelCase = name.toCamelCase() return " val $nameCamelCase = prop { ${(name != nameCamelCase) .then { "externalName(\"$name\")." }}${toDslInit(nameCamelCase)} }" } private fun Property.toDslPropValue(name: String, suffix: String = "", prefix: String = ""): String { return ((this is StringProperty && default.isNullOrEmpty().not())).ifElse({ "${suffix}value(${(this as StringProperty).enum.isNotEmpty().ifElse({ "$name.${default.toUnderscoredUpperCase()}" }, { "\"$name.$default\"" })})$prefix" }, { "" }) } private fun io.swagger.models.Model.toDslValues(name: String) { if (this is ComposedModel) { typesToFill[name] = """ object ${name.toDslTypeName()} : Values({ ${ interfaces.joinSurroundIfNotEmptyToString(",", "superUnit(", ")") { it.simpleRef.toDslTypeName() }}${description.toDslDoc()} }) {${allOf.filterNot { interfaces.contains(it) }.joinToString("") { it.properties.toDslProperties() }} }""" } else if (this is ArrayModel) { val prop = items if (prop is ObjectProperty) { val typeName = prop.toDslTypeName() typesToFill[typeName] = prop.toDslType(typeName) } else { log.info("not supported yet {} {}", this, prop) } } else if (this is ModelImpl && this.enum != null && this.enum.isNotEmpty()) { typesToFill[name] = """ object $name : EnumType(${description.toDslDoc("{", "}")}) {${ enum.joinToString(nL, nL) { val externalName = it.toString() val literalName = externalName.toUnderscoredUpperCase() val init = if (literalName != externalName) " { externalName(\"$externalName\") }" else "()" " val $literalName = lit$init" }} }""" } else { typesToFill[name] = """ object ${name.toDslTypeName()} : Values(${ description.toDslDoc("{ ", " }")}) {${ properties.toDslProperties()} }""" } } private fun io.swagger.models.properties.StringProperty.toDslEnum(name: String): String { return """ object $name : EnumType(${description.toDslDoc("{", "}")}) {${ enum.joinToString(nL, nL) { val externalName = it.toString() val literalName = externalName.toUnderscoredUpperCase() val init = if (literalName != externalName) " { externalName(\"$externalName\") }" else "()" " val $literalName = lit$init" }} }""" } private fun io.swagger.models.properties.ObjectProperty.toDslType(name: String): String { return """ object $name : Values(${description.toDslDoc("{", "}")}) {${properties.toDslProperties()} }""" } private fun io.swagger.models.properties.Property.toDslTypeName(name: String): String { val prop = this return when (prop) { is ArrayProperty -> { "n.List.GT(${prop.items.toDslTypeName(name)})" } is BinaryProperty -> { "n.Bytes" } is BooleanProperty -> { "n.Boolean" } is ByteArrayProperty -> { "n.Bytes" } is DateProperty -> { "n.Date" } is DateTimeProperty -> { "n.Date" } is DecimalProperty -> { "n.Double" } is DoubleProperty -> { "n.Double" } is EmailProperty -> { "n.String" } is FileProperty -> { "n.File" } is FloatProperty -> { "n.Float" } is IntegerProperty -> { "n.Int" } is BaseIntegerProperty -> { "n.Int" } is LongProperty -> { "n.Long" } is MapProperty -> { "n.Map" } is ObjectProperty -> { val typeName = prop.toDslTypeName() if (!typesToFill.containsKey(typeName)) { typesToFill[typeName] = prop.toDslType(typeName) } typeName } is PasswordProperty -> { "n.String" } is UntypedProperty -> { "n.String" } is UUIDProperty -> { "n.String" } is RefProperty -> { prop.simpleRef.toDslTypeName() } is StringProperty -> { if (prop.enum != null && prop.enum.isNotEmpty()) { val typeName = name.toDslTypeName() if (!typesToFill.containsKey(typeName)) { typesToFill[typeName] = prop.toDslEnum(typeName) } typeName } else { "n.String" } } else -> { "" } } } private fun Parameter.toDslTypeName(name: String): String { val prop = this return when (prop) { is SerializableParameter -> { primitiveTypes.getOrDefault(prop.type, "n.String") } is RefParameter -> { swagger.parameters[prop.simpleRef]!!.toDslTypeName(name) } else -> { log.warn("can't find type for {}, use n.String", prop) "n.String" } } } private fun ObjectProperty.toDslTypeName(): String = properties.keys.joinToString( "") { it.capitalize() }.toDslTypeName() private fun String.toDslTypeName(): String { return typeToPrimitive[this] ?: namesToTypeName.getOrPut(this) { toCamelCase().capitalize() } } private fun io.swagger.models.properties.Property.toDslInit(name: String): String { return if (this is RefProperty) { if (swagger.parameters != null && swagger.parameters.containsKey(simpleRef)) { swagger.parameters[simpleRef]!!.toDslInit(name) } else if (swagger.definitions != null && swagger.definitions.containsKey(simpleRef)) { toDslInitDirect(name) } else { toDslInitDirect(name) } } else { toDslInitDirect(name) } } private fun Parameter.toDslInit(name: String): String { val typeName = toDslTypeName(name) return "type($typeName)${required.not().then { ".nullable()" }}${description.toDslDoc(".")}" } private fun io.swagger.models.properties.Property.toDslInitDirect(name: String): String { val typeName = toDslTypeName(name) return "type($typeName)${required.not().then { ".nullable()" }}${(this is PasswordProperty) .then { ".hidden()" }}${toDslPropValue(typeName, ".")}${description.toDslDoc(".")}" } private fun io.swagger.models.Model.toValues(name: String): Values { val model = this return Values { name(name).doc(model.description ?: "") model.properties?.forEach { propName, p -> prop { name(propName).type(p.type.toType()).doc(p.description ?: "") } } }.init() } private fun String?.toType(): TypeI<*> { return if (this == null) { n.String } else { log.info("type: {}", this) n.String } } }
apache-2.0
1564ea4b532412be769a06b8fa0c4ab1
34.305466
108
0.534153
4.843405
false
false
false
false
AlmasB/GroupNet
src/main/kotlin/icurves/graph/GraphCycle.kt
1
1038
package icurves.graph import javafx.geometry.Point2D import javafx.scene.shape.Path /** * * * @author Almas Baimagambetov ([email protected]) */ data class GraphCycle<V, E>(val nodes: List<V>, val edges: List<E>) { lateinit var path: Path lateinit var smoothingData: MutableList<Point2D> fun length() = nodes.size /** * Computes length - nodes that lie in the same basic region */ fun lengthUnique() = nodesUnique().size fun nodesUnique() = nodes.map { it as EulerDualNode }.distinctBy { it.zone.toString() } // fun contains(node: V): Boolean { // for (n in nodes) { // if (n.toString() == node.toString()) { // return true // } // } // // return false // } // fun contains(zones: List<AbstractBasicRegion>): Boolean { // val mappedNodes = nodes.map { it.zone.abstractZone } // // return mappedNodes.containsAll(zones) // } override fun toString(): String { return nodes.joinToString() } }
apache-2.0
d450a694a4abf5519044fe8701732c54
22.088889
91
0.599229
3.707143
false
false
false
false
guoxiaoxing/material-design-music-player
cloud/src/main/java/com/guoxiaoxing/cloud/music/ui/activity/MainActivity.kt
1
8813
package com.guoxiaoxing.cloud.music.ui.activity import android.app.Activity import android.app.ActivityManager import android.content.Intent import android.os.Build import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.support.v7.widget.Toolbar import android.view.Gravity import android.view.KeyEvent import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.ImageView import android.widget.Toast import com.guoxiaoxing.cloud.music.R import com.guoxiaoxing.cloud.music.adapter.MenuItemAdapter import com.guoxiaoxing.cloud.music.handler.HandlerUtil import com.guoxiaoxing.cloud.music.magicasakura.utils.ThemeUtils import com.guoxiaoxing.cloud.music.ui.BaseActivity import com.guoxiaoxing.cloud.music.ui.fragment.BitSetFragment import com.guoxiaoxing.cloud.music.ui.fragment.MineFragment import com.guoxiaoxing.cloud.music.ui.fragment.TimingFragment import com.guoxiaoxing.cloud.music.ui.fragment.MusicLibraryFragment import com.guoxiaoxing.cloud.music.service.MusicPlayer import com.guoxiaoxing.cloud.music.uitl.ThemeHelper import com.guoxiaoxing.cloud.music.widget.CustomViewPager import com.guoxiaoxing.cloud.music.widget.SplashScreen import com.guoxiaoxing.cloud.music.widget.dialog.CardPickerDialog import kotlinx.android.synthetic.main.activity_main.* import java.util.ArrayList class MainActivity : BaseActivity(), CardPickerDialog.ClickListener { private val tabs = ArrayList<ImageView?>() private var time: Long = 0 var splashScreen: SplashScreen? = null override fun onCreate(savedInstanceState: Bundle?) { splashScreen = SplashScreen(this) splashScreen?.show(R.drawable.art_login_bg, SplashScreen.SLIDE_LEFT) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) window.setBackgroundDrawableResource(R.color.background_material_light_1) setToolBar() setViewPager() setupDrawer() HandlerUtil.getInstance(this).postDelayed({ splashScreen?.removeSplashScreen() }, 3000) } private fun setToolBar() { val toolbar = findViewById(R.id.activity_main_toolbar) as Toolbar setSupportActionBar(toolbar) val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) actionBar?.setHomeAsUpIndicator(R.drawable.ic_menu) actionBar?.title = "" } private fun setViewPager() { tabs.add(activity_main_bar_music_library) tabs.add(activity_main_bar_mine) val customViewPager = findViewById(R.id.activity_main_viewpager) as CustomViewPager val mineFragment = MineFragment() val musicLibraryFragment = MusicLibraryFragment() val customViewPagerAdapter = CustomViewPagerAdapter(supportFragmentManager) customViewPagerAdapter.addFragment(musicLibraryFragment) customViewPagerAdapter.addFragment(mineFragment) customViewPager.adapter = customViewPagerAdapter customViewPager.currentItem = 1 activity_main_bar_mine.isSelected = true customViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { switchTabs(position) } override fun onPageScrollStateChanged(state: Int) { } }) activity_main_bar_music_library.setOnClickListener { customViewPager.currentItem = 0 } activity_main_bar_mine.setOnClickListener { customViewPager.currentItem = 1 } activity_main_bar_search.setOnClickListener { val intent = Intent(this@MainActivity, NetSearchWordsActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NO_ANIMATION [email protected](intent) } } private fun setupDrawer() { val inflater = LayoutInflater.from(this) activity_main_id_lv_left_menu.addHeaderView(inflater.inflate(R.layout.nav_header_main, activity_main_id_lv_left_menu, false)) activity_main_id_lv_left_menu.adapter = MenuItemAdapter(this) activity_main_id_lv_left_menu.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> when (position) { 1 -> activity_main_fd.closeDrawers() 2 -> { val dialog = CardPickerDialog() dialog.setClickListener(this@MainActivity) dialog.show(supportFragmentManager, "theme") activity_main_fd.closeDrawers() } 3 -> { val fragment3 = TimingFragment() fragment3.show(supportFragmentManager, "timing") activity_main_fd.closeDrawers() } 4 -> { val bfragment = BitSetFragment() bfragment.show(supportFragmentManager, "bitset") activity_main_fd.closeDrawers() } 5 -> { if (MusicPlayer.isPlaying()) { MusicPlayer.playOrPause() } unbindService() finish() activity_main_fd.closeDrawers() } } } } private fun switchTabs(position: Int) { for (i in tabs.indices) { tabs.get(i)?.isSelected = position == i } } override fun onConfirm(currentTheme: Int) { if (ThemeHelper.getTheme(this@MainActivity) != currentTheme) { ThemeHelper.setTheme(this@MainActivity, currentTheme) ThemeUtils.refreshUI(this@MainActivity, object : ThemeUtils.ExtraRefreshable { override fun refreshGlobal(activity: Activity) { //for global setting, just do once if (Build.VERSION.SDK_INT >= 21) { val context = this@MainActivity val taskDescription = ActivityManager.TaskDescription(null, null, ThemeUtils.getThemeAttrColor(context, android.R.attr.colorPrimary)) setTaskDescription(taskDescription) window.statusBarColor = ThemeUtils.getColorById(context, R.color.theme_color_primary) } } override fun refreshSpecificView(view: View) {} } ) } changeTheme() } internal class CustomViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { private val mFragments = ArrayList<Fragment>() fun addFragment(fragment: Fragment) { mFragments.add(fragment) } override fun getItem(position: Int): Fragment { return mFragments[position] } override fun getCount(): Int { return mFragments.size } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home //Menu icon -> { activity_main_fd.openDrawer(Gravity.LEFT) return true } else -> return super.onOptionsItemSelected(item) } } override fun onDestroy() { super.onDestroy() splashScreen?.removeSplashScreen() } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { if (System.currentTimeMillis() - time > 1000) { Toast.makeText(this, "再按一次返回桌面", Toast.LENGTH_SHORT).show() time = System.currentTimeMillis() } else { val intent = Intent(Intent.ACTION_MAIN) intent.addCategory(Intent.CATEGORY_HOME) startActivity(intent) } return true } else { return super.onKeyDown(keyCode, event) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) val fragments = supportFragmentManager.fragments if (fragments != null) { for (fragment in fragments) { fragment?.onRequestPermissionsResult(requestCode, permissions, grantResults) } } } override fun onBackPressed() { super.onBackPressed() } }
apache-2.0
095c8019393c7960ae915b41566f4823
37.082251
157
0.644538
5.058654
false
false
false
false
pwittchen/ReactiveNetwork
app-kotlin/src/main/kotlin/com/github/pwittchen/reactivenetwork/kotlinapp/MainActivity.kt
1
2485
/* * Copyright (C) 2016 Piotr Wittchen * * 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.pwittchen.reactivenetwork.kotlinapp import android.app.Activity import android.os.Bundle import android.util.Log import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_main.connectivity_status import kotlinx.android.synthetic.main.activity_main.internet_status class MainActivity : Activity() { private var connectivityDisposable: Disposable? = null private var internetDisposable: Disposable? = null companion object { private val TAG = "ReactiveNetwork" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onResume() { super.onResume() connectivityDisposable = ReactiveNetwork.observeNetworkConnectivity(applicationContext) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { connectivity -> Log.d(TAG, connectivity.toString()) val state = connectivity.state() val name = connectivity.typeName() connectivity_status.text = String.format("state: %s, typeName: %s", state, name) } internetDisposable = ReactiveNetwork.observeInternetConnectivity() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { isConnectedToInternet -> internet_status.text = isConnectedToInternet.toString() } } override fun onPause() { super.onPause() safelyDispose(connectivityDisposable) safelyDispose(internetDisposable) } private fun safelyDispose(disposable: Disposable?) { if (disposable != null && !disposable.isDisposed) { disposable.dispose() } } }
apache-2.0
ef35568912b18114788be34da658f462
33.054795
91
0.744467
4.542962
false
false
false
false
siempredelao/Distance-From-Me-Android
app/src/main/java/gc/david/dfm/ui/fragment/OpenSourceMasterFragment.kt
1
5907
/* * Copyright (c) 2019 David Aguiar Gonzalez * * 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 gc.david.dfm.ui.fragment import android.os.Bundle import android.transition.Fade import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import butterknife.BindView import butterknife.ButterKnife import com.google.android.material.snackbar.Snackbar import gc.david.dfm.DFMApplication import gc.david.dfm.R import gc.david.dfm.adapter.OpenSourceLibraryAdapter import gc.david.dfm.dagger.DaggerOpenSourceComponent import gc.david.dfm.dagger.OpenSourceModule import gc.david.dfm.dagger.RootModule import gc.david.dfm.logger.DFMLogger import gc.david.dfm.opensource.domain.OpenSourceUseCase import gc.david.dfm.opensource.presentation.OpenSource import gc.david.dfm.opensource.presentation.OpenSourcePresenter import gc.david.dfm.opensource.presentation.mapper.OpenSourceLibraryMapper import gc.david.dfm.opensource.presentation.model.OpenSourceLibraryModel import gc.david.dfm.ui.animation.DetailsTransition import javax.inject.Inject /** * Created by david on 24.01.17. */ class OpenSourceMasterFragment : Fragment(), OpenSource.View { @BindView(R.id.opensourcelibrary_fragment_recyclerview) lateinit var recyclerView: RecyclerView @BindView(R.id.opensourcelibrary_fragment_progressbar) lateinit var progressbar: ProgressBar @Inject lateinit var openSourceUseCase: OpenSourceUseCase @Inject lateinit var openSourceLibraryMapper: OpenSourceLibraryMapper private lateinit var presenter: OpenSource.Presenter private lateinit var adapter: OpenSourceLibraryAdapter private val listener = object : OnItemClickListener { override fun onItemClick(openSourceLibraryModel: OpenSourceLibraryModel, viewHolder: OpenSourceLibraryAdapter.OpenSourceLibraryViewHolder) { val openSourceDetailFragment = OpenSourceDetailFragment().apply { val changeBoundsTransition = DetailsTransition() val fadeTransition = Fade() [email protected] = fadeTransition sharedElementEnterTransition = changeBoundsTransition enterTransition = fadeTransition sharedElementReturnTransition = changeBoundsTransition arguments = bundleOf(OpenSourceDetailFragment.LIBRARY_KEY to openSourceLibraryModel) } requireActivity().supportFragmentManager .beginTransaction() .addSharedElement(viewHolder.tvName, getString(R.string.transition_opensourcelibrary_name)) .addSharedElement(viewHolder.tvShortLicense, getString(R.string.transition_opensourcelibrary_description)) .replace(R.id.about_activity_container_framelayout, openSourceDetailFragment) .addToBackStack(null) .commit() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DaggerOpenSourceComponent.builder() .rootModule(RootModule(requireActivity().application as DFMApplication)) .openSourceModule(OpenSourceModule()) .build() .inject(this) adapter = OpenSourceLibraryAdapter(listener) presenter = OpenSourcePresenter(this, openSourceUseCase, openSourceLibraryMapper) presenter.start() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_opensourcelibrary_master, container, false) ButterKnife.bind(this, view) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { if (adapter.itemCount != 0) { hideLoading() setupList() } } override fun setPresenter(presenter: OpenSource.Presenter) { this.presenter = presenter } override fun showLoading() { if (view != null) { // Workaround: at this point, onCreateView could not have been executed progressbar.isVisible = true recyclerView.isVisible = false } } override fun hideLoading() { progressbar.isVisible = false recyclerView.isVisible = true } override fun add(openSourceLibraryModelList: List<OpenSourceLibraryModel>) { adapter.add(openSourceLibraryModelList) } override fun showError(errorMessage: String) { DFMLogger.logException(Exception(errorMessage)) Snackbar.make(recyclerView, R.string.opensourcelibrary_error_message, Snackbar.LENGTH_LONG).show() } override fun setupList() { recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.adapter = adapter } interface OnItemClickListener { fun onItemClick(openSourceLibraryModel: OpenSourceLibraryModel, item: OpenSourceLibraryAdapter.OpenSourceLibraryViewHolder) } }
apache-2.0
d267de6f678ee36a53dd257bc96c5371
36.865385
131
0.71847
5.250667
false
false
false
false
Shynixn/PetBlocks
petblocks-bukkit-plugin/petblocks-bukkit-nms-108R3/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_8_R3/NMSPetArmorstand.kt
1
18483
@file:Suppress("UNCHECKED_CAST") package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_8_R3 import com.github.shynixn.petblocks.api.PetBlocksApi import com.github.shynixn.petblocks.api.bukkit.event.PetBlocksAIPreChangeEvent import com.github.shynixn.petblocks.api.business.proxy.EntityPetProxy import com.github.shynixn.petblocks.api.business.proxy.NMSPetProxy import com.github.shynixn.petblocks.api.business.proxy.PetProxy import com.github.shynixn.petblocks.api.business.service.AIService import com.github.shynixn.petblocks.api.business.service.ConfigurationService import com.github.shynixn.petblocks.api.business.service.LoggingService import com.github.shynixn.petblocks.api.persistence.entity.* import com.github.shynixn.petblocks.core.logic.business.extension.hasChanged import com.github.shynixn.petblocks.core.logic.business.extension.relativeFront import com.github.shynixn.petblocks.core.logic.persistence.entity.PositionEntity import net.minecraft.server.v1_8_R3.* import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.craftbukkit.v1_8_R3.CraftWorld import org.bukkit.entity.ArmorStand import org.bukkit.entity.LivingEntity import org.bukkit.entity.Player import org.bukkit.event.entity.CreatureSpawnEvent import org.bukkit.util.Vector import java.lang.reflect.Field /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class NMSPetArmorstand(owner: Player, val petMeta: PetMeta) : EntityArmorStand((owner.location.world as CraftWorld).handle), NMSPetProxy { private var internalProxy: PetProxy? = null private var jumpingField: Field = EntityLiving::class.java.getDeclaredField("aY") private var internalHitBox: EntityInsentient? = null private val aiService = PetBlocksApi.resolve(AIService::class.java) private val flyCanHitWalls = PetBlocksApi.resolve(ConfigurationService::class.java) .findValue<Boolean>("global-configuration.fly-wall-colision") private var flyHasTakenOffGround = false private var flyIsOnGround: Boolean = false private var flyHasHitFloor: Boolean = false private var flyWallCollisionVector: Vector? = null /** * Proxy handler. */ override val proxy: PetProxy get() = internalProxy!! /** * Initializes the nms design. */ init { jumpingField.isAccessible = true val location = owner.location val mcWorld = (location.world as CraftWorld).handle val position = PositionEntity() position.x = location.x position.y = location.y position.z = location.z position.yaw = location.yaw.toDouble() position.pitch = location.pitch.toDouble() position.worldName = location.world.name position.relativeFront(3.0) this.setPositionRotation(position.x, position.y, position.z, location.yaw, location.pitch) mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM) internalProxy = Class.forName("com.github.shynixn.petblocks.bukkit.logic.business.proxy.PetProxyImpl") .getDeclaredConstructor(PetMeta::class.java, ArmorStand::class.java, Player::class.java) .newInstance(petMeta, this.bukkitEntity, owner) as PetProxy petMeta.propertyTracker.onPropertyChanged(PetMeta::aiGoals, true) applyNBTTagForArmorstand() } /** * Spawns a new hitbox */ private fun spawnHitBox() { val shouldDeleteHitBox = shouldDeleteHitBox() if (shouldDeleteHitBox && internalHitBox != null) { (internalHitBox!!.bukkitEntity as EntityPetProxy).deleteFromWorld() internalHitBox = null proxy.changeHitBox(internalHitBox) } val player = proxy.getPlayer<Player>() this.applyNBTTagForArmorstand() val hasRidingAi = petMeta.aiGoals.count { a -> a is AIGroundRiding || a is AIFlyRiding } > 0 if (hasRidingAi) { val armorstand = proxy.getHeadArmorstand<ArmorStand>() if (armorstand.passenger != player) { armorstand.velocity = Vector(0, 1, 0) armorstand.passenger = player } return } else { if (player.passenger != null) { player.eject() } } val aiWearing = this.petMeta.aiGoals.firstOrNull { a -> a is AIWearing } if (aiWearing != null) { this.applyNBTTagForArmorstand() val armorstand = proxy.getHeadArmorstand<ArmorStand>() if (player.passenger != armorstand) { player.passenger = armorstand } return } val flyingAi = petMeta.aiGoals.firstOrNull { a -> a is AIFlying } if (flyingAi != null) { if (internalHitBox == null) { internalHitBox = NMSPetBat(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetBat).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) return } val hoppingAi = petMeta.aiGoals.firstOrNull { a -> a is AIHopping } if (hoppingAi != null) { if (internalHitBox == null) { internalHitBox = NMSPetRabbit(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetRabbit).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) return } if (internalHitBox == null) { internalHitBox = NMSPetVillager(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetVillager).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) } /** * Disable setting slots. */ override fun setEquipment(i: Int, itemstack: ItemStack?) { } /** * Sets the slot securely. */ fun setSecureSlot(enumitemslot: Int, itemstack: ItemStack?) { super.setEquipment(enumitemslot, itemstack) } /** * Entity tick. */ override fun doTick() { super.doTick() try { proxy.run() if (dead) { return } if (this.internalHitBox != null) { val location = internalHitBox!!.bukkitEntity.location val aiGoal = petMeta.aiGoals.lastOrNull { p -> p is AIMovement } ?: return var y = location.y + (aiGoal as AIMovement).movementYOffSet if (this.isSmall) { y += 0.6 } if (y > -100) { this.setPositionRotation(location.x, y, location.z, location.yaw, location.pitch) this.motX = this.internalHitBox!!.motX this.motY = this.internalHitBox!!.motY this.motZ = this.internalHitBox!!.motZ } } if (proxy.teleportTarget != null) { val location = proxy.teleportTarget!! as Location if (this.internalHitBox != null) { this.internalHitBox!!.setPositionRotation( location.x, location.y, location.z, location.yaw, location.pitch ) } this.setPositionRotation(location.x, location.y, location.z, location.yaw, location.pitch) proxy.teleportTarget = null } if (PetMeta::aiGoals.hasChanged(petMeta)) { val event = PetBlocksAIPreChangeEvent(proxy.getPlayer(), proxy) Bukkit.getPluginManager().callEvent(event) if (event.isCancelled) { return } spawnHitBox() proxy.aiGoals = null } } catch (e: Exception) { PetBlocksApi.resolve(LoggingService::class.java).error("Failed to execute tick.", e) } } /** * Overrides the moving of the pet design. */ override fun move(d0: Double, d1: Double, d2: Double) { super.move(d0, d1, d2) if (passenger == null || passenger !is EntityHuman) { return } val groundAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding } val airAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding } var offSet = when { groundAi != null -> (groundAi as AIGroundRiding).ridingYOffSet airAi != null -> (airAi as AIFlyRiding).ridingYOffSet else -> 0.0 } if (this.isSmall) { offSet += 0.6 } val axisBoundingBox = this.boundingBox this.locX = (axisBoundingBox.a + axisBoundingBox.d) / 2.0 this.locY = axisBoundingBox.b + offSet this.locZ = (axisBoundingBox.c + axisBoundingBox.f) / 2.0 } /** * Gets the bukkit entity. */ override fun getBukkitEntity(): CraftPetArmorstand { if (this.bukkitEntity == null) { this.bukkitEntity = CraftPetArmorstand(this.world.server, this) } return this.bukkitEntity as CraftPetArmorstand } /** * Riding function. */ override fun g(sidemot: Float, formot: Float) { if (passenger == null || passenger !is EntityHuman) { flyHasTakenOffGround = false return } val human = passenger as EntityHuman val aiFlyRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding } if (aiFlyRiding != null) { rideInAir(human, aiFlyRiding as AIFlyRiding) return } val aiGroundRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding } if (aiGroundRiding != null) { rideOnGround(human, aiGroundRiding as AIGroundRiding) return } } /** * Handles the riding in air. */ private fun rideInAir(human: EntityHuman, ai: AIFlyRiding) { val sideMot: Float = human.aZ * 0.5f val forMot: Float = human.ba this.yaw = human.yaw this.lastYaw = this.yaw this.pitch = human.pitch * 0.5f this.setYawPitch(this.yaw, this.pitch) this.aK = this.yaw this.aI = this.aK val flyingVector = Vector() val flyingLocation = Location(this.world.world, this.locX, this.locY, this.locZ) if (sideMot < 0.0f) { flyingLocation.yaw = human.yaw - 90 flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5)) } else if (sideMot > 0.0f) { flyingLocation.yaw = human.yaw + 90 flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5)) } if (forMot < 0.0f) { flyingLocation.yaw = human.yaw flyingVector.add(flyingLocation.direction.normalize().multiply(0.5)) } else if (forMot > 0.0f) { flyingLocation.yaw = human.yaw flyingVector.add(flyingLocation.direction.normalize().multiply(0.5)) } if (!flyHasTakenOffGround) { flyHasTakenOffGround = true flyingVector.setY(1f) } if (this.isPassengerJumping()) { flyingVector.setY(0.5f) this.flyIsOnGround = true this.flyHasHitFloor = false } else if (this.flyIsOnGround) { flyingVector.setY(-0.2f) } if (this.flyHasHitFloor) { flyingVector.setY(0) flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed)) this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z) } else { flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed)) this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z) } val vec3d = Vec3D(this.locX, this.locY, this.locZ) val vec3d1 = Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ) val movingObjectPosition = this.world.rayTrace(vec3d, vec3d1) if (movingObjectPosition == null) { this.flyWallCollisionVector = flyingLocation.toVector() } else if (this.flyWallCollisionVector != null && flyCanHitWalls) { this.setPosition( this.flyWallCollisionVector!!.x, this.flyWallCollisionVector!!.y, this.flyWallCollisionVector!!.z ) } } /** * Handles the riding on ground. */ private fun rideOnGround(human: EntityHuman, ai: AIGroundRiding) { val sideMot: Float = human.aZ * 0.5f var forMot: Float = human.ba this.yaw = human.yaw this.lastYaw = this.yaw this.pitch = human.pitch * 0.5f this.setYawPitch(this.yaw, this.pitch) this.aK = this.yaw this.aI = this.aK if (forMot <= 0.0f) { forMot *= 0.25f } if (this.onGround && this.isPassengerJumping()) { this.motY = 0.5 } this.S = ai.climbingHeight.toFloat() this.aM = this.bI() * 0.1f if (!this.world.isClientSide) { this.k(0.35f) super.g(sideMot * ai.ridingSpeed.toFloat(), forMot * ai.ridingSpeed.toFloat()) } this.aA = this.aB val d0 = this.locX - this.lastX val d1 = this.locZ - this.lastZ var f4 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0f if (f4 > 1.0f) { f4 = 1.0f } this.aB += (f4 - this.aB) * 0.4f this.aC += this.aB } /** * Applies the entity NBT to the hitbox. */ private fun applyNBTTagToHitBox(hitBox: EntityInsentient) { val compound = NBTTagCompound() hitBox.b(compound) applyAIEntityNbt( compound, this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.hitBoxNbt }.toList() ) hitBox.a(compound) // CustomNameVisible does not working via NBT Tags. hitBox.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1 } /** * Applies the entity NBT to the armorstand. */ private fun applyNBTTagForArmorstand() { val compound = NBTTagCompound() this.b(compound) applyAIEntityNbt( compound, this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.armorStandNbt }.toList() ) this.a(compound) // CustomNameVisible does not working via NBT Tags. this.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1 } /** * Applies the raw NbtData to the given target. */ private fun applyAIEntityNbt(target: NBTTagCompound, rawNbtDatas: List<String>) { val compoundMapField = NBTTagCompound::class.java.getDeclaredField("map") compoundMapField.isAccessible = true val rootCompoundMap = compoundMapField.get(target) as MutableMap<Any?, Any?> for (rawNbtData in rawNbtDatas) { if (rawNbtData.isEmpty()) { continue } val parsedCompound = try { MojangsonParser.parse(rawNbtData) } catch (e: Exception) { throw RuntimeException("NBT Tag '$rawNbtData' cannot be parsed.", e) } val parsedCompoundMap = compoundMapField.get(parsedCompound) as Map<*, *> for (key in parsedCompoundMap.keys) { rootCompoundMap[key] = parsedCompoundMap[key] } } } /** * Should the hitbox of the armorstand be deleted. */ private fun shouldDeleteHitBox(): Boolean { val hasEmptyHitBoxAi = petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding || a is AIFlyRiding || a is AIWearing } != null if (hasEmptyHitBoxAi) { return true } if (internalHitBox != null) { if (internalHitBox is NMSPetVillager && petMeta.aiGoals.firstOrNull { a -> a is AIWalking } == null) { return true } else if (internalHitBox is NMSPetRabbit && petMeta.aiGoals.firstOrNull { a -> a is AIHopping } == null) { return true } else if (internalHitBox is NMSPetBat && petMeta.aiGoals.firstOrNull { a -> a is AIFlying } == null) { return true } } return false } /** * Gets if a passenger of the pet is jumping. */ private fun isPassengerJumping(): Boolean { if (passenger == null) { return false } return jumpingField.getBoolean(this.passenger) } }
apache-2.0
7bb471087682610df82a423ef643a025
33.873585
119
0.61002
4.446235
false
false
false
false
danielrs/botellier
src/test/kotlin/org/botellier/serializer/ByteSerializer.kt
1
2370
package org.botellier.serializer import org.botellier.value.* import org.junit.Assert import org.junit.Test class ByteSerializerTest { @Test fun renderInt() { val value = IntValue(1) Assert.assertArrayEquals(value.toByteArray(), ":1\r\n".toByteArray()) } @Test fun renderFloat() { val value = FloatValue(2.0) Assert.assertArrayEquals(value.toByteArray(), ";2.0\r\n".toByteArray()) } @Test fun renderString() { val value = StringValue("Hello, World!") Assert.assertArrayEquals(value.toByteArray(), "$13\r\nHello, World!\r\n".toByteArray()) } @Test fun renderRaw() { val bytes = "Hello, World!".toByteArray() val value = RawValue(bytes) Assert.assertArrayEquals(value.toByteArray(), "$13\r\nHello, World!\r\n".toByteArray()) } @Test fun renderEmptyString() { val value = StringValue("") Assert.assertArrayEquals(value.toByteArray(), "$0\r\n\r\n".toByteArray()) } @Test fun renderList() { val value = ListValue(listOf(IntValue(1), FloatValue(2.0), StringValue("three"))) Assert.assertArrayEquals( value.toByteArray(), "*3\r\n:1\r\n;2.0\r\n$5\r\nthree\r\n".toByteArray() ) } @Test fun renderEmptyList() { val value = ListValue() Assert.assertArrayEquals(value.toByteArray(), "*0\r\n".toByteArray()) } @Test fun renderSet() { val value = SetValue(listOf("one", "two", "three").toSet()) Assert.assertArrayEquals( value.toByteArray(), "&3\r\n$3\r\none\r\n$3\r\ntwo\r\n$5\r\nthree\r\n".toByteArray() ) } @Test fun renderEmptySet() { val value = SetValue() Assert.assertArrayEquals(value.toByteArray(), "&0\r\n".toByteArray()) } @Test fun renderMap() { val value = MapValue(mapOf("one" to IntValue(1), "two" to FloatValue(2.0), "three" to StringValue("three"))) Assert.assertArrayEquals( value.toByteArray(), "#3\r\n$3\r\none\r\n:1\r\n$3\r\ntwo\r\n;2.0\r\n$5\r\nthree\r\n$5\r\nthree\r\n".toByteArray() ) } @Test fun renderEmptyMap() { val value = MapValue() Assert.assertArrayEquals(value.toByteArray(), "#0\r\n".toByteArray()) } }
mit
cc577adad39230b9c6f05b11f4c8006b
27.566265
116
0.579747
3.657407
false
true
false
false
JetBrains/resharper-unity
rider/src/main/kotlin/icons/UnityIcons.kt
1
9795
package icons import com.intellij.openapi.util.IconLoader import com.intellij.ui.AnimatedIcon import javax.swing.Icon // FYI: Icons are defined in C# files in the backend. When being shown in the frontend, only the icon ID is passed to // the frontend, and IJ will look it up in resources/resharper. The name of the enclosing C# class is stripped of any // trailing "Icons" or "ThemedIcons" and used as the folder name. The icon is named after the inner class. IJ will // automatically add `_dark` to the basename of the SVG file if in Darcula. // Note that IJ has a different palette and colour scheme to ReSharper. This means that the front end svg files might // not be the same as the backed C# files... // We need to be in the icons root package so we can use this class from plugin.xml. We also need to use @JvmField so // that the kotlin value is visible as a JVM field via reflection class UnityIcons { class Icons { companion object { val UnityLogo = IconLoader.getIcon("/resharper/Logo/Unity.svg", UnityIcons::class.java) } } class Toolbar { companion object { val Toolbar = IconLoader.getIcon("/resharper/Toolbar/UnityToolbar.svg", UnityIcons::class.java) val ToolbarConnected = IconLoader.getIcon("/resharper/Toolbar/UnityToolbarConnected.svg", UnityIcons::class.java) val ToolbarDisconnected = IconLoader.getIcon("/resharper/Toolbar/UnityToolbarDisconnected.svg", UnityIcons::class.java) } } class Common { companion object { val UnityEditMode = IconLoader.getIcon("/unityIcons/common/unityEditMode.svg", UnityIcons::class.java) val UnityPlayMode = IconLoader.getIcon("/unityIcons/common/unityPlayMode.svg", UnityIcons::class.java) val UnityToolWindow = IconLoader.getIcon("/unityIcons/common/unityToolWindow.svg", UnityIcons::class.java) } } class LogView { companion object { val FilterBeforePlay = IconLoader.getIcon("/unityIcons/logView/filterBeforePlay.svg", UnityIcons::class.java) val FilterBeforeRefresh = IconLoader.getIcon("/unityIcons/logView/filterBeforeRefresh.svg", UnityIcons::class.java) } } class FileTypes { companion object { val ShaderLab = IconLoader.getIcon("/resharper/ShaderFileType/FileShader.svg", UnityIcons::class.java) val Cg = ShaderLab val AsmDef: Icon = ReSharperIcons.PsiJavaScript.Json val AsmRef: Icon = ReSharperIcons.PsiJavaScript.Json val UnityYaml = IconLoader.getIcon("/resharper/YamlFileType/FileYaml.svg", UnityIcons::class.java) val UnityScene = IconLoader.getIcon("/resharper/UnityFileType/FileUnity.svg", UnityIcons::class.java) val Meta = IconLoader.getIcon("/resharper/UnityFileType/FileUnityMeta.svg", UnityIcons::class.java) val Asset = IconLoader.getIcon("/resharper/UnityFileType/FileUnityAsset.svg", UnityIcons::class.java) val Prefab = IconLoader.getIcon("/resharper/UnityFileType/FileUnityPrefab.svg", UnityIcons::class.java) val Controller = IconLoader.getIcon("/resharper/UnityFileType/FileAnimatorController.svg", UnityIcons::class.java) val Anim = IconLoader.getIcon("/resharper/UnityFileType/FileAnimationClip.svg", UnityIcons::class.java) // These are front end only file types val Uss = IconLoader.getIcon("/unityIcons/fileTypes/uss.svg", UnityIcons::class.java) val Uxml = IconLoader.getIcon("/unityIcons/fileTypes/uxml.svg", UnityIcons::class.java) } } class Debugger { // Field and file names deliberately match the AllIcons.Debugger icons. // Pausepoints are by definition "no suspend". Where the default breakpoint icon set includes a "no_suspend" // variant, the same file name is used. Otherwise, the default name is drawn as "no_suspend". companion object { val Db_dep_line_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_dep_line_pausepoint.svg", UnityIcons::class.java) val Db_disabled_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_disabled_pausepoint.svg", UnityIcons::class.java) val Db_invalid_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_invalid_pausepoint.svg", UnityIcons::class.java) val Db_muted_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_muted_pausepoint.svg", UnityIcons::class.java) val Db_muted_disabled_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_muted_disabled_pausepoint.svg", UnityIcons::class.java) val Db_no_suspend_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_no_suspend_pausepoint.svg", UnityIcons::class.java) val Db_set_pausepoint = Db_no_suspend_pausepoint val Db_verified_no_suspend_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_verified_no_suspend_pausepoint.svg", UnityIcons::class.java) val Db_verified_pausepoint = Db_verified_no_suspend_pausepoint } } class Explorer { companion object { val AssetsRoot = IconLoader.getIcon("/unityIcons/Explorer/UnityAssets.svg", UnityIcons::class.java) val PackagesRoot = IconLoader.getIcon("/resharper/UnityObjectType/UnityPackages.svg", UnityIcons::class.java) val ReferencesRoot: Icon = ReSharperIcons.Common.CompositeElement val ReadOnlyPackagesRoot = IconLoader.getIcon("/unityIcons/Explorer/FolderReadOnly.svg", UnityIcons::class.java) val DependenciesRoot = IconLoader.getIcon("/unityIcons/Explorer/FolderDependencies.svg", UnityIcons::class.java) val BuiltInPackagesRoot = IconLoader.getIcon("/unityIcons/Explorer/FolderModules.svg", UnityIcons::class.java) val BuiltInPackage = IconLoader.getIcon("/unityIcons/Explorer/UnityModule.svg", UnityIcons::class.java) val ReferencedPackage = IconLoader.getIcon("/resharper/UnityFileType/FolderPackageReferenced.svg", UnityIcons::class.java) val EmbeddedPackage = IconLoader.getIcon("/unityIcons/Explorer/FolderPackageEmbedded.svg", UnityIcons::class.java) val LocalPackage = IconLoader.getIcon("/unityIcons/Explorer/FolderPackageLocal.svg", UnityIcons::class.java) val LocalTarballPackage = LocalPackage val GitPackage = IconLoader.getIcon("/unityIcons/Explorer/FolderGit.svg", UnityIcons::class.java) val UnknownPackage = IconLoader.getIcon("/unityIcons/Explorer/UnityPackageUnresolved.svg", UnityIcons::class.java) val PackageDependency = IconLoader.getIcon("/unityIcons/Explorer/UnityPackageDependency.svg", UnityIcons::class.java) val Reference: Icon = ReSharperIcons.ProjectModel.Assembly val AsmdefFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderAssetsAlt.svg", UnityIcons::class.java) val AssetsFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderAssets.svg", UnityIcons::class.java) val EditorDefaultResourcesFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderEditorResources.svg", UnityIcons::class.java) val EditorFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderEditor.svg", UnityIcons::class.java) val GizmosFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderGizmos.svg", UnityIcons::class.java) val PluginsFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderPlugins.svg", UnityIcons::class.java) val ResourcesFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderResources.svg", UnityIcons::class.java) val StreamingAssetsFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderStreamingAssets.svg", UnityIcons::class.java) val UnloadedFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderUnloaded.svg", UnityIcons::class.java) } } class Actions { companion object { val UnityActionsGroup = Icons.UnityLogo @JvmField val StartUnity = Icons.UnityLogo @JvmField val Execute = IconLoader.getIcon("/unityIcons/actions/execute.svg", UnityIcons::class.java) @JvmField val Pause = IconLoader.getIcon("/unityIcons/actions/pause.svg", UnityIcons::class.java) @JvmField val Step = IconLoader.getIcon("/unityIcons/actions/step.svg", UnityIcons::class.java) val FilterEditModeMessages = Common.UnityEditMode val FilterPlayModeMessages = Common.UnityPlayMode @JvmField val OpenEditorLog = FilterEditModeMessages @JvmField val OpenPlayerLog = FilterPlayModeMessages @JvmField val AttachToUnity = IconLoader.getIcon("/unityIcons/actions/attachToUnityProcess.svg", UnityIcons::class.java) @JvmField val RefreshInUnity = IconLoader.getIcon("/unityIcons/actions/refreshInUnity.svg", UnityIcons::class.java) } } class RunConfigurations { companion object { val AttachToUnityParentConfiguration = Icons.UnityLogo val AttachAndDebug = Common.UnityEditMode val AttachDebugAndPlay = Common.UnityPlayMode val UnityExe = Common.UnityPlayMode } } class Ide { companion object { val Warning = IconLoader.getIcon("/unityIcons/ide/warning.svg", UnityIcons::class.java) val Info = IconLoader.getIcon("/unityIcons/ide/info.svg", UnityIcons::class.java) val Error = IconLoader.getIcon("/unityIcons/ide/error.svg", UnityIcons::class.java) } } class ToolWindows { companion object { val UnityLog = Common.UnityToolWindow val UnityExplorer = Common.UnityToolWindow } } }
apache-2.0
fc3676b291cc9ee464e0f0665fc14d72
59.092025
156
0.705666
4.752547
false
false
false
false
inv3rse/ProxerTv
app/src/main/java/com/inverse/unofficial/proxertv/base/client/interceptors/CloudFlareInterceptor.kt
1
3052
package com.inverse.unofficial.proxertv.base.client.interceptors import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response import org.mozilla.javascript.Context /** * Interceptor that tries to handle the CloudFlare js challenge */ class CloudFlareInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response? { // always set the user agent val request = chain.request().newBuilder() .header("User-Agent", USER_AGENT) .build() val response = chain.proceed(request) if (response.code() == 503 && "cloudflare-nginx" == response.header("Server")) { val body = response.body().string() val operationPattern = Regex("setTimeout\\(function\\(\\)\\{\\s+(var s,t,o,p,b,r,e,a,k,i,n,g,f.+?\\r?\\n[\\s\\S]+?a\\.value =.+?)\\r?\\n") val passPattern = Regex("name=\"pass\" value=\"(.+?)\"") val challengePattern = Regex("name=\"jschl_vc\" value=\"(\\w+)\"") val rawOperation = operationPattern.find(body)?.groupValues?.get(1) val challenge = challengePattern.find(body)?.groupValues?.get(1) val challengePass = passPattern.find(body)?.groupValues?.get(1) if (rawOperation != null && challenge != null && challengePass != null) { val js = rawOperation.replace(Regex("a\\.value = (parseInt\\(.+?\\)).+"), "$1") .replace(Regex("\\s{3,}[a-z](?: = |\\.).+"), "") .replace("\n", "") // init js engine val rhino = Context.enter() rhino.optimizationLevel = -1 val scope = rhino.initStandardObjects() val result = (rhino.evaluateString(scope, js, "CloudFlare JS Challenge", 1, null) as Double).toInt() val requestUrl = response.request().url() val answer = (result + requestUrl.host().length).toString() val url = HttpUrl.Builder() .scheme(requestUrl.scheme()) .host(requestUrl.host()) .addPathSegment("/cdn-cgi/l/chk_jschl") .addQueryParameter("jschl_vc", challenge) .addQueryParameter("pass", challengePass) .addQueryParameter("jschl_answer", answer) .build() val challengeRequest = Request.Builder().get() .url(url) .header("Referer", requestUrl.toString()) .header("User-Agent", USER_AGENT) .build() // javascript waits 4 seconds until it proceeds Thread.sleep(4500) return chain.proceed(challengeRequest) } } return response } companion object { private const val USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0" } }
mit
a7c7f62c8a927481ece07a7f0777f707
39.706667
150
0.538008
4.475073
false
false
false
false
FF14org/ChouseiFF14
src/main/kotlin/com/ff14/chousei/domain/model/User.kt
1
1744
package com.ff14.chousei.domain.model import javax.persistence.Entity import javax.persistence.Column import javax.persistence.Id import javax.persistence.GeneratedValue import javax.persistence.GenerationType import java.util.Date import javax.persistence.OneToMany; import javax.persistence.Table import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.userdetails.UserDetails /* * UserテーブルのEntity. * @param id 主キー * @param title 書籍名 * @param subTitle 書籍の副題 ない場合はnull * @param leadingSentence リード文 * @param url リンク先URLパス */ @Entity @Table(name = "user") data class User( @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long = 0, @Column(nullable = false) var name: String = "", @Column(nullable = false) var pass: String = "", @OneToMany(mappedBy = "user") @Column val charcters: List<Character>? = null, @Column(nullable = false, updatable = false) val createTime: Date? = null, @Column(nullable = false) val imagePath: String = "", @Column(nullable = false) val twitterId: String = "" ) : UserDetails { override fun getAuthorities(): MutableCollection<out GrantedAuthority>? { return null } override fun getUsername(): String? { return this.name } override fun getPassword(): String? { return this.pass } override fun isAccountNonExpired(): Boolean { return true } override fun isAccountNonLocked(): Boolean { return true } override fun isCredentialsNonExpired(): Boolean { return true } override fun isEnabled(): Boolean { return true } }
apache-2.0
b49d0a6d9e97c497da36d9bf86f3255d
24.119403
78
0.686683
4.072639
false
false
false
false
AllanWang/Frost-for-Facebook
buildSrc/src/main/kotlin/Versions.kt
1
933
object Versions { const val targetSdk = 33 // https://developer.android.com/jetpack/androidx/releases/biometric const val andxBiometric = "1.1.0" // https://mvnrepository.com/artifact/org.apache.commons/commons-text // Updates blocked due to javax.script dependency const val apacheCommonsText = "1.4" // https://github.com/brianwernick/ExoMedia/releases const val exoMedia = "4.3.0" // https://github.com/jhy/jsoup/releases const val jsoup = "1.15.3" // https://square.github.io/okhttp/changelog/ const val okhttp = "4.10.0" // https://developer.android.com/jetpack/androidx/releases/room const val room = "2.4.3" // http://robolectric.org/getting-started/ const val roboelectric = "4.8" // https://github.com/Piasy/BigImageViewer#add-the-dependencies const val bigImageViewer = "1.8.1" // https://github.com/node-gradle/gradle-node-plugin/releases const val nodeGradle = "3.4.0" }
gpl-3.0
93256e662b0a11cb4b7a6b2faf647a72
28.15625
71
0.708467
3.285211
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/utils/TimeUtils.kt
1
1881
/* * Copyright 2019 Allan Wang * * 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.pitchedapps.frost.utils import android.content.Context import ca.allanwang.kau.utils.string import com.pitchedapps.frost.R import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale /** * Converts time in millis to readable date, eg Apr 24 at 7:32 PM * * With regards to date modifications in calendars, it appears to respect calendar rules; see * https://stackoverflow.com/a/43227817/4407321 */ fun Long.toReadableTime(context: Context): String { val cal = Calendar.getInstance() cal.timeInMillis = this val timeFormatter = SimpleDateFormat.getTimeInstance(DateFormat.SHORT) val time = timeFormatter.format(Date(this)) val day = when { cal >= Calendar.getInstance().apply { add(Calendar.DAY_OF_MONTH, -1) } -> context.string(R.string.today) cal >= Calendar.getInstance().apply { add(Calendar.DAY_OF_MONTH, -2) } -> context.string(R.string.yesterday) else -> { val dayFormatter = SimpleDateFormat("MMM dd", Locale.getDefault()) dayFormatter.format(Date(this)) } } return context.getString(R.string.time_template, day, time) }
gpl-3.0
c2da239494be02d2085b58d743359b59
35.882353
93
0.728336
3.943396
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/service/YamlSerializationServiceImpl.kt
1
17583
@file:Suppress("UNCHECKED_CAST", "CascadeIf") package com.github.shynixn.blockball.core.logic.business.service import com.github.shynixn.blockball.api.business.annotation.YamlSerialize import com.github.shynixn.blockball.api.business.serializer.YamlSerializer import com.github.shynixn.blockball.api.business.service.YamlSerializationService import java.lang.reflect.Field import java.lang.reflect.ParameterizedType import java.util.* import kotlin.collections.ArrayList import kotlin.collections.set /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class YamlSerializationServiceImpl : YamlSerializationService { /** * Serializes the given [instance] to a key value pair map. */ override fun serialize(instance: Any): Map<String, Any?> { return if (instance.javaClass.isArray) { serializeArray(null, instance as Array<Any?>) } else if (Collection::class.java.isAssignableFrom(instance.javaClass)) { serializeCollection(null, instance as Collection<Any?>) } else if (Map::class.java.isAssignableFrom(instance.javaClass)) { serializeMap(instance as Map<Any, Any>) } else { serializeObject(instance)!! } } /** * Deserializes the given [dataSource] into a new instance of the given [targetObjectClass]. */ override fun <R> deserialize(targetObjectClass: Class<R>, dataSource: Map<String, Any?>): R { if (targetObjectClass.isInterface) { throw IllegalArgumentException("Use a class intead of the interface $targetObjectClass.") } val instance: R? try { instance = targetObjectClass.newInstance() } catch (e: Exception) { throw IllegalArgumentException("Cannot instanciate the class $targetObjectClass. Does it have a default constructor?") } deserializeObject(instance!!, targetObjectClass, dataSource) return instance } /** * Deserialize the given object collection. */ private fun deserializeCollection( annotation: YamlSerialize, field: Field, collection: MutableCollection<Any?>, dataSource: Any ) { if (dataSource is Map<*, *>) { dataSource.keys.forEach { key -> if (key is String && key.toIntOrNull() == null) { throw IllegalArgumentException("Initializing " + annotation.value + " as collection failed as dataSource contains a invalid key.") } val value = dataSource[key] if (value == null) { collection.add(null) } else if (getArgumentType(field, 0).isEnum) { @Suppress("UPPER_BOUND_VIOLATED", "UNCHECKED_CAST") collection.add( java.lang.Enum.valueOf<Any>( getArgumentType(field, 0) as Class<Any>, value.toString().toUpperCase(Locale.ENGLISH) ) ) } else if (isPrimitive(value.javaClass)) { collection.add(value) } else { collection.add(deserialize(getArgumentType(field, 0) as Class<Any>, value as Map<String, Any?>)) } } } else if (dataSource is Collection<*>) { dataSource.forEach { item -> collection.add(item) } } else { throw IllegalArgumentException("Initializing " + annotation.value + " from given data source did succeed.") } } /** * Deserialize the given object map. */ private fun deserializeMap( annotation: YamlSerialize, map: MutableMap<Any, Any?>, keyClazz: Class<*>, valueClazz: Class<*>, dataSource: Map<String, Any?> ) { dataSource.keys.forEach { key -> val value = dataSource[key] val finalKey = if (keyClazz.isEnum) { @Suppress("UPPER_BOUND_VIOLATED", "UNCHECKED_CAST") java.lang.Enum.valueOf<Any>(keyClazz as Class<Any>, key.toUpperCase(Locale.ENGLISH)) } else if (isPrimitive(keyClazz)) { key } else { throw java.lang.IllegalArgumentException("Initializing " + annotation.value + " as map failed as map key is not primitiv or an enum.") } if (value == null) { map[finalKey] = null } else if (isPrimitive(valueClazz)) { map[finalKey] = value } else { if (valueClazz.isInterface) { if (annotation.implementation == Any::class) { throw IllegalArgumentException("Map Value $annotation is an interface without deserialization implementation.") } map[finalKey] = deserialize(annotation.implementation.javaObjectType, value as Map<String, Any?>) } else { map[finalKey] = deserialize(valueClazz, value as Map<String, Any?>) } } } } /** * Deserialize the given object array. */ private fun deserializeArray( annotation: YamlSerialize, field: Field, array: Array<Any?>, dataSource: Map<String, Any?> ) { dataSource.keys.forEach { key -> if (key.toIntOrNull() == null) { throw java.lang.IllegalArgumentException("Initializing " + annotation.value + " as array failed as dataSource contains a invalid key.") } val keyPlace = key.toInt() - 1 val value = dataSource[key] if (keyPlace < array.size) { if (value == null) { array[keyPlace] = null } else if (annotation.customserializer != Any::class) { array[keyPlace] = (annotation.customserializer.java.newInstance() as YamlSerializer<*, Map<String, Any?>>).onDeserialization( value as Map<String, Any?> ) } else if (field.type.componentType.isEnum) { @Suppress("UPPER_BOUND_VIOLATED", "UNCHECKED_CAST") array[keyPlace] = java.lang.Enum.valueOf<Any>(field.type as Class<Any>, value.toString().toUpperCase(Locale.ENGLISH)) } else if (isPrimitive(value.javaClass)) { array[keyPlace] = value } else { array[keyPlace] = deserialize(value.javaClass, value as Map<String, Any?>) } } } } /** * Deserializes the given [instance] of the [instanceClazz] from the [dataSource]. */ private fun deserializeObject(instance: Any, instanceClazz: Class<*>, dataSource: Map<String, Any?>) { var runningClazz: Class<*>? = instanceClazz while (runningClazz != null) { runningClazz.declaredFields.forEach { field -> field.isAccessible = true field.declaredAnnotations.forEach { annotation -> if (annotation.annotationClass == YamlSerialize::class) { deserializeField(field, annotation as YamlSerialize, instance, dataSource) } } } runningClazz = runningClazz.superclass } } /** * Deserializes a single field of an object. */ private fun deserializeField( field: Field, annotation: YamlSerialize, instance: Any, dataSource: Map<String, Any?> ) { if (!dataSource.containsKey(annotation.value)) { return } val value = dataSource[annotation.value] if (value == null) { field.set(instance, value) } else if (annotation.customserializer != Any::class && !field.type.isArray && !Collection::class.java.isAssignableFrom( field.type ) ) { val deserializedValue = (annotation.customserializer.java.newInstance() as YamlSerializer<Any, Any>).onDeserialization(value) field.set(instance, deserializedValue) } else if (isPrimitive(field.type)) { field.set(instance, value) } else if (field.type.isEnum) run { @Suppress("UPPER_BOUND_VIOLATED", "UNCHECKED_CAST") field.set(instance, java.lang.Enum.valueOf<Any>(field.type as Class<Any>, value.toString().toUpperCase(Locale.ENGLISH))) } else if (field.type.isArray) { val array = field.get(instance) if (array == null) { throw IllegalArgumentException("Array field " + field.name + " should already be initialized with a certain array.") } deserializeArray(annotation, field, array as Array<Any?>, value as Map<String, Any?>) } else if (Collection::class.java.isAssignableFrom(field.type)) { val collection = field.get(instance) if (collection == null) { throw IllegalArgumentException("Collection field " + field.name + " should already be initialized with a certain collection.") } (collection as MutableCollection<Any?>).clear() deserializeCollection(annotation, field, collection, value) } else if (Map::class.java.isAssignableFrom(field.type)) { val map = field.get(instance) if (map == null) { throw IllegalArgumentException("Map field " + field.name + " should already be initialized with a certain map.") } (map as MutableMap<Any, Any?>).clear() deserializeMap( annotation, map, getArgumentType(field, 0), getArgumentType(field, 1), value as Map<String, Any?> ) } else { val instanceClazz: Class<*> = if (field.type.isInterface) { if (annotation.implementation == Any::class) { throw IllegalArgumentException("Type of field " + field.name + " is an interface without deserialization implementation.") } annotation.implementation.java } else { field.type } field.set(instance, deserialize(instanceClazz, value as Map<String, Any?>)) } } /** * Serializes the given [instance] into a key value pair map. */ private fun serializeCollection(annotation: YamlSerialize?, instance: Collection<Any?>): Map<String, Any?> { return serializeArray(annotation, instance.toTypedArray()) } /** * Serializes the given [instances] into a key value pair map. */ private fun serializeArray(annotation: YamlSerialize?, instances: Array<Any?>): Map<String, Any?> { val data = LinkedHashMap<String, Any?>() for (i in 1..instances.size) { val instance = instances[i - 1] if (instance == null) { data[i.toString()] = null } else if (isPrimitive(instance::class.java)) { data[i.toString()] = instance } else if (annotation != null && annotation.customserializer != Any::class) { data[i.toString()] = (annotation.customserializer.java.newInstance() as YamlSerializer<Any, Any>).onSerialization( instance ) } else if (instance::class.java.isEnum) { data[i.toString()] = (instance as Enum<*>).name } else { data[i.toString()] = serialize(instance) } } return data } /** * Serializes the given [instance] map into a key value pair map. */ private fun serializeMap(instance: Map<Any, Any?>): Map<String, Any?> { val data = LinkedHashMap<String, Any?>() for (key in instance.keys) { if (isPrimitive(key::class.java)) { data[key.toString()] = serialize(instance[key]!!) } else if (key.javaClass.isEnum) { val value = instance[key] if (value == null) { data[(key as Enum<*>).name] = null } else if (isPrimitive(value.javaClass)) { data[(key as Enum<*>).name] = value } else { data[(key as Enum<*>).name] = serialize(value) } } else { throw IllegalArgumentException("Given map [$instance] does not contain a primitive type key or enum key.") } } return data } /** * Serializes the given [instance] into a key value pair map. */ private fun serializeObject(instance: Any?): Map<String, Any?>? { if (instance == null) { return null } val data = LinkedHashMap<String, Any?>() getOrderedAnnotations(instance::class.java).forEach { element -> val field = element.second val yamlAnnotation = element.first if (field.get(instance) == null) { } else if (yamlAnnotation.customserializer != Any::class && !field.type.isArray && !Collection::class.java.isAssignableFrom( field.type ) ) { val serializedValue = (yamlAnnotation.customserializer.java.newInstance() as YamlSerializer<Any, Any>).onSerialization( field.get(instance) ) data[yamlAnnotation.value] = serializedValue } else if (isPrimitive(field.type)) { data[yamlAnnotation.value] = field.get(instance) } else if (field.type.isEnum || field.type == Enum::class.java) { data[yamlAnnotation.value] = (field.get(instance) as Enum<*>).name.toUpperCase() } else if (field.type.isArray) { data[yamlAnnotation.value] = serializeArray(yamlAnnotation, field.get(instance) as Array<Any?>) } else if (Collection::class.java.isAssignableFrom(field.type)) { if (getArgumentType(field, 0) == String::class.java) { data[yamlAnnotation.value] = field.get(instance) } else { data[yamlAnnotation.value] = serializeCollection(yamlAnnotation, field.get(instance) as Collection<*>) } } else if (Map::class.java.isAssignableFrom(field.type)) { data[yamlAnnotation.value] = serializeMap(field.get(instance) as Map<Any, Any?>) } else { data[yamlAnnotation.value] = serializeObject(field.get(instance)) } } return data } /** * Gets all yaml annotations ordered from a class. */ private fun getOrderedAnnotations(clazz: Class<*>): List<Pair<YamlSerialize, Field>> { val result = ArrayList<Pair<YamlSerialize, Field>>() var runningClazz: Class<*>? = clazz while (runningClazz != null) { runningClazz.declaredFields.forEach { field -> field.isAccessible = true field.declaredAnnotations.forEach { annotation -> if (annotation.annotationClass == YamlSerialize::class) { result.add(Pair(annotation as YamlSerialize, field)) } } } runningClazz = runningClazz.superclass } return result.sortedBy { param -> param.first.orderNumber } } /** * Gets the type of the argument at the given [number] index. */ private fun getArgumentType(field: Field, number: Int): Class<*> { return (field.genericType as ParameterizedType).actualTypeArguments[number] as Class<*> } /** * Gets if the given [clazz] is a primitive class. */ private fun isPrimitive(clazz: Class<*>): Boolean { return clazz.isPrimitive || clazz == String::class.java || clazz == Int::class.java || clazz == Double::class.java || clazz == Long::class.java || clazz == Float::class.java || clazz == Integer::class.java } }
apache-2.0
2f73296622172d1c9acf414d10723402
38.601351
213
0.571234
4.943211
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIPageControl.kt
1
5269
package com.yy.codex.uikit import android.content.Context import android.util.AttributeSet import android.view.View import com.yy.codex.coreanimation.CALayer /** * Created by adi on 17/2/6. */ class UIPageControl : UIView { constructor(context: Context, view: View) : super(context, view) constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) override fun init() { super.init() dotView = UIView(context) dotView.wantsLayer = true addSubview(dotView) } override fun prepareProps(attrs: AttributeSet) { super.prepareProps(attrs) val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.UIPageControl, 0, 0) typedArray.getInteger(R.styleable.UIPageControl_pagecontrol_currentPage, 0)?.let { initializeAttributes.put("UIPageControl.currentPage", it) } typedArray.getInteger(R.styleable.UIPageControl_pagecontrol_numberOfPages, 0)?.let { initializeAttributes.put("UIPageControl.numberOfPages", it) } typedArray.getBoolean(R.styleable.UIPageControl_pagecontrol_hidesForSinglePage, false)?.let { initializeAttributes.put("UIPageControl.hidesForSinglePage", it) } typedArray.getColor(R.styleable.UIPageControl_pagecontrol_pageIndicatorColor, -1)?.let { if (it != -1) { initializeAttributes.put("UIPageControl.pageIndicatorColor", UIColor(it)) } } typedArray.getColor(R.styleable.UIPageControl_pagecontrol_currentPageIndicatorColor, -1)?.let { if (it != -1) { initializeAttributes.put("UIPageControl.currentPageIndicatorColor", UIColor(it)) } } } override fun resetProps() { super.resetProps() initializeAttributes?.let { (it["UIPageControl.currentPage"] as? Int)?.let { currentPage = it } (it["UIPageControl.numberOfPages"] as? Int)?.let { numberOfPages = it } (it["UIPageControl.hidesForSinglePage"] as? Boolean)?.let { hidesForSinglePage = it } (it["UIPageControl.pageIndicatorColor"] as? UIColor)?.let { pageIndicatorColor = it } (it["UIPageControl.currentPageIndicatorColor"] as? UIColor)?.let { currentPageIndicatorColor = it } } } override fun intrinsicContentSize(): CGSize { return CGSize(0.0, 16.0) } private val dotSpacing: Double = 10.0 private val dotRadius: Double = 5.0 private lateinit var dotView: UIView var currentPage: Int = 0 set(value) { if (field != value){ field = value updatePagesColor() } } var numberOfPages: Int = 3 set(value) { if (field != value){ field = value updatePagesLayout() updatePagesColor() } } var hidesForSinglePage: Boolean = false set(value) { if (field != value){ field = value updatePagesLayout() } } var pageIndicatorColor: UIColor = (tintColor ?: UIColor(0x12 / 255.0, 0x6a / 255.0, 1.0, 1.0)).colorWithAlpha(0.50) set(value) { if (field != value){ field = value updatePagesColor() } } var currentPageIndicatorColor: UIColor = tintColor ?: UIColor(0x12 / 255.0, 0x6a / 255.0, 1.0, 1.0) set(value) { if (field != value){ field = value updatePagesColor() } } override fun layoutSubviews() { super.layoutSubviews() updatePagesLayout() updatePagesColor() } private fun updatePagesLayout(){ if (hidesForSinglePage && numberOfPages == 1){ dotView.hidden = true return } val contentWidth = numberOfPages * ( dotSpacing + dotRadius*2 ) dotView.frame = CGRect((frame.width - contentWidth) / 2.0, 0.0, contentWidth, dotRadius * 2) dotView.layer.removeSubLayers() dotView.hidden = false for (i in 0..numberOfPages - 1) { val x = dotSpacing / 2.0 + i * (dotSpacing + dotRadius * 2) val layer = CALayer(CGRect(x, 0.0, dotRadius * 2, dotRadius * 2)) layer.cornerRadius = dotRadius dotView.layer.addSubLayer(layer) } } private fun updatePagesColor(){ dotView.layer.sublayers.forEachIndexed { idx, dotLayer -> dotLayer.backgroundColor = if (currentPage == idx) currentPageIndicatorColor else pageIndicatorColor } } fun sizeForNumberOfPages(): CGSize { return CGSize( numberOfPages * (dotSpacing+dotRadius*2), dotRadius * 2 ) } }
gpl-3.0
1ca4776c63bb0fb192b6fda9575cb38e
33
142
0.590245
4.764014
false
false
false
false
SimpleTimeTracking/StandaloneClient
src/main/kotlin/org/stt/persistence/stt/InsertHelper.kt
1
2001
package org.stt.persistence.stt import org.stt.model.TimeTrackingItem import org.stt.persistence.ItemReader import org.stt.persistence.ItemWriter internal class InsertHelper(val reader: ItemReader, val writer: ItemWriter, val itemToInsert: TimeTrackingItem) { private var lastReadItem: TimeTrackingItem? = null fun performInsert() { copyAllItemsEndingAtOrBeforeItemToInsert() lastReadItem?.let { this.adjustEndOfLastItemReadAndWrite(it) } writer.write(itemToInsert) skipAllItemsCompletelyCoveredByItemToInsert() lastReadItem?.let { this.adjustStartOfLastItemReadAndWrite(it) } copyRemainingItems() } private fun copyAllItemsEndingAtOrBeforeItemToInsert() { copyWhile { it.endsAtOrBefore(itemToInsert.start) } } private fun adjustStartOfLastItemReadAndWrite(item: TimeTrackingItem) { val itemToWrite = itemToInsert.end?.let { end -> if (end.isAfter(item.start)) item.withStart(end) else null } ?: item writer.write(itemToWrite) } private fun adjustEndOfLastItemReadAndWrite(item: TimeTrackingItem) { if (item.start.isBefore(itemToInsert.start)) { val itemBeforeItemToInsert = item .withEnd(itemToInsert.start) writer.write(itemBeforeItemToInsert) } } private fun copyRemainingItems() { copyWhile { true } } private fun skipAllItemsCompletelyCoveredByItemToInsert() { var currentItem = lastReadItem while (currentItem != null && itemToInsert.endsSameOrAfter(currentItem)) { currentItem = reader.read() } lastReadItem = currentItem } private fun copyWhile(condition: (TimeTrackingItem) -> Boolean) { do { lastReadItem = reader.read() lastReadItem?.let { if (condition(it)) writer.write(it) else return } } while (lastReadItem != null) } }
gpl-3.0
ad5a513b36fe45215cbd527a5ec09b53
34.105263
117
0.66017
4.916462
false
false
false
false
cdowney/krest
src/main/kotlin/net/cad/config/SwaggerConfig.kt
1
3522
package net.cad.config import org.slf4j.LoggerFactory import org.springframework.boot.bind.RelaxedPropertyResolver import org.springframework.context.EnvironmentAware import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.env.Environment import org.springframework.util.StopWatch import springfox.documentation.builders.PathSelectors import springfox.documentation.builders.RequestHandlerSelectors import springfox.documentation.service.ApiInfo import springfox.documentation.service.ApiKey import springfox.documentation.service.Contact import springfox.documentation.service.SecurityScheme import springfox.documentation.spi.DocumentationType import springfox.documentation.spring.web.plugins.Docket import springfox.documentation.swagger.web.ApiKeyVehicle import springfox.documentation.swagger.web.SecurityConfiguration import springfox.documentation.swagger2.annotations.EnableSwagger2 import java.util.* @Configuration @EnableSwagger2 open class SwaggerConfig : EnvironmentAware { private lateinit var propertyResolver: RelaxedPropertyResolver; private fun apiInfo(): ApiInfo { val contactInfo = Contact( propertyResolver.getProperty("contact.name"), propertyResolver.getProperty("contact.url"), propertyResolver.getProperty("contact.email")) return ApiInfo( propertyResolver.getProperty("api.title"), propertyResolver.getProperty("api.description"), propertyResolver.getProperty("api.version"), propertyResolver.getProperty("api.termsofserviceurl"), contactInfo, propertyResolver.getProperty("api.license"), propertyResolver.getProperty("api.licenseurl")) } override fun setEnvironment(environment: Environment) { this.propertyResolver = RelaxedPropertyResolver(environment, "swagger.") } @Bean open fun api(): Docket { log.info("Starting Swagger") val watch = StopWatch() watch.start() val docket = Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("net.cad.controllers")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()) .forCodeGeneration(true) .directModelSubstitute(java.time.LocalDate::class.java, String::class.java) .directModelSubstitute(java.time.ZonedDateTime::class.java, Date::class.java) .directModelSubstitute(java.time.LocalDateTime::class.java, Date::class.java) watch.stop() log.info("Started Swagger in {} ms", watch.totalTimeMillis) return docket } @Bean open fun apiKey(): SecurityScheme { return ApiKey("myKey", "Authorization", "header") } @Bean open fun security(): SecurityConfiguration { return SecurityConfiguration( "", // clientId "", // clientSecret "", // realm "Salesforce Integration API", // appName "api_key", // apiKeyValue ApiKeyVehicle.HEADER, //apiKeyVechicle "Authorization", // apiKeyName ",") // scopeSeparator } companion object { private val log = LoggerFactory.getLogger(SwaggerConfig::class.java) } }
mit
bc7ac02fd3daf121ade1855d7a04c48b
38.133333
93
0.674901
5.233284
false
true
false
false
Devexperts/lin-check
lincheck/src/main/java/com/devexperts/dxlab/lincheck/verifier/LTS.kt
1
6604
/*- * #%L * Lincheck * %% * Copyright (C) 2015 - 2018 Devexperts, LLC * %% * This program 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 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package com.devexperts.dxlab.lincheck.verifier import com.devexperts.dxlab.lincheck.Actor import com.devexperts.dxlab.lincheck.Result import com.devexperts.dxlab.lincheck.execution.ExecutionResult import com.devexperts.dxlab.lincheck.execution.ExecutionScenario import com.devexperts.dxlab.lincheck.verifier.quantitative.ExtendedLTS /** * An abstraction for verifiers which use the labeled transition system (LTS) under the hood. * The main idea of such verifiers is finding a path in LTS, which starts from the initial * LTS state (see [LTS.initialState]) and goes through all actors with the specified results. * To determine which transitions are possible from the current state, we store related * to the current path prefix information in the special [LTSContext], which determines * the next possible transitions using [LTSContext.nextContexts] function. This verifier * uses depth-first search to find a proper path. */ abstract class AbstractLTSVerifier<STATE>(val scenario: ExecutionScenario, val testClass: Class<*>) : CachedVerifier() { abstract fun createInitialContext(results: ExecutionResult): LTSContext<STATE> override fun verifyResultsImpl(results: ExecutionResult): Boolean { return verify(createInitialContext(results)) } private fun verify(context: LTSContext<STATE>): Boolean { // Check if a possible path is found. if (context.completed) return true // Traverse through next possible transitions using depth-first search (DFS). Note that // initial and post parts are represented as threads with ids `0` and `threads + 1` respectively. for (threadId in 0..scenario.threads + 1) { for (c in context.nextContexts(threadId)) { if (verify(c)) return true } } return false } } /** * Common interface for different labeled transition systems, which several correctness formalisms use. * Lin-Check widely uses LTS-based formalisms for verification, see [Verifier] implementations as examples. * Essentially, LTS provides an information of the possibility to do a transition from one state to another * by the specified actor with the specified result. Nevertheless, it should be extended and provide any additional * information, like the transition penalty in [ExtendedLTS]. */ interface LTS<STATE> { /** * Returns the state corresponding to the initial state of the data structure. */ val initialState: STATE } /** * Reflects the current path prefix information and stores the current LTS state * (which essentially indicates the data structure state) for a single step of a legal path search * in LTS-based verifiers. It counts next possible transitions via [nextContexts] function. */ abstract class LTSContext<STATE>( /** * Current execution scenario. */ val scenario: ExecutionScenario, /** * LTS state of this context */ val state: STATE, /** * Number of executed actors in each thread. Note that initial and post parts * are represented as threads with ids `0` and `threads + 1` respectively. */ val executed: IntArray) { /** * Counts next possible states and the corresponding contexts if the specified thread is executed. */ abstract fun nextContexts(threadId: Int): List<LTSContext<STATE>> // The total number of actors in init part of the execution scenario. val initActors: Int = scenario[0].size // The number of executed actors in the init part. val initExecuted: Int = executed[0] // `true` if all actors in the init part are executed. val initCompleted: Boolean = initActors == initExecuted // The total number of actors in parallel part of the execution scenario. val parallelActors: Int = scenario.parallelExecution.fold(0) { sum, t -> sum + t.size } // The number of executed actors in the parallel part. val parallelExecuted: Int = executed.slice(1..scenario.threads).fold(0) { sum, e -> sum + e } // `true` if all actors in the init part are executed. val parallelCompleted: Boolean = parallelActors == parallelExecuted // The total number of actors in post part of the execution scenario. val postActors: Int = scenario[scenario.threads + 1].size // The number of executed actors in the post part. val postExecuted: Int = executed[scenario.threads + 1] // `true` if all actors in the post part are executed. val postCompleted: Boolean = postActors == postExecuted // The total number of actors in the execution scenario. val totalActors: Int = initActors + parallelActors + postActors // The total number of executed actors. val totalExecuted: Int = initExecuted + parallelExecuted + postExecuted // `true` if all actors are executed and a legal path is found therefore. val completed: Boolean = totalActors == totalExecuted // Returns `true` if all actors in the specified thread are executed. fun isCompleted(threadId: Int) = executed[threadId] == scenario[threadId].size } /** * Returns scenario for the specified thread. Note that initial and post parts * are represented as threads with ids `0` and `threads + 1` respectively. */ operator fun ExecutionScenario.get(threadId: Int): List<Actor> = when (threadId) { 0 -> initExecution threads + 1 -> postExecution else -> parallelExecution[threadId - 1] } /** * Returns results for the specified thread. Note that initial and post parts * are represented as threads with ids `0` and `threads + 1` respectively. */ operator fun ExecutionResult.get(threadId: Int): List<Result> = when (threadId) { 0 -> initResults parallelResults.size + 1 -> postResults else -> parallelResults[threadId - 1] }
lgpl-3.0
e5305d904a25b61bd84f99857f9ce2a9
41.883117
120
0.714567
4.471225
false
false
false
false
danfma/kodando
kodando-mithril-router-dom/src/main/kotlin/kodando/mithril/router/dom/Route.kt
1
2656
package kodando.mithril.routing import kodando.history.Location import kodando.mithril.* import kodando.mithril.context.contextConsumer external interface RouteProps : Props { var computedMatch: Match? var location: Location? var path: String? var exact: Boolean var strict: Boolean var sensitive: Boolean var view: View<*> var render: (RoutedProps) -> VNode<*>? } object Route : View<RouteProps> { private fun computeMatch(props: RouteProps, context: RouterContext): Match? { val computedMatch = props.computedMatch if (computedMatch != null) { return computedMatch } val route = context.route val pathName = (props.location ?: context.route.location).pathname return matchPath( pathName, props.path, props.strict, props.exact, props.sensitive, route.match ) } override fun view(vnode: VNode<RouteProps>): VNode<*>? { val attrs = vnode.attrs ?: return null return root { contextConsumer(routerContextKey) { context -> val route = context.route val history = context.history val location = attrs.location ?: route.location val match = computeMatch(attrs, context) val routedProps = routedProps(match, location, history) if (addView(attrs.view, routedProps)) { return@contextConsumer } if (addRender(attrs.render, routedProps)) { return@contextConsumer } addChildren(vnode.children, match) } } } private fun Props.addView(view: View<*>, routedProps: RoutedProps): Boolean { if (view === undefined) { return false } val match = routedProps.match addChild( match?.let { createElement(view, routedProps) } ) return true } private fun Props.addRender(render: (RoutedProps) -> VNode<*>?, routedProps: RoutedProps): Boolean { if (render === undefined) { return false } val match = routedProps.match addChild( match?.let { render(routedProps) } ) return true } private fun Props.addChildren(children: Array<out VNode<*>?>, match: Match?) { val child = children.firstOrNull() addChild( match?.let { child } ) } } fun Props.route( path: String, exact: Boolean = true, strict: Boolean = false, applier: Props.(RoutedProps) -> Unit) { addChild(Route) { this.path = path this.exact = exact this.strict = strict this.render = { root { applier(it) } } } } fun Props.route(applier: Applier<RouteProps>) { addChild(Route, applier) }
mit
70f69896faaa8ead55eec02f46f766ca
20.079365
102
0.625377
4.15
false
false
false
false
blackbbc/Tucao
app/src/main/kotlin/me/sweetll/tucao/extension/ObservableExtensions.kt
1
1680
package me.sweetll.tucao.extension import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import io.reactivex.android.schedulers.AndroidSchedulers import me.sweetll.tucao.di.service.ApiConfig import me.sweetll.tucao.model.json.BaseResponse import me.sweetll.tucao.model.json.ListResponse import okhttp3.ResponseBody import org.jsoup.Jsoup import org.jsoup.nodes.Document fun <T> Observable<BaseResponse<T>>.sanitizeJson(): Observable<T> = this .subscribeOn(Schedulers.io()) .retryWhen(ApiConfig.RetryWithDelay()) .flatMap { response -> if (response.code == "200") { Observable.just(response.result!!) } else { Observable.error(Throwable(response.msg)) } } .observeOn(AndroidSchedulers.mainThread()) fun <T> Observable<ListResponse<T>>.sanitizeJsonList(): Observable<ListResponse<T>> = this .subscribeOn(Schedulers.io()) .retryWhen(ApiConfig.RetryWithDelay()) .flatMap { response -> if (response.code == "200") { response.result = response.result ?: mutableListOf() Observable.just(response) } else { Observable.error(Throwable(response.msg)) } } .observeOn(AndroidSchedulers.mainThread()) fun <T> Observable<ResponseBody>.sanitizeHtml(transform: Document.() -> T): Observable<T> = this .subscribeOn(Schedulers.io()) .retryWhen(ApiConfig.RetryWithDelay()) .map { response -> Jsoup.parse(response.string()).transform() } .observeOn(AndroidSchedulers.mainThread())
mit
1f12a382fea76c73cf3922e935d20d41
36.355556
97
0.643452
4.666667
false
true
false
false
square/duktape-android
zipline/src/jvmMain/kotlin/app/cash/zipline/QuickJsNativeLoader.kt
1
1981
/* * Copyright (C) 2021 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 app.cash.zipline import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption.REPLACE_EXISTING import java.util.Locale.US @Suppress("UnsafeDynamicallyLoadedCode") // Only loading from our own JAR contents. internal fun loadNativeLibrary() { val osName = System.getProperty("os.name").lowercase(US) val osArch = System.getProperty("os.arch").lowercase(US) val nativeLibraryJarPath = if (osName.contains("linux")) { "/jni/$osArch/libquickjs.so" } else if (osName.contains("mac")) { "/jni/$osArch/libquickjs.dylib" } else { throw IllegalStateException("Unsupported OS: $osName") } val nativeLibraryUrl = QuickJs::class.java.getResource(nativeLibraryJarPath) ?: throw IllegalStateException("Unable to read $nativeLibraryJarPath from JAR") val nativeLibraryFile: Path try { nativeLibraryFile = Files.createTempFile("quickjs", null) // File-based deleteOnExit() uses a special internal shutdown hook that always runs last. nativeLibraryFile.toFile().deleteOnExit() nativeLibraryUrl.openStream().use { nativeLibrary -> Files.copy(nativeLibrary, nativeLibraryFile, REPLACE_EXISTING) } } catch (e: IOException) { throw RuntimeException("Unable to extract native library from JAR", e) } System.load(nativeLibraryFile.toAbsolutePath().toString()) }
apache-2.0
3944c7bce4f556bccd4cef612cc71a84
38.62
93
0.742049
4.197034
false
false
false
false
damien5314/HoldTheNarwhal
app/src/main/java/com/ddiehl/android/htn/view/text/CenteredRelativeSizeSpan.kt
1
821
package com.ddiehl.android.htn.view.text import android.graphics.Rect import android.text.TextPaint import android.text.style.MetricAffectingSpan /** * https://stackoverflow.com/a/37088653/3238938 */ class CenteredRelativeSizeSpan(val sizeChange: Float) : MetricAffectingSpan() { override fun updateDrawState(ds: TextPaint) { updateAnyState(ds) } override fun updateMeasureState(ds: TextPaint) { updateAnyState(ds) } private fun updateAnyState(ds: TextPaint) { val bounds = Rect() ds.getTextBounds("1A", 0, 2, bounds) var shift = bounds.top - bounds.bottom ds.textSize = ds.textSize * sizeChange ds.getTextBounds("1A", 0, 2, bounds) shift -= bounds.top - bounds.bottom shift /= 2 ds.baselineShift += shift } }
apache-2.0
b5c47939f3979f0c357ad7715f8b71d7
26.366667
79
0.666261
3.966184
false
false
false
false
tipsy/javalin
javalin-openapi/src/main/java/io/javalin/plugin/openapi/dsl/OpenApiCrudHandlerDocumentation.kt
1
913
package io.javalin.plugin.openapi.dsl data class OpenApiCrudHandlerDocumentation( var getAllDocumentation: OpenApiDocumentation = OpenApiDocumentation(), var getOneDocumentation: OpenApiDocumentation = OpenApiDocumentation(), var createDocumentation: OpenApiDocumentation = OpenApiDocumentation(), var updateDocumentation: OpenApiDocumentation = OpenApiDocumentation(), var deleteDocumentation: OpenApiDocumentation = OpenApiDocumentation() ) { fun getAll(doc: OpenApiDocumentation) = apply { this.getAllDocumentation = doc } fun getOne(doc: OpenApiDocumentation) = apply { this.getOneDocumentation = doc } fun create(doc: OpenApiDocumentation) = apply { this.createDocumentation = doc } fun update(doc: OpenApiDocumentation) = apply { this.updateDocumentation = doc } fun delete(doc: OpenApiDocumentation) = apply { this.deleteDocumentation = doc } }
apache-2.0
d4df7c4f1a3fedef7a878c8922dd77b9
59.866667
84
0.763417
5.70625
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/commonMain/kotlin/nl/adaptivity/util/xml/IterableCombinedNamespaceContext.kt
1
3540
/* * Copyright (c) 2021. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.util.xml import nl.adaptivity.xmlutil.* @OptIn(XmlUtilInternal::class) class IterableCombinedNamespaceContext( val primary: NamespaceContext, val secondary: NamespaceContext ) : IterableNamespaceContext, NamespaceContextImpl { override fun getNamespaceURI(prefix: String): String? { val namespaceURI = primary.getNamespaceURI(prefix) return if (namespaceURI == null || XMLConstants.NULL_NS_URI == namespaceURI) { secondary.getNamespaceURI(prefix) } else namespaceURI } override fun getPrefix(namespaceURI: String): String? { val prefix = primary.getPrefix(namespaceURI) return if (prefix == null || XMLConstants.NULL_NS_URI == namespaceURI && XMLConstants.DEFAULT_NS_PREFIX == prefix) { secondary.getPrefix(namespaceURI) } else prefix } @OptIn(XmlUtilInternal::class) override fun freeze(): IterableNamespaceContext = when { primary is SimpleNamespaceContext && secondary is SimpleNamespaceContext -> this primary !is IterableNamespaceContext -> (secondary as? IterableNamespaceContext)?.freeze() ?: SimpleNamespaceContext() secondary !is IterableNamespaceContext || ! secondary.iterator().hasNext() -> primary.freeze() !primary.iterator().hasNext() -> secondary.freeze() else -> { val frozenPrimary = primary.freeze() val frozenSecondary = secondary.freeze() if (frozenPrimary === primary && frozenSecondary == secondary) { this } else { @Suppress("DEPRECATION") (IterableCombinedNamespaceContext(primary.freeze(), secondary.freeze())) } } } @OptIn(XmlUtilInternal::class) override fun iterator(): Iterator<Namespace> { val p = (primary as? IterableNamespaceContext)?.run { freeze().asSequence() } ?: emptySequence() val s = (secondary as? IterableNamespaceContext)?.run { freeze().asSequence() } ?: emptySequence() return (p + s).iterator() } @Suppress("OverridingDeprecatedMember") override fun getPrefixesCompat(namespaceURI: String): Iterator<String> { val prefixes1 = primary.prefixesFor(namespaceURI) val prefixes2 = secondary.prefixesFor(namespaceURI) val prefixes = hashSetOf<String>() while (prefixes1.hasNext()) { prefixes.add(prefixes1.next()) } while (prefixes2.hasNext()) { prefixes.add(prefixes2.next()) } return prefixes.iterator() } override fun plus(secondary: FreezableNamespaceContext): FreezableNamespaceContext = @Suppress("DEPRECATION") (IterableCombinedNamespaceContext(this, secondary)) }
lgpl-3.0
618e5e437292a9aff00e38bc8b6d8ecf
37.478261
124
0.65904
5.167883
false
false
false
false
SchoolPower/SchoolPower-Android
app/src/main/java/com/carbonylgroup/schoolpower/activities/SettingsActivity.kt
1
3098
/** * Copyright (C) 2019 SchoolPower Studio */ package com.carbonylgroup.schoolpower.activities import android.animation.AnimatorListenerAdapter import android.app.Activity import android.os.Bundle import androidx.fragment.app.Fragment import androidx.core.app.NavUtils import androidx.appcompat.widget.Toolbar import android.view.MenuItem import android.view.View import android.view.ViewAnimationUtils import android.widget.RelativeLayout import com.carbonylgroup.schoolpower.R import com.carbonylgroup.schoolpower.fragments.SettingsFragment import kotterknife.bindView private var recreated = false class SettingsActivity : BaseActivity(), SettingsFragment.SettingsCallBack { private val settingsToolBar: Toolbar by bindView(R.id.settings_toolbar) private val rootLayout: RelativeLayout by bindView(R.id.settings_root_layout) override fun onRecreate() { recreated = true setResult(Activity.RESULT_OK) recreate() } override fun initActivity() { super.initActivity() setContentView(R.layout.settings_toolbar) setSupportActionBar(settingsToolBar) supportFragmentManager.beginTransaction().replace(R.id.settings_content, SettingsFragment()).commit() supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = getString(R.string.settings) setResult(Activity.RESULT_OK) if (recreated) { rootLayout.post( { startAnimation() }) // to invoke onActivityResult to apply settings recreated = false } } private fun startAnimation() { val cx = rootLayout.width / 2 val cy = rootLayout.height / 2 val finalRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat() val anim = ViewAnimationUtils.createCircularReveal(rootLayout, cx, cy, 0f, finalRadius) anim.addListener(object : AnimatorListenerAdapter() {}) rootLayout.visibility = View.VISIBLE anim.start() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { NavUtils.navigateUpFromSameTask(this) return true } } return super.onOptionsItemSelected(item) } override fun onSupportNavigateUp(): Boolean { finish() return true } override fun onSaveInstanceState(outState: Bundle) { // finish setting activity to avoid java.io.NotSerializableException // com.thirtydegreesray.openhub.ui.widget.colorChooser.ColorChooserPreference // android.os.Parcel.writeSerializable(Parcel.java:1761) if (recreated) { super.onSaveInstanceState(outState) } else { finish() } } fun addFragmentOnTop(fragment: Fragment){ supportFragmentManager.beginTransaction() .add(R.id.settings_content, fragment) .addToBackStack("TAG") .commit() } }
gpl-3.0
1dd8fbdf64fa9b116596b201b3b0defc
31.270833
109
0.678179
5.087028
false
false
false
false
fossasia/open-event-android
app/src/main/java/org/fossasia/openevent/general/attendees/AttendeeFragment.kt
1
43728
package org.fossasia.openevent.general.attendees import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.os.CountDownTimer import android.telephony.TelephonyManager import android.text.Editable import android.text.Spannable import android.text.SpannableStringBuilder import android.text.TextPaint import android.text.TextWatcher import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import com.paypal.android.sdk.payments.PayPalConfiguration import com.paypal.android.sdk.payments.PayPalPayment import com.paypal.android.sdk.payments.PayPalService import com.paypal.android.sdk.payments.PaymentActivity import com.paypal.android.sdk.payments.PaymentConfirmation import com.paypal.android.sdk.payments.ShippingAddress import com.stripe.android.ApiResultCallback import com.stripe.android.Stripe import com.stripe.android.model.Card import com.stripe.android.model.Token import java.math.BigDecimal import java.util.Calendar import java.util.Currency import kotlin.collections.ArrayList import kotlinx.android.synthetic.main.fragment_attendee.view.accept import kotlinx.android.synthetic.main.fragment_attendee.view.acceptCheckbox import kotlinx.android.synthetic.main.fragment_attendee.view.amount import kotlinx.android.synthetic.main.fragment_attendee.view.attendeeRecycler import kotlinx.android.synthetic.main.fragment_attendee.view.attendeeScrollView import kotlinx.android.synthetic.main.fragment_attendee.view.bankRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.billingAddress import kotlinx.android.synthetic.main.fragment_attendee.view.billingAddressLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingCity import kotlinx.android.synthetic.main.fragment_attendee.view.billingCityLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingCompany import kotlinx.android.synthetic.main.fragment_attendee.view.billingCompanyLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingEnabledCheckbox import kotlinx.android.synthetic.main.fragment_attendee.view.billingInfoCheckboxSection import kotlinx.android.synthetic.main.fragment_attendee.view.billingInfoContainer import kotlinx.android.synthetic.main.fragment_attendee.view.billingPostalCode import kotlinx.android.synthetic.main.fragment_attendee.view.billingPostalCodeLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingState import kotlinx.android.synthetic.main.fragment_attendee.view.cancelButton import kotlinx.android.synthetic.main.fragment_attendee.view.cardNumber import kotlinx.android.synthetic.main.fragment_attendee.view.cardNumberLayout import kotlinx.android.synthetic.main.fragment_attendee.view.chequeRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.countryPicker import kotlinx.android.synthetic.main.fragment_attendee.view.cvc import kotlinx.android.synthetic.main.fragment_attendee.view.cvcLayout import kotlinx.android.synthetic.main.fragment_attendee.view.email import kotlinx.android.synthetic.main.fragment_attendee.view.emailLayout import kotlinx.android.synthetic.main.fragment_attendee.view.eventName import kotlinx.android.synthetic.main.fragment_attendee.view.firstName import kotlinx.android.synthetic.main.fragment_attendee.view.firstNameLayout import kotlinx.android.synthetic.main.fragment_attendee.view.helloUser import kotlinx.android.synthetic.main.fragment_attendee.view.lastName import kotlinx.android.synthetic.main.fragment_attendee.view.lastNameLayout import kotlinx.android.synthetic.main.fragment_attendee.view.loginButton import kotlinx.android.synthetic.main.fragment_attendee.view.month import kotlinx.android.synthetic.main.fragment_attendee.view.monthText import kotlinx.android.synthetic.main.fragment_attendee.view.offlinePayment import kotlinx.android.synthetic.main.fragment_attendee.view.offlinePaymentDescription import kotlinx.android.synthetic.main.fragment_attendee.view.onSiteRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.paymentOptionsGroup import kotlinx.android.synthetic.main.fragment_attendee.view.paymentSelectorContainer import kotlinx.android.synthetic.main.fragment_attendee.view.paypalRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.qty import kotlinx.android.synthetic.main.fragment_attendee.view.register import kotlinx.android.synthetic.main.fragment_attendee.view.sameBuyerCheckBox import kotlinx.android.synthetic.main.fragment_attendee.view.signInEditLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInEmail import kotlinx.android.synthetic.main.fragment_attendee.view.signInEmailLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInPassword import kotlinx.android.synthetic.main.fragment_attendee.view.signInPasswordLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInText import kotlinx.android.synthetic.main.fragment_attendee.view.signInTextLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signOut import kotlinx.android.synthetic.main.fragment_attendee.view.signOutLayout import kotlinx.android.synthetic.main.fragment_attendee.view.stripePayment import kotlinx.android.synthetic.main.fragment_attendee.view.stripeRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.taxId import kotlinx.android.synthetic.main.fragment_attendee.view.taxLayout import kotlinx.android.synthetic.main.fragment_attendee.view.taxPrice import kotlinx.android.synthetic.main.fragment_attendee.view.ticketDetails import kotlinx.android.synthetic.main.fragment_attendee.view.ticketTableDetails import kotlinx.android.synthetic.main.fragment_attendee.view.ticketsRecycler import kotlinx.android.synthetic.main.fragment_attendee.view.time import kotlinx.android.synthetic.main.fragment_attendee.view.timeoutCounterLayout import kotlinx.android.synthetic.main.fragment_attendee.view.timeoutInfoTextView import kotlinx.android.synthetic.main.fragment_attendee.view.timeoutTextView import kotlinx.android.synthetic.main.fragment_attendee.view.totalAmountLayout import kotlinx.android.synthetic.main.fragment_attendee.view.totalPrice import kotlinx.android.synthetic.main.fragment_attendee.view.year import kotlinx.android.synthetic.main.fragment_attendee.view.yearText import org.fossasia.openevent.general.BuildConfig import org.fossasia.openevent.general.ComplexBackPressFragment import org.fossasia.openevent.general.R import org.fossasia.openevent.general.auth.User import org.fossasia.openevent.general.event.Event import org.fossasia.openevent.general.event.EventId import org.fossasia.openevent.general.event.EventUtils import org.fossasia.openevent.general.order.Charge import org.fossasia.openevent.general.ticket.TicketDetailsRecyclerAdapter import org.fossasia.openevent.general.ticket.TicketId import org.fossasia.openevent.general.utils.StringUtils.getTermsAndPolicyText import org.fossasia.openevent.general.utils.Utils import org.fossasia.openevent.general.utils.Utils.isNetworkConnected import org.fossasia.openevent.general.utils.Utils.setToolbar import org.fossasia.openevent.general.utils.Utils.show import org.fossasia.openevent.general.utils.checkEmpty import org.fossasia.openevent.general.utils.checkValidEmail import org.fossasia.openevent.general.utils.extensions.nonNull import org.fossasia.openevent.general.utils.nullToEmpty import org.fossasia.openevent.general.utils.setRequired import org.jetbrains.anko.design.longSnackbar import org.jetbrains.anko.design.snackbar import org.koin.androidx.viewmodel.ext.android.viewModel private const val PAYPAL_REQUEST_CODE = 101 class AttendeeFragment : Fragment(), ComplexBackPressFragment { private lateinit var rootView: View private val attendeeViewModel by viewModel<AttendeeViewModel>() private val ticketsRecyclerAdapter: TicketDetailsRecyclerAdapter = TicketDetailsRecyclerAdapter() private val attendeeRecyclerAdapter: AttendeeRecyclerAdapter = AttendeeRecyclerAdapter() private val safeArgs: AttendeeFragmentArgs by navArgs() private lateinit var timer: CountDownTimer private lateinit var card: Card override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (attendeeViewModel.ticketIdAndQty == null) { attendeeViewModel.ticketIdAndQty = safeArgs.ticketIdAndQty?.value attendeeViewModel.singleTicket = safeArgs.ticketIdAndQty?.value?.map { it.second }?.sum() == 1 } attendeeRecyclerAdapter.setEventId(safeArgs.eventId) if (attendeeViewModel.paymentCurrency.isNotBlank()) ticketsRecyclerAdapter.setCurrency(attendeeViewModel.paymentCurrency) safeArgs.ticketIdAndQty?.value?.let { val quantities = it.map { pair -> pair.second }.filter { it != 0 } val donations = it.filter { it.second != 0 }.map { pair -> pair.third * pair.second } ticketsRecyclerAdapter.setQuantity(quantities) ticketsRecyclerAdapter.setDonations(donations) attendeeRecyclerAdapter.setQuantity(quantities) } attendeeViewModel.forms.value?.let { attendeeRecyclerAdapter.setCustomForm(it) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.fragment_attendee, container, false) setToolbar(activity, getString(R.string.attendee_details)) setHasOptionsMenu(true) attendeeViewModel.message .nonNull() .observe(viewLifecycleOwner, Observer { rootView.longSnackbar(it) }) val progressDialog = Utils.progressDialog(context, getString(R.string.creating_order_message)) attendeeViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { progressDialog.show(it) }) attendeeViewModel.redirectToProfile .observe(viewLifecycleOwner, Observer { rootView.longSnackbar(getString(R.string.verify_your_profile)) findNavController(rootView).navigate( AttendeeFragmentDirections.actionTicketsToProfile() ) }) rootView.sameBuyerCheckBox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { val firstName = rootView.firstName.text.toString() val lastName = rootView.lastName.text.toString() if (firstName.isEmpty() || lastName.isEmpty()) { rootView.longSnackbar(getString(R.string.fill_required_fields_message)) rootView.sameBuyerCheckBox.isChecked = false return@setOnCheckedChangeListener } attendeeRecyclerAdapter.setFirstAttendee( Attendee(firstname = firstName, lastname = lastName, email = rootView.email.text.toString(), id = attendeeViewModel.getId()) ) } else { attendeeRecyclerAdapter.setFirstAttendee(null) } } setupEventInfo() setupPendingOrder() setupTicketDetailTable() setupSignOutLogIn() setupAttendeeDetails() setupCustomForms() setupBillingInfo() setupCountryOptions() setupCardNumber() setupMonthOptions() setupYearOptions() setupTermsAndCondition() setupRegisterOrder() return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val attendeeDetailChangeListener = object : AttendeeDetailChangeListener { override fun onAttendeeDetailChanged(attendee: Attendee, position: Int) { attendeeViewModel.attendees[position] = attendee } } attendeeRecyclerAdapter.apply { attendeeChangeListener = attendeeDetailChangeListener } } override fun onResume() { super.onResume() if (!isNetworkConnected(context)) { rootView.attendeeScrollView.longSnackbar(getString(R.string.no_internet_connection_message)) } } override fun onDestroyView() { super.onDestroyView() attendeeRecyclerAdapter.attendeeChangeListener = null } override fun onDestroy() { super.onDestroy() if (this::timer.isInitialized) timer.cancel() activity?.stopService(Intent(activity, PayPalService::class.java)) } override fun handleBackPress() { AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.cancel_order)) .setMessage(getString(R.string.cancel_order_message)) .setPositiveButton(getString(R.string.cancel_order_button)) { _, _ -> findNavController(rootView).popBackStack() }.setNeutralButton(getString(R.string.continue_order_button)) { dialog, _ -> dialog.cancel() }.create() .show() } private fun setupEventInfo() { attendeeViewModel.event .nonNull() .observe(viewLifecycleOwner, Observer { loadEventDetailsUI(it) setupPaymentOptions(it) }) attendeeViewModel.getSettings() attendeeViewModel.orderExpiryTime .nonNull() .observe(viewLifecycleOwner, Observer { setupCountDownTimer(it) }) val currentEvent = attendeeViewModel.event.value if (currentEvent == null) attendeeViewModel.loadEvent(safeArgs.eventId) else { setupPaymentOptions(currentEvent) loadEventDetailsUI(currentEvent) } rootView.register.text = if (safeArgs.amount > 0) getString(R.string.pay_now) else getString(R.string.register) } private fun setupPendingOrder() { val currentPendingOrder = attendeeViewModel.pendingOrder.value if (currentPendingOrder == null) { attendeeViewModel.initializeOrder(safeArgs.eventId) } } private fun setupCountDownTimer(orderExpiryTime: Int) { rootView.timeoutCounterLayout.isVisible = true rootView.timeoutInfoTextView.text = getString(R.string.ticket_timeout_info_message, orderExpiryTime.toString()) val timeLeft: Long = if (attendeeViewModel.timeout == -1L) orderExpiryTime * 60 * 1000L else attendeeViewModel.timeout timer = object : CountDownTimer(timeLeft, 1000) { override fun onFinish() { findNavController(rootView).navigate(AttendeeFragmentDirections .actionAttendeeToTicketPop(safeArgs.eventId, safeArgs.currency, true)) } override fun onTick(millisUntilFinished: Long) { attendeeViewModel.timeout = millisUntilFinished val minutes = millisUntilFinished / 1000 / 60 val seconds = millisUntilFinished / 1000 % 60 rootView.timeoutTextView.text = "$minutes:$seconds" } } timer.start() } private fun setupTicketDetailTable() { attendeeViewModel.ticketIdAndQty?.map { it.second }?.sum()?.let { rootView.qty.text = resources.getQuantityString(R.plurals.order_quantity_item, it, it) } rootView.ticketsRecycler.layoutManager = LinearLayoutManager(activity) rootView.ticketsRecycler.adapter = ticketsRecyclerAdapter rootView.ticketsRecycler.isNestedScrollingEnabled = false rootView.taxLayout.isVisible = safeArgs.taxAmount > 0f rootView.taxPrice.text = "${Currency.getInstance(safeArgs.currency).symbol}${"%.2f".format(safeArgs.taxAmount)}" rootView.totalAmountLayout.isVisible = safeArgs.amount > 0f rootView.totalPrice.text = "${Currency.getInstance(safeArgs.currency).symbol}${"%.2f".format(safeArgs.amount)}" rootView.ticketTableDetails.setOnClickListener { attendeeViewModel.ticketDetailsVisible = !attendeeViewModel.ticketDetailsVisible loadTicketDetailsTableUI(attendeeViewModel.ticketDetailsVisible) } loadTicketDetailsTableUI(attendeeViewModel.ticketDetailsVisible) attendeeViewModel.totalAmount.value = safeArgs.amount rootView.paymentSelectorContainer.isVisible = safeArgs.amount > 0 attendeeViewModel.tickets .nonNull() .observe(viewLifecycleOwner, Observer { tickets -> ticketsRecyclerAdapter.addAll(tickets) attendeeRecyclerAdapter.addAllTickets(tickets) }) val currentTickets = attendeeViewModel.tickets.value if (currentTickets != null) { rootView.paymentSelectorContainer.isVisible = safeArgs.amount > 0 ticketsRecyclerAdapter.addAll(currentTickets) attendeeRecyclerAdapter.addAllTickets(currentTickets) } else { attendeeViewModel.getTickets() } } private fun setupSignOutLogIn() { rootView.signInEmailLayout.setRequired() rootView.signInPasswordLayout.setRequired() rootView.firstNameLayout.setRequired() rootView.lastNameLayout.setRequired() rootView.emailLayout.setRequired() setupSignInLayout() setupUser() setupLoginSignoutClickListener() attendeeViewModel.signedIn .nonNull() .observe(viewLifecycleOwner, Observer { signedIn -> rootView.signInLayout.isVisible = !signedIn rootView.signOutLayout.isVisible = signedIn if (signedIn) { rootView.sameBuyerCheckBox.isVisible = true attendeeViewModel.loadUser() } else { attendeeViewModel.isShowingSignInText = true handleSignedOut() } }) if (attendeeViewModel.isLoggedIn()) { rootView.signInLayout.isVisible = false rootView.signOutLayout.isVisible = true rootView.sameBuyerCheckBox.isVisible = true val currentUser = attendeeViewModel.user.value if (currentUser == null) attendeeViewModel.loadUser() else loadUserUI(currentUser) } else { handleSignedOut() } } private fun handleSignedOut() { rootView.signInEditLayout.isVisible = !attendeeViewModel.isShowingSignInText rootView.signInTextLayout.isVisible = attendeeViewModel.isShowingSignInText rootView.email.setText("") rootView.firstName.setText("") rootView.lastName.setText("") rootView.sameBuyerCheckBox.isChecked = false rootView.sameBuyerCheckBox.isVisible = false } private fun setupSignInLayout() { val stringBuilder = SpannableStringBuilder() val signIn = getString(R.string.sign_in) val signInForOrderText = getString(R.string.sign_in_order_text) stringBuilder.append(signIn) stringBuilder.append(" $signInForOrderText") val signInSpan = object : ClickableSpan() { override fun onClick(widget: View) { rootView.signInTextLayout.isVisible = false rootView.signInEditLayout.isVisible = true attendeeViewModel.isShowingSignInText = false } override fun updateDrawState(ds: TextPaint) { super.updateDrawState(ds) ds.isUnderlineText = false } } stringBuilder.setSpan(signInSpan, 0, signIn.length + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) rootView.signInText.text = stringBuilder rootView.signInText.movementMethod = LinkMovementMethod.getInstance() } private fun setupLoginSignoutClickListener() { rootView.cancelButton.setOnClickListener { rootView.signInTextLayout.isVisible = true rootView.signInEditLayout.isVisible = false attendeeViewModel.isShowingSignInText = true } rootView.loginButton.setOnClickListener { var validForLogin = true validForLogin = rootView.signInEmail.checkEmpty(rootView.signInEmailLayout) && validForLogin validForLogin = rootView.signInEmail.checkValidEmail(rootView.signInEmailLayout) && validForLogin validForLogin = rootView.signInPassword.checkEmpty(rootView.signInEmailLayout) && validForLogin if (validForLogin) attendeeViewModel.login(rootView.signInEmail.text.toString(), rootView.signInPassword.text.toString()) } rootView.signOut.setOnClickListener { if (!isNetworkConnected(context)) { rootView.snackbar(getString(R.string.no_internet_connection_message)) return@setOnClickListener } attendeeViewModel.logOut() } } private fun setupUser() { attendeeViewModel.user .nonNull() .observe(viewLifecycleOwner, Observer { user -> loadUserUI(user) if (attendeeViewModel.singleTicket) { val pos = attendeeViewModel.ticketIdAndQty?.map { it.second }?.indexOf(1) val ticket = pos?.let { it1 -> attendeeViewModel.ticketIdAndQty?.get(it1)?.first?.toLong() } ?: -1 val attendee = Attendee(id = attendeeViewModel.getId(), firstname = rootView.firstName.text.toString(), lastname = rootView.lastName.text.toString(), email = rootView.email.text.toString(), ticket = TicketId(ticket), event = EventId(safeArgs.eventId)) attendeeViewModel.attendees.clear() attendeeViewModel.attendees.add(attendee) } }) } private fun setupAttendeeDetails() { rootView.attendeeRecycler.layoutManager = LinearLayoutManager(activity) rootView.attendeeRecycler.adapter = attendeeRecyclerAdapter rootView.attendeeRecycler.isNestedScrollingEnabled = false if (attendeeViewModel.attendees.isEmpty()) { attendeeViewModel.ticketIdAndQty?.let { it.forEach { pair -> repeat(pair.second) { attendeeViewModel.attendees.add(Attendee( id = attendeeViewModel.getId(), firstname = "", lastname = "", email = "", ticket = TicketId(pair.first.toLong()), event = EventId(safeArgs.eventId) )) } } } } attendeeRecyclerAdapter.addAllAttendees(attendeeViewModel.attendees) } private fun setupCustomForms() { attendeeViewModel.forms .nonNull() .observe(viewLifecycleOwner, Observer { attendeeRecyclerAdapter.setCustomForm(it) }) val currentForms = attendeeViewModel.forms.value if (currentForms == null) { attendeeViewModel.getCustomFormsForAttendees(safeArgs.eventId) } else { attendeeRecyclerAdapter.setCustomForm(currentForms) } } private fun setupBillingInfo() { rootView.billingInfoCheckboxSection.isVisible = safeArgs.amount > 0 rootView.billingCompanyLayout.setRequired() rootView.billingAddressLayout.setRequired() rootView.billingCityLayout.setRequired() rootView.billingPostalCodeLayout.setRequired() rootView.billingInfoContainer.isVisible = rootView.billingEnabledCheckbox.isChecked attendeeViewModel.billingEnabled = rootView.billingEnabledCheckbox.isChecked rootView.billingEnabledCheckbox.setOnCheckedChangeListener { _, isChecked -> attendeeViewModel.billingEnabled = isChecked rootView.billingInfoContainer.isVisible = isChecked } } private fun setupCountryOptions() { ArrayAdapter.createFromResource( requireContext(), R.array.country_arrays, android.R.layout.simple_spinner_dropdown_item ).also { adapter -> rootView.countryPicker.adapter = adapter if (attendeeViewModel.countryPosition == -1) autoSetCurrentCountry() else rootView.countryPicker.setSelection(attendeeViewModel.countryPosition) } rootView.countryPicker.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { /*Do nothing*/ } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { attendeeViewModel.countryPosition = position } } } private fun setupPaymentOptions(event: Event) { rootView.paypalRadioButton.isVisible = event.canPayByPaypal rootView.stripeRadioButton.isVisible = event.canPayByStripe rootView.chequeRadioButton.isVisible = event.canPayByCheque rootView.bankRadioButton.isVisible = event.canPayByBank rootView.onSiteRadioButton.isVisible = event.canPayOnsite rootView.paymentOptionsGroup.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { R.id.stripeRadioButton -> { rootView.stripePayment.isVisible = true rootView.offlinePayment.isVisible = false attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_STRIPE rootView.register.text = getString(R.string.pay_now) } R.id.onSiteRadioButton -> { rootView.offlinePayment.isVisible = true rootView.stripePayment.isVisible = false rootView.offlinePaymentDescription.text = event.onsiteDetails attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_ONSITE rootView.register.text = getString(R.string.register) } R.id.bankRadioButton -> { rootView.offlinePayment.isVisible = true rootView.stripePayment.isVisible = false rootView.offlinePaymentDescription.text = event.bankDetails attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_BANK rootView.register.text = getString(R.string.register) } R.id.chequeRadioButton -> { rootView.offlinePayment.isVisible = true rootView.stripePayment.isVisible = false rootView.offlinePaymentDescription.text = event.chequeDetails attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_CHEQUE rootView.register.text = getString(R.string.register) } else -> { rootView.stripePayment.isVisible = false rootView.offlinePayment.isVisible = false attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_PAYPAL rootView.register.text = getString(R.string.pay_now) } } } } private fun setupCardNumber() { rootView.cardNumberLayout.setRequired() rootView.cvcLayout.setRequired() rootView.cardNumber.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { /*Do Nothing*/ } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { /*Do Nothing*/ } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (s != null) { val cardType = Utils.getCardType(s.toString()) if (cardType == Utils.cardType.NONE) { rootView.cardNumberLayout.error = getString(R.string.invalid_card_number_message) return } } rootView.cardNumber.error = null } }) attendeeViewModel.stripeOrderMade .nonNull() .observe(viewLifecycleOwner, Observer { if (it && this::card.isInitialized) sendToken(card) }) attendeeViewModel.paypalOrderMade .nonNull() .observe(viewLifecycleOwner, Observer { startPaypalPayment() }) } private fun setupMonthOptions() { val month = mutableListOf( getString(R.string.month_string), getString(R.string.january), getString(R.string.february), getString(R.string.march), getString(R.string.april), getString(R.string.may), getString(R.string.june), getString(R.string.july), getString(R.string.august), getString(R.string.september), getString(R.string.october), getString(R.string.november), getString(R.string.december) ) rootView.month.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, month) rootView.month.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { /* Do nothing */ } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { attendeeViewModel.monthSelectedPosition = p2 rootView.monthText.text = month[p2] } } rootView.monthText.setOnClickListener { rootView.month.performClick() } rootView.month.setSelection(attendeeViewModel.monthSelectedPosition) } private fun setupYearOptions() { val year = ArrayList<String>() val currentYear = Calendar.getInstance().get(Calendar.YEAR) val a = currentYear + 20 for (i in currentYear..a) { year.add(i.toString()) } rootView.year.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, year) rootView.year.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { /* Do nothing */ } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, pos: Int, p3: Long) { attendeeViewModel.yearSelectedPosition = pos rootView.yearText.text = year[pos] } } rootView.yearText.setOnClickListener { rootView.year.performClick() } rootView.year.setSelection(attendeeViewModel.yearSelectedPosition) } private fun setupTermsAndCondition() { rootView.accept.text = getTermsAndPolicyText(requireContext(), resources) rootView.accept.movementMethod = LinkMovementMethod.getInstance() } private fun checkPaymentOptions(): Boolean = when (attendeeViewModel.selectedPaymentMode) { PAYMENT_MODE_STRIPE -> { card = Card.create(rootView.cardNumber.text.toString(), attendeeViewModel.monthSelectedPosition, rootView.year.selectedItem.toString().toInt(), rootView.cvc.text.toString()) if (!card.validateCard()) { rootView.snackbar(getString(R.string.invalid_card_data_message)) false } else { true } } PAYMENT_MODE_CHEQUE, PAYMENT_MODE_ONSITE, PAYMENT_MODE_FREE, PAYMENT_MODE_BANK, PAYMENT_MODE_PAYPAL -> true else -> { rootView.snackbar(getString(R.string.select_payment_option_message)) false } } private fun startPaypalPayment() { val paypalEnvironment = if (BuildConfig.DEBUG) PayPalConfiguration.ENVIRONMENT_SANDBOX else PayPalConfiguration.ENVIRONMENT_PRODUCTION val paypalConfig = PayPalConfiguration() .environment(paypalEnvironment) .clientId(BuildConfig.PAYPAL_CLIENT_ID) val paypalIntent = Intent(activity, PaymentActivity::class.java) paypalIntent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig) activity?.startService(paypalIntent) val paypalPayment = paypalThingsToBuy(PayPalPayment.PAYMENT_INTENT_SALE) val payeeEmail = attendeeViewModel.event.value?.paypalEmail ?: "" paypalPayment.payeeEmail(payeeEmail) addShippingAddress(paypalPayment) val intent = Intent(activity, PaymentActivity::class.java) intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig) intent.putExtra(PaymentActivity.EXTRA_PAYMENT, paypalPayment) startActivityForResult(intent, PAYPAL_REQUEST_CODE) } private fun addShippingAddress(paypalPayment: PayPalPayment) { if (rootView.billingEnabledCheckbox.isChecked) { val shippingAddress = ShippingAddress() .recipientName("${rootView.firstName.text} ${rootView.lastName.text}") .line1(rootView.billingAddress.text.toString()) .city(rootView.billingCity.text.toString()) .state(rootView.billingState.text.toString()) .postalCode(rootView.billingPostalCode.text.toString()) .countryCode(getCountryCodes(rootView.countryPicker.selectedItem.toString())) paypalPayment.providedShippingAddress(shippingAddress) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PAYPAL_REQUEST_CODE && resultCode == Activity.RESULT_OK) { val paymentConfirm = data?.getParcelableExtra<PaymentConfirmation>(PaymentActivity.EXTRA_RESULT_CONFIRMATION) if (paymentConfirm != null) { val paymentId = paymentConfirm.proofOfPayment.paymentId attendeeViewModel.sendPaypalConfirm(paymentId) } } } private fun paypalThingsToBuy(paymentIntent: String): PayPalPayment = PayPalPayment(BigDecimal(safeArgs.amount.toString()), Currency.getInstance(safeArgs.currency).currencyCode, getString(R.string.tickets_for, attendeeViewModel.event.value?.name), paymentIntent) private fun checkRequiredFields(): Boolean { val checkBasicInfo = rootView.firstName.checkEmpty(rootView.firstNameLayout) && rootView.lastName.checkEmpty(rootView.lastNameLayout) && rootView.email.checkEmpty(rootView.emailLayout) var checkBillingInfo = true if (rootView.billingEnabledCheckbox.isChecked) { checkBillingInfo = rootView.billingCompany.checkEmpty(rootView.billingCompanyLayout) && checkBillingInfo checkBillingInfo = rootView.billingAddress.checkEmpty(rootView.billingAddressLayout) && checkBillingInfo checkBillingInfo = rootView.billingCity.checkEmpty(rootView.billingCityLayout) && checkBillingInfo checkBillingInfo = rootView.billingPostalCode.checkEmpty(rootView.billingPostalCodeLayout) && checkBillingInfo } var checkStripeInfo = true if (safeArgs.amount != 0F && attendeeViewModel.selectedPaymentMode == PAYMENT_MODE_STRIPE) { checkStripeInfo = rootView.cardNumber.checkEmpty(rootView.cardNumberLayout) && rootView.cvc.checkEmpty(rootView.cvcLayout) } return checkAttendeesInfo() && checkBasicInfo && checkBillingInfo && checkStripeInfo } private fun checkAttendeesInfo(): Boolean { var valid = true for (pos in 0..attendeeRecyclerAdapter.itemCount) { val viewHolderItem = rootView.attendeeRecycler.findViewHolderForAdapterPosition(pos) if (viewHolderItem is AttendeeViewHolder) { if (!viewHolderItem.checkValidFields()) valid = false } } return valid } private fun setupRegisterOrder() { rootView.register.setOnClickListener { val currentUser = attendeeViewModel.user.value if (currentUser == null) { rootView.longSnackbar(getString(R.string.sign_in_to_order_ticket)) return@setOnClickListener } if (!isNetworkConnected(context)) { rootView.attendeeScrollView.longSnackbar(getString(R.string.no_internet_connection_message)) return@setOnClickListener } if (!rootView.acceptCheckbox.isChecked) { rootView.attendeeScrollView.longSnackbar(getString(R.string.term_and_conditions)) return@setOnClickListener } if (!checkRequiredFields()) { rootView.snackbar(R.string.fill_required_fields_message) return@setOnClickListener } if (attendeeViewModel.totalAmount.value != 0F && !checkPaymentOptions()) return@setOnClickListener val attendees = attendeeViewModel.attendees if (attendeeViewModel.areAttendeeEmailsValid(attendees)) { val country = rootView.countryPicker.selectedItem.toString() val paymentOption = if (safeArgs.amount != 0F) attendeeViewModel.selectedPaymentMode else PAYMENT_MODE_FREE val company = rootView.billingCompany.text.toString() val city = rootView.billingCity.text.toString() val state = rootView.billingState.text.toString() val taxId = rootView.taxId.text.toString() val address = rootView.billingAddress.text.toString() val postalCode = rootView.billingPostalCode.text.toString() attendeeViewModel.createAttendees(attendees, country, company, taxId, address, city, postalCode, state, paymentOption) } else { rootView.attendeeScrollView.longSnackbar(getString(R.string.invalid_email_address_message)) } } attendeeViewModel.ticketSoldOut .nonNull() .observe(viewLifecycleOwner, Observer { showTicketSoldOutDialog(it) }) attendeeViewModel.orderCompleted .nonNull() .observe(viewLifecycleOwner, Observer { if (it) openOrderCompletedFragment() }) } private fun showTicketSoldOutDialog(show: Boolean) { if (show) { val builder = AlertDialog.Builder(requireContext()) builder.setMessage(getString(R.string.tickets_sold_out)) .setPositiveButton(getString(R.string.ok)) { dialog, _ -> dialog.cancel() } builder.show() } } private fun sendToken(card: Card) { Stripe(requireContext(), BuildConfig.STRIPE_API_KEY) .createCardToken(card = card, callback = object : ApiResultCallback<Token> { override fun onSuccess(token: Token) { val charge = Charge(attendeeViewModel.getId().toInt(), token.id, null) attendeeViewModel.chargeOrder(charge) } override fun onError(error: Exception) { rootView.snackbar(error.localizedMessage.toString()) } }) } private fun loadEventDetailsUI(event: Event) { val startsAt = EventUtils.getEventDateTime(event.startsAt, event.timezone) val endsAt = EventUtils.getEventDateTime(event.endsAt, event.timezone) attendeeViewModel.paymentCurrency = Currency.getInstance(event.paymentCurrency).symbol ticketsRecyclerAdapter.setCurrency(attendeeViewModel.paymentCurrency) rootView.eventName.text = event.name val total = if (safeArgs.amount > 0) "${attendeeViewModel.paymentCurrency} ${"%.2f".format(safeArgs.amount)}" else getString(R.string.free) rootView.amount.text = getString(R.string.total_amount, total) rootView.time.text = EventUtils.getFormattedDateTimeRangeDetailed(startsAt, endsAt) } private fun loadUserUI(user: User) { rootView.helloUser.text = getString(R.string.hello_user, user.firstName.nullToEmpty()) rootView.firstName.text = SpannableStringBuilder(user.firstName.nullToEmpty()) rootView.lastName.text = SpannableStringBuilder(user.lastName.nullToEmpty()) rootView.email.text = SpannableStringBuilder(user.email.nullToEmpty()) rootView.firstName.isEnabled = user.firstName.isNullOrEmpty() rootView.lastName.isEnabled = user.lastName.isNullOrEmpty() rootView.email.isEnabled = false } private fun loadTicketDetailsTableUI(show: Boolean) { if (show) { rootView.ticketDetails.isVisible = true rootView.ticketTableDetails.text = context?.getString(R.string.hide) } else { rootView.ticketDetails.isVisible = false rootView.ticketTableDetails.text = context?.getString(R.string.view) } } private fun openOrderCompletedFragment() { attendeeViewModel.orderCompleted.value = false findNavController(rootView).navigate(AttendeeFragmentDirections .actionAttendeeToOrderCompleted(safeArgs.eventId)) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { activity?.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } private fun autoSetCurrentCountry() { val telephonyManager: TelephonyManager = activity?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager val currentCountryCode = telephonyManager.networkCountryIso val countryCodes = resources.getStringArray(R.array.country_code_arrays) val countryIndex = countryCodes.indexOf(currentCountryCode.toUpperCase()) if (countryIndex != -1) rootView.countryPicker.setSelection(countryIndex) } private fun getCountryCodes(countryName: String): String { val countryCodes = resources.getStringArray(R.array.country_code_arrays) val countryList = resources.getStringArray(R.array.country_arrays) val index = countryList.indexOf(countryName) return countryCodes[index] } }
apache-2.0
228407aa050e9667c6d3e05c5b49c351
44.884575
120
0.677758
5.322298
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/data/models/Casting.kt
1
1318
package app.youkai.data.models import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.github.jasminb.jsonapi.Links import com.github.jasminb.jsonapi.annotations.Relationship import com.github.jasminb.jsonapi.annotations.RelationshipLinks import com.github.jasminb.jsonapi.annotations.Type @Type("castings") @JsonIgnoreProperties(ignoreUnknown = true) class Casting : BaseJsonModel(JsonType("castings")) { companion object FieldNames { val ROLE = "role" val VOICE_ACTOR = "voiceActor" val FEATURED = "featured" val LANGUAGE = "language" val PERSON = "person" val MEDIA = "media" val CHARACTER = "character" } var role: String? = null @JsonProperty("voiceActor") var isVoiceActor: Boolean? = null var featured: Boolean? = null var language: String? = null @Relationship("person") var person: Person? = null @RelationshipLinks("person") var personLinks: Links? = null @Relationship("media") var media: BaseMedia? = null @RelationshipLinks("media") var mediaLinks: Links? = null @Relationship("character") var character: Character? = null @RelationshipLinks("character") var characterLinks: Links? = null }
gpl-3.0
ac1e6a6d6c59e21b3922a0650d1cc6a7
25.38
63
0.699545
4.364238
false
false
false
false
BasinMC/Basin
sink/src/main/kotlin/org/basinmc/sink/SinkVersion.kt
1
1835
/* * Copyright 2019 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.basinmc.sink import org.apache.logging.log4j.LogManager import java.io.IOException import java.util.* /** * @author [Johannes Donath](mailto:[email protected]) */ object SinkVersion { val version: String val guava: String val log4j: String val commonsLang: String val gson: String val netty: String val findbugs: String init { val p = Properties() try { SinkVersion::class.java .getResourceAsStream("/sink-version.properties") .use(p::load) } catch (ex: IOException) { LogManager.getLogger(SinkVersion::class.java) .error("Could not load Sink version information: " + ex.message, ex) } version = p.getProperty("sink.version", "0.0.0") guava = p.getProperty("dependency.guava.version", "0.0.0") log4j = p.getProperty("dependency.log4j.version", "0.0.0") commonsLang = p.getProperty("dependency.commons.lang.version", "0.0.0") gson = p.getProperty("dependency.gson.version", "0.0.0") netty = p.getProperty("dependency.netty.version", "0.0.0") findbugs = p.getProperty("dependency.findbugs.version", "0.0.0") } }
apache-2.0
e97659164efa5de7bc1fca54675774d0
31.192982
78
0.698093
3.707071
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/state/AbstractStateContainer.kt
1
8659
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.state import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import com.google.common.collect.ImmutableTable import com.google.common.collect.Lists import org.lanternpowered.api.catalog.CatalogType import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.api.key.namespacedKey import org.lanternpowered.api.registry.CatalogTypeRegistry import org.lanternpowered.api.util.collections.immutableMapBuilderOf import org.lanternpowered.api.util.collections.immutableMapOf import org.lanternpowered.api.util.collections.immutableSetBuilderOf import org.lanternpowered.api.util.collections.immutableSetOf import org.lanternpowered.api.util.collections.toImmutableList import org.lanternpowered.api.util.uncheckedCast import org.spongepowered.api.data.Key import org.spongepowered.api.data.persistence.DataContainer import org.spongepowered.api.data.persistence.DataQuery import org.spongepowered.api.data.persistence.DataView import org.spongepowered.api.data.value.Value import org.spongepowered.api.state.State import org.spongepowered.api.state.StateContainer import org.spongepowered.api.state.StateProperty import java.util.LinkedHashMap import java.util.Optional abstract class AbstractStateContainer<S : State<S>>( baseKey: NamespacedKey, stateProperties: Iterable<StateProperty<*>>, constructor: (StateBuilder<S>) -> S ) : StateContainer<S> { // The lookup to convert between key <--> state property val keysToProperty: ImmutableMap<Key<out Value<*>>, StateProperty<*>> private val validStates: ImmutableList<S> init { val properties = stateProperties.toMutableList() properties.sortBy { property -> property.getName() } val keysToPropertyBuilder = immutableMapBuilderOf<Key<out Value<*>>, StateProperty<*>>() for (property in properties) keysToPropertyBuilder.put((property as IStateProperty<*,*>).valueKey, property) this.keysToProperty = keysToPropertyBuilder.build() val cartesianProductInput = properties.map { property -> property.getPossibleValues().map { comparable -> @Suppress("UNCHECKED_CAST") val valueKey = (property as IStateProperty<*,*>).valueKey as Key<Value<Any>> val value = Value.immutableOf(valueKey, comparable as Any).asImmutable() Triple(property, comparable, value) } } val cartesianProduct = Lists.cartesianProduct(cartesianProductInput) val stateBuilders = mutableListOf<LanternStateBuilder<S>>() // A map with as the key the property values map and as value the state val stateByValuesMap = LinkedHashMap<Map<*, *>, S>() for ((internalId, list) in cartesianProduct.withIndex()) { val stateValuesBuilder = immutableMapBuilderOf<StateProperty<*>, Comparable<*>>() val immutableValuesBuilder = immutableSetBuilderOf<Value.Immutable<*>>() for ((property, comparable, value) in list) { stateValuesBuilder.put(property, comparable) immutableValuesBuilder.add(value) } val stateValues = stateValuesBuilder.build() val immutableValues = immutableValuesBuilder.build() val key = this.buildKey(baseKey, stateValues) val dataContainer = this.buildDataContainer(baseKey, stateValues) @Suppress("LeakingThis") stateBuilders += LanternStateBuilder(key, dataContainer, this, stateValues, immutableValues, internalId) } // There are no properties, so just add // the single state of this container if (properties.isEmpty()) { val dataContainer = this.buildDataContainer(baseKey, immutableMapOf()) @Suppress("LeakingThis") stateBuilders += LanternStateBuilder(baseKey, dataContainer, this, immutableMapOf(), immutableSetOf(), 0) } this.validStates = stateBuilders.map { val state = constructor(it) stateByValuesMap[it.stateValues] = state state }.toImmutableList() for (state in this.validStates) { val tableBuilder = ImmutableTable.builder<StateProperty<*>, Comparable<*>, S>() for (property in properties) { @Suppress("UNCHECKED_CAST") property as StateProperty<Comparable<Comparable<*>>> for (value in property.possibleValues) { if (value == state.getStateProperty(property).get()) continue val valueByProperty = HashMap<StateProperty<*>, Any>(state.statePropertyMap) valueByProperty[property] = value tableBuilder.put(property, value, checkNotNull(stateByValuesMap[valueByProperty])) } } @Suppress("UNCHECKED_CAST") (state as AbstractState<S,*>).propertyValueTable = tableBuilder.build() } // Call the completion for (stateBuilder in stateBuilders) { stateBuilder.whenCompleted.forEach { it() } } } companion object { private val NAME = DataQuery.of("Name") private val PROPERTIES = DataQuery.of("Properties") fun <T, S : State<S>> deserializeState(dataView: DataView, registry: CatalogTypeRegistry<T>): S where T : CatalogType, T : StateContainer<S> { val id = dataView.getString(NAME).get() val catalogType = registry.require(NamespacedKey.resolve(id)) var state = catalogType.defaultState val properties = dataView.getView(PROPERTIES).orElse(null) if (properties != null) { for ((key, rawValue) in properties.getValues(false)) { val stateProperty = state.getStatePropertyByName(key.toString()).orElse(null) if (stateProperty != null) { val value = stateProperty.parseValue(rawValue.toString()).orElse(null) if (value != null) { @Suppress("UNCHECKED_CAST") stateProperty as StateProperty<Comparable<Comparable<*>>> val newState = state.withStateProperty(stateProperty, value.uncheckedCast()).orElse(null) if (newState != null) { state = newState } } } } } return state } } private fun buildDataContainer(baseKey: NamespacedKey, values: Map<StateProperty<*>, Comparable<*>>): DataContainer { val dataContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED) dataContainer[NAME] = baseKey.toString() if (values.isEmpty()) return dataContainer val propertiesView = dataContainer.createView(PROPERTIES) for ((property, comparable) in values) { propertiesView[DataQuery.of(property.getName())] = comparable } return dataContainer } private fun buildKey(baseKey: NamespacedKey, values: Map<StateProperty<*>, Comparable<*>>): NamespacedKey { if (values.isEmpty()) return baseKey val builder = StringBuilder() builder.append(baseKey.value).append('[') val propertyValues = mutableListOf<String>() for ((property, comparable) in values) { val value = if (comparable is Enum) comparable.name else comparable.toString() propertyValues.add(property.getName() + '=' + value.toLowerCase()) } builder.append(propertyValues.joinToString(separator = ",")) builder.append(']') return namespacedKey(baseKey.namespace, builder.toString()) } override fun getValidStates(): ImmutableList<S> = this.validStates override fun getDefaultState(): S = this.validStates[0] override fun getStateProperties(): Collection<StateProperty<*>> = this.keysToProperty.values override fun getStatePropertyByName(statePropertyId: String): Optional<StateProperty<*>> = this.defaultState.getStatePropertyByName(statePropertyId) }
mit
8fca12129838e8a92ed1616a3d5da628
42.295
121
0.652731
5.166468
false
false
false
false
jensim/kotlin-koans
src/i_introduction/_9_Extension_Functions/ExtensionFunctions.kt
1
1014
package i_introduction._9_Extension_Functions import util.TODO import util.doc9 fun String.lastChar() = this.get(this.length - 1) // 'this' can be omitted fun String.lastChar1() = get(length - 1) fun use() { // try Ctrl+Space "default completion" after the dot: lastChar() is visible "abc".lastChar() } // 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode9.useExtension) fun todoTask9(): Nothing = TODO( """ Task 9. Implement the extension functions Int.r(), Pair<Int, Int>.r() to support the following manner of creating rational numbers: 1.r(), Pair(1, 2).r() """, documentation = doc9(), references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) }) data class RationalNumber(val numerator: Int, val denominator: Int) fun Int.r(): RationalNumber = RationalNumber(numerator = this, denominator = 1) fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(numerator = this.first, denominator = this.second)
mit
5c1f66b1e7422e39bb2cfd9cf01c2c83
31.709677
109
0.68146
3.727941
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/widget/DefaultBrowserPreference.kt
1
2006
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.widget import android.content.Context import android.os.Build import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceViewHolder import android.util.AttributeSet import android.widget.Switch import org.mozilla.focus.R import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.Browsers import org.mozilla.focus.utils.SupportUtils class DefaultBrowserPreference : Preference { private var switchView: Switch? = null // Instantiated from XML constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) // Instantiated from XML constructor(context: Context, attrs: AttributeSet) : super(context, attrs) init { widgetLayoutResource = R.layout.preference_default_browser val appName = context.resources.getString(R.string.app_name) val title = context.resources.getString(R.string.preference_default_browser2, appName) setTitle(title) } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) switchView = holder.findViewById(R.id.switch_widget) as Switch update() } fun update() { if (switchView != null) { val browsers = Browsers(context, Browsers.TRADITIONAL_BROWSER_URL) switchView?.isChecked = browsers.isDefaultBrowser(context) } } public override fun onClick() { val context = context if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { SupportUtils.openDefaultAppsSettings(context) TelemetryWrapper.makeDefaultBrowserSettings() } else { SupportUtils.openDefaultBrowserSumoPage(context) } } }
mpl-2.0
bbba467f194e8d99ca9a34642b191a68
31.885246
111
0.711864
4.418502
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/io/serializers/Serializers.kt
1
1633
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.core.io.serializers /** * 직렬화 인스턴스를 제공합니다. * * @author [email protected] */ object Serializers { /** Binary Serializer */ @JvmField val BINARY = BinarySerializer() /** FST Serializer for Java 6 */ @JvmField val FST = FstSerializer() /** Deflater + Binary Serializer */ @JvmField val DEFLATER_BINARY = DeflaterBinarySerializer() /** Deflater + FST Serializer */ @JvmField val DEFLATER_FST = DeflaterFstSerializer() /** GZip + Binary Serializer */ @JvmField val GZIP_BINARY = GZipBinarySerializer() /** GZip + FST Serializer */ @JvmField val GZIP_FST = GZipFstSerializer() /** LZ4 + Binary Serializer */ @JvmField val LZ4_BINARY = LZ4BinarySerializer() /** LZ4 + FST Serializer */ @JvmField val LZ4_FST = LZ4FstSerializer() /** SNAPPY + Binary Serializer */ @JvmField val SNAPPY_BINARY = SnappyBinarySerializer() /** SNAPPY + FST Serializer */ @JvmField val SNAPPY_FST_JAVA6 = SnappyFstSerializer() }
apache-2.0
01574eca804c0150738ddeec33332b3c
27.714286
75
0.70504
3.948403
false
false
false
false
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/repo/internals/migrations/Migration29to30.kt
1
5799
package voice.data.repo.internals.migrations import android.annotation.SuppressLint import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.squareup.anvil.annotations.ContributesMultibinding import org.json.JSONObject import voice.common.AppScope import voice.data.repo.internals.moveToNextLoop import javax.inject.Inject // tables private const val TABLE_BOOK = "tableBooks" private const val TABLE_CHAPTERS = "tableChapters" private const val TABLE_BOOKMARKS = "tableBookmarks" private const val BOOK_ID = "bookId" private const val BOOK_NAME = "bookName" private const val BOOK_AUTHOR = "bookAuthor" private const val BOOK_CURRENT_MEDIA_PATH = "bookCurrentMediaPath" private const val BOOK_PLAYBACK_SPEED = "bookSpeed" private const val BOOK_ROOT = "bookRoot" private const val BOOK_TIME = "bookTime" private const val BOOK_TYPE = "bookType" private const val BOOK_USE_COVER_REPLACEMENT = "bookUseCoverReplacement" private const val BOOK_ACTIVE = "BOOK_ACTIVE" // chapter keys private const val CHAPTER_DURATION = "chapterDuration" private const val CHAPTER_NAME = "chapterName" private const val CHAPTER_PATH = "chapterPath" // bookmark keys private const val BOOKMARK_TIME = "bookmarkTime" private const val BOOKMARK_PATH = "bookmarkPath" private const val BOOKMARK_TITLE = "bookmarkTitle" private const val CREATE_TABLE_BOOK = """ CREATE TABLE $TABLE_BOOK ( $BOOK_ID INTEGER PRIMARY KEY AUTOINCREMENT, $BOOK_NAME TEXT NOT NULL, $BOOK_AUTHOR TEXT, $BOOK_CURRENT_MEDIA_PATH TEXT NOT NULL, $BOOK_PLAYBACK_SPEED REAL NOT NULL, $BOOK_ROOT TEXT NOT NULL, $BOOK_TIME INTEGER NOT NULL, $BOOK_TYPE TEXT NOT NULL, $BOOK_USE_COVER_REPLACEMENT INTEGER NOT NULL, $BOOK_ACTIVE INTEGER NOT NULL DEFAULT 1 ) """ private const val CREATE_TABLE_CHAPTERS = """ CREATE TABLE $TABLE_CHAPTERS ( $CHAPTER_DURATION INTEGER NOT NULL, $CHAPTER_NAME TEXT NOT NULL, $CHAPTER_PATH TEXT NOT NULL, $BOOK_ID INTEGER NOT NULL, FOREIGN KEY ($BOOK_ID) REFERENCES $TABLE_BOOK($BOOK_ID) ) """ private const val CREATE_TABLE_BOOKMARKS = """ CREATE TABLE $TABLE_BOOKMARKS ( $BOOKMARK_PATH TEXT NOT NULL, $BOOKMARK_TITLE TEXT NOT NULL, $BOOKMARK_TIME INTEGER NOT NULL, $BOOK_ID INTEGER NOT NULL, FOREIGN KEY ($BOOK_ID) REFERENCES $TABLE_BOOK($BOOK_ID) ) """ @ContributesMultibinding( scope = AppScope::class, boundType = Migration::class, ) @SuppressLint("Recycle") class Migration29to30 @Inject constructor() : IncrementalMigration(29) { override fun migrate(db: SupportSQLiteDatabase) { // fetching old contents val cursor = db.query( "TABLE_BOOK", arrayOf("BOOK_JSON", "BOOK_ACTIVE"), ) val bookContents = ArrayList<String>(cursor.count) val activeMapping = ArrayList<Boolean>(cursor.count) cursor.moveToNextLoop { bookContents.add(cursor.getString(0)) activeMapping.add(cursor.getInt(1) == 1) } db.execSQL("DROP TABLE TABLE_BOOK") // drop tables in case they exist db.execSQL("DROP TABLE IF EXISTS $TABLE_BOOK") db.execSQL("DROP TABLE IF EXISTS $TABLE_CHAPTERS") db.execSQL("DROP TABLE IF EXISTS $TABLE_BOOKMARKS") // create new tables db.execSQL(CREATE_TABLE_BOOK) db.execSQL(CREATE_TABLE_CHAPTERS) db.execSQL(CREATE_TABLE_BOOKMARKS) for (i in bookContents.indices) { val bookJson = bookContents[i] val bookActive = activeMapping[i] val bookObj = JSONObject(bookJson) val bookmarks = bookObj.getJSONArray("bookmarks") val chapters = bookObj.getJSONArray("chapters") val currentMediaPath = bookObj.getString("currentMediaPath") val bookName = bookObj.getString("name") val speed = bookObj.getDouble("playbackSpeed").toFloat() val root = bookObj.getString("root") val time = bookObj.getInt("time") val type = bookObj.getString("type") val useCoverReplacement = bookObj.getBoolean("useCoverReplacement") val bookCV = ContentValues() bookCV.put(BOOK_CURRENT_MEDIA_PATH, currentMediaPath) bookCV.put(BOOK_NAME, bookName) bookCV.put(BOOK_PLAYBACK_SPEED, speed) bookCV.put(BOOK_ROOT, root) bookCV.put(BOOK_TIME, time) bookCV.put(BOOK_TYPE, type) bookCV.put(BOOK_USE_COVER_REPLACEMENT, if (useCoverReplacement) 1 else 0) bookCV.put(BOOK_ACTIVE, if (bookActive) 1 else 0) val bookId = db.insert(TABLE_BOOK, SQLiteDatabase.CONFLICT_FAIL, bookCV) for (j in 0 until chapters.length()) { val chapter = chapters.getJSONObject(j) val chapterDuration = chapter.getInt("duration") val chapterName = chapter.getString("name") val chapterPath = chapter.getString("path") val chapterCV = ContentValues() chapterCV.put(CHAPTER_DURATION, chapterDuration) chapterCV.put(CHAPTER_NAME, chapterName) chapterCV.put(CHAPTER_PATH, chapterPath) chapterCV.put(BOOK_ID, bookId) db.insert(TABLE_CHAPTERS, SQLiteDatabase.CONFLICT_FAIL, chapterCV) } for (j in 0 until bookmarks.length()) { val bookmark = bookmarks.getJSONObject(j) val bookmarkTime = bookmark.getInt("time") val bookmarkPath = bookmark.getString("mediaPath") val bookmarkTitle = bookmark.getString("title") val bookmarkCV = ContentValues() bookmarkCV.put(BOOKMARK_PATH, bookmarkPath) bookmarkCV.put(BOOKMARK_TITLE, bookmarkTitle) bookmarkCV.put(BOOKMARK_TIME, bookmarkTime) bookmarkCV.put(BOOK_ID, bookId) db.insert(TABLE_BOOKMARKS, SQLiteDatabase.CONFLICT_FAIL, bookmarkCV) } } } }
gpl-3.0
269c7109e48e0b1e3629368e2f3c49cd
34.359756
79
0.705294
4.101132
false
false
false
false
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTaskCallable.kt
1
2538
/* * Copyright (C) 2014-2022 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.asynctasks.ftp.auth import androidx.annotation.WorkerThread import com.amaze.filemanager.filesystem.ftp.FTPClientImpl import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.CONNECT_TIMEOUT import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTP_URI_PREFIX import net.schmizz.sshj.userauth.UserAuthException import org.apache.commons.net.ftp.FTPClient import java.util.concurrent.Callable open class FtpAuthenticationTaskCallable( protected val hostname: String, protected val port: Int, protected val username: String, protected val password: String ) : Callable<FTPClient> { @WorkerThread override fun call(): FTPClient { val ftpClient = createFTPClient() ftpClient.connectTimeout = CONNECT_TIMEOUT ftpClient.controlEncoding = Charsets.UTF_8.name() ftpClient.connect(hostname, port) val loginSuccess = if (username.isBlank() && password.isBlank()) { ftpClient.login( FTPClientImpl.ANONYMOUS, FTPClientImpl.generateRandomEmailAddressForLogin() ) } else { ftpClient.login(username, password) } return if (loginSuccess) { ftpClient.enterLocalPassiveMode() ftpClient } else { throw UserAuthException("Login failed") } } protected open fun createFTPClient(): FTPClient = NetCopyClientConnectionPool.ftpClientFactory.create(FTP_URI_PREFIX) }
gpl-3.0
1e68541d8cdade0cfb0f0846f227c3ca
39.285714
107
0.727344
4.5
false
false
false
false
coconautti/sequel
src/test/kotlin/coconautti/sql/DeleteSpec.kt
1
1348
package coconautti.sql import io.kotlintest.matchers.shouldEqual import io.kotlintest.specs.BehaviorSpec class DeleteSpec : BehaviorSpec() { init { given("a delete statement") { val stmt = Database.deleteFrom("users") {} `when`("extracting SQL") { val sql = stmt.toString() then("it should match expectation") { sql.shouldEqual("DELETE FROM users") } } } given("a delete statement with where clause") { val stmt = Database.deleteFrom("users") { where("id" eq 1) } `when`("extracting SQL") { val sql = stmt.toString() then("it should match expectation") { sql.shouldEqual("DELETE FROM users WHERE id = ?") } } } given("a delete statement with composite where clause") { val stmt = Database.deleteFrom("users") { where(("id" eq 1) or ("name" ne "Donald")) } `when`("extracting SQL") { val sql = stmt.toString() then("it should match expectation") { sql.shouldEqual("DELETE FROM users WHERE id = ? OR name != ?") } } } } }
apache-2.0
6dd8e1ad11c506f9608826cd7718340d
31.095238
82
0.478487
5.067669
false
false
false
false
nemerosa/ontrack
ontrack-job/src/main/java/net/nemerosa/ontrack/job/JobKey.kt
1
732
package net.nemerosa.ontrack.job import io.micrometer.core.instrument.Tag data class JobKey( val type: JobType, val id: String ) { fun sameType(type: JobType): Boolean { return this.type == type } fun sameCategory(category: JobCategory): Boolean { return this.type.category == category } override fun toString(): String { return "$type[$id]" } val metricTags: List<Tag> get() = listOf( Tag.of("job-type", type.key), Tag.of("job-category", type.category.key) ) companion object { @JvmStatic fun of(type: JobType, id: String): JobKey { return JobKey(type, id) } } }
mit
3ce479864431a148267543aad97df2fe
19.914286
57
0.558743
4.089385
false
false
false
false
liceoArzignano/app_bold
app/src/main/kotlin/it/liceoarzignano/bold/settings/SettingsActivity.kt
1
2312
package it.liceoarzignano.bold.settings import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.preference.PreferenceFragmentCompat import com.afollestad.materialdialogs.MaterialDialog import it.liceoarzignano.bold.R class SettingsActivity : AppCompatActivity() { override fun onCreate(savedInstance: Bundle?) { super.onCreate(savedInstance) setContentView(R.layout.activity_settings) val toolbar = findViewById<Toolbar>(R.id.toolbar_include) setSupportActionBar(toolbar) toolbar.setNavigationIcon(R.drawable.ic_toolbar_back) toolbar.setNavigationOnClickListener { finish() } } class MyPreferenceFragment : PreferenceFragmentCompat() { private lateinit var mContext: Context private lateinit var mPrefs: AppPrefs override fun onCreatePreferences(savedInstance: Bundle?, key: String?) { addPreferencesFromResource(R.xml.settings) mContext = activity ?: return mPrefs = AppPrefs(mContext) val changeLog = findPreference("changelog_key") val name = findPreference("username_key") changeLog.setOnPreferenceClickListener { MaterialDialog.Builder(mContext) .title(getString(R.string.pref_changelog)) .content(getString(R.string.dialog_updated_content)) .positiveText(getString(android.R.string.ok)) .negativeText(R.string.dialog_updated_changelog) .onNegative { dialog, _ -> dialog.hide() val mIntent = Intent(Intent.ACTION_VIEW) mIntent.data = Uri.parse(getString(R.string.config_url_changelog)) startActivity(mIntent) } .show() true } name.summary = mPrefs.get(AppPrefs.KEY_USERNAME, "") name.setOnPreferenceChangeListener { _, newValue -> name.summary = newValue.toString() true } } } }
lgpl-3.0
978c5d8a20aff39ff68f2bd3b718a045
36.901639
94
0.615484
5.557692
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/ValidationRunMutations.kt
1
6008
package net.nemerosa.ontrack.graphql.schema import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.graphql.support.TypeRef import net.nemerosa.ontrack.graphql.support.TypedMutationProvider import net.nemerosa.ontrack.json.JsonParseException import net.nemerosa.ontrack.model.annotations.APIDescription import net.nemerosa.ontrack.model.exceptions.BuildNotFoundException import net.nemerosa.ontrack.model.exceptions.ValidationRunDataJSONInputException import net.nemerosa.ontrack.model.structure.* import org.springframework.stereotype.Component @Component class ValidationRunMutations( private val structureService: StructureService, private val validationRunStatusService: ValidationRunStatusService, private val validationDataTypeService: ValidationDataTypeService, private val runInfoService: RunInfoService, ) : TypedMutationProvider() { override val mutations: List<Mutation> = listOf( simpleMutation( name = CREATE_VALIDATION_RUN_FOR_BUILD_BY_NAME, description = "Creating a validation run for a build identified by its name", input = CreateValidationRunInput::class, outputName = "validationRun", outputDescription = "Created validation run", outputType = ValidationRun::class ) { input -> val build = (structureService.findBuildByName(input.project, input.branch, input.build) .getOrNull() ?: throw BuildNotFoundException(input.project, input.branch, input.build)) validate(build, input) }, simpleMutation( name = CREATE_VALIDATION_RUN_FOR_BUILD_BY_ID, description = "Creating a validation run for a build identified by its ID", input = CreateValidationRunByIdInput::class, outputName = "validationRun", outputDescription = "Created validation run", outputType = ValidationRun::class ) { input -> val build = structureService.getBuild(ID.of(input.buildId)) validate(build, input) } ) private fun validate(build: Build, input: ValidationRunInput): ValidationRun { val run = structureService.newValidationRun( build = build, validationRunRequest = ValidationRunRequest( validationStampName = input.validationStamp, validationRunStatusId = input.validationRunStatus?.let(validationRunStatusService::getValidationRunStatus), dataTypeId = input.dataTypeId, data = parseValidationRunData(build, input.validationStamp, input.dataTypeId, input.data), description = input.description ) ) // Run info val runInfo = input.runInfo if (runInfo != null) { runInfoService.setRunInfo( entity = run, input = runInfo, ) } // OK return run } fun parseValidationRunData( build: Build, validationStampName: String, dataTypeId: String?, data: JsonNode?, ): Any? = data?.run { // Gets the validation stamp val validationStamp: ValidationStamp = structureService.getOrCreateValidationStamp( build.branch, validationStampName ) // Gets the data type ID if any // First, the data type in the request, and if not specified, the type of the validation stamp val typeId: String? = dataTypeId ?: validationStamp.dataType?.descriptor?.id // If no type, ignore the data return typeId ?.run { // Gets the actual type validationDataTypeService.getValidationDataType<Any, Any>(this) }?.run { // Parses data from the form try { fromForm(data) } catch (ex: JsonParseException) { throw ValidationRunDataJSONInputException(ex, data) } } } companion object { const val CREATE_VALIDATION_RUN_FOR_BUILD_BY_ID = "createValidationRunById" const val CREATE_VALIDATION_RUN_FOR_BUILD_BY_NAME = "createValidationRun" } } interface ValidationRunInput { val validationStamp: String val validationRunStatus: String? val description: String? val dataTypeId: String? val data: JsonNode? val runInfo: RunInfoInput? } class CreateValidationRunInput( @APIDescription("Project name") val project: String, @APIDescription("Branch name") val branch: String, @APIDescription("Build name") val build: String, @APIDescription("Validation stamp name") override val validationStamp: String, @APIDescription("Validation run status") override val validationRunStatus: String?, @APIDescription("Validation description") override val description: String?, @APIDescription("Type of the data to associated with the validation") override val dataTypeId: String?, @APIDescription("Data to associated with the validation") override val data: JsonNode?, @APIDescription("Run info") @TypeRef override val runInfo: RunInfoInput?, ): ValidationRunInput class CreateValidationRunByIdInput( @APIDescription("Build ID") val buildId: Int, @APIDescription("Validation stamp name") override val validationStamp: String, @APIDescription("Validation run status") override val validationRunStatus: String?, @APIDescription("Validation description") override val description: String?, @APIDescription("Type of the data to associated with the validation") override val dataTypeId: String?, @APIDescription("Data to associated with the validation") override val data: JsonNode?, @APIDescription("Run info") @TypeRef override val runInfo: RunInfoInput?, ): ValidationRunInput
mit
5b4b24a78cdc364cfde5ece6c78100b9
37.76129
123
0.666611
5.29806
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/intentions/IfLetToMatchIntention.kt
1
4067
package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.parentOfType class IfLetToMatchIntention : RsElementBaseIntentionAction<IfLetToMatchIntention.Context>() { override fun getText(): String = "Convert if let statement to match" override fun getFamilyName(): String = text data class Context( val ifStmt: RsIfExpr, val target: RsExpr, val matchArms: MutableList<MatchArm>, var elseBody: RsBlock? ) data class MatchArm( val matchArm: RsPat, val body: RsBlock ) override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { //1) Check that we have an if statement var ifStatement = element.parentOfType<RsIfExpr>() ?: return null // We go up in the tree to detect cases like `... else if let Some(value) = x { ... }` // and select the correct if statement while (ifStatement.parent is RsElseBranch) { // In that case // typeof(if.parent) = RsElseBranch ==> typeof(if.parent.parent) = RsIfExpr ifStatement = ifStatement.parent.parent as? RsIfExpr ?: return null } //Here we have extracted the upper most if statement node return extractIfLetStatementIfAny(ifStatement) } override fun invoke(project: Project, editor: Editor, ctx: Context) { val (ifStmt, target, matchArms, elseBody) = ctx //var generatedCode = "match ${target.text} {" var generatedCode = buildString { append("match ") append(target.text) append(" {") append(matchArms.map { arm -> "${arm.matchArm.text} => ${arm.body.text}" } .joinToString(", ")) if (elseBody != null) { append(", _ => ") append(elseBody.text) } append("}") } val matchExpression = RsPsiFactory(project).createExpression(generatedCode) as RsMatchExpr ifStmt.replace(matchExpression) } private fun extractIfLetStatementIfAny(iflet: RsIfExpr, ctx: Context? = null): Context? { val condition = iflet.condition ?: return null //2) Check that we have a let condition if (condition.let == null) { return null } //3) Extract the match arm condition val matchArmPat = condition.pat ?: return null //4) Extract the target val target = condition.expr //5) Extract the if body val ifBody = iflet.block ?: return null val matchArm = MatchArm(matchArmPat, ifBody) var context = if (ctx != null) { //If we reach this code, that mean we are in a `if let Some(value) = x { ... } else if let Other(value) = x { ... }` case // ^ val newContext = ctx.copy() // Check that the target is the same // Otherwise that doesn't make sense if (newContext.target.text != target.text) { return null } newContext.matchArms.add(matchArm) newContext } else { val newContext = Context(iflet, target, mutableListOf(matchArm), null) newContext } //6) Extract else body if any if (iflet.elseBranch != null) { val elseBody = iflet.elseBranch!! if (elseBody.ifExpr != null) { // This particular case mean that we have an `else if` that we must handle context = extractIfLetStatementIfAny(elseBody.ifExpr!!, context) ?: return null } else if (elseBody.block != null) { //This will go in the `_ => { ... }` arm context.elseBody = elseBody.block } } return context } }
mit
6e0a41de12df3f26d51072e98350596c
33.176471
133
0.574625
4.632118
false
false
false
false
deadpixelsociety/twodee
src/main/kotlin/com/thedeadpixelsociety/twodee/input/DefaultActionController.kt
1
3718
package com.thedeadpixelsociety.twodee.input import com.badlogic.gdx.Gdx import com.badlogic.gdx.utils.Array import com.badlogic.gdx.utils.IntMap import com.badlogic.gdx.utils.ObjectMap import com.thedeadpixelsociety.twodee.Predicate import com.thedeadpixelsociety.twodee.gdxArray class DefaultActionController<T> : ActionController<T>() { private val keyMap = IntMap<T>() private val buttonMap = IntMap<Array<T>>() private val reverseButtonMap = ObjectMap<T, Int>() private val touchMap = IntMap<Array<T>>() private val reverseTouchMap = ObjectMap<T, Int>() private val stateMap = ObjectMap<T, Boolean>() private val predicateMap = ObjectMap<T, Predicate<T>>() private val listeners = gdxArray<ActionListener<T>>() override fun mapKey(action: T, key: Int, predicate: Predicate<T>?) { val existing = keyMap.findKey(action, false, -1) if (existing != -1) { keyMap.remove(key) stateMap.remove(action) predicateMap.remove(action) } keyMap.put(key, action) stateMap.put(action, false) if (predicate != null) predicateMap.put(action, predicate) } override fun mapButton(action: T, button: Int, predicate: Predicate<T>?) { val actions = getActions(buttonMap, button) if (actions.contains(action)) { actions.removeValue(action, false) stateMap.remove(action) predicateMap.remove(action) reverseButtonMap.remove(action) } actions.add(action) stateMap.put(action, false) reverseButtonMap.put(action, button) if (predicate != null) predicateMap.put(action, predicate) } override fun mapTouch(action: T, pointer: Int, predicate: Predicate<T>?) { val actions = getActions(buttonMap, pointer) if (actions.contains(action)) { actions.removeValue(action, false) stateMap.remove(action) predicateMap.remove(action) reverseTouchMap.remove(action) } actions.add(action) stateMap.put(action, false) reverseTouchMap.put(action, pointer) if (predicate != null) predicateMap.put(action, predicate) } override fun actionDown(action: T): Boolean { val predicate = predicateMap.get(action, null) val key = keyMap.findKey(action, false, -1) if (key != -1) return Gdx.input.isKeyPressed(key) && predicate?.invoke(action) ?: true val button = reverseButtonMap.get(action, -1) if (button != -1) return Gdx.input.isButtonPressed(button) && predicate?.invoke(action) ?: true val pointer = reverseTouchMap.get(action, -1) if (pointer != -1) return Gdx.input.isTouched(pointer) && predicate?.invoke(action) ?: true return false } override fun actionUp(action: T): Boolean { return !actionDown(action) } private fun getActions(map: IntMap<Array<T>>, key: Int): Array<T> { var actions = map.get(key) if (actions == null) { actions = Array() map.put(key, actions) } return actions } override fun update() { stateMap.forEach { val action = it.key val lastState = it.value val state = actionDown(action) if (state != lastState) { listeners.forEach { it.invoke(action, state) } stateMap.put(action, state) } } } override fun addListener(listener: ActionListener<T>) { listeners.add(listener) } override fun removeListener(listener: ActionListener<T>) { listeners.removeValue(listener, true) } }
mit
a54617483f0beb6a879feb6d31b26782
33.757009
103
0.625336
4.278481
false
false
false
false
nickbutcher/plaid
app/src/test/java/io/plaidapp/TestData.kt
1
2693
/* * 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 io.plaidapp import io.plaidapp.core.designernews.data.DesignerNewsSearchSourceItem import io.plaidapp.core.designernews.data.stories.model.Story import io.plaidapp.core.designernews.data.stories.model.StoryLinks import io.plaidapp.core.dribbble.data.DribbbleSourceItem import io.plaidapp.core.dribbble.data.api.model.Images import io.plaidapp.core.dribbble.data.api.model.Shot import io.plaidapp.core.dribbble.data.api.model.User import io.plaidapp.core.producthunt.data.api.model.Post import io.plaidapp.core.ui.filter.SourceUiModel import java.util.Date import java.util.GregorianCalendar val designerNewsSource = DesignerNewsSearchSourceItem( "query", true ) val designerNewsSourceUiModel = SourceUiModel( id = "id", key = designerNewsSource.key, name = designerNewsSource.name, active = designerNewsSource.active, iconRes = designerNewsSource.iconRes, isSwipeDismissable = designerNewsSource.isSwipeDismissable, onSourceClicked = {}, onSourceDismissed = {} ) val dribbbleSource = DribbbleSourceItem("dribbble", true) val post = Post( id = 345L, title = "Plaid", url = "www.plaid.amazing", tagline = "amazing", discussionUrl = "www.disc.plaid", redirectUrl = "www.d.plaid", commentsCount = 5, votesCount = 100 ) val player = User( id = 1L, name = "Nick Butcher", username = "nickbutcher", avatarUrl = "www.prettyplaid.nb" ) val shot = Shot( id = 1L, title = "Foo Nick", page = 0, description = "", images = Images(), user = player ).apply { dataSource = dribbbleSource.key } const val userId = 5L const val storyId = 1345L val createdDate: Date = GregorianCalendar(2018, 1, 13).time val commentIds = listOf(11L, 12L) val storyLinks = StoryLinks( user = userId, comments = commentIds, upvotes = emptyList(), downvotes = emptyList() ) val story = Story( id = storyId, title = "Plaid 2.0 was released", page = 0, createdAt = createdDate, userId = userId, links = storyLinks ).apply { dataSource = designerNewsSource.key }
apache-2.0
381e4a1ac2f19cdac602e1b5970b7675
27.052083
75
0.71593
3.858166
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/ui/util/CategoryPickerFragment.kt
1
5001
package treehou.se.habit.ui.util import android.app.Activity import android.content.Intent import android.graphics.Color import android.os.Bundle import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.mikepenz.community_material_typeface_library.CommunityMaterial import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.IIcon import treehou.se.habit.R import treehou.se.habit.ui.BaseFragment import treehou.se.habit.util.Util import java.util.* /** * Fragment for picking categories of icons. */ class CategoryPickerFragment : BaseFragment() { private var lstIcons: RecyclerView? = null private var adapter: CategoryAdapter? = null private var container: ViewGroup? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.fragment_icon_picker, container, false) lstIcons = rootView.findViewById<View>(R.id.lst_categories) as RecyclerView val gridLayoutManager = GridLayoutManager(activity, 1) lstIcons!!.layoutManager = gridLayoutManager lstIcons!!.itemAnimator = DefaultItemAnimator() // Hookup list of categories val categoryList = ArrayList<CategoryPicker>() categoryList.add(CategoryPicker(null, getString(R.string.empty), Util.IconCategory.EMPTY)) categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_play, getString(R.string.media), Util.IconCategory.MEDIA)) categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_alarm, getString(R.string.sensor), Util.IconCategory.SENSORS)) categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_power, getString(R.string.command), Util.IconCategory.COMMANDS)) categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_arrow_up, getString(R.string.arrows), Util.IconCategory.ARROWS)) categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_view_module, getString(R.string.all), Util.IconCategory.ALL)) adapter = CategoryAdapter(categoryList) lstIcons!!.adapter = adapter this.container = container return rootView } private inner class CategoryPicker(var icon: IIcon?, var category: String?, var id: Util.IconCategory?) /** * Adapter showing category of icons. */ private inner class CategoryAdapter(val categories: MutableList<CategoryPicker>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { internal inner class CategoryHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var imgIcon: ImageView = itemView.findViewById<View>(R.id.img_menu) as ImageView var lblCategory: TextView = itemView.findViewById<View>(R.id.lbl_label) as TextView } fun add(category: CategoryPicker) { categories.add(category) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) val itemView = inflater.inflate(R.layout.item_category, parent, false) return CategoryHolder(itemView) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val item = categories[position] val catHolder = holder as CategoryHolder catHolder.lblCategory.text = item.category if (item.id != Util.IconCategory.EMPTY) { val drawable = IconicsDrawable(activity!!, item.icon).color(Color.BLACK).sizeDp(60) catHolder.imgIcon.setImageDrawable(drawable) holder.itemView.setOnClickListener { v -> activity!!.supportFragmentManager.beginTransaction() .replace(container!!.id, IconPickerFragment.newInstance(item.id!!)) .addToBackStack(null) .commit() } } else { catHolder.imgIcon.setImageDrawable(null) holder.itemView.setOnClickListener { v -> val intent = Intent() intent.putExtra(IconPickerFragment.RESULT_ICON, "") activity!!.setResult(Activity.RESULT_OK, intent) activity!!.finish() } } } override fun getItemCount(): Int { return categories.size } } companion object { fun newInstance(): CategoryPickerFragment { val fragment = CategoryPickerFragment() val args = Bundle() fragment.arguments = args return fragment } } }
epl-1.0
33b8d3687eb442d34b4be5adab93093a
39.008
136
0.678664
5.036254
false
false
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/ProjectDetailsFragment.kt
2
15190
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2021 University of California * * BOINC 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 3 of the License, or (at your option) any later version. * * BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc import android.app.Activity import android.app.Dialog import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Point import android.os.Build import android.os.Bundle import android.os.RemoteException import android.text.SpannableString import android.text.style.UnderlineSpan import android.view.* import android.widget.Button import android.widget.TextView import androidx.core.graphics.scale import androidx.core.net.toUri import androidx.core.view.MenuHost import androidx.core.view.MenuProvider import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import edu.berkeley.boinc.databinding.ProjectDetailsLayoutBinding import edu.berkeley.boinc.databinding.ProjectDetailsSlideshowImageLayoutBinding import edu.berkeley.boinc.rpc.ImageWrapper import edu.berkeley.boinc.rpc.Project import edu.berkeley.boinc.rpc.ProjectInfo import edu.berkeley.boinc.rpc.RpcClient import edu.berkeley.boinc.utils.Logging import java.util.* import kotlinx.coroutines.* class ProjectDetailsFragment : Fragment() { private var url: String = "" // might be null for projects added via manual URL attach private var projectInfo: ProjectInfo? = null private var project: Project? = null private var slideshowImages: List<ImageWrapper> = ArrayList() private var _binding: ProjectDetailsLayoutBinding? = null private val binding get() = _binding!! // display dimensions private var width = 0 private var height = 0 private var retryLayout = true private val currentProjectData: Unit get() { try { project = BOINCActivity.monitor!!.projects.firstOrNull { it.masterURL == url } projectInfo = BOINCActivity.monitor!!.getProjectInfoAsync(url).await() } catch (e: Exception) { Logging.logError(Logging.Category.GUI_VIEW, "ProjectDetailsFragment getCurrentProjectData could not" + " retrieve project list") } if (project == null) { Logging.logWarning(Logging.Category.GUI_VIEW, "ProjectDetailsFragment getCurrentProjectData could not find project for URL: $url") } if (projectInfo == null) { Logging.logDebug(Logging.Category.GUI_VIEW, "ProjectDetailsFragment getCurrentProjectData could not find project" + " attach list for URL: $url") } } // BroadcastReceiver event is used to update the UI with updated information from // the client. This is generally called once a second. // private val ifcsc = IntentFilter("edu.berkeley.boinc.clientstatuschange") private val mClientStatusChangeRec: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { currentProjectData if (retryLayout) { populateLayout() } else { updateChangingItems() } } } override fun onCreate(savedInstanceState: Bundle?) { // get data url = requireArguments().getString("url") ?: "" currentProjectData super.onCreate(savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val menuHost: MenuHost = requireActivity() // enables fragment specific menu // add the project menu to the fragment menuHost.addMenuProvider(object: MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.project_details_menu, menu) } override fun onPrepareMenu(menu: Menu) { super.onPrepareMenu(menu) if (project == null) { return } // no new tasks, adapt based on status val nnt = menu.findItem(R.id.projects_control_nonewtasks) if (project!!.doNotRequestMoreWork) { nnt.setTitle(R.string.projects_control_allownewtasks) } else { nnt.setTitle(R.string.projects_control_nonewtasks) } // project suspension, adapt based on status val suspend = menu.findItem(R.id.projects_control_suspend) if (project!!.suspendedViaGUI) { suspend.setTitle(R.string.projects_control_resume) } else { suspend.setTitle(R.string.projects_control_suspend) } // detach, only show when project not managed val remove = menu.findItem(R.id.projects_control_remove) if (project!!.attachedViaAcctMgr) { remove.isVisible = false } } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { lifecycleScope.launch { when (menuItem.itemId) { R.id.projects_control_update -> performProjectOperation(RpcClient.PROJECT_UPDATE) R.id.projects_control_suspend -> if (project!!.suspendedViaGUI) { performProjectOperation(RpcClient.PROJECT_RESUME) } else { performProjectOperation(RpcClient.PROJECT_SUSPEND) } R.id.projects_control_nonewtasks -> if (project!!.doNotRequestMoreWork) { performProjectOperation(RpcClient.PROJECT_ANW) } else { performProjectOperation(RpcClient.PROJECT_NNW) } R.id.projects_control_reset -> showConfirmationDialog(RpcClient.PROJECT_RESET) R.id.projects_control_remove -> showConfirmationDialog(RpcClient.PROJECT_DETACH) else -> { Logging.logError(Logging.Category.USER_ACTION, "ProjectDetailsFragment onOptionsItemSelected: could not match ID") } } } return true } }, viewLifecycleOwner, Lifecycle.State.RESUMED) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { Logging.logVerbose(Logging.Category.GUI_VIEW, "ProjectDetailsFragment onCreateView") // Inflate the layout for this fragment _binding = ProjectDetailsLayoutBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onAttach(context: Context) { if (context is Activity) { val size = Point() if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { @Suppress("DEPRECATION") context.windowManager.defaultDisplay.getSize(size) } else { val r = context.windowManager.currentWindowMetrics.bounds size.x = r.width() size.y = r.height() } width = size.x height = size.y } super.onAttach(context) } override fun onPause() { activity?.unregisterReceiver(mClientStatusChangeRec) super.onPause() } override fun onResume() { super.onResume() activity?.registerReceiver(mClientStatusChangeRec, ifcsc) } private fun showConfirmationDialog(operation: Int) { val dialog = Dialog(requireActivity()).apply { requestWindowFeature(Window.FEATURE_NO_TITLE) setContentView(R.layout.dialog_confirm) } val confirm = dialog.findViewById<Button>(R.id.confirm) val tvTitle = dialog.findViewById<TextView>(R.id.title) val tvMessage = dialog.findViewById<TextView>(R.id.message) // operation-dependent texts if (operation == RpcClient.PROJECT_DETACH) { val removeStr = getString(R.string.projects_confirm_detach_confirm) tvTitle.text = getString(R.string.projects_confirm_title, removeStr) tvMessage.text = getString(R.string.projects_confirm_message, removeStr.lowercase(Locale.ROOT), project!!.projectName + " " + getString(R.string.projects_confirm_detach_message)) confirm.text = removeStr } else if (operation == RpcClient.PROJECT_RESET) { val resetStr = getString(R.string.projects_confirm_reset_confirm) tvTitle.text = getString(R.string.projects_confirm_title, resetStr) tvMessage.text = getString(R.string.projects_confirm_message, resetStr.lowercase(Locale.ROOT), project!!.projectName) confirm.text = resetStr } confirm.setOnClickListener { lifecycleScope.launch { performProjectOperation(operation) } dialog.dismiss() } dialog.findViewById<Button>(R.id.cancel).apply { setOnClickListener { dialog.dismiss() } } dialog.show() } private fun populateLayout() { if (project == null) { retryLayout = true return // if data not available yet, return. Frequently retry with onReceive } retryLayout = false updateChangingItems() // set website val content = SpannableString(project!!.masterURL) content.setSpan(UnderlineSpan(), 0, content.length, 0) binding.projectUrl.text = content binding.projectUrl.setOnClickListener { startActivity(Intent(Intent.ACTION_VIEW, project!!.masterURL.toUri())) } // set general area if (projectInfo?.generalArea != null) { binding.generalArea.text = projectInfo!!.generalArea } else { binding.generalAreaWrapper.visibility = View.GONE } // set specific area if (projectInfo?.specificArea != null) { binding.specificArea.text = projectInfo!!.specificArea } else { binding.specificAreaWrapper.visibility = View.GONE } // set description if (projectInfo?.description != null) { binding.description.text = projectInfo!!.description } else { binding.descriptionWrapper.visibility = View.GONE } // set home if (projectInfo?.home != null) { binding.basedAt.text = projectInfo!!.home } else { binding.basedAtWrapper.visibility = View.GONE } // load slideshow lifecycleScope.launch { updateSlideshowImages() } } private fun updateChangingItems() { try { // status val newStatus = BOINCActivity.monitor!!.getProjectStatus(project!!.masterURL) if (newStatus.isNotEmpty()) { binding.statusWrapper.visibility = View.VISIBLE binding.statusText.text = newStatus } else { binding.statusWrapper.visibility = View.GONE } } catch (e: Exception) { Logging.logException(Logging.Category.GUI_VIEW, "ProjectDetailsFragment.updateChangingItems error: ", e) } } // executes project operations in new thread private suspend fun performProjectOperation(operation: Int) = coroutineScope { Logging.logVerbose(Logging.Category.USER_ACTION, "performProjectOperation()") val success = async { return@async try { BOINCActivity.monitor!!.projectOp(operation, project!!.masterURL) } catch (e: Exception) { Logging.logException(Logging.Category.USER_ACTION, "performProjectOperation() error: ", e) false } }.await() if (success) { try { BOINCActivity.monitor!!.forceRefresh() } catch (e: RemoteException) { Logging.logException(Logging.Category.USER_ACTION, "performProjectOperation() error: ", e) } } else { Logging.logError(Logging.Category.USER_ACTION, "performProjectOperation() failed.") } } private suspend fun updateSlideshowImages() = coroutineScope { Logging.logDebug(Logging.Category.GUI_VIEW, "UpdateSlideshowImagesAsync updating images in new thread. project:" + " $project!!.masterURL") val success = withContext(Dispatchers.Default) { slideshowImages = try { BOINCActivity.monitor!!.getSlideshowForProject(project!!.masterURL) } catch (e: Exception) { Logging.logError(Logging.Category.GUI_VIEW, "updateSlideshowImages: Could not load data, " + "clientStatus not initialized.") return@withContext false } return@withContext slideshowImages.isNotEmpty() } Logging.logDebug(Logging.Category.GUI_VIEW, "UpdateSlideshowImagesAsync success: $success, images: ${slideshowImages.size}") if (success && slideshowImages.isNotEmpty()) { binding.slideshowLoading.visibility = View.GONE for (image in slideshowImages) { val slideshowBinding = ProjectDetailsSlideshowImageLayoutBinding.inflate(layoutInflater) var bitmap = image.image!! if (scaleImages(bitmap.height, bitmap.width)) { bitmap = bitmap.scale(bitmap.width * 2, bitmap.height * 2, filter = false) } slideshowBinding.slideshowImage.setImageBitmap(bitmap) binding.slideshowHook.addView(slideshowBinding.slideshowImage) } } else { binding.slideshowWrapper.visibility = View.GONE } } private fun scaleImages(imageHeight: Int, imageWidth: Int) = height >= imageHeight * 2 && width >= imageWidth * 2 }
lgpl-3.0
22b271d2fa24bf836277863b0aff3409
38.557292
142
0.613232
5.178998
false
false
false
false
andretortolano/GithubSearch
app/src/main/java/com/example/andretortolano/githubsearch/ui/screens/showuser/ShowUserView.kt
1
2029
package com.example.andretortolano.githubsearch.ui.screens.showuser import android.os.Bundle import android.view.* import com.example.andretortolano.githubsearch.R import com.example.andretortolano.githubsearch.api.github.GithubService import com.example.andretortolano.githubsearch.api.github.responses.User import com.example.andretortolano.githubsearch.ui.screens.BaseFragment import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_user.* class ShowUserView : BaseFragment<ShowUserContract.Presenter>(), ShowUserContract.View { override lateinit var mPresenter: ShowUserContract.Presenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mPresenter = ShowUserPresenter(this, GithubService(), arguments.getString(USER_LOGIN)) } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { super.onCreateOptionsMenu(menu, inflater) menu?.clear() } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?) = inflater!!.inflate(R.layout.fragment_user, container, false)!! override fun showProgress() { progress_view.visibility = View.VISIBLE } override fun hideProgress() { progress_view.visibility = View.GONE } override fun showErrorMessage(message: String) { showToast(message) } override fun showUser(user: User) { user_name.text = user.name Picasso.with(context) .load(user.avatarUrl) .placeholder(R.drawable.harrypotter_cat) .into(user_avatar) } companion object { var USER_LOGIN = "BUNDLE_USER_LOGIN" fun newInstance(login: String): ShowUserView { val fragment: ShowUserView = ShowUserView() val args: Bundle = Bundle() args.putString(USER_LOGIN, login) fragment.arguments = args return fragment } } }
mit
f869f7d1c76c318e2ca85db51e68a24a
31.725806
108
0.694431
4.762911
false
false
false
false
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/decode/internal/DecodeUtilsTest.kt
1
54118
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.decode.internal import android.graphics.Bitmap import android.graphics.Bitmap.Config.ARGB_8888 import android.graphics.BitmapFactory import android.graphics.Rect import android.os.Build.VERSION import android.os.Build.VERSION_CODES import androidx.exifinterface.media.ExifInterface import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.github.panpf.sketch.datasource.AssetDataSource import com.github.panpf.sketch.datasource.DataFrom.LOCAL import com.github.panpf.sketch.datasource.DataFrom.MEMORY import com.github.panpf.sketch.datasource.FileDataSource import com.github.panpf.sketch.datasource.ResourceDataSource import com.github.panpf.sketch.decode.BitmapDecodeResult import com.github.panpf.sketch.decode.ImageInfo import com.github.panpf.sketch.decode.ImageInvalidException import com.github.panpf.sketch.decode.internal.ImageFormat import com.github.panpf.sketch.decode.internal.appliedExifOrientation import com.github.panpf.sketch.decode.internal.appliedResize import com.github.panpf.sketch.decode.internal.calculateSampleSize import com.github.panpf.sketch.decode.internal.calculateSampleSizeForRegion import com.github.panpf.sketch.decode.internal.calculateSampledBitmapSize import com.github.panpf.sketch.decode.internal.calculateSampledBitmapSizeForRegion import com.github.panpf.sketch.decode.internal.computeSizeMultiplier import com.github.panpf.sketch.decode.internal.createInSampledTransformed import com.github.panpf.sketch.decode.internal.createSubsamplingTransformed import com.github.panpf.sketch.decode.internal.decodeBitmap import com.github.panpf.sketch.decode.internal.decodeRegionBitmap import com.github.panpf.sketch.decode.internal.getExifOrientationTransformed import com.github.panpf.sketch.decode.internal.isAnimatedHeif import com.github.panpf.sketch.decode.internal.isAnimatedWebP import com.github.panpf.sketch.decode.internal.isGif import com.github.panpf.sketch.decode.internal.isHeif import com.github.panpf.sketch.decode.internal.isInBitmapError import com.github.panpf.sketch.decode.internal.isSrcRectError import com.github.panpf.sketch.decode.internal.isSupportInBitmap import com.github.panpf.sketch.decode.internal.isSupportInBitmapForRegion import com.github.panpf.sketch.decode.internal.isWebP import com.github.panpf.sketch.decode.internal.limitedSampleSizeByMaxBitmapSize import com.github.panpf.sketch.decode.internal.limitedSampleSizeByMaxBitmapSizeForRegion import com.github.panpf.sketch.decode.internal.maxBitmapSize import com.github.panpf.sketch.decode.internal.readImageInfoWithBitmapFactory import com.github.panpf.sketch.decode.internal.readImageInfoWithBitmapFactoryOrNull import com.github.panpf.sketch.decode.internal.readImageInfoWithBitmapFactoryOrThrow import com.github.panpf.sketch.decode.internal.realDecode import com.github.panpf.sketch.decode.internal.sizeString import com.github.panpf.sketch.decode.internal.supportBitmapRegionDecoder import com.github.panpf.sketch.fetch.newAssetUri import com.github.panpf.sketch.fetch.newResourceUri import com.github.panpf.sketch.request.LoadRequest import com.github.panpf.sketch.resize.Precision.EXACTLY import com.github.panpf.sketch.resize.Precision.LESS_PIXELS import com.github.panpf.sketch.resize.Precision.SAME_ASPECT_RATIO import com.github.panpf.sketch.resize.Scale.CENTER_CROP import com.github.panpf.sketch.sketch import com.github.panpf.sketch.test.R import com.github.panpf.sketch.test.utils.ExifOrientationTestFileHelper import com.github.panpf.sketch.test.utils.TestAssets import com.github.panpf.sketch.test.utils.corners import com.github.panpf.sketch.test.utils.getTestContext import com.github.panpf.sketch.test.utils.getTestContextAndNewSketch import com.github.panpf.sketch.test.utils.size import com.github.panpf.sketch.test.utils.toRequestContext import com.github.panpf.sketch.util.Bytes import com.github.panpf.sketch.util.Size import com.github.panpf.tools4j.test.ktx.assertThrow import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import java.io.IOException @RunWith(AndroidJUnit4::class) class DecodeUtilsTest { @Test fun testCalculateSampledBitmapSize() { Assert.assertEquals( Size(503, 101), calculateSampledBitmapSize( imageSize = Size(1005, 201), sampleSize = 2 ) ) Assert.assertEquals( Size(503, 101), calculateSampledBitmapSize( imageSize = Size(1005, 201), sampleSize = 2, mimeType = "image/jpeg" ) ) Assert.assertEquals( Size(502, 100), calculateSampledBitmapSize( imageSize = Size(1005, 201), sampleSize = 2, mimeType = "image/png" ) ) Assert.assertEquals( Size(503, 101), calculateSampledBitmapSize( imageSize = Size(1005, 201), sampleSize = 2, mimeType = "image/bmp" ) ) Assert.assertEquals( Size(503, 101), calculateSampledBitmapSize( imageSize = Size(1005, 201), sampleSize = 2, mimeType = "image/gif" ) ) Assert.assertEquals( Size(503, 101), calculateSampledBitmapSize( imageSize = Size(1005, 201), sampleSize = 2, mimeType = "image/webp" ) ) Assert.assertEquals( Size(503, 101), calculateSampledBitmapSize( imageSize = Size(1005, 201), sampleSize = 2, mimeType = "image/heic" ) ) Assert.assertEquals( Size(503, 101), calculateSampledBitmapSize( imageSize = Size(1005, 201), sampleSize = 2, mimeType = "image/heif" ) ) } @Test fun testCalculateSampledBitmapSizeForRegion() { Assert.assertEquals( if (VERSION.SDK_INT >= VERSION_CODES.N) Size(503, 101) else Size(502, 100), calculateSampledBitmapSizeForRegion( regionSize = Size(1005, 201), sampleSize = 2, mimeType = "image/jpeg", imageSize = Size(1005, 201) ) ) Assert.assertEquals( Size(502, 100), calculateSampledBitmapSizeForRegion( regionSize = Size(1005, 201), sampleSize = 2, mimeType = "image/png", imageSize = Size(1005, 201) ) ) Assert.assertEquals( Size(288, 100), calculateSampledBitmapSizeForRegion( regionSize = Size(577, 201), sampleSize = 2, mimeType = "image/jpeg", imageSize = Size(1005, 201) ) ) Assert.assertEquals( Size(502, 55), calculateSampledBitmapSizeForRegion( regionSize = Size(1005, 111), sampleSize = 2, mimeType = "image/jpeg", imageSize = Size(1005, 201) ) ) Assert.assertEquals( Size(288, 55), calculateSampledBitmapSizeForRegion( regionSize = Size(577, 111), sampleSize = 2, mimeType = "image/jpeg", imageSize = Size(1005, 201) ) ) Assert.assertEquals( Size(288, 55), calculateSampledBitmapSizeForRegion( regionSize = Size(577, 111), sampleSize = 2, mimeType = "image/jpeg", ) ) } @Test fun testCalculateSampleSize() { Assert.assertEquals( 1, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(1006, 202), ) ) Assert.assertEquals( 1, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(1005, 201), ) ) Assert.assertEquals( 2, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(1004, 200), ) ) Assert.assertEquals( 2, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(503, 101), ) ) Assert.assertEquals( 4, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(502, 100), ) ) Assert.assertEquals( 4, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(252, 51), ) ) Assert.assertEquals( 8, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(251, 50), ) ) Assert.assertEquals( 4, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(502, 100), mimeType = "image/jpeg" ) ) Assert.assertEquals( 2, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(502, 100), mimeType = "image/png" ) ) Assert.assertEquals( 4, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(502, 100), mimeType = "image/bmp" ) ) Assert.assertEquals( 4, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(502, 100), mimeType = "image/webp" ) ) Assert.assertEquals( 4, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(502, 100), mimeType = "image/gif" ) ) Assert.assertEquals( 4, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(502, 100), mimeType = "image/heic" ) ) Assert.assertEquals( 4, calculateSampleSize( imageSize = Size(1005, 201), targetSize = Size(502, 100), mimeType = "image/heif" ) ) } @Test fun testCalculateSampleSizeForRegion() { Assert.assertEquals( 1, calculateSampleSizeForRegion( regionSize = Size(1005, 201), targetSize = Size(1006, 202), ) ) Assert.assertEquals( 1, calculateSampleSizeForRegion( regionSize = Size(1005, 201), targetSize = Size(1005, 201), ) ) Assert.assertEquals( 2, calculateSampleSizeForRegion( regionSize = Size(1005, 201), targetSize = Size(1004, 200), imageSize = Size(2005, 301), ) ) Assert.assertEquals( 2, calculateSampleSizeForRegion( regionSize = Size(1005, 201), targetSize = Size(502, 100), imageSize = Size(2005, 301), ) ) Assert.assertEquals( 4, calculateSampleSizeForRegion( regionSize = Size(1005, 201), targetSize = Size(501, 99), imageSize = Size(2005, 301), ) ) Assert.assertEquals( 4, calculateSampleSizeForRegion( regionSize = Size(1005, 201), targetSize = Size(251, 50), imageSize = Size(2005, 301), ) ) Assert.assertEquals( 8, calculateSampleSizeForRegion( regionSize = Size(1005, 201), targetSize = Size(250, 49), imageSize = Size(2005, 301), ) ) Assert.assertEquals( if (VERSION.SDK_INT >= VERSION_CODES.N) 4 else 2, calculateSampleSizeForRegion( regionSize = Size(1005, 201), targetSize = Size(502, 100), imageSize = Size(1005, 201), ) ) Assert.assertEquals( 2, calculateSampleSizeForRegion( regionSize = Size(1005, 201), targetSize = Size(502, 100), mimeType = "image/png", imageSize = Size(1005, 201), ) ) } @Test fun testLimitedSampleSizeByMaxBitmapSize() { val maxSize = maxBitmapSize.width Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSize(1, Size(maxSize - 1, maxSize)) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSize(1, Size(maxSize, maxSize - 1)) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSize(1, Size(maxSize - 1, maxSize - 1)) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSize(1, Size(maxSize, maxSize)) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSize(1, Size(maxSize + 1, maxSize)) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSize(1, Size(maxSize, maxSize + 1)) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSize(1, Size(maxSize + 1, maxSize + 1)) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSize(0, Size(maxSize, maxSize)) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSize(-1, Size(maxSize, maxSize)) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSize(-1, Size(maxSize + 1, maxSize + 1)) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSize(0, Size(maxSize + 1, maxSize + 1)) ) } @Test fun testLimitedSampleSizeByMaxBitmapSizeForRegion() { val maxSize = maxBitmapSize.width Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize - 1, maxSize), 1) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize - 1), 1) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSizeForRegion( Size(maxSize - 1, maxSize - 1), 1 ) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize), 1) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize + 1, maxSize), 1) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize + 1), 1) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSizeForRegion( Size(maxSize + 1, maxSize + 1), 1 ) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize), 0) ) Assert.assertEquals( 1, limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize), -1) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSizeForRegion( Size(maxSize + 1, maxSize + 1), -1 ) ) Assert.assertEquals( 2, limitedSampleSizeByMaxBitmapSizeForRegion( Size(maxSize + 1, maxSize + 1), 0 ) ) } @Test fun testRealDecode() { val context = InstrumentationRegistry.getInstrumentation().context val sketch = context.sketch val hasExifFile = ExifOrientationTestFileHelper(context, "sample.jpeg") .files().find { it.exifOrientation == ExifInterface.ORIENTATION_ROTATE_90 }!! @Suppress("ComplexRedundantLet") val result1 = LoadRequest(context, hasExifFile.file.path) { resizeSize(3000, 3000) resizePrecision(LESS_PIXELS) }.let { realDecode( it.toRequestContext(), LOCAL, ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation), { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! } ) { rect, config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!! } }.apply { Assert.assertEquals(imageInfo.size, bitmap.size) Assert.assertEquals( ImageInfo( 1936, 1291, "image/jpeg", ExifInterface.ORIENTATION_ROTATE_90 ), imageInfo ) Assert.assertEquals(LOCAL, dataFrom) Assert.assertNull(transformedList) } LoadRequest(context, hasExifFile.file.path) { resizeSize(3000, 3000) resizePrecision(LESS_PIXELS) ignoreExifOrientation(true) }.let { realDecode( requestContext = it.toRequestContext(), dataFrom = LOCAL, imageInfo = ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation), decodeFull = { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! } ) { rect, config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!! } }.apply { Assert.assertEquals(imageInfo.size, bitmap.size) Assert.assertEquals( ImageInfo( 1936, 1291, "image/jpeg", ExifInterface.ORIENTATION_ROTATE_90 ), imageInfo ) Assert.assertEquals(LOCAL, dataFrom) Assert.assertNull(transformedList) Assert.assertEquals(result1.bitmap.corners(), bitmap.corners()) } val result3 = LoadRequest(context, hasExifFile.file.path).newLoadRequest { resizeSize(100, 200) resizePrecision(EXACTLY) }.let { realDecode( requestContext = it.toRequestContext(), dataFrom = LOCAL, imageInfo = ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation), decodeFull = { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! } ) { rect, config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!! } }.apply { Assert.assertEquals(Size(121, 60), bitmap.size) Assert.assertEquals( ImageInfo( 1936, 1291, "image/jpeg", ExifInterface.ORIENTATION_ROTATE_90 ), imageInfo ) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals( listOf( createInSampledTransformed(16), createSubsamplingTransformed(Rect(0, 161, 1936, 1129)) ), transformedList ) } LoadRequest(context, hasExifFile.file.path).newLoadRequest { resizeSize(100, 200) resizePrecision(EXACTLY) }.let { realDecode( requestContext = it.toRequestContext(), dataFrom = LOCAL, imageInfo = ImageInfo(1936, 1291, "image/jpeg", 0), decodeFull = { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! } ) { rect, config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!! } }.apply { Assert.assertEquals(Size(80, 161), bitmap.size) Assert.assertEquals(ImageInfo(1936, 1291, "image/jpeg", 0), imageInfo) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals( listOf( createInSampledTransformed(8), createSubsamplingTransformed(Rect(645, 0, 1290, 1291)) ), transformedList ) Assert.assertNotEquals(result3.bitmap.corners(), bitmap.corners()) } val result5 = LoadRequest(context, hasExifFile.file.path).newLoadRequest { resizeSize(100, 200) resizePrecision(SAME_ASPECT_RATIO) }.let { realDecode( requestContext = it.toRequestContext(), dataFrom = LOCAL, imageInfo = ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation), decodeFull = { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! } ) { rect, config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!! } }.apply { Assert.assertEquals(Size(121, 60), bitmap.size) Assert.assertEquals( ImageInfo( 1936, 1291, "image/jpeg", ExifInterface.ORIENTATION_ROTATE_90 ), imageInfo ) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals( listOf( createInSampledTransformed(16), createSubsamplingTransformed(Rect(0, 161, 1936, 1129)) ), transformedList ) } LoadRequest(context, hasExifFile.file.path).newLoadRequest { resizeSize(100, 200) resizePrecision(SAME_ASPECT_RATIO) }.let { realDecode( requestContext = it.toRequestContext(), dataFrom = LOCAL, imageInfo = ImageInfo(1936, 1291, "image/jpeg", 0), decodeFull = { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! } ) { rect, config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!! } }.apply { Assert.assertEquals(Size(80, 161), bitmap.size) Assert.assertEquals(ImageInfo(1936, 1291, "image/jpeg", 0), imageInfo) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals( listOf( createInSampledTransformed(8), createSubsamplingTransformed(Rect(645, 0, 1290, 1291)) ), transformedList ) Assert.assertNotEquals(result5.bitmap.corners(), bitmap.corners()) } val result7 = LoadRequest(context, hasExifFile.file.path).newLoadRequest { resizeSize(100, 200) resizePrecision(LESS_PIXELS) }.let { realDecode( requestContext = it.toRequestContext(), dataFrom = LOCAL, imageInfo = ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation), decodeFull = { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! } ) { rect, config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!! } }.apply { Assert.assertEquals(Size(121, 81), bitmap.size) Assert.assertEquals( ImageInfo( 1936, 1291, "image/jpeg", ExifInterface.ORIENTATION_ROTATE_90 ), imageInfo ) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals(listOf(createInSampledTransformed(16)), transformedList) } LoadRequest(context, hasExifFile.file.path).newLoadRequest { resizeSize(100, 200) resizePrecision(LESS_PIXELS) }.let { realDecode( requestContext = it.toRequestContext(), dataFrom = LOCAL, imageInfo = ImageInfo(1936, 1291, "image/jpeg", 0), decodeFull = { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! } ) { rect, config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!! } }.apply { Assert.assertEquals(Size(121, 81), bitmap.size) Assert.assertEquals(ImageInfo(1936, 1291, "image/jpeg", 0), imageInfo) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals(listOf(createInSampledTransformed(16)), transformedList) Assert.assertEquals(result7.bitmap.corners(), bitmap.corners()) } val result9 = LoadRequest(context, newAssetUri("sample.bmp")) { resizeSize(100, 200) resizePrecision(EXACTLY) }.let { realDecode( requestContext = it.toRequestContext(), dataFrom = LOCAL, imageInfo = ImageInfo(700, 1012, "image/bmp", 0), decodeFull = { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! }, decodeRegion = null ) }.apply { Assert.assertEquals(Size(87, 126), bitmap.size) Assert.assertEquals(ImageInfo(700, 1012, "image/bmp", 0), imageInfo) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals(listOf(createInSampledTransformed(8)), transformedList) } LoadRequest(context, newAssetUri("sample.bmp")).newLoadRequest { resizeSize(100, 200) resizePrecision(EXACTLY) ignoreExifOrientation(true) }.let { realDecode( requestContext = it.toRequestContext(), dataFrom = LOCAL, imageInfo = ImageInfo(700, 1012, "image/jpeg", 0), decodeFull = { config -> runBlocking { sketch.components.newFetcher(it).fetch() }.dataSource.decodeBitmap(config.toBitmapOptions())!! }, decodeRegion = null ) }.apply { Assert.assertEquals(Size(87, 126), bitmap.size) Assert.assertEquals(ImageInfo(700, 1012, "image/jpeg", 0), imageInfo) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals(listOf(createInSampledTransformed(8)), transformedList) Assert.assertEquals(result9.bitmap.corners(), bitmap.corners()) } } @Test fun testAppliedExifOrientation() { val (context, sketch) = getTestContextAndNewSketch() val request = LoadRequest(context, TestAssets.SAMPLE_JPEG_URI) val hasExifFile = ExifOrientationTestFileHelper(context, "sample.jpeg") .files().find { it.exifOrientation == ExifInterface.ORIENTATION_ROTATE_90 }!! val bitmap = BitmapFactory.decodeFile(hasExifFile.file.path) val result = BitmapDecodeResult( bitmap = bitmap, imageInfo = ImageInfo( width = bitmap.width, height = bitmap.height, mimeType = "image/jpeg", exifOrientation = hasExifFile.exifOrientation ), dataFrom = LOCAL, transformedList = null, extras = null, ) val resultCorners = result.bitmap.corners() Assert.assertNull(result.transformedList?.getExifOrientationTransformed()) result.appliedExifOrientation( sketch, request.toRequestContext() ).apply { Assert.assertNotSame(result, this) Assert.assertNotSame(result.bitmap, this.bitmap) Assert.assertEquals(Size(result.bitmap.height, result.bitmap.width), this.bitmap.size) Assert.assertEquals( Size(result.imageInfo.height, result.imageInfo.width), this.imageInfo.size ) Assert.assertNotEquals(resultCorners, this.bitmap.corners()) Assert.assertNotNull(this.transformedList?.getExifOrientationTransformed()) } val noExifOrientationResult = result.newResult( imageInfo = result.imageInfo.newImageInfo(exifOrientation = 0) ) noExifOrientationResult.appliedExifOrientation( sketch, request.toRequestContext() ).apply { Assert.assertSame(noExifOrientationResult, this) } } @Test fun testAppliedResize() { val (context, sketch) = getTestContextAndNewSketch() var request = LoadRequest(context, TestAssets.SAMPLE_JPEG_URI) val newResult: () -> BitmapDecodeResult = { BitmapDecodeResult( bitmap = Bitmap.createBitmap(80, 50, ARGB_8888), imageInfo = ImageInfo(80, 50, "image/png", 0), dataFrom = MEMORY, transformedList = null, extras = null, ) } /* * LESS_PIXELS */ // small request = request.newLoadRequest { resize(40, 20, LESS_PIXELS, CENTER_CROP) } var result = newResult() result.appliedResize(sketch, request.toRequestContext()).apply { Assert.assertTrue(this !== result) Assert.assertEquals("20x13", this.bitmap.sizeString) } // big request = request.newLoadRequest { resize(50, 150, LESS_PIXELS) } result = newResult() result.appliedResize(sketch, request.toRequestContext()).apply { Assert.assertTrue(this === result) } /* * SAME_ASPECT_RATIO */ // small request = request.newLoadRequest { resize(40, 20, SAME_ASPECT_RATIO) } result = newResult() result.appliedResize(sketch, request.toRequestContext()).apply { Assert.assertTrue(this !== result) Assert.assertEquals("40x20", this.bitmap.sizeString) } // big request = request.newLoadRequest { resize(50, 150, SAME_ASPECT_RATIO) } result = newResult() result.appliedResize(sketch, request.toRequestContext()).apply { Assert.assertTrue(this !== result) Assert.assertEquals("17x50", this.bitmap.sizeString) } /* * EXACTLY */ // small request = request.newLoadRequest { resize(40, 20, EXACTLY) } result = newResult() result.appliedResize(sketch, request.toRequestContext()).apply { Assert.assertTrue(this !== result) Assert.assertEquals("40x20", this.bitmap.sizeString) } // big request = request.newLoadRequest { resize(50, 150, EXACTLY) } result = newResult() result.appliedResize(sketch, request.toRequestContext()).apply { Assert.assertTrue(this !== result) Assert.assertEquals("50x150", this.bitmap.sizeString) } } @Test fun testComputeSizeMultiplier() { Assert.assertEquals(0.2, computeSizeMultiplier(1000, 600, 200, 400, true), 0.1) Assert.assertEquals(0.6, computeSizeMultiplier(1000, 600, 200, 400, false), 0.1) Assert.assertEquals(0.3, computeSizeMultiplier(1000, 600, 400, 200, true), 0.1) Assert.assertEquals(0.4, computeSizeMultiplier(1000, 600, 400, 200, false), 0.1) Assert.assertEquals(0.6, computeSizeMultiplier(1000, 600, 2000, 400, true), 0.1) Assert.assertEquals(2.0, computeSizeMultiplier(1000, 600, 2000, 400, false), 0.1) Assert.assertEquals(0.4, computeSizeMultiplier(1000, 600, 400, 2000, true), 0.1) Assert.assertEquals(3.3, computeSizeMultiplier(1000, 600, 400, 2000, false), 0.1) Assert.assertEquals(2.0, computeSizeMultiplier(1000, 600, 2000, 4000, true), 0.1) Assert.assertEquals(6.6, computeSizeMultiplier(1000, 600, 2000, 4000, false), 0.1) Assert.assertEquals(3.3, computeSizeMultiplier(1000, 600, 4000, 2000, true), 0.1) Assert.assertEquals(4.0, computeSizeMultiplier(1000, 600, 4000, 2000, false), 0.1) } @Test fun testReadImageInfoWithBitmapFactory() { val (context, sketch) = getTestContextAndNewSketch() AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg") .readImageInfoWithBitmapFactory().apply { Assert.assertEquals(1291, width) Assert.assertEquals(1936, height) Assert.assertEquals("image/jpeg", mimeType) Assert.assertEquals(ExifInterface.ORIENTATION_NORMAL, exifOrientation) } AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp") .readImageInfoWithBitmapFactory().apply { Assert.assertEquals(1080, width) Assert.assertEquals(1344, height) if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { Assert.assertEquals("image/webp", mimeType) } else { Assert.assertEquals("", mimeType) } Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation) } ResourceDataSource( sketch, LoadRequest(context, newResourceUri(R.xml.network_security_config)), packageName = context.packageName, context.resources, R.xml.network_security_config ).readImageInfoWithBitmapFactory().apply { Assert.assertEquals(-1, width) Assert.assertEquals(-1, height) Assert.assertEquals("", mimeType) Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation) } ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach { FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readImageInfoWithBitmapFactory().apply { Assert.assertEquals(it.exifOrientation, exifOrientation) } FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readImageInfoWithBitmapFactory(true).apply { Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation) } } } @Test fun testReadImageInfoWithBitmapFactoryOrThrow() { val (context, sketch) = getTestContextAndNewSketch() AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg") .readImageInfoWithBitmapFactoryOrThrow().apply { Assert.assertEquals(1291, width) Assert.assertEquals(1936, height) Assert.assertEquals("image/jpeg", mimeType) Assert.assertEquals(ExifInterface.ORIENTATION_NORMAL, exifOrientation) } AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp") .readImageInfoWithBitmapFactoryOrThrow().apply { Assert.assertEquals(1080, width) Assert.assertEquals(1344, height) if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { Assert.assertEquals("image/webp", mimeType) } else { Assert.assertEquals("", mimeType) } Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation) } assertThrow(ImageInvalidException::class) { ResourceDataSource( sketch, LoadRequest(context, newResourceUri(R.xml.network_security_config)), packageName = context.packageName, context.resources, R.xml.network_security_config ).readImageInfoWithBitmapFactoryOrThrow() } ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach { FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readImageInfoWithBitmapFactoryOrThrow().apply { Assert.assertEquals(it.exifOrientation, exifOrientation) } FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readImageInfoWithBitmapFactoryOrThrow(true).apply { Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation) } } } @Test fun testReadImageInfoWithBitmapFactoryOrNull() { val (context, sketch) = getTestContextAndNewSketch() AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg") .readImageInfoWithBitmapFactoryOrNull()!!.apply { Assert.assertEquals(1291, width) Assert.assertEquals(1936, height) Assert.assertEquals("image/jpeg", mimeType) Assert.assertEquals(ExifInterface.ORIENTATION_NORMAL, exifOrientation) } AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp") .readImageInfoWithBitmapFactoryOrNull()!!.apply { Assert.assertEquals(1080, width) Assert.assertEquals(1344, height) if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { Assert.assertEquals("image/webp", mimeType) } else { Assert.assertEquals("", mimeType) } Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation) } Assert.assertNull( ResourceDataSource( sketch, LoadRequest(context, newResourceUri(R.xml.network_security_config)), packageName = context.packageName, context.resources, R.xml.network_security_config ).readImageInfoWithBitmapFactoryOrNull() ) ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach { FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readImageInfoWithBitmapFactoryOrNull()!!.apply { Assert.assertEquals(it.exifOrientation, exifOrientation) } FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readImageInfoWithBitmapFactoryOrNull(true)!!.apply { Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation) } } } @Test fun testDecodeBitmap() { val (context, sketch) = getTestContextAndNewSketch() AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg") .decodeBitmap()!!.apply { Assert.assertEquals(1291, width) Assert.assertEquals(1936, height) } AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg") .decodeBitmap(BitmapFactory.Options().apply { inSampleSize = 2 })!! .apply { Assert.assertEquals(646, width) Assert.assertEquals(968, height) } AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp") .decodeBitmap()!!.apply { Assert.assertEquals(1080, width) Assert.assertEquals(1344, height) } Assert.assertNull( ResourceDataSource( sketch, LoadRequest(context, newResourceUri(R.xml.network_security_config)), packageName = context.packageName, context.resources, R.xml.network_security_config ).decodeBitmap() ) } @Test fun testDecodeRegionBitmap() { val (context, sketch) = getTestContextAndNewSketch() AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg") .decodeRegionBitmap(Rect(500, 500, 600, 600))!!.apply { Assert.assertEquals(100, width) Assert.assertEquals(100, height) } AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg") .decodeRegionBitmap( Rect(500, 500, 600, 600), BitmapFactory.Options().apply { inSampleSize = 2 })!! .apply { Assert.assertEquals(50, width) Assert.assertEquals(50, height) } AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp") .decodeRegionBitmap(Rect(500, 500, 700, 700))!!.apply { Assert.assertEquals(200, width) Assert.assertEquals(200, height) } assertThrow(IOException::class) { ResourceDataSource( sketch, LoadRequest(context, newResourceUri(R.xml.network_security_config)), packageName = context.packageName, context.resources, R.xml.network_security_config ).decodeRegionBitmap(Rect(500, 500, 600, 600)) } } @Test fun testSupportBitmapRegionDecoder() { if (VERSION.SDK_INT >= VERSION_CODES.P) { Assert.assertTrue(ImageFormat.HEIC.supportBitmapRegionDecoder()) } else { Assert.assertFalse(ImageFormat.HEIC.supportBitmapRegionDecoder()) } if (VERSION.SDK_INT >= VERSION_CODES.P) { Assert.assertTrue(ImageFormat.HEIF.supportBitmapRegionDecoder()) } else { Assert.assertFalse(ImageFormat.HEIF.supportBitmapRegionDecoder()) } Assert.assertFalse(ImageFormat.BMP.supportBitmapRegionDecoder()) Assert.assertFalse(ImageFormat.GIF.supportBitmapRegionDecoder()) Assert.assertTrue(ImageFormat.JPEG.supportBitmapRegionDecoder()) Assert.assertTrue(ImageFormat.PNG.supportBitmapRegionDecoder()) Assert.assertTrue(ImageFormat.WEBP.supportBitmapRegionDecoder()) } @Test fun testIsInBitmapError() { Assert.assertTrue( isInBitmapError(IllegalArgumentException("Problem decoding into existing bitmap")) ) Assert.assertTrue( isInBitmapError(IllegalArgumentException("bitmap")) ) Assert.assertFalse( isInBitmapError(IllegalArgumentException("Problem decoding")) ) Assert.assertFalse( isInBitmapError(IllegalStateException("Problem decoding into existing bitmap")) ) } @Test fun testIsSrcRectError() { Assert.assertTrue( isSrcRectError(IllegalArgumentException("rectangle is outside the image srcRect")) ) Assert.assertTrue( isSrcRectError(IllegalArgumentException("srcRect")) ) Assert.assertFalse( isSrcRectError(IllegalStateException("rectangle is outside the image srcRect")) ) Assert.assertFalse( isSrcRectError(IllegalArgumentException("")) ) } @Test fun testIsSupportInBitmap() { Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmap("image/jpeg", 1)) Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/jpeg", 2)) Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmap("image/png", 1)) Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/png", 2)) Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/gif", 1)) Assert.assertEquals(VERSION.SDK_INT >= 21, isSupportInBitmap("image/gif", 2)) Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/webp", 1)) Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/webp", 2)) Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/bmp", 1)) Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/bmp", 2)) Assert.assertEquals(false, isSupportInBitmap("image/heic", 1)) Assert.assertEquals(false, isSupportInBitmap("image/heic", 2)) Assert.assertEquals(VERSION.SDK_INT >= 28, isSupportInBitmap("image/heif", 1)) Assert.assertEquals(VERSION.SDK_INT >= 28, isSupportInBitmap("image/heif", 2)) Assert.assertEquals(VERSION.SDK_INT >= 32, isSupportInBitmap("image/svg", 1)) Assert.assertEquals(VERSION.SDK_INT >= 32, isSupportInBitmap("image/svg", 2)) } @Test fun testIsSupportInBitmapForRegion() { Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmapForRegion("image/jpeg")) Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmapForRegion("image/png")) Assert.assertEquals(false, isSupportInBitmapForRegion("image/gif")) Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmapForRegion("image/webp")) Assert.assertEquals(false, isSupportInBitmapForRegion("image/bmp")) Assert.assertEquals(VERSION.SDK_INT >= 28, isSupportInBitmapForRegion("image/heic")) Assert.assertEquals(VERSION.SDK_INT >= 28, isSupportInBitmapForRegion("image/heif")) Assert.assertEquals(VERSION.SDK_INT >= 32, isSupportInBitmapForRegion("image/svg")) } @Test fun testIsWebP() { val context = getTestContext() Bytes(context.assets.open("sample.webp").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertTrue(isWebP()) } Bytes(context.assets.open("sample_anim.webp").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertTrue(isWebP()) } Bytes(context.assets.open("sample.webp").use { ByteArray(1024).apply { it.read(this) }.apply { set(8, 'V'.code.toByte()) } }).apply { Assert.assertFalse(isWebP()) } Bytes(context.assets.open("sample.jpeg").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertFalse(isWebP()) } } @Test fun testIsAnimatedWebP() { val context = getTestContext() Bytes(context.assets.open("sample_anim.webp").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertTrue(isAnimatedWebP()) } Bytes(context.assets.open("sample_anim.webp").use { ByteArray(1024).apply { it.read(this) }.apply { set(12, 'X'.code.toByte()) } }).apply { Assert.assertFalse(isAnimatedWebP()) } Bytes(context.assets.open("sample_anim.webp").use { ByteArray(1024).apply { it.read(this) }.apply { set(16, 0) } }).apply { Assert.assertFalse(isAnimatedWebP()) } Bytes(context.assets.open("sample.webp").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertFalse(isAnimatedWebP()) } Bytes(context.assets.open("sample.jpeg").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertFalse(isAnimatedWebP()) } } @Test fun testIsHeif() { val context = getTestContext() Bytes(context.assets.open("sample.heic").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertTrue(isHeif()) } Bytes(context.assets.open("sample_anim.webp").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertFalse(isHeif()) } Bytes(context.assets.open("sample.jpeg").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertFalse(isHeif()) } } @Test fun testIsAnimatedHeif() { val context = getTestContext() Bytes(context.assets.open("sample_anim.heif").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertTrue(isAnimatedHeif()) } Bytes(context.assets.open("sample_anim.heif").use { ByteArray(1024).apply { it.read(this) }.apply { set(8, 'h'.code.toByte()) set(9, 'e'.code.toByte()) set(10, 'v'.code.toByte()) set(11, 'c'.code.toByte()) } }).apply { Assert.assertTrue(isAnimatedHeif()) } Bytes(context.assets.open("sample_anim.heif").use { ByteArray(1024).apply { it.read(this) }.apply { set(8, 'h'.code.toByte()) set(9, 'e'.code.toByte()) set(10, 'v'.code.toByte()) set(11, 'x'.code.toByte()) } }).apply { Assert.assertTrue(isAnimatedHeif()) } Bytes(context.assets.open("sample.heic").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertFalse(isAnimatedHeif()) } Bytes(context.assets.open("sample_anim.webp").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertFalse(isAnimatedHeif()) } Bytes(context.assets.open("sample.jpeg").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertFalse(isAnimatedHeif()) } } @Test fun testIsGif() { val context = getTestContext() Bytes(context.assets.open("sample_anim.gif").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertTrue(isGif()) } Bytes(context.assets.open("sample_anim.gif").use { ByteArray(1024).apply { it.read(this) }.apply { set(4, '7'.code.toByte()) } }).apply { Assert.assertTrue(isGif()) } Bytes(context.assets.open("sample_anim.webp").use { ByteArray(1024).apply { it.read(this) } }).apply { Assert.assertFalse(isGif()) } } }
apache-2.0
002b579b461b17a489bb668a29bd5056
36.478532
98
0.565062
5.284961
false
true
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/org/mariotaku/ktextension/PromiseArrayCombine.kt
1
1474
package org.mariotaku.ktextension import nl.komponents.kovenant.Deferred import nl.komponents.kovenant.Promise import nl.komponents.kovenant.deferred import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReferenceArray /** * Created by mariotaku on 2016/12/2. */ fun <V, E> combine(promises: List<Promise<V, E>>): Promise<List<V>, E> { return concreteCombine(promises) } fun <V, E> concreteCombine(promises: List<Promise<V, E>>): Promise<List<V>, E> { val deferred = deferred<List<V>, E>() val results = AtomicReferenceArray<V>(promises.size) val successCount = AtomicInteger(promises.size) fun createArray(): List<V> { return (0 until results.length()).map { results[it] } } fun Promise<V, *>.registerSuccess(idx: Int) { success { v -> results.set(idx, v) if (successCount.decrementAndGet() == 0) { deferred.resolve(createArray()) } } } fun <V, E> Deferred<V, E>.registerFail(promises: List<Promise<*, E>>) { val failCount = AtomicInteger(0) promises.forEach { promise -> promise.fail { e -> if (failCount.incrementAndGet() == 1) { this.reject(e) } } } } promises.forEachIndexed { idx, promise -> promise.registerSuccess(idx) } deferred.registerFail(promises) return deferred.promise }
gpl-3.0
c4f3ca81d4bf391c8c9cc69146727c52
27.346154
80
0.613976
4.027322
false
false
false
false
paulofernando/localchat
app/src/main/kotlin/site/paulo/localchat/data/remote/FirebaseHelper.kt
1
16874
/* * Copyright 2017 Paulo Fernando * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package site.paulo.localchat.data.remote import android.location.Location import ch.hsr.geohash.GeoHash import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.ChildEventListener import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.Query import com.google.firebase.database.ServerValue import com.google.firebase.database.ValueEventListener import site.paulo.localchat.data.manager.CurrentUserManager import site.paulo.localchat.ui.utils.Utils import site.paulo.localchat.ui.utils.getFirebaseId import timber.log.Timber import java.util.HashMap import javax.inject.Inject import javax.inject.Singleton import com.google.firebase.database.DatabaseError import com.google.firebase.database.DataSnapshot import durdinapps.rxfirebase2.DataSnapshotMapper import durdinapps.rxfirebase2.RxFirebaseAuth import durdinapps.rxfirebase2.RxFirebaseDatabase import io.reactivex.Maybe import site.paulo.localchat.data.model.firebase.* import site.paulo.localchat.exception.MissingCurrentUserException @Singleton class FirebaseHelper @Inject constructor(val firebaseDatabase: FirebaseDatabase, val currentUserManager: CurrentUserManager, val firebaseAuth: FirebaseAuth) { object Reference { val CHATS = "chats" val MESSAGES = "messages" val USERS = "users" val GEOHASHES = "geohashes" } object Child { val ACCURACY = "acc" val AGE = "age" val CHATS = "chats" val DELIVERED_MESSAGES = "deliveredMessages" val EMAIL = "email" val GENDER = "gender" val GEOHASH = "geohash" val ID = "id" val LAST_MESSAGE = "lastMessage" val LAST_GEO_UPDATE = "lastGeoUpdate" val LATITUDE = "lat" val LOCATION = "loc" val LONGITUDE = "lon" val MESSAGE = "message" val NAME = "name" val OWNER = "owner" val PIC = "pic" val TIMESTAMP = "timestamp" val TOKEN = "token" val USERS = "users" } companion object { enum class UserDataType { NAME, AGE, PIC } } private var childEventListeners: HashMap<String, ChildEventListener> = HashMap() private var valueEventListeners: HashMap<String, ValueEventListener> = HashMap() /**************** User *********************/ fun getUsers(): Maybe<LinkedHashMap<String, User>> { return RxFirebaseDatabase.observeSingleValueEvent(firebaseDatabase.getReference(Reference.USERS), DataSnapshotMapper.mapOf(User::class.java)) } //TODO update to user this function fun getNearbyUsers(geoHash: String): Maybe<LinkedHashMap<String, Any>> { return RxFirebaseDatabase.observeSingleValueEvent(firebaseDatabase.getReference(Reference.GEOHASHES).child(geoHash), DataSnapshotMapper.mapOf(Any::class.java)) } fun getUser(userId: String): Maybe<User> { return RxFirebaseDatabase.observeSingleValueEvent(firebaseDatabase.getReference(Reference.USERS).child(userId), User::class.java) } fun registerUser(user: User) { val userData = mutableMapOf<String, Any>() userData[Child.EMAIL] = user.email userData[Child.NAME] = user.name userData[Child.AGE] = user.age userData[Child.GENDER] = user.gender userData[Child.PIC] = "https://api.adorable.io/avatars/240/" + Utils.getFirebaseId(user.email) + ".png" val completionListener = DatabaseReference.CompletionListener { _, _ -> Timber.e("User %s registered", user.email) } firebaseDatabase.getReference(Reference.USERS).child(Utils.getFirebaseId(user.email)).setValue(userData, completionListener) } fun authenticateUser(email: String, password: String): Maybe<AuthResult> { return RxFirebaseAuth.signInWithEmailAndPassword(firebaseAuth, email, password) } fun updateUserData(dataType: UserDataType, newValue: String, completionListener: DatabaseReference.CompletionListener) { when (dataType) { UserDataType.NAME -> { val newName = mutableMapOf<String, Any>() newName[Child.NAME] = newValue firebaseDatabase.getReference(Reference.USERS) .child(currentUserManager.getUserId()) .updateChildren(newName, completionListener) } UserDataType.AGE -> { val newAge = mutableMapOf<String, Any>() newAge[Child.AGE] = newValue.toInt() firebaseDatabase.getReference(Reference.USERS) .child(currentUserManager.getUserId()).updateChildren(newAge, completionListener) } UserDataType.PIC -> { val newPic = mutableMapOf<String, Any>() newPic[Child.PIC] = newValue firebaseDatabase.getReference(Reference.USERS) .child(currentUserManager.getUserId()).updateChildren(newPic, completionListener) } } } fun updateToken(token: String?) { val completionListener = DatabaseReference.CompletionListener { _, _ -> Timber.d("Token updated") } if (token != null) { val newToken = mutableMapOf<String, Any>() newToken[Child.TOKEN] = token firebaseDatabase.getReference(Reference.USERS) .child(currentUserManager.getUserId()) .updateChildren(newToken, completionListener) } } fun updateProfilePic(url: String?) { val completionListener = DatabaseReference.CompletionListener { _, _ -> Timber.d("Profile pic updated") } if (url != null) { val newProfilePic = mutableMapOf<String, Any>() newProfilePic[Child.PIC] = url firebaseDatabase.getReference(Reference.USERS) .child(currentUserManager.getUserId()) .updateChildren(newProfilePic, completionListener) } } fun updateUserLocation(location: Location?, callNext: (() -> Unit)? = null) { val currentUser = currentUserManager.getUser() ?: return val locationCompletionListener = DatabaseReference.CompletionListener { _, _ -> Timber.d("Location updated: lat %s, lon %s", location?.latitude, location?.longitude) } val userInfoCompletionListener = DatabaseReference.CompletionListener { _, _ -> Timber.d("Geohash updated") } val removeListener = DatabaseReference.CompletionListener { _, _ -> Timber.d("Removed from old area") } if (location != null) { val geoHash = GeoHash.geoHashStringWithCharacterPrecision(location.latitude, location.longitude, 5) currentUser.geohash = geoHash if (!geoHash.equals(currentUser.geohash)) firebaseDatabase.getReference(Reference.GEOHASHES) .child(currentUser.geohash) .child(currentUserManager.getUserId()) .removeValue(removeListener) val newUserLocation = mutableMapOf<String, Any>() newUserLocation[Child.LATITUDE] = location.latitude newUserLocation[Child.LONGITUDE] = location.longitude newUserLocation[Child.ACCURACY] = location.accuracy newUserLocation[Child.GEOHASH] = geoHash firebaseDatabase.getReference(Reference.USERS) .child(currentUserManager.getUserId()) .updateChildren(newUserLocation, locationCompletionListener) val newUserInfo = mutableMapOf<String, Any>() newUserInfo[Child.NAME] = currentUser.name newUserInfo[Child.PIC] = currentUser.pic newUserInfo[Child.EMAIL] = currentUser.email newUserInfo[Child.AGE] = currentUser.age newUserInfo[Child.LAST_GEO_UPDATE] = ServerValue.TIMESTAMP firebaseDatabase.getReference(Reference.GEOHASHES) .child(geoHash) .child(currentUserManager.getUserId()) .updateChildren(newUserInfo, userInfoCompletionListener) callNext?.invoke() } } fun registerUserChildEventListener(listener: ChildEventListener) { registerChildEventListener(firebaseDatabase.getReference(Reference.USERS) .child(currentUserManager.getUserId()), listener, "User") } fun registerUserValueEventListener(listener: ValueEventListener) { registerValueEventListener(firebaseDatabase.getReference(Reference.USERS) .child(currentUserManager.getUserId()), listener, "User") } /*******************************************/ /**************** Room ****************/ fun sendMessage(message: ChatMessage, chatId: String, completionListener: DatabaseReference.CompletionListener) { val valueMessage = mutableMapOf<String, Any>() valueMessage[Child.OWNER] = message.owner valueMessage[Child.MESSAGE] = message.message valueMessage[Child.TIMESTAMP] = ServerValue.TIMESTAMP val valueLastMessage = mutableMapOf<String, Any>() valueLastMessage[Child.LAST_MESSAGE] = valueMessage firebaseDatabase.getReference(Reference.MESSAGES).child(chatId).push().setValue(valueMessage, completionListener) firebaseDatabase.getReference(Reference.CHATS).child(chatId).updateChildren(valueLastMessage) } fun getChatRoom(chatId: String): Maybe<Chat> { val storedChat = firebaseDatabase.getReference(Reference.CHATS).child(chatId) storedChat.keepSynced(true) return RxFirebaseDatabase.observeSingleValueEvent(storedChat, Chat::class.java) } fun createNewRoom(otherUser: SummarizedUser, otherEmail: String): Chat { val currentUser = currentUserManager.getUser() ?: throw MissingCurrentUserException("No user set as current") val summarizedCurrentUser = SummarizedUser(currentUser.name, currentUser.pic) val summarizedOtherUser = SummarizedUser(otherUser.name, otherUser.pic) val reference = firebaseDatabase.getReference(Reference.CHATS).push() val chat = Chat(reference.key!!, mapOf(Utils.getFirebaseId(currentUser.email) to summarizedCurrentUser, Utils.getFirebaseId(otherEmail) to summarizedOtherUser), ChatMessage("", "", 0L), mapOf(Utils.getFirebaseId(currentUser.email) to 0, Utils.getFirebaseId(otherEmail) to 0)) reference.setValue(chat) firebaseDatabase.getReference(Reference.USERS) .child(Utils.getFirebaseId(currentUser.email)) .child(Child.CHATS) .updateChildren(mapOf(Utils.getFirebaseId(otherEmail) to reference.key)) firebaseDatabase.getReference(Reference.USERS) .child(Utils.getFirebaseId(otherEmail)) .child(Child.CHATS) .updateChildren(mapOf(Utils.getFirebaseId(currentUser.email) to reference.key)) return chat } fun registerRoomChildEventListener(listener: ChildEventListener, roomId: String, listenerId: String? = null): Boolean { firebaseDatabase.getReference(Reference.MESSAGES).child(roomId).keepSynced(true) return registerChildEventListener(firebaseDatabase.getReference(Reference.MESSAGES) .child(roomId).orderByChild(Child.TIMESTAMP), listener, listenerId ?: roomId) } fun unregisterRoomChildEventListener(listener: ChildEventListener, roomId: String) { Timber.d("Unregistering room $roomId") removeChildListeners(firebaseDatabase.getReference(Reference.MESSAGES) .child(roomId), listener) childEventListeners.remove(roomId) } fun registerRoomValueEventListener(listener: ValueEventListener, roomId: String, listenerId: String? = null): Boolean { return registerValueEventListener(firebaseDatabase.getReference(Reference.MESSAGES) .child(roomId).orderByChild(Child.TIMESTAMP), listener, listenerId ?: roomId) } fun addRoomSingleValueEventListener(listener: ValueEventListener, roomId: String) { firebaseDatabase.getReference(Reference.MESSAGES) .child(roomId).addListenerForSingleValueEvent(listener) } fun unregisterRoomValueEventListener(listener: ValueEventListener, roomId: String) { Timber.d("Unregistering room $roomId") removeValueListeners(firebaseDatabase.getReference(Reference.MESSAGES) .child(roomId), listener) valueEventListeners.remove(roomId) } fun registerNewChatRoomChildEventListener(listener: ChildEventListener, _userId: String? = null) { var userId: String? = _userId if (userId == null) { userId = currentUserManager.getUserId() } firebaseDatabase.getReference(Reference.USERS).child(userId).child(Child.CHATS).keepSynced(true) registerChildEventListener(firebaseDatabase.getReference(Reference.USERS).child(userId) .child(Child.CHATS), listener, "myChats") } fun registerNewUsersChildEventListener(listener: ChildEventListener) { val currentUser = currentUserManager.getUser() ?: return firebaseDatabase.getReference(Reference.GEOHASHES).child(currentUser.geohash).keepSynced(true) registerChildEventListener(firebaseDatabase.getReference(Reference.GEOHASHES).child(currentUser.geohash), listener, "nearbyUsers") } fun messageDelivered(chatId: String) { val mDeliveredRef = firebaseDatabase.getReference(Reference.CHATS).child(chatId).child(Child.DELIVERED_MESSAGES) mDeliveredRef.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { var delivered = dataSnapshot.child(currentUserManager.getUserId()).value as Long mDeliveredRef.child(currentUserManager.getUserId()).setValue(++delivered) } override fun onCancelled(databaseError: DatabaseError) { throw databaseError.toException() } }) } /**************************************/ /**************** Listeners ****************/ private fun registerChildEventListener(query: Query, listener: ChildEventListener, listenerIdentifier: String): Boolean { if (childEventListeners.containsKey(listenerIdentifier)) { Timber.d("Removing and registering event listener $listenerIdentifier again") firebaseDatabase.reference.removeEventListener(listener) } childEventListeners.put(listenerIdentifier, listener) query.addChildEventListener(listener) return true } private fun registerValueEventListener(query: Query, listener: ValueEventListener, listenerIdentifier: String): Boolean { if (!valueEventListeners.containsKey(listenerIdentifier)) { Timber.d("Registering value listener... $listenerIdentifier") valueEventListeners.put(listenerIdentifier, listener) query.addValueEventListener(listener) return true } Timber.d("Listener already registered. Skipping.") return false } fun removeChildListeners(query: Query, listener: ChildEventListener) { query.removeEventListener(listener) } fun removeValueListeners(query: Query, listener: ValueEventListener) { query.removeEventListener(listener) } fun removeAllListeners() { for ((_, listener) in childEventListeners) { firebaseDatabase.reference.removeEventListener(listener) } for ((_, listener) in valueEventListeners) { firebaseDatabase.reference.removeEventListener(listener) } } /*******************************************/ }
apache-2.0
daca089ccfdbe0f2ed00ef838df5ae46
41.0798
132
0.66238
5.326389
false
false
false
false
willmadison/Axiomatic
src/main/kotlin/com/willmadison/rules/Condition.kt
1
760
package com.willmadison.rules abstract class Condition : RuleElement { protected var affirmative: RuleElement? = null protected var negative: RuleElement? = null abstract fun evaluateCondition(o: Any): Boolean override fun evaluate(o: Any): Boolean { if (evaluateCondition(o)) { return if (affirmative != null) affirmative!!.evaluate(o) else true } else { return if (negative != null) negative!!.evaluate(o) else false } } enum class Operator(val symbol: String) { EQUALS("=="), EXISTS("exists"), LESS_THAN("<"), GREATER_THAN(">"), CONTAINS("contains"); override fun toString(): String { return symbol } } }
mit
fd68fe6e41d58cf6ca09f8e0282322c5
25.241379
79
0.584211
4.550898
false
false
false
false
Deadleg/idea-openresty-lua-support
src/com/github/deadleg/idea/openresty/lua/NgxLuaParameterInfoHandler.kt
1
4171
package com.github.deadleg.idea.openresty.lua import com.intellij.codeInsight.lookup.LookupElement import com.intellij.lang.parameterInfo.CreateParameterInfoContext import com.intellij.lang.parameterInfo.ParameterInfoContext import com.intellij.lang.parameterInfo.ParameterInfoHandler import com.intellij.lang.parameterInfo.ParameterInfoUIContext import com.intellij.lang.parameterInfo.UpdateParameterInfoContext import com.intellij.psi.PsiElement class NgxLuaParameterInfoHandler : ParameterInfoHandler<PsiElement, Any> { override fun couldShowInLookup(): Boolean { return true } override fun getParametersForLookup(item: LookupElement, context: ParameterInfoContext): Array<Any>? { return null } override fun getParametersForDocumentation(p: Any, context: ParameterInfoContext): Array<Any>? { return null } override fun findElementForParameterInfo(context: CreateParameterInfoContext): PsiElement? { val offset = context.offset // LuaFunctionCallExpression return context.file.findElementAt(offset)?.parent?.parent } override fun showParameterInfo(element: PsiElement, context: CreateParameterInfoContext) { // The lua plugin PSI elements have lua in its name if (!element.javaClass.name.contains("Lua")) { return } // Remove braces val functionElement = if ("com.sylvanaar.idea.Lua.lang.psi.impl.lists.LuaExpressionListImpl" == element.javaClass.name) { element.parent.parent } else { element } val function = if (functionElement.textContains('(')) { functionElement.text.substring(0, functionElement.text.indexOf('(')) } else { functionElement.text } val parameters = NgxLuaKeywords.getArgs(function) ?: return context.itemsToShow = parameters.toTypedArray() context.showHint(element, element.textRange.startOffset, this) } override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): PsiElement? { return context.file.findElementAt(context.offset)?.parent?.parent } override fun updateParameterInfo(psiElement: PsiElement, context: UpdateParameterInfoContext) { // The lua plugin PSI elements have lua in its name if (!psiElement.javaClass.name.contains("Lua")) { return } // Remove braces val function = if (psiElement.textContains('(')) { psiElement.text.substring(0, psiElement.text.indexOf('(')) } else { // Case when getting info from just ngx.location.capture, not ngx.location.capture() psiElement.text } val parameters = NgxLuaKeywords.getArgs(function) ?: return // Traverse up the tree until we hit the parent that holds the children var root = context.file.findElementAt(context.offset - 1) // Get element at start of cursor for (i in 0..2) { root = root?.parent if (root == null) { return } } var numberOfArgs = root!!.children.size if (numberOfArgs < 0) { numberOfArgs = 0 } else if (numberOfArgs > parameters.size) { return } context.highlightedParameter = parameters[numberOfArgs - 1] } override fun getParameterCloseChars(): String? { return ",){}\t" } override fun tracksParameterIndex(): Boolean { return true } override fun updateUI(p: Any, context: ParameterInfoUIContext) { val highlightStartOffset = -1 val highlightEndOffset = -1 val buffer = StringBuilder() if (p is PsiElement) { buffer.append(p.text) } if (p is String) { buffer.append(p) } context.setupUIComponentPresentation( buffer.toString(), highlightStartOffset, highlightEndOffset, !context.isUIComponentEnabled, false, false, context.defaultParameterColor) } }
mit
ba8e7339a5a547a989a0e705830a685f
34.05042
129
0.64421
5.007203
false
false
false
false
AndroidX/androidx
datastore/datastore-preferences-rxjava3/src/main/java/androidx/datastore/preferences/rxjava3/RxPreferenceDataStoreDelegate.kt
3
4756
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.datastore.preferences.rxjava3 import android.content.Context import androidx.annotation.GuardedBy import androidx.datastore.core.DataMigration import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStoreFile import androidx.datastore.rxjava3.RxDataStore import io.reactivex.rxjava3.core.Scheduler import io.reactivex.rxjava3.schedulers.Schedulers import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty /** * Creates a property delegate for a single process Preferences DataStore. This should only be * called once in a file (at the top level), and all usages of the DataStore should use a * reference the same Instance. The receiver type for the property delegate must be an instance * of [Context]. * * This should only be used from a single application in a single classloader in a single process. * * Example usage: * ``` * val Context.myRxDataStore by rxPreferencesDataStore("filename", serializer) * * class SomeClass(val context: Context) { * fun update(): Single<Preferences> = context.myRxDataStore.updateDataAsync {...} * } * ``` * * * @param name The name of the preferences. The preferences will be stored in a file in the * "datastore/" subdirectory in the application context's files directory and is generated using * [preferencesDataStoreFile]. * @param corruptionHandler The corruptionHandler is invoked if DataStore encounters a * [androidx.datastore.core.CorruptionException] when attempting to read data. CorruptionExceptions * are thrown by serializers when data can not be de-serialized. * @param produceMigrations produce the migrations. The ApplicationContext is passed in to these * callbacks as a parameter. DataMigrations are run before any access to data can occur. Each * producer and migration may be run more than once whether or not it already succeeded * (potentially because another migration failed or a write to disk failed.) * @param scheduler The scope in which IO operations and transform functions will execute. * * @return a property delegate that manages a datastore as a singleton. */ @Suppress("MissingJvmstatic") public fun rxPreferencesDataStore( name: String, corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null, produceMigrations: (Context) -> List<DataMigration<Preferences>> = { listOf() }, scheduler: Scheduler = Schedulers.io() ): ReadOnlyProperty<Context, RxDataStore<Preferences>> { return RxDataStoreSingletonDelegate(name, corruptionHandler, produceMigrations, scheduler) } /** * Delegate class to manage DataStore as a singleton. */ internal class RxDataStoreSingletonDelegate internal constructor( private val fileName: String, private val corruptionHandler: ReplaceFileCorruptionHandler<Preferences>?, private val produceMigrations: (Context) -> List<DataMigration<Preferences>>, private val scheduler: Scheduler ) : ReadOnlyProperty<Context, RxDataStore<Preferences>> { private val lock = Any() @GuardedBy("lock") @Volatile private var INSTANCE: RxDataStore<Preferences>? = null /** * Gets the instance of the DataStore. * * @param thisRef must be an instance of [Context] * @param property not used */ override fun getValue(thisRef: Context, property: KProperty<*>): RxDataStore<Preferences> { return INSTANCE ?: synchronized(lock) { if (INSTANCE == null) { val applicationContext = thisRef.applicationContext INSTANCE = with(RxPreferenceDataStoreBuilder(applicationContext, fileName)) { setIoScheduler(scheduler) @Suppress("NewApi", "ClassVerificationFailure") // b/187418647 produceMigrations(applicationContext).forEach { addDataMigration(it) } corruptionHandler?.let { setCorruptionHandler(it) } build() } } INSTANCE!! } } }
apache-2.0
9217ca66028c6e5c3ba1c53344f1123f
41.097345
99
0.730025
5.022175
false
false
false
false
yechaoa/YUtils
yutilskt/src/main/java/com/yechaoa/yutilskt/LogUtil.kt
1
4755
package com.yechaoa.yutilskt import android.util.Log /** * Created by yechao on 2020/1/7. * Describe : 日志管理 * * GitHub : https://github.com/yechaoa * CSDN : http://blog.csdn.net/yechaoa */ object LogUtil { private var TAG = "LogUtil" private var IS_LOG = false private const val MAX_LENGTH = 4000 /** * 设置是否开启打印 */ fun setIsLog(isLog: Boolean) { IS_LOG = isLog } fun setIsLog(isLog: Boolean, tag: String) { TAG = tag IS_LOG = isLog } fun i(msg: String) { if (IS_LOG) { val info = autoJumpLogInfos val msgLength = msg.length var start = 0 var end = MAX_LENGTH for (i in 0..99) { if (msgLength > end) { Log.i(TAG, info[1] + info[2] + " --->> " + msg.substring(start, end)) start = end end += MAX_LENGTH } else { Log.i(TAG, info[1] + info[2] + " --->> " + msg.substring(start, msgLength)) break } } } } fun i(tag: String?, msg: String) { if (IS_LOG) { val info = autoJumpLogInfos val msgLength = msg.length var start = 0 var end = MAX_LENGTH for (i in 0..99) { if (msgLength > end) { Log.i(tag, info[1] + info[2] + " --->> " + msg.substring(start, end)) start = end end += MAX_LENGTH } else { Log.i(tag, info[1] + info[2] + " --->> " + msg.substring(start, msgLength)) break } } } } fun d(msg: String) { if (IS_LOG) { val info = autoJumpLogInfos val msgLength = msg.length var start = 0 var end = MAX_LENGTH for (i in 0..99) { if (msgLength > end) { Log.d(TAG, info[1] + info[2] + " --->> " + msg.substring(start, end)) start = end end += MAX_LENGTH } else { Log.d(TAG, info[1] + info[2] + " --->> " + msg.substring(start, msgLength)) break } } } } fun d(tag: String?, msg: String) { if (IS_LOG) { val info = autoJumpLogInfos val msgLength = msg.length var start = 0 var end = MAX_LENGTH for (i in 0..99) { if (msgLength > end) { Log.d(tag, info[1] + info[2] + " --->> " + msg.substring(start, end)) start = end end += MAX_LENGTH } else { Log.d(tag, info[1] + info[2] + " --->> " + msg.substring(start, msgLength)) break } } } } fun e(msg: String) { if (IS_LOG) { val info = autoJumpLogInfos val msgLength = msg.length var start = 0 var end = MAX_LENGTH for (i in 0..99) { if (msgLength > end) { Log.e(TAG, info[1] + info[2] + " --->> " + msg.substring(start, end)) start = end end += MAX_LENGTH } else { Log.e(TAG, info[1] + info[2] + " --->> " + msg.substring(start, msgLength)) break } } } } fun e(tag: String?, msg: String) { if (IS_LOG) { val info = autoJumpLogInfos val msgLength = msg.length var start = 0 var end = MAX_LENGTH for (i in 0..99) { if (msgLength > end) { Log.e(tag, info[1] + info[2] + " --->> " + msg.substring(start, end)) start = end end += MAX_LENGTH } else { Log.e(tag, info[1] + info[2] + " --->> " + msg.substring(start, msgLength)) break } } } } /** * 获取打印信息所在方法名,行号等信息 */ private val autoJumpLogInfos: Array<String> get() { val infos = arrayOf("", "", "") val elements = Thread.currentThread().stackTrace infos[0] = elements[4].className.substring(elements[4].className.lastIndexOf(".") + 1) infos[1] = elements[4].methodName infos[2] = "(" + elements[4].fileName + ":" + elements[4].lineNumber + ")" return infos } }
apache-2.0
cc5194c7aeeccbdfcfe8942c732bf5b0
29.309677
98
0.404939
4.156637
false
false
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/model/GuiaDestinatarioDetalle.kt
1
848
package com.quijotelui.model import org.hibernate.annotations.Immutable import java.io.Serializable import java.math.BigDecimal import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table @Entity @Immutable @Table(name = "v_ele_guias_receptor_detalle") class GuiaDestinatarioDetalle : Serializable { @Id @Column(name = "id") var id : Long? = null @Column(name = "codigo") var codigo : String? = null @Column(name = "numero") var numero : String? = null @Column(name = "documento") var documento : String? = null @Column(name = "codigo_articulo") var codigoArticulo : String? = null @Column(name = "nombre_articulo") var nombreArticulo : String? = null @Column(name = "cantidad") var cantidad : BigDecimal? = null }
gpl-3.0
5a45194d8ba5463e4ede1f76d939c599
21.342105
47
0.694575
3.578059
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/asynctasks/CopyMoveTask.kt
1
14660
package com.simplemobiletools.commons.asynctasks import android.app.NotificationChannel import android.app.NotificationManager import android.content.ContentValues import android.os.AsyncTask import android.os.Handler import android.provider.MediaStore import androidx.core.app.NotificationCompat import androidx.core.util.Pair import androidx.documentfile.provider.DocumentFile import com.simplemobiletools.commons.R import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.CONFLICT_KEEP_BOTH import com.simplemobiletools.commons.helpers.CONFLICT_SKIP import com.simplemobiletools.commons.helpers.getConflictResolution import com.simplemobiletools.commons.helpers.isOreoPlus import com.simplemobiletools.commons.interfaces.CopyMoveListener import com.simplemobiletools.commons.models.FileDirItem import java.io.File import java.io.InputStream import java.io.OutputStream import java.lang.ref.WeakReference class CopyMoveTask( val activity: BaseSimpleActivity, val copyOnly: Boolean, val copyMediaOnly: Boolean, val conflictResolutions: LinkedHashMap<String, Int>, listener: CopyMoveListener, val copyHidden: Boolean ) : AsyncTask<Pair<ArrayList<FileDirItem>, String>, Void, Boolean>() { private val INITIAL_PROGRESS_DELAY = 3000L private val PROGRESS_RECHECK_INTERVAL = 500L private var mListener: WeakReference<CopyMoveListener>? = null private var mTransferredFiles = ArrayList<FileDirItem>() private var mFileDirItemsToDelete = ArrayList<FileDirItem>() // confirm the deletion of files on Android 11 from Downloads and Android at once private var mDocuments = LinkedHashMap<String, DocumentFile?>() private var mFiles = ArrayList<FileDirItem>() private var mFileCountToCopy = 0 private var mDestinationPath = "" // progress indication private var mNotificationBuilder: NotificationCompat.Builder private var mCurrFilename = "" private var mCurrentProgress = 0L private var mMaxSize = 0 private var mNotifId = 0 private var mIsTaskOver = false private var mProgressHandler = Handler() init { mListener = WeakReference(listener) mNotificationBuilder = NotificationCompat.Builder(activity) } override fun doInBackground(vararg params: Pair<ArrayList<FileDirItem>, String>): Boolean? { if (params.isEmpty()) { return false } val pair = params[0] mFiles = pair.first!! mDestinationPath = pair.second!! mFileCountToCopy = mFiles.size mNotifId = (System.currentTimeMillis() / 1000).toInt() mMaxSize = 0 for (file in mFiles) { if (file.size == 0L) { file.size = file.getProperSize(activity, copyHidden) } val newPath = "$mDestinationPath/${file.name}" val fileExists = activity.getDoesFilePathExist(newPath) if (getConflictResolution(conflictResolutions, newPath) != CONFLICT_SKIP || !fileExists) { mMaxSize += (file.size / 1000).toInt() } } mProgressHandler.postDelayed({ initProgressNotification() updateProgress() }, INITIAL_PROGRESS_DELAY) for (file in mFiles) { try { val newPath = "$mDestinationPath/${file.name}" var newFileDirItem = FileDirItem(newPath, newPath.getFilenameFromPath(), file.isDirectory) if (activity.getDoesFilePathExist(newPath)) { val resolution = getConflictResolution(conflictResolutions, newPath) if (resolution == CONFLICT_SKIP) { mFileCountToCopy-- continue } else if (resolution == CONFLICT_KEEP_BOTH) { val newFile = activity.getAlternativeFile(File(newFileDirItem.path)) newFileDirItem = FileDirItem(newFile.path, newFile.name, newFile.isDirectory) } } copy(file, newFileDirItem) } catch (e: Exception) { activity.showErrorToast(e) return false } } return true } override fun onPostExecute(success: Boolean) { if (activity.isFinishing || activity.isDestroyed) { return } deleteProtectedFiles() mProgressHandler.removeCallbacksAndMessages(null) activity.notificationManager.cancel(mNotifId) val listener = mListener?.get() ?: return if (success) { listener.copySucceeded(copyOnly, mTransferredFiles.size >= mFileCountToCopy, mDestinationPath, mTransferredFiles.size == 1) } else { listener.copyFailed() } } private fun initProgressNotification() { val channelId = "Copy/Move" val title = activity.getString(if (copyOnly) R.string.copying else R.string.moving) if (isOreoPlus()) { val importance = NotificationManager.IMPORTANCE_LOW NotificationChannel(channelId, title, importance).apply { enableLights(false) enableVibration(false) activity.notificationManager.createNotificationChannel(this) } } mNotificationBuilder.setContentTitle(title) .setSmallIcon(R.drawable.ic_copy_vector) .setChannelId(channelId) } private fun updateProgress() { if (mIsTaskOver) { activity.notificationManager.cancel(mNotifId) cancel(true) return } mNotificationBuilder.apply { setContentText(mCurrFilename) setProgress(mMaxSize, (mCurrentProgress / 1000).toInt(), false) activity.notificationManager.notify(mNotifId, build()) } mProgressHandler.removeCallbacksAndMessages(null) mProgressHandler.postDelayed({ updateProgress() if (mCurrentProgress / 1000 >= mMaxSize) { mIsTaskOver = true } }, PROGRESS_RECHECK_INTERVAL) } private fun copy(source: FileDirItem, destination: FileDirItem) { if (source.isDirectory) { copyDirectory(source, destination.path) } else { copyFile(source, destination) } } private fun copyDirectory(source: FileDirItem, destinationPath: String) { if (!activity.createDirectorySync(destinationPath)) { val error = String.format(activity.getString(R.string.could_not_create_folder), destinationPath) activity.showErrorToast(error) return } if (activity.isPathOnOTG(source.path)) { val children = activity.getDocumentFile(source.path)?.listFiles() ?: return for (child in children) { val newPath = "$destinationPath/${child.name}" if (File(newPath).exists()) { continue } val oldPath = "${source.path}/${child.name}" val oldFileDirItem = FileDirItem(oldPath, child.name!!, child.isDirectory, 0, child.length()) val newFileDirItem = FileDirItem(newPath, child.name!!, child.isDirectory) copy(oldFileDirItem, newFileDirItem) } mTransferredFiles.add(source) } else if (activity.isRestrictedSAFOnlyRoot(source.path)) { activity.getAndroidSAFFileItems(source.path, true) { files -> for (child in files) { val newPath = "$destinationPath/${child.name}" if (activity.getDoesFilePathExist(newPath)) { continue } val oldPath = "${source.path}/${child.name}" val oldFileDirItem = FileDirItem(oldPath, child.name, child.isDirectory, 0, child.size) val newFileDirItem = FileDirItem(newPath, child.name, child.isDirectory) copy(oldFileDirItem, newFileDirItem) } mTransferredFiles.add(source) } } else if (activity.isAccessibleWithSAFSdk30(source.path)) { val children = activity.getDocumentSdk30(source.path)?.listFiles() ?: return for (child in children) { val newPath = "$destinationPath/${child.name}" if (File(newPath).exists()) { continue } val oldPath = "${source.path}/${child.name}" val oldFileDirItem = FileDirItem(oldPath, child.name!!, child.isDirectory, 0, child.length()) val newFileDirItem = FileDirItem(newPath, child.name!!, child.isDirectory) copy(oldFileDirItem, newFileDirItem) } mTransferredFiles.add(source) } else { val children = File(source.path).list() for (child in children) { val newPath = "$destinationPath/$child" if (activity.getDoesFilePathExist(newPath)) { continue } val oldFile = File(source.path, child) val oldFileDirItem = oldFile.toFileDirItem(activity) val newFileDirItem = FileDirItem(newPath, newPath.getFilenameFromPath(), oldFile.isDirectory) copy(oldFileDirItem, newFileDirItem) } mTransferredFiles.add(source) } } private fun copyFile(source: FileDirItem, destination: FileDirItem) { if (copyMediaOnly && !source.path.isMediaFile()) { mCurrentProgress += source.size return } val directory = destination.getParentPath() if (!activity.createDirectorySync(directory)) { val error = String.format(activity.getString(R.string.could_not_create_folder), directory) activity.showErrorToast(error) mCurrentProgress += source.size return } mCurrFilename = source.name var inputStream: InputStream? = null var out: OutputStream? = null try { if (!mDocuments.containsKey(directory) && activity.needsStupidWritePermissions(destination.path)) { mDocuments[directory] = activity.getDocumentFile(directory) } out = activity.getFileOutputStreamSync(destination.path, source.path.getMimeType(), mDocuments[directory]) inputStream = activity.getFileInputStreamSync(source.path)!! var copiedSize = 0L val buffer = ByteArray(DEFAULT_BUFFER_SIZE) var bytes = inputStream.read(buffer) while (bytes >= 0) { out!!.write(buffer, 0, bytes) copiedSize += bytes mCurrentProgress += bytes bytes = inputStream.read(buffer) } out?.flush() if (source.size == copiedSize && activity.getDoesFilePathExist(destination.path)) { mTransferredFiles.add(source) if (copyOnly) { activity.rescanPath(destination.path) { if (activity.baseConfig.keepLastModified) { updateLastModifiedValues(source, destination) activity.rescanPath(destination.path) } } } else if (activity.baseConfig.keepLastModified) { updateLastModifiedValues(source, destination) activity.rescanPath(destination.path) inputStream.close() out?.close() deleteSourceFile(source) } else { inputStream.close() out?.close() deleteSourceFile(source) } } } catch (e: Exception) { activity.showErrorToast(e) } finally { inputStream?.close() out?.close() } } private fun updateLastModifiedValues(source: FileDirItem, destination: FileDirItem) { copyOldLastModified(source.path, destination.path) val lastModified = File(source.path).lastModified() if (lastModified != 0L) { File(destination.path).setLastModified(lastModified) } } private fun deleteSourceFile(source: FileDirItem) { if (activity.isRestrictedWithSAFSdk30(source.path) && !activity.canManageMedia()) { mFileDirItemsToDelete.add(source) } else { activity.deleteFileBg(source, isDeletingMultipleFiles = false) activity.deleteFromMediaStore(source.path) } } // if we delete multiple files from Downloads folder on Android 11 or 12 without being a Media Management app, show the confirmation dialog just once private fun deleteProtectedFiles() { if (mFileDirItemsToDelete.isNotEmpty()) { val fileUris = activity.getFileUrisFromFileDirItems(mFileDirItemsToDelete) activity.deleteSDK30Uris(fileUris) { success -> if (success) { mFileDirItemsToDelete.forEach { activity.deleteFromMediaStore(it.path) } } } } } private fun copyOldLastModified(sourcePath: String, destinationPath: String) { val projection = arrayOf( MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATE_MODIFIED ) val uri = MediaStore.Files.getContentUri("external") val selection = "${MediaStore.MediaColumns.DATA} = ?" var selectionArgs = arrayOf(sourcePath) val cursor = activity.applicationContext.contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { if (cursor.moveToFirst()) { val dateTaken = cursor.getLongValue(MediaStore.Images.Media.DATE_TAKEN) val dateModified = cursor.getIntValue(MediaStore.Images.Media.DATE_MODIFIED) val values = ContentValues().apply { put(MediaStore.Images.Media.DATE_TAKEN, dateTaken) put(MediaStore.Images.Media.DATE_MODIFIED, dateModified) } selectionArgs = arrayOf(destinationPath) activity.applicationContext.contentResolver.update(uri, values, selection, selectionArgs) } } } }
gpl-3.0
69bd638bd76dd792447f6c093a31bf8b
39.385675
153
0.608254
5.407599
false
false
false
false
smichel17/simpletask-android
app/src/main/java/nl/mpcjanssen/simpletask/FilterSortFragment.kt
1
6661
package nl.mpcjanssen.simpletask import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import com.mobeta.android.dslv.DragSortListView import nl.mpcjanssen.simpletask.util.Config import java.util.* import kotlin.collections.ArrayList class FilterSortFragment : Fragment() { private var originalItems: ArrayList<String>? = null private var lv: DragSortListView? = null internal lateinit var adapter: SortItemAdapter internal var directions = ArrayList<String>() internal var adapterList = ArrayList<String>() internal var sortUpId: Int = 0 internal var sortDownId: Int = 0 internal lateinit var m_app: TodoApplication private val onDrop = DragSortListView.DropListener { from, to -> if (from != to) { val item = adapter.getItem(from) adapter.remove(item) adapter.insert(item, to) val sortItem = directions[from] directions.removeAt(from) directions.add(to, sortItem) } } private val onRemove = DragSortListView.RemoveListener { which -> adapter.remove(adapter.getItem(which)) } private // this DSLV xml declaration does not call for the use // of the default DragSortController; therefore, // DSLVFragment has a buildController() method. val layout: Int get() = R.layout.simple_list_item_single_choice override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val arguments = arguments if (originalItems == null) { if (savedInstanceState != null) { originalItems = savedInstanceState.getStringArrayList(STATE_SELECTED) } else { originalItems = arguments?.getStringArrayList(FilterActivity.FILTER_ITEMS)?: ArrayList() } } Log.d(TAG, "Created view with: " + originalItems) m_app = TodoApplication.app // Set the proper theme if (Config.isDarkTheme || Config.isBlackTheme) { sortDownId = R.drawable.ic_action_sort_down_dark sortUpId = R.drawable.ic_action_sort_up_dark } else { sortDownId = R.drawable.ic_action_sort_down sortUpId = R.drawable.ic_action_sort_up } adapterList.clear() val layout: LinearLayout layout = inflater.inflate(R.layout.single_filter, container, false) as LinearLayout val keys = resources.getStringArray(R.array.sortKeys) for (item in originalItems!!) { val parts = item.split("!".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val sortType: String var sortDirection: String if (parts.size == 1) { sortType = parts[0] sortDirection = Query.NORMAL_SORT } else { sortDirection = parts[0] sortType = parts[1] if (sortDirection.isEmpty() || sortDirection != Query.REVERSED_SORT) { sortDirection = Query.NORMAL_SORT } } val index = Arrays.asList(*keys).indexOf(sortType) if (index != -1) { adapterList.add(sortType) directions.add(sortDirection) keys[index] = null } } // Add sorts not already in the sortlist for (item in keys) { if (item != null) { adapterList.add(item) directions.add(Query.NORMAL_SORT) } } lv = layout.findViewById(R.id.dslistview) as DragSortListView lv!!.setDropListener(onDrop) lv!!.setRemoveListener(onRemove) adapter = SortItemAdapter(activity, R.layout.sort_list_item, R.id.text, adapterList) lv!!.adapter = adapter lv!!.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> var direction = directions[position] if (direction == Query.REVERSED_SORT) { direction = Query.NORMAL_SORT } else { direction = Query.REVERSED_SORT } directions.removeAt(position) directions.add(position, direction) adapter.notifyDataSetChanged() } return layout } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putStringArrayList(STATE_SELECTED, selectedItem) } override fun onDestroyView() { originalItems = selectedItem super.onDestroyView() } val selectedItem: ArrayList<String> get() { val multiSort = ArrayList<String>() if (lv != null) { for (i in 0..adapter.count - 1) { multiSort.add(directions[i] + Query.SORT_SEPARATOR + adapter.getSortType(i)) } } else if (originalItems != null) { multiSort.addAll(originalItems as ArrayList<String>) } else { multiSort.addAll(arguments?.getStringArrayList(FilterActivity.FILTER_ITEMS) ?: java.util.ArrayList()) } return multiSort } inner class SortItemAdapter(context: Context?, resource: Int, textViewResourceId: Int, objects: List<String>) : ArrayAdapter<String>(context, resource, textViewResourceId, objects) { private val names: Array<String> init { names = resources.getStringArray(R.array.sort) } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val row = super.getView(position, convertView, parent) val reverseButton = row.findViewById(R.id.reverse_button) as ImageButton val label = row.findViewById(R.id.text) as TextView label.text = Config.getSortString(adapterList[position]) if (directions[position] == Query.REVERSED_SORT) { reverseButton.setBackgroundResource(sortUpId) } else { reverseButton.setBackgroundResource(sortDownId) } return row } fun getSortType(position: Int): String { return adapterList[position] } } companion object { private val STATE_SELECTED = "selectedItem" internal val TAG = FilterActivity::class.java.simpleName } }
gpl-3.0
67530d6128d2602ed69ee56c12ff6ad9
35.005405
186
0.603663
4.894195
false
false
false
false
alxrm/audiowave-progressbar
audiowave/src/main/kotlin/rm/com/audiowave/Sampler.kt
1
1819
package rm.com.audiowave import android.os.Handler import android.os.Looper import java.util.concurrent.ExecutorService import java.util.concurrent.Executors /** * Created by alex */ internal val MAIN_THREAD = Handler(Looper.getMainLooper()) internal val SAMPLER_THREAD: ExecutorService = Executors.newSingleThreadExecutor() object Sampler { fun downSampleAsync(data: ByteArray, targetSize: Int, answer: (ByteArray) -> Unit) { SAMPLER_THREAD.submit { val scaled = downSample(data, targetSize) MAIN_THREAD.post { answer(scaled) } } } fun downSample(data: ByteArray, targetSize: Int): ByteArray { val targetSized = ByteArray(targetSize) val chunkSize = data.size / targetSize val chunkStep = Math.max(Math.floor((chunkSize / 10.0)), 1.0).toInt() var prevDataIndex = 0 var sampledPerChunk = 0F var sumPerChunk = 0F if (targetSize >= data.size) { return targetSized.paste(data) } for (index in 0..data.size step chunkStep) { val currentDataIndex = (targetSize * index.toLong() / data.size).toInt() if (prevDataIndex == currentDataIndex) { sampledPerChunk += 1 sumPerChunk += data[index].abs } else { targetSized[prevDataIndex] = (sumPerChunk / sampledPerChunk).toByte() sumPerChunk = 0F sampledPerChunk = 0F prevDataIndex = currentDataIndex } } return targetSized } } internal val Byte.abs: Byte get() = when (this) { Byte.MIN_VALUE -> Byte.MAX_VALUE in (Byte.MIN_VALUE + 1..0) -> (-this).toByte() else -> this } internal fun ByteArray.paste(other: ByteArray): ByteArray { if (size == 0) return byteArrayOf() return this.apply { forEachIndexed { i, _ -> this[i] = other.getOrElse(i, { this[i].abs }) } } }
mit
e491a18198c442f1126b71b1463cac49
23.917808
86
0.654206
3.878465
false
false
false
false
felipebz/sonar-plsql
zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/IdenticalExpressionCheck.kt
1
1864
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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.sonar.plsqlopen.checks import com.felipebz.flr.api.AstNode import org.sonar.plugins.plsqlopen.api.ConditionsGrammar import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.annotations.* @Rule(priority = Priority.BLOCKER, tags = [Tags.BUG]) @ConstantRemediation("2min") @RuleInfo(scope = RuleInfo.Scope.ALL) @ActivatedByDefault class IdenticalExpressionCheck : AbstractBaseCheck() { override fun init() { subscribeTo(PlSqlGrammar.COMPARISON_EXPRESSION) } override fun visitNode(node: AstNode) { val operator = node.getFirstChildOrNull(ConditionsGrammar.RELATIONAL_OPERATOR) if (operator != null) { val leftSide = node.firstChild val rightSide = node.lastChild if (CheckUtils.equalNodes(leftSide, rightSide)) { addIssue(leftSide, getLocalizedMessage(), operator.tokenValue) .secondary(rightSide, "Original") } } } }
lgpl-3.0
4548444add75c4d4672a50c2cb54e885
34.846154
86
0.715129
4.396226
false
false
false
false
eboudrant/net.ebt.muzei.miyazaki
android-common/src/main/java/net/ebt/muzei/miyazaki/load/UpdateMuzeiWorker.kt
1
2999
package net.ebt.muzei.miyazaki.load import android.content.Context import androidx.core.content.edit import androidx.core.net.toUri import androidx.work.CoroutineWorker import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import com.google.android.apps.muzei.api.provider.Artwork import com.google.android.apps.muzei.api.provider.ProviderContract import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import net.ebt.muzei.miyazaki.common.BuildConfig.GHIBLI_AUTHORITY import net.ebt.muzei.miyazaki.database.ArtworkDatabase class UpdateMuzeiWorker( context: Context, workerParams: WorkerParameters ) : CoroutineWorker(context, workerParams) { companion object { private const val CURRENT_PREF_NAME = "MuzeiGhibli.current" private const val SELECTED_COLOR = "muzei_color" fun toggleColor(context: Context, color: String) { val sharedPreferences = context.getSharedPreferences( CURRENT_PREF_NAME, Context.MODE_PRIVATE) val currentColor = sharedPreferences.getString(SELECTED_COLOR, null) sharedPreferences.edit { if (color == currentColor) { remove(SELECTED_COLOR) } else { putString(SELECTED_COLOR, color) } } enqueueUpdate(context) } fun getCurrentColor(context: Context): String? { val sharedPreferences = context.getSharedPreferences( CURRENT_PREF_NAME, Context.MODE_PRIVATE) return sharedPreferences.getString(SELECTED_COLOR, null) } private fun enqueueUpdate(context: Context) { val workManager = WorkManager.getInstance(context) workManager.enqueueUniqueWork("load", ExistingWorkPolicy.APPEND, OneTimeWorkRequestBuilder<UpdateMuzeiWorker>() .build()) } } override suspend fun doWork(): Result { val sharedPreferences = applicationContext.getSharedPreferences( CURRENT_PREF_NAME, Context.MODE_PRIVATE) val artworkList = ArtworkDatabase.getInstance(applicationContext) .artworkDao() .getArtwork(sharedPreferences.getString(SELECTED_COLOR, "")) withContext(Dispatchers.IO) { val providerClient = ProviderContract.getProviderClient( applicationContext, GHIBLI_AUTHORITY) providerClient.setArtwork(artworkList.shuffled().map { artwork -> Artwork.Builder() .token(artwork.hash) .persistentUri(artwork.url.toUri()) .title(artwork.caption) .byline(artwork.subtitle) .build() }) } return Result.success() } }
apache-2.0
aa61450e369ec373ef0efbc97d7065e4
38.986667
81
0.641214
5.233857
false
false
false
false
RightHandedMonkey/PersonalWebNotifier
app/src/main/java/com/rhm/pwn/home_feature/HomeFeatureOld.kt
1
2779
package com.rhm.pwn.home_feature import com.badoo.mvicore.element.Actor import com.badoo.mvicore.element.Reducer import com.badoo.mvicore.feature.ActorReducerFeature import com.rhm.pwn.home_feature.HomeFeatureOld.Wish import com.rhm.pwn.home_feature.HomeFeatureOld.Effect import com.rhm.pwn.home_feature.HomeFeatureOld.State import com.rhm.pwn.model.URLCheck import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers class HomeFeatureOld : ActorReducerFeature<Wish, Effect, State, Nothing>( initialState = State(), actor = ActorImpl(), reducer = ReducerImpl() ) { data class State( val isLoading: Boolean = false, val editShown: Boolean = false, val editUrlCheck: URLCheck? = null, val list: List<URLCheck> = emptyList()) sealed class Wish { object HomeScreenLoading : Wish() data class HomeScreenView(val urlCheck: URLCheck) data class HomeScreenEditOpen(val urlCheck: URLCheck) object HomeScreenEditCancel : Wish() data class HomeScreenEditSave(val urlCheck: URLCheck) data class HomeScreenEditDelete(val urlCheck: URLCheck) data class HomeScreenEditSelect(val urlCheck: URLCheck) } sealed class Effect { object StartedLoading : Effect() data class FinishedWithSuccess(val urlChecks: List<URLCheck>) : Effect() data class FinishedWithFailure(val throwable: Throwable) : Effect() } class ActorImpl : Actor<State, Wish, Effect> { private val service: Observable<List<URLCheck>> = TODO() override fun invoke(state: State, wish: Wish): Observable<Effect> = when (wish) { is Wish.HomeScreenLoading -> { if (!state.isLoading) { service .observeOn(AndroidSchedulers.mainThread()) .map { Effect.FinishedWithSuccess(urlChecks = it) as Effect } .startWith(Effect.StartedLoading) .onErrorReturn { Effect.FinishedWithFailure(it) } } else { Observable.empty() } } else -> Observable.empty() } } class ReducerImpl : Reducer<State, Effect> { override fun invoke(state: State, effect: Effect): State = when (effect) { is Effect.StartedLoading -> state.copy( isLoading = true ) is Effect.FinishedWithSuccess -> state.copy( isLoading = false, list = effect.urlChecks ) is Effect.FinishedWithFailure -> state.copy( isLoading = false ) } } }
mit
d324e32f78f7acbe5b5524ab9b8cbac8
35.578947
89
0.608132
4.849913
false
false
false
false
campos20/tnoodle
webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/zip/folder/InterchangeFolder.kt
1
2287
package org.worldcubeassociation.tnoodle.server.webscrambles.zip.folder import org.worldcubeassociation.tnoodle.server.serial.JsonConfig import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.StringUtil.toFileSafeString import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.StringUtil.stripNewlines import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.ScrambleDrawingData import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model.Competition import org.worldcubeassociation.tnoodle.server.webscrambles.zip.ZipInterchangeInfo import org.worldcubeassociation.tnoodle.server.webscrambles.zip.folder import org.worldcubeassociation.tnoodle.server.webscrambles.zip.model.Folder import java.time.LocalDateTime data class InterchangeFolder(val wcif: Competition, val uniqueTitles: Map<String, ScrambleDrawingData>, val globalTitle: String) { fun assemble(generationDate: LocalDateTime, versionTag: String, generationUrl: String?): Folder { val safeGlobalTitle = globalTitle.toFileSafeString() val jsonInterchangeData = ZipInterchangeInfo(globalTitle, versionTag, generationDate, generationUrl, wcif) val jsonStr = JsonConfig.SERIALIZER.encodeToString(ZipInterchangeInfo.serializer(), jsonInterchangeData) val jsonpFileName = "$safeGlobalTitle.jsonp" val jsonpStr = "var SCRAMBLES_JSON = $jsonStr;" val viewerResource = this::class.java.getResourceAsStream(HTML_SCRAMBLE_VIEWER).bufferedReader().readText() .replace("%SCRAMBLES_JSONP_FILENAME%", jsonpFileName) return folder("Interchange") { folder("txt") { for ((uniqueTitle, scrambleRequest) in uniqueTitles) { val scrambleLines = scrambleRequest.scrambleSet.allScrambles.flatMap { it.allScrambleStrings } val txtScrambles = scrambleLines.stripNewlines().joinToString("\r\n") file("$uniqueTitle.txt", txtScrambles) } } file("$safeGlobalTitle.json", jsonStr) file(jsonpFileName, jsonpStr) file("$safeGlobalTitle.html", viewerResource) } } companion object { private const val HTML_SCRAMBLE_VIEWER = "/wca/scrambleviewer.html" } }
gpl-3.0
8c460d776c9b5c397a81f05461cac344
50.977273
130
0.740708
4.764583
false
false
false
false
elect86/jAssimp
src/test/kotlin/assimp/postProcess/Triangulate Test.kt
2
2913
package assimp.postProcess import assimp.AiMesh import assimp.AiPrimitiveType import assimp.or import glm_.glm import glm_.vec3.Vec3 import io.kotest.matchers.shouldBe import io.kotest.core.spec.style.StringSpec import kotlin.math.cos import kotlin.math.sin class TriangulateTest : StringSpec() { init { val count = 1000 val piProcess = TriangulateProcess() val mesh = AiMesh().apply { numFaces = count faces = MutableList(count) { mutableListOf<Int>() } vertices = MutableList(count * 10) { Vec3() } primitiveTypes = AiPrimitiveType.POINT or AiPrimitiveType.LINE or AiPrimitiveType.LINE or AiPrimitiveType.POLYGON } run { var m = 0 var t = 0 var q = 4 while (m < count) { ++t val face = mesh.faces[m] var numIndices = t if (4 == t) { numIndices = q++ t = 0 if (10 == q) q = 4 } for (i in 0 until numIndices) face += 0 for (p in 0 until numIndices) { face[p] = mesh.numVertices // construct fully convex input data in ccw winding, xy plane mesh.vertices[mesh.numVertices++]( cos(p * glm.PI2f / numIndices), sin(p * glm.PI2f / numIndices), 0f) } ++m } } "triangulate process test" { piProcess.triangulateMesh(mesh) var m = 0 var t = 0 var q = 4 var max = count var idx = 0 while (m < max) { ++t val face = mesh.faces[m] if (4 == t) { t = 0 max += q - 3 val ait = BooleanArray(q) var i = 0 val tt = q - 2 while (i < tt) { val f = mesh.faces[m] f.size shouldBe 3 for (qqq in 0 until f.size) ait[f[qqq] - idx] = true ++i ++m } ait.forEach { it shouldBe true } --m idx += q if (++q == 10) q = 4 } else { face.size shouldBe t for (i in face.indices) face[i] shouldBe idx++ } ++m } // we should have no valid normal vectors now necause we aren't a pure polygon mesh mesh.normals.isEmpty() shouldBe true } } }
mit
1cd59708fea63274183a194bf45907e0
28.434343
125
0.403021
5.022414
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaController.kt
1
8063
package eu.kanade.tachiyomi.ui.manga import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.os.Bundle import android.support.design.widget.TabLayout import android.support.graphics.drawable.VectorDrawableCompat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.bluelinelabs.conductor.Router import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.support.RouterPagerAdapter import com.jakewharton.rxrelay.BehaviorRelay import com.jakewharton.rxrelay.PublishRelay import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.ui.base.controller.RxController import eu.kanade.tachiyomi.ui.base.controller.TabbedController import eu.kanade.tachiyomi.ui.base.controller.requestPermissionsSafe import eu.kanade.tachiyomi.ui.catalogue.CatalogueController import eu.kanade.tachiyomi.ui.manga.chapter.ChaptersController import eu.kanade.tachiyomi.ui.manga.chapter.ChaptersPresenter import eu.kanade.tachiyomi.ui.manga.info.MangaInfoController import eu.kanade.tachiyomi.ui.manga.track.TrackController import eu.kanade.tachiyomi.util.toast import kotlinx.android.synthetic.main.main_activity.* import kotlinx.android.synthetic.main.manga_controller.* import rx.Subscription import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.util.Date class MangaController : RxController, TabbedController { constructor(manga: Manga?, fromCatalogue: Boolean = false, smartSearchConfig: CatalogueController.SmartSearchConfig? = null, update: Boolean = false) : super(Bundle().apply { putLong(MANGA_EXTRA, manga?.id ?: 0) putBoolean(FROM_CATALOGUE_EXTRA, fromCatalogue) putParcelable(SMART_SEARCH_CONFIG_EXTRA, smartSearchConfig) putBoolean(UPDATE_EXTRA, update) }) { this.manga = manga if (manga != null) { source = Injekt.get<SourceManager>().getOrStub(manga.source) } } // EXH --> constructor(redirect: ChaptersPresenter.EXHRedirect) : super(Bundle().apply { putLong(MANGA_EXTRA, redirect.manga.id!!) putBoolean(UPDATE_EXTRA, redirect.update) }) { this.manga = redirect.manga if (manga != null) { source = Injekt.get<SourceManager>().getOrStub(redirect.manga.source) } } // EXH <-- constructor(mangaId: Long) : this( Injekt.get<DatabaseHelper>().getManga(mangaId).executeAsBlocking()) @Suppress("unused") constructor(bundle: Bundle) : this(bundle.getLong(MANGA_EXTRA)) var manga: Manga? = null private set var source: Source? = null private set private var adapter: MangaDetailAdapter? = null val fromCatalogue = args.getBoolean(FROM_CATALOGUE_EXTRA, false) var update = args.getBoolean(UPDATE_EXTRA, false) // EXH --> val smartSearchConfig: CatalogueController.SmartSearchConfig? = args.getParcelable(SMART_SEARCH_CONFIG_EXTRA) // EXH <-- val lastUpdateRelay: BehaviorRelay<Date> = BehaviorRelay.create() val chapterCountRelay: BehaviorRelay<Float> = BehaviorRelay.create() val mangaFavoriteRelay: PublishRelay<Boolean> = PublishRelay.create() private val trackingIconRelay: BehaviorRelay<Boolean> = BehaviorRelay.create() private var trackingIconSubscription: Subscription? = null override fun getTitle(): String? { return manga?.title } override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View { return inflater.inflate(R.layout.manga_controller, container, false) } override fun onViewCreated(view: View) { super.onViewCreated(view) if (manga == null || source == null) return requestPermissionsSafe(arrayOf(WRITE_EXTERNAL_STORAGE), 301) adapter = MangaDetailAdapter() manga_pager.offscreenPageLimit = 3 manga_pager.adapter = adapter if (!fromCatalogue) manga_pager.currentItem = CHAPTERS_CONTROLLER } override fun onDestroyView(view: View) { super.onDestroyView(view) adapter = null } override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) { super.onChangeStarted(handler, type) if (type.isEnter) { activity?.tabs?.setupWithViewPager(manga_pager) trackingIconSubscription = trackingIconRelay.subscribe { setTrackingIconInternal(it) } } } override fun onChangeEnded(handler: ControllerChangeHandler, type: ControllerChangeType) { super.onChangeEnded(handler, type) if (manga == null || source == null) { activity?.toast(R.string.manga_not_in_db) router.popController(this) } } override fun configureTabs(tabs: TabLayout) { with(tabs) { tabGravity = TabLayout.GRAVITY_FILL tabMode = TabLayout.MODE_FIXED } } override fun cleanupTabs(tabs: TabLayout) { trackingIconSubscription?.unsubscribe() setTrackingIconInternal(false) } fun setTrackingIcon(visible: Boolean) { trackingIconRelay.call(visible) } private fun setTrackingIconInternal(visible: Boolean) { val tab = activity?.tabs?.getTabAt(TRACK_CONTROLLER) ?: return val drawable = if (visible) VectorDrawableCompat.create(resources!!, R.drawable.ic_done_white_18dp, null) else null val view = tabField.get(tab) as LinearLayout val textView = view.getChildAt(1) as TextView textView.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null) textView.compoundDrawablePadding = if (visible) 4 else 0 } private inner class MangaDetailAdapter : RouterPagerAdapter(this@MangaController) { private val tabCount = if (Injekt.get<TrackManager>().hasLoggedServices()) 3 else 2 private val tabTitles = listOf( R.string.manga_detail_tab, R.string.manga_chapters_tab, R.string.manga_tracking_tab) .map { resources!!.getString(it) } override fun getCount(): Int { return tabCount } override fun configureRouter(router: Router, position: Int) { if (!router.hasRootController()) { val controller = when (position) { INFO_CONTROLLER -> MangaInfoController() CHAPTERS_CONTROLLER -> ChaptersController() TRACK_CONTROLLER -> TrackController() else -> error("Wrong position $position") } router.setRoot(RouterTransaction.with(controller)) } } override fun getPageTitle(position: Int): CharSequence { return tabTitles[position] } } companion object { // EXH --> const val UPDATE_EXTRA = "update" const val SMART_SEARCH_CONFIG_EXTRA = "smartSearchConfig" // EXH <-- const val FROM_CATALOGUE_EXTRA = "from_catalogue" const val MANGA_EXTRA = "manga" const val INFO_CONTROLLER = 0 const val CHAPTERS_CONTROLLER = 1 const val TRACK_CONTROLLER = 2 private val tabField = TabLayout.Tab::class.java.getDeclaredField("view") .apply { isAccessible = true } } }
apache-2.0
d1fceb2291ad246dabf92244258a3ed7
33.995536
113
0.666377
4.693248
false
false
false
false
y20k/trackbook
app/src/main/java/org/y20k/trackbook/core/WayPoint.kt
1
2151
/* * WayPoint.kt * Implements the WayPoint data class * A WayPoint stores a location plus additional metadata * * This file is part of * TRACKBOOK - Movement Recorder for Android * * Copyright (c) 2016-22 - Y20K.org * Licensed under the MIT-License * http://opensource.org/licenses/MIT * * Trackbook uses osmdroid - OpenStreetMap-Tools for Android * https://github.com/osmdroid/osmdroid */ package org.y20k.trackbook.core import android.location.Location import android.os.Parcelable import androidx.annotation.Keep import com.google.gson.annotations.Expose import kotlinx.parcelize.Parcelize import org.y20k.trackbook.helpers.LocationHelper /* * WayPoint data class */ @Keep @Parcelize data class WayPoint(@Expose val provider: String, @Expose val latitude: Double, @Expose val longitude: Double, @Expose val altitude: Double, @Expose val accuracy: Float, @Expose val time: Long, @Expose val distanceToStartingPoint: Float = 0f, @Expose val numberSatellites: Int = 0, @Expose var isStopOver: Boolean = false, @Expose var starred: Boolean = false): Parcelable { /* Constructor using just Location */ constructor(location: Location) : this (location.provider, location.latitude, location.longitude, location. altitude, location.accuracy, location.time) /* Constructor using Location plus distanceToStartingPoint and numberSatellites */ constructor(location: Location, distanceToStartingPoint: Float) : this (location.provider, location.latitude, location.longitude, location. altitude, location.accuracy, location.time, distanceToStartingPoint, LocationHelper.getNumberOfSatellites(location)) /* Converts WayPoint into Location */ fun toLocation(): Location { val location: Location = Location(provider) location.latitude = latitude location.longitude = longitude location.altitude = altitude location.accuracy = accuracy location.time = time return location } }
mit
b1cfd2799be3282127c4afdf9720d44a
34.262295
260
0.688052
4.769401
false
false
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingResponsePacket.kt
1
1443
package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import javax.inject.Inject /** * InjectionSnackSettingResponsePacket */ class InjectionSnackSettingResponsePacket( injector: HasAndroidInjector ) : DiaconnG8Packet(injector ) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump var result = 0 init { msgType = 0x87.toByte() aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackSettingResponsePacket init ") } override fun handleMessage(data: ByteArray?) { val defectCheck = defect(data) if (defectCheck != 0) { aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackSettingResponsePacket Got some Error") failed = true return } else failed = false val bufferData = prefixDecode(data) result = getByteToInt(bufferData) if(!isSuccSettingResponseResult(result)) { diaconnG8Pump.resultErrorCode = result failed = true return } diaconnG8Pump.otpNumber = getIntToInt(bufferData) aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") } override fun getFriendlyName(): String { return "PUMP_INJECTION_SNACK_SETTING_RESPONSE" } }
agpl-3.0
7d327e1a3a0f789745ccd63912b4a29f
30.391304
97
0.684685
4.685065
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt
1
3143
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan import android.bluetooth.le.ScanRecord import android.bluetooth.le.ScanResult import android.os.ParcelUuid class BleDiscoveredDevice(val scanResult: ScanResult, private val scanRecord: ScanRecord, private val podId: Long) { private val sequenceNo: Int private val lotNo: Long @Throws(DiscoveredInvalidPodException::class) private fun validateServiceUUIDs() { val serviceUuids = scanRecord.serviceUuids if (serviceUuids.size != 9) { throw DiscoveredInvalidPodException("Expected 9 service UUIDs, got" + serviceUuids.size, serviceUuids) } if (extractUUID16(serviceUuids[0]) != MAIN_SERVICE_UUID) { // this is the service that we filtered for throw DiscoveredInvalidPodException( "The first exposed service UUID should be 4024, got " + extractUUID16( serviceUuids[0] ), serviceUuids ) } // TODO understand what is serviceUUIDs[1]. 0x2470. Alarms? if (extractUUID16(serviceUuids[2]) != UNKNOWN_THIRD_SERVICE_UUID) { // constant? throw DiscoveredInvalidPodException( "The third exposed service UUID should be 000a, got " + serviceUuids[2], serviceUuids ) } } @Throws(DiscoveredInvalidPodException::class) private fun validatePodId() { val serviceUUIDs = scanRecord.serviceUuids val hexPodId = extractUUID16(serviceUUIDs[3]) + extractUUID16(serviceUUIDs[4]) val podId = hexPodId.toLong(16) if (this.podId != podId) { throw DiscoveredInvalidPodException( "This is not the POD we are looking for: ${this.podId} . Found: $podId/$hexPodId", serviceUUIDs ) } } private fun parseLotNo(): Long { val serviceUUIDs = scanRecord.serviceUuids val lotSeq = extractUUID16(serviceUUIDs[5]) + extractUUID16(serviceUUIDs[6]) + extractUUID16(serviceUUIDs[7]) return lotSeq.substring(0, 10).toLong(16) } private fun parseSeqNo(): Int { val serviceUUIDs = scanRecord.serviceUuids val lotSeq = extractUUID16(serviceUUIDs[7]) + extractUUID16(serviceUUIDs[8]) return lotSeq.substring(2).toInt(16) } override fun toString(): String { return "BleDiscoveredDevice{" + "scanRecord=" + scanRecord + ", podID=" + podId + "scanResult=" + scanResult + ", sequenceNo=" + sequenceNo + ", lotNo=" + lotNo + '}' } companion object { const val MAIN_SERVICE_UUID = "4024" const val UNKNOWN_THIRD_SERVICE_UUID = "000a" // FIXME: why is this 000a? private fun extractUUID16(uuid: ParcelUuid): String { return uuid.toString().substring(4, 8) } } init { validateServiceUUIDs() validatePodId() lotNo = parseLotNo() sequenceNo = parseSeqNo() } }
agpl-3.0
adaf5dd24e6b2ae68cbfead25987870c
33.922222
116
0.607063
4.691045
false
false
false
false
PolymerLabs/arcs
java/arcs/core/data/HandleMode.kt
1
1035
/* * Copyright 2020 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 arcs.core.data /** * Specifies the access mode for a [Handle]. */ enum class HandleMode( val canRead: Boolean = false, val canWrite: Boolean = false, val canQuery: Boolean = false ) { /** [Handle] is read only. */ Read(canRead = true), /** [Handle] is write only. */ Write(canWrite = true), /** [Handle] is query only. */ Query(canQuery = true), /** [Handle] is read-write. */ ReadWrite(canRead = true, canWrite = true), /** [Handle] is read-query. */ ReadQuery(canRead = true, canQuery = true), /** [Handle] is query-write. */ WriteQuery(canWrite = true, canQuery = true), /** [Handle] is read-query-write. */ ReadWriteQuery(canRead = true, canWrite = true, canQuery = true); }
bsd-3-clause
dfd7af2870b2bb2c8569e5dff718d661
24.243902
96
0.655072
3.581315
false
false
false
false
onoderis/failchat
src/test/kotlin/failchat/Utils.kt
2
823
package failchat import failchat.util.sleep import java.time.Duration fun <T> doAwhile(tries: Int, retryDelay: Duration, operation: () -> T): T { lateinit var lastException: Throwable repeat(tries) { try { return operation.invoke() } catch (t: Throwable) { lastException = t sleep(retryDelay) } } throw lastException } fun Long.s(): Duration = Duration.ofSeconds(this) fun Int.s(): Duration = Duration.ofSeconds(this.toLong()) fun Long.ms(): Duration = Duration.ofMillis(this) fun Int.ms(): Duration = Duration.ofMillis(this.toLong()) object Utils fun readResourceAsString(resource: String): String { val bytes = Utils::class.java.getResourceAsStream(resource)?.readBytes() ?: error("No resource $resource") return String(bytes) }
gpl-3.0
4d8064babc1d9cf7cb6b881600a05798
24.71875
110
0.667072
4.074257
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/neuralprocessor/embeddingsprocessor/EmbeddingsProcessorWithContext.kt
1
3612
/* Copyright 2018-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.neuralprocessor.embeddingsprocessor import com.kotlinnlp.simplednn.core.arrays.ParamsArray import com.kotlinnlp.simplednn.core.embeddings.EmbeddingsMap import com.kotlinnlp.simplednn.core.layers.LayerInterface import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.StackedLayersParameters import com.kotlinnlp.simplednn.core.neuralprocessor.batchfeedforward.BatchFeedforwardProcessor import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsAccumulator import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * Extension of the [EmbeddingsProcessor] with a context vector that is concatenated to each embedding. * * The [dropout] has no effect on the [contextVector]. * * @param embeddingsMap an embeddings map * @param contextVector the context vector concatenated to each embedding * @param dropout the probability to get the unknown embedding (default 0.0) */ class EmbeddingsProcessorWithContext<T>( embeddingsMap: EmbeddingsMap<T>, private val contextVector: ParamsArray, dropout: Double = 0.0 ) : EmbeddingsProcessor<T>( embeddingsMap = embeddingsMap, dropout = dropout ) { /** * The processor that concatenates the [contextVector] to each embedding. */ private val concatProcessor = BatchFeedforwardProcessor<DenseNDArray>( model = StackedLayersParameters( LayerInterface(sizes = listOf(embeddingsMap.size, contextVector.values.length), type = LayerType.Input.Dense), LayerInterface(sizes = listOf(), connectionType = LayerType.Connection.Concat)), dropout = 0.0, propagateToInput = true) /** * Accumulator of the errors of the [contextVector]. */ private val contextErrorsAccumulator by lazy { ParamsErrorsAccumulator() } /** * The Forward. * * @param input the input * * @return the result of the forward */ override fun forward(input: List<T>): List<DenseNDArray> { val embeddings: List<DenseNDArray> = super.forward(input) return this.concatProcessor.forward(embeddings.map { listOf(it, this.contextVector.values) }.toTypedArray()) } /** * The Backward. * * @param outputErrors the output errors */ override fun backward(outputErrors: List<DenseNDArray>) { val concatErrors: List<List<DenseNDArray>> = this.concatProcessor.let { it.backward(outputErrors) it.getInputsErrors(copy = false) } super.backward(concatErrors.map { it.first() }) this.accumulateContextVectorErrors(concatErrors.map { it.last() }) } /** * Return the params errors of the last backward. * * @param copy a Boolean indicating whether the returned errors must be a copy or a reference (default true) * * @return the parameters errors */ override fun getParamsErrors(copy: Boolean) = super.getParamsErrors(copy) + this.contextErrorsAccumulator.getParamsErrors(copy) /** * Accumulate the errors of the context vector. * * @param outputErrors the errors to accumulate */ private fun accumulateContextVectorErrors(outputErrors: List<DenseNDArray>) { this.contextErrorsAccumulator.clear() this.contextErrorsAccumulator.accumulate(params = this.contextVector, errors = outputErrors) } }
mpl-2.0
30810f4e47ca4cafc4bec2338f5d8e12
34.067961
116
0.732835
4.415648
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/layers/merge/avg/AvgLayerStructureSpec.kt
1
2315
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain contexte at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.layers.merge.avg import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertTrue /** * */ class AvgLayerStructureSpec : Spek({ describe("a AvgLayer") { context("forward") { val layer = AvgLayerUtils.buildLayer() layer.forward() it("should match the expected outputArray") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.275, 0.075, 0.025)), tolerance = 1.0e-05) } } } context("backward") { val layer = AvgLayerUtils.buildLayer() layer.forward() layer.outputArray.assignErrors(AvgLayerUtils.getOutputErrors()) layer.backward(propagateToInput = true) it("should match the expected errors of the inputArray at index 0") { assertTrue { layer.inputArrays[0].errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.25, -0.05, 0.1)), tolerance = 1.0e-05) } } it("should match the expected errors of the inputArray at index 1") { assertTrue { layer.inputArrays[1].errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.25, -0.05, 0.1)), tolerance = 1.0e-05) } } it("should match the expected errors of the inputArray at index 2") { assertTrue { layer.inputArrays[2].errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.25, -0.05, 0.1)), tolerance = 1.0e-05) } } it("should match the expected errors of the inputArray at index 3") { assertTrue { layer.inputArrays[3].errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.25, -0.05, 0.1)), tolerance = 1.0e-05) } } } } })
mpl-2.0
ce15cfac6fcc30f4ccb8ed2a48ba5655
28.679487
77
0.609071
4.294991
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/indrnn/IndRNNBackwardHelper.kt
1
3145
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.recurrent.indrnn import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.helpers.BackwardHelper import com.kotlinnlp.simplednn.core.arrays.getInputErrors import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The helper which executes the backward on a [layer]. * * @property layer the [IndRNNLayer] in which the backward is executed */ internal class IndRNNBackwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>( override val layer: IndRNNLayer<InputNDArrayType> ) : BackwardHelper<InputNDArrayType>(layer) { /** * Executes the backward calculating the errors of the parameters and eventually of the input through the SGD * algorithm, starting from the preset errors of the output array. * * @param propagateToInput whether to propagate the errors to the input array */ override fun execBackward(propagateToInput: Boolean) { val prevStateLayer = this.layer.layersWindow.getPrevState() val nextStateLayer = this.layer.layersWindow.getNextState() if (nextStateLayer != null) { this.addLayerRecurrentGradients(nextStateLayer as IndRNNLayer<*>) } this.layer.applyOutputActivationDeriv() // must be applied AFTER having added the recurrent contribution this.assignParamsGradients(prevStateOutput = prevStateLayer?.outputArray) if (propagateToInput) { this.assignLayerGradients() } } /** * gb = gy * 1 * gw = gb (dot) x' * gwRec = gy * yPrev * * @param prevStateOutput the output array in the previous state */ private fun assignParamsGradients(prevStateOutput: AugmentedArray<DenseNDArray>?) { this.layer.outputArray.assignParamsGradients( gw = this.layer.params.feedforwardUnit.weights.errors.values, gb = this.layer.params.feedforwardUnit.biases.errors.values, x = this.layer.inputArray.values ) val gwRec = this.layer.params.recurrentWeights.errors.values as DenseNDArray val yPrev = prevStateOutput?.values if (yPrev != null) gwRec.assignProd(this.layer.outputArray.errors, yPrev) else gwRec.zeros() } /** * gx = gb (dot) w */ private fun assignLayerGradients() { this.layer.inputArray.assignErrors( this.layer.outputArray.getInputErrors(w = this.layer.params.feedforwardUnit.weights.values) ) } /** * gy += gyNext * wRec */ private fun addLayerRecurrentGradients(nextStateLayer: IndRNNLayer<*>) { val gy: DenseNDArray = this.layer.outputArray.errors val wRec: DenseNDArray = this.layer.params.recurrentWeights.values val gRec = nextStateLayer.outputArray.errors.prod(wRec) gy.assignSum(gRec) } }
mpl-2.0
6af2dec892058133158826f8334d58c7
32.457447
111
0.719555
4.480057
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/commands/model/UpdatePlayerStatus.kt
1
1755
package com.kelsos.mbrc.commands.model import com.fasterxml.jackson.databind.node.ObjectNode import com.kelsos.mbrc.constants.Protocol import com.kelsos.mbrc.events.bus.RxBus import com.kelsos.mbrc.events.ui.RepeatChange import com.kelsos.mbrc.events.ui.ScrobbleChange import com.kelsos.mbrc.events.ui.ShuffleChange import com.kelsos.mbrc.events.ui.VolumeChange import com.kelsos.mbrc.interfaces.ICommand import com.kelsos.mbrc.interfaces.IEvent import com.kelsos.mbrc.model.MainDataModel import javax.inject.Inject class UpdatePlayerStatus @Inject constructor( private val model: MainDataModel, private val bus: RxBus ) : ICommand { override fun execute(e: IEvent) { val node = e.data as ObjectNode model.playState = node.path(Protocol.PlayerState).asText() val newMute = node.path(Protocol.PlayerMute).asBoolean() if (newMute != model.isMute) { model.isMute = newMute bus.post(if (newMute) VolumeChange() else VolumeChange(model.volume)) } model.setRepeatState(node.path(Protocol.PlayerRepeat).asText()) bus.post(RepeatChange(model.repeat)) val newShuffle = node.path(Protocol.PlayerShuffle).asText() if (newShuffle != model.shuffle) { //noinspection ResourceType model.shuffle = newShuffle bus.post(ShuffleChange(newShuffle)) } val newScrobbleState = node.path(Protocol.PlayerScrobble).asBoolean() if (newScrobbleState != model.isScrobblingEnabled) { model.isScrobblingEnabled = newScrobbleState bus.post(ScrobbleChange(newScrobbleState)) } val newVolume = Integer.parseInt(node.path(Protocol.PlayerVolume).asText()) if (newVolume != model.volume) { model.volume = newVolume bus.post(VolumeChange(model.volume)) } } }
gpl-3.0
c590d90a498fbdc4e9df8b0f48a8ae7f
31.5
79
0.745869
3.865639
false
false
false
false
ingokegel/intellij-community
platform/core-api/src/com/intellij/openapi/application/coroutines.kt
1
6323
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.application import com.intellij.openapi.progress.blockingContext import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus.Experimental import kotlin.coroutines.CoroutineContext /** * Suspends until it's possible to obtain the read lock and then * runs the [action] holding the lock **without** preventing write actions. * See [constrainedReadAction] for semantic details. * * @see readActionBlocking */ suspend fun <T> readAction(action: () -> T): T { return constrainedReadAction(action = action) } /** * Suspends until it's possible to obtain the read lock in smart mode and then * runs the [action] holding the lock **without** preventing write actions. * See [constrainedReadAction] for semantic details. * * @see smartReadActionBlocking */ suspend fun <T> smartReadAction(project: Project, action: () -> T): T { return constrainedReadAction(ReadConstraint.inSmartMode(project), action = action) } /** * Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction] * **without** preventing write actions. * * The function suspends if at the moment of calling it's not possible to acquire the read lock, * or if [constraints] are not [satisfied][ReadConstraint.isSatisfied]. * If the write action happens while the [action] is running, then the [action] is canceled, * and the function suspends until its possible to acquire the read lock, and then the [action] is tried again. * * Since the [action] might me executed several times, it must be idempotent. * The function returns when given [action] was completed fully. * To support cancellation, the [action] must regularly invoke [com.intellij.openapi.progress.ProgressManager.checkCanceled]. * * The [action] is dispatched to [Dispatchers.Default], because a read action is expected to be a CPU-bound task. * * @see constrainedReadActionBlocking */ suspend fun <T> constrainedReadAction(vararg constraints: ReadConstraint, action: () -> T): T { return readActionSupport().executeReadAction(constraints.toList(), blocking = false, action) } /** * Suspends until it's possible to obtain the read lock and then * runs the [action] holding the lock and **preventing** write actions. * See [constrainedReadActionBlocking] for semantic details. * * @see readAction */ suspend fun <T> readActionBlocking(action: () -> T): T { return constrainedReadActionBlocking(action = action) } /** * Suspends until it's possible to obtain the read lock in smart mode and then * runs the [action] holding the lock and **preventing** write actions. * See [constrainedReadActionBlocking] for semantic details. * * @see smartReadAction */ suspend fun <T> smartReadActionBlocking(project: Project, action: () -> T): T { return constrainedReadActionBlocking(ReadConstraint.inSmartMode(project), action = action) } /** * Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction] * **preventing** write actions. * * The function suspends if at the moment of calling it's not possible to acquire the read lock, * or if [constraints] are not [satisfied][ReadConstraint.isSatisfied]. * If the write action happens while the [action] is running, then the [action] is **not** canceled, * meaning the [action] will block pending write actions until finished. * * The function returns when given [action] was completed fully. * To support cancellation, the [action] must regularly invoke [com.intellij.openapi.progress.ProgressManager.checkCanceled]. * * The [action] is dispatched to [Dispatchers.Default], because a read action is expected to be a CPU-bound task. * * @see constrainedReadAction */ suspend fun <T> constrainedReadActionBlocking(vararg constraints: ReadConstraint, action: () -> T): T { return readActionSupport().executeReadAction(constraints.toList(), blocking = true, action) } /** * Runs given [action] under [write lock][com.intellij.openapi.application.Application.runWriteAction]. * * Currently, the [action] is dispatched by [Dispatchers.EDT] within the [context modality state][asContextElement]. * If the calling coroutine is already executed by [Dispatchers.EDT], then no re-dispatch happens. * Acquiring the write-lock happens in blocking manner, * i.e. [runWriteAction][com.intellij.openapi.application.Application.runWriteAction] call will block * until all currently running read actions are finished. * * NB This function is an API stub. * The implementation will change once running write actions would be allowed on other threads. * This function exists to make it possible to use it in suspending contexts * before the platform is ready to handle write actions differently. */ @Experimental suspend fun <T> writeAction(action: () -> T): T { return withContext(Dispatchers.EDT) { blockingContext { ApplicationManager.getApplication().runWriteAction(Computable(action)) } } } private fun readActionSupport() = ApplicationManager.getApplication().getService(ReadActionSupport::class.java) /** * The code within [ModalityState.any] context modality state must only perform pure UI operations, * it must not access any PSI, VFS, project model, or indexes. It also must not show any modal dialogs. */ fun ModalityState.asContextElement(): CoroutineContext = coroutineSupport().asContextElement(this) /** * UI dispatcher which dispatches onto Swing event dispatching thread within the [context modality state][asContextElement]. * If no context modality state is specified, then the coroutine is dispatched within [ModalityState.NON_MODAL] modality state. * * This dispatcher is also installed as [Dispatchers.Main]. * Use [Dispatchers.EDT] when in doubt, use [Dispatchers.Main] if the coroutine doesn't care about IJ model, * e.g. when it is also able to be executed outside of IJ process. */ @Suppress("UnusedReceiverParameter") val Dispatchers.EDT: CoroutineContext get() = coroutineSupport().edtDispatcher() private fun coroutineSupport() = ApplicationManager.getApplication().getService(CoroutineSupport::class.java)
apache-2.0
b24ebe3abf09430e6f151634419944a2
44.818841
127
0.762296
4.421678
false
false
false
false
android/nowinandroid
core/domain/src/main/java/com/google/samples/apps/nowinandroid/core/domain/GetSaveableNewsResourcesStreamUseCase.kt
1
3191
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.domain import com.google.samples.apps.nowinandroid.core.data.repository.NewsRepository import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource import com.google.samples.apps.nowinandroid.core.model.data.NewsResource import javax.inject.Inject import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filterNot import kotlinx.coroutines.flow.map /** * A use case responsible for obtaining news resources with their associated bookmarked (also known * as "saved") state. */ class GetSaveableNewsResourcesStreamUseCase @Inject constructor( private val newsRepository: NewsRepository, userDataRepository: UserDataRepository ) { private val bookmarkedNewsResourcesStream = userDataRepository.userDataStream.map { it.bookmarkedNewsResources } /** * Returns a list of SaveableNewsResources which match the supplied set of topic ids or author * ids. * * @param filterTopicIds - A set of topic ids used to filter the list of news resources. If * this is empty AND filterAuthorIds is empty the list of news resources will not be filtered. * @param filterAuthorIds - A set of author ids used to filter the list of news resources. If * this is empty AND filterTopicIds is empty the list of news resources will not be filtered. * */ operator fun invoke( filterTopicIds: Set<String> = emptySet(), filterAuthorIds: Set<String> = emptySet() ): Flow<List<SaveableNewsResource>> = if (filterTopicIds.isEmpty() && filterAuthorIds.isEmpty()) { newsRepository.getNewsResourcesStream() } else { newsRepository.getNewsResourcesStream( filterTopicIds = filterTopicIds, filterAuthorIds = filterAuthorIds ) }.mapToSaveableNewsResources(bookmarkedNewsResourcesStream) } private fun Flow<List<NewsResource>>.mapToSaveableNewsResources( savedNewsResourceIdsStream: Flow<Set<String>> ): Flow<List<SaveableNewsResource>> = filterNot { it.isEmpty() } .combine(savedNewsResourceIdsStream) { newsResources, savedNewsResourceIds -> newsResources.map { newsResource -> SaveableNewsResource( newsResource = newsResource, isSaved = savedNewsResourceIds.contains(newsResource.id) ) } }
apache-2.0
76511d22e8907156b6dad3da0f9e11a9
40.441558
99
0.722344
4.871756
false
false
false
false
android/nowinandroid
feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt
1
6970
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.feature.bookmarks import androidx.annotation.VisibleForTesting import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.grid.GridCells.Adaptive import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaLoadingWheel import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState.Loading import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState.Success import com.google.samples.apps.nowinandroid.core.ui.TrackScrollJank import com.google.samples.apps.nowinandroid.core.ui.newsFeed @OptIn(ExperimentalLifecycleComposeApi::class) @Composable internal fun BookmarksRoute( modifier: Modifier = Modifier, viewModel: BookmarksViewModel = hiltViewModel() ) { val feedState by viewModel.feedUiState.collectAsStateWithLifecycle() BookmarksScreen( feedState = feedState, removeFromBookmarks = viewModel::removeFromSavedResources, modifier = modifier ) } /** * Displays the user's bookmarked articles. Includes support for loading and empty states. */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) @Composable internal fun BookmarksScreen( feedState: NewsFeedUiState, removeFromBookmarks: (String) -> Unit, modifier: Modifier = Modifier ) { when (feedState) { Loading -> LoadingState(modifier) is Success -> if (feedState.feed.isNotEmpty()) { BookmarksGrid(feedState, removeFromBookmarks, modifier) } else { EmptyState(modifier) } } } @Composable private fun LoadingState(modifier: Modifier = Modifier) { NiaLoadingWheel( modifier = modifier .fillMaxWidth() .wrapContentSize() .testTag("forYou:loading"), contentDesc = stringResource(id = R.string.saved_loading), ) } @Composable private fun BookmarksGrid( feedState: NewsFeedUiState, removeFromBookmarks: (String) -> Unit, modifier: Modifier = Modifier ) { val scrollableState = rememberLazyGridState() TrackScrollJank(scrollableState = scrollableState, stateName = "bookmarks:grid") LazyVerticalGrid( columns = Adaptive(300.dp), contentPadding = PaddingValues(16.dp), horizontalArrangement = Arrangement.spacedBy(32.dp), verticalArrangement = Arrangement.spacedBy(24.dp), state = scrollableState, modifier = modifier .fillMaxSize() .testTag("bookmarks:feed") ) { newsFeed( feedState = feedState, onNewsResourcesCheckedChanged = { id, _ -> removeFromBookmarks(id) }, ) item(span = { GridItemSpan(maxLineSpan) }) { Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing)) } } } @Composable private fun EmptyState(modifier: Modifier = Modifier) { Column( modifier = modifier .padding(16.dp) .fillMaxSize() .testTag("bookmarks:empty"), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( modifier = Modifier.fillMaxWidth(), painter = painterResource(id = R.drawable.img_empty_bookmarks), contentDescription = null ) Spacer(modifier = Modifier.height(16.dp)) Text( text = stringResource(id = R.string.bookmarks_empty_error), modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(8.dp)) Text( text = stringResource(id = R.string.bookmarks_empty_description), modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.bodyMedium ) } } @Preview @Composable private fun LoadingStatePreview() { NiaTheme { LoadingState() } } @Preview @Composable private fun BookmarksGridPreview() { NiaTheme { BookmarksGrid( feedState = Success( previewNewsResources.map { SaveableNewsResource(it, false) } ), removeFromBookmarks = {} ) } } @Preview @Composable fun EmptyStatePreview() { NiaTheme { EmptyState() } }
apache-2.0
80a7fad1115e967a85a96ce6cacb73c4
33.50495
90
0.725538
4.722222
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database-tests/src/test/kotlin/database/save/StandardIdentifierConcurrencyTest.kt
1
17562
package database.save import com.onyx.exception.NoResultsException import com.onyx.persistence.IManagedEntity import database.base.DatabaseBaseTest import entities.AllAttributeEntity import org.junit.* import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.junit.runners.Parameterized import java.util.* import java.util.concurrent.Executors import java.util.concurrent.Future import kotlin.reflect.KClass import kotlin.test.assertEquals import kotlin.test.assertTrue @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(Parameterized::class) class StandardIdentifierConcurrencyTest(override var factoryClass: KClass<*>) : DatabaseBaseTest(factoryClass) { companion object { private val threadPool = Executors.newFixedThreadPool(10) } /** * Tests Batch inserting 10,000 record with a String identifier * last test took: 759(mac) */ @Test fun aConcurrencyStandardPerformanceTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<AllAttributeEntity>() val before = System.currentTimeMillis() for (i in 0..10000) { val entity = AllAttributeEntity() entity.id = randomString + i entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) if (i % 500 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) }) } } threads.forEach { it.get() } val after = System.currentTimeMillis() assertTrue(after - before < 350, "Should not take more than 1.5 seconds to complete") } /** * Runs 10 threads that insert 10k entities with a String identifier. * After insertion, this test validates the data integrity. * last test took: 698(win) 2231(mac) */ @Test fun concurrencyStandardSaveIntegrityTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<AllAttributeEntity>() val entitiesToValidate = ArrayList<AllAttributeEntity>() for (i in 0..5000) { val entity = AllAttributeEntity() entity.id = randomString + i entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) entitiesToValidate.add(entity) if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() tmpList.forEach { manager.saveEntity(it) } } } threads.forEach { it.get() } // Validate entities to ensure it was persisted correctly entitiesToValidate.parallelStream().forEach { var newEntity = AllAttributeEntity() newEntity.id = it.id newEntity = manager.find(newEntity) assertEquals(it.id, newEntity.id, "ID was not as expected ${it.id}") assertEquals(it.longPrimitive, newEntity.longPrimitive, "longPrimitive was not as expected ${it.longPrimitive}") } } @Test fun concurrencyStandardSaveIntegrityTestWithBatching() { val threads = ArrayList<Future<*>>() val entities = ArrayList<AllAttributeEntity>() val entitiesToValidate = ArrayList<AllAttributeEntity>() for (i in 1..10000) { val entity = AllAttributeEntity() entity.id = randomString + i entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) entitiesToValidate.add(entity) if (i % 1000 == 0) { val tmpList = ArrayList<AllAttributeEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) }) } } threads.forEach { it.get() } // Validate entities to ensure it was persisted correctly entitiesToValidate.parallelStream().forEach { var newEntity = AllAttributeEntity() newEntity.id = it.id newEntity = manager.find(newEntity) assertEquals(it.id, newEntity.id, "ID was not as expected ${it.id}") assertEquals(it.longPrimitive, newEntity.longPrimitive, "longPrimitive was not as expected ${it.longPrimitive}") } } @Test fun concurrencyStandardDeleteIntegrityTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<AllAttributeEntity>() val entitiesToValidate = ArrayList<AllAttributeEntity>() val entitiesToValidateDeleted = ArrayList<AllAttributeEntity>() for (i in 0..10000) { val entity = AllAttributeEntity() entity.id = randomString + i entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) if (i % 2 == 0) { entitiesToValidateDeleted.add(entity) } else { entitiesToValidate.add(entity) } if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { tmpList.forEach { manager.saveEntity(it) } }) } } threads.forEach { it.get() } threads.clear() entities.clear() var deleteCount = 0 for (i in 0..10000) { val entity = AllAttributeEntity() entity.id = randomString + i entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) entitiesToValidate.add(entity) if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() val deletedIndex = deleteCount threads.add(async(threadPool) { tmpList.forEach { manager.saveEntity(it) } var t = deletedIndex while (t < deletedIndex + 5 && t < entitiesToValidateDeleted.size) { manager.deleteEntity(entitiesToValidateDeleted[t]) t++ } }) deleteCount += 5 } } threads.forEach { it.get() } entitiesToValidate.parallelStream().forEach { var newEntity = AllAttributeEntity() newEntity.id = it.id newEntity = manager.find(newEntity) assertEquals(it.longPrimitive, newEntity.longPrimitive, "longPrimitive was not persisted correctly") } entitiesToValidateDeleted.parallelStream().forEach { val newEntity = AllAttributeEntity() newEntity.id = it.id var pass = false try { manager.find<IManagedEntity>(newEntity) } catch (e: NoResultsException) { pass = true } assertTrue(pass, "Entity ${newEntity.id} was not deleted") } } @Test fun concurrencyStandardDeleteBatchIntegrityTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<AllAttributeEntity>() val entitiesToValidate = ArrayList<AllAttributeEntity>() val entitiesToValidateDeleted = ArrayList<AllAttributeEntity>() val ignore = HashMap<String, AllAttributeEntity>() for (i in 0..10000) { val entity = AllAttributeEntity() entity.id = randomString + i entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) if (i % 2 == 0) { entitiesToValidateDeleted.add(entity) ignore.put(entity.id!!, entity) } else { entitiesToValidate.add(entity) } if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) }) } } threads.forEach { it.get() } threads.clear() entities.clear() for (i in 0..10000) { val entity = AllAttributeEntity() entity.id = randomString + i entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) entitiesToValidate.add(entity) if (i % 10 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) for(k in 0 .. 6) { var entityToDelete:IManagedEntity? = null synchronized(entitiesToValidateDeleted) { if (entitiesToValidateDeleted.size > 0) { entityToDelete = entitiesToValidateDeleted.removeAt(0) } } if(entityToDelete != null) manager.deleteEntity(entityToDelete!!) } }) } } threads.forEach { it.get() } entitiesToValidate.parallelStream().forEach { var newEntity = AllAttributeEntity() newEntity.id = it.id if (!ignore.containsKey(newEntity.id)) { newEntity = manager.find(newEntity) assertEquals(it.longPrimitive, newEntity.longPrimitive, "Entity did not hydrate correctly") } } entitiesToValidateDeleted.parallelStream().forEach { val newEntity = AllAttributeEntity() newEntity.id = it.id var pass = false try { manager.find<IManagedEntity>(newEntity) } catch (e: NoResultsException) { pass = true } assertTrue(pass, "Entity ${newEntity.id} was not deleted") } } /** * Executes 10 threads that insert 30k entities with string id, then 10k are updated and 10k are deleted. * Then it validates the integrity of those actions */ @Test fun concurrencyStandardAllIntegrityTest() { val threads = ArrayList<Future<*>>() val entities = ArrayList<AllAttributeEntity>() val entitiesToValidate = ArrayList<AllAttributeEntity>() val entitiesToValidateDeleted = ArrayList<AllAttributeEntity>() val entitiesToValidateUpdated = ArrayList<AllAttributeEntity>() val ignore = HashMap<String, AllAttributeEntity>() for (i in 0..30000) { val entity = AllAttributeEntity() entity.id = randomString + i entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) // Delete Even ones when { i % 2 == 0 -> { entitiesToValidateDeleted.add(entity) ignore.put(entity.id!!, entity) } i % 3 == 0 && i % 2 != 0 -> entitiesToValidateUpdated.add(entity) else -> entitiesToValidate.add(entity) } if (i % 1000 == 0) { val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() threads.add(async(threadPool) { manager.saveEntities(tmpList) }) } } threads.forEach { it.get() } threads.clear() entities.clear() entitiesToValidateDeleted -= entitiesToValidateUpdated entitiesToValidateUpdated -= entitiesToValidateDeleted val entitiesToBeDeleted = ArrayList<AllAttributeEntity>(entitiesToValidateDeleted) entitiesToValidateUpdated.forEach { it.longPrimitive = 45645 } var updateCount = 0 for (i in 0..30000) { val entity = AllAttributeEntity() entity.id = randomString + i entity.longValue = 4L entity.longPrimitive = 3L entity.stringValue = "String key" entity.dateValue = Date(1483736263743L) entity.doublePrimitive = 342.23 entity.doubleValue = 232.2 entity.booleanPrimitive = true entity.booleanValue = false entities.add(entity) if (i % 20 == 0) { entitiesToValidate.add(entity) val tmpList = ArrayList<IManagedEntity>(entities) entities.clear() val updatedIndex = updateCount threads.add(async(threadPool) { manager.saveEntities(tmpList) var t = updatedIndex while (t < updatedIndex + 13 && t < entitiesToValidateUpdated.size) { manager.saveEntity<IManagedEntity>(entitiesToValidateUpdated[t]) t++ } for(k in 0..31) { var entityToDelete:AllAttributeEntity? = null synchronized(entitiesToBeDeleted) { if(!entitiesToBeDeleted.isEmpty()) entityToDelete = entitiesToBeDeleted.removeAt(0) } if(entityToDelete != null) manager.deleteEntity(entityToDelete!!) } }) updateCount += 13 } } entitiesToValidateDeleted -= entitiesToValidateUpdated threads.forEach { it.get() } var failedEntities = 0 entitiesToValidate.parallelStream().forEach { val newEntity = AllAttributeEntity() newEntity.id = it.id if (!ignore.containsKey(newEntity.id)) { try { manager.find<IManagedEntity>(newEntity) } catch (e: Exception) { failedEntities++ } } } assertEquals(0, failedEntities, "There were several entities that failed to be found") entitiesToValidateDeleted.parallelStream().forEach { val newEntity = AllAttributeEntity() newEntity.id = it.id var pass = false try { manager.find<IManagedEntity>(newEntity) } catch (e: NoResultsException) { pass = true } if (!pass) { failedEntities++ manager.deleteEntity(newEntity) manager.find<IManagedEntity>(newEntity) } } assertEquals(0, failedEntities, "There were several entities that failed to be deleted") entitiesToValidateUpdated.parallelStream().forEach { var newEntity = AllAttributeEntity() newEntity.id = it.id newEntity = manager.find(newEntity) assertEquals(45645L, newEntity.longPrimitive, "Entity failed to update") } } }
agpl-3.0
584ab593e73ebe22f10f2217c974f188
32.903475
124
0.551304
5.72425
false
false
false
false
ktorio/ktor
ktor-io/jvm/src/io/ktor/utils/io/ConsumeEach.kt
1
1454
package io.ktor.utils.io import io.ktor.utils.io.bits.* import java.nio.* /** * Visitor function that is invoked for every available buffer (or chunk) of a channel. * The last parameter shows that the buffer is known to be the last. */ public typealias ConsumeEachBufferVisitor = (buffer: ByteBuffer, last: Boolean) -> Boolean /** * For every available bytes range invokes [visitor] function until it return false or end of stream encountered. * The provided buffer should be never captured outside of the visitor block otherwise resource leaks, crashes and * data corruptions may occur. The visitor block may be invoked multiple times, once or never. */ @Suppress("EXTENSION_SHADOWED_BY_MEMBER") public suspend inline fun ByteReadChannel.consumeEachBufferRange(visitor: ConsumeEachBufferVisitor) { var continueFlag: Boolean var lastChunkReported = false do { continueFlag = false read { source, start, endExclusive -> val nioBuffer = when { endExclusive > start -> source.slice(start, endExclusive - start).buffer else -> Memory.Empty.buffer } lastChunkReported = nioBuffer.remaining() == availableForRead && isClosedForWrite continueFlag = visitor(nioBuffer, lastChunkReported) nioBuffer.position() } if (lastChunkReported && isClosedForRead) { break } } while (continueFlag) }
apache-2.0
5bc357b6a9782ba57aa34e79dc365dca
35.35
114
0.689133
4.81457
false
false
false
false
ktorio/ktor
ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/internals/Chars.kt
1
3776
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http.cio.internals import io.ktor.http.* import io.ktor.utils.io.* internal const val HTAB: Char = '\u0009' internal fun CharSequence.hashCodeLowerCase(start: Int = 0, end: Int = length): Int { var hashCode = 0 for (pos in start until end) { val v = get(pos).code.toLowerCase() hashCode = 31 * hashCode + v } return hashCode } internal fun CharSequence.equalsLowerCase(start: Int = 0, end: Int = length, other: CharSequence): Boolean { if (end - start != other.length) return false for (pos in start until end) { if (get(pos).code.toLowerCase() != other[pos - start].code.toLowerCase()) return false } return true } @Suppress("NOTHING_TO_INLINE") private inline fun Int.toLowerCase() = if (this in 'A'.code..'Z'.code) 'a'.code + (this - 'A'.code) else this internal val DefaultHttpMethods = AsciiCharTree.build(HttpMethod.DefaultMethods, { it.value.length }, { m, idx -> m.value[idx] }) private val HexTable = (0..0xff).map { v -> when { v in 0x30..0x39 -> v - 0x30L v >= 'a'.code.toLong() && v <= 'f'.code.toLong() -> v - 'a'.code.toLong() + 10 v >= 'A'.code.toLong() && v <= 'F'.code.toLong() -> v - 'A'.code.toLong() + 10 else -> -1L } }.toLongArray() internal val HexLetterTable: ByteArray = (0..0xf).map { if (it < 0xa) (0x30 + it).toByte() else ('a' + it - 0x0a).code.toByte() }.toByteArray() internal fun CharSequence.parseHexLong(): Long { var result = 0L val table = HexTable for (i in 0 until length) { val v = this[i].code and 0xffff val digit = if (v < 0xff) table[v] else -1L if (digit == -1L) hexNumberFormatException(this, i) result = (result shl 4) or digit } return result } /** * Converts [CharSequence] representation in decimal format to [Long] */ public fun CharSequence.parseDecLong(): Long { val length = length if (length > 19) numberFormatException(this) if (length == 19) return parseDecLongWithCheck() var result = 0L for (i in 0 until length) { val digit = this[i].code.toLong() - 0x30L if (digit < 0 || digit > 9) numberFormatException(this, i) result = (result shl 3) + (result shl 1) + digit } return result } private fun CharSequence.parseDecLongWithCheck(): Long { var result = 0L for (i in 0 until length) { val digit = this[i].code.toLong() - 0x30L if (digit < 0 || digit > 9) numberFormatException(this, i) result = (result shl 3) + (result shl 1) + digit if (result < 0) numberFormatException(this) } return result } internal suspend fun ByteWriteChannel.writeIntHex(value: Int) { require(value > 0) { "Does only work for positive numbers" } // zero is not included! var current = value val table = HexLetterTable var digits = 0 while (digits++ < 8) { val v = current ushr 28 current = current shl 4 if (v != 0) { writeByte(table[v]) break } } while (digits++ < 8) { val v = current ushr 28 current = current shl 4 writeByte(table[v]) } } private fun hexNumberFormatException(s: CharSequence, idx: Int): Nothing { throw NumberFormatException("Invalid HEX number: $s, wrong digit: ${s[idx]}") } private fun numberFormatException(cs: CharSequence, idx: Int) { throw NumberFormatException("Invalid number: $cs, wrong digit: ${cs[idx]} at position $idx") } private fun numberFormatException(cs: CharSequence) { throw NumberFormatException("Invalid number $cs: too large for Long type") }
apache-2.0
002595a139a24a8585b7b682c16edbf2
28.046154
118
0.623146
3.613397
false
false
false
false
ktorio/ktor
ktor-io/js/src/io/ktor/utils/io/charsets/CharsetJS.kt
1
10136
package io.ktor.utils.io.charsets import io.ktor.utils.io.core.* import io.ktor.utils.io.js.* import org.khronos.webgl.* public actual abstract class Charset(internal val _name: String) { public actual abstract fun newEncoder(): CharsetEncoder public actual abstract fun newDecoder(): CharsetDecoder override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class.js != other::class.js) return false other as Charset if (_name != other._name) return false return true } override fun hashCode(): Int { return _name.hashCode() } override fun toString(): String { return _name } public actual companion object { @Suppress("LocalVariableName") public actual fun forName(name: String): Charset { if (name == "UTF-8" || name == "utf-8" || name == "UTF8" || name == "utf8") return Charsets.UTF_8 if (name == "ISO-8859-1" || name == "iso-8859-1" || name.replace('_', '-').let { it == "iso-8859-1" || it.lowercase() == "iso-8859-1" } || name == "latin1" || name == "Latin1" ) { return Charsets.ISO_8859_1 } throw IllegalArgumentException("Charset $name is not supported") } public actual fun isSupported(charset: String): Boolean = when { charset == "UTF-8" || charset == "utf-8" || charset == "UTF8" || charset == "utf8" -> true charset == "ISO-8859-1" || charset == "iso-8859-1" || charset.replace('_', '-').let { it == "iso-8859-1" || it.lowercase() == "iso-8859-1" } || charset == "latin1" -> true else -> false } } } public actual val Charset.name: String get() = _name // ----------------------- public actual abstract class CharsetEncoder(internal val _charset: Charset) private data class CharsetEncoderImpl(private val charset: Charset) : CharsetEncoder(charset) public actual val CharsetEncoder.charset: Charset get() = _charset public actual fun CharsetEncoder.encodeToByteArray(input: CharSequence, fromIndex: Int, toIndex: Int): ByteArray = encodeToByteArrayImpl1(input, fromIndex, toIndex) internal actual fun CharsetEncoder.encodeImpl(input: CharSequence, fromIndex: Int, toIndex: Int, dst: Buffer): Int { require(fromIndex <= toIndex) if (charset == Charsets.ISO_8859_1) { return encodeISO88591(input, fromIndex, toIndex, dst) } require(charset === Charsets.UTF_8) { "Only UTF-8 encoding is supported in JS" } val encoder = TextEncoder() // Only UTF-8 is supported so we know that at most 6 bytes per character is used var start = fromIndex var dstRemaining = dst.writeRemaining while (start < toIndex && dstRemaining > 0) { val numChars = minOf(toIndex - start, dstRemaining / 6).coerceAtLeast(1) val dropLastChar = input[start + numChars - 1].isHighSurrogate() val endIndexExclusive = when { dropLastChar && numChars == 1 -> start + 2 dropLastChar -> start + numChars - 1 else -> start + numChars } val array1 = encoder.encode(input.substring(start, endIndexExclusive)) if (array1.length > dstRemaining) break dst.writeFully(array1) start = endIndexExclusive dstRemaining -= array1.length } return start - fromIndex } public actual fun CharsetEncoder.encodeUTF8(input: ByteReadPacket, dst: Output) { require(charset === Charsets.UTF_8) // we only support UTF-8 so as far as input is UTF-8 encoded string then we simply copy bytes dst.writePacket(input) } internal actual fun CharsetEncoder.encodeComplete(dst: Buffer): Boolean = true // ---------------------------------------------------------------------- public actual abstract class CharsetDecoder(internal val _charset: Charset) private data class CharsetDecoderImpl(private val charset: Charset) : CharsetDecoder(charset) public actual val CharsetDecoder.charset: Charset get() = _charset internal actual fun CharsetDecoder.decodeBuffer( input: Buffer, out: Appendable, lastBuffer: Boolean, max: Int ): Int { if (max == 0) return 0 val decoder = Decoder(charset.name) val copied: Int input.readDirectInt8Array { view -> val result = view.decodeBufferImpl(decoder, max) out.append(result.charactersDecoded) copied = result.bytesConsumed result.bytesConsumed } return copied } public actual fun CharsetDecoder.decode(input: Input, dst: Appendable, max: Int): Int { val decoder = Decoder(charset.name, true) var charactersCopied = 0 // use decode stream while we have remaining characters count > buffer size in bytes // it is much faster than using decodeBufferImpl input.takeWhileSize { buffer -> val rem = max - charactersCopied val bufferSize = buffer.readRemaining if (rem < bufferSize) return@takeWhileSize 0 buffer.readDirectInt8Array { view -> val decodedText = decodeWrap { decoder.decodeStream(view, stream = true) } dst.append(decodedText) charactersCopied += decodedText.length view.byteLength } when { charactersCopied == max -> { val tail = try { decoder.decode() } catch (_: dynamic) { "" } if (tail.isNotEmpty()) { // if we have a trailing byte then we can't handle this chunk via fast-path // because we don't know how many bytes in the end we need to preserve buffer.rewind(bufferSize) } 0 } charactersCopied < max -> MAX_CHARACTERS_SIZE_IN_BYTES else -> 0 } } if (charactersCopied < max) { var size = 1 input.takeWhileSize(1) { buffer -> val rc = buffer.readDirectInt8Array { view -> val result = view.decodeBufferImpl(decoder, max - charactersCopied) dst.append(result.charactersDecoded) charactersCopied += result.charactersDecoded.length result.bytesConsumed } when { rc > 0 -> size = 1 size == MAX_CHARACTERS_SIZE_IN_BYTES -> size = 0 else -> size++ } size } } return charactersCopied } public actual fun CharsetDecoder.decodeExactBytes(input: Input, inputLength: Int): String { if (inputLength == 0) return "" if (input.headRemaining >= inputLength) { val decoder = Decoder(charset._name, true) val head = input.head val view = input.headMemory.view val text = decodeWrap { val subView: ArrayBufferView = when { head.readPosition == 0 && inputLength == view.byteLength -> view else -> DataView(view.buffer, view.byteOffset + head.readPosition, inputLength) } decoder.decode(subView) } input.discardExact(inputLength) return text } return decodeExactBytesSlow(input, inputLength) } // ----------------------------------------------------------- public actual object Charsets { public actual val UTF_8: Charset = CharsetImpl("UTF-8") public actual val ISO_8859_1: Charset = CharsetImpl("ISO-8859-1") } private data class CharsetImpl(val name: String) : Charset(name) { override fun newEncoder(): CharsetEncoder = CharsetEncoderImpl(this) override fun newDecoder(): CharsetDecoder = CharsetDecoderImpl(this) } public actual open class MalformedInputException actual constructor(message: String) : Throwable(message) private fun CharsetDecoder.decodeExactBytesSlow(input: Input, inputLength: Int): String { val decoder = Decoder(charset.name, true) var inputRemaining = inputLength val sb = StringBuilder(inputLength) decodeWrap { input.takeWhileSize(6) { buffer -> val chunkSize = buffer.readRemaining val size = minOf(chunkSize, inputRemaining) val text = when { buffer.readPosition == 0 && buffer.memory.view.byteLength == size -> decoder.decodeStream( buffer.memory.view, true ) else -> decoder.decodeStream( Int8Array( buffer.memory.view.buffer, buffer.memory.view.byteOffset + buffer.readPosition, size ), true ) } sb.append(text) buffer.discardExact(size) inputRemaining -= size if (inputRemaining > 0) 6 else 0 } if (inputRemaining > 0) { input.takeWhile { buffer -> val chunkSize = buffer.readRemaining val size = minOf(chunkSize, inputRemaining) val text = when { buffer.readPosition == 0 && buffer.memory.view.byteLength == size -> { decoder.decode(buffer.memory.view) } else -> decoder.decodeStream( Int8Array( buffer.memory.view.buffer, buffer.memory.view.byteOffset + buffer.readPosition, size ), true ) } sb.append(text) buffer.discardExact(size) inputRemaining -= size true } } sb.append(decoder.decode()) } if (inputRemaining > 0) { throw EOFException( "Not enough bytes available: had only ${inputLength - inputRemaining} instead of $inputLength" ) } return sb.toString() }
apache-2.0
3798e3f64ab509ae1ed98994c6a6664b
33.013423
116
0.572119
4.803791
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/OES_texture_float.kt
4
2114
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val OES_texture_float = EXT_FLAG.nativeClassGLES("OES_texture_float", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. These extensions add texture formats with 16- (aka half float) and 32-bit floating-point components. The 32-bit floating-point components are in the standard IEEE float format. The 16-bit floating-point components have 1 sign bit, 5 exponent bits, and 10 mantissa bits. Floating-point components are clamped to the limits of the range representable by their format. The OES_texture_float extension string indicates that the implementation supports 32-bit floating pt texture formats. Both these extensions only require NEAREST magnification filter and NEAREST, and NEAREST_MIPMAP_NEAREST minification filters to be supported. """ } val OES_texture_half_float = "OESTextureHalfFloat".nativeClassGLES("OES_texture_half_float", postfix = OES) { documentation = """ Native bindings to the ${registryLink("OES_texture_float")} extension. These extensions add texture formats with 16- (aka half float) and 32-bit floating-point components. The 32-bit floating-point components are in the standard IEEE float format. The 16-bit floating-point components have 1 sign bit, 5 exponent bits, and 10 mantissa bits. Floating-point components are clamped to the limits of the range representable by their format. The OES_texture_half_float extension string indicates that the implementation supports 16-bit floating pt texture formats. Both these extensions only require NEAREST magnification filter and NEAREST, and NEAREST_MIPMAP_NEAREST minification filters to be supported. """ IntConstant( "Accepted by the {@code type} parameter of TexImage2D, TexSubImage2D, TexImage3D, and TexSubImage3D.", "HALF_FLOAT_OES"..0x8D61 ) }
bsd-3-clause
12e86cab204266e61c7a44472793bcbb
47.068182
158
0.732734
4.676991
false
false
false
false
Frederikam/FredBoat
FredBoat/src/main/java/fredboat/command/moderation/UnbanCommand.kt
1
5325
/* * * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package fredboat.command.moderation import com.fredboat.sentinel.SentinelExchanges import com.fredboat.sentinel.entities.ModRequest import com.fredboat.sentinel.entities.ModRequestType import fredboat.commandmeta.abs.CommandContext import fredboat.messaging.internal.Context import fredboat.perms.Permission import fredboat.sentinel.User import fredboat.util.ArgumentUtil import fredboat.util.TextUtils import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.amqp.core.MessageDeliveryMode import reactor.core.publisher.Mono /** * Created by napster on 27.01.18. * * Unban a user. */ class UnbanCommand(name: String, vararg aliases: String) : DiscordModerationCommand(name, *aliases) { companion object { private val log: Logger = LoggerFactory.getLogger(UnbanCommand::class.java) } override fun modAction(args: DiscordModerationCommand.ModActionInfo): Mono<Unit> { return args.context.sentinel.genericMonoSendAndReceive<String, Unit>( exchange = SentinelExchanges.REQUESTS, request = ModRequest( guildId = args.context.guild.id, userId = args.targetUser.id, type = ModRequestType.UNBAN, reason = args.formattedReason ), routingKey = args.context.routingKey, mayBeEmpty = true, deliveryMode = MessageDeliveryMode.PERSISTENT, transform = {} ) } override fun requiresMember() = false override fun onSuccess(args: DiscordModerationCommand.ModActionInfo): () -> Unit { val successOutput = args.context.i18nFormat("unbanSuccess", args.targetUser.asMention + " " + TextUtils.escapeAndDefuse(args.targetAsString())) return { args.context.replyWithName(successOutput) } } override fun onFail(args: DiscordModerationCommand.ModActionInfo): (t: Throwable) -> Unit { val escapedTargetName = TextUtils.escapeAndDefuse(args.targetAsString()) return { t -> val context = args.context if (t is IllegalArgumentException) { //user was not banned in this guild (see GuildController#unban(String) handling of the response) context.reply(context.i18nFormat("modUnbanFailNotBanned", args.targetUser.asMention)) } else { log.error("Failed to unban ${args.targetUser} from ${args.context.guild}") context.replyWithName(context.i18nFormat("modUnbanFail", args.targetUser.asMention + " " + escapedTargetName)) } } } override suspend fun fromFuzzySearch(context: CommandContext, searchTerm: String): Mono<User> { return fetchBanlist(context) .collectList() .map { banlist -> ArgumentUtil.checkSingleFuzzyUserSearchResult( banlist.map { User(it.user) }, context, searchTerm, true).orElse(null) } } override suspend fun checkPreconditionWithFeedback(user: User, context: CommandContext): Mono<Boolean> { return fetchBanlist(context) .collectList() .map { banlist -> if (banlist.stream().noneMatch { it.user.id == user.id }) { context.reply(context.i18nFormat("modUnbanFailNotBanned", user.asMention)) return@map false } true } } override suspend fun checkAuthorizationWithFeedback(args: DiscordModerationCommand.ModActionInfo): Boolean { return args.context.run { checkInvokerPermissionsWithFeedback(Permission.BAN_MEMBERS) && checkSelfPermissionsWithFeedback(Permission.BAN_MEMBERS) } } //don't dm users upon being unbanned override fun dmForTarget(args: DiscordModerationCommand.ModActionInfo): String? = null override fun help(context: Context): String { return ("{0}{1} userId OR username\n" + "#" + context.i18n("helpUnbanCommand")) } }
mit
1721e45b332b41d4ebdeb28e60e2bf00
40.27907
145
0.664225
4.849727
false
false
false
false
marc-inn/learning-kotlin-from-jb
src/i_introduction/_2_Named_Arguments/NamedArguments.kt
1
679
package i_introduction._2_Named_Arguments import util.* import i_introduction._1_Java_To_Kotlin_Converter.task1 fun todoTask2(): Nothing = TODO( """ Task 2. Implement the same logic as in 'task1' again through the library method 'joinToString()'. Change values of some of the 'joinToString' arguments. Use default and named arguments to improve the readability of the function invocation. """, documentation = doc2(), references = { collection: Collection<Int> -> task1(collection); collection.joinToString() }) fun task2(collection: Collection<Int>): String { return collection.joinToString (prefix = "{", postfix = "}") }
mit
a38e37669d2a4153da7e7e414b6cbd25
36.722222
97
0.693667
4.409091
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/page/leadimages/PageHeaderView.kt
1
3020
package org.wikipedia.page.leadimages import android.content.Context import android.net.Uri import android.util.AttributeSet import android.view.Gravity import android.view.LayoutInflater import android.view.ViewGroup import androidx.coordinatorlayout.widget.CoordinatorLayout import org.wikipedia.R import org.wikipedia.databinding.ViewPageHeaderBinding import org.wikipedia.util.DimenUtil import org.wikipedia.util.GradientUtil import org.wikipedia.views.FaceAndColorDetectImageView import org.wikipedia.views.LinearLayoutOverWebView import org.wikipedia.views.ObservableWebView class PageHeaderView : LinearLayoutOverWebView, ObservableWebView.OnScrollChangeListener { interface Callback { fun onImageClicked() fun onCallToActionClicked() } private val binding = ViewPageHeaderBinding.inflate(LayoutInflater.from(context), this) var callback: Callback? = null constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) init { binding.viewPageHeaderImageGradientBottom.background = GradientUtil.getPowerGradient(R.color.black38, Gravity.BOTTOM) binding.viewPageHeaderImage.setOnClickListener { callback?.onImageClicked() } binding.callToActionContainer.setOnClickListener { callback?.onCallToActionClicked() } } override fun onScrollChanged(oldScrollY: Int, scrollY: Int, isHumanScroll: Boolean) { updateScroll(scrollY) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) updateScroll() } private fun updateScroll(scrollY: Int = -translationY.toInt()) { binding.viewPageHeaderImage.translationY = 0f translationY = -height.coerceAtMost(scrollY).toFloat() } fun hide() { visibility = GONE } fun show() { layoutParams = CoordinatorLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.leadImageHeightForDevice(context)) visibility = VISIBLE } fun getImageView(): FaceAndColorDetectImageView { return binding.viewPageHeaderImage } fun setUpCallToAction(callToActionText: String?) { if (callToActionText != null) { binding.callToActionContainer.visibility = VISIBLE binding.callToActionText.text = callToActionText binding.viewPageHeaderImageGradientBottom.visibility = VISIBLE } else { binding.callToActionContainer.visibility = GONE binding.viewPageHeaderImageGradientBottom.visibility = GONE } } fun loadImage(url: String?) { if (url.isNullOrEmpty()) { hide() } else { show() binding.viewPageHeaderImage.loadImage(Uri.parse(url)) } } }
apache-2.0
e859fa66bdb89900b6b4aa228b96aa1d
33.712644
135
0.712583
4.95082
false
false
false
false
fabianonline/telegram_backup
src/main/kotlin/de/fabianonline/telegram_backup/CommandLineDownloadProgress.kt
1
3047
/* Telegram_Backup * Copyright (C) 2016 Fabian Schlenz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.fabianonline.telegram_backup import de.fabianonline.telegram_backup.DownloadProgressInterface import de.fabianonline.telegram_backup.mediafilemanager.AbstractMediaFileManager import de.fabianonline.telegram_backup.Utils internal class CommandLineDownloadProgress : DownloadProgressInterface { private var mediaCount = 0 private var i = 0 private var step = 0 private val chars = arrayOf("|", "/", "-", "\\") override fun onMessageDownloadStart(count: Int, source: String?) { i = 0 if (source == null) { System.out.println("Downloading $count messages.") } else { System.out.println("Downloading " + count + " messages from " + source.anonymize()) } } override fun onMessageDownloaded(number: Int) { i += number print("..." + i) } override fun onMessageDownloadFinished() { println(" done.") } override fun onMediaDownloadStart(count: Int) { i = 0 mediaCount = count println("Checking and downloading media.") println("Legend:") println("'V' - Video 'P' - Photo 'D' - Document") println("'S' - Sticker 'A' - Audio 'G' - Geolocation") println("'.' - Previously downloaded file 'e' - Empty file") println("' ' - Ignored media type (weblinks or contacts, for example)") println("'x' - File skipped (because of max_file_age or max_file_size)") println("'!' - Download failed. Will be tried again at next run.") println("" + count + " Files to check / download") } override fun onMediaDownloaded(file_manager: AbstractMediaFileManager) { show(file_manager.letter.toUpperCase()) } override fun onMediaFileDownloadStarted() { step = 0 print(chars[step % chars.size]) } override fun onMediaFileDownloadStep() { step++ print("\b") print(chars[step % chars.size]) } override fun onMediaFileDownloadFinished() { print("\b") } override fun onMediaDownloadedEmpty() { show("e") } override fun onMediaAlreadyPresent(file_manager: AbstractMediaFileManager) { show(".") } override fun onMediaSkipped() { show("x") } override fun onMediaDownloadFinished() { showNewLine() println("Done.") } override fun onMediaFailed() = show("!") private fun show(letter: String) { print(letter) i++ if (i % 100 == 0) showNewLine() } private fun showNewLine() { println(" - $i/$mediaCount") } }
gpl-3.0
83a1ec3c5fb82fafd404f6a4413e6be5
27.212963
86
0.693141
3.715854
false
false
false
false
jguerinet/MyMartlet-Android
app/src/main/java/ui/wishlist/WishlistAdapter.kt
2
4161
/* * Copyright 2014-2019 Julien Guerinet * * 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.guerinet.mymartlet.ui.wishlist import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.DiffUtil import com.guerinet.mymartlet.R import com.guerinet.mymartlet.model.CourseResult import com.guerinet.mymartlet.model.Term import com.guerinet.mymartlet.util.DayUtils import com.guerinet.suitcase.ui.BaseListAdapter import kotlinx.android.synthetic.main.item_course.view.* /** * Displays the list of courses in the user's wish list or after a course search * @author Julien Guerinet * @since 1.0.0 */ internal class WishlistAdapter(private val empty: TextView) : BaseListAdapter<CourseResult>(ItemCallback(), empty) { val checkedCourses = mutableListOf<CourseResult>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CourseHolder = CourseHolder(parent) /** * Updates the list of [courses] shown */ fun update(courses: List<CourseResult>) = submitList(courses.toMutableList()) /** * Updates the list of courses shown for a [term] (null if no wishlist semesters available) */ fun update(term: Term?, courses: List<CourseResult>) { if (term == null) { // Hide all of the main content and show explanatory text if the currentTerm is null empty.setText(R.string.registration_no_semesters) submitList(mutableListOf()) return } submitList(courses.toMutableList()) } internal inner class CourseHolder(parent: ViewGroup) : BaseHolder<CourseResult>(parent, R.layout.item_course) { override fun bind(position: Int, item: CourseResult) { itemView.apply { code.text = item.code credits.text = context.getString(R.string.course_credits, item.credits.toString()) title.text = item.title spots.visibility = View.VISIBLE spots.text = context.getString( R.string.registration_spots, item.seatsRemaining.toString() ) type.text = item.type waitlistRemaining.visibility = View.VISIBLE waitlistRemaining.text = context.getString( R.string.registration_waitlist, item.waitlistRemaining.toString() ) days.text = DayUtils.getDayStrings(item.days) hours.text = item.timeString dates.text = item.dateString checkBox.visibility = View.VISIBLE // Remove any other listeners checkBox.setOnCheckedChangeListener(null) // Initial state checkBox.isChecked = checkedCourses.contains(item) checkBox.setOnCheckedChangeListener { _, checked -> // If it becomes checked, add it to the list. If not, remove it if (checked) { checkedCourses.add(item) } else { checkedCourses.remove(item) } } } } } internal class ItemCallback : DiffUtil.ItemCallback<CourseResult>() { override fun areItemsTheSame(oldItem: CourseResult, newItem: CourseResult): Boolean = oldItem.term == newItem.term && oldItem.crn == newItem.crn override fun areContentsTheSame(oldItem: CourseResult, newItem: CourseResult): Boolean = oldItem == newItem } }
apache-2.0
b59fc48e99786e4e997661867f49ea45
37.174312
98
0.635184
4.91844
false
false
false
false
chrhsmt/Sishen
app/src/main/java/com/chrhsmt/sisheng/debug/CompareActivity.kt
1
13620
package com.chrhsmt.sisheng.debug import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.View import android.view.animation.AlphaAnimation import android.widget.TextView import android.widget.Toast import com.chrhsmt.sisheng.* import com.chrhsmt.sisheng.exception.AudioServiceException import com.chrhsmt.sisheng.font.FontUtils import com.chrhsmt.sisheng.network.RaspberryPi import com.chrhsmt.sisheng.persistence.SDCardManager import com.chrhsmt.sisheng.point.SimplePointCalculator import com.chrhsmt.sisheng.ui.Chart import com.chrhsmt.sisheng.ui.ScreenUtils import com.github.mikephil.charting.charts.LineChart import dmax.dialog.SpotsDialog import kotlinx.android.synthetic.main.activity_analyze_compare.* import okhttp3.Call import okhttp3.Callback import okhttp3.Response import java.io.IOException class CompareActivity : AppCompatActivity() { private val TAG: String = "CompareActivity" private val PERMISSION_REQUEST_CODE = 1 private var service: AudioServiceInterface? = null private var chart: Chart? = null private var isRecording = false enum class REIBUN_STATUS(val rawValue: Int) { PREPARE(1), NORMAL(2), PLAYING(3), RECODING(4), ANALYZING(5), ANALYZE_FINISH(6), ANALYZE_ERROR_OCCUR(7), } private var nowStatus: REIBUN_STATUS = REIBUN_STATUS.NORMAL override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_analyze_compare) // フルスクリーンにする ScreenUtils.setFullScreen(this.window) ScreenUtils.setScreenBackground(this) // ピンイン、中文、英文の配置 val reibunInfo = ReibunInfo.getInstance(this) txtDebugPinyin.text = ReibunInfo.replaceNewLine(reibunInfo.selectedItem!!.pinyin) txtDebugChinese.text = ReibunInfo.replaceNewLine(reibunInfo.selectedItem!!.chinese) // 音声再生、録画の準備 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO), PERMISSION_REQUEST_CODE) //return } Settings.setDefaultValue(this, false) // グラフの準備 this.chart = Chart() this.chart!!.initChartView(this.findViewById<LineChart>(R.id.chart)) this.service = AudioService(this.chart!!, this) // プログレスダイアログを表示する val dialog = SpotsDialog(this@CompareActivity, getString(R.string.screen6_2), R.style.CustomSpotDialog) dialog.show() ScreenUtils.setFullScreen(dialog.window) // お手本事前再生 nowStatus = REIBUN_STATUS.PREPARE updateButtonStatus() val fileName = reibunInfo.selectedItem!!.getMFSZExampleAudioFileName() Settings.sampleAudioFileName = fileName this.service!!.testPlay(fileName, playback = false, callback = object : Runnable { override fun run() { [email protected] { // DEBUG解析 val analyzed = AnalyzedRecordedData.getSelected() if (analyzed != null) { val file = analyzed.file val path= SDCardManager().copyAudioFile(file, this@CompareActivity) [email protected]!!.debugTestPlay(file.name, path, callback = object : Runnable { override fun run() { val v2Point = [email protected]?.analyze() val calcurator = SimplePointCalculator() calcurator.setV1() val v1Point = ([email protected] as AudioService)?.analyze(calcurator) [email protected] { ([email protected] as? AudioService)?.addOtherChart( v1Point?.analyzedFreqList, "男女設定キャリブレーション", Color.rgb(10, 255, 10)) ([email protected] as? AudioService)?.addOtherChart( v2Point?.analyzedFreqList, "周波数キャリブレーション", Color.rgb(255, 10, 255)) txtScore.text = String.format("Point: %s, F-Point: %s", v1Point?.score, v2Point?.score) } } }) } nowStatus = REIBUN_STATUS.NORMAL updateButtonStatus() dialog.dismiss() } } }) // お手本再生 btnAnalyzeOtehon.setOnClickListener({ nowStatus = CompareActivity.REIBUN_STATUS.PLAYING updateButtonStatus() [email protected]!!.clearTestFrequencies() [email protected]!!.clear() val fileName = reibunInfo.selectedItem!!.getMFSZExampleAudioFileName() Log.d(TAG, "Play " + fileName) this.service!!.testPlay(fileName, callback = object : Runnable { override fun run() { Thread.sleep(300) [email protected] { // DEBUG解析 val analyzed = AnalyzedRecordedData.getSelected() if (analyzed != null) { val file = analyzed.file val path= SDCardManager().copyAudioFile(file, this@CompareActivity) [email protected]!!.clearFrequencies() [email protected]!!.debugTestPlay(file.name, path, playback = true, callback = object : Runnable { override fun run() { val v2Point = [email protected]?.analyze() val calcurator = SimplePointCalculator() calcurator.setV1() val v1Point = ([email protected] as AudioService)?.analyze(calcurator) [email protected] { ([email protected] as? AudioService)?.addOtherChart( v1Point?.analyzedFreqList, "男女設定キャリブレーション", Color.rgb(10, 255, 10)) ([email protected] as? AudioService)?.addOtherChart( v2Point?.analyzedFreqList, "周波数キャリブレーション", Color.rgb(255, 10, 255)) txtScore.text = String.format("Point: %s, F-Point: %s", v1Point?.score, v2Point?.score) [email protected] = REIBUN_STATUS.NORMAL [email protected]() dialog.dismiss() } } }) } } } }) Thread(Runnable { Thread.sleep(2000) when ([email protected]!!.isRunning()) { true -> Thread.sleep(1000) } [email protected] { nowStatus = CompareActivity.REIBUN_STATUS.NORMAL updateButtonStatus() } }).start() }) // タイトル長押下された場合は、デバッグ画面に遷移する。 if (Settings.DEBUG_MODE) { txtDebugReibun.setOnLongClickListener(View.OnLongClickListener { val intent = Intent(this@CompareActivity, MainActivity::class.java) startActivity(intent) true }) } } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) ScreenUtils.setFullScreen([email protected]) } fun analyze() { // プログレスダイアログを表示する val dialog = SpotsDialog(this@CompareActivity, getString(R.string.screen6_3), R.style.CustomSpotDialog) dialog.show() FontUtils.changeFont(this@CompareActivity, dialog.findViewById<TextView>(dmax.dialog.R.id.dmax_spots_title), 1.1f) ScreenUtils.setFullScreen(dialog.window) // スレッドを開始する Thread(Runnable { Thread.sleep(1000 * 3) try { analyzeInner() } catch (e: AudioServiceException) { Log.e(TAG, e.message) runOnUiThread { dialog.dismiss() txtDebugError.visibility = View.VISIBLE nowStatus = REIBUN_STATUS.ANALYZE_ERROR_OCCUR updateButtonStatus() } } }).start() } @Throws(AudioServiceException::class) private fun analyzeInner() { val info = [email protected]!!.analyze() // val info2 = [email protected]!!.analyze(FreqTransitionPointCalculator::class.qualifiedName!!) // val info = [email protected]!!.analyze(NMultiplyLogarithmPointCalculator::class.qualifiedName!!) if (info.success()) { RaspberryPi().send(object: Callback { override fun onFailure(call: Call?, e: IOException?) { runOnUiThread { Toast.makeText(this@CompareActivity, e!!.message, Toast.LENGTH_LONG).show() } } override fun onResponse(call: Call?, response: Response?) { runOnUiThread { Toast.makeText(this@CompareActivity, response!!.body()!!.string(), Toast.LENGTH_LONG).show() } } }) } runOnUiThread { nowStatus = REIBUN_STATUS.ANALYZE_FINISH updateButtonStatus() val intent = Intent(this@CompareActivity, ResultActivity::class.java) intent.putExtra("result", info.success()) intent.putExtra("score", info.score.toString()) startActivity(intent) overridePendingTransition(0, 0); } } private fun updateButtonStatus() { when (nowStatus) { REIBUN_STATUS.PREPARE -> { // 録音ボタン:録音可、再生ボタン:再生可 btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button) btnAnalyzeOtehon.setEnabled(false) } REIBUN_STATUS.NORMAL -> { // 録音ボタン:録音可、再生ボタン:再生可 btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button) btnAnalyzeOtehon.setEnabled(true) } REIBUN_STATUS.PLAYING -> { // 録音ボタン:利用不可、再生ボタン:再生中 btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button_press) btnAnalyzeOtehon.setEnabled(false) } REIBUN_STATUS.RECODING -> { // 録音ボタン:録音中、再生ボタン:再生不可 val alphaAnimation = AlphaAnimation(1.0f, 0.7f) alphaAnimation.duration = 1000 alphaAnimation.fillAfter = true alphaAnimation.repeatCount = -1 btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button_disable) btnAnalyzeOtehon.setEnabled(false) } REIBUN_STATUS.ANALYZING -> { // 録音ボタン:録音不可、再生ボタン:再生不可 btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button_disable) btnAnalyzeOtehon.setEnabled(false) } REIBUN_STATUS.ANALYZE_FINISH -> { //ボタン等のパーツの状態を戻さずに結果画面に遷移する想定。 //本画面に戻る時は、再度 onCreate から行われる想定。 } REIBUN_STATUS.ANALYZE_ERROR_OCCUR -> { // 録音ボタン:録音可、再生ボタン:再生不可 btnAnalyzeOtehon.setBackgroundResource(R.drawable.shape_round_button_disable) btnAnalyzeOtehon.setEnabled(false) } } } }
mit
d5a93a04edf7470da14cc900790e5ef9
41.169381
137
0.549977
5.199197
false
false
false
false
cdcalc/cdcalc
core/src/main/kotlin/com/github/cdcalc/strategy/GitFlowStrategies.kt
1
3271
package com.github.cdcalc.strategy import com.github.cdcalc.configuration.EnvironmentConfiguration import com.github.cdcalc.data.SemVer import com.github.cdcalc.git.RefSemVer import com.github.cdcalc.git.aheadOfTag import com.github.cdcalc.git.processTags import com.github.cdcalc.git.semVerTags import org.eclipse.jgit.api.Git fun versionForHotfixBranch(): (Git, EnvironmentConfiguration) -> SemVer { return { git, branch -> val semVer = SemVer.parse(branch.branch) val tags = git.semVerTags() .filterTagsDescending { versionFromTag -> versionFromTag == semVer.copy(patch = Math.max(0, semVer.patch - 1)) } val (_, ahead) = git.aheadOfTag(tags) semVer.copy(identifiers = listOf("rc", ahead.toString())) } } fun versionForReleaseBranch(): (Git, EnvironmentConfiguration) -> SemVer { return { git, branch -> val semVer = SemVer.parse(branch.branch) val tags = git.semVerTags() .filterTagsDescending { versionFromTag -> versionFromTag == semVer.copy(identifiers = listOf("rc", "0")) } val (_, ahead) = git.aheadOfTag(tags) semVer.copy(identifiers = listOf("rc", ahead.toString())) } } fun versionForDevelopBranch(): (Git, EnvironmentConfiguration) -> SemVer { return { git, _ -> val tags = git.semVerTags() .filterTagsDescending { versionFromTag -> versionFromTag.identifiers == listOf("rc", "0") } val (semVer, ahead) = git.aheadOfTag(tags, true) if (semVer == SemVer.Empty || ahead == 0) { throw TrackingException("Couldn't find any reachable rc.0 tags before current commit") } semVer.bump().copy(identifiers = listOf("beta", (ahead - 1).toString())) } } class TrackingException(message: String) : Throwable(message) fun versionForMasterBranch(): (Git, EnvironmentConfiguration) -> SemVer { return { git, _ -> val tags = git.semVerTags() .filterTagsDescending({ it.isStable() }) git.processTags(tags) { _, headCommit, list -> list.firstOrNull { headCommit == it.commit }?.semVer ?: SemVer() } } } fun directTag(): (Git, EnvironmentConfiguration) -> SemVer { return { _, config -> SemVer.parse(config.tag) } } fun versionForAnyBranch(): (Git, EnvironmentConfiguration) -> SemVer { return { git, _ -> val tags = git.semVerTags() .filterTagsDescending({ versionFromTag -> versionFromTag.identifiers == listOf("rc", "0") || versionFromTag.isStable() }) val processTags: SemVer = git.processTags(tags) { walk, headCommit, list -> val taggedCommit = list.firstOrNull { walk.isMergedInto(it.commit, headCommit) && headCommit != it.commit }?.semVer ?: SemVer() taggedCommit.bump().copy(identifiers = listOf("alpha", headCommit.abbreviate(7).name().toUpperCase())) } processTags } } private fun List<RefSemVer>.filterTagsDescending(tagFilter: (SemVer) -> Boolean) : List<RefSemVer> { return this.filter { tag -> tagFilter(tag.semVer) } .sortedByDescending { tag -> tag.semVer } }
mit
08f3f843695ef8fb7543259894cfb677
32.731959
114
0.62458
4.438263
false
true
false
false