repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
Cognifide/AET
core/accessibility-report/src/main/kotlin/com/cognifide/aet/accessibility/report/models/AccessibilityIssue.kt
1
2327
/* * AET * * Copyright (C) 2020 Cognifide Limited * * 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.cognifide.aet.accessibility.report.models import java.io.Serializable import java.util.Objects class AccessibilityIssue( val type: IssueType, val message: String, val code: String, val elementString: String, val elementStringAbbreviated: String) : Serializable { var lineNumber = 0 var columnNumber = 0 var isExcluded = false private set var url: String = "" fun getAccessibilityCode(): AccessibilityCode = AccessibilityCode(code) override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other == null || javaClass != other.javaClass) { return false } val that = other as AccessibilityIssue return (lineNumber == that.lineNumber && columnNumber == that.columnNumber && isExcluded == that.isExcluded && type == that.type && message == that.message && code == that.code && elementString == that.elementString && elementStringAbbreviated == that.elementStringAbbreviated && url == that.url) } override fun hashCode(): Int { return Objects.hash( type, message, code, elementString, elementStringAbbreviated, lineNumber, columnNumber, isExcluded, url) } enum class IssueType { ERROR, WARN, NOTICE, UNKNOWN; companion object { fun fromString(issue: String): IssueType? = values().find { it.toString() == issue.toUpperCase() } ?: throw IllegalArgumentException("Unrecognized value for issue verbosity was provided: $issue") } } companion object { private const val serialVersionUID = -53665467524179701L } }
apache-2.0
gradle/gradle
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/TrackingDynamicLookupRoutine.kt
2
2735
/* * Copyright 2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.configurationcache import groovy.lang.MissingPropertyException import org.gradle.api.internal.project.DynamicLookupRoutine import org.gradle.configuration.internal.DynamicCallContextTracker import org.gradle.internal.Factory import org.gradle.internal.deprecation.DeprecationLogger import org.gradle.internal.metaobject.DynamicInvokeResult import org.gradle.internal.metaobject.DynamicObject class TrackingDynamicLookupRoutine( private val dynamicCallContextTracker: DynamicCallContextTracker ) : DynamicLookupRoutine { @Throws(MissingPropertyException::class) override fun property(receiver: DynamicObject, propertyName: String): Any? = withDynamicCall(receiver) { receiver.getProperty(propertyName) } override fun findProperty(receiver: DynamicObject, propertyName: String): Any? = withDynamicCall(receiver) { val dynamicInvokeResult: DynamicInvokeResult = receiver.tryGetProperty(propertyName) if (dynamicInvokeResult.isFound) dynamicInvokeResult.value else null } override fun setProperty(receiver: DynamicObject, name: String, value: Any?) = withDynamicCall(receiver) { receiver.setProperty(name, value) } override fun hasProperty(receiver: DynamicObject, propertyName: String): Boolean = withDynamicCall(receiver) { receiver.hasProperty(propertyName) } override fun getProperties(receiver: DynamicObject): Map<String, *>? = withDynamicCall(receiver) { DeprecationLogger.whileDisabled(Factory<Map<String, *>> { receiver.properties }) } override fun invokeMethod(receiver: DynamicObject, name: String, args: Array<Any>): Any? = withDynamicCall(receiver) { receiver.invokeMethod(name, *args) } private fun <T> withDynamicCall(entryPoint: Any, action: () -> T): T = try { dynamicCallContextTracker.enterDynamicCall(entryPoint) action() } finally { dynamicCallContextTracker.leaveDynamicCall(entryPoint) } }
apache-2.0
halangode/WifiDeviceScanner
devicescanner/src/main/java/com/halangode/devicescanner/IScanEvents.kt
1
225
package com.halangode.devicescanner import java.util.HashMap /** * Created by Harikumar Alangode on 24-Jun-17. */ interface IScanEvents { fun onScanCompleted(ips: Map<String, String>) fun onError(error: Error) }
mit
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/ui/StockFieldView.kt
1
4290
package com.github.premnirmal.ticker.ui import android.content.Context import android.content.res.TypedArray import android.util.AttributeSet import android.util.TypedValue import android.view.Gravity import android.view.LayoutInflater import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import com.github.premnirmal.tickerwidget.R import com.robinhood.ticker.TickerUtils import com.robinhood.ticker.TickerView /** * Created by premnirmal on 2/27/16. */ class StockFieldView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : LinearLayout(context, attrs) { companion object { const val ORIENTATION_HORIZONTAL = 0 const val ORIENTATION_VERTICAL = 1 const val GRAVITY_LEFT = 0 const val GRAVITY_RIGHT = 1 const val GRAVITY_CENTER = 2 } private val fieldname: TextView private val fieldvalue: TickerView init { LayoutInflater.from(context) .inflate(R.layout.stock_field_view, this, true) fieldname = findViewById(R.id.fieldname) fieldvalue = findViewById(R.id.fieldvalue) fieldvalue.setCharacterLists(TickerUtils.provideNumberList()) attrs?.let { val array = context.obtainStyledAttributes(it, R.styleable.StockFieldView) val orientation = array.getInt(R.styleable.StockFieldView_or, 0) if (orientation == ORIENTATION_HORIZONTAL) { setOrientation(HORIZONTAL) fieldname.layoutParams = LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 0.5f) fieldvalue.layoutParams = LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 0.5f) fieldvalue.gravity = Gravity.END } else { setOrientation(VERTICAL) fieldname.layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) fieldvalue.layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) fieldvalue.gravity = Gravity.START } weightSum = 1f val name = getStringValue(context, array, R.styleable.StockFieldView_name) fieldname.text = name val textSize = array.getDimensionPixelSize(R.styleable.StockFieldView_size, 20) .toFloat() fieldname.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize) fieldvalue.setTextSize(textSize * 0.9f) val centerText = array.getBoolean(R.styleable.StockFieldView_center_text, false) when { centerText -> { fieldname.gravity = Gravity.CENTER fieldvalue.gravity = Gravity.CENTER } orientation == ORIENTATION_HORIZONTAL -> { fieldname.gravity = Gravity.START fieldvalue.gravity = Gravity.END } orientation == ORIENTATION_VERTICAL -> { val textGravity = array.getInt(R.styleable.StockFieldView_text_gravity, 0) when (textGravity) { GRAVITY_LEFT -> { fieldname.gravity = Gravity.START fieldvalue.gravity = Gravity.START } GRAVITY_RIGHT -> { fieldname.gravity = Gravity.END fieldvalue.gravity = Gravity.END } GRAVITY_CENTER -> { fieldname.gravity = Gravity.CENTER fieldvalue.gravity = Gravity.CENTER } } } } array.recycle() } } constructor( context: Context, attrs: AttributeSet, defStyleAttr: Int ) : this(context, attrs) constructor( context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int ) : this( context, attrs ) fun setLabel(text: CharSequence?) { fieldname.text = text } fun setText(text: CharSequence?) { fieldvalue.text = text.toString() } fun setTextColor(color: Int) { fieldvalue.textColor = color } private fun getStringValue( context: Context, array: TypedArray, stylelable: Int ): String { var name = array.getString(stylelable) if (name == null) { val stringId = array.getResourceId(stylelable, -1) name = if (stringId > 0) { context.getString(stringId) } else { "" } } return name } }
gpl-3.0
AlmasB/FXGL
fxgl-scene/src/main/kotlin/com/almasb/fxgl/ui/InGamePanel.kt
1
1740
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.ui import com.almasb.fxgl.animation.Interpolators import javafx.animation.TranslateTransition import javafx.geometry.HorizontalDirection import javafx.scene.layout.Pane import javafx.scene.paint.Color import javafx.scene.shape.Rectangle import javafx.util.Duration /** * An in-game semi-transparent panel with in/out animations. * Can be used to display various UI elements, e.g. game score, inventory, * player stats, etc. * * @author Almas Baimagambetov ([email protected]) */ class InGamePanel(val panelWidth: Double, val panelHeight: Double, val direction: HorizontalDirection = HorizontalDirection.LEFT) : Pane() { var isOpen = false private set init { translateX = -panelWidth - 4 val bg = Rectangle(panelWidth, panelHeight, Color.color(0.0, 0.0, 0.0, 0.85)) children += bg isDisable = true } fun open() { if (isOpen) return isOpen = true isDisable = false val translation = TranslateTransition(Duration.seconds(0.33), this) with(translation) { interpolator = Interpolators.EXPONENTIAL.EASE_OUT() toX = 0.0 play() } } fun close() { if (!isOpen) return isOpen = false isDisable = true val translation = TranslateTransition(Duration.seconds(0.33), this) with(translation) { interpolator = Interpolators.EXPONENTIAL.EASE_OUT() toX = -panelWidth - 4 play() } } }
mit
duftler/orca
orca-queue-tck/src/main/kotlin/com/netflix/spinnaker/orca/q/PendingExecutionServiceTest.kt
1
3985
package com.netflix.spinnaker.orca.q import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.q.pending.PendingExecutionService import com.netflix.spinnaker.q.Message import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.assertj.core.api.Assertions import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.subject.SubjectSpek import java.util.UUID object PendingExecutionServiceTest : SubjectSpek<PendingExecutionService>({ val id = UUID.randomUUID().toString() val pipeline = pipeline { pipelineConfigId = id stage { refId = "1" } stage { refId = "2" requisiteStageRefIds = setOf("1") } } val startMessage = StartExecution(pipeline) val restartMessage = RestartStage(pipeline.stageByRef("2"), "[email protected]") val callback = mock<(Message) -> Unit>() sequenceOf<Message>(startMessage, restartMessage).forEach { message -> describe("enqueueing a ${message.javaClass.simpleName} message") { given("the queue is empty") { beforeGroup { Assertions.assertThat(subject.depth(id)).isZero() } on("enqueueing the message") { subject.enqueue(id, message) it("makes the depth 1") { Assertions.assertThat(subject.depth(id)).isOne() } } afterGroup { subject.purge(id, callback) } } } } describe("popping a message") { given("the queue is empty") { beforeGroup { Assertions.assertThat(subject.depth(id)).isZero() } on("popping a message") { val popped = subject.popOldest(id) it("returns null") { Assertions.assertThat(popped).isNull() } } } given("a message was enqueued") { beforeGroup { subject.enqueue(id, startMessage) } on("popping a message") { val popped = subject.popOldest(id) it("returns the message") { Assertions.assertThat(popped).isEqualTo(startMessage) } it("removes the message from the queue") { Assertions.assertThat(subject.depth(id)).isZero() } } afterGroup { subject.purge(id, callback) } } given("multiple messages were enqueued") { beforeEachTest { subject.enqueue(id, startMessage) subject.enqueue(id, restartMessage) } on("popping the oldest message") { val popped = subject.popOldest(id) it("returns the oldest message") { Assertions.assertThat(popped).isEqualTo(startMessage) } it("removes the message from the queue") { Assertions.assertThat(subject.depth(id)).isOne() } } on("popping the newest message") { val popped = subject.popNewest(id) it("returns the newest message") { Assertions.assertThat(popped).isEqualTo(restartMessage) } it("removes the message from the queue") { Assertions.assertThat(subject.depth(id)).isOne() } } afterEachTest { subject.purge(id, callback) } } } describe("purging the queue") { val purgeCallback = mock<(Message) -> Unit>() given("there are some messages on the queue") { beforeGroup { subject.enqueue(id, startMessage) subject.enqueue(id, restartMessage) } on("purging the queue") { subject.purge(id, purgeCallback) it("makes the queue empty") { Assertions.assertThat(subject.depth(id)).isZero() } it("invokes the callback passing each message") { verify(purgeCallback).invoke(startMessage) verify(purgeCallback).invoke(restartMessage) } } afterGroup { subject.purge(id, callback) } } } })
apache-2.0
dslomov/intellij-community
plugins/settings-repository/src/IcsBundle.kt
23
911
package org.jetbrains.settingsRepository import com.intellij.CommonBundle import org.jetbrains.annotations.PropertyKey import java.lang.ref.Reference import java.lang.ref.SoftReference import java.util.ResourceBundle import kotlin.platform.platformStatic class IcsBundle { companion object { private var ourBundle: Reference<ResourceBundle>? = null val BUNDLE: String = "messages.IcsBundle" platformStatic fun message(PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any?): String { return CommonBundle.message(getBundle(), key, *params) } private fun getBundle(): ResourceBundle { var bundle: ResourceBundle? = null if (ourBundle != null) { bundle = ourBundle!!.get() } if (bundle == null) { bundle = ResourceBundle.getBundle(BUNDLE) ourBundle = SoftReference(bundle) } return bundle!! } } }
apache-2.0
coil-kt/coil
coil-compose-base/src/main/java/coil/compose/ImagePainter.kt
1
4144
@file:Suppress("NOTHING_TO_INLINE", "UNUSED_PARAMETER") package coil.compose import androidx.compose.runtime.Composable import androidx.compose.ui.geometry.Size import androidx.compose.ui.platform.LocalContext import coil.ImageLoader import coil.compose.AsyncImagePainter.State import coil.request.ImageRequest @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "AsyncImagePainter", imports = ["coil.compose.AsyncImagePainter"] ) ) typealias ImagePainter = AsyncImagePainter @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(data, imageLoader)", imports = ["coil.compose.rememberAsyncImagePainter"] ) ) @Composable inline fun rememberImagePainter( data: Any?, imageLoader: ImageLoader, ) = rememberAsyncImagePainter(data, imageLoader) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(data, imageLoader)", imports = ["coil.compose.rememberAsyncImagePainter"] ), level = DeprecationLevel.ERROR // ExecuteCallback is no longer supported. ) @Composable inline fun rememberImagePainter( data: Any?, imageLoader: ImageLoader, onExecute: ExecuteCallback ) = rememberAsyncImagePainter(data, imageLoader) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(ImageRequest.Builder(LocalContext.current)" + ".data(data).apply(builder).build(), imageLoader)", imports = [ "androidx.compose.ui.platform.LocalContext", "coil.compose.rememberAsyncImagePainter", "coil.request.ImageRequest", ] ) ) @Composable inline fun rememberImagePainter( data: Any?, imageLoader: ImageLoader, builder: ImageRequest.Builder.() -> Unit, ) = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current).data(data).apply(builder).build(), imageLoader = imageLoader ) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(ImageRequest.Builder(LocalContext.current)" + ".data(data).apply(builder).build(), imageLoader)", imports = [ "androidx.compose.ui.platform.LocalContext", "coil.compose.rememberAsyncImagePainter", "coil.request.ImageRequest", ] ), level = DeprecationLevel.ERROR // ExecuteCallback is no longer supported. ) @Composable inline fun rememberImagePainter( data: Any?, imageLoader: ImageLoader, onExecute: ExecuteCallback, builder: ImageRequest.Builder.() -> Unit, ) = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current).data(data).apply(builder).build(), imageLoader = imageLoader ) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(request, imageLoader)", imports = ["coil.compose.rememberAsyncImagePainter"] ) ) @Composable inline fun rememberImagePainter( request: ImageRequest, imageLoader: ImageLoader, ) = rememberAsyncImagePainter(request, imageLoader) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(request, imageLoader)", imports = ["coil.compose.rememberAsyncImagePainter"] ), level = DeprecationLevel.ERROR // ExecuteCallback is no longer supported. ) @Composable inline fun rememberImagePainter( request: ImageRequest, imageLoader: ImageLoader, onExecute: ExecuteCallback, ) = rememberAsyncImagePainter(request, imageLoader) private typealias ExecuteCallback = (Snapshot, Snapshot) -> Boolean private typealias Snapshot = Triple<State, ImageRequest, Size>
apache-2.0
sugarmanz/Pandroid
app/src/main/java/com/jeremiahzucker/pandroid/request/json/v5/method/exp/bookmark/DeleteSongBookmark.kt
1
283
package com.jeremiahzucker.pandroid.request.json.v5.method.exp.bookmark import com.jeremiahzucker.pandroid.request.BaseMethod /** * Created by Jeremiah Zucker on 8/22/2017. * TODO: Not "unofficially" documented. Determine usefulness. */ object DeleteSongBookmark : BaseMethod()
mit
burntcookie90/Sleep-Cycle-Alarm
wear/src/main/kotlin/io/dwak/sleepcyclealarm/MainActivity.kt
1
846
package io.dwak.sleepcyclealarm import android.app.Activity import android.widget.TextView public class MainActivity : Activity() { private var mTextView : TextView? = null override fun onCreate(savedInstanceState : android.os.Bundle?) { super.onCreate(savedInstanceState) setContentView(io.dwak.sleepcyclealarm.R.layout.activity_main) val stub = findViewById(io.dwak.sleepcyclealarm.R.id.watch_view_stub) as android.support.wearable.view.WatchViewStub stub.setOnLayoutInflatedListener(object : android.support.wearable.view.WatchViewStub.OnLayoutInflatedListener { override fun onLayoutInflated(stub : android.support.wearable.view.WatchViewStub) { mTextView = stub.findViewById(io.dwak.sleepcyclealarm.R.id.text) as android.widget.TextView } }) } }
apache-2.0
madtcsa/AppManager
app/src/main/java/com/md/appmanager/activities/SettingsActivity.kt
1
6921
package com.md.appmanager.activities import android.content.Context import android.content.SharedPreferences import android.content.res.ColorStateList import android.os.Build import android.os.Bundle import android.preference.ListPreference import android.preference.Preference import android.preference.PreferenceActivity import android.preference.PreferenceManager import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.ViewGroup import android.view.WindowManager import android.widget.LinearLayout import com.md.appmanager.AppManagerApplication import com.md.appmanager.R import com.md.appmanager.utils.AppPreferences import com.md.appmanager.utils.UtilsApp import com.md.appmanager.utils.UtilsUI import net.rdrei.android.dirchooser.DirectoryChooserConfig import net.rdrei.android.dirchooser.DirectoryChooserFragment class SettingsActivity : PreferenceActivity(), SharedPreferences.OnSharedPreferenceChangeListener, DirectoryChooserFragment.OnFragmentInteractionListener { // Load Settings private var appPreferences: AppPreferences? = null private var toolbar: Toolbar? = null private var context: Context? = null private var prefDeleteAll: Preference? = null private var prefNavigationBlack: Preference? = null private var prefCustomPath: Preference? = null private var prefCustomFilename: ListPreference? = null private var prefSortMode: ListPreference? = null private var chooserDialog: DirectoryChooserFragment? = null public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.settings) this.context = this this.appPreferences = AppManagerApplication.appPreferences val prefs = PreferenceManager.getDefaultSharedPreferences(this) prefs.registerOnSharedPreferenceChangeListener(this) prefDeleteAll = findPreference("prefDeleteAll") prefCustomFilename = findPreference("prefCustomFilename") as ListPreference prefSortMode = findPreference("prefSortMode") as ListPreference prefCustomPath = findPreference("prefCustomPath") setInitialConfiguration() val versionName = UtilsApp.getAppVersionName(context as SettingsActivity) val versionCode = UtilsApp.getAppVersionCode(context as SettingsActivity) // prefCustomFilename setCustomFilenameSummary() // prefSortMode setSortModeSummary() // prefCustomPath setCustomPathSummary() // prefDeleteAll prefDeleteAll!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { prefDeleteAll!!.setSummary(R.string.deleting) prefDeleteAll!!.isEnabled = false val deleteAll = UtilsApp.deleteAppFiles() if (deleteAll!!) { prefDeleteAll!!.setSummary(R.string.deleting_done) } else { prefDeleteAll!!.setSummary(R.string.deleting_error) } prefDeleteAll!!.isEnabled = true true } // prefCustomPath prefCustomPath!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { val chooserConfig = DirectoryChooserConfig.builder() .newDirectoryName("App Manager APKs") .allowReadOnlyDirectory(false) .allowNewDirectoryNameModification(true) .initialDirectory(appPreferences!!.customPath) .build() chooserDialog = DirectoryChooserFragment.newInstance(chooserConfig) chooserDialog!!.show(fragmentManager, null) false } } override fun setContentView(layoutResID: Int) { val contentView = LayoutInflater.from(this).inflate(R.layout.activity_settings, LinearLayout(this), false) as ViewGroup toolbar = contentView.findViewById(R.id.toolbar) as Toolbar toolbar!!.setTitleTextColor(resources.getColor(R.color.white)) toolbar!!.setNavigationOnClickListener { onBackPressed() } toolbar!!.navigationIcon = UtilsUI.tintDrawable(toolbar!!.navigationIcon!!, ColorStateList.valueOf(resources.getColor(R.color.white))) val contentWrapper = contentView.findViewById(R.id.content_wrapper) as ViewGroup LayoutInflater.from(this).inflate(layoutResID, contentWrapper, true) window.setContentView(contentView) } private fun setInitialConfiguration() { toolbar!!.title = resources.getString(R.string.action_settings) // Android 5.0+ devices if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = UtilsUI.darker(appPreferences!!.primaryColorPref, 0.8) toolbar!!.setBackgroundColor(appPreferences!!.primaryColorPref) if (appPreferences!!.navigationBlackPref!!) { window.navigationBarColor = appPreferences!!.primaryColorPref } } // Pre-Lollipop devices if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { prefNavigationBlack!!.isEnabled = false prefNavigationBlack!!.setDefaultValue(true) } } private fun setCustomFilenameSummary() { val filenameValue = Integer.valueOf(appPreferences!!.customFilename)!! - 1 prefCustomFilename!!.summary = resources.getStringArray(R.array.filenameEntries)[filenameValue] } private fun setSortModeSummary() { val sortValue = Integer.valueOf(appPreferences!!.sortMode)!! - 1 prefSortMode!!.summary = resources.getStringArray(R.array.sortEntries)[sortValue] } private fun setCustomPathSummary() { val path = appPreferences!!.customPath if (path == UtilsApp.defaultAppFolder.getPath()) { prefCustomPath!!.summary = resources.getString(R.string.button_default) + ": " + UtilsApp.defaultAppFolder.getPath() } else { prefCustomPath!!.summary = path } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { val pref = findPreference(key) if (pref === prefCustomFilename) { setCustomFilenameSummary() } else if (pref === prefSortMode) { setSortModeSummary() } else if (pref === prefCustomPath) { setCustomPathSummary() } } override fun onSelectDirectory(path: String) { appPreferences!!.customPath = path setCustomPathSummary() chooserDialog!!.dismiss() } override fun onCancelChooser() { chooserDialog!!.dismiss() } override fun onBackPressed() { super.onBackPressed() overridePendingTransition(R.anim.fade_forward, R.anim.slide_out_right) } }
gpl-3.0
izumin5210/Sunazuri
app/src/main/java/info/izumin/android/sunazuri/data/action/user/AddAuthorizedUserAction.kt
1
420
package info.izumin.android.sunazuri.data.action.user; import info.izumin.android.sunazuri.data.action.common.BaseAction import info.izumin.android.sunazuri.domain.entity.AuthorizedUser /** * Created by izumin on 5/22/2016 AD. */ class AddAuthorizedUserAction : BaseAction<AddAuthorizedUserAction.RequestValue>() { data class RequestValue( val user: AuthorizedUser ) : BaseAction.RequestValue; }
apache-2.0
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/base/UINavigationView.kt
1
6058
package com.angcyo.uiview.base import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import com.angcyo.uiview.R import com.angcyo.uiview.container.ContentLayout import com.angcyo.uiview.container.UILayoutImpl import com.angcyo.uiview.container.UIParam import com.angcyo.uiview.model.TitleBarPattern import com.angcyo.uiview.widget.TouchMoveGroupLayout import com.angcyo.uiview.widget.TouchMoveView /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:自带类似QQ底部导航效果的主页面 * 创建人员:Robi * 创建时间:2017/06/06 10:51 * 修改人员:Robi * 修改时间:2017/06/06 10:51 * 修改备注: * Version: 1.0.0 */ abstract class UINavigationView : UIContentView() { /**默认选择的页面*/ var selectorPosition = 0 set(value) { touchMoveGroupLayout?.selectorPosition = selectorPosition } /**保存所有界面*/ var pages = arrayListOf<PageBean>() var lastIndex = selectorPosition override fun getTitleBar(): TitleBarPattern? { return null } /**导航的root layout, 用来包裹 TouchMoveView*/ val touchMoveGroupLayout: TouchMoveGroupLayout? by lazy { mViewHolder.v<TouchMoveGroupLayout>(R.id.navigation_bar_wrapper) } /**底部导航上层的阴影图层*/ val shadowView: View? by lazy { val view = mViewHolder.v<View>(R.id.shadow_view) view?.visibility = if (showShadowView) View.VISIBLE else View.GONE view } /**用来管理子页面的ILayout*/ val mainLayoutImpl: UILayoutImpl? by lazy { val impl = mViewHolder.v<UILayoutImpl>(R.id.main_layout_imp) setChildILayout(impl) impl } var showShadowView = true set(value) { field = value shadowView?.visibility = if (value) View.VISIBLE else View.GONE } override fun inflateContentLayout(baseContentLayout: ContentLayout?, inflater: LayoutInflater?) { inflate(R.layout.base_navigation_view) } override fun onViewLoad() { super.onViewLoad() mainLayoutImpl?.setEnableSwipeBack(false)//关闭侧滑 createPages(pages) onCreatePages() } fun onCreatePages() { pages?.forEach { touchMoveGroupLayout?.addView(createNavItem(it)) } touchMoveGroupLayout?.selectorPosition = selectorPosition touchMoveGroupLayout?.updateSelectorStyle() touchMoveGroupLayout?.listener = object : TouchMoveGroupLayout.OnSelectorPositionListener { override fun onRepeatSelectorPosition(targetView: TouchMoveView, position: Int) { //重复选择页面 [email protected](targetView, position) } override fun onSelectorPosition(targetView: TouchMoveView, position: Int) { //选择新页面 mainLayoutImpl?.startIView(pages?.get(position)?.iview?.setIsRightJumpLeft(lastIndex > position), UIParam(lastIndex != position).setLaunchMode(UIParam.SINGLE_TOP)) lastIndex = position [email protected](targetView, position) } } } open fun createNavItem(page: PageBean): TouchMoveView { val view = TouchMoveView(mActivity) view.textNormal = page.textNormal view.textSelected = page.textSelected if (page.textColorNormal != null) { view.mTextColorNormal = page.textColorNormal } if (page.textColorSelected != null) { view.mTextColorSelected = page.textColorSelected } if (page.icoResNormal != null) { view.mDrawableNormal = getDrawable(page.icoResNormal) } else { view.mDrawableNormal = null } if (page.icoResSelected != null) { view.mDrawableSelected = getDrawable(page.icoResSelected) } else { view.mDrawableSelected = null } if (page.icoSubResNormal != null) { view.mSubDrawableNormal = getDrawable(page.icoSubResNormal) } else { view.mSubDrawableNormal = null } if (page.icoSubResSelected != null) { view.mSubDrawableSelected = getDrawable(page.icoSubResSelected) } else { view.mSubDrawableSelected = null } page.iview.bindParentILayout(iLayout) return view } /**创建页面*/ abstract fun createPages(pages: ArrayList<PageBean>) open fun onSelectorPosition(targetView: TouchMoveView, position: Int) { } open fun onRepeatSelectorPosition(targetView: TouchMoveView, position: Int) { } /**页面*/ data class PageBean( val iview: UIBaseView, val textNormal: String? = null, val textSelected: String? = null, val textColorNormal: Int? = null, val textColorSelected: Int? = null, val icoResNormal: Int? = null, val icoResSelected: Int? = null, val icoSubResNormal: Int? = null, val icoSubResSelected: Int? = null ) { constructor(iview: UIBaseView, textNormal: String? = null, icoResNormal: Int? = null ) : this(iview, textNormal, textNormal, null, null, icoResNormal, icoResNormal, null, null) constructor(iview: UIBaseView, textNormal: String? = null, textColorNormal: Int? = null, textColorSelected: Int? = null, icoResNormal: Int? = null ) : this(iview, textNormal, textNormal, textColorNormal, textColorSelected, icoResNormal, icoResNormal, null, null) } }
apache-2.0
kekc42/memorizing-pager
app/src/main/java/com/lockwood/pagerdemo/BaseNavigationActivity.kt
1
1424
package com.lockwood.pagerdemo import android.os.Bundle import android.os.Parcelable import androidx.appcompat.app.AppCompatActivity import com.google.android.material.bottomnavigation.BottomNavigationView import com.lockwood.memorizingpager.NavigationHistory abstract class BaseNavigationActivity(contentLayoutId: Int) : AppCompatActivity(contentLayoutId), BottomNavigationView.OnNavigationItemSelectedListener { protected lateinit var navigation: BottomNavigationView protected lateinit var navigationHistory: NavigationHistory override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) navigationHistory = if (savedInstanceState == null) { NavigationHistory() } else { savedInstanceState.getParcelable<Parcelable>(EXTRA_NAV_HISTORY) as NavigationHistory } // initBottomNavigation navigation = findViewById(R.id.navigation) navigation.setOnNavigationItemSelectedListener(this) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(EXTRA_NAV_HISTORY, navigationHistory) } protected fun isItemSelected(itemId: Int): Boolean = navigation.selectedItemId == itemId companion object { const val HOME_NAVIGATION_ITEM = 0 private const val EXTRA_NAV_HISTORY = "nav_history" } }
apache-2.0
r-artworks/game-seed
core/src/com/rartworks/engine/events/Event.kt
1
425
package com.rartworks.engine.events import com.rartworks.engine.utils.fastForEach /** * An event that can be fired. */ class Event { private var handlers: MutableList<() -> (Unit)> = arrayListOf() /** * Subscribes to the event with a [handler]. */ operator fun invoke(handler: () -> (Unit)) { this.handlers.add(handler) } /** * Fires the event. */ fun fire() { this.handlers.fastForEach { it() } } }
mit
christophpickl/gadsu
src/test/kotlin/non_test/kotlin_playground/config.kt
1
2962
package non_test.kotlin_playground import non_test.kotlin_playground.ConfigFields.baseUrl import non_test.kotlin_playground.ConfigFields.threshold import java.net.URL interface Config { fun <T> get(field: Field<T>): T } class InMemoryConfig : Config, InternalConfig { private val data = mapOf( "presto.port" to "80", "presto.host" to "localhost", "threshold" to "142" ) override fun <T> get(field: Field<T>) = field.valueOf(this) override fun get(name: String) = data[name] ?: throw IllegalArgumentException(name) } interface InternalConfig { operator fun get(name: String): String } interface Field<out T> { fun valueOf(config: InternalConfig): T val name: String } open class IntField(override val name: String) : Field<Int> { override fun valueOf(config: InternalConfig) = config[name].toInt() } open class StringField(override val name: String) : Field<String> { override fun valueOf(config: InternalConfig) = config[name] } open class UrlField(final override val name: String) : Field<URL> { private val host = StringField("$name.host") private val port = IntField("$name.port") override fun valueOf(config: InternalConfig) = URL("https://${host.valueOf(config)}:${port.valueOf(config)}") } object ConfigFields { object threshold : IntField(name = "threshold") object baseUrl : UrlField(name = "presto") } fun main(args: Array<String>) { val config = InMemoryConfig() // and we call get and get directly the proper type val thresholdConfig: Int = config.get(threshold) val url: URL = config.get(baseUrl) println(thresholdConfig) println(url) } // //interface Config { // fun <T> get(field: Field<T>): T //} //class InMemoryConfig : Config { // private val data = mapOf("port" to "80", "url" to "http://localhost") // override fun <T> get(field: Field<T>) = // data[field.name]?.toT(field) ?: // throw IllegalArgumentException(field.name) // private fun <T> String.toT(field: Field<T>) = field.valueOf(this) //} // //interface Field<out T> { // fun valueOf(rawValue: String): T // val name: String //} //open class IntField(override val name: String) : Field<Int> { // override fun valueOf(rawValue: String) = rawValue.toInt() //} //open class StringField(override val name: String) : Field<String> { // override fun valueOf(rawValue: String) = rawValue //} //open class UrlField(override val name: String) : Field<URL> { // override fun valueOf(rawValue: String) = URL() //} // //object ConfigFields { // object port : IntField(name = "port") // object url : StringField(name = "url") //} // //fun main(args: Array<String>) { // val config = InMemoryConfig() // // val jettyPort: Int = config.get(port) // val jettyUrl: String = config.get(url) // // println("$jettyUrl:$jettyPort") //} //
apache-2.0
eugeis/ee
ee-system/src/main/kotlin/ee/system/JavaServiceQueries.kt
1
217
package ee.system open class JavaServiceQueries<T : JavaService> : JavaServiceQueriesBase<T> { companion object { val EMPTY = JavaServiceQueriesBase.EMPTY } constructor() : super() { } }
apache-2.0
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/hnutils/services/db/Res.kt
2
1548
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ir.iais.utilities.hnutils.services.db import ir.iais.utilities.hnutils.services.db.interfaces.ISession import java.io.Closeable /** * Result Wrapper * * @param <T> Result type * @author yoones </T> */ @Deprecated("Will be deleted soon.") class Res<T > constructor(private val result: T, private val session: ISession<*>?) : Closeable { override fun close() { closeSession() } @Deprecated("") fun <RT> then(thenAction: (T) -> RT): RT = use { thenAction(result) } // @Deprecated("") // fun <RT> then_NotCloseSession(thenAction: (T) -> RT): RT = try { // thenAction(result) // } catch (t: Throwable) { // close().run { throw t } // } @Deprecated("") fun run(runnable: (T) -> Unit): Res<T> = try { runnable(result) } catch (e: Throwable) { close() }.let { this } @Suppress("MemberVisibilityCanPrivate") @Deprecated("") fun closeSession(): Unit? = session?.close() @Deprecated("") fun session(): ISession<*>? = session @Deprecated("") fun result(): T = closeSession().run { result } // @Deprecated("") // fun result_NotCloseSession(): T = result companion object { @Deprecated("Will be deleted soon. ") @JvmStatic fun <T > of(result: T): Res<T> { return Res(result, null) } } }
gpl-3.0
bassph/bassph-app-android
app/src/main/java/org/projectbass/bass/inject/RestModule.kt
1
1411
package org.projectbass.bass.inject import android.content.Context import com.facebook.stetho.okhttp3.StethoInterceptor import org.projectbass.bass.post.api.RestAPI import com.readystatesoftware.chuck.ChuckInterceptor import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import rx.schedulers.Schedulers /** * YOYO HOLDINGS * @author A-Ar Andrew Concepcion * * * * * * @since 14/12/2016 */ @Module class RestModule { @Provides @PerApplication fun provideOkHttpClient(context: Context): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(ChuckInterceptor(context)) .addInterceptor(StethoInterceptor()) .build() } @Provides @PerApplication fun provideRetrofit(client: OkHttpClient): Retrofit { return Retrofit.Builder() .client(client) .baseUrl(RestAPI.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .build() } @Provides @PerApplication fun provideRestApi(retrofit: Retrofit): RestAPI { return retrofit.create(RestAPI::class.java) } }
agpl-3.0
christophpickl/kpotpourri
boot-aop4k/src/test/kotlin/com/github/christophpickl/kpotpourri/bootaop/LogAspectIntegrationTest.kt
1
4974
package com.github.christophpickl.kpotpourri.bootaop // FIXME enable integration test (requires spring boot startup + mockito and stuff) /* @ExtendWith(SpringExtension::class) @ContextConfiguration(classes = [LogAspectTestConfig::class]) class LogAspectIntegrationTest { @Inject private lateinit var loggedComponent: LoggedComponent @MockBean private lateinit var loggerFactory: MyLoggerFactory @Test fun `Given log level enabled When invoke logged method Then proper debug messaged logged`() { val logger = initLogger(LoggedComponent::class.java, isDebugEnabled = true) loggedComponent.loggedMethod() assertThat(logger.captureDebug(), equalTo("loggedMethod()")) } @Test fun `Given log level enabled When invoke logged method with parameter Then proper debug messaged logged`() { val logger = initLogger(LoggedComponent::class.java, isDebugEnabled = true) loggedComponent.loggedMethodWithParam("paramValue") assertThat(logger.captureDebug(), equalTo("loggedMethodWithParam(paramName=paramValue)")) } @Test fun `Given log level enabled When invoke logged method with two parameters Then proper debug messaged logged`() { val logger = initLogger(LoggedComponent::class.java, isDebugEnabled = true) loggedComponent.loggedMethodWithParams("paramValue", 42) assertThat(logger.captureDebug(), equalTo("loggedMethodWithParams(paramName1=paramValue, paramName2=42)")) } @Test fun `Given log level disabled When invoke logged method Then nothing logged`() { val logger = initLogger(LoggedComponent::class.java, isDebugEnabled = false) loggedComponent.loggedMethod() verify(logger).isDebugEnabled verifyNoMoreInteractions(logger) } @Test fun `Given log level enabed When invoke method with NoLog param Then dont log param value`() { val logger = initLogger(LoggedComponent::class.java, isDebugEnabled = true) loggedComponent.loggedMethodNoLogParam("notPrinted") assertThat(logger.captureDebug(), equalTo("loggedMethodNoLogParam(paramName)")) } @Test fun `Given log level enabed When invoke method with NoLog collection param Then only log params value size`() { val logger = initLogger(LoggedComponent::class.java, isDebugEnabled = true) loggedComponent.loggedMethodNoLogCollectionParam(listOf("notPrinted")) assertThat(logger.captureDebug(), equalTo("loggedMethodNoLogCollectionParam(paramName.size=1)")) } @Test fun `Given log level enabled When invoke method with custom log level Then log`() { val logger = initLogger(LoggedComponent::class.java, isTraceEnabled = true) loggedComponent.loggedMethodTraceLevel() assertThat(logger.captureTrace(), equalTo("loggedMethodTraceLevel()")) verify(logger).isTraceEnabled verifyNoMoreInteractions(logger) } @Test fun `Given log log level disabled WHen invoke method with custom log level Then`() { val logger = initLogger(LoggedComponent::class.java, isTraceEnabled = false) loggedComponent.loggedMethodTraceLevel() verify(logger).isTraceEnabled verifyNoMoreInteractions(logger) } private fun initLogger(logTarget: Class<*>, isDebugEnabled: Boolean? = null, isTraceEnabled: Boolean? = null): Logger { val logger = mock<Logger>() whenever(loggerFactory.getLogger(logTarget)).thenReturn(logger) if (isDebugEnabled != null) { whenever(logger.isDebugEnabled).thenReturn(isDebugEnabled) } if (isTraceEnabled != null) { whenever(logger.isTraceEnabled).thenReturn(isTraceEnabled) } return logger } private fun Logger.captureDebug(): String { val captor = argumentCaptor<String>() verify(this).debug(captor.capture()) return captor.firstValue } private fun Logger.captureTrace(): String { val captor = argumentCaptor<String>() verify(this).trace(captor.capture()) return captor.firstValue } } @TestConfiguration @EnableAspectJAutoProxy private class LogAspectTestConfig { @Bean fun loggedComponent() = LoggedComponent() @Bean fun logAspect( // will be wired by test @Suppress("SpringJavaInjectionPointsAutowiringInspection") loggerFactory: MyLoggerFactory ) = LogAspect(loggerFactory) } @Component private class LoggedComponent { @Logged fun loggedMethod() { } @Logged fun loggedMethodWithParam(paramName: String) { } @Logged fun loggedMethodWithParams(paramName1: String, paramName2: Int) { } @Logged fun loggedMethodNoLogParam(@NoLog paramName: String) { } @Logged fun loggedMethodNoLogCollectionParam(@NoLog paramName: List<String>) { } @Logged(level = Level.TRACE) fun loggedMethodTraceLevel() { } } */
apache-2.0
bassph/bassph-app-android
app/src/main/java/org/projectbass/bass/core/Database.kt
1
307
package org.projectbass.bass.core import io.requery.Persistable import io.requery.reactivex.KotlinReactiveEntityStore interface Database { /** * Returns the [KotlinReactiveEntityStore] for executing sql commands to the database. */ fun store(): KotlinReactiveEntityStore<Persistable> }
agpl-3.0
daring2/fms
common/src/main/kotlin/com/gitlab/daring/fms/common/json/DurationJsonSupport.kt
1
1181
package com.gitlab.daring.fms.common.json import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.deser.std.StdNodeBasedDeserializer import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.databind.ser.std.StdSerializer import com.gitlab.daring.fms.common.util.CommonUtils.parseDuration import java.time.Duration object DurationJsonSupport { val handledType = Duration::class.java fun register(m: SimpleModule) { m.addSerializer(Serializer()) m.addDeserializer(handledType, Deserializer()) } class Serializer: StdSerializer<Duration>(handledType) { override fun serialize(v: Duration, gen: JsonGenerator, p: SerializerProvider) { gen.writeNumber(v.toMillis()) } } class Deserializer: StdNodeBasedDeserializer<Duration>(handledType) { override fun convert(n: JsonNode, ctxt: DeserializationContext): Duration { return parseDuration(n.asText()) } } }
apache-2.0
chRyNaN/GuitarChords
core/src/commonMain/kotlin/com.chrynan.chords/util/CharUtils.kt
1
384
package com.chrynan.chords.util private val DIGIT_CHARS = setOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') /** * Returns true if this character (Unicode code point) is a digit. * * Note: I had to explicitly create this function because this is not part of the Kotlin Common Standard Utils. * * @author chRyNaN */ fun Char.isDigit(): Boolean = DIGIT_CHARS.contains(this)
apache-2.0
jsargent7089/android
src/main/java/com/nextcloud/client/core/Cancellable.kt
1
1332
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.core /** * Interface allowing cancellation of a running task. * Once must be careful when cancelling a non-idempotent task, * as cancellation does not guarantee a task termination. * One trivial case would be a task finished and cancelled * before result delivery. * * @see [com.nextcloud.client.core.AsyncRunner] */ interface Cancellable { /** * Cancel running task. Task termination is not guaranteed, but the result * shall not be delivered. */ fun cancel() }
gpl-2.0
Bombe/Sone
src/main/kotlin/net/pterodactylus/sone/database/SoneProvider.kt
1
1163
/* * Sone - SoneProvider.kt - Copyright © 2011–2020 David Roden * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.pterodactylus.sone.database import com.google.inject.* import net.pterodactylus.sone.core.* import net.pterodactylus.sone.data.* /** * Interface for objects that can provide [Sone]s by their ID. */ @ImplementedBy(Core::class) interface SoneProvider { val sones: Collection<Sone> val localSones: Collection<Sone> val remoteSones: Collection<Sone> val soneLoader: (String) -> Sone? fun getSone(soneId: String): Sone? }
gpl-3.0
thanhnbt/kovert
core/src/main/kotlin/uy/kohesive/kovert/core/Exceptions.kt
1
549
package uy.kohesive.kovert.core public open class HttpRedirect(val path: String, val code: Int = 302) : Exception() public open class HttpErrorUnauthorized() : HttpErrorCode("unauthorized", 401) public open class HttpErrorForbidden() : HttpErrorCode("forbidden", 403) public open class HttpErrorBadRequest() : HttpErrorCode("bad request", 400) public open class HttpErrorNotFound() : HttpErrorCode("not found", 404) public open class HttpErrorCode(message: String, val code: Int = 500, causedBy: Throwable? = null) : Exception(message, causedBy)
mit
puras/mo-seed
mo-backend/mo-kotlin-seed/src/main/kotlin/me/puras/mo/seed/kotlin/controller/HomeController.kt
1
837
package me.puras.mo.seed.kotlin.controller import me.puras.common.json.Response import me.puras.common.json.ResponseHelper import me.puras.common.util.ListSlice import me.puras.common.util.Pagination import me.puras.mo.seed.kotlin.domain.User import me.puras.mo.seed.kotlin.service.user.UserService import org.springframework.ui.Model import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class HomeController(var service : UserService) : BaseController() { @GetMapping("/") fun sayHello(pagination : Pagination, model : Model) : Response<List<User>> { var slice : ListSlice<User> = service.findAll(getBounds(pagination)) pagination.totalCount = slice.total return ResponseHelper.createSuccessResponse(slice.list) } }
mit
mp911de/lettuce
src/main/kotlin/io/lettuce/core/api/coroutines/RedisServerCoroutinesCommandsImpl.kt
1
6074
/* * Copyright 2020-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.lettuce.core.api.coroutines import io.lettuce.core.ExperimentalLettuceCoroutinesApi import io.lettuce.core.KillArgs import io.lettuce.core.TrackingArgs import io.lettuce.core.UnblockType import io.lettuce.core.api.reactive.RedisServerReactiveCommands import io.lettuce.core.protocol.CommandType import kotlinx.coroutines.flow.toList import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitFirstOrNull import java.util.* /** * Coroutine executed commands (based on reactive commands) for Server Control. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 * * @generated by io.lettuce.apigenerator.CreateKotlinCoroutinesReactiveImplementation */ @ExperimentalLettuceCoroutinesApi internal class RedisServerCoroutinesCommandsImpl<K : Any, V : Any>(private val ops: RedisServerReactiveCommands<K, V>) : RedisServerCoroutinesCommands<K, V> { override suspend fun bgrewriteaof(): String? = ops.bgrewriteaof().awaitFirstOrNull() override suspend fun bgsave(): String? = ops.bgsave().awaitFirstOrNull() override suspend fun clientCaching(enabled: Boolean): String? = ops.clientCaching(enabled).awaitFirstOrNull() override suspend fun clientGetname(): K? = ops.clientGetname().awaitFirstOrNull() override suspend fun clientGetredir(): Long? = ops.clientGetredir().awaitFirstOrNull() override suspend fun clientId(): Long? = ops.clientId().awaitFirstOrNull() override suspend fun clientKill(addr: String): String? = ops.clientKill(addr).awaitFirstOrNull() override suspend fun clientKill(killArgs: KillArgs): Long? = ops.clientKill(killArgs).awaitFirstOrNull() override suspend fun clientList(): String? = ops.clientList().awaitFirstOrNull() override suspend fun clientPause(timeout: Long): String? = ops.clientPause(timeout).awaitFirstOrNull() override suspend fun clientSetname(name: K): String? = ops.clientSetname(name).awaitFirstOrNull() override suspend fun clientTracking(args: TrackingArgs): String? = ops.clientTracking(args).awaitFirstOrNull() override suspend fun clientUnblock(id: Long, type: UnblockType): Long? = ops.clientUnblock(id, type).awaitFirstOrNull() override suspend fun command(): List<Any> = ops.command().asFlow().toList() override suspend fun commandCount(): Long? = ops.commandCount().awaitFirstOrNull() override suspend fun commandInfo(vararg commands: String): List<Any> = ops.commandInfo(*commands).asFlow().toList() override suspend fun commandInfo(vararg commands: CommandType): List<Any> = ops.commandInfo(*commands).asFlow().toList() override suspend fun configGet(parameter: String): Map<String, String>? = ops.configGet(parameter).awaitFirstOrNull() override suspend fun configResetstat(): String? = ops.configResetstat().awaitFirstOrNull() override suspend fun configRewrite(): String? = ops.configRewrite().awaitFirstOrNull() override suspend fun configSet(parameter: String, value: String): String? = ops.configSet(parameter, value).awaitFirstOrNull() override suspend fun dbsize(): Long? = ops.dbsize().awaitFirstOrNull() override suspend fun debugCrashAndRecover(delay: Long): String? = ops.debugCrashAndRecover(delay).awaitFirstOrNull() override suspend fun debugHtstats(db: Int): String? = ops.debugHtstats(db).awaitFirstOrNull() override suspend fun debugObject(key: K): String? = ops.debugObject(key).awaitFirstOrNull() override suspend fun debugOom() = ops.debugOom().awaitFirstOrNull().let { Unit } override suspend fun debugReload(): String? = ops.debugReload().awaitFirstOrNull() override suspend fun debugRestart(delay: Long): String? = ops.debugRestart(delay).awaitFirstOrNull() override suspend fun debugSdslen(key: K): String? = ops.debugSdslen(key).awaitFirstOrNull() override suspend fun debugSegfault() = ops.debugSegfault().awaitFirstOrNull().let { Unit } override suspend fun flushall(): String? = ops.flushall().awaitFirstOrNull() override suspend fun flushallAsync(): String? = ops.flushallAsync().awaitFirstOrNull() override suspend fun flushdb(): String? = ops.flushdb().awaitFirstOrNull() override suspend fun flushdbAsync(): String? = ops.flushdbAsync().awaitFirstOrNull() override suspend fun info(): String? = ops.info().awaitFirstOrNull() override suspend fun info(section: String): String? = ops.info(section).awaitFirstOrNull() override suspend fun lastsave(): Date? = ops.lastsave().awaitFirstOrNull() override suspend fun memoryUsage(key: K): Long? = ops.memoryUsage(key).awaitFirstOrNull() override suspend fun save(): String? = ops.save().awaitFirstOrNull() override suspend fun shutdown(save: Boolean) = ops.shutdown(save).awaitFirstOrNull().let { Unit } override suspend fun slaveof(host: String, port: Int): String? = ops.slaveof(host, port).awaitFirstOrNull() override suspend fun slaveofNoOne(): String? = ops.slaveofNoOne().awaitFirstOrNull() override suspend fun slowlogGet(): List<Any> = ops.slowlogGet().asFlow().toList() override suspend fun slowlogGet(count: Int): List<Any> = ops.slowlogGet(count).asFlow().toList() override suspend fun slowlogLen(): Long? = ops.slowlogLen().awaitFirstOrNull() override suspend fun slowlogReset(): String? = ops.slowlogReset().awaitFirstOrNull() override suspend fun time(): List<V> = ops.time().asFlow().toList() }
apache-2.0
spark/photon-tinker-android
meshui/src/main/java/io/particle/mesh/ui/setup/BoronConnectingStatusFragment.kt
1
1401
package io.particle.mesh.ui.setup import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.FragmentActivity import androidx.lifecycle.Observer import io.particle.mesh.common.truthy import io.particle.mesh.setup.flow.FlowRunnerUiListener import io.particle.mesh.ui.BaseFlowFragment import io.particle.mesh.ui.utils.markProgress import io.particle.mesh.ui.R class BoronConnectingStatusFragment : BaseFlowFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_boron_connecting_status, container, false) } override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) { super.onFragmentReady(activity, flowUiListener) markProgress(true, R.id.status_stage_1) flowUiListener.targetDevice.isSimActivatedLD.observe(this, Observer { if (it.truthy()) { markProgress(true, R.id.status_stage_2) flowUiListener.targetDevice.isDeviceConnectedToCloudLD.observe(this, Observer { if (it.truthy()) { markProgress(true, R.id.status_stage_3) } }) } }) } }
apache-2.0
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepShowLetsGetBuildingUi.kt
1
456
package io.particle.mesh.setup.flow.setupsteps import io.particle.mesh.setup.flow.FlowUiDelegate import io.particle.mesh.setup.flow.MeshSetupStep import io.particle.mesh.setup.flow.Scopes import io.particle.mesh.setup.flow.context.SetupContexts class StepShowLetsGetBuildingUi(private val flowUi: FlowUiDelegate) : MeshSetupStep() { override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) { flowUi.showSetupFinishedUi() } }
apache-2.0
chenxyu/android-banner
bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/indicator/ScrollBarView.kt
1
4982
package com.chenxyu.bannerlibrary.indicator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.view.View import androidx.recyclerview.widget.RecyclerView import com.chenxyu.bannerlibrary.extend.dpToPx import java.math.BigDecimal /** * @Author: ChenXingYu * @CreateDate: 2021/3/27 22:38 * @Description: 滚动条 * @Version: 1.0 */ internal class ScrollBarView : View { companion object { private const val RADIUS = 5F } private val mPaint: Paint = Paint() private val mRectF = RectF() private var mMeasureWidth: Int = 0 private var mMeasureHeight: Int = 0 private var mBarWH: Int = 0 private var mStartX: Int = 0 private var mStartY: Int = 0 private var mDx: Float = 0F private var mDy: Float = 0F private var mMaxWH: Int = 0 /** * 方向 */ var orientation: Int = RecyclerView.HORIZONTAL /** * 滚动条颜色 */ var barColor: Int? = null set(value) { field = value invalidate() } /** * 滚动条轨道颜色 */ var trackColor: Int? = null set(value) { field = value invalidate() } init { mPaint.apply { isAntiAlias = true style = Paint.Style.FILL } } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = MeasureSpec.getMode(widthMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) mMeasureWidth = 0 mMeasureHeight = 0 if (widthMode == MeasureSpec.EXACTLY) { mMeasureWidth = widthSize } else if (widthMode == MeasureSpec.AT_MOST) { mMeasureWidth = widthSize.coerceAtMost(width) } if (heightMode == MeasureSpec.EXACTLY) { mMeasureHeight = heightSize } else if (heightMode == MeasureSpec.AT_MOST) { mMeasureHeight = heightSize.coerceAtMost(height) } setMeasuredDimension(mMeasureWidth, mMeasureHeight) } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) when (orientation) { RecyclerView.HORIZONTAL -> { mBarWH = mMeasureWidth.div(2) // 轨道 mPaint.apply { color = trackColor ?: Color.WHITE } mRectF.set(0F, 0F, mMeasureWidth.toFloat(), mMeasureHeight.toFloat()) canvas?.drawRoundRect(mRectF, RADIUS.dpToPx(context), RADIUS.dpToPx(context), mPaint) // 滚动条 mPaint.apply { color = barColor ?: Color.BLUE } mRectF.set(mDx, 0F, mBarWH + mDx, mMeasureHeight.toFloat()) canvas?.drawRoundRect(mRectF, RADIUS.dpToPx(context), RADIUS.dpToPx(context), mPaint) } RecyclerView.VERTICAL -> { mBarWH = mMeasureHeight.div(2) // 轨道 mPaint.apply { color = trackColor ?: Color.WHITE } mRectF.set(0F, 0F, mMeasureWidth.toFloat(), mMeasureHeight.toFloat()) canvas?.drawRoundRect(mRectF, RADIUS.dpToPx(context), RADIUS.dpToPx(context), mPaint) // 滚动条 mPaint.apply { color = barColor ?: Color.BLUE } mRectF.set(0F, mDy, mMeasureWidth.toFloat(), mBarWH + mDy) canvas?.drawRoundRect(mRectF, RADIUS.dpToPx(context), RADIUS.dpToPx(context), mPaint) } } } fun scroll(maxWH: Int, dx: Int, dy: Int) { if (maxWH != 0) { when (orientation) { RecyclerView.HORIZONTAL -> { mMaxWH = maxWH val b1 = BigDecimal(mMeasureWidth - mBarWH) val b2 = BigDecimal(mMaxWH) val b3 = BigDecimal(mStartX + dx) mDx = b1.divide(b2, 5, BigDecimal.ROUND_HALF_UP).times(b3).toFloat() mStartX += dx } RecyclerView.VERTICAL -> { mMaxWH = maxWH val b1 = BigDecimal(mMeasureHeight - mBarWH) val b2 = BigDecimal(mMaxWH) val b3 = BigDecimal(mStartY + dy) mDy = b1.divide(b2, 5, BigDecimal.ROUND_HALF_UP).times(b3).toFloat() mStartY += dy } } invalidate() } } }
mit
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/lang/core/types/ty/TyTuple.kt
2
516
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types.ty import org.rust.lang.core.types.infer.TypeFolder import org.rust.lang.core.types.infer.TypeVisitor data class TyTuple(val types: List<Ty>) : Ty(mergeFlags(types)) { override fun superFoldWith(folder: TypeFolder): Ty = TyTuple(types.map { it.foldWith(folder) }) override fun superVisitWith(visitor: TypeVisitor): Boolean = types.any(visitor) }
mit
square/leakcanary
shark-hprof/src/main/java/shark/HprofRecordTag.kt
2
2287
package shark import java.util.EnumSet enum class HprofRecordTag(val tag: Int) { STRING_IN_UTF8(0x01), LOAD_CLASS(0x02), // Currently ignored UNLOAD_CLASS(0x03), STACK_FRAME(0x04), STACK_TRACE(0x05), // Currently ignored ALLOC_SITES(0x06), // Currently ignored HEAP_SUMMARY(0x07), // Currently ignored START_THREAD(0x0a), // Currently ignored END_THREAD(0x0b), // Currently not reported HEAP_DUMP(0x0c), // Currently not reported HEAP_DUMP_SEGMENT(0x1c), HEAP_DUMP_END(0x2c), // Currently ignored CPU_SAMPLES(0x0d), // Currently ignored CONTROL_SETTINGS(0x0e), ROOT_UNKNOWN(0xff), ROOT_JNI_GLOBAL(0x01), ROOT_JNI_LOCAL(0x02), ROOT_JAVA_FRAME(0x03), ROOT_NATIVE_STACK(0x04), ROOT_STICKY_CLASS(0x05), // An object that was referenced from an active thread block. ROOT_THREAD_BLOCK(0x06), ROOT_MONITOR_USED(0x07), ROOT_THREAD_OBJECT(0x08), /** * Android format addition * * Specifies information about which heap certain objects came from. When a sub-tag of this type * appears in a HPROF_HEAP_DUMP or HPROF_HEAP_DUMP_SEGMENT record, entries that follow it will * be associated with the specified heap. The HEAP_DUMP_INFO data is reset at the end of the * `HEAP_DUMP[_SEGMENT]`. Multiple HEAP_DUMP_INFO entries may appear in a single * `HEAP_DUMP[_SEGMENT]`. * * Format: u1: Tag value (0xFE) u4: heap ID ID: heap name string ID */ HEAP_DUMP_INFO(0xfe), ROOT_INTERNED_STRING(0x89), ROOT_FINALIZING(0x8a), ROOT_DEBUGGER(0x8b), ROOT_REFERENCE_CLEANUP(0x8c), ROOT_VM_INTERNAL(0x8d), ROOT_JNI_MONITOR(0x8e), ROOT_UNREACHABLE(0x90), // Not supported. PRIMITIVE_ARRAY_NODATA(0xc3), CLASS_DUMP(0x20), INSTANCE_DUMP(0x21), OBJECT_ARRAY_DUMP(0x22), PRIMITIVE_ARRAY_DUMP(0x23), ; companion object { val rootTags: EnumSet<HprofRecordTag> = EnumSet.of( ROOT_UNKNOWN, ROOT_JNI_GLOBAL, ROOT_JNI_LOCAL, ROOT_JAVA_FRAME, ROOT_NATIVE_STACK, ROOT_STICKY_CLASS, ROOT_THREAD_BLOCK, ROOT_MONITOR_USED, ROOT_THREAD_OBJECT, ROOT_INTERNED_STRING, ROOT_FINALIZING, ROOT_DEBUGGER, ROOT_REFERENCE_CLEANUP, ROOT_VM_INTERNAL, ROOT_JNI_MONITOR, ROOT_UNREACHABLE ) } }
apache-2.0
google/horologist
media-sample/src/androidTest/java/com/google/android/horologist/mediasample/runner/MediaAppRunner.kt
1
1148
/* * 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.android.horologist.mediasample.runner import android.app.Application import android.content.Context import androidx.test.runner.AndroidJUnitRunner import dagger.hilt.android.testing.HiltTestApplication import kotlin.reflect.jvm.jvmName class MediaAppRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, HiltTestApplication::class.jvmName, context) } }
apache-2.0
tmarsteel/compiler-fiddle
src/compiler/binding/expression/BoundIfExpression.kt
1
3931
/* * Copyright 2018 Tobias Marstaller * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.binding.expression import compiler.ast.expression.Expression import compiler.ast.expression.IfExpression import compiler.binding.BoundExecutable import compiler.binding.context.CTContext import compiler.binding.type.BaseTypeReference import compiler.binding.type.BuiltinBoolean import compiler.binding.type.Unit import compiler.nullableAnd import compiler.reportings.Reporting class BoundIfExpression( override val context: CTContext, override val declaration: IfExpression, val condition: BoundExpression<Expression<*>>, val thenCode: BoundExecutable<*>, val elseCode: BoundExecutable<*>? ) : BoundExpression<IfExpression>, BoundExecutable<IfExpression> { override val isGuaranteedToThrow: Boolean? get() = thenCode.isGuaranteedToThrow nullableAnd (elseCode?.isGuaranteedToThrow ?: false) override val isGuaranteedToReturn: Boolean? get() { if (elseCode == null) { return false } else { return thenCode.isGuaranteedToReturn nullableAnd elseCode.isGuaranteedToReturn } } override var type: BaseTypeReference? = null private set override fun semanticAnalysisPhase1(): Collection<Reporting> { var reportings = condition.semanticAnalysisPhase1() + thenCode.semanticAnalysisPhase1() val elseCodeReportings = elseCode?.semanticAnalysisPhase1() if (elseCodeReportings != null) { reportings = reportings + elseCodeReportings } return reportings } override fun semanticAnalysisPhase2(): Collection<Reporting> { var reportings = condition.semanticAnalysisPhase2() + thenCode.semanticAnalysisPhase2() val elseCodeReportings = elseCode?.semanticAnalysisPhase2() if (elseCodeReportings != null) { reportings = reportings + elseCodeReportings } return reportings } override fun semanticAnalysisPhase3(): Collection<Reporting> { var reportings = mutableSetOf<Reporting>() reportings.addAll(condition.semanticAnalysisPhase3()) reportings.addAll(thenCode.semanticAnalysisPhase3()) if (elseCode != null) { reportings.addAll(elseCode.semanticAnalysisPhase3()) } if (condition.type != null) { val conditionType = condition.type!! if (!conditionType.isAssignableTo(BuiltinBoolean.baseReference(context))) { reportings.add(Reporting.conditionIsNotBoolean(condition, condition.declaration.sourceLocation)) } } var thenType = if (thenCode is BoundExpression<*>) thenCode.type else Unit.baseReference(context) var elseType = if (elseCode is BoundExpression<*>) elseCode.type else Unit.baseReference(context) if (thenType != null && elseType != null) { type = BaseTypeReference.closestCommonAncestorOf(thenType, elseType) } return reportings } override fun enforceReturnType(type: BaseTypeReference) { thenCode.enforceReturnType(type) elseCode?.enforceReturnType(type) } }
lgpl-3.0
epabst/kotlin-showcase
src/jsMain/kotlin/bootstrap/Row.kt
1
491
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused") @file:JsModule("react-bootstrap") package bootstrap import org.w3c.dom.HTMLDivElement external interface RowProps : HTMLElementProps<HTMLDivElement> { var noGutters: Boolean? get() = definedExternally; set(value) = definedExternally } abstract external class Row<As : React.ElementType> : BsPrefixComponent<As, RowProps>
apache-2.0
yshrsmz/monotweety
data/src/main/java/net/yslibrary/monotweety/data/SingletonDataModule.kt
1
1384
package net.yslibrary.monotweety.data import android.content.Context import android.content.pm.PackageManager import com.codingfeline.twitter4kt.core.ConsumerKeys import com.codingfeline.twitter4kt.core.Twitter import com.codingfeline.twitter4kt.core.oauth1a.OAuthConfig import dagger.Module import dagger.Provides import kotlinx.datetime.Clock import net.yslibrary.monotweety.data.auth.AuthDataModule import net.yslibrary.monotweety.data.session.SessionDataModule import net.yslibrary.monotweety.data.settings.SettingsDataModule import net.yslibrary.monotweety.data.twitterapp.TwitterAppDataModule @Module( includes = [ AuthDataModule::class, SessionDataModule::class, SettingsDataModule::class, TwitterAppDataModule::class, ] ) object SingletonDataModule { @Provides fun providePackageManager(context: Context): PackageManager = context.packageManager @Provides fun provideTwitter( consumerKeys: ConsumerKeys, clock: Clock, ): Twitter { return Twitter { this.consumerKeys = consumerKeys this.oAuthConfig = OAuthConfig() this.clock = clock // this.httpClientConfig = { // install(Logging) { // level = LogLevel.ALL // logger = Logger.SIMPLE // } // } } } }
apache-2.0
lehaSVV2009/dnd
api/src/main/kotlin/kadet/dnd/api/model/Profile.kt
1
749
package kadet.dnd.api.model class Profile { /** * Display name like 'Frode' or 'Alex' */ val name: String? = null /** * Hero notes */ val description: String? = null /** * Link to avatar */ val avatar: String? = null /** * Link to large descriptive image */ val image: String? = null /** * From 0 to .... * Level is calculated from experience */ val experience: Int = 0 /** * Wizard/warrior/... */ // TODO move to enums val category: String? = null /** * Elf/dwarf/... */ // TODO move to enums val race: String? = null /** * Known languages */ val languages: Set<String> = setOf() }
mit
clhols/zapr
app/src/main/java/dk/youtec/zapr/ui/view/AspectImageView.kt
1
1264
package dk.youtec.zapr.ui.view import android.content.Context import android.support.v7.widget.AppCompatImageView import android.util.AttributeSet class AspectImageView : AppCompatImageView { private var mMeasurer: ViewAspectRatioMeasurer? = 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) { } fun setAspectRatio(width: Int, height: Int) { val ratio = width.toDouble() / height if (mMeasurer?.aspectRatio != ratio) { mMeasurer = ViewAspectRatioMeasurer(ratio) } } fun setAspectRatio(ratio: Double) { if (mMeasurer?.aspectRatio != ratio) { mMeasurer = ViewAspectRatioMeasurer(ratio) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { if (mMeasurer != null) { mMeasurer!!.measure(widthMeasureSpec, heightMeasureSpec) setMeasuredDimension(mMeasurer!!.measuredWidth, mMeasurer!!.measuredHeight) } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } } }
mit
vase4kin/TeamCityApp
app/src/test/java/com/github/vase4kin/teamcityapp/changes/presenter/ChangesPresenterImplTest.kt
1
4640
/* * Copyright 2019 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.changes.presenter import com.github.vase4kin.teamcityapp.account.create.data.OnLoadingListener import com.github.vase4kin.teamcityapp.base.tracker.ViewTracker import com.github.vase4kin.teamcityapp.changes.api.Changes import com.github.vase4kin.teamcityapp.changes.data.ChangesDataManager import com.github.vase4kin.teamcityapp.changes.extractor.ChangesValueExtractor import com.github.vase4kin.teamcityapp.changes.view.ChangesView import com.github.vase4kin.teamcityapp.utils.any import com.github.vase4kin.teamcityapp.utils.capture import com.github.vase4kin.teamcityapp.utils.eq import com.mugen.MugenCallbacks import org.hamcrest.core.Is.`is` import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.runners.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class ChangesPresenterImplTest { @Captor private lateinit var onLoadMoreListenerArgumentCaptor: ArgumentCaptor<MugenCallbacks> @Captor private lateinit var onChangesLoadingListener: ArgumentCaptor<OnLoadingListener<List<Changes.Change>>> @Captor private lateinit var onLoadingListenerArgumentCaptor: ArgumentCaptor<OnLoadingListener<Int>> @Mock private lateinit var loadingListener: OnLoadingListener<List<Changes.Change>> @Mock private lateinit var view: ChangesView @Mock internal lateinit var dataManager: ChangesDataManager @Mock internal lateinit var tracker: ViewTracker @Mock internal lateinit var valueExtractor: ChangesValueExtractor private lateinit var presenter: ChangesPresenterImpl @Before fun setUp() { presenter = ChangesPresenterImpl(view, dataManager, tracker, valueExtractor) } @Test fun testInitViews() { `when`(dataManager.canLoadMore()).thenReturn(false) presenter.initViews() verify(view).setLoadMoreListener(capture(onLoadMoreListenerArgumentCaptor)) val onLoadMoreListener = onLoadMoreListenerArgumentCaptor.value assertThat(onLoadMoreListener.hasLoadedAllItems(), `is`(true)) verify(dataManager).canLoadMore() onLoadMoreListener.onLoadMore() verify(view).addLoadMore() verify(dataManager).loadMore(capture(onChangesLoadingListener)) assertThat(presenter.isLoadMoreLoading, `is`(true)) val onChangesLoadingListener = this.onChangesLoadingListener.value val changes = emptyList<Changes.Change>() onChangesLoadingListener.onSuccess(changes) verify(view).removeLoadMore() verify(view).addMoreBuilds(any()) assertThat(presenter.isLoadMoreLoading, `is`(false)) onChangesLoadingListener.onFail("error") verify(view, times(2)).removeLoadMore() verify(view).showRetryLoadMoreSnackBar() assertThat(presenter.isLoadMoreLoading, `is`(false)) } @Test fun testLoadData() { `when`(valueExtractor.url).thenReturn("url") presenter.loadData(loadingListener, false) verify(valueExtractor).url verify(dataManager).loadLimited(eq("url"), eq(loadingListener), eq(false)) verifyNoMoreInteractions(view, dataManager, tracker, valueExtractor) } @Test fun testCreateModel() { val changes = mutableListOf<Changes.Change>() assertThat(presenter.createModel(changes).itemCount, `is`(0)) } @Test fun testOnViewsCreated() { `when`(valueExtractor.url).thenReturn("url") presenter.onViewsCreated() verify(valueExtractor, times(2)).url verify(dataManager).loadTabTitle(eq("url"), capture(onLoadingListenerArgumentCaptor)) val listener = onLoadingListenerArgumentCaptor.value listener.onSuccess(1) verify(dataManager).postChangeTabTitleEvent(eq(1)) listener.onFail("error") verifyNoMoreInteractions(valueExtractor) } }
apache-2.0
seansu4you87/kupo
projects/gategallop/services/cartman/src/main/kotlin/cartman.kt
1
483
import gg.cartman.data.Cart import gg.cartman.service.CartmanGrpc import io.grpc.stub.StreamObserver /** * Created by sean on 7/31/17. */ class Cartman : CartmanGrpc.CartmanImplBase() { override fun createCart(request: Cart?, responseObserver: StreamObserver<Cart>?) { super.createCart(request, responseObserver) } override fun updateCart(request: Cart?, responseObserver: StreamObserver<Cart>?) { super.updateCart(request, responseObserver) } }
mit
adelnizamutdinov/headphone-reminder
app/src/main/kotlin/common/view/flow.kt
1
491
package common.view import domain.Screen import flow.Flow import flow.History fun Flow.push(t: Screen): Unit = history.buildUpon() .push(t) .build() .let { setHistory(it, Flow.Direction.FORWARD) } private fun History.Builder.replace(s: Screen): History.Builder = run { pop() push(s) } fun Flow.replaceTo(t: Screen): Unit = history.buildUpon() .replace(t) .build() .let { setHistory(it, Flow.Direction.REPLACE) }
mit
googleads/googleads-mobile-flutter
samples/admob/adaptive_banner_example/android/app/src/main/kotlin/com/example/banner_example/MainActivity.kt
1
140
package com.example.adaptive_banner_example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
apache-2.0
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/feedback/Flag.kt
1
678
package wu.seal.jsontokotlin.feedback import com.intellij.ide.plugins.PluginManager import com.intellij.openapi.extensions.PluginId import wu.seal.jsontokotlin.model.ConfigManager import wu.seal.jsontokotlin.test.TestConfig /** * Flag relative * Created by Seal.Wu on 2017/9/25. */ val PLUGIN_VERSION = if (TestConfig.isTestModel.not()){ PluginManager.getPlugin(PluginId.getId("wu.seal.tool.jsontokotlin"))?.version.toString() } else "1.X" val UUID = if (ConfigManager.userUUID.isEmpty()) { val uuid = java.util.UUID.randomUUID().toString() ConfigManager.userUUID = uuid uuid } else ConfigManager.userUUID const val PLUGIN_NAME = "JSON To Kotlin Class"
gpl-3.0
SimpleTimeTracking/StandaloneClient
src/main/kotlin/org/stt/config/CliConfig.kt
1
136
package org.stt.config class CliConfig : ConfigurationContainer { var cliReportingWidth = 80 var systemOutEncoding = "UTF-8" }
gpl-3.0
roylanceMichael/yaorm
buildSrc/src/main/java/utilities/FileProcessUtilities.kt
1
7511
package utilities import org.apache.commons.compress.archivers.tar.TarArchiveEntry import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream import org.apache.commons.io.IOUtils import java.io.* import java.util.* object FileProcessUtilities { private const val Space = " " private const val TempDirectory = "java.io.tmpdir" private val knownApplicationLocations = HashMap<String, String>() private val whitespaceRegex = Regex("\\s+") fun buildCommand(application: String, allArguments: String):List<String> { val returnList = ArrayList<String>() val actualApplicationLocation = getActualLocation(application) print(actualApplicationLocation) if (actualApplicationLocation.isEmpty()) { returnList.add(application) } else { returnList.add(actualApplicationLocation) } val splitArguments = allArguments.split(whitespaceRegex) returnList.addAll(splitArguments) return returnList } fun readFile(path: String): String { val foundFile = File(path) return foundFile.readText() } fun writeFile(file: String, path: String) { val newFile = File(path) newFile.writeText(file) } fun handleProcess(process: ProcessBuilder, name: String) { try { process.redirectError(ProcessBuilder.Redirect.INHERIT) process.redirectOutput(ProcessBuilder.Redirect.INHERIT) process.start().waitFor() println("finished $name") } catch (e: IOException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } } fun buildReport(process: Process): MusubiModel.ProcessReport { val returnReport = MusubiModel.ProcessReport.newBuilder() val inputWriter = StringWriter() val errorWriter = StringWriter() IOUtils.copy(process.inputStream, inputWriter) IOUtils.copy(process.errorStream, errorWriter) return returnReport.setErrorOutput(errorWriter.toString()).setNormalOutput(inputWriter.toString()).build() } fun executeProcess(location: String, application: String, allArguments: String): MusubiModel.ProcessReport { val tempFile = File(getTempDirectory(), UUID.randomUUID().toString()) val actualCommand = buildCommand(application, allArguments).joinToString(Space) val tempScript = buildTempScript(location, actualCommand) tempFile.writeText(tempScript) try { Runtime.getRuntime().exec("${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempFile.absolutePath}") val process = Runtime.getRuntime().exec(tempFile.absolutePath) process.waitFor() val report = buildReport(process).toBuilder() report.normalOutput = report.normalOutput + "\n" + tempScript return report.build() } finally { tempFile.delete() } } fun executeScript(location: String, application: String, script: String): MusubiModel.ProcessReport { val tempScript = File(getTempDirectory(), UUID.randomUUID().toString()) tempScript.writeText(script) val tempFile = File(getTempDirectory(), UUID.randomUUID().toString()) val actualCommand = buildCommand(application, tempScript.absolutePath).joinToString(Space) val tempExecuteScript = buildTempScript(location, actualCommand) tempFile.writeText(tempExecuteScript) try { Runtime.getRuntime().exec("${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempFile.absolutePath}") Runtime.getRuntime().exec("${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempScript.absolutePath}") val process = Runtime.getRuntime().exec(tempFile.absolutePath) process.waitFor() val report = buildReport(process).toBuilder() report.normalOutput = report.normalOutput + "\n" + tempScript return report.build() } finally { tempScript.delete() tempFile.delete() } } fun createTarFromDirectory(inputDirectory: String, outputFile: String, directoriesToExclude: HashSet<String>): Boolean { val directory = File(inputDirectory) if (!directory.exists()) { return false } val outputStream = FileOutputStream(File(outputFile)) val bufferedOutputStream = BufferedOutputStream(outputStream) val gzipOutputStream = GzipCompressorOutputStream(bufferedOutputStream) val tarOutputStream = TarArchiveOutputStream(gzipOutputStream) try { addFileToTarGz(tarOutputStream, inputDirectory, "", directoriesToExclude) } finally { tarOutputStream.finish() tarOutputStream.close() gzipOutputStream.close() bufferedOutputStream.close() outputStream.close() } return true } fun getActualLocation(application: String): String { if (knownApplicationLocations.containsKey(application)) { return knownApplicationLocations[application]!! } val tempFile = File(getTempDirectory(), UUID.randomUUID().toString()) tempFile.writeText("""#!/usr/bin/env bash . ~/.bash_profile . ~/.bashrc which $application""") print(tempFile.readText()) val inputWriter = StringWriter() try { Runtime.getRuntime().exec("${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempFile.absolutePath}") val process = Runtime.getRuntime().exec(tempFile.absolutePath) process.waitFor() IOUtils.copy(process.inputStream, inputWriter) return inputWriter.toString().trim() } finally { inputWriter.close() tempFile.delete() } } private fun addFileToTarGz(tarOutputStream: TarArchiveOutputStream, path: String, base: String, directoriesToExclude: HashSet<String>) { val fileOrDirectory = File(path) if (directoriesToExclude.contains(fileOrDirectory.name)) { return } val entryName: String if (base.isEmpty()) { entryName = "." } else { entryName = base + fileOrDirectory.name } val tarEntry = TarArchiveEntry(fileOrDirectory, entryName) tarOutputStream.putArchiveEntry(tarEntry) if (fileOrDirectory.isDirectory) { fileOrDirectory.listFiles()?.forEach { file -> addFileToTarGz(tarOutputStream, file.absolutePath, "$entryName/", directoriesToExclude) } } else { val inputStream = FileInputStream(fileOrDirectory) try { IOUtils.copy(inputStream, tarOutputStream) } finally { inputStream.close() tarOutputStream.closeArchiveEntry() } } } private fun getTempDirectory(): String { return System.getProperty(TempDirectory) } private fun buildTempScript(location: String, actualCommand: String): String { return """#!/usr/bin/env bash . ~/.bash_profile . ~/.bashrc pushd $location $actualCommand """ } }
mit
rumboalla/apkupdater
app/src/main/java/com/apkupdater/repository/googleplay/GooglePlayRepository.kt
1
3434
package com.apkupdater.repository.googleplay import android.content.Context import android.content.res.Resources import android.util.Log import com.apkupdater.R import com.apkupdater.model.ui.AppInstalled import com.apkupdater.model.ui.AppSearch import com.apkupdater.model.ui.AppUpdate import com.apkupdater.util.aurora.NativeDeviceInfoProvider import com.apkupdater.util.aurora.OkHttpClientAdapter import com.apkupdater.util.ioScope import com.apkupdater.util.orZero import com.dragons.aurora.playstoreapiv2.AppDetails import com.dragons.aurora.playstoreapiv2.DocV2 import com.dragons.aurora.playstoreapiv2.GooglePlayAPI import com.dragons.aurora.playstoreapiv2.PlayStoreApiBuilder import com.dragons.aurora.playstoreapiv2.SearchIterator import kotlinx.coroutines.async import org.koin.core.KoinComponent import org.koin.core.inject @Suppress("BlockingMethodInNonBlockingContext") class GooglePlayRepository: KoinComponent { private val dispenserUrl = "http://auroraoss.com:8080" private val context: Context by inject() private val api: GooglePlayAPI by lazy { getApi(context) } fun updateAsync(apps: Sequence<AppInstalled>) = ioScope.async { runCatching { val details = api.bulkDetails(apps.map { it.packageName }.toList()) val updates = mutableListOf<AppUpdate>() // TODO: Filter experimental? details.entryList.forEach { entry -> runCatching { apps.getApp(entry.doc.details.appDetails.packageName)?.let { app -> if (entry.doc.details.appDetails.versionCode > app.versionCode.orZero()) { updates.add(AppUpdate.from(app, entry.doc.details.appDetails)) } } }.onFailure { Log.e("GooglePlayRepository", "updateAsync", it) } } updates }.fold(onSuccess = { Result.success(it) }, onFailure = { Result.failure(it) }) } fun searchAsync(text: String) = ioScope.async { runCatching { SearchIterator(api, text).next()?.toList().orEmpty().map { AppSearch.from(it) }.shuffled().take(10).sortedBy { it.name }.toList() }.fold(onSuccess = { Result.success(it) }, onFailure = { Result.failure(it) }) } fun getDownloadUrl(packageName: String, versionCode: Int, oldVersionCode: Int): String { val p = api.purchase(packageName, versionCode, 1) val d = api.delivery(packageName, oldVersionCode, versionCode, 1, p.downloadToken) return d.appDeliveryData.downloadUrl } private fun getProvider(context: Context) = NativeDeviceInfoProvider().apply { setContext(context) setLocaleString(Resources.getSystem().configuration.locale.toString()) } private fun getApi(context: Context): GooglePlayAPI = PlayStoreApiBuilder().apply { httpClient = OkHttpClientAdapter(context) tokenDispenserUrl = dispenserUrl deviceInfoProvider = getProvider(context) }.build() private fun AppSearch.Companion.from(doc: DocV2) = AppSearch( doc.title, "play", doc.imageList.find { image -> image.imageType == GooglePlayAPI.IMAGE_TYPE_APP_ICON }?.imageUrl.orEmpty(), doc.details.appDetails.packageName, R.drawable.googleplay_logo, doc.details.appDetails.packageName, doc.details.appDetails.versionCode ) private fun AppUpdate.Companion.from(app: AppInstalled, entry: AppDetails) = AppUpdate( app.name, app.packageName, entry.versionString, entry.versionCode, app.version, app.versionCode, "play", R.drawable.googleplay_logo ) private fun Sequence<AppInstalled>.getApp(packageName: String) = this.find { it.packageName == packageName } }
gpl-3.0
jtlalka/fiszki
app/src/main/kotlin/net/tlalka/fiszki/view/activities/LessonActivity.kt
1
3211
package net.tlalka.fiszki.view.activities import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import butterknife.BindView import butterknife.OnClick import net.tlalka.fiszki.R import net.tlalka.fiszki.domain.controllers.LessonController import net.tlalka.fiszki.domain.utils.ValidUtils import net.tlalka.fiszki.model.dto.parcel.LessonDto import net.tlalka.fiszki.model.types.LanguageType import net.tlalka.fiszki.view.fragments.LanguageDialogFragment import net.tlalka.fiszki.view.navigations.Navigator import javax.inject.Inject class LessonActivity : BasePageActivity(), LanguageDialogFragment.DialogListener { @BindView(R.id.lesson_topic) lateinit var lessonTopic: TextView @BindView(R.id.lesson_progress) lateinit var lessonProgress: TextView @BindView(R.id.lesson_show_word) lateinit var lessonShowWord: Button @BindView(R.id.lesson_check_word) lateinit var lessonCheckWord: Button @Inject lateinit var lessonController: LessonController @Inject lateinit var navigator: Navigator @Inject lateinit var lessonDto: LessonDto public override fun onCreate(bundle: Bundle?) { super.onCreate(bundle) super.setContentView(R.layout.lesson_activity) super.activityComponent.inject(this) runActivity() } private fun runActivity() { lessonTopic.text = getString(R.string.lesson_topic, lessonDto.lessonIndex, lessonDto.lessonName) generateView() } private fun generateView() { if (lessonController.hasNextWord()) { lessonProgress.text = lessonController.getLessonStatus() lessonShowWord.text = lessonController.getNextWord() lessonCheckWord.text = getText(R.string.lesson_check_word) } else { showLessonSummary() } } private fun showLessonSummary() { lessonController.updateLessonDto(lessonDto) lessonController.updateLessonProgress() navigator.openLessonScoreActivity(this, lessonDto) navigator.finish(this) } @OnClick(R.id.lesson_check_word) fun onCheckWordClick(@Suppress("UNUSED_PARAMETER") view: View?) { val word = this.lessonController.getTranslateWord() if (ValidUtils.isNotNull(word)) { lessonCheckWord.text = word.value } else { LanguageDialogFragment .getInstance(lessonController.getLanguages()) .show(fragmentManager, LanguageDialogFragment::class.java.name) } } override fun onLanguageSelected(languageType: LanguageType) { lessonController.setTranslation(languageType) onCheckWordClick(lessonCheckWord) } @OnClick(R.id.button_correct) fun onCorrectClick(@Suppress("UNUSED_PARAMETER") view: View) { lessonController.correctAnswer() generateView() } @OnClick(R.id.button_incorrect) fun onIncorrectClick(@Suppress("UNUSED_PARAMETER") view: View) { lessonController.incorrectAnswer() generateView() } }
mit
czyzby/gdx-setup
src/main/kotlin/com/github/czyzby/setup/data/project/project.kt
1
12484
package com.github.czyzby.setup.data.project import com.badlogic.gdx.Files import com.badlogic.gdx.utils.GdxRuntimeException import com.github.czyzby.setup.data.files.* import com.github.czyzby.setup.data.gradle.GradleFile import com.github.czyzby.setup.data.gradle.RootGradleFile import com.github.czyzby.setup.data.langs.Java import com.github.czyzby.setup.data.libs.unofficial.USL import com.github.czyzby.setup.data.platforms.Android import com.github.czyzby.setup.data.platforms.Assets import com.github.czyzby.setup.data.platforms.Platform import com.github.czyzby.setup.data.templates.KtxTemplate import com.github.czyzby.setup.data.templates.Template import com.github.czyzby.setup.views.AdvancedData import com.github.czyzby.setup.views.BasicProjectData import com.github.czyzby.setup.views.ExtensionsData import com.github.czyzby.setup.views.LanguagesData import com.kotcrab.vis.ui.util.OsUtils import java.io.BufferedReader import java.io.File import java.io.InputStreamReader /** * Contains data about the generated project. * @author MJ */ class Project(val basic: BasicProjectData, val platforms: Map<String, Platform>, val advanced: AdvancedData, val languages: LanguagesData, val extensions: ExtensionsData, val template: Template) { private val gradleFiles: Map<String, GradleFile> val files = mutableListOf<ProjectFile>() val rootGradle: RootGradleFile val properties = mutableMapOf( "org.gradle.daemon" to "true", "org.gradle.jvmargs" to "-Xms128m -Xmx512m", "org.gradle.configureondemand" to "true") val postGenerationTasks = mutableListOf<(Project) -> Unit>() val gwtInherits = mutableSetOf<String>() val androidPermissions = mutableSetOf<String>() val reflectedClasses = mutableSetOf<String>() val reflectedPackages = mutableSetOf<String>() // README.md: var readmeDescription = "" val gradleTaskDescriptions = mutableMapOf<String, String>() init { gradleFiles = mutableMapOf<String, GradleFile>() rootGradle = RootGradleFile(this) platforms.forEach { gradleFiles[it.key] = it.value.createGradleFile(this) } addBasicGradleTasksDescriptions() } private fun addBasicGradleTasksDescriptions() { if (advanced.generateReadme) { arrayOf("idea" to "generates IntelliJ project data.", "cleanIdea" to "removes IntelliJ project data.", "eclipse" to "generates Eclipse project data.", "cleanEclipse" to "removes Eclipse project data.", "clean" to "removes `build` folders, which store compiled classes and built archives.", "test" to "runs unit tests (if any).", "build" to "builds sources and archives of every project.", "--daemon" to "thanks to this flag, Gradle daemon will be used to run chosen tasks.", "--offline" to "when using this flag, cached dependency archives will be used.", "--continue" to "when using this flag, errors will not stop the tasks from running.", "--refresh-dependencies" to "this flag forces validation of all dependencies. Useful for snapshot versions.") .forEach { gradleTaskDescriptions[it.first] = it.second } } } fun hasPlatform(id: String): Boolean = platforms.containsKey(id) fun getGradleFile(id: String): GradleFile = gradleFiles.get(id)!! fun addGradleTaskDescription(task: String, description: String) { if (advanced.generateReadme) { gradleTaskDescriptions[task] = description } } fun generate() { addBasicFiles() template.apply(this) addExtensions() addJvmLanguagesSupport() addPlatforms() addSkinAssets() addReadmeFile() saveProperties() saveFiles() // Invoking post-generation tasks: postGenerationTasks.forEach { it(this) } } private fun addBasicFiles() { // Adding global assets folder: files.add(SourceDirectory(Assets.ID, "")) // Adding .gitignore: files.add(CopiedFile(path = ".gitignore", original = path("generator", "gitignore"))) } private fun addJvmLanguagesSupport() { Java().initiate(this) // Java is supported by default. languages.getSelectedLanguages().forEach { it.initiate(this) properties[it.id + "Version"] = languages.getVersion(it.id) } languages.appendSelectedLanguagesVersions(this) } private fun addExtensions() { extensions.getSelectedOfficialExtensions().forEach { it.initiate(this) } extensions.getSelectedThirdPartyExtensions().forEach { it.initiate(this) } } private fun addPlatforms() { platforms.values.forEach { it.initiate(this) } SettingsFile(platforms.values).save(basic.destination) } private fun saveFiles() { rootGradle.save(basic.destination) gradleFiles.values.forEach { it.save(basic.destination) } files.forEach { it.save(basic.destination) } } private fun saveProperties() { // Adding LibGDX version property: properties["gdxVersion"] = advanced.gdxVersion PropertiesFile(properties).save(basic.destination) } private fun addSkinAssets() { if (advanced.generateSkin || advanced.generateUsl) { // Adding raw assets directory: files.add(SourceDirectory("raw", "ui")) // Adding GUI assets directory: files.add(SourceDirectory(Assets.ID, "ui")) } if (advanced.generateSkin) { // Adding JSON only if USL is not checked if (!advanced.generateUsl) { files.add(CopiedFile(projectName = Assets.ID, path = path("ui", "skin.json"), original = path("generator", "assets", "ui", "skin.json"))) } // Android does not support classpath fonts loading through skins. // Explicitly copying Arial font if Android platform is included: if (hasPlatform(Android.ID)) { arrayOf("png", "fnt").forEach { val path = path("com", "badlogic", "gdx", "utils", "arial-15.$it") files.add(CopiedFile(projectName = Assets.ID, path = path, original = path, fileType = Files.FileType.Classpath)) } } // README task description: gradleTaskDescriptions["pack"] = "packs GUI assets from `raw/ui`. Saves the atlas file at `assets/ui`." // Copying raw assets - internal files listing doesn't work, so we're hard-coding raw/ui content: arrayOf("check.png", "check-on.png", "dot.png", "knob-h.png", "knob-v.png", "line-h.png", "line-v.png", "pack.json", "rect.png", "select.9.png", "square.png", "tree-minus.png", "tree-plus.png", "window-border.9.png", "window-resize.9.png").forEach { files.add(CopiedFile(projectName = "raw", path = "ui${File.separator}$it", original = path("generator", "raw", "ui", it))) } // Appending "pack" task to root Gradle: postGenerationTasks.add({ basic.destination.child(rootGradle.path).writeString(""" // Run `gradle pack` task to generate skin.atlas file at assets/ui. import com.badlogic.gdx.tools.texturepacker.TexturePacker task pack << { // Note that if you need multiple atlases, you can duplicate the // TexturePacker.process invocation and change paths to generate // additional atlases with this task. TexturePacker.process( 'raw/ui', // Raw assets path. 'assets/ui', // Output directory. 'skin' // Name of the generated atlas (without extension). ) }""", true, "UTF-8"); }) } if (advanced.generateUsl) { // Make sure USL extension is added USL().initiate(this) // Copy USL file: files.add(CopiedFile(projectName = "raw", path = path("ui", "skin.usl"), original = path("generator", "raw", "ui", "skin.usl"))) gradleTaskDescriptions["compileSkin"] = "compiles USL skin from `raw/ui`. Saves the result json file at `assets/ui`." // Add "compileSkin" task to root Gradle file: postGenerationTasks.add({ basic.destination.child(rootGradle.path).writeString(""" // Run `gradle compileSkin` task to generate skin.json at assets/ui. task compileSkin << { // Convert USL skin file into JSON String[] uslArgs = [ projectDir.path + '/raw/ui/skin.usl', // Input USL file projectDir.path + '/assets/ui/skin.json' // Output JSON file ] com.kotcrab.vis.usl.Main.main(uslArgs) }""", true, "UTF-8"); }) } if (advanced.generateSkin && advanced.generateUsl) { gradleTaskDescriptions["packAndCompileSkin"] = "pack GUI assets and compiles USL skin from `raw/ui`. Saves the result files at `assets/ui`." // Add "packAndCompileSkin" task to root Gradle file: postGenerationTasks.add({ basic.destination.child(rootGradle.path).writeString(""" // Run `gradle packAndCompileSkin` to generate skin atlas and compile USL into JSON task packAndCompileSkin(dependsOn: [pack, compileSkin])""", true, "UTF-8"); }) } } private fun addReadmeFile() { if (advanced.generateReadme) { files.add(SourceFile(projectName = "", fileName = "README.md", content = """# ${basic.name} A [LibGDX](http://libgdx.badlogicgames.com/) project generated with [gdx-setup](https://github.com/czyzby/gdx-setup). ${readmeDescription} ## Gradle This project uses [Gradle](http://gradle.org/) to manage dependencies. ${if (advanced.addGradleWrapper) "Gradle wrapper was included, so you can run Gradle tasks using `gradlew.bat` or `./gradlew` commands." else "Gradle wrapper was not included by default, so you have to install Gradle locally."} Useful Gradle tasks and flags: ${gradleTaskDescriptions.map { "- `${it.key}`: ${it.value}" }.sorted().joinToString(separator = "\n")} Note that most tasks that are not specific to a single project can be run with `name:` prefix, where the `name` should be replaced with the ID of a specific project. For example, `core:clean` removes `build` folder only from the `core` project.""")) } } fun includeGradleWrapper(logger: ProjectLogger) { if (advanced.addGradleWrapper) { arrayOf("gradlew", "gradlew.bat", path("gradle", "wrapper", "gradle-wrapper.jar"), path("gradle", "wrapper", "gradle-wrapper.properties")).forEach { CopiedFile(path = it, original = path("generator", it)).save(basic.destination) } basic.destination.child("gradlew").file().setExecutable(true) basic.destination.child("gradlew.bat").file().setExecutable(true) logger.logNls("copyGradle") } val gradleTasks = advanced.gradleTasks if (gradleTasks.isNotEmpty()) { logger.logNls("runningGradleTasks") val commands = determineGradleCommand() + advanced.gradleTasks logger.log(commands.joinToString(separator = " ")) val process = ProcessBuilder(*commands).directory(basic.destination.file()) .redirectErrorStream(true).start() val stream = BufferedReader(InputStreamReader(process.inputStream)) var line = stream.readLine(); while (line != null) { logger.log(line) line = stream.readLine(); } process.waitFor() if (process.exitValue() != 0) { throw GdxRuntimeException("Gradle process ended with non-zero value.") } } } private fun determineGradleCommand(): Array<String> { return if (OsUtils.isWindows()) { arrayOf("cmd", "/c", if (advanced.addGradleWrapper) "gradlew" else "gradle") } else { arrayOf(if (advanced.addGradleWrapper) "./gradlew" else "gradle") } } } interface ProjectLogger { fun log(message: String) fun logNls(bundleLine: String) }
unlicense
facebookincubator/ktfmt
core/src/main/java/com/facebook/ktfmt/kdoc/KDocWriter.kt
1
8461
/* * Copyright 2016 Google 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. */ /* * This was copied from https://github.com/google/google-java-format and modified extensively to * work for Kotlin formatting */ package com.facebook.ktfmt.kdoc import com.facebook.ktfmt.kdoc.KDocToken.Type.CODE_BLOCK_MARKER import com.facebook.ktfmt.kdoc.KDocToken.Type.HEADER_OPEN_TAG import com.facebook.ktfmt.kdoc.KDocToken.Type.LIST_ITEM_OPEN_TAG import com.facebook.ktfmt.kdoc.KDocToken.Type.PARAGRAPH_OPEN_TAG import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.BLANK_LINE import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.CONDITIONAL_WHITESPACE import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.NEWLINE import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.NONE import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.WHITESPACE import com.google.common.base.Strings import com.google.common.collect.Ordering import com.google.common.collect.Sets.immutableEnumSet /** * Stateful object that accepts "requests" and "writes," producing formatted Javadoc. * * Our Javadoc formatter doesn't ever generate a parse tree, only a stream of tokens, so the writer * must compute and store the answer to questions like "How many levels of nested HTML list are we * inside?" */ internal class KDocWriter(blockIndentCount: Int, private val maxLineLength: Int) { /** * Tokens that are always pinned to the following token. For example, `<p>` in `<p>Foo bar` (never * `<p> Foo bar` or `<p>\nFoo bar`). * * This is not the only kind of "pinning" that we do: See also the joining of LITERAL tokens done * by the lexer. The special pinning here is necessary because these tokens are not of type * LITERAL (because they require other special handling). */ private val START_OF_LINE_TOKENS = immutableEnumSet(LIST_ITEM_OPEN_TAG, PARAGRAPH_OPEN_TAG, HEADER_OPEN_TAG) private val output = StringBuilder() private val blockIndent = Strings.repeat(" ", blockIndentCount + 1) private var remainingOnLine: Int = 0 private var atStartOfLine: Boolean = false private var inCodeBlock: Boolean = false private var requestedWhitespace = NONE /** * Requests whitespace between the previously written token and the next written token. The * request may be honored, or it may be overridden by a request for "more significant" whitespace, * like a newline. */ fun requestWhitespace() { requestWhitespace(WHITESPACE) } fun writeBeginJavadoc() { /* * JavaCommentsHelper will make sure this is indented right. But it seems sensible enough that, * if our input starts with ∕✱✱, so too does our output. */ appendTrackingLength("/**") } fun writeEndJavadoc() { requestCloseCodeBlockMarker() output.append("\n") appendTrackingLength(blockIndent) appendTrackingLength("*/") } fun writeListItemOpen(token: KDocToken) { requestCloseCodeBlockMarker() requestNewline() writeToken(token) } fun writePreOpen(token: KDocToken) { requestBlankLine() writeToken(token) } fun writePreClose(token: KDocToken) { writeToken(token) requestBlankLine() } fun writeCodeOpen(token: KDocToken) { writeToken(token) } fun writeCodeClose(token: KDocToken) { writeToken(token) } fun writeTableOpen(token: KDocToken) { requestBlankLine() writeToken(token) } fun writeTableClose(token: KDocToken) { writeToken(token) requestBlankLine() } fun writeTag(token: KDocToken) { requestNewline() writeToken(token) } fun writeCodeLine(token: KDocToken) { requestOpenCodeBlockMarker() requestNewline() if (token.value.isNotEmpty()) { writeToken(token) } } /** Adds a code block marker if we are not in a code block currently */ private fun requestCloseCodeBlockMarker() { if (inCodeBlock) { this.requestedWhitespace = NEWLINE writeExplicitCodeBlockMarker(KDocToken(CODE_BLOCK_MARKER, "```")) } } /** Adds a code block marker if we are in a code block currently */ private fun requestOpenCodeBlockMarker() { if (!inCodeBlock) { this.requestedWhitespace = NEWLINE writeExplicitCodeBlockMarker(KDocToken(CODE_BLOCK_MARKER, "```")) } } fun writeExplicitCodeBlockMarker(token: KDocToken) { requestNewline() writeToken(token) requestNewline() inCodeBlock = !inCodeBlock } fun writeLiteral(token: KDocToken) { requestCloseCodeBlockMarker() writeToken(token) } fun writeMarkdownLink(token: KDocToken) { writeToken(token) } override fun toString(): String { return output.toString() } fun requestBlankLine() { requestWhitespace(BLANK_LINE) } fun requestNewline() { requestWhitespace(NEWLINE) } private fun requestWhitespace(requestedWhitespace: RequestedWhitespace) { this.requestedWhitespace = Ordering.natural<Comparable<*>>().max(requestedWhitespace, this.requestedWhitespace) } /** * The kind of whitespace that has been requested between the previous and next tokens. The order * of the values is significant: It goes from lowest priority to highest. For example, if the * previous token requests [.BLANK_LINE] after it but the next token requests only [ ][.NEWLINE] * before it, we insert [.BLANK_LINE]. */ internal enum class RequestedWhitespace { NONE, /** * Add one space, only if the next token seems like a word In contrast, punctuation like a dot * does need a space before it. */ CONDITIONAL_WHITESPACE, /** Add one space, e.g. " " */ WHITESPACE, /** Break to the next line */ NEWLINE, /** Add a whole blank line between the two lines of content */ BLANK_LINE, } private fun writeToken(token: KDocToken) { if (requestedWhitespace == BLANK_LINE) { writeBlankLine() requestedWhitespace = NONE } else if (requestedWhitespace == NEWLINE) { writeNewline() requestedWhitespace = NONE } val needWhitespace = when (requestedWhitespace) { WHITESPACE -> true CONDITIONAL_WHITESPACE -> token.value.first().isLetterOrDigit() else -> false } /* * Write a newline if necessary to respect the line limit. (But if we're at the beginning of the * line, a newline won't help. Or it might help but only by separating "<p>veryverylongword," * which goes against our style.) */ if (!atStartOfLine && token.length() + (if (needWhitespace) 1 else 0) > remainingOnLine) { writeNewline() } if (!atStartOfLine && needWhitespace) { appendTrackingLength(" ") } appendTrackingLength(token.value) requestedWhitespace = NONE if (!START_OF_LINE_TOKENS.contains(token.type)) { atStartOfLine = false } } private fun writeBlankLine() { output.append("\n") appendTrackingLength(blockIndent) appendTrackingLength("*") writeNewline() } private fun writeNewline() { output.append("\n") remainingOnLine = maxLineLength appendTrackingLength(blockIndent) appendTrackingLength("* ") atStartOfLine = true } /* * TODO(cpovirk): We really want the number of "characters," not chars. Figure out what the * right way of measuring that is (grapheme count (with BreakIterator?)? sum of widths of all * graphemes? I don't think that our style guide is specific about this.). Moreover, I am * probably brushing other problems with surrogates, etc. under the table. Hopefully I mostly * get away with it by joining all non-space, non-tab characters together. * * Possibly the "width" question has no right answer: * http://denisbider.blogspot.com/2015/09/when-monospace-fonts-arent-unicode.html */ private fun appendTrackingLength(str: String) { output.append(str) remainingOnLine -= str.length } }
apache-2.0
mehulsbhatt/emv-bertlv
src/test/java/io/github/binaryfoo/decoders/ICCPublicKeyDecoderTest.kt
1
1284
package io.github.binaryfoo.decoders import io.github.binaryfoo.tlv.ISOUtil import org.junit.Test import org.hamcrest.core.Is.`is` import org.junit.Assert.assertThat public class ICCPublicKeyDecoderTest { Test public fun certificateWithRemainder() { val recovered = ISOUtil.hex2byte("6A045413330089600044FFFF121400000101019003A028E99BECB507C507243C2E8DF4FE56A0297CD0AE72E2CFA992A98C80788422DBE00A1395B1545B09D66CFAB9ECEAF413E3DFF8227BC80BF6DA7F142B32673C527BB79129B5965C0F5DC4C3732BE6FA284F2469CDC545CD8AF915D2DD4AF2E171F5D36D502C42D0D7519B1CA8D3C689B65CC775687F051B2849BC") val byteLengthOfIssuerModulus = 144 assertThat(decodeICCPublicKeyCertificate(recovered, byteLengthOfIssuerModulus, 0).detail, io.github.binaryfoo.DecodedAsStringMatcher.decodedAsString("""Header: 6A Format: 04 PAN: 5413330089600044FFFF Expiry Date (MMYY): 1214 Serial number: 000001 Hash algorithm: 01 Public key algorithm: 01 Public key length: 144 Public key exponent length: 03 Public key: A028E99BECB507C507243C2E8DF4FE56A0297CD0AE72E2CFA992A98C80788422DBE00A1395B1545B09D66CFAB9ECEAF413E3DFF8227BC80BF6DA7F142B32673C527BB79129B5965C0F5DC4C3732BE6FA284F2469CDC545CD8AF915D2DD4AF2E171F5D36D502C Hash: 42D0D7519B1CA8D3C689B65CC775687F051B2849 Trailer: BC """)) } }
mit
gmillz/SlimFileManager
manager/src/main/java/com/slim/slimfilemanager/utils/FileUtil.kt
1
9351
package com.slim.slimfilemanager.utils import android.content.Context import android.os.Build import android.support.v4.provider.DocumentFile import android.text.TextUtils import android.util.Log import com.slim.slimfilemanager.settings.SettingsProvider import org.apache.commons.io.FileUtils import org.apache.commons.io.FilenameUtils import org.apache.commons.io.IOUtils import java.io.DataOutputStream import java.io.File import java.io.FileInputStream import java.io.IOException import java.io.OutputStream object FileUtil { fun copyFile(context: Context, f: String, fol: String): Boolean { val file = File(f) val folder = File(fol) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { var fis: FileInputStream? = null var os: OutputStream? = null try { fis = FileInputStream(file) val target = DocumentFile.fromFile(folder) os = context.contentResolver.openOutputStream(target.uri) IOUtils.copy(fis, os) return true } catch (e: Exception) { e.printStackTrace() } finally { try { fis?.close() if (os != null) { os.flush() os.close() } } catch (e: IOException) { e.printStackTrace() } } } if (file.exists()) { if (!folder.exists()) { if (!mkdir(context, folder)) return false } try { if (file.isDirectory) { FileUtils.copyDirectoryToDirectory(file, folder) } else if (file.isFile) { FileUtils.copyFileToDirectory(file, folder) } return true } catch (e: IOException) { return (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false) && RootUtils.isRootAvailable && RootUtils.copyFile(f, fol)) } } else { return false } } fun moveFile(context: Context, source: String, destination: String): Boolean { if (TextUtils.isEmpty(source) || TextUtils.isEmpty(destination)) { return false } val file = File(source) val folder = File(destination) try { FileUtils.moveFileToDirectory(file, folder, true) return true } catch (e: IOException) { return (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false) && RootUtils.isRootAvailable && RootUtils.moveFile(source, destination)) } } fun deleteFile(context: Context, path: String): Boolean { try { FileUtils.forceDelete(File(path)) return true } catch (e: IOException) { return (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false) && RootUtils.isRootAvailable && RootUtils.deleteFile(path)) } } fun getFileProperties(context: Context, file: File): Array<String>? { var info: Array<String>? = null val out: RootUtils.CommandOutput? if (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false) && RootUtils.isRootAvailable) { out = RootUtils.runCommand("ls -l " + file.absolutePath) } else { out = runCommand("ls -l " + file.absolutePath) } if (out == null) return null if (TextUtils.isEmpty(out.error) && out.exitCode == 0) { info = getAttrs(out.output!!) } return info } private fun getAttrs(string: String): Array<String> { if (string.length < 44) { throw IllegalArgumentException("Bad ls -l output: $string") } val chars = string.toCharArray() val results = emptyArray<String>() var ind = 0 val current = StringBuilder() Loop@ for (i in chars.indices) { when (chars[i]) { ' ', '\t' -> if (current.length != 0) { results[ind] = current.toString() ind++ current.setLength(0) if (ind == 10) { results[ind] = string.substring(i).trim({ it <= ' ' }) break@Loop } } else -> current.append(chars[i]) } } return results } fun runCommand(cmd: String): RootUtils.CommandOutput { val output = RootUtils.CommandOutput() try { val process = Runtime.getRuntime().exec("sh") val os = DataOutputStream( process.outputStream) os.writeBytes(cmd + "\n") os.writeBytes("exit\n") os.flush() output.exitCode = process.waitFor() output.output = IOUtils.toString(process.inputStream) output.error = IOUtils.toString(process.errorStream) if (output.exitCode != 0 || !TextUtils.isEmpty(output.error)) { Log.e("Shell Error, cmd: $cmd", "error: " + output.error!!) } } catch (e: IOException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } return output } fun changeGroupOwner(context: Context, file: File, owner: String, group: String): Boolean { try { var useRoot = false if (!file.canWrite() && SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false) && RootUtils.isRootAvailable) { useRoot = true RootUtils.remountSystem("rw") } if (useRoot) { RootUtils.runCommand("chown " + owner + "." + group + " " + file.absolutePath) } else { runCommand("chown " + owner + "." + group + " " + file.absolutePath) } return true } catch (e: Exception) { e.printStackTrace() } return false } fun applyPermissions(context: Context, file: File, permissions: Permissions): Boolean { try { var useSu = false if (!file.canWrite() && SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false) && RootUtils.isRootAvailable) { useSu = true RootUtils.remountSystem("rw") } if (useSu) { RootUtils.runCommand("chmod " + permissions.octalPermissions + " " + file.absolutePath) } else { runCommand("chmod " + permissions.octalPermissions + " " + file.absolutePath) } return true } catch (e: Exception) { e.printStackTrace() } return false } fun mkdir(context: Context, dir: File): Boolean { if (dir.exists()) { return false } if (dir.mkdirs()) { return true } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val document = DocumentFile.fromFile(dir.parentFile) if (document.exists()) { if (document.createDirectory(dir.absolutePath)!!.exists()) { return true } } } } return (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false) && RootUtils.isRootAvailable && RootUtils.createFolder(dir)) } fun getExtension(fileName: String): String { return FilenameUtils.getExtension(fileName) } fun removeExtension(s: String): String { return FilenameUtils.removeExtension(File(s).name) } fun writeFile(context: Context, content: String, file: File, encoding: String) { if (file.canWrite()) { try { FileUtils.write(file, content, encoding) } catch (e: IOException) { // ignore } } else if (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false)) { RootUtils.writeFile(file, content) } } fun renameFile(context: Context, oldFile: File, newFile: File) { if (oldFile.renameTo(newFile)) { return } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val document = DocumentFile.fromFile(oldFile) if (document.renameTo(newFile.absolutePath)) { return } } } if (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false)) { RootUtils.renameFile(oldFile, newFile) } } fun getFileSize(file: File): Long { return file.length() } }
gpl-3.0
Aidanvii7/Toolbox
databinding/src/test/java/com/aidanvii/toolbox/databinding/ObservableViewModelTest.kt
1
572
package com.aidanvii.toolbox.databinding import com.aidanvii.toolbox.spied import com.nhaarman.mockito_kotlin.verify import org.junit.Test class ObservableViewModelTest { val spiedTested = TestObservableViewModel().spied() @Test fun `dispose calls onCleared`() { spiedTested.dispose() verify(spiedTested).onDisposed() } @Test fun `dispose is idempotent`() { spiedTested.dispose() spiedTested.dispose() verify(spiedTested).onDisposed() } class TestObservableViewModel : ObservableViewModel() }
apache-2.0
tokenbrowser/token-android-client
app/src/main/java/com/toshi/manager/chat/tasks/NewGroupAvatarTask.kt
1
1451
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.manager.chat.tasks import com.toshi.manager.store.ConversationStore import com.toshi.model.local.Avatar import org.whispersystems.signalservice.api.SignalServiceMessageReceiver import org.whispersystems.signalservice.api.messages.SignalServiceGroup import rx.Completable class NewGroupAvatarTask( private val conversationStore: ConversationStore, private val messageReceiver: SignalServiceMessageReceiver ) { fun run(groupId: String, signalGroup: SignalServiceGroup): Completable { return Avatar .processFromSignalGroup(signalGroup, messageReceiver) .flatMapCompletable { avatar -> conversationStore.saveGroupAvatar(groupId, avatar) } } }
gpl-3.0
strykeforce/thirdcoast
src/main/kotlin/org/strykeforce/healthcheck/tests/TalonPosition.kt
1
1776
package org.strykeforce.healthcheck.tests import com.ctre.phoenix.motorcontrol.ControlMode import com.ctre.phoenix.motorcontrol.can.BaseTalon import kotlinx.html.TagConsumer import mu.KotlinLogging import org.strykeforce.healthcheck.TalonGroup import org.strykeforce.healthcheck.Test import kotlin.math.absoluteValue private val logger = KotlinLogging.logger {} class TalonPosition(private val group: TalonGroup) : Test { override var name = "position talon" var controlMode = ControlMode.MotionMagic var encoderTarget = 0 var encoderGoodEnough = 10 private var state = State.STARTING private lateinit var talon: BaseTalon override fun execute() { when (state) { State.STARTING -> { if (group.talons.size != 1) { logger.error { "position test valid for one talon, has ${group.talons.size}, skipping" } state = State.STOPPED return } logger.info { "$name starting" } talon = group.talons.first() talon.set(controlMode, encoderTarget.toDouble()) state = State.RUNNING } State.RUNNING -> { if ((encoderTarget - talon.selectedSensorPosition).absoluteValue < encoderGoodEnough) { logger.info { "repositioned to $encoderTarget, finishing" } state = State.STOPPED } } State.STOPPED -> logger.info { "position talon stopped" } } } override fun isFinished() = state == State.STOPPED override fun report(tagConsumer: TagConsumer<Appendable>) {} private enum class State { STARTING, RUNNING, STOPPED } }
mit
thiago-soliveira/android-kotlin-dagger-poc
DaggerPoc/app/src/main/java/dagger/poc/android/domain/SomeUseCase.kt
1
716
package dagger.poc.android.domain import android.util.Log import dagger.poc.android.data.SomeRepository import dagger.poc.android.data.model.Answer import dagger.poc.android.data.model.User import dagger.poc.android.injection.ActivityScope import io.reactivex.Flowable import io.reactivex.android.schedulers.AndroidSchedulers import javax.inject.Inject /** * Created by Thiago on 6/14/2017. */ @ActivityScope class SomeUseCase @Inject constructor(val someRepository: SomeRepository) { fun execute(user: User): Flowable<List<Answer>> { Log.d("DaggerPOC", "SomeUseCase called - instance: " + hashCode()) return someRepository.getAllAnswers().observeOn(AndroidSchedulers.mainThread()) } }
mit
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osm/edits/ElementEditsTable.kt
1
1501
package de.westnordost.streetcomplete.data.osm.edits object ElementEditsTable { const val NAME = "osm_element_edits" object Columns { const val ID = "id" const val QUEST_TYPE = "quest_type" const val ELEMENT_ID = "element_id" const val ELEMENT_TYPE = "element_type" const val ELEMENT = "element" const val GEOMETRY = "geometry" const val SOURCE = "source" const val LATITUDE = "latitude" const val LONGITUDE = "longitude" const val CREATED_TIMESTAMP = "created" const val IS_SYNCED = "synced" const val ACTION = "action" } const val CREATE = """ CREATE TABLE $NAME ( ${Columns.ID} INTEGER PRIMARY KEY AUTOINCREMENT, ${Columns.QUEST_TYPE} varchar(255) NOT NULL, ${Columns.ELEMENT_ID} int NOT NULL, ${Columns.ELEMENT_TYPE} varchar(255) NOT NULL, ${Columns.ELEMENT} text NOT NULL, ${Columns.GEOMETRY} text NOT NULL, ${Columns.SOURCE} varchar(255) NOT NULL, ${Columns.LATITUDE} double NOT NULL, ${Columns.LONGITUDE} double NOT NULL, ${Columns.CREATED_TIMESTAMP} int NOT NULL, ${Columns.IS_SYNCED} int NOT NULL, ${Columns.ACTION} text );""" const val ELEMENT_INDEX_CREATE = """ CREATE INDEX osm_element_edits_index ON $NAME ( ${Columns.ELEMENT_TYPE}, ${Columns.ELEMENT_ID} ); """ }
gpl-3.0
pdvrieze/ProcessManager
PE-common/src/jvmMain/kotlin/nl/adaptivity/util/HttpMessage.kt
1
18753
/* * Copyright (c) 2018. * * 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 import net.devrieze.util.Iterators import net.devrieze.util.security.SimplePrincipal import net.devrieze.util.toString import net.devrieze.util.webServer.HttpRequest import net.devrieze.util.webServer.parseMultipartFormDataTo import nl.adaptivity.xmlutil.util.CompactFragment import nl.adaptivity.xmlutil.util.ICompactFragment import nl.adaptivity.xmlutil.* import org.w3c.dom.Document import java.io.* import java.io.IOException import java.net.URLDecoder import java.nio.ByteBuffer import java.nio.charset.Charset import java.security.Principal import java.util.* import javax.activation.DataHandler import javax.activation.DataSource import javax.servlet.http.HttpServletRequest import javax.xml.bind.annotation.XmlAttribute import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.Map.Entry import nl.adaptivity.xmlutil.serialization.XmlSerialName import nl.adaptivity.xmlutil.xmlserializable.writeChildren // TODO change this to handle regular request bodies. /* @Element(name = HttpMessage.ELEMENTLOCALNAME, nsUri = HttpMessage.NAMESPACE, attributes = arrayOf( Attribute("user")), children = arrayOf( Child(property = "queries", type = Query::class), Child(property = "posts", type = Post::class), Child( name = HttpMessage.BODYELEMENTLOCALNAME, property = "body", type = AnyType::class))) @XmlDeserializer(HttpMessage.Factory::class) */ class HttpMessage { private val _queries: MutableMap<String, String>// by lazy { HashMap<String, String>() } @XmlSerialName("query", HttpMessage.NAMESPACE, "http") val queries: Collection<Query> get() = QueryCollection(_queries) private val _post: MutableMap<String, String>// by lazy { HashMap<String, String>() } @XmlSerialName("post", HttpMessage.NAMESPACE, "http") val posts: Collection<Post> get() = PostCollection(_post) @XmlSerialName("body", HttpMessage.NAMESPACE, "http") var body: ICompactFragment? = null private val _byteContent: MutableList<ByteContentDataSource> by lazy { ArrayList<ByteContentDataSource>() } val byteContent: List<ByteContentDataSource> get() = _byteContent @get:XmlAttribute var requestPath: String? = null var contextPath: String? = null var method: String? = null var contentType: String? = null private set var characterEncoding: Charset? = null private set private val _headers: Map<String, List<String>> val headers: Map<String, List<String>> get() = Collections.unmodifiableMap(_headers) private val _attachments: MutableMap<String, DataSource> val attachments: Map<String, DataSource> get() = Collections.unmodifiableMap(_attachments) var userPrincipal: Principal? = null internal set val content: XmlReader? @Throws(XmlException::class) get() = body?.getXmlReader() @XmlSerialName("user", HttpMessage.NAMESPACE, "http") internal var user: String? get() = userPrincipal?.name set(name) { userPrincipal = name?.let { SimplePrincipal(it) } } class ByteContentDataSource( private var name: String?, private var contentType: String?, var byteContent: ByteArray? ) : DataSource { val dataHandler: DataHandler get() = DataHandler(this) fun setContentType(contentType: String) { this.contentType = contentType } override fun getContentType(): String? { return contentType } fun setName(name: String) { this.name = name } override fun getName(): String? { return name } @Throws(IOException::class) override fun getInputStream(): InputStream { return ByteArrayInputStream(byteContent!!) } @Throws(IOException::class) override fun getOutputStream(): OutputStream { throw UnsupportedOperationException("Byte content is not writable") } override fun toString(): String { return "ByteContentDataSource [name=" + name + ", contentType=" + contentType + ", byteContent=\"" + String( byteContent!! ) + "\"]" } } private class QueryIterator(iterator: MutableIterator<Entry<String, String>>) : PairBaseIterator<Query>(iterator) { override fun newItem(): Query { return Query(mIterator!!.next()) } } private class PostIterator(iterator: MutableIterator<Entry<String, String>>) : PairBaseIterator<Post>(iterator) { override fun newItem(): Post { return Post(mIterator!!.next()) } } abstract class PairBaseIterator<T : PairBase>(protected val mIterator: MutableIterator<Entry<String, String>>?) : MutableIterator<T> { override fun hasNext(): Boolean { return mIterator != null && mIterator.hasNext() } override fun next(): T { if (mIterator == null) { throw NoSuchElementException() } return newItem() } protected abstract fun newItem(): T override fun remove() { if (mIterator == null) { throw IllegalStateException("Removing elements from empty collection") } mIterator.remove() } } class Query : PairBase { protected constructor() {} constructor(entry: Entry<String, String>) : super(entry) {} companion object { private val ELEMENTNAME = QName(NAMESPACE, "query", "http") } } class Post : PairBase { protected constructor() constructor(entry: Entry<String, String>) : super(entry) {} companion object { private val ELEMENTNAME = QName(NAMESPACE, "post", "http") } } abstract class PairBase { @XmlSerialName("name", HttpMessage.NAMESPACE, "http") lateinit var key: String lateinit var value: String protected constructor() {} protected constructor(entry: Entry<String, String>) { key = entry.key value = entry.value } override fun hashCode(): Int { val prime = 31 var result = 1 result = prime * result + key.hashCode() result = prime * result + value.hashCode() return result } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other == null) { return false } if (javaClass != other.javaClass) { return false } other as PairBase? if (key != other.key) { return false } if (value != other.value) { return false } return true } } class QueryCollection(map: MutableMap<String, String>) : PairBaseCollection<Query>(map) { override fun iterator(): MutableIterator<Query> { return QueryIterator(map.entries.iterator()) } } class PostCollection(map: MutableMap<String, String>) : PairBaseCollection<Post>(map) { override fun iterator(): MutableIterator<Post> { return PostIterator(map.entries.iterator()) } } abstract class PairBaseCollection<T : PairBase>(map: MutableMap<String, String>?) : AbstractCollection<T>() { protected var map = map?.toMutableMap() ?: mutableMapOf() override fun add(element: T): Boolean { return map.put(element.key, element.value) != null } override fun clear() { map.clear() } override operator fun contains(element: T): Boolean { return element.value == map[element.key] } override fun isEmpty(): Boolean { return map.isEmpty() } override fun remove(element: T): Boolean { val candidate = map[element.key] if (candidate != null && candidate == element.value) { map.remove(element.key) return true } else { return false } } override val size: Int get() = map.size } private constructor() { _headers = HashMap() _post = HashMap() _queries = HashMap() _attachments = HashMap() } @Throws(IOException::class) constructor(request: HttpServletRequest) { _headers = getHeaders(request) _queries = toQueries(request.queryString) var post: MutableMap<String, String>? = null var attachments: MutableMap<String, DataSource> = HashMap() userPrincipal = request.userPrincipal method = request.method val pathInfo = request.pathInfo requestPath = if (pathInfo == null || pathInfo.length == 0) request.servletPath else pathInfo contextPath = request.contextPath if ("POST" == request.method || "PUT" == request.method) { contentType = request.contentType characterEncoding = null contentType?.let { contentType -> var i = contentType.indexOf(';') if (i >= 0) { var tail: String = contentType this.contentType = contentType.substring(0, i).trim { it <= ' ' } while (i >= 0) { tail = tail.substring(i + 1).trim { it <= ' ' } i = tail.indexOf(';') val param: String if (i > 0) { param = tail.substring(0, i).trim { it <= ' ' } } else { param = tail } val j = param.indexOf('=') if (j >= 0) { val paramName = param.substring(0, j).trim { it <= ' ' } if (paramName == "charset") { characterEncoding = Charset.forName(param.substring(j + 1).trim { it <= ' ' }) } } } } } if (characterEncoding == null) { characterEncoding = getCharacterEncoding(request) } if (characterEncoding == null) { characterEncoding = DEFAULT_CHARSSET } val isMultipart = contentType != null && contentType!!.startsWith("multipart/") if ("application/x-www-form-urlencoded" == contentType) { post = toQueries(String(getBody(request))) } else if (isMultipart) { request.inputStream.parseMultipartFormDataTo(attachments, HttpRequest.mimeType(request.contentType)) } else { val bytes = getBody(request) val xml: Document val isXml = XmlStreaming.newReader(InputStreamReader(ByteArrayInputStream(bytes), characterEncoding!!)).isXml() if (!isXml) { addByteContent(bytes, request.contentType) } else { val decoder = characterEncoding!!.newDecoder() val buffer = decoder.decode(ByteBuffer.wrap(bytes)) var chars: CharArray? = null if (buffer.hasArray()) { chars = buffer.array() if (chars!!.size > buffer.limit()) { chars = null } } if (chars == null) { chars = CharArray(buffer.limit()) buffer.get(chars) } body = CompactFragment(emptyList(), chars) } } } this._post = post ?: mutableMapOf() this._attachments = attachments ?: mutableMapOf() } protected fun getCharacterEncoding(request: HttpServletRequest): Charset { val name = request.characterEncoding ?: return DEFAULT_CHARSSET return Charset.forName(request.characterEncoding) } private fun addByteContent(byteArray: ByteArray, contentType: String) { _byteContent.add(ByteContentDataSource(null, contentType, byteArray)) } /* * Getters and setters */ fun getQuery(name: String): String? { return if (_queries == null) null else _queries!![name] } fun getPosts(name: String): String? { if (_post != null) { var result: String? = _post!![name] if (result == null && _attachments != null) { val source = _attachments!![name] if (source != null) { try { result = toString(InputStreamReader(source.inputStream, "UTF-8")) return result } catch (e: UnsupportedEncodingException) { throw RuntimeException(e) } catch (e: IOException) { throw RuntimeException(e) } } } } return if (_post == null) null else _post!![name] } fun getParam(name: String): String? { val result = getQuery(name) return result ?: getPosts(name) } fun getAttachment(name: String?): DataSource? { return _attachments[name ?: NULL_KEY] } fun getHeaders(name: String): Iterable<String> { return Collections.unmodifiableList(_headers[name]) } fun getHeader(name: String): String? { val list = _headers[name] return if (list == null || list.size < 1) { null } else list[0] } companion object { const val NULL_KEY = "KJJMBZLZKNC<MNCJHASIUJZNCZM>NSJHLCALSNDM<>BNADSBLKH" const val NAMESPACE = "http://adaptivity.nl/HttpMessage" const val ELEMENTLOCALNAME = "httpMessage" val ELEMENTNAME = QName(NAMESPACE, ELEMENTLOCALNAME, "http") internal const val BODYELEMENTLOCALNAME = "Body" internal val BODYELEMENTNAME = QName(NAMESPACE, BODYELEMENTLOCALNAME, "http") private val DEFAULT_CHARSSET = Charset.forName("UTF-8") /* * Utility methods */ private fun getHeaders(request: HttpServletRequest): Map<String, List<String>> { val result = HashMap<String, List<String>>() for (oname in Iterators.toIterable(request.headerNames)) { val name = oname as String val values = Iterators.toList(request.getHeaders(name)) result[name] = values } return result } private fun toQueries(queryString: String?): MutableMap<String, String> { val result = HashMap<String, String>() if (queryString == null) { return result } var query: String = queryString if (query.length > 0 && query[0] == '?') { /* strip questionmark */ query = query.substring(1) } var startPos = 0 var key: String? = null for (i in 0 until query.length) { if (key == null) { if ('=' == query[i]) { key = query.substring(startPos, i) startPos = i + 1 } } else { if ('&' == query[i] || ';' == query[i]) { val value: String try { value = URLDecoder.decode(query.substring(startPos, i), "UTF-8") } catch (e: UnsupportedEncodingException) { throw RuntimeException(e) } result[key] = value key = null startPos = i + 1 } } } if (key == null) { key = query.substring(startPos) if (key.length > 0) { result[key] = "" } } else { try { val value = URLDecoder.decode(query.substring(startPos), "UTF-8") result[key] = value } catch (e: UnsupportedEncodingException) { throw RuntimeException(e) } } return result } private fun getBody(request: HttpServletRequest): ByteArray { val contentLength = request.contentLength val baos: ByteArrayOutputStream = if (contentLength > 0) ByteArrayOutputStream(contentLength) else ByteArrayOutputStream() val buffer = ByteArray(0xfffff) request.inputStream.use { inStream -> var i: Int = inStream.read(buffer) while (i >= 0) { baos.write(buffer, 0, i) i = inStream.read(buffer) } } return baos.toByteArray() } } }
lgpl-3.0
akvo/akvo-flow-mobile
app/src/main/java/org/akvo/flow/presentation/form/view/groups/QuestionViewHolder.kt
1
14648
/* * Copyright (C) 2020 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Akvo Flow is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.presentation.form.view.groups import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.google.android.material.textfield.TextInputEditText import org.akvo.flow.R import org.akvo.flow.presentation.form.view.groups.entity.ViewQuestionAnswer import org.akvo.flow.util.image.GlideImageLoader import org.akvo.flow.util.image.ImageLoader sealed class QuestionViewHolder<T : ViewQuestionAnswer>(val view: View) : RecyclerView.ViewHolder(view) { abstract fun setUpView(questionAnswer: T, index: Int) private fun mandatoryText(mandatory: Boolean): String { return when { mandatory -> { "*" } else -> { "" } } } fun setUpTitle(title: String, mandatory: Boolean) { view.findViewById<TextView>(R.id.questionTitle).text = "$title${mandatoryText(mandatory)}" } fun setUpInputText(answer: String, textInputEditText: TextInputEditText) { if (answer.isEmpty()) { textInputEditText.visibility = View.GONE } else { textInputEditText.visibility = View.VISIBLE textInputEditText.setText(answer) } } class NumberQuestionViewHolder(singleView: View) : QuestionViewHolder<ViewQuestionAnswer.NumberViewQuestionAnswer>(singleView) { override fun setUpView( questionAnswer: ViewQuestionAnswer.NumberViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) setUpAnswer(questionAnswer.answer) setUpRepetition(questionAnswer.requireDoubleEntry, questionAnswer.answer) } //TODO: repeated code from number/text... refactor private fun setUpRepetition(repeated: Boolean, answer: String) { val repeatedInput = view.findViewById<TextInputEditText>( R.id.questionResponseRepeated ) val repeatTitle = view.findViewById<TextView>( R.id.repeatTitle ) if (repeated) { setUpInputText(answer, repeatedInput) if (answer.isEmpty()) { repeatTitle.visibility = View.GONE } else { repeatTitle.visibility = View.VISIBLE } } else { repeatTitle.visibility = View.GONE repeatedInput.visibility = View.GONE } } private fun setUpAnswer(answer: String) { val textInputEditText = view.findViewById<TextInputEditText>( R.id.questionResponseInput ) setUpInputText(answer, textInputEditText) } } class TextQuestionViewHolder(singleView: View) : QuestionViewHolder<ViewQuestionAnswer.FreeTextViewQuestionAnswer>(singleView) { override fun setUpView( questionAnswer: ViewQuestionAnswer.FreeTextViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) setUpAnswer(questionAnswer.answer) setUpRepetition(questionAnswer.requireDoubleEntry, questionAnswer.answer) } private fun setUpAnswer(answer: String) { val textInputEditText = view.findViewById<TextInputEditText>( R.id.questionResponseInput ) setUpInputText(answer, textInputEditText) } private fun setUpRepetition(repeatable: Boolean, answer: String) { val repeatedInput = view.findViewById<TextInputEditText>( R.id.questionResponseRepeated ) val repeatTitle = view.findViewById<TextView>( R.id.repeatTitle ) if (repeatable) { setUpInputText(answer, repeatedInput) if (answer.isEmpty()) { repeatTitle.visibility = View.GONE } else { repeatTitle.visibility = View.VISIBLE } } else { repeatTitle.visibility = View.GONE repeatedInput.visibility = View.GONE } } } class PhotoQuestionViewHolder(mediaView: View) : QuestionViewHolder<ViewQuestionAnswer.PhotoViewQuestionAnswer>(mediaView) { private val mediaLayout: MediaQuestionLayout = view.findViewById(R.id.preview_container) override fun setUpView( questionAnswer: ViewQuestionAnswer.PhotoViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) if (questionAnswer.filePath.isNotEmpty()) { mediaLayout.visibility = View.VISIBLE mediaLayout.setUpImageDisplay(index, questionAnswer.filePath) setupLocation(questionAnswer) } else { mediaLayout.visibility = View.GONE } } private fun setupLocation(questionAnswer: ViewQuestionAnswer.PhotoViewQuestionAnswer) { val locationTv = view.findViewById(R.id.location_info) as TextView val location = questionAnswer.location if (location != null) { val locationText: String = view.context .getString( R.string.image_location_coordinates, location.latitude, location.longitude ) locationTv.text = locationText locationTv.visibility = View.VISIBLE } else { locationTv.visibility = View.GONE } } } class VideoQuestionViewHolder(mediaView: View) : QuestionViewHolder<ViewQuestionAnswer.VideoViewQuestionAnswer>(mediaView) { private val mediaLayout: MediaQuestionLayout = view.findViewById(R.id.preview_container) override fun setUpView( questionAnswer: ViewQuestionAnswer.VideoViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) if (questionAnswer.filePath.isNotEmpty()) { mediaLayout.visibility = View.VISIBLE mediaLayout.setUpImageDisplay(index, questionAnswer.filePath) } else { mediaLayout.visibility = View.GONE } } } class SignatureQuestionViewHolder(signView: View) : QuestionViewHolder<ViewQuestionAnswer.SignatureViewQuestionAnswer>(signView) { private val imageIv: ImageView = view.findViewById(R.id.signatureIv) private val nameTv: TextView = view.findViewById(R.id.signatureTv) private val questionLayout: LinearLayout = view.findViewById(R.id.questionContentLayout) private var imageLoader: ImageLoader = GlideImageLoader(view.context) override fun setUpView( questionAnswer: ViewQuestionAnswer.SignatureViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) if (questionAnswer.base64ImageString.isNotEmpty() && questionAnswer.name.isNotEmpty()) { questionLayout.visibility = View.VISIBLE imageIv.visibility = View.VISIBLE imageLoader.loadFromBase64String(questionAnswer.base64ImageString, imageIv) nameTv.text = questionAnswer.name } else { questionLayout.visibility = View.GONE } } } class DateQuestionViewHolder(dateView: View) : QuestionViewHolder<ViewQuestionAnswer.DateViewQuestionAnswer>(dateView) { override fun setUpView( questionAnswer: ViewQuestionAnswer.DateViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) val textInputEditText = view.findViewById<TextInputEditText>( R.id.questionResponseInput ) setUpInputText(questionAnswer.answer, textInputEditText) } } class LocationQuestionViewHolder(locationView: View) : QuestionViewHolder<ViewQuestionAnswer.LocationViewQuestionAnswer>(locationView) { override fun setUpView( questionAnswer: ViewQuestionAnswer.LocationViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) if (questionAnswer.viewLocation != null && questionAnswer.viewLocation.isValid()) { view.findViewById<TextInputEditText>(R.id.lat_et) .setText(questionAnswer.viewLocation.latitude) view.findViewById<TextInputEditText>(R.id.lon_et) .setText(questionAnswer.viewLocation.longitude) view.findViewById<TextInputEditText>(R.id.height_et) .setText(questionAnswer.viewLocation.altitude) val accuracy = questionAnswer.viewLocation.accuracy val accuracyTv = view.findViewById<TextView>(R.id.acc_tv) if (accuracy.isNotEmpty()) { accuracyTv.text = accuracy } else { accuracyTv.setText(R.string.geo_location_accuracy_default) } } } } class ShapeQuestionViewHolder(geoshapeView: View) : QuestionViewHolder<ViewQuestionAnswer.GeoShapeViewQuestionAnswer>(geoshapeView) { private val viewShapeBt = view.findViewById<Button>(R.id.view_shape_btn) private val shapeTv = view.findViewById<TextView>(R.id.geo_shape_captured_text) override fun setUpView( questionAnswer: ViewQuestionAnswer.GeoShapeViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) if (questionAnswer.geojsonAnswer.isNotEmpty()) { viewShapeBt.visibility = View.VISIBLE shapeTv.visibility = View.VISIBLE viewShapeBt.setOnClickListener { val activityContext = view.context if (activityContext is GeoShapeListener) { activityContext.viewShape(questionAnswer.geojsonAnswer) } else { throw throw IllegalArgumentException("Activity must implement GeoShapeListener") } } } else { viewShapeBt.visibility = View.GONE shapeTv.visibility = View.GONE } } } class OptionsViewHolder(optionsView: View) : QuestionViewHolder<ViewQuestionAnswer.OptionViewQuestionAnswer>(optionsView) { override fun setUpView( questionAnswer: ViewQuestionAnswer.OptionViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) val optionsQuestionLayout = view.findViewById<OptionsQuestionLayout>(R.id.options_layout) if (questionAnswer.options.isNotEmpty()){ optionsQuestionLayout.visibility = View.VISIBLE optionsQuestionLayout.setUpViews(questionAnswer) } else { optionsQuestionLayout.visibility = View.GONE } } } class BarcodeViewHolder(barcodeView: View) : QuestionViewHolder<ViewQuestionAnswer.BarcodeViewQuestionAnswer>(barcodeView) { override fun setUpView( questionAnswer: ViewQuestionAnswer.BarcodeViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) val barcodesQuestionLayout = view.findViewById<BarcodesQuestionLayout>(R.id.barcodes_layout) if (questionAnswer.answers.isNotEmpty()) { barcodesQuestionLayout.visibility = View.VISIBLE barcodesQuestionLayout.setUpViews(questionAnswer) } else { barcodesQuestionLayout.visibility = View.GONE } } } class CascadeViewHolder(barcodeView: View) : QuestionViewHolder<ViewQuestionAnswer.CascadeViewQuestionAnswer>(barcodeView) { override fun setUpView( questionAnswer: ViewQuestionAnswer.CascadeViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) val barcodesQuestionLayout = view.findViewById<CascadeQuestionLayout>(R.id.barcodes_layout) if (questionAnswer.answers.isNotEmpty()) { barcodesQuestionLayout.visibility = View.VISIBLE barcodesQuestionLayout.setUpViews(questionAnswer) } else { barcodesQuestionLayout.visibility = View.GONE } } } class CaddisflyViewHolder(barcodeView: View) : QuestionViewHolder<ViewQuestionAnswer.CaddisflyViewQuestionAnswer>(barcodeView) { override fun setUpView( questionAnswer: ViewQuestionAnswer.CaddisflyViewQuestionAnswer, index: Int ) { setUpTitle(questionAnswer.title, questionAnswer.mandatory) val barcodesQuestionLayout = view.findViewById<CaddisflyQuestionLayout>(R.id.caddisfly_layout) if (questionAnswer.answers.isNotEmpty()) { barcodesQuestionLayout.visibility = View.VISIBLE barcodesQuestionLayout.setUpViews(questionAnswer) } else { barcodesQuestionLayout.visibility = View.GONE } } } }
gpl-3.0
perseacado/feedback-ui
feedback-ui-web/src/main/java/com/github/perseacado/feedbackui/filter/FeedbackInjectorFilter.kt
1
612
package com.github.perseacado.feedbackui.filter import org.springframework.stereotype.Component import org.springframework.web.filter.OncePerRequestFilter import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * @author Marco Eigletsberger, 24.06.16. */ @Component open class FeedbackInjectorFilter: OncePerRequestFilter() { override fun doFilterInternal(req: HttpServletRequest?, res: HttpServletResponse?, filterChain: FilterChain?) { throw UnsupportedOperationException() filterChain?.doFilter(req, res) } }
mit
Kotlin/kotlinx.serialization
core/commonMain/src/kotlinx/serialization/PolymorphicSerializer.kt
1
4268
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization import kotlinx.serialization.builtins.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* import kotlinx.serialization.internal.* import kotlinx.serialization.modules.* import kotlin.reflect.* /** * This class provides support for multiplatform polymorphic serialization for interfaces and abstract classes. * * To avoid the most common security pitfalls and reflective lookup (and potential load) of an arbitrary class, * all serializable implementations of any polymorphic type must be [registered][SerializersModuleBuilder.polymorphic] * in advance in the scope of base polymorphic type, efficiently preventing unbounded polymorphic serialization * of an arbitrary type. * * Polymorphic serialization is enabled automatically by default for interfaces and [Serializable] abstract classes. * To enable this feature explicitly on other types, use `@SerializableWith(PolymorphicSerializer::class)` * or [Polymorphic] annotation on the property. * * Usage of the polymorphic serialization can be demonstrated by the following example: * ``` * abstract class BaseRequest() * @Serializable * data class RequestA(val id: Int): BaseRequest() * @Serializable * data class RequestB(val s: String): BaseRequest() * * abstract class BaseResponse() * @Serializable * data class ResponseC(val payload: Long): BaseResponse() * @Serializable * data class ResponseD(val payload: ByteArray): BaseResponse() * * @Serializable * data class Message( * @Polymorphic val request: BaseRequest, * @Polymorphic val response: BaseResponse * ) * ``` * In this example, both request and response in `Message` are serializable with [PolymorphicSerializer]. * * `BaseRequest` and `BaseResponse` are base classes and they are captured during compile time by the plugin. * Yet [PolymorphicSerializer] for `BaseRequest` should only allow `RequestA` and `RequestB` serializers, and none of the response's serializers. * * This is achieved via special registration function in the module: * ``` * val requestAndResponseModule = SerializersModule { * polymorphic(BaseRequest::class) { * subclass(RequestA::class) * subclass(RequestB::class) * } * polymorphic(BaseResponse::class) { * subclass(ResponseC::class) * subclass(ResponseD::class) * } * } * ``` * * @see SerializersModule * @see SerializersModuleBuilder.polymorphic */ @OptIn(ExperimentalSerializationApi::class) public class PolymorphicSerializer<T : Any>(override val baseClass: KClass<T>) : AbstractPolymorphicSerializer<T>() { @PublishedApi // See comment in SealedClassSerializer internal constructor( baseClass: KClass<T>, classAnnotations: Array<Annotation> ) : this(baseClass) { _annotations = classAnnotations.asList() } private var _annotations: List<Annotation> = emptyList() public override val descriptor: SerialDescriptor by lazy(LazyThreadSafetyMode.PUBLICATION) { buildSerialDescriptor("kotlinx.serialization.Polymorphic", PolymorphicKind.OPEN) { element("type", String.serializer().descriptor) element( "value", buildSerialDescriptor("kotlinx.serialization.Polymorphic<${baseClass.simpleName}>", SerialKind.CONTEXTUAL) ) annotations = _annotations }.withContext(baseClass) } override fun toString(): String { return "kotlinx.serialization.PolymorphicSerializer(baseClass: $baseClass)" } } @InternalSerializationApi public fun <T : Any> AbstractPolymorphicSerializer<T>.findPolymorphicSerializer( decoder: CompositeDecoder, klassName: String? ): DeserializationStrategy<out T> = findPolymorphicSerializerOrNull(decoder, klassName) ?: throwSubtypeNotRegistered(klassName, baseClass) @InternalSerializationApi public fun <T : Any> AbstractPolymorphicSerializer<T>.findPolymorphicSerializer( encoder: Encoder, value: T ): SerializationStrategy<T> = findPolymorphicSerializerOrNull(encoder, value) ?: throwSubtypeNotRegistered(value::class, baseClass)
apache-2.0
android/topeka
base/src/main/java/com/google/samples/apps/topeka/model/JsonAttributes.kt
3
1114
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.topeka.model object JsonAttributes { const val ANSWER = "answer" const val END = "end" const val ID = "id" const val MAX = "max" const val MIN = "min" const val NAME = "name" const val OPTIONS = "options" const val QUESTION = "question" const val QUIZZES = "quizzes" const val START = "start" const val STEP = "step" const val THEME = "theme" const val TYPE = "type" const val SCORES = "scores" const val SOLVED = "solved" }
apache-2.0
ursjoss/scipamato
core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/paper/jasper/summary/PaperSummaryTest.kt
2
3753
package ch.difty.scipamato.core.web.paper.jasper.summary import ch.difty.scipamato.core.web.paper.jasper.CoreShortFieldConcatenator import ch.difty.scipamato.core.web.paper.jasper.CoreShortFieldWithEmptyMainFieldConcatenator import ch.difty.scipamato.core.web.paper.jasper.ExportEntityTest import ch.difty.scipamato.core.web.paper.jasper.ReportHeaderFields import nl.jqno.equalsverifier.EqualsVerifier import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test internal class PaperSummaryTest : ExportEntityTest() { private val shortFieldConcatenator: CoreShortFieldConcatenator = CoreShortFieldWithEmptyMainFieldConcatenator() private lateinit var ps: PaperSummary private var rhf = newReportHeaderFields() private fun newReportHeaderFields() = ReportHeaderFields( headerPart = HEADER_PART, brand = BRAND, populationLabel = POPULATION_LABEL, goalsLabel = GOALS_LABEL, methodsLabel = METHODS_LABEL, resultLabel = RESULT_LABEL, commentLabel = COMMENT_LABEL, ) @Test fun instantiating() { ps = PaperSummary(p, shortFieldConcatenator, rhf) assertPaperSummary() } private fun assertPaperSummary() { ps.number shouldBeEqualTo NUMBER.toString() ps.authors shouldBeEqualTo AUTHORS ps.title shouldBeEqualTo TITLE ps.location shouldBeEqualTo LOCATION ps.goals shouldBeEqualTo GOALS ps.population shouldBeEqualTo POPULATION ps.methods shouldBeEqualTo METHODS ps.result shouldBeEqualTo RESULT ps.comment shouldBeEqualTo COMMENT ps.populationLabel shouldBeEqualTo POPULATION_LABEL ps.methodsLabel shouldBeEqualTo METHODS_LABEL ps.resultLabel shouldBeEqualTo RESULT_LABEL ps.commentLabel shouldBeEqualTo COMMENT_LABEL ps.header shouldBeEqualTo "$HEADER_PART $NUMBER" ps.brand shouldBeEqualTo BRAND ps.createdBy shouldBeEqualTo CREATED_BY } @Test fun populationLabelIsBlankIfPopulationIsBlank() { p.population = "" ps = newPaperSummary() ps.population shouldBeEqualTo "" ps.populationLabel shouldBeEqualTo "" } private fun newPaperSummary(): PaperSummary = PaperSummary(p, shortFieldConcatenator, rhf) @Test fun methodsLabelIsBlankIfMethodsIsBlank() { p.methods = "" ps = newPaperSummary() ps.methods shouldBeEqualTo "" ps.methodsLabel shouldBeEqualTo "" } @Test fun resultLabelIsBlankIfResultIsBlank() { p.result = "" ps = newPaperSummary() ps.result shouldBeEqualTo "" ps.resultLabel shouldBeEqualTo "" } @Test fun commentLabelIsBlankIfCommentIsBlank() { p.comment = "" ps = newPaperSummary() ps.comment shouldBeEqualTo "" ps.commentLabel shouldBeEqualTo "" } @Test fun headerHasNoNumberIfNumberIsNull() { p.number = null ps = newPaperSummary() ps.header shouldBeEqualTo "headerPart" } @Test fun headerOnlyShowsIdIfHeaderPartIsBlank() { rhf = ReportHeaderFields( headerPart = "", brand = BRAND, populationLabel = POPULATION_LABEL, goalsLabel = GOALS_LABEL, methodsLabel = METHODS_LABEL, resultLabel = RESULT_LABEL, commentLabel = COMMENT_LABEL, ) p.number = 5L ps = newPaperSummary() ps.header shouldBeEqualTo "5" } @Test fun equalsVerify() { EqualsVerifier.simple() .forClass(PaperSummary::class.java) .withRedefinedSuperclass() .withOnlyTheseFields("number") .verify() } }
bsd-3-clause
pokk/mvp-magazine
app/src/main/kotlin/taiwan/no1/app/ui/adapter/viewholder/MovieCrewViewHolder.kt
1
2248
package taiwan.no1.app.ui.adapter.viewholder import android.support.v7.widget.CardView import android.view.View import android.widget.ImageView import android.widget.TextView import kotterknife.bindView import taiwan.no1.app.R import taiwan.no1.app.mvp.contracts.adapter.MovieCrewAdapterContract import taiwan.no1.app.mvp.models.FilmCastsModel import taiwan.no1.app.ui.adapter.CommonRecyclerAdapter import taiwan.no1.app.ui.listeners.GlideResizeTargetListener import taiwan.no1.app.utilies.ImageLoader.IImageLoader import javax.inject.Inject /** * A [BaseViewHolder] of displaying crews of the movie view of the MVP architecture's V. * * @author Jieyi * @since 1/7/17 */ class MovieCrewViewHolder(view: View) : BaseViewHolder<FilmCastsModel.CrewBean>(view), MovieCrewAdapterContract.View { @Inject lateinit var presenter: MovieCrewAdapterContract.Presenter @Inject lateinit var imageLoader: IImageLoader //region View variables val item by bindView<CardView>(R.id.item_cast) val ivCast by bindView<ImageView>(R.id.iv_cast) val tvCharacter by bindView<TextView>(R.id.tv_character) val tvName by bindView<TextView>(R.id.tv_name) //endregion //region BaseViewHolder override fun initView(model: FilmCastsModel.CrewBean, position: Int, adapter: CommonRecyclerAdapter) { super.initView(model, position, adapter) this.ivCast.viewTreeObserver.addOnGlobalLayoutListener { this.ivCast.measuredWidth.let { this.tvCharacter.width = it this.tvName.width = it } } } override fun inject() { this.component.inject(MovieCrewViewHolder@ this) } override fun initPresenter(model: FilmCastsModel.CrewBean) { this.presenter.init(MovieCrewViewHolder@ this, model) } //endregion //region ViewHolder implementations override fun showCrewProfilePhoto(uri: String) { this.imageLoader.display(uri, listener = GlideResizeTargetListener(this.ivCast, this.item)) } override fun showCrewCharacter(character: String) { this.tvCharacter.text = character } override fun showCrewName(name: String) { this.tvName.text = name } //endregion }
apache-2.0
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/util/magic/PatternMagic.kt
1
4156
package nl.hannahsten.texifyidea.util.magic import nl.hannahsten.texifyidea.inspections.latex.codestyle.LatexLineBreakInspection import java.util.regex.Pattern typealias RegexPattern = Pattern /** * @author Hannah Schellekens */ object PatternMagic { val ellipsis = Regex("""(?<!\.)(\.\.\.)(?!\.)""") /** * This is the only correct way of using en dashes. */ val correctEnDash = RegexPattern.compile("[0-9]+--[0-9]+")!! /** * Matches the prefix of a label. Amazing comment this is right? */ val labelPrefix = RegexPattern.compile(".*:")!! /** * Matches the end of a sentence. * * Includes `[^.][^.]` because of abbreviations (at least in Dutch) like `s.v.p.` */ const val sentenceEndPrefix = "[^.A-Z][^.A-Z]" val sentenceEnd = RegexPattern.compile("($sentenceEndPrefix[.?!;;] +[^%\\s])|(^\\. )")!! /** * Matches all interpunction that marks the end of a sentence. */ val sentenceSeparator = RegexPattern.compile("[.?!;;]")!! /** * Matches all sentenceSeparators at the end of a line (with or without space). */ val sentenceSeparatorAtLineEnd = RegexPattern.compile("$sentenceSeparator\\s*$")!! /** * Matches when a string ends with a non breaking space. */ val endsWithNonBreakingSpace = RegexPattern.compile("~$")!! /** * Finds all abbreviations that have at least two letters separated by comma's. * * It might be more parts, like `b.v.b.d. ` is a valid abbreviation. Likewise are `sajdflkj.asdkfj.asdf ` and * `i.e. `. Single period abbreviations are not being detected as they can easily be confused with two letter words * at the end of the sentence (also localisation...) For this there is a quickfix in [LatexLineBreakInspection]. */ val abbreviation = RegexPattern.compile("[0-9A-Za-z.]+\\.[A-Za-z](\\.[\\s~])")!! /** * Abbreviations not detected by [PatternMagic.abbreviation]. */ val unRegexableAbbreviations = listOf( "et al." ) /** [abbreviation]s that are missing a normal space (or a non-breaking space) */ val abbreviationWithoutNormalSpace = RegexPattern.compile("[0-9A-Za-z.]+\\.[A-Za-z](\\.[\\s])")!! /** * Matches all comments, starting with % and ending with a newline. */ val comments: RegexPattern = RegexPattern.compile("%(.*)\\n") /** * Matches leading and trailing whitespace on a string. */ val excessWhitespace = RegexPattern.compile("(^(\\s+).*(\\s*)\$)|(^(\\s*).*(\\s+)\$)")!! /** * Matches a non-ASCII character. */ val nonAscii = RegexPattern.compile("\\P{ASCII}")!! /** * Separator for multiple parameter values in one parameter. * * E.g. when you have \cite{citation1,citation2,citation3}, this pattern will match the separating * comma. */ val parameterSplit = RegexPattern.compile("\\s*,\\s*")!! /** * Matches the extension of a file name. */ val fileExtension = RegexPattern.compile("\\.[a-zA-Z0-9]+$")!! /** * Matches all leading whitespace. */ val leadingWhitespace = RegexPattern.compile("^\\s*")!! /** * Matches newlines. */ val newline = RegexPattern.compile("\\n")!! /** * Checks if the string is `text`, two newlines, `text`. */ val containsMultipleNewlines = RegexPattern.compile("[^\\n]*\\n\\n+[^\\n]*")!! /** * Matches HTML tags of the form `<tag>`, `<tag/>` and `</tag>`. */ val htmlTag = RegexPattern.compile("""<.*?/?>""")!! /** * Matches a LaTeX command that is the start of an \if-\fi structure. */ val ifCommand = RegexPattern.compile("\\\\if[a-zA-Z@]*")!! /** * Matches the begin and end commands of the cases and split environments. */ val casesOrSplitCommands = Regex( "((?=\\\\begin\\{cases})|(?<=\\\\begin\\{cases}))" + "|((?=\\\\end\\{cases})|(?<=\\\\end\\{cases}))" + "|((?=\\\\begin\\{split})|(?<=\\\\begin\\{split}))" + "|((?=\\\\end\\{split})|(?<=\\\\end\\{split}))" ) }
mit
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/utils/codecs/CompressableStringEncoder.kt
1
1474
/* * 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.utils.codecs import debop4k.core.compress.Compressor import debop4k.core.compress.SNAPPY /** * 바이트 배열을 압축하고, 문자열로 인코딩 / 문자열을 디코딩하고 압축해제를 수행합니다. * @author [email protected] */ open class CompressableStringEncoder @JvmOverloads constructor(encoder: StringEncoder, val compressor: Compressor = SNAPPY) : StringEncoderDecorator(encoder) { /** * 바이트 배열을 압축 한 후, 인코딩하여 문자열로 만든다. */ override fun encode(bytes: ByteArray?): String { return super.encode(compressor.compress(bytes)) } /** * 문자열을 디코딩한 후, 압축을 풉니다. */ override fun decode(str: String?): ByteArray { return compressor.decompress(super.decode(str)) } }
apache-2.0
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/index/LatexIncludesIndex.kt
1
647
package nl.hannahsten.texifyidea.index import com.intellij.psi.stubs.StringStubIndexExtension import nl.hannahsten.texifyidea.LatexParserDefinition import nl.hannahsten.texifyidea.psi.LatexCommands /** * Index all commands that include other files, see [nl.hannahsten.texifyidea.util.getIncludeCommands]. * @author Hannah Schellekens */ class LatexIncludesIndex : StringStubIndexExtension<LatexCommands>() { companion object : IndexCommandsUtilBase(IndexKeys.INCLUDES_KEY) @Suppress("RedundantCompanionReference") override fun getKey() = Companion.key() override fun getVersion() = LatexParserDefinition.FILE.stubVersion }
mit
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/views/viewer/NoTouchImageView.kt
1
492
package com.pr0gramm.app.ui.views.viewer import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView class NoTouchImageView(context: Context, attr: AttributeSet) : SubsamplingScaleImageView(context, attr) { @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { return false } }
mit
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/fragments/base/BasePresenter.kt
1
795
package com.duopoints.android.fragments.base import android.os.Bundle import com.duopoints.android.utils.logging.LogLevel import com.duopoints.android.utils.logging.log import com.evernote.android.state.StateSaver import com.trello.rxlifecycle2.components.support.RxFragment abstract class BasePresenter<View : RxFragment> protected constructor(protected var view: View) { internal fun onCreate(savedState: Bundle?) { StateSaver.restoreInstanceState(this, savedState) } internal fun onSave(state: Bundle) { StateSaver.saveInstanceState(this, state) } fun log(logLevel: LogLevel, message: String) { javaClass.log(logLevel, message) } fun log(logLevel: LogLevel, throwable: Throwable) { javaClass.log(logLevel, throwable) } }
gpl-3.0
FHannes/intellij-community
java/java-impl/src/com/intellij/psi/filters/getters/BuilderCompletion.kt
4
4168
/* * 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 com.intellij.psi.filters.getters import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.completion.JavaMethodCallElement import com.intellij.codeInsight.lookup.ExpressionLookupItem import com.intellij.codeInsight.lookup.LookupElement import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.PlatformIcons import java.util.* /** * @author peter */ internal class BuilderCompletion(private val expectedType: PsiClassType, private val expectedClass: PsiClass, private val place: PsiElement) { fun suggestBuilderVariants(): List<LookupElement> { val result = ArrayList<LookupElement>() for (builderClass in expectedClass.innerClasses.filter { it.name?.contains("Builder") == true }) { for (buildMethods in methodsReturning(expectedClass, builderClass, true)) { for (createMethods in methodsReturning(builderClass, expectedClass, false)) { createBuilderCall(buildMethods, createMethods)?.let { result.add(it) } } } } return result } private fun methodsReturning(containingClass: PsiClass, returnedClass: PsiClass, isStatic: Boolean): Collection<List<PsiMethod>> { return containingClass.methods .filter { it.hasModifierProperty(PsiModifier.STATIC) == isStatic && returnedClass == PsiUtil.resolveClassInClassTypeOnly(it.returnType) && PsiUtil.isAccessible(it, place, null) } .groupBy { it.name } .values } private fun showOverloads(methods: List<PsiMethod>) = if (methods.any { it.parameterList.parametersCount > 0 }) "..." else "" private fun createBuilderCall(buildOverloads: List<PsiMethod>, createOverloads: List<PsiMethod>): LookupElement? { val classQname = expectedClass.qualifiedName ?: return null val classShortName = expectedClass.name ?: return null val buildName = buildOverloads.first().name val createName = createOverloads.first().name val typeArgs = JavaMethodCallElement.getTypeParamsText(false, expectedClass, expectedType.resolveGenerics().substitutor) ?: "" val canonicalText = "$classQname.$typeArgs$buildName().$createName()" val presentableText = "$classShortName.$buildName(${showOverloads(buildOverloads)}).$createName(${showOverloads(createOverloads)})" val expr = try { JavaPsiFacade.getElementFactory(expectedClass.project).createExpressionFromText(canonicalText, place) } catch(e: IncorrectOperationException) { return null } if (expr.type != expectedType) return null return object: ExpressionLookupItem(expr, PlatformIcons.METHOD_ICON, presentableText, canonicalText, presentableText, buildName, createName) { override fun handleInsert(context: InsertionContext) { super.handleInsert(context) positionCaret(context) } } } } private fun positionCaret(context: InsertionContext) { val createCall = PsiTreeUtil.findElementOfClassAtOffset(context.file, context.tailOffset - 1, PsiMethodCallExpression::class.java, false) val buildCall = createCall?.methodExpression?.qualifierExpression as? PsiMethodCallExpression ?: return val hasParams = buildCall.methodExpression.multiResolve(true).any { ((it.element as? PsiMethod)?.parameterList?.parametersCount ?: 0) > 0 } val argRange = buildCall.argumentList.textRange context.editor.caretModel.moveToOffset(if (hasParams) (argRange.startOffset + argRange.endOffset) / 2 else argRange.endOffset) }
apache-2.0
AriaLyy/Aria
app/src/main/java/com/arialyy/simple/core/download/KotlinDownloadActivity.kt
2
9812
/* * Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria) * * 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.arialyy.simple.core.download import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.arialyy.annotations.Download import com.arialyy.aria.core.Aria import com.arialyy.aria.core.download.DownloadEntity import com.arialyy.aria.core.inf.IEntity import com.arialyy.aria.core.listener.ISchedulers import com.arialyy.aria.util.ALog import com.arialyy.aria.util.CommonUtil import com.arialyy.frame.util.show.T import com.arialyy.simple.R import com.arialyy.simple.R.string import com.arialyy.simple.base.BaseActivity import com.arialyy.simple.common.ModifyPathDialog import com.arialyy.simple.common.ModifyUrlDialog import com.arialyy.simple.databinding.ActivitySingleKotlinBinding import com.arialyy.simple.util.AppUtil import com.pddstudio.highlightjs.models.Language import java.io.IOException class KotlinDownloadActivity : BaseActivity<ActivitySingleKotlinBinding>() { private var mUrl: String? = null private var mFilePath: String? = null private var mModule: HttpDownloadModule? = null private var mTaskId: Long = -1 internal var receiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive( context: Context, intent: Intent ) { if (intent.action == ISchedulers.ARIA_TASK_INFO_ACTION) { ALog.d( TAG, "state = " + intent.getIntExtra(ISchedulers.TASK_STATE, -1) ) ALog.d( TAG, "type = " + intent.getIntExtra(ISchedulers.TASK_TYPE, -1) ) ALog.d( TAG, "speed = " + intent.getLongExtra(ISchedulers.TASK_SPEED, -1) ) ALog.d( TAG, "percent = " + intent.getIntExtra( ISchedulers.TASK_PERCENT, -1 ) ) ALog.d( TAG, "entity = " + intent.getParcelableExtra<DownloadEntity>( ISchedulers.TASK_ENTITY ).toString() ) } } } override fun onResume() { super.onResume() //registerReceiver(receiver, new IntentFilter(ISchedulers.ARIA_TASK_INFO_ACTION)); } override fun onDestroy() { super.onDestroy() //unregisterReceiver(receiver); Aria.download(this) .unRegister() } override fun init(savedInstanceState: Bundle?) { super.init(savedInstanceState) title = "单任务下载" Aria.download(this) .register() mModule = ViewModelProviders.of(this) .get(HttpDownloadModule::class.java) mModule!!.getHttpDownloadInfo(this) .observe(this, Observer { entity -> if (entity == null) { return@Observer } if (entity.state == IEntity.STATE_STOP) { binding.stateStr = getString(string.resume) } if (Aria.download(this).load(entity.id).isRunning) { binding.stateStr = getString(string.stop) } if (entity.fileSize != 0L) { binding.fileSize = CommonUtil.formatFileSize(entity.fileSize.toDouble()) binding.progress = if (entity.isComplete) 100 else (entity.currentProgress * 100 / entity.fileSize).toInt() } binding.url = entity.url binding.filePath = entity.filePath mUrl = entity.url mFilePath = entity.filePath }) binding.viewModel = this try { binding.codeView.setSource(AppUtil.getHelpCode(this, "KotlinHttpDownload.kt"), Language.JAVA) } catch (e: IOException) { e.printStackTrace() } } fun chooseUrl() { val dialog = ModifyUrlDialog(this, getString(R.string.modify_url_dialog_title), mUrl) dialog.show(supportFragmentManager, "ModifyUrlDialog") } fun chooseFilePath() { val dialog = ModifyPathDialog(this, getString(R.string.modify_file_path), mFilePath) dialog.show(supportFragmentManager, "ModifyPathDialog") } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_single_task_activity, menu) return super.onCreateOptionsMenu(menu) } override fun onMenuItemClick(item: MenuItem): Boolean { var speed = -1 var msg = "" when (item.itemId) { R.id.help -> { msg = ("一些小知识点:\n" + "1、你可以在注解中增加链接,用于指定被注解的方法只能被特定的下载任务回调,以防止progress乱跳\n" + "2、当遇到网络慢的情况时,你可以先使用onPre()更新UI界面,待连接成功时,再在onTaskPre()获取完整的task数据,然后给UI界面设置正确的数据\n" + "3、你可以在界面初始化时通过Aria.download(this).load(URL).getPercent()等方法快速获取相关任务的一些数据") showMsgDialog("tip", msg) } R.id.speed_0 -> speed = 0 R.id.speed_128 -> speed = 128 R.id.speed_256 -> speed = 256 R.id.speed_512 -> speed = 512 R.id.speed_1m -> speed = 1024 } if (speed > -1) { msg = item.title.toString() Aria.download(this) .setMaxSpeed(speed) T.showShort(this, msg) } return true } @Download.onWait fun onWait(task: com.arialyy.aria.core.task.DownloadTask) { if (task.key == mUrl) { Log.d(TAG, "wait ==> " + task.downloadEntity.fileName) } } @Download.onPre fun onPre(task: com.arialyy.aria.core.task.DownloadTask) { if (task.key == mUrl) { binding.stateStr = getString(R.string.stop) } } @Download.onTaskStart fun taskStart(task: com.arialyy.aria.core.task.DownloadTask) { if (task.key == mUrl) { binding.fileSize = task.convertFileSize } } @Download.onTaskRunning fun running(task: com.arialyy.aria.core.task.DownloadTask) { if (task.key == mUrl) { //Log.d(TAG, task.getKey()); val len = task.fileSize if (len == 0L) { binding.progress = 0 } else { binding.progress = task.percent } binding.speed = task.convertSpeed } } @Download.onTaskResume fun taskResume(task: com.arialyy.aria.core.task.DownloadTask) { if (task.key == mUrl) { binding.stateStr = getString(R.string.stop) } } @Download.onTaskStop fun taskStop(task: com.arialyy.aria.core.task.DownloadTask) { if (task.key == mUrl) { binding.stateStr = getString(R.string.resume) binding.speed = "" } } @Download.onTaskCancel fun taskCancel(task: com.arialyy.aria.core.task.DownloadTask) { if (task.key == mUrl) { binding.progress = 0 binding.stateStr = getString(R.string.start) binding.speed = "" Log.d(TAG, "cancel") } } /** * */ @Download.onTaskFail fun taskFail( task: com.arialyy.aria.core.task.DownloadTask, e: Exception ) { if (task.key == mUrl) { Toast.makeText(this, getString(R.string.download_fail), Toast.LENGTH_SHORT) .show() binding.stateStr = getString(R.string.start) } } @Download.onTaskComplete fun taskComplete(task: com.arialyy.aria.core.task.DownloadTask) { if (task.key == mUrl) { binding.progress = 100 Toast.makeText( this, getString(R.string.download_success), Toast.LENGTH_SHORT ) .show() binding.stateStr = getString(R.string.re_start) binding.speed = "" } } override fun setLayoutId(): Int { return R.layout.activity_single_kotlin } fun onClick(view: View) { when (view.id) { R.id.start -> if (Aria.download(this).load(mTaskId).isRunning) { Aria.download(this) .load(mTaskId) .stop() } else { startD() } R.id.stop -> Aria.download(this).load(mTaskId).stop() R.id.cancel -> Aria.download(this).load(mTaskId).cancel(true) } } private fun startD() { if (mTaskId == -1L) { mTaskId = Aria.download(this) .load(mUrl!!) //.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3") //.addHeader("Accept-Encoding", "gzip, deflate") //.addHeader("DNT", "1") //.addHeader("Cookie", "BAIDUID=648E5FF020CC69E8DD6F492D1068AAA9:FG=1; BIDUPSID=648E5FF020CC69E8DD6F492D1068AAA9; PSTM=1519099573; BD_UPN=12314753; locale=zh; BDSVRTM=0") .setFilePath(mFilePath!!, true) .create() } else { Aria.download(this) .load(mTaskId) .resume() } } override fun onStop() { super.onStop() //Aria.download(this).unRegister(); } override fun dataCallback( result: Int, data: Any ) { super.dataCallback(result, data) if (result == ModifyUrlDialog.MODIFY_URL_DIALOG_RESULT) { mModule!!.uploadUrl(this, data.toString()) } else if (result == ModifyPathDialog.MODIFY_PATH_RESULT) { mModule!!.updateFilePath(this, data.toString()) } } }
apache-2.0
GeoffreyMetais/vlc-android
application/moviepedia/src/main/java/org/videolan/moviepedia/models/body/ScrobbleBody.kt
1
1665
/* * ************************************************************************ * ScrobbleBody.kt * ************************************************************************* * Copyright © 2019 VLC authors and VideoLAN * Author: Nicolas POMEPUY * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.moviepedia.models.body data class ScrobbleBody( val osdbhash: String? = null, val infohash: String? = null, val imdbId: String? = null, val dvdId: String? = null, val title: String? = null, val alternativeTitles: String? = null, val filename: String? = null, val show: String? = null, val year: String? = null, val season: String? = null, val episode: String? = null, val duration: String? = null ) data class ScrobbleBodyBatch( val id: String, val metadata: ScrobbleBody )
gpl-2.0
QuickBlox/quickblox-android-sdk
sample-pushnotifications-kotlin/app/src/main/java/com/quickblox/sample/pushnotifications/kotlin/utils/ActivityLifecycle.kt
1
964
package com.quickblox.sample.pushnotifications.kotlin.utils import android.app.Activity import android.app.Application import android.os.Bundle object ActivityLifecycle : Application.ActivityLifecycleCallbacks { private var isForeground: Boolean = false fun isBackground(): Boolean { return !isForeground } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { // empty } override fun onActivityStarted(activity: Activity) { // empty } override fun onActivityResumed(activity: Activity) { isForeground = true } override fun onActivityPaused(activity: Activity) { isForeground = false } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { // empty } override fun onActivityDestroyed(activity: Activity) { // empty } }
bsd-3-clause
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/filesystem/smb/CifsContexts.kt
3
3589
/* * Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.smb import android.net.Uri import android.text.TextUtils import android.util.Log import io.reactivex.Single import io.reactivex.schedulers.Schedulers import jcifs.CIFSException import jcifs.config.PropertyConfiguration import jcifs.context.BaseContext import jcifs.context.SingletonContext import java.util.* import java.util.concurrent.ConcurrentHashMap object CifsContexts { const val SMB_URI_PREFIX = "smb://" private val TAG = CifsContexts::class.java.simpleName private val defaultProperties: Properties = Properties().apply { setProperty("jcifs.resolveOrder", "BCAST") setProperty("jcifs.smb.client.responseTimeout", "30000") setProperty("jcifs.netbios.retryTimeout", "5000") setProperty("jcifs.netbios.cachePolicy", "-1") } private val contexts: MutableMap<String, BaseContext> = ConcurrentHashMap() @JvmStatic fun clearBaseContexts() { contexts.forEach { try { it.value.close() } catch (e: CIFSException) { Log.w(TAG, "Error closing SMB connection", e) } } contexts.clear() } @JvmStatic fun createWithDisableIpcSigningCheck( basePath: String, disableIpcSigningCheck: Boolean ): BaseContext { return if (disableIpcSigningCheck) { val extraProperties = Properties() extraProperties["jcifs.smb.client.ipcSigningEnforced"] = "false" create(basePath, extraProperties) } else { create(basePath, null) } } @JvmStatic fun create(basePath: String, extraProperties: Properties?): BaseContext { val basePathKey: String = Uri.parse(basePath).run { val prefix = "$scheme://$authority" val suffix = if (TextUtils.isEmpty(query)) "" else "?$query" "$prefix$suffix" } return if (contexts.containsKey(basePathKey)) { contexts.getValue(basePathKey) } else { val context = Single.fromCallable { try { val p = Properties(defaultProperties) if (extraProperties != null) p.putAll(extraProperties) BaseContext(PropertyConfiguration(p)) } catch (e: CIFSException) { Log.e(TAG, "Error initialize jcifs BaseContext, returning default", e) SingletonContext.getInstance() } }.subscribeOn(Schedulers.io()) .blockingGet() contexts[basePathKey] = context context } } }
gpl-3.0
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/lread.kt
1
1898
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext import cc.aoeiuv020.panovel.api.reverseRemoveDuplication /** * Created by AoEiuV020 on 2018.06.03-19:35:33. */ class Lread : DslJsoupNovelContext() {init { hide = true site { name = "乐阅读" baseUrl = "https://www.6ks.net" logo = "https://www.6ks.net/images/logo.gif" } search { post { // https://www.lread.net/modules/article/search.php?searchkey=%B6%BC%CA%D0 charset = "UTF-8" url = "/search.php" data { "searchtype" to "articlename" "searchkey" to it } } // 搜索结果可能过多,但是页面不太大,无所谓了, document { items("#nr") { name("> td:nth-child(1) > a") author("> td:nth-child(3)") } } } // https://m.lread.net/book/88917.html // https://www.lread.net/read/88917/ detailPageTemplate = "/read/%s/" detail { document { novel { name("#info > h1") author("#info > p:nth-child(2)", block = pickString("作\\s*者:(\\S*)")) } image("#fmimg > img") update("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)")) introduction("#intro > p") } } chapters { document { items("#list > dl > dd > a") lastUpdate("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)")) }.reverseRemoveDuplication() } // https://www.lread.net/read/88917/32771268.html contentPageTemplate = "/read/%s.html" content { document { items("#content") } } } }
gpl-3.0
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/search/FuzzySearchActivity.kt
1
6144
package cc.aoeiuv020.panovel.search import android.content.Context import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import cc.aoeiuv020.panovel.IView import cc.aoeiuv020.panovel.R import cc.aoeiuv020.panovel.data.NovelManager import cc.aoeiuv020.panovel.data.entity.Novel import cc.aoeiuv020.panovel.list.NovelListAdapter import cc.aoeiuv020.panovel.settings.ListSettings import cc.aoeiuv020.panovel.settings.OtherSettings import cc.aoeiuv020.panovel.util.getStringExtra import com.google.android.material.snackbar.Snackbar import com.miguelcatalan.materialsearchview.MaterialSearchView import kotlinx.android.synthetic.main.activity_fuzzy_search.* import kotlinx.android.synthetic.main.novel_item_list.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.ctx import org.jetbrains.anko.startActivity class FuzzySearchActivity : AppCompatActivity(), IView, AnkoLogger { companion object { fun start(ctx: Context) { ctx.startActivity<FuzzySearchActivity>() } fun start(ctx: Context, novel: Novel) { // 精确搜索,refine search, start(ctx, novel.name, novel.author) } fun start(ctx: Context, name: String) { // 模糊搜索,fuzzy search, ctx.startActivity<FuzzySearchActivity>("name" to name) } fun start(ctx: Context, name: String, author: String) { // 精确搜索,refine search, ctx.startActivity<FuzzySearchActivity>("name" to name, "author" to author) } fun startSingleSite(ctx: Context, site: String) { // 单个网站模糊搜索,fuzzy search, ctx.startActivity<FuzzySearchActivity>("site" to site) } } private lateinit var presenter: FuzzySearchPresenter private val novelListAdapter by lazy { NovelListAdapter(onError = ::showError) } private var name: String? = null private var author: String? = null private var site: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_fuzzy_search) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) searchView.setOnQueryTextListener(object : MaterialSearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { searchView.hideKeyboard(searchView) search(query) return true } override fun onQueryTextChange(newText: String?): Boolean = false }) rvNovel.layoutManager = if (ListSettings.gridView) { androidx.recyclerview.widget.GridLayoutManager(ctx, if (ListSettings.largeView) 3 else 5) } else { androidx.recyclerview.widget.LinearLayoutManager(ctx) } presenter = FuzzySearchPresenter() presenter.attach(this) rvNovel.adapter = novelListAdapter name = getStringExtra("name", savedInstanceState) author = getStringExtra("author", savedInstanceState) site = getStringExtra("site", savedInstanceState) site?.let { presenter.singleSite(it) } srlRefresh.setOnRefreshListener { // 任何时候刷新都没影响,所以一开始就初始化好, forceRefresh() } // 如果传入了名字,就直接开始搜索, name?.let { nameNonnull -> search(nameNonnull, author) } ?: searchView.post { showSearch() } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString("name", name) outState.putString("author", author) } private fun showSearch() { searchView.showSearch() searchView.setQuery(presenter.name, false) } override fun onDestroy() { presenter.detach() super.onDestroy() } private fun search(name: String, author: String? = null) { srlRefresh.isRefreshing = true title = name this.name = name this.author = author novelListAdapter.clear() if (OtherSettings.refreshOnSearch) { novelListAdapter.refresh() } presenter.search(name, author) } private fun refresh() { // 重新搜索就是刷新了, // 没搜索就刷新也是不禁止的,所以要判断下, name?.let { search(it, author) } ?: run { srlRefresh.isRefreshing = false } } /** * 刷新列表,同时刷新小说章节信息, * 为了方便从书架过来,找一本小说的所有源的最新章节, */ private fun forceRefresh() { novelListAdapter.refresh() refresh() } fun addResult(list: List<NovelManager>) { // 插入有时会导致下滑,原因不明,保存状态解决, val lm = rvNovel.layoutManager ?: return val state = lm.onSaveInstanceState() ?: return novelListAdapter.addAll(list) lm.onRestoreInstanceState(state) } fun showOnComplete() { srlRefresh.isRefreshing = false } private val snack: Snackbar by lazy { Snackbar.make(rvNovel, "", Snackbar.LENGTH_SHORT) } fun showError(message: String, e: Throwable) { srlRefresh.isRefreshing = false snack.setText(message + e.message) snack.show() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_fuzzy_search, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.search -> { searchView.showSearch() searchView.setQuery(presenter.name, false) } android.R.id.home -> onBackPressed() else -> return super.onOptionsItemSelected(item) } return true } }
gpl-3.0
natanieljr/droidmate
project/pcComponents/core/src/test/kotlin/org/droidmate/test_tools/device_simulation/GuiScreen.kt
1
11231
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // 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/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.test_tools.device_simulation import org.droidmate.deviceInterface.exploration.DeviceResponse import org.droidmate.deviceInterface.exploration.ExplorationAction /** * <p> * The time generator provides successive timestamps to the logs returned by the simulated device from a call to * {@link #perform(org.droidmate.uiautomator_daemon.guimodel.ExplorationAction)}. * * </p><p> * If this object s a part of simulation obtained from exploration output the time generator is null, as no time needs to be * generated. Instead, all time is obtained from the exploration output timestamps. * * </p> */ class GuiScreen /*constructor(private val internalId: String, packageName : String = "", private val timeGenerator : ITimeGenerator? = null)*/ // TODO Fix tests : IGuiScreen { override fun perform(action: ExplorationAction): IScreenTransitionResult { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getGuiSnapshot(): DeviceResponse { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getId(): String { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun addHomeScreenReference(home: IGuiScreen) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun addMainScreenReference(main: IGuiScreen) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun addWidgetTransition(widgetId: String, targetScreen: IGuiScreen) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun addWidgetTransition(widgetId: String, targetScreen: IGuiScreen, ignoreDuplicates: Boolean) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun buildInternals() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun verify() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } // TODO Fix tests //private static final String packageAndroidLauncher = new DeviceConfigurationFactory(DeviceConstants.DEVICE_DEFAULT).getConfiguration().getPackageAndroidLauncher() /*companion object { const val idHome = "home" const val idChrome = "chrome" val reservedIds = arrayListOf(idHome, idChrome) val reservedIdsPackageNames = mapOf( idHome to DeviceModel.buildDefault().getAndroidLauncherPackageName(), idChrome to "com.android.chrome") fun getSingleMatchingWidget(action: ClickAction, widgets: List<Widget>): Widget { return widgets.find { w->w.xpath==action.xPath }!! } fun getSingleMatchingWidget(action: CoordinateClickAction, widgets: List<Widget>): Widget { return widgets.find { w->w.bounds.contains(action.x, action.y) }!! } } private val packageName: String private var internalGuiSnapshot: IDeviceGuiSnapshot = MissingGuiSnapshot() private var home: IGuiScreen? = null private var main: IGuiScreen? = null private val widgetTransitions: MutableMap<Widget, IGuiScreen> = mutableMapOf() private var finishedBuilding = false constructor(snapshot: IDeviceGuiSnapshot) : this(snapshot.id, snapshot.getPackageName()) { this.internalGuiSnapshot = snapshot } initialize { this.packageName = if (packageName.isNotEmpty()) packageName else reservedIdsPackageNames[internalId]!! assert(this.internalId.isNotEmpty()) assert(this.packageName.isNotEmpty()) assert((this.internalId !in reservedIds) || (this.packageName == reservedIdsPackageNames[internalId])) assert((this.internalId in reservedIds) || (this.packageName !in reservedIdsPackageNames.values)) } override fun perform(action: ExplorationAction): IScreenTransitionResult { assert(finishedBuilding) return when (action) { // TODO review is SimulationAdbClearPackageAction -> internalPerform(action) is LaunchAppAction -> internalPerform(action) is ClickAction -> internalPerform(action) is CoordinateClickAction -> internalPerform(action) is LongClickAction -> internalPerform(action) is CoordinateLongClickAction -> internalPerform(action) else -> throw UnsupportedMultimethodDispatch(action) } } //region internalPerform multimethod // This method is used: it is a multimethod. private fun internalPerform(clearPackage: SimulationAdbClearPackageAction): IScreenTransitionResult { return if (this.getGuiSnapshot().getPackageName() == clearPackage.packageName) ScreenTransitionResult(home!!, ArrayList()) else ScreenTransitionResult(this, ArrayList()) } @Suppress("UNUSED_PARAMETER") private fun internalPerform(launch: LaunchAppAction): IScreenTransitionResult = ScreenTransitionResult(main!!, this.buildMonitorMessages()) private fun internalPerform(action: ExplorationAction): IScreenTransitionResult { return when (action) { is PressHomeAction -> ScreenTransitionResult(home!!, ArrayList()) is EnableWifiAction -> { assert(this == home) ScreenTransitionResult(this, ArrayList()) } is PressBackAction -> ScreenTransitionResult(this, ArrayList()) is ClickAction -> { val widget = getSingleMatchingWidget(action, widgetTransitions.keys.toList()) ScreenTransitionResult(widgetTransitions[widget]!!, ArrayList()) } is CoordinateClickAction -> { val widget = getSingleMatchingWidget(action, widgetTransitions.keys.toList()) ScreenTransitionResult(widgetTransitions[widget]!!, ArrayList()) } else -> throw UnexpectedIfElseFallthroughError("Found action $action") } } //endregion internalPerform multimethod override fun addWidgetTransition(widgetId: String, targetScreen: IGuiScreen, ignoreDuplicates: Boolean) { assert(!finishedBuilding) assert(this.internalId !in reservedIds) assert(ignoreDuplicates || !(widgetTransitions.keys.any { it.id.contains(widgetId) })) if (!(ignoreDuplicates && widgetTransitions.keys.any { it.id.contains(widgetId) })) { val widget = if (this.getGuiSnapshot() !is MissingGuiSnapshot) this.getGuiSnapshot().guiState.widgets.single { it.id == widgetId } else WidgetTestHelper.newClickableWidget(mutableMapOf("uid" to widgetId), /* widgetGenIndex */ widgetTransitions.keys.size) widgetTransitions[widget] = targetScreen } assert(widgetTransitions.keys.any { it.id.contains(widgetId) }) } override fun addHomeScreenReference(home: IGuiScreen) { assert(!finishedBuilding) assert(home.getId() == idHome) this.home = home } override fun addMainScreenReference(main: IGuiScreen) { assert(!finishedBuilding) assert(main.getId() !in reservedIds) this.main = main } override fun buildInternals() { assert(!this.finishedBuilding) assert(this.getGuiSnapshot() is MissingGuiSnapshot) val widgets = widgetTransitions.keys when (internalId) { !in reservedIds -> { val guiState = if (widgets.isEmpty()) { buildEmptyInternals() } else GuiStateTestHelper.newGuiStateWithWidgets( widgets.size, packageName, /* enabled */ true, internalId, widgets.map { it.id }) this.internalGuiSnapshot = UiautomatorWindowDumpTestHelper.fromGuiState(guiState) } idHome -> this.internalGuiSnapshot = UiautomatorWindowDumpTestHelper.newHomeScreenWindowDump(this.internalId) idChrome -> this.internalGuiSnapshot = UiautomatorWindowDumpTestHelper.newAppOutOfScopeWindowDump(this.internalId) else -> throw UnexpectedIfElseFallthroughError("Unsupported reserved uid: $internalId") } assert(this.getGuiSnapshot().id.isNotEmpty()) } private fun buildEmptyInternals(): DeviceResponse { val guiState = GuiStateTestHelper.newGuiStateWithTopLevelNodeOnly(packageName, internalId) // This one widget is necessary, as it is the only xml element from which packageName can be obtained. Without it, following // method would fail: UiautomatorWindowDump.getPackageName when called on // org.droidmate.exploration.device.simulation.GuiScreen.guiSnapshot. assert(guiState.widgets.size == 1) return guiState } override fun verify() { assert(!finishedBuilding) this.finishedBuilding = true assert(this.home?.getId() == idHome) assert(this.main?.getId() !in reservedIds) assert(this.getGuiSnapshot().id.isNotEmpty()) assert(this.getGuiSnapshot().guiState.id.isNotEmpty()) // TODO: Review later //assert((this.internalId in reservedIds) || (this.widgetTransitions.keys.map { it.uid }.sorted() == this.getGuiSnapshot().guiStatus.getActionableWidgets().map { it.uid }.sorted())) assert(this.finishedBuilding) } private fun buildMonitorMessages(): List<TimeFormattedLogMessageI> { return listOf( TimeFormattedLogcatMessage.from( this.timeGenerator!!.shiftAndGet(mapOf("milliseconds" to 1500)), // Milliseconds amount based on empirical evidence. MonitorConstants.loglevel.toUpperCase(), MonitorConstants.tag_mjt, "4224", // arbitrary process ID MonitorConstants.msg_ctor_success), TimeFormattedLogcatMessage.from( this.timeGenerator.shiftAndGet(mapOf("milliseconds" to 1810)), // Milliseconds amount based on empirical evidence. MonitorConstants.loglevel.toUpperCase(), MonitorConstants.tag_mjt, "4224", // arbitrary process ID MonitorConstants.msgPrefix_init_success + this.packageName) ) } override fun toString(): String { return MoreObjects.toStringHelper(this) .update("uid", internalId) .toString() } override fun getId(): String = this.internalId override fun getGuiSnapshot(): IDeviceGuiSnapshot = this.internalGuiSnapshot override fun addWidgetTransition(widgetId: String, targetScreen: IGuiScreen) { addWidgetTransition(widgetId, targetScreen, false) }*/ }
gpl-3.0
ademar111190/Studies
Projects/Test/app/src/main/java/ademar/study/test/presenter/LoadDataView.kt
1
315
package ademar.study.test.presenter import ademar.study.test.model.ErrorViewModel import ademar.study.test.view.base.BaseActivity interface LoadDataView { fun getBaseActivity(): BaseActivity? fun showLoading() fun showRetry() fun showContent() fun showError(viewModel: ErrorViewModel) }
mit
soniccat/android-taskmanager
storagemanager/src/main/java/com/example/alexeyglushkov/cachemanager/disk/serializer/DiskMetadataDeserializer.kt
1
1748
package com.example.alexeyglushkov.cachemanager.disk.serializer import com.example.alexeyglushkov.cachemanager.disk.DiskStorageMetadata import com.example.alexeyglushkov.jacksonlib.CustomDeserializer import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import java.io.IOException /** * Created by alexeyglushkov on 18.09.16. */ class DiskMetadataDeserializer(vc: Class<DiskStorageMetadata>) : CustomDeserializer<DiskStorageMetadata>(vc) { override fun createObject(): DiskStorageMetadata { return DiskStorageMetadata() } @Throws(IOException::class) protected override fun handle(p: JsonParser, ctxt: DeserializationContext, metadata: DiskStorageMetadata): Boolean { val name = p.currentName var isHandled = false when (name) { "contentSize" -> { val contentSize = _parseLong(p, ctxt) metadata.contentSize = contentSize isHandled = true } "createTime" -> { val createTime = _parseLong(p, ctxt) metadata.createTime = createTime isHandled = true } "expireTime" -> { val expireTime = _parseLong(p, ctxt) metadata.expireTime = expireTime isHandled = true } "entryClass" -> { val className = _parseString(p, ctxt) try { metadata.entryClass = Class.forName(className) } catch (e: ClassNotFoundException) { e.printStackTrace() } isHandled = true } } return isHandled } }
mit
juxeii/dztools
java/dzjforex/src/main/kotlin/com/jforex/dzjforex/stop/BrokerStop.kt
1
2120
package com.jforex.dzjforex.stop import com.dukascopy.api.IOrder import com.jforex.dzjforex.misc.* import com.jforex.dzjforex.order.OrderLookupApi.getTradeableOrderForId import com.jforex.dzjforex.zorro.BROKER_ADJUST_SL_FAIL import com.jforex.dzjforex.zorro.BROKER_ADJUST_SL_OK import com.jforex.kforexutils.order.event.OrderEvent import com.jforex.kforexutils.order.event.OrderEventType import com.jforex.kforexutils.order.extension.setSL object BrokerStopApi { fun <F> ContextDependencies<F>.brokerStop(orderId: Int, slPrice: Double) = getTradeableOrderForId(orderId) .flatMap { order -> logger.debug("BrokerStop: setting stop loss price $slPrice for oder $order") setSLPrice(order, slPrice) } .map(::processCloseEvent) .handleErrorWith { error -> processError(error) } private fun <F> ContextDependencies<F>.processError(error: Throwable) = delay { when (error) { is OrderIdNotFoundException -> natives.logAndPrintErrorOnZorro("BrokerStop: order id ${error.orderId} not found!") is AssetNotTradeableException -> natives.logAndPrintErrorOnZorro("BrokerStop: ${error.instrument} currently not tradeable!") else -> logger.error( "BrokerStop failed! Error: ${error.message} " + "Stack trace: ${getStackTrace(error)}" ) } BROKER_ADJUST_SL_FAIL } fun processCloseEvent(orderEvent: OrderEvent) = if (orderEvent.type == OrderEventType.CHANGED_SL) { logger.debug("BrokerStop: stop loss price successfully set for order ${orderEvent.order}") BROKER_ADJUST_SL_OK } else { logger.debug("BrokerStop: setting stop loss failed for order ${orderEvent.order} event $orderEvent") BROKER_ADJUST_SL_FAIL } fun <F> ContextDependencies<F>.setSLPrice(order: IOrder, slPrice: Double) = catch { order .setSL(slPrice = slPrice) {} .blockingLast() } }
mit
cout970/Magneticraft
ignore/test/item/ItemThermometer.kt
2
2685
package item import com.cout970.magneticraft.api.heat.IHeatNode import com.cout970.magneticraft.api.heat.IHeatNodeHandler import com.cout970.magneticraft.config.Config import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.registry.HEAT_NODE_HANDLER import com.cout970.magneticraft.registry.fromTile import com.cout970.magneticraft.util.guessAmbientTemp import com.cout970.magneticraft.util.toCelsius import com.cout970.magneticraft.util.toFahrenheit import com.teamwizardry.librarianlib.common.base.item.ItemMod import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.util.EnumActionResult import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.BlockPos import net.minecraft.util.text.TextComponentString import net.minecraft.world.World /** * Created by cout970 on 20/07/2016. */ object ItemThermometer : ItemMod("thermometer") { override fun onItemUse(stack: ItemStack?, playerIn: EntityPlayer, worldIn: World, pos: BlockPos, hand: EnumHand?, facing: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): EnumActionResult { //DEBUG //if (Debug.DEBUG && Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) { // val tile = worldIn.getTileEntity(pos) // playerIn.sendMessage("Server: ${worldIn.isServer}, Tile: ${tile?.serializeNBT()}\n") //} //NO DEBUG if (worldIn.isServer) { val tile = worldIn.getTileEntity(pos) if (tile != null) { val handler = HEAT_NODE_HANDLER!!.fromTile(tile, facing) if (handler is IHeatNodeHandler) { for (i in handler.nodes) { if (i !is IHeatNode) continue if (Config.heatUnitCelsius) playerIn.addChatComponentMessage(TextComponentString("%.2fC".format(i.temperature.toCelsius()))) else playerIn.addChatComponentMessage(TextComponentString("%.2fF".format(i.temperature.toFahrenheit()))) return super.onItemUse(stack, playerIn, worldIn, pos, hand, facing, hitX, hitY, hitZ) } } } if (Config.heatUnitCelsius) { playerIn.addChatComponentMessage(TextComponentString("Ambient: %.2fC".format(guessAmbientTemp(worldIn, pos).toCelsius()))) } else { playerIn.addChatComponentMessage(TextComponentString("Ambient: %.2fF".format(guessAmbientTemp(worldIn, pos).toFahrenheit()))) } } return super.onItemUse(stack, playerIn, worldIn, pos, hand, facing, hitX, hitY, hitZ) } }
gpl-2.0
fallGamlet/DnestrCinema
KinotirApi/src/main/java/com/kinotir/api/mappers/Mapper.kt
1
91
package com.kinotir.api.mappers interface Mapper<From, To> { fun map(src: From): To }
gpl-3.0
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/command/handlers/CallCommandHandler.kt
1
1233
package com.flexpoker.table.command.handlers import com.flexpoker.framework.command.CommandHandler import com.flexpoker.framework.event.EventPublisher import com.flexpoker.table.command.aggregate.applyEvents import com.flexpoker.table.command.aggregate.eventproducers.call import com.flexpoker.table.command.commands.CallCommand import com.flexpoker.table.command.events.TableEvent import com.flexpoker.table.command.repository.TableEventRepository import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Component import javax.inject.Inject @Component class CallCommandHandler @Inject constructor( private val eventPublisher: EventPublisher<TableEvent>, private val tableEventRepository: TableEventRepository ) : CommandHandler<CallCommand> { @Async override fun handle(command: CallCommand) { val existingEvents = tableEventRepository.fetchAll(command.tableId) val state = applyEvents(existingEvents) val newEvents = call(state, command.playerId) val newlySavedEventsWithVersions = tableEventRepository.setEventVersionsAndSave(existingEvents.size, newEvents) newlySavedEventsWithVersions.forEach { eventPublisher.publish(it) } } }
gpl-2.0
arturbosch/detekt
detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/IgnoredReturnValueSpec.kt
1
28441
package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.assertThat import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext import io.gitlab.arturbosch.detekt.test.lintWithContext import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object IgnoredReturnValueSpec : Spek({ setupKotlinEnvironment() val env: KotlinCoreEnvironment by memoized() describe("default config with non-annotated return values") { val subject by memoized { IgnoredReturnValue() } it("does not report when a function which returns a value is called and the return is ignored") { val code = """ fun foo() { listOf("hello") } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function which returns a value is called before a valid return") { val code = """ fun foo() : Int { listOf("hello") return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function which returns a value is called in chain and the return is ignored") { val code = """ fun foo() { listOf("hello").isEmpty().not() } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function which returns a value is called before a semicolon") { val code = """ fun foo() { listOf("hello");println("foo") } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function which returns a value is called after a semicolon") { val code = """ fun foo() { println("foo");listOf("hello") } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function which returns a value is called between comments") { val code = """ fun foo() { listOf("hello")//foo } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when an extension function which returns a value is called and the return is ignored") { val code = """ fun Int.isTheAnswer(): Boolean = this == 42 fun foo(input: Int) { input.isTheAnswer() } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when the return value is assigned to a pre-existing variable") { val code = """ package test annotation class CheckReturnValue @CheckReturnValue @Deprecated("Yes") fun listA() = listOf("hello") fun foo() { var x: List<String> x = listA() } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function which doesn't return a value is called") { val code = """ fun noReturnValue() {} fun foo() { noReturnValue() } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function's return value is used in a test statement") { val code = """ fun returnsBoolean() = true fun f() { if (returnsBoolean()) {} } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function's return value is used in a comparison") { val code = """ fun returnsInt() = 42 fun f() { if (42 == returnsInt()) {} } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function's return value is used as parameter for another call") { val code = """ fun returnsInt() = 42 fun f() { println(returnsInt()) } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function's return value is used with named parameters") { val code = """ fun returnsInt() = 42 fun f() { println(message = returnsInt()) } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } } describe("default config with annotated return values") { val subject by memoized { IgnoredReturnValue() } it("reports when a function which returns a value is called and the return is ignored") { val code = """ package annotation @CheckReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() { listOfChecked("hello") println("foo") } """ val annotationClass = """ package annotation annotation class CheckReturnValue """ val findings = subject.lintWithContext(env, code, annotationClass) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(7, 5) assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.") } it("reports when a function which returns a value is called before a valid return") { val code = """ package noreturn annotation class CheckReturnValue @CheckReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() : Int { listOfChecked("hello") return 42 } """ val findings = subject.lintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(9, 5) assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.") } it("reports when a function which returns a value is called in chain as first statement and the return is ignored") { val code = """ package noreturn annotation class CheckReturnValue @CheckReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() : Int { listOfChecked("hello").isEmpty().not() return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function which returns a value is called in the middle of a chain and the return is ignored") { val code = """ package noreturn annotation class CheckReturnValue @CheckReturnValue fun String.listOfChecked() = listOf(this) fun foo() : Int { val hello = "world " hello.toUpperCase() .trim() .listOfChecked() .isEmpty() .not() return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("reports when a function which returns a value is called in the end of a chain and the return is ignored") { val code = """ package noreturn annotation class CheckReturnValue @CheckReturnValue fun String.listOfChecked() = listOf(this) fun foo() : Int { val hello = "world " hello.toUpperCase() .trim() .listOfChecked() return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(12, 10) assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.") } it("reports when a function which returns a value is called before a semicolon") { val code = """ package special annotation class CheckReturnValue @CheckReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() { listOfChecked("hello");println("foo") } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(9, 5) assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.") } it("reports when a function which returns a value is called after a semicolon") { val code = """ package special annotation class CheckReturnValue @CheckReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() : Int { println("foo");listOfChecked("hello") return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(9, 20) assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.") } it("reports when a function which returns a value is called between comments") { val code = """ package special annotation class CheckReturnValue @CheckReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() : Int { /* foo */listOfChecked("hello")//foo return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(9, 14) assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.") } it("reports when an extension function which returns a value is called and the return is ignored") { val code = """ package specialize annotation class CheckReturnValue @CheckReturnValue fun Int.isTheAnswer(): Boolean = this == 42 fun foo(input: Int) : Int { input.isTheAnswer() return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(8, 11) assertThat(findings[0]).hasMessage("The call isTheAnswer is returning a value that is ignored.") } it("does not report when the return value is assigned to a pre-existing variable") { val code = """ package specialize annotation class CheckReturnValue @CheckReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() : Int { var x: List<String> x = listOfChecked("hello") return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function which doesn't return a value is called") { val code = """ package specialize annotation class CheckReturnValue @CheckReturnValue fun noReturnValue() {} fun foo() : Int { noReturnValue() return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function's return value is used in a test statement") { val code = """ package comparison annotation class CheckReturnValue @CheckReturnValue fun returnsBoolean() = true fun f() { if (returnsBoolean()) {} } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function's return value is used in a comparison") { val code = """ package comparison annotation class CheckReturnValue @CheckReturnValue fun returnsInt() = 42 fun f() { if (42 == returnsInt()) {} } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function's return value is used as parameter for another call") { val code = """ package parameter annotation class CheckReturnValue @CheckReturnValue fun returnsInt() = 42 fun f() { println(returnsInt()) } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function's return value is used with named parameters") { val code = """ package parameter annotation class CheckReturnValue @CheckReturnValue fun returnsInt() = 42 fun f() { println(message = returnsInt()) } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function is the last statement in a block and it's used") { val code = """ package block annotation class CheckReturnValue @CheckReturnValue fun returnsInt() = 42 val result = if (true) { 1 } else { returnsInt() } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("report when a function is not the last statement in a 'if' block and 'if' block is used") { val code = """ package block annotation class CheckReturnValue @CheckReturnValue fun returnsInt() = 42 val result = if (true) { 1 } else { returnsInt() 2 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("does not report when a function is the last statement in a block and it's in a chain") { val code = """ package block annotation class CheckReturnValue @CheckReturnValue fun returnsInt() = 42 fun test() { if (true) { 1 } else { returnsInt() }.plus(1) } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("report when a function is not the last statement in a block and it's in a chain") { val code = """ package block annotation class CheckReturnValue @CheckReturnValue fun returnsInt() = 42 fun test() { if (true) { 1 } else { returnsInt() 2 }.plus(1) } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("report when a function is the last statement in a block") { val code = """ package block annotation class CheckReturnValue @CheckReturnValue fun returnsInt() = 42 fun test() { if (true) { println("hello") } else { returnsInt() } } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) } it("does not report when a function return value is consumed in a chain that returns a Unit") { val code = """ package callchain annotation class CheckReturnValue @CheckReturnValue fun String.listOfChecked() = listOf(this) fun List<String>.print() { println(this) } fun foo() : Int { val hello = "world " hello.toUpperCase() .trim() .listOfChecked() .print() return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("reports when the containing class of a function has `@CheckReturnValue`") { val code = """ package foo annotation class CheckReturnValue @CheckReturnValue class Assertions { fun listOfChecked(value: String) = listOf(value) } fun main() { Assertions().listOfChecked("hello") } """ val findings = subject.lintWithContext(env, code) assertThat(findings).hasSize(1) } it("reports when the containing object of a function has `@CheckReturnValue`") { val code = """ package foo annotation class CheckReturnValue @CheckReturnValue object Assertions { fun listOfChecked(value: String) = listOf(value) } fun main() { Assertions.listOfChecked("hello") } """ val findings = subject.lintWithContext(env, code) assertThat(findings).hasSize(1) } it("does not report when the containing class of a function has `@CheckReturnValue` but the function has `@CanIgnoreReturnValue`") { val code = """ package foo annotation class CheckReturnValue annotation class CanIgnoreReturnValue @CheckReturnValue class Assertions { @CanIgnoreReturnValue fun listOfChecked(value: String) = listOf(value) } fun main() { Assertions().listOfChecked("hello") } """ val findings = subject.lintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when the containing class of a function has no `@CheckReturnValue` but the parent class has `@CheckReturnValue`") { val code = """ package foo annotation class CheckReturnValue @CheckReturnValue class Parent { class Child { fun listOfChecked(value: String) = listOf(value) } } fun main() { Parent.Child().listOfChecked("hello") } """ val findings = subject.lintWithContext(env, code) assertThat(findings).isEmpty() } } describe("custom annotation config") { val subject by memoized { IgnoredReturnValue( TestConfig(mapOf("returnValueAnnotations" to listOf("*.CustomReturn"))) ) } it("reports when a function is annotated with the custom annotation") { val code = """ package config annotation class CustomReturn @CustomReturn fun listOfChecked(value: String) = listOf(value) fun foo() : Int { listOfChecked("hello") return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(8, 5) assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.") } it("does not report when a function is annotated with the not included annotation") { val code = """ package config annotation class CheckReturnValue @CheckReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() : Int { listOfChecked("hello") return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function is not annotated") { val code = """ package config fun listOfChecked(value: String) = listOf(value) fun foo() : Int { listOfChecked("hello") return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } } describe("restrict to annotated methods config") { val subject by memoized { IgnoredReturnValue(TestConfig(mapOf("restrictToAnnotatedMethods" to false))) } it("reports when a function is annotated with a custom annotation") { val code = """ package config annotation class CheckReturnValue @CheckReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() : Int { listOfChecked("hello") return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(9, 5) assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.") } it("reports when a function is not annotated") { val code = """ fun listOfChecked(value: String) = listOf(value) fun foo() : Int { listOfChecked("hello") return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocation(4, 5) assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.") } it("does not report when a function has `@CanIgnoreReturnValue`") { val code = """ package foo annotation class CanIgnoreReturnValue @CanIgnoreReturnValue fun listOfChecked(value: String) = listOf(value) fun foo() : Int { listOfChecked("hello") return 42 } """ val findings = subject.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } it("does not report when a function has a custom annotation") { val code = """ package foo annotation class CustomIgnoreReturn @CustomIgnoreReturn fun listOfChecked(value: String) = listOf(value) fun foo() : Int { listOfChecked("hello") return 42 } """ val rule = IgnoredReturnValue( TestConfig( mapOf( "ignoreReturnValueAnnotations" to listOf("*.CustomIgnoreReturn"), "restrictToAnnotatedMethods" to false ) ) ) val findings = rule.compileAndLintWithContext(env, code) assertThat(findings).isEmpty() } } })
apache-2.0
adrcotfas/Goodtime
app/src/main/java/com/apps/adrcotfas/goodtime/di/AppModule.kt
1
1686
package com.apps.adrcotfas.goodtime.di import android.content.Context import com.apps.adrcotfas.goodtime.bl.CurrentSessionManager import com.apps.adrcotfas.goodtime.bl.NotificationHelper import com.apps.adrcotfas.goodtime.bl.RingtoneAndVibrationPlayer import com.apps.adrcotfas.goodtime.database.AppDatabase import com.apps.adrcotfas.goodtime.settings.PreferenceHelper import com.apps.adrcotfas.goodtime.settings.reminders.ReminderHelper import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun providePreferenceHelper(@ApplicationContext context: Context) = PreferenceHelper(context) @Provides @Singleton fun provideRingtoneAndVibrationPlayer(@ApplicationContext context: Context, preferenceHelper: PreferenceHelper) = RingtoneAndVibrationPlayer(context, preferenceHelper) @Provides @Singleton fun provideCurrentSessionManager(@ApplicationContext context: Context, preferenceHelper: PreferenceHelper) = CurrentSessionManager(context, preferenceHelper) @Provides @Singleton fun provideReminderHelper(@ApplicationContext context: Context, preferenceHelper: PreferenceHelper) = ReminderHelper(context, preferenceHelper) @Provides @Singleton fun provideNotificationHelper(@ApplicationContext context: Context) = NotificationHelper(context) @Provides @Singleton fun provideLocalDatabase(@ApplicationContext context: Context) = AppDatabase.getDatabase(context) }
apache-2.0
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/options/AbstractOption.kt
1
1655
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.options import javafx.scene.input.KeyCodeCombination import java.io.Serializable abstract class AbstractOption( override var code: String = "", override var aliases: MutableList<String> = mutableListOf<String>(), override var label: String = "", override var isRow: Boolean = true, override var isMultiple: Boolean = false, override var newTab: Boolean = false, override var prompt: Boolean = false, override var refresh: Boolean = false, override var shortcut: KeyCodeCombination? = null ) : Option, Serializable { protected fun copyTo(result: AbstractOption) { result.code = code result.aliases = ArrayList<String>(aliases) result.label = label result.isRow = isRow result.isMultiple = isMultiple result.newTab = newTab result.prompt = prompt result.refresh = refresh result.shortcut = shortcut } }
gpl-3.0
ksmirenko/flexicards-android
app/src/main/java/com/ksmirenko/flexicards/app/parsers/TxtParser.kt
1
1636
package com.ksmirenko.flexicards.app.parsers import com.ksmirenko.flexicards.app.datatypes.CardPack import java.io.BufferedReader import java.io.File import java.io.FileReader import java.io.IOException import java.util.ArrayList /** * Parses a text file into a CardPack. * * @author Kirill Smirenko */ class TxtParser(file : File) { val reader : BufferedReader val pack : CardPack init { reader = BufferedReader(FileReader(file)) pack = CardPack(null, null, null, ArrayList<Pair<String, String>>()) } fun parse() : CardPack? { try { var line = reader.readLine() val list = pack.cardList as ArrayList while (line != null) { when { line.startsWith("category=", true) -> pack.categoryName = line.removeSurrounding("category=\"", "\"") line.startsWith("lang=", true) -> pack.language = line.removeSurrounding("lang=\"", "\"") line.startsWith("module=", true) -> pack.moduleName = line.removeSurrounding("module=\"", "\"") line.contains('\t') -> { val arr = line.split('\t') if (arr.size == 2) { list.add(arr[0] to arr[1]) } } } line = reader.readLine() } return pack } catch (e : IOException) { return null } finally { reader.close() } } }
apache-2.0
dykstrom/jcc
src/test/kotlin/se/dykstrom/jcc/basic/compiler/BasicCodeGeneratorFunctionTests.kt
1
14847
/* * Copyright (C) 2017 Johan Dykstrom * * 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 se.dykstrom.jcc.basic.compiler import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import se.dykstrom.jcc.basic.ast.DefStrStatement import se.dykstrom.jcc.basic.ast.PrintStatement import se.dykstrom.jcc.basic.functions.BasicBuiltInFunctions.* import se.dykstrom.jcc.common.assembly.base.Line import se.dykstrom.jcc.common.assembly.instruction.* import se.dykstrom.jcc.common.assembly.instruction.floating.* import se.dykstrom.jcc.common.assembly.other.DataDefinition import se.dykstrom.jcc.common.ast.AssignStatement import se.dykstrom.jcc.common.ast.FunctionCallExpression import se.dykstrom.jcc.common.functions.BuiltInFunctions.FUN_PRINTF import se.dykstrom.jcc.common.functions.ExternalFunction import se.dykstrom.jcc.common.functions.FunctionUtils.LIB_LIBC import se.dykstrom.jcc.common.functions.LibraryFunction import se.dykstrom.jcc.common.types.F64 import se.dykstrom.jcc.common.types.I64 import se.dykstrom.jcc.common.types.Str class BasicCodeGeneratorFunctionTests : AbstractBasicCodeGeneratorTest() { @Before fun setUp() { // Define some functions for testing defineFunction(FUN_ABS) defineFunction(FUN_CINT) defineFunction(FUN_FOO) defineFunction(FUN_FLO) defineFunction(FUN_LEN) defineFunction(FUN_SGN) defineFunction(FUN_SIN) } @Test fun shouldGenerateSingleFunctionCallWithInt() { val fe = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(IL_1)) val ps = PrintStatement(0, 0, listOf(fe)) val result = assembleProgram(listOf(ps)) val lines = result.lines() // Three moves: format string, integer expression, and exit code assertEquals(3, countInstances(MoveImmToReg::class.java, lines)) // Three calls: abs, printf, and exit assertCodeLines(lines, 1, 3, 1, 3) assertTrue(hasIndirectCallTo(lines, FUN_ABS.mappedName)) } @Test fun shouldGenerateFunctionCallWithString() { val fe = FunctionCallExpression(0, 0, FUN_LEN.identifier, listOf(SL_ONE)) val ps = PrintStatement(0, 0, listOf(fe)) val result = assembleProgram(listOf(ps)) val lines = result.lines() // Three moves: format string, string expression, and exit code assertEquals(3, countInstances(MoveImmToReg::class.java, lines)) // Three calls: len, printf, and exit assertCodeLines(lines, 1, 3, 1, 3) assertTrue(hasIndirectCallTo(lines, FUN_LEN.mappedName)) } @Test fun shouldGenerateFunctionCallWithFloat() { val expression = FunctionCallExpression(0, 0, FUN_SIN.identifier, listOf(FL_3_14)) val assignStatement = AssignStatement(0, 0, NAME_F, expression) val result = assembleProgram(listOf(assignStatement)) val lines = result.lines() // One move: exit code assertEquals(1, countInstances(MoveImmToReg::class.java, lines)) // One move: float literal assertEquals(1, countInstances(MoveMemToFloatReg::class.java, lines)) // Two moves: argument to argument passing float register, and result to non-volatile float register assertEquals(2, countInstances(MoveFloatRegToFloatReg::class.java, lines)) // Two calls: sin and exit assertCodeLines(lines, 1, 2, 1, 2) assertTrue(hasIndirectCallTo(lines, FUN_SIN.mappedName)) } @Test fun shouldGenerateFunctionCallWithIntegerCastToFloat() { val expression = FunctionCallExpression(0, 0, FUN_SIN.identifier, listOf(IL_4)) val assignStatement = AssignStatement(0, 0, NAME_F, expression) val result = assembleProgram(listOf(assignStatement)) val lines = result.lines() // Two moves: exit code and integer literal assertEquals(2, countInstances(MoveImmToReg::class.java, lines)) // One conversion: integer literal to float assertEquals(1, countInstances(ConvertIntRegToFloatReg::class.java, lines)) // One move: result to non-volatile float register assertEquals(1, countInstances(MoveFloatRegToFloatReg::class.java, lines)) // Two calls: sin and exit assertCodeLines(lines, 1, 2, 1, 2) assertTrue(hasIndirectCallTo(lines, FUN_SIN.mappedName)) } @Test fun shouldGenerateFunctionCallWithFloatCastToInteger() { val expression = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(FL_3_14)) val assignStatement = AssignStatement(0, 0, NAME_A, expression) val result = assembleProgram(listOf(assignStatement)) val lines = result.lines() // One move: float literal assertEquals(1, countInstances(MoveMemToFloatReg::class.java, lines)) // One conversion: float literal to integer assertEquals(1, countInstances(RoundFloatRegToIntReg::class.java, lines)) // Two moves: result to non-volatile integer register, call to exit assertEquals(2, countInstances(MoveRegToReg::class.java, lines)) // One move: float literal assertEquals(1, countInstances(MoveRegToMem::class.java, lines)) // Two calls: abs and exit assertCodeLines(lines, 1, 2, 1, 2) assertTrue(hasIndirectCallTo(lines, FUN_ABS.mappedName)) } @Test fun shouldGenerateCallToFloatToIntFunction() { val expression = FunctionCallExpression(0, 0, FUN_CINT.identifier, listOf(FL_3_14)) val assignStatement = AssignStatement(0, 0, NAME_A, expression) val result = assembleProgram(listOf(assignStatement)) val lines = result.lines() // One move: exit code assertEquals(1, countInstances(MoveImmToReg::class.java, lines)) // One move: float literal assertEquals(1, countInstances(MoveMemToFloatReg::class.java, lines)) // One move: argument to argument passing float register assertEquals(1, countInstances(MoveFloatRegToFloatReg::class.java, lines)) // Two calls: sin and exit assertCodeLines(lines, 1, 1, 2, 2) // CINT is an assembly function, which makes the call direct assertTrue(hasDirectCallTo(lines, FUN_CINT.mappedName)) } @Test fun shouldGenerateVarargsFunctionCall() { // The varargs function call will be to printf val printStatement = PrintStatement(0, 0, listOf(FL_3_14, IL_1)) val result = assembleProgram(listOf(printStatement)) val lines = result.lines() // Three moves: format string, integer literal, and exit code assertEquals(3, countInstances(MoveImmToReg::class.java, lines)) // One move: float literal assertEquals(1, countInstances(MoveMemToFloatReg::class.java, lines)) // One move: argument to argument passing float register assertEquals(1, countInstances(MoveFloatRegToFloatReg::class.java, lines)) // Two calls: printf and exit assertCodeLines(lines, 1, 2, 1, 2) assertTrue(hasIndirectCallTo(lines, FUN_PRINTF.name)) } @Test fun shouldGenerateNestedFunctionCall() { val fe1 = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(IL_1)) val fe2 = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(fe1)) val fe3 = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(fe2)) val ps = PrintStatement(0, 0, listOf(fe3)) val result = assembleProgram(listOf(ps)) val lines = result.lines() // Three moves: format string, integer expression, and exit code assertEquals(3, countInstances(MoveImmToReg::class.java, lines)) // Five calls: abs*3, printf, and exit assertCodeLines(lines, 1, 3, 1, 5) } @Test fun shouldGenerateDeeplyNestedFunctionCall() { val fe1 = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(IL_1)) val fe2 = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(fe1)) val fe3 = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(fe2)) val fe4 = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(fe3)) val fe5 = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(fe4)) val fe6 = FunctionCallExpression(0, 0, FUN_ABS.identifier, listOf(fe5)) val ps = PrintStatement(0, 0, listOf(fe6)) val result = assembleProgram(listOf(ps)) val lines = result.lines() // Three moves: format string, integer expression, and exit code assertEquals(3, countInstances(MoveImmToReg::class.java, lines)) // Eight calls: abs*6, printf, and exit assertCodeLines(lines, 1, 3, 1, 8) } /** * Tests that we can encode a deeply nested function call to a function with many arguments, * even though we run out of registers to store evaluated arguments in. In that case, temporary * variables (memory addresses) will be used instead. */ @Test fun shouldGenerateNestedFunctionCallWithManyIntArgs() { val fe1 = FunctionCallExpression(0, 0, IDENT_FUN_FOO, listOf(IL_1, IL_2, IL_1)) val fe2 = FunctionCallExpression(0, 0, IDENT_FUN_FOO, listOf(IL_3, IL_4, IL_3)) val fe3 = FunctionCallExpression(0, 0, IDENT_FUN_FOO, listOf(fe1, fe2, IL_2)) val fe4 = FunctionCallExpression(0, 0, IDENT_FUN_FOO, listOf(fe1, fe2, IL_4)) val fe5 = FunctionCallExpression(0, 0, IDENT_FUN_FOO, listOf(fe3, fe4, IL_1)) val fe6 = FunctionCallExpression(0, 0, IDENT_FUN_FOO, listOf(fe5, IL_4, IL_3)) val ps = PrintStatement(0, 0, listOf(fe6, fe6, fe6)) val result = assembleProgram(listOf(ps)) val lines = result.lines() // We should be able to find at least one case where an evaluated argument is moved to and from a temporary variable assertTrue(lines.filterIsInstance<DataDefinition>().any { it.identifier().mappedName.startsWith("__tmp") }) assertTrue(lines.filterIsInstance<MoveRegToMem>().any { it.destination.startsWith("[__tmp") }) // Mapped name assertTrue(lines.filterIsInstance<MoveMemToReg>().any { it.source.startsWith("[__tmp") }) // Mapped name } /** * Tests that we can encode a deeply nested function call to a function with many float arguments. */ @Test fun shouldGenerateNestedFunctionCallWithManyFloatArgs() { val fe1 = FunctionCallExpression(0, 0, IDENT_FUN_FLO, listOf(FL_3_14, FL_17_E4, FL_3_14)) val fe2 = FunctionCallExpression(0, 0, IDENT_FUN_FLO, listOf(FL_3_14, FL_17_E4, FL_3_14)) val fe3 = FunctionCallExpression(0, 0, IDENT_FUN_FLO, listOf(fe1, fe2, FL_17_E4)) val fe4 = FunctionCallExpression(0, 0, IDENT_FUN_FLO, listOf(fe1, fe2, FL_3_14)) val fe5 = FunctionCallExpression(0, 0, IDENT_FUN_FLO, listOf(fe3, fe4, FL_17_E4)) val fe6 = FunctionCallExpression(0, 0, IDENT_FUN_FLO, listOf(fe5, FL_3_14, FL_17_E4)) val ps = PrintStatement(0, 0, listOf(fe6, fe6, fe6)) val result = assembleProgram(listOf(ps)) val lines = result.lines() // We should be able to find at least one case where an evaluated argument is moved to and from a temporary variable // This is used for parameter passing to the printf function to move values from float register to g.p. register assertTrue(lines.filterIsInstance<DataDefinition>().any { it.identifier().mappedName.startsWith("__tmp") }) assertTrue(lines.filterIsInstance<MoveFloatRegToMem>().any { it.destination.startsWith("[__tmp") }) // Mapped name assertTrue(lines.filterIsInstance<MoveMemToReg>().any { it.source.startsWith("[__tmp") }) // Mapped name } @Test fun shouldGenerateFunctionCallToAssemblyFunction() { val fe = FunctionCallExpression(0, 0, FUN_CINT.identifier, listOf(IL_1)) val ps = PrintStatement(0, 0, listOf(fe)) val result = assembleProgram(listOf(ps)) val lines = result.lines() // Three moves in main program: format string, integer expression, and exit code assertEquals(3, countInstances(MoveImmToReg::class.java, lines)) // One return from function assertEquals(1, countInstances(Ret::class.java, lines)) // Three calls: cint, printf, and exit // Two labels: main, cint assertCodeLines(lines, 1, 2, 2, 3) // cint is an assembly function, which makes the call direct assertTrue(hasDirectCallTo(lines, FUN_CINT.mappedName)) } @Test fun shouldGenerateFunctionCallWithDefinedType() { val ds = DefStrStatement(0, 0, setOf('b')) val fe = FunctionCallExpression(0, 0, FUN_LEN.identifier, listOf(IDE_STR_B)) val ps = PrintStatement(0, 0, listOf(fe)) val result = assembleProgram(listOf(ds, ps)) val lines = result.lines() // Two moves: format string and exit code assertEquals(2, countInstances(MoveImmToReg::class.java, lines)) // One move: variable b assertEquals(1, countInstances(MoveMemToReg::class.java, lines)) // One data definition: variable b of type string assertTrue(lines.filterIsInstance<DataDefinition>().any { it.type() is Str && it.identifier().mappedName == IDENT_STR_B.mappedName }) // Three calls: len, printf, and exit assertCodeLines(lines, 1, 3, 1, 3) assertTrue(hasIndirectCallTo(lines, FUN_LEN.mappedName)) } private fun hasIndirectCallTo(lines: List<Line>, mappedName: String) = lines.filterIsInstance<CallIndirect>().any { it.target.contains(mappedName) } private fun hasDirectCallTo(lines: List<Line>, mappedName: String) = lines.filterIsInstance<CallDirect>().any { it.target.contains(mappedName) } companion object { private val FUN_FOO = LibraryFunction("foo", listOf(I64.INSTANCE, I64.INSTANCE, I64.INSTANCE), I64.INSTANCE, LIB_LIBC, ExternalFunction("fooo")) private val FUN_FLO = LibraryFunction("flo", listOf(F64.INSTANCE, F64.INSTANCE, F64.INSTANCE), F64.INSTANCE, LIB_LIBC, ExternalFunction("floo")) private val IDENT_FUN_FOO = FUN_FOO.identifier private val IDENT_FUN_FLO = FUN_FLO.identifier } }
gpl-3.0
enolive/exercism
kotlin/saddle-points/src/main/kotlin/MatrixCoordinate.kt
3
56
data class MatrixCoordinate(val row: Int, val col: Int)
mit
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/feature/player/filter/selection/SelectFilterSongViewModel.kt
1
1176
package be.florien.anyflow.feature.player.filter.selection import be.florien.anyflow.data.DataRepository import be.florien.anyflow.data.local.model.DbSongDisplay import be.florien.anyflow.data.view.Filter import be.florien.anyflow.player.FiltersManager import javax.inject.Inject class SelectFilterSongViewModel @Inject constructor(val dataRepository: DataRepository, filtersManager: FiltersManager) : SelectFilterViewModel(filtersManager) { override val itemDisplayType = ITEM_LIST override fun getUnfilteredPagingList() = dataRepository.getSongs(::convert) override fun getFilteredPagingList(search: String) = dataRepository.getSongsFiltered(search, ::convert) override suspend fun getFoundFilters(search: String): List<FilterItem> = dataRepository.getSongsFilteredList(search, ::convert) override fun getFilter(filterValue: FilterItem) = Filter.SongIs(filterValue.id, filterValue.displayName, filterValue.artUrl) private fun convert(song: DbSongDisplay) = FilterItem(song.id, "${song.title}\nby ${song.artistName}\nfrom ${song.albumName}", song.art, filtersManager.isFilterInEdition(Filter.SongIs(song.id, song.title, song.art))) }
gpl-3.0
d9n/intellij-rust
src/main/kotlin/org/rust/lang/core/resolve/ref/RsLifetimeReferenceImpl.kt
1
904
package org.rust.lang.core.resolve.ref import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsLifetime import org.rust.lang.core.psi.ext.RsCompositeElement import org.rust.lang.core.resolve.collectCompletionVariants import org.rust.lang.core.resolve.collectResolveVariants import org.rust.lang.core.resolve.processLifetimeResolveVariants import org.rust.lang.core.types.BoundElement class RsLifetimeReferenceImpl( element: RsLifetime ) : RsReferenceBase<RsLifetime>(element), RsReference { override val RsLifetime.referenceAnchor: PsiElement get() = quoteIdentifier override fun resolveInner(): List<BoundElement<RsCompositeElement>> = collectResolveVariants(element.referenceName) { processLifetimeResolveVariants(element, it) } override fun getVariants(): Array<out Any> = collectCompletionVariants { processLifetimeResolveVariants(element, it) } }
mit
mockk/mockk
modules/mockk-dsl/src/jvmMain/kotlin/io/mockk/MockKSettings.kt
1
1457
package io.mockk import java.util.* actual object MockKSettings { private val properties = Properties() init { MockKSettings::class.java .getResourceAsStream("settings.properties") ?.use(properties::load) } private fun booleanProperty(property: String, defaultValue: String) = properties.getProperty( property, defaultValue )!!.toBoolean() actual val relaxed: Boolean get() = booleanProperty("relaxed", "false") actual val relaxUnitFun: Boolean get() = booleanProperty("relaxUnitFun", "false") actual val recordPrivateCalls: Boolean get() = booleanProperty("recordPrivateCalls", "false") actual val stackTracesOnVerify: Boolean get() = booleanProperty("stackTracesOnVerify", "true") actual val stackTracesAlignment: StackTracesAlignment get() = stackTracesAlignmentValueOf(properties.getProperty("stackTracesAlignment", "center")) fun setRelaxed(value: Boolean) { properties.setProperty("relaxed", value.toString()); } fun setRelaxUnitFun(value: Boolean) { properties.setProperty("relaxUnitFun", value.toString()); } fun setRecordPrivateCalls(value: Boolean) { properties.setProperty("recordPrivateCalls", value.toString()); } fun setStackTracesAlignment(value: String) { properties.setProperty("stackTracesAlignment", value) } }
apache-2.0
MaTriXy/RxBinding
rxbinding-material/src/main/java/com/jakewharton/rxbinding3/material/TabLayoutSelectionEventObservable.kt
2
2149
@file:JvmName("RxTabLayout") @file:JvmMultifileClass package com.jakewharton.rxbinding3.material import androidx.annotation.CheckResult import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayout.Tab import com.jakewharton.rxbinding3.internal.checkMainThread import io.reactivex.Observable import io.reactivex.Observer import io.reactivex.android.MainThreadDisposable /** * Create an observable which emits selection, reselection, and unselection events for the tabs * in `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* If a tab is already selected, an event will be emitted immediately on subscribe. */ @CheckResult fun TabLayout.selectionEvents(): Observable<TabLayoutSelectionEvent> { return TabLayoutSelectionEventObservable(this) } private class TabLayoutSelectionEventObservable( val view: TabLayout ) : Observable<TabLayoutSelectionEvent>() { override fun subscribeActual(observer: Observer<in TabLayoutSelectionEvent>) { if (!checkMainThread(observer)) { return } val listener = Listener(view, observer) observer.onSubscribe(listener) view.addOnTabSelectedListener(listener) val index = view.selectedTabPosition if (index != -1) { observer.onNext(TabLayoutSelectionSelectedEvent(view, view.getTabAt(index)!!)) } } private class Listener( private val view: TabLayout, private val observer: Observer<in TabLayoutSelectionEvent> ) : MainThreadDisposable(), TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: Tab) { if (!isDisposed) { observer.onNext(TabLayoutSelectionSelectedEvent(view, tab)) } } override fun onTabUnselected(tab: Tab) { if (!isDisposed) { observer.onNext(TabLayoutSelectionUnselectedEvent(view, tab)) } } override fun onTabReselected(tab: Tab) { if (!isDisposed) { observer.onNext(TabLayoutSelectionReselectedEvent(view, tab)) } } override fun onDispose() { view.removeOnTabSelectedListener(this) } } }
apache-2.0
mockk/mockk
modules/mockk/src/commonTest/kotlin/io/mockk/test/SkipInstrumentedAndroidTest.kt
2
68
package io.mockk.test annotation class SkipInstrumentedAndroidTest
apache-2.0
arturbosch/TiNBo
tinbo-time/src/main/kotlin/io/gitlab/arturbosch/tinbo/time/TimeDataHolder.kt
1
1317
package io.gitlab.arturbosch.tinbo.time import io.gitlab.arturbosch.tinbo.api.config.ConfigDefaults import io.gitlab.arturbosch.tinbo.api.config.Defaults import io.gitlab.arturbosch.tinbo.api.config.TinboConfig import io.gitlab.arturbosch.tinbo.api.model.AbstractDataHolder import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component /** * @author artur */ @Component open class TimeDataHolder @Autowired constructor(persister: TimePersister, private val config: TinboConfig) : AbstractDataHolder<TimeEntry, TimeData>(persister) { override val lastUsedData: String get() = config.getKey(ConfigDefaults.TIMERS) .getOrElse(ConfigDefaults.LAST_USED) { Defaults.TIME_NAME } override fun newData(name: String, entriesInMemory: List<TimeEntry>): TimeData { return TimeData(name, entriesInMemory) } override fun getEntriesFilteredBy(filter: String): List<TimeEntry> { return getEntries().filter { it.category == filter } } override fun changeCategory(oldName: String, newName: String) { val updatedEntries = getEntries().map { if (it.category.equals(oldName, ignoreCase = true)) { TimeEntry(newName, it.message, it.hours, it.minutes, it.seconds, it.date) } else { it } } saveData(data.name, updatedEntries) } }
apache-2.0
devmpv/chan-reactor
src/main/kotlin/com/devmpv/model/Thread.kt
1
544
package com.devmpv.model import javax.persistence.* /** * Thread entity based on [Message] * * @author devmpv */ @Entity class Thread( @ManyToOne @JoinColumn(name = "board_id", nullable = false) var board: Board? = null, title: String, text: String ) : Message(title, text) { @OneToMany(cascade = arrayOf(CascadeType.ALL), fetch = FetchType.LAZY, mappedBy = "thread", targetEntity = Message::class) var messages: MutableSet<Message> = HashSet() constructor() : this(null, "", "") }
mit
HedvigInsurance/bot-service
src/main/java/com/hedvig/botService/utils/BirthDateFromSSNUtil.kt
1
600
package com.hedvig.botService.utils import java.time.LocalDate object BirthDateFromSSNUtil { fun birthDateFromSSN(ssn: String): LocalDate { return LocalDate.parse( ssn.substring(0, 4) + "-" + ssn.substring(4, 6) + "-" + ssn.substring(6, 8) ) } fun addCenturyToSSN(ssn: String): String { val ssnYear = ssn.substring(0, 2).toInt() val breakePoint = LocalDate.now().minusYears(10).year.toString().substring(2, 4).toInt() return if (ssnYear > breakePoint) { "19$ssn" } else { "20$ssn" } } }
agpl-3.0
ojacquemart/spring-kotlin-euro-bets
src/test/kotlin/org/ojacquemart/eurobets/firebase/management/table/TableRowTest.kt
2
1139
package org.ojacquemart.eurobets.firebase.management.table import org.assertj.core.api.AssertionsForInterfaceTypes.assertThat import org.junit.Test class TableRowTest { val rows = listOf( // 30 points TableRow(bets = 10, points = 30, perfects = 0, goods = 10, bads = 0), TableRow(bets = 3, points = 30, perfects = 3, goods = 0, bads = 0), // 9 points TableRow(bets = 4, points = 9, perfects = 0, goods = 3, bads = 1), // 10 points TableRow(bets = 3, points = 10, perfects = 1, goods = 0, bads = 2), TableRow(bets = 4, points = 10, perfects = 1, goods = 0, bads = 3), // 0 point TableRow(bets = 0, points = 0, perfects = 0, goods = 0, bads = 0) ) @Test fun testGetPositionCoefficient() { val rowsPositions = TableRow.getPositions(rows) assertThat(rowsPositions).hasSize(4) assertThat(rowsPositions[0]).isEqualTo(30) assertThat(rowsPositions[1]).isEqualTo(10) assertThat(rowsPositions[2]).isEqualTo(9) assertThat(rowsPositions[3]).isEqualTo(0) } }
unlicense
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge3d/Shaders3D.kt
1
8923
package com.soywiz.korge3d import com.soywiz.korag.shader.* import com.soywiz.korag.shader.gl.* import com.soywiz.korge.internal.* @Korge3DExperimental open class Shaders3D { //@ThreadLocal private val programCache = LinkedHashMap<String, Program>() var printShaders = false @Suppress("RemoveCurlyBracesFromTemplate") fun getProgram3D(nlights: Int, nweights: Int, meshMaterial: Material3D?, hasTexture: Boolean): Program { return programCache.getOrPut("program_L${nlights}_W${nweights}_M${meshMaterial?.kind}_T${hasTexture}") { StandardShader3D(nlights, nweights, meshMaterial, hasTexture).program.apply { if (printShaders) { println(GlslGenerator(kind = ShaderType.VERTEX).generate(this.vertex.stm)) println(GlslGenerator(kind = ShaderType.FRAGMENT).generate(this.fragment.stm)) } } } } companion object { val u_Shininess = Uniform("u_shininess", VarType.Float1) val u_IndexOfRefraction = Uniform("u_indexOfRefraction", VarType.Float1) val u_AmbientColor = Uniform("u_ambientColor", VarType.Float4) val u_ProjMat = Uniform("u_ProjMat", VarType.Mat4) val u_ViewMat = Uniform("u_ViewMat", VarType.Mat4) val u_BindShapeMatrix = Uniform("u_BindShapeMat", VarType.Mat4) val u_BindShapeMatrixInv = Uniform("u_BindShapeMatInv", VarType.Mat4) val u_ModMat = Uniform("u_ModMat", VarType.Mat4) val u_NormMat = Uniform("u_NormMat", VarType.Mat4) //val MAX_BONE_MATS = 16 val MAX_BONE_MATS = 64 val u_BoneMats = Uniform("u_BoneMats", VarType.Mat4, arrayCount = MAX_BONE_MATS) val u_TexUnit = Uniform("u_TexUnit", VarType.TextureUnit) val a_pos = Attribute("a_Pos", VarType.Float3, normalized = false, precision = Precision.HIGH) val a_norm = Attribute("a_Norm", VarType.Float3, normalized = false, precision = Precision.HIGH) val a_tex = Attribute("a_TexCoords", VarType.Float2, normalized = false, precision = Precision.MEDIUM) val a_boneIndex = Array(4) { Attribute("a_BoneIndex$it", VarType.Float4, normalized = false) } val a_weight = Array(4) { Attribute("a_Weight$it", VarType.Float4, normalized = false) } val a_col = Attribute("a_Col", VarType.Float3, normalized = true) val v_col = Varying("v_Col", VarType.Float3) val v_Pos = Varying("v_Pos", VarType.Float3, precision = Precision.HIGH) val v_Norm = Varying("v_Norm", VarType.Float3, precision = Precision.HIGH) val v_TexCoords = Varying("v_TexCoords", VarType.Float2, precision = Precision.MEDIUM) val v_Temp1 = Varying("v_Temp1", VarType.Float4) val programColor3D = Program( vertex = VertexShader { SET(v_col, a_col) SET(out, u_ProjMat * u_ModMat * u_ViewMat * vec4(a_pos, 1f.lit)) }, fragment = FragmentShader { SET(out, vec4(v_col, 1f.lit)) //SET(out, vec4(1f.lit, 1f.lit, 1f.lit, 1f.lit)) }, name = "programColor3D" ) val lights = (0 until 4).map { LightAttributes(it) } val emission = MaterialLightUniform("emission") val ambient = MaterialLightUniform("ambient") val diffuse = MaterialLightUniform("diffuse") val specular = MaterialLightUniform("specular") val layoutPosCol = VertexLayout(a_pos, a_col) private val FLOATS_PER_VERTEX = layoutPosCol.totalSize / Int.SIZE_BYTES /*Float.SIZE_BYTES is not defined*/ } class LightAttributes(val id: Int) { val u_sourcePos = Uniform("light${id}_pos", VarType.Float3) val u_color = Uniform("light${id}_color", VarType.Float4) val u_attenuation = Uniform("light${id}_attenuation", VarType.Float3) } class MaterialLightUniform(val kind: String) { //val mat = Material3D val u_color = Uniform("u_${kind}_color", VarType.Float4) val u_texUnit = Uniform("u_${kind}_texUnit", VarType.TextureUnit) } } @Korge3DExperimental data class StandardShader3D( override val nlights: Int, override val nweights: Int, override val meshMaterial: Material3D?, override val hasTexture: Boolean ) : AbstractStandardShader3D() @Korge3DExperimental abstract class AbstractStandardShader3D() : BaseShader3D() { abstract val nlights: Int abstract val nweights: Int abstract val meshMaterial: Material3D? abstract val hasTexture: Boolean override fun Program.Builder.vertex() = Shaders3D.run { val modelViewMat = createTemp(VarType.Mat4) val normalMat = createTemp(VarType.Mat4) val boneMatrix = createTemp(VarType.Mat4) val localPos = createTemp(VarType.Float4) val localNorm = createTemp(VarType.Float4) val skinPos = createTemp(VarType.Float4) if (nweights == 0) { //SET(boneMatrix, mat4Identity()) SET(localPos, vec4(a_pos, 1f.lit)) SET(localNorm, vec4(a_norm, 0f.lit)) } else { SET(localPos, vec4(0f.lit)) SET(localNorm, vec4(0f.lit)) SET(skinPos, u_BindShapeMatrix * vec4(a_pos["xyz"], 1f.lit)) for (wIndex in 0 until nweights) { IF(getBoneIndex(wIndex) ge 0.lit) { SET(boneMatrix, getBone(wIndex)) SET(localPos, localPos + boneMatrix * vec4(skinPos["xyz"], 1f.lit) * getWeight(wIndex)) SET(localNorm, localNorm + boneMatrix * vec4(a_norm, 0f.lit) * getWeight(wIndex)) } } SET(localPos, u_BindShapeMatrixInv * localPos) } SET(modelViewMat, u_ModMat * u_ViewMat) SET(normalMat, u_NormMat) SET(v_Pos, vec3(modelViewMat * (vec4(localPos["xyz"], 1f.lit)))) SET(v_Norm, vec3(normalMat * normalize(vec4(localNorm["xyz"], 1f.lit)))) if (hasTexture) SET(v_TexCoords, a_tex["xy"]) SET(out, u_ProjMat * vec4(v_Pos, 1f.lit)) } override fun Program.Builder.fragment() { val meshMaterial = meshMaterial if (meshMaterial != null) { computeMaterialLightColor(out, Shaders3D.diffuse, meshMaterial.diffuse) } else { SET(out, vec4(.5f.lit, .5f.lit, .5f.lit, 1f.lit)) } for (n in 0 until nlights) { addLight(Shaders3D.lights[n], out) } //SET(out, vec4(v_Temp1.x, v_Temp1.y, v_Temp1.z, 1f.lit)) } open fun Program.Builder.computeMaterialLightColor(out: Operand, uniform: Shaders3D.MaterialLightUniform, light: Material3D.Light) { when (light) { is Material3D.LightColor -> { SET(out, uniform.u_color) } is Material3D.LightTexture -> { SET(out, vec4(texture2D(uniform.u_texUnit, Shaders3D.v_TexCoords["xy"])["rgb"], 1f.lit)) } else -> error("Unsupported MateriaList: $light") } } fun Program.Builder.mat4Identity() = Program.Func("mat4", 1f.lit, 0f.lit, 0f.lit, 0f.lit, 0f.lit, 1f.lit, 0f.lit, 0f.lit, 0f.lit, 0f.lit, 1f.lit, 0f.lit, 0f.lit, 0f.lit, 0f.lit, 1f.lit ) open fun Program.Builder.addLight(light: Shaders3D.LightAttributes, out: Operand) { val v = Shaders3D.v_Pos val N = Shaders3D.v_Norm val L = createTemp(VarType.Float3) val E = createTemp(VarType.Float3) val R = createTemp(VarType.Float3) val attenuation = createTemp(VarType.Float1) val dist = createTemp(VarType.Float1) val NdotL = createTemp(VarType.Float1) val lightDir = createTemp(VarType.Float3) SET(L, normalize(light.u_sourcePos["xyz"] - v)) SET(E, normalize(-v)) // we are in Eye Coordinates, so EyePos is (0,0,0) SET(R, normalize(-reflect(L, N))) val constantAttenuation = light.u_attenuation.x val linearAttenuation = light.u_attenuation.y val quadraticAttenuation = light.u_attenuation.z SET(lightDir, light.u_sourcePos["xyz"] - Shaders3D.v_Pos) SET(dist, length(lightDir)) //SET(dist, length(vec3(4f.lit, 1f.lit, 6f.lit) - vec3(0f.lit, 0f.lit, 0f.lit))) SET(attenuation, 1f.lit / (constantAttenuation + linearAttenuation * dist + quadraticAttenuation * dist * dist)) //SET(attenuation, 1f.lit / (1f.lit + 0f.lit * dist + 0.00111109f.lit * dist * dist)) //SET(attenuation, 0.9.lit) SET(NdotL, max(dot(normalize(N), normalize(lightDir)), 0f.lit)) IF(NdotL ge 0f.lit) { SET(out["rgb"], out["rgb"] + (light.u_color["rgb"] * NdotL + Shaders3D.u_AmbientColor["rgb"]) * attenuation * Shaders3D.u_Shininess) } //SET(out["rgb"], out["rgb"] * attenuation) //SET(out["rgb"], out["rgb"] + clamp(light.diffuse * max(dot(N, L), 0f.lit), 0f.lit, 1f.lit)["rgb"]) //SET(out["rgb"], out["rgb"] + clamp(light.specular * pow(max(dot(R, E), 0f.lit), 0.3f.lit * u_Shininess), 0f.lit, 1f.lit)["rgb"]) } fun Program.Builder.getBoneIndex(index: Int): Operand = int(Shaders3D.a_boneIndex[index / 4][index % 4]) fun Program.Builder.getWeight(index: Int): Operand = Shaders3D.a_weight[index / 4][index % 4] fun Program.Builder.getBone(index: Int): Operand = Shaders3D.u_BoneMats[getBoneIndex(index)] } @Korge3DExperimental abstract class BaseShader3D { abstract fun Program.Builder.vertex() abstract fun Program.Builder.fragment() val program by lazy { Program( vertex = VertexShader { vertex() }, fragment = FragmentShader { fragment() }, name = [email protected]() ) } } private fun Program.Builder.transpose(a: Operand) = Program.Func("transpose", a) private fun Program.Builder.inverse(a: Operand) = Program.Func("inverse", a) private fun Program.Builder.int(a: Operand) = Program.Func("int", a) private operator fun Operand.get(index: Operand) = Program.ArrayAccess(this, index)
apache-2.0
pr0ves/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/util/pokemon/CatchablePokemon.kt
2
7008
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.util.pokemon import POGOProtos.Data.Capture.CaptureProbabilityOuterClass.CaptureProbability import POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId import POGOProtos.Networking.Responses.CatchPokemonResponseOuterClass.CatchPokemonResponse.CatchStatus import ink.abb.pogo.api.cache.Inventory import ink.abb.pogo.api.cache.MapPokemon import ink.abb.pogo.api.request.CatchPokemon import ink.abb.pogo.api.request.UseItemCapture import ink.abb.pogo.scraper.util.Log import java.util.concurrent.atomic.AtomicInteger /** * Extension function to make the code more readable in the CatchOneNearbyPokemon task */ fun MapPokemon.catch(normalizedHitPosition: Double = 1.0, normalizedReticleSize: Double = 1.95 + Math.random() * 0.05, spinModifier: Double = 0.85 + Math.random() * 0.15, ballType: ItemId = ItemId.ITEM_POKE_BALL): rx.Observable<CatchPokemon> { return poGoApi.queueRequest(CatchPokemon() .withEncounterId(encounterId) .withHitPokemon(true) .withNormalizedHitPosition(normalizedHitPosition) .withNormalizedReticleSize(normalizedReticleSize) .withPokeball(ballType) .withSpinModifier(spinModifier) .withSpawnPointId(spawnPointId)) } fun MapPokemon.catch(captureProbability: CaptureProbability, inventory: Inventory, desiredCatchProbability: Double, alwaysCurve: Boolean = false, allowBerries: Boolean = false, randomBallThrows: Boolean = false, waitBetweenThrows: Boolean = false, amount: Int): rx.Observable<CatchPokemon> { var catch: rx.Observable<CatchPokemon> var numThrows = 0 do { catch = catch(captureProbability, inventory, desiredCatchProbability, alwaysCurve, allowBerries, randomBallThrows) val first = catch.toBlocking().first() if (first != null) { val result = first.response if (result.status != CatchStatus.CATCH_ESCAPE && result.status != CatchStatus.CATCH_MISSED) { break } if (waitBetweenThrows) { val waitTime = (Math.random() * 2900 + 100) Log.blue("Pokemon got out of the ball. Waiting for ca. ${Math.round(waitTime / 1000)} second(s) until next throw") Thread.sleep(waitTime.toLong()) } numThrows++ } } while (amount < 0 || numThrows < amount) return catch } fun MapPokemon.catch(captureProbability: CaptureProbability, inventory: Inventory, desiredCatchProbability: Double, alwaysCurve: Boolean = false, allowBerries: Boolean = false, randomBallThrows: Boolean = false): rx.Observable<CatchPokemon> { val ballTypes = captureProbability.pokeballTypeList val probabilities = captureProbability.captureProbabilityList //Log.yellow(probabilities.toString()) var ball: ItemId? = null var needCurve = alwaysCurve var needRazzBerry = false var highestAvailable: ItemId? = null var catchProbability = 0f for ((index, ballType) in ballTypes.withIndex()) { val probability = probabilities.get(index) val ballAmount = inventory.items.getOrPut(ballType, { AtomicInteger(0) }).get() if (ballAmount == 0) { //Log.yellow("Don't have any ${ballType}") continue } else { //Log.yellow("Have ${ballAmount} of ${ballType}") highestAvailable = ballType catchProbability = probability } if (probability >= desiredCatchProbability) { catchProbability = probability ball = ballType break } else if (probability >= desiredCatchProbability - 0.1) { ball = ballType needCurve = true catchProbability = probability + 0.1f break } else if (probability >= desiredCatchProbability - 0.2) { ball = ballType needCurve = true needRazzBerry = true catchProbability = probability + 0.2f break } } if (highestAvailable == null) { /*Log.red("No pokeballs?!") Log.red("Has pokeballs: ${itemBag.hasPokeballs()}")*/ return rx.Observable.just(null) } if (ball == null) { ball = highestAvailable needCurve = true needRazzBerry = true catchProbability += 0.2f } var logMessage = "Using ${ball.name}" val razzBerryCount = inventory.items.getOrPut(ItemId.ITEM_RAZZ_BERRY, { AtomicInteger(0) }).get() if (allowBerries && razzBerryCount > 0 && needRazzBerry) { logMessage += "; Using Razz Berry" poGoApi.queueRequest(UseItemCapture().withEncounterId(encounterId).withItemId(ItemId.ITEM_RAZZ_BERRY).withSpawnPointId(spawnPointId)).toBlocking() } if (needCurve) { logMessage += "; Using curve" } logMessage += "; achieved catch probability: ${Math.round(catchProbability * 100.0)}%, desired: ${Math.round(desiredCatchProbability * 100.0)}%" Log.yellow(logMessage) //excellent throw value var recticleSize = 1.7 + Math.random() * 0.3 if (randomBallThrows) { //excellent throw if capture probability is still less then desired if (catchProbability <= desiredCatchProbability) { // the recticle size is already set for an excelent throw } //if catch probability is too high... else { // we substract the difference from the recticle size, the lower this size, the worse the ball recticleSize = 1 + Math.random() - (catchProbability - desiredCatchProbability) * 0.5 if (recticleSize > 2) { recticleSize = 2.0 } else if (recticleSize < 0) { recticleSize = 0.01 } if (recticleSize < 1) { Log.blue("Your trainer threw a normal ball, no xp/catching bonus, good for pretending to be not a bot however") } else if (recticleSize >= 1 && recticleSize < 1.3) { Log.blue("Your trainer got a 'Nice throw' - nice") } else if (recticleSize >= 1.3 && recticleSize < 1.7) { Log.blue("Your trainer got a 'Great throw!'") } else if (recticleSize > 1.7) { Log.blue("Your trainer got an 'Excellent throw!' - that's suspicious, might he be a bot?") } } } return catch( normalizedHitPosition = 1.0, normalizedReticleSize = recticleSize, spinModifier = if (needCurve) 0.85 + Math.random() * 0.15 else Math.random() * 0.10, ballType = ball ) }
gpl-3.0