repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
apollostack/apollo-android
apollo-runtime/src/main/java/com/apollographql/apollo3/http/OkHttpExecutionContext.kt
1
930
package com.apollographql.apollo3.http import com.apollographql.apollo3.api.ExecutionContext import com.apollographql.apollo3.api.ResponseContext import okhttp3.Response /** * Http GraphQL execution context, provides access to the raw {@link okhttp3.Response} response. */ class OkHttpExecutionContext( response: Response ) : ResponseContext(OkHttpExecutionContext) { companion object Key : ExecutionContext.Key<OkHttpExecutionContext> val response: Response = response.strip() private fun Response.strip(): Response { val builder = newBuilder() if (body() != null) { builder.body(null) } val cacheResponse = cacheResponse() if (cacheResponse != null) { builder.cacheResponse(cacheResponse.strip()) } val networkResponse = networkResponse() if (networkResponse != null) { builder.networkResponse(networkResponse.strip()) } return builder.build() } }
mit
f94c86657ca5b791bbea8789d17024db
24.833333
96
0.723656
4.536585
false
false
false
false
jmonad/kaybe
kaybe/src/main/java/com/jmonad/kaybe/Nothing.kt
1
383
package com.jmonad.kaybe class Nothing<A> : IMaybe<A> { override fun <B> bind(fn: (a : A) -> B): IMaybe<B> = Nothing() override fun fromJust(): A = throw RuntimeException("Cannot call fromJust() on Nothing") override fun fromMaybe(def: A) : A = def override fun isJust() = false override fun isNothing() = true override fun <B> maybe(def: B, fn: (a : A) -> B): B = def }
mit
c4a93d64448d5c0c9d34d6d7a65f6c8b
37.4
90
0.64752
3.08871
false
false
false
false
SirLYC/Android-Gank-Share
app/src/main/java/com/lyc/gank/category/CategoryFragment.kt
1
1422
package com.lyc.gank.category import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.lyc.data.types import com.lyc.gank.R import com.lyc.gank.base.BaseFragment import kotlinx.android.synthetic.main.fragment_category.* /** * Created by Liu Yuchuan on 2018/2/23. */ class CategoryFragment : BaseFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_category, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { vp_category.adapter = CategoryPagerAdapter(childFragmentManager) vp_category.offscreenPageLimit = 7 tab_category.setupWithViewPager(vp_category) } private class CategoryPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { private val fragments = arrayOfNulls<SingleContentFragment>(types.size) override fun getItem(position: Int): Fragment { return fragments[position] ?: SingleContentFragment.instance(types[position]) } override fun getCount() = fragments.size override fun getPageTitle(position: Int) = types[position] } }
apache-2.0
24c0ef72785c3335fb3bf0656db3ccf6
33.682927
116
0.748945
4.471698
false
false
false
false
exponentjs/exponent
android/expoview/src/main/java/host/exp/exponent/experience/splashscreen/ManagedAppSplashScreenViewController.kt
2
2223
package host.exp.exponent.experience.splashscreen import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Handler import android.view.View import android.view.ViewGroup import com.google.android.material.snackbar.Snackbar import expo.modules.splashscreen.BuildConfig import expo.modules.splashscreen.SplashScreenViewController class ManagedAppSplashScreenViewController( activity: Activity, rootView: Class<out ViewGroup>, private val splashScreenView: View ) : SplashScreenViewController(activity, rootView, splashScreenView) { private val mWarningHandler = Handler() private var mSnackbar: Snackbar? = null private var mRunnable: Runnable? = null fun startSplashScreenWarningTimer() { if (BuildConfig.DEBUG) { mRunnable = Runnable { // this runnable is being executed after the parent view has been destroyed, causing a crash // an easy way to trigger this is to toggle the debug JS option in the dev menu // this causes the whole app to remount, I suspect this is why the timer isn't cleaned up // TODO: cancel runnable when app is unmounted / reloaded if (splashScreenView?.parent != null) { mSnackbar = Snackbar.make(splashScreenView, "Stuck on splash screen?", Snackbar.LENGTH_LONG) mSnackbar!!.setAction( "Info", View.OnClickListener { v -> val url = "https://expo.fyi/splash-screen-hanging" val webpage = Uri.parse(url) val intent = Intent(Intent.ACTION_VIEW, webpage) v.context.startActivity(intent) mSnackbar!!.dismiss() } ) mSnackbar!!.show() } } mWarningHandler.postDelayed(mRunnable!!, 20000) } } override fun showSplashScreen(successCallback: () -> Unit) { super.showSplashScreen { successCallback() } } override fun hideSplashScreen(successCallback: (hasEffect: Boolean) -> Unit, failureCallback: (reason: String) -> Unit) { super.hideSplashScreen( { mRunnable?.let { it1 -> mWarningHandler.removeCallbacks(it1) } successCallback(it) }, failureCallback ) } }
bsd-3-clause
0038a3d944de1090a7b38534a498e3b5
33.734375
123
0.680162
4.650628
false
false
false
false
maiconhellmann/pomodoro
app/src/main/kotlin/br/com/maiconhellmann/pomodoro/util/extension/MaskExtension.kt
1
3213
package br.com.maiconhellmann.pomodoro.util.extension import android.support.annotation.StringDef import android.text.Editable import android.text.TextWatcher import android.widget.EditText /** * Source: https://andremrezende.wordpress.com/tag/android-mask-mascara-edittext-java-layout-cpf-cnpj/ */ @StringDef(PHONE_9_MASK, PHONE_8_MASK, CPF_MASK, ZIP_CODE_PT_BR, MONTH_YEAR, CREDIT_CARD) @Retention(AnnotationRetention.SOURCE) annotation class MaskType const val PHONE_9_MASK = "(##) #####-####" const val PHONE_8_MASK = "(##) ####-####" const val CPF_MASK = "###.###.###-##" const val ZIP_CODE_PT_BR = "#####-###" const val MONTH_YEAR = "##/##" const val CREDIT_CARD = "#### #### #### ####" fun String.unmask(): String { return replace("[\\./\\(\\) \\-\\+]".toRegex(), "") } @Suppress("UNUSED") fun EditText.insert(@MaskType mask: String): TextWatcher { val textWatcher = MaskTextWatcher(mask) addTextChangedListener(textWatcher) return textWatcher } fun EditText.insertPhoneMask(): TextWatcher { val textWatcher = object : MaskTextWatcher() { override fun getMask(unmaskedValue: String): String { if (unmaskedValue.length < 11) { return PHONE_8_MASK } return PHONE_9_MASK } } addTextChangedListener(textWatcher) return textWatcher } fun String.formatPhone(): String { var _phone = this if (length == 8) _phone = String.format("%s-%s", substring(0, 4), substring(4, length)) else if (length == 9) _phone = String.format("%s-%s", substring(0, 5), substring(5, length)) else if (length == 10) _phone = String.format("%s %s-%s", substring(0, 2), substring(2, 6), substring(6, length)) else if (length == 11) _phone = String.format("%s %s-%s", substring(0, 2), substring(2, 7), substring(7, length)) return _phone } open class MaskTextWatcher(val mask: String = ""): SimpleTextWatcher() { internal var oldValue = "" internal var isUpdating: Boolean = false open fun getMask(unmaskedValue: String): String { return mask } override fun afterTextChanged(edit: Editable) { val unmaskedString = edit.toString().unmask() val maskedString = StringBuilder("") val mask = getMask(unmaskedString) // EditText was GC'ed if (isUpdating) { oldValue = unmaskedString isUpdating = false return } var i = 0 for (m in mask.toCharArray()) { if (m != '#' && i < unmaskedString.length) { maskedString.append(m) continue } try { maskedString.append(unmaskedString[i]) } catch (e: Exception) { break } i++ } isUpdating = true edit.replace(0, edit.length, maskedString) } } open class SimpleTextWatcher : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } override fun afterTextChanged(edit: Editable) { } }
apache-2.0
53ad6aad840a67ff5d1719e4608109ad
25.561983
102
0.599751
3.966667
false
false
false
false
hurricup/intellij-community
platform/projectModel-api/src/com/intellij/openapi/options/scheme.kt
1
2678
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.options import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.WriteExternalException import org.jdom.Parent interface ExternalizableScheme : Scheme { fun setName(value: String) } abstract class SchemeManagerFactory { companion object { @JvmStatic fun getInstance() = ServiceManager.getService(SchemeManagerFactory::class.java)!! @JvmStatic fun getInstance(project: Project) = ServiceManager.getService(project, SchemeManagerFactory::class.java)!! } /** * directoryName — like "keymaps". */ @JvmOverloads fun <SCHEME : Scheme, MUTABLE_SCHEME: SCHEME> create(directoryName: String, processor: SchemeProcessor<SCHEME, MUTABLE_SCHEME>, presentableName: String? = null, isUseOldFileNameSanitize: Boolean = false): SchemeManager<SCHEME> = create(directoryName, processor, presentableName, RoamingType.DEFAULT, isUseOldFileNameSanitize) protected abstract fun <SCHEME : Scheme, MUTABLE_SCHEME: SCHEME> create(directoryName: String, processor: SchemeProcessor<SCHEME, MUTABLE_SCHEME>, presentableName: String? = null, roamingType: RoamingType = RoamingType.DEFAULT, isUseOldFileNameSanitize: Boolean = false): SchemeManager<SCHEME> } enum class SchemeState { UNCHANGED, NON_PERSISTENT, POSSIBLY_CHANGED } abstract class SchemeProcessor<SCHEME : Scheme, in MUTABLE_SCHEME: SCHEME> { open fun isExternalizable(scheme: SCHEME) = scheme is ExternalizableScheme /** * Element will not be modified, it is safe to return non-cloned instance. */ @Throws(WriteExternalException::class) abstract fun writeScheme(scheme: MUTABLE_SCHEME): Parent open fun initScheme(scheme: MUTABLE_SCHEME) { } open fun onSchemeAdded(scheme: MUTABLE_SCHEME) { } open fun onSchemeDeleted(scheme: MUTABLE_SCHEME) { } open fun onCurrentSchemeSwitched(oldScheme: SCHEME?, newScheme: SCHEME?) { } open fun getState(scheme: SCHEME): SchemeState = SchemeState.POSSIBLY_CHANGED }
apache-2.0
56d30db6745f051ef9eaac20b48b4bde
36.180556
327
0.767564
4.574359
false
false
false
false
hurricup/intellij-community
plugins/settings-repository/testSrc/RespositoryHelper.kt
1
1956
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.test import com.intellij.util.exists import com.intellij.util.isFile import gnu.trove.THashSet import org.assertj.core.api.Assertions.assertThat import org.eclipse.jgit.lib.Constants import java.nio.file.Files import java.nio.file.Path private fun getChildrenStream(path: Path, excludes: Array<out String>? = null) = Files.list(path) .filter { !it.endsWith(Constants.DOT_GIT) && (excludes == null || !excludes.contains(it.fileName.toString())) } .sorted() fun compareFiles(path1: Path, path2: Path, vararg localExcludes: String) { assertThat(path1).isDirectory() assertThat(path2).isDirectory() val notFound = THashSet<Path>() for (path in getChildrenStream(path1, localExcludes)) { notFound.add(path) } for (child2 in getChildrenStream(path2)) { val childName = child2.fileName.toString() val child1 = path1.resolve(childName) if (child1.isFile()) { assertThat(child2).hasSameContentAs(child1) } else if (!child1.exists()) { throw AssertionError("Path '$path2' must not contain '$childName'") } else { compareFiles(child1, child2, *localExcludes) } notFound.remove(child1) } if (notFound.isNotEmpty()) { throw AssertionError("Path '$path2' must contain ${notFound.joinToString { "'${it.toString().substring(1)}'" }}.") } }
apache-2.0
5a23a1df011b1d76515de4dd96c6d1a5
33.333333
119
0.719325
3.812865
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/compiler-plugins/allopen/gradle/src/org/jetbrains/kotlin/idea/compilerPlugin/allopen/gradleJava/AllOpenGradleProjectImportHandler.kt
3
1548
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.compilerPlugin.allopen.gradleJava import org.jetbrains.kotlin.allopen.AllOpenPluginNames.ANNOTATION_OPTION_NAME import org.jetbrains.kotlin.allopen.AllOpenPluginNames.PLUGIN_ID import org.jetbrains.kotlin.allopen.AllOpenPluginNames.SUPPORTED_PRESETS import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath import org.jetbrains.kotlin.idea.gradleJava.compilerPlugin.AbstractAnnotationBasedCompilerPluginGradleImportHandler import org.jetbrains.kotlin.idea.gradleTooling.model.allopen.AllOpenModel class AllOpenGradleProjectImportHandler : AbstractAnnotationBasedCompilerPluginGradleImportHandler<AllOpenModel>() { override val compilerPluginId = PLUGIN_ID override val pluginName = "allopen" override val annotationOptionName = ANNOTATION_OPTION_NAME override val pluginJarFileFromIdea = KotlinArtifacts.allopenCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath() override val modelKey = AllOpenProjectResolverExtension.KEY override fun getAnnotationsForPreset(presetName: String): List<String> { for ((name, annotations) in SUPPORTED_PRESETS.entries) { if (presetName == name) { return annotations } } return super.getAnnotationsForPreset(presetName) } }
apache-2.0
694cac7d20f57b5dc41d4161753fc4fa
52.37931
158
0.80491
5.283276
false
false
false
false
PolymerLabs/arcs
java/arcs/android/storage/ProxyMessageProto.kt
1
2101
package arcs.android.storage import arcs.android.crdt.toData import arcs.android.crdt.toOperation import arcs.android.crdt.toProto import arcs.android.util.decodeProto import arcs.core.crdt.CrdtData import arcs.core.crdt.CrdtOperation import arcs.core.storage.ProxyMessage import com.google.protobuf.Int32Value /** Constructs a [ProxyMessage] from the given [ProxyMessageProto]. */ fun ProxyMessageProto.decode(): ProxyMessage<CrdtData, CrdtOperation, Any?> { // Convert Int32Value to nullable Int. val id = if (hasId()) id.value else null return when (messageCase) { ProxyMessageProto.MessageCase.SYNC_REQUEST -> ProxyMessage.SyncRequest( id = id ) ProxyMessageProto.MessageCase.MODEL_UPDATE -> ProxyMessage.ModelUpdate( id = id, model = modelUpdate.data.toData() ) ProxyMessageProto.MessageCase.OPERATIONS -> ProxyMessage.Operations( id = id, operations = operations.operationsList.map { it.toOperation() } ) ProxyMessageProto.MessageCase.MESSAGE_NOT_SET, null -> throw UnsupportedOperationException( "Unknown ProxyMessage type: $messageCase." ) } } /** Serializes a [ProxyMessage] to its proto form. */ fun ProxyMessage<*, *, *>.toProto(): ProxyMessageProto { val proto = ProxyMessageProto.newBuilder() // Convert nullable Int to Int32Value. id?.let { proto.setId(Int32Value.of(it)) } when (this) { is ProxyMessage.SyncRequest -> { proto.syncRequest = ProxyMessageProto.SyncRequest.getDefaultInstance() } is ProxyMessage.ModelUpdate -> { proto.modelUpdate = ProxyMessageProto.ModelUpdate.newBuilder() .setData(model.toProto()) .build() } is ProxyMessage.Operations -> { proto.operations = ProxyMessageProto.Operations.newBuilder() .addAllOperations(operations.map { it.toProto() }) .build() } } return proto.build() } /** Decodes a [ProxyMessage] from the [ByteArray]. */ fun ByteArray.decodeProxyMessage(): ProxyMessage<CrdtData, CrdtOperation, Any?> { return decodeProto(this, ProxyMessageProto.getDefaultInstance()).decode() }
bsd-3-clause
677c00dbbbcf4bbe1c4dae84ffbee407
34.016667
95
0.719181
4.386221
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/scroll/MotionScrollLastScreenLinePageStartAction.kt
1
2296
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.motion.scroll import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.normalizeLine import com.maddyhome.idea.vim.api.normalizeVisualLine import com.maddyhome.idea.vim.api.visualLineToBufferLine import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.VimActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* class MotionScrollLastScreenLinePageStartAction : VimActionHandler.SingleExecution() { override val type: Command.Type = Command.Type.OTHER_READONLY override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_IGNORE_SCROLL_JUMP) override fun execute( editor: VimEditor, context: ExecutionContext, cmd: Command, operatorArguments: OperatorArguments, ): Boolean { val motion = injector.motion // Without [count]: Redraw with the line just above the window at the bottom of the window. Put the cursor in that // line, at the first non-blank in the line. if (cmd.rawCount == 0) { val prevVisualLine = editor.normalizeVisualLine(injector.engineEditorHelper.getVisualLineAtTopOfScreen(editor) - 1) val bufferLine = editor.visualLineToBufferLine(prevVisualLine) return motion.scrollCurrentLineToDisplayBottom(editor, bufferLine + 1, true) } // [count]z^ first scrolls [count] to the bottom of the window, then moves the caret to the line that is now at // the top, and then move that line to the bottom of the window var bufferLine = editor.normalizeLine(cmd.rawCount - 1) if (motion.scrollCurrentLineToDisplayBottom(editor, bufferLine + 1, false)) { bufferLine = editor.visualLineToBufferLine(injector.engineEditorHelper.getVisualLineAtTopOfScreen(editor)) return motion.scrollCurrentLineToDisplayBottom(editor, bufferLine + 1, true) } return false } }
mit
0e7a1f376d96bf98e6386767332306cd
41.518519
121
0.772648
4.182149
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/TextAreaBuilder.kt
1
1345
package org.hexworks.zircon.api.builder.component import org.hexworks.zircon.api.component.TextArea import org.hexworks.zircon.api.component.builder.base.BaseComponentBuilder import org.hexworks.zircon.api.component.builder.base.ComponentWithTextBuilder import org.hexworks.zircon.internal.component.impl.DefaultTextArea import org.hexworks.zircon.internal.component.renderer.DefaultTextAreaRenderer import org.hexworks.zircon.internal.dsl.ZirconDsl import kotlin.jvm.JvmStatic @Suppress("UNCHECKED_CAST") @ZirconDsl class TextAreaBuilder private constructor() : BaseComponentBuilder<TextArea, TextAreaBuilder>( initialRenderer = DefaultTextAreaRenderer(), ) { var text: String = "" /** * Sets the [text] for the component that is being built and returns the builder. */ @Suppress("UNCHECKED_CAST") fun withText(text: String) = also { this.text = text } override fun build(): TextArea { return DefaultTextArea( componentMetadata = createMetadata(), renderingStrategy = createRenderingStrategy(), initialText = text, ).attachListeners() } override fun createCopy() = newBuilder() .withProps(props.copy()) .withText(text) companion object { @JvmStatic fun newBuilder() = TextAreaBuilder() } }
apache-2.0
b154b659bd033f5c888bc00c53146d95
29.568182
94
0.713755
4.686411
false
false
false
false
brianegan/bansa
examples/listOfTrendingGifs/src/main/kotlin/com/brianegan/bansa/listOfTrendingGifs/ui/gifView.kt
1
930
package com.brianegan.bansa.listOfTrendingGifs.ui import com.brianegan.bansa.listOfTrendingGifs.models.Gif import com.brianegan.bansa.listOfTrendingGifs.ui.utils.src import trikita.anvil.DSL.imageView import trikita.anvil.DSL.size fun gifView(model: Gif) { val (url, width, height) = model val deviceMetrics = com.brianegan.bansa.listOfTrendingGifs.ui.measureDevice(trikita.anvil.Anvil.currentView<android.view.View>().context) val widthRatio = deviceMetrics.x.toFloat().div(width) imageView { size(deviceMetrics.x, height.toFloat().times(widthRatio).toInt()) src(url) } } private fun measureDevice(context: android.content.Context): android.graphics.Point { val wm = context.getSystemService(android.content.Context.WINDOW_SERVICE) as android.view.WindowManager val display = wm.defaultDisplay val point = android.graphics.Point() display.getSize(point) return point }
mit
2c55eba973ed9c201a03c965e339555b
36.2
141
0.760215
3.957447
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/androidTest/java/org/wordpress/android/util/StatsMocksReader.kt
1
3100
package org.wordpress.android.util import androidx.test.platform.app.InstrumentationRegistry import org.json.JSONObject import java.util.ArrayList class StatsMocksReader { private fun readDayStatsGenericFile(fileName: String, lastObjectName: String, keyName: String, valueName: String): MutableList<StatsKeyValueData> { val todayMarker = "{{now format='yyyy-MM-dd'}}" val readString = this.readAssetsFile("mocks/mappings/wpcom/stats/$fileName.json") val wireMockJSON = JSONObject(readString) val arrayRaw = wireMockJSON .getJSONObject("response") .getJSONObject("jsonBody") .getJSONObject("days") .getJSONObject(todayMarker) .getJSONArray(lastObjectName) val listStripped: MutableList<StatsKeyValueData> = ArrayList<StatsKeyValueData>() for (i in 0 until arrayRaw.length()) { val item: JSONObject = arrayRaw.optJSONObject(i) listStripped.add( StatsKeyValueData( item.optString(keyName), item.optString(valueName) ) ) } return listStripped } fun readDayTopPostsToList(): MutableList<StatsKeyValueData> { return readDayStatsGenericFile( "stats_top-posts-day", "postviews", "title", "views" ) } fun readDayTopReferrersToList(): MutableList<StatsKeyValueData> { return readDayStatsGenericFile( "stats_referrers-day", "groups", "name", "total" ) } fun readDayClicksToList(): MutableList<StatsKeyValueData> { return readDayStatsGenericFile( "stats_clicks-day", "clicks", "name", "views" ) } fun readDayAuthorsToList(): MutableList<StatsKeyValueData> { return readDayStatsGenericFile( "stats_top-authors-day", "authors", "name", "views" ) } fun readDayCountriesToList(): MutableList<StatsKeyValueData> { val countriesList = readDayStatsGenericFile( "stats_country-views-day", "views", "country_code", "views" ) // We need to translate the country code (e.g. "DE") from json // to a full country name (e.g. "Germany") for (item in countriesList) { item.key = countriesMap[item.key].toString() } return countriesList } fun readDayVideoPlaysToList(): MutableList<StatsKeyValueData> { return readDayStatsGenericFile( "stats_video-plays-day", "plays", "title", "plays" ) } fun readDayFileDownloadsToList(): MutableList<StatsKeyValueData> { return readDayStatsGenericFile( "stats_file-downloads-day", "files", "filename", "downloads" ) } private fun readAssetsFile(fileName: String): String { val appContext = InstrumentationRegistry.getInstrumentation().context return appContext.assets.open(fileName).bufferedReader().use { it.readText() } } }
gpl-2.0
82fcd6225452d86b423c7fa48056d0c8
33.831461
118
0.614839
5.04886
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/posts/editor/PostEditorAnalyticsSessionTest.kt
1
2607
package org.wordpress.android.ui.posts.editor import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatcher import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argThat import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.ui.posts.PostEditorAnalyticsSession import org.wordpress.android.ui.posts.PostEditorAnalyticsSession.Editor.GUTENBERG import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper @RunWith(MockitoJUnitRunner::class) class PostEditorAnalyticsSessionTest { @Test fun `verify editor_session events have blog_id field`() { // Arrange val analyticsTracker = mock<AnalyticsTrackerWrapper>() val postEditorAnalyticsSession = createPostEditorAnalyticsSessionTracker(analyticsTracker) // trigger all the editor_session events postEditorAnalyticsSession.start(null, true, null) postEditorAnalyticsSession.end() postEditorAnalyticsSession.switchEditor(GUTENBERG) postEditorAnalyticsSession.applyTemplate("Just a template name") // verify that all invocations have the blog_id entry verify(analyticsTracker, times(4)) .track(anyOrNull(), argThat(MapHasEntry("blog_id" to blogId))) } internal class MapHasEntry(val entry: Pair<*, *>) : ArgumentMatcher<Map<String, Any?>> { override fun matches(map: Map<String, Any?>): Boolean { return map.containsKey(entry.first) && map.get(entry.first) == entry.second } override fun toString(): String { // to print when verification fails return "[Map containing a (\"${entry.first}\", ${entry.second}L) pair]" } } private companion object Fixtures { private const val blogId = 1234L fun createPostEditorAnalyticsSessionTracker( analyticsTrackerWrapper: AnalyticsTrackerWrapper = mock() ): PostEditorAnalyticsSession { val site = mock<SiteModel>() whenever(site.origin).thenReturn(SiteModel.ORIGIN_WPCOM_REST) whenever(site.siteId).thenReturn(blogId) site.getSiteId() return PostEditorAnalyticsSession.getNewPostEditorAnalyticsSession( GUTENBERG, mock(), site, false, analyticsTrackerWrapper ) } } }
gpl-2.0
a59596806cd46accdf48844dd5ba02c1
37.910448
98
0.688147
5.152174
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/posts/editor/ImageEditorFileUtilsTest.kt
1
1964
package org.wordpress.android.ui.posts.editor import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.wordpress.android.test import java.io.File private const val TEST_OUTPUT_FOLDER = "outputFolder" private const val TEST_OUTPUT_FILE_NAME = "outputFile" private const val DURATION = 24 * 60 * 60 * 1000.toLong() class ImageEditorFileUtilsTest { @Rule @JvmField val temporaryFolder = TemporaryFolder() // Class under test private lateinit var fileUtils: ImageEditorFileUtils @Before fun setUp() { fileUtils = ImageEditorFileUtils() } @Test fun `if file inside directory is modified within given duration, it is not deleted`() { // Arrange val directory: File = temporaryFolder.newFolder(TEST_OUTPUT_FOLDER) val directoryPath: String = directory.path val outputFile = File(directory, TEST_OUTPUT_FILE_NAME) outputFile.createNewFile() // Act test { fileUtils.deleteFilesOlderThanDurationFromDirectory(directoryPath, DURATION) } // Assert assertThat(outputFile.exists()).isTrue() } @Test fun `if file inside directory is modified on or after given duration, it is deleted`() { // Arrange val directory: File = temporaryFolder.newFolder(TEST_OUTPUT_FOLDER) val directoryPath: String = directory.path val outputFile = File(directory, TEST_OUTPUT_FILE_NAME) outputFile.createNewFile() outputFile.setLastModified(System.currentTimeMillis() - DURATION) // Act test { fileUtils.deleteFilesOlderThanDurationFromDirectory(directoryPath, DURATION) } // Assert assertThat(outputFile.exists()).isFalse() } @After fun tearDown() { temporaryFolder.delete() } }
gpl-2.0
f5858ff99ce9b3e4033643864929f71d
27.882353
92
0.680754
4.778589
false
true
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustPathPartImplMixin.kt
1
2079
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import org.rust.lang.core.lexer.RustTokenElementTypes import org.rust.lang.core.psi.RustPathPart import org.rust.lang.core.psi.RustQualifiedReferenceElement import org.rust.lang.core.psi.RustViewPath import org.rust.lang.core.psi.impl.RustNamedElementImpl import org.rust.lang.core.resolve.ref.RustReference import org.rust.lang.core.resolve.ref.RustQualifiedReferenceImpl abstract class RustPathPartImplMixin(node: ASTNode) : RustNamedElementImpl(node) , RustQualifiedReferenceElement , RustPathPart { override fun getReference(): RustReference = RustQualifiedReferenceImpl(this) override val nameElement: PsiElement? get() = identifier override val separator: PsiElement? get() = findChildByType(RustTokenElementTypes.COLONCOLON) override val qualifier: RustQualifiedReferenceElement? get() = if (pathPart?.firstChild != null) pathPart else null private val isViewPath: Boolean get() { val parent = parent return when (parent) { is RustViewPath -> true is RustPathPartImplMixin -> parent.isViewPath else -> false } } override val isFullyQualified: Boolean get() { val qual = qualifier return if (qual == null) { separator != null || (isViewPath && self == null && `super` == null) } else { qual.isFullyQualified } } override val isModulePrefix: Boolean get() { val qual = qualifier return if (qual == null) { separator == null && (self != null || `super` != null) } else { `super` != null && qual.isModulePrefix } } override val isSelf: Boolean get() = self != null }
mit
11cb9516c82ade9e83e0367ba3f865e2
33.65
84
0.590669
4.92654
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/engagement/NextPageLoadViewHolder.kt
1
928
package org.wordpress.android.ui.engagement import android.view.View import android.view.ViewGroup import android.widget.Button import org.wordpress.android.R import org.wordpress.android.ui.engagement.EngageItem.NextLikesPageLoader class NextPageLoadViewHolder(parent: ViewGroup) : EngagedPeopleViewHolder(parent, R.layout.load_or_action_item) { private val progress = itemView.findViewById<View>(R.id.progress) private val actionButton = itemView.findViewById<Button>(R.id.action_button) fun bind(item: NextLikesPageLoader) { if (item.isLoading) { item.action.invoke() progress.visibility = View.VISIBLE actionButton.visibility = View.GONE } else { progress.visibility = View.GONE actionButton.visibility = View.VISIBLE actionButton.setOnClickListener { item.action.invoke() } } } }
gpl-2.0
281b4937aff7b0ad103c220f9fcf3679
34.692308
113
0.690733
4.398104
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/JKResolver.kt
7
4458
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.impl.java.stubs.index.JavaFullClassNameIndex import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelFunctionFqnNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelPropertyFqnNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelTypeAliasFqNameIndex import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.resolve.ImportPath class JKResolver(val project: Project, module: Module?, private val contextElement: PsiElement) { private val scope = module?.let { GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(it) } ?: GlobalSearchScope.allScope(project) fun resolveClass(fqName: FqName): PsiElement? = resolveFqNameOfKtClassByIndex(fqName) ?: resolveFqNameOfJavaClassByIndex(fqName) ?: resolveFqName(fqName) fun resolveMethod(fqName: FqName): PsiElement? = resolveFqNameOfKtFunctionByIndex(fqName) ?: resolveFqName(fqName) fun resolveMethodWithExactSignature(methodFqName: FqName, parameterTypesFqNames: List<FqName>): PsiElement? = resolveFqNameOfKtFunctionByIndex(methodFqName) { it.valueParameters.size == parameterTypesFqNames.size && it.valueParameters.map { param -> param.resolveToParameterDescriptorIfAny()?.type?.fqName } == parameterTypesFqNames } fun resolveField(fqName: FqName): PsiElement? = resolveFqNameOfKtPropertyByIndex(fqName) ?: resolveFqName(fqName) private fun resolveFqNameOfKtClassByIndex(fqName: FqName): KtDeclaration? { val fqNameString = fqName.asString() val classesPsi = KotlinFullClassNameIndex.get(fqNameString, project, scope) val typeAliasesPsi = KotlinTopLevelTypeAliasFqNameIndex.get(fqNameString, project, scope) return selectNearest(classesPsi, typeAliasesPsi) } private fun resolveFqNameOfJavaClassByIndex(fqName: FqName): PsiClass? { val fqNameString = fqName.asString() return JavaFullClassNameIndex.getInstance()[fqNameString, project, scope] .firstOrNull { it.qualifiedName == fqNameString } } private fun resolveFqNameOfKtFunctionByIndex(fqName: FqName, filter: (KtNamedFunction) -> Boolean = { true }): KtNamedFunction? = KotlinTopLevelFunctionFqnNameIndex.get(fqName.asString(), project, scope).firstOrNull { filter(it) } private fun resolveFqNameOfKtPropertyByIndex(fqName: FqName): KtProperty? = KotlinTopLevelPropertyFqnNameIndex.get(fqName.asString(), project, scope).firstOrNull() private fun resolveFqName(fqName: FqName): PsiElement? { if (fqName.isRoot) return null return constructImportDirectiveWithContext(fqName) .getChildOfType<KtDotQualifiedExpression>() ?.selectorExpression ?.references ?.firstNotNullOfOrNull(PsiReference::resolve) } private fun constructImportDirectiveWithContext(fqName: FqName): KtImportDirective { val importDirective = KtPsiFactory(contextElement).createImportDirective(ImportPath(fqName, false)) importDirective.containingKtFile.analysisContext = contextElement.containingFile return importDirective } private fun selectNearest(classesPsi: Collection<KtDeclaration>, typeAliasesPsi: Collection<KtTypeAlias>): KtDeclaration? = when { typeAliasesPsi.isEmpty() -> classesPsi.firstOrNull() classesPsi.isEmpty() -> typeAliasesPsi.firstOrNull() else -> (classesPsi.asSequence() + typeAliasesPsi.asSequence()).minWithOrNull(Comparator { o1, o2 -> scope.compare(o1.containingFile.virtualFile, o2.containingFile.virtualFile) }) } }
apache-2.0
a0acf127cd502f860f87e887c8b13977
46.935484
136
0.745402
5.351741
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/LinkedListEntityImpl.kt
1
8192
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class LinkedListEntityImpl : LinkedListEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _myName: String? = null override val myName: String get() = _myName!! @JvmField var _next: LinkedListEntityId? = null override val next: LinkedListEntityId get() = _next!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: LinkedListEntityData?) : ModifiableWorkspaceEntityBase<LinkedListEntity>(), LinkedListEntity.Builder { constructor() : this(LinkedListEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity LinkedListEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isMyNameInitialized()) { error("Field LinkedListEntity#myName should be initialized") } if (!getEntityData().isNextInitialized()) { error("Field LinkedListEntity#next should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as LinkedListEntity this.entitySource = dataSource.entitySource this.myName = dataSource.myName this.next = dataSource.next if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var myName: String get() = getEntityData().myName set(value) { checkModificationAllowed() getEntityData().myName = value changedProperty.add("myName") } override var next: LinkedListEntityId get() = getEntityData().next set(value) { checkModificationAllowed() getEntityData().next = value changedProperty.add("next") } override fun getEntityData(): LinkedListEntityData = result ?: super.getEntityData() as LinkedListEntityData override fun getEntityClass(): Class<LinkedListEntity> = LinkedListEntity::class.java } } class LinkedListEntityData : WorkspaceEntityData.WithCalculablePersistentId<LinkedListEntity>(), SoftLinkable { lateinit var myName: String lateinit var next: LinkedListEntityId fun isMyNameInitialized(): Boolean = ::myName.isInitialized fun isNextInitialized(): Boolean = ::next.isInitialized override fun getLinks(): Set<PersistentEntityId<*>> { val result = HashSet<PersistentEntityId<*>>() result.add(next) return result } override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) { index.index(this, next) } override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val removedItem_next = mutablePreviousSet.remove(next) if (!removedItem_next) { index.index(this, next) } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean { var changed = false val next_data = if (next == oldLink) { changed = true newLink as LinkedListEntityId } else { null } if (next_data != null) { next = next_data } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LinkedListEntity> { val modifiable = LinkedListEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): LinkedListEntity { val entity = LinkedListEntityImpl() entity._myName = myName entity._next = next entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun persistentId(): PersistentEntityId<*> { return LinkedListEntityId(myName) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return LinkedListEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return LinkedListEntity(myName, next, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as LinkedListEntityData if (this.entitySource != other.entitySource) return false if (this.myName != other.myName) return false if (this.next != other.next) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as LinkedListEntityData if (this.myName != other.myName) return false if (this.next != other.next) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + myName.hashCode() result = 31 * result + next.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + myName.hashCode() result = 31 * result + next.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(LinkedListEntityId::class.java) collector.sameForAllEntities = true } }
apache-2.0
32b2f7da07d9b508e2d7a107da4e6cda
30.148289
130
0.717773
5.268167
false
false
false
false
byu-oit/android-byu-suite-v2
support/src/main/java/edu/byu/support/payment/model/PaymentAccount.kt
2
1395
package edu.byu.support.payment.model import android.os.Parcel import android.os.Parcelable import edu.byu.support.ByuParcelable2 import edu.byu.support.ByuParcelable2.Companion.parcelableCreator import edu.byu.support.R import edu.byu.support.utils.readBoolean import edu.byu.support.utils.writeBoolean /** * Created by geogor37 on 2/13/18 */ open class PaymentAccount( var id: String? = null, var mungedAccountNum: String? = null, var nickname: String? = null, var financialInstitution: String? = null, private var isCreditCard: Boolean = false ): ByuParcelable2 { companion object { @JvmField val CREATOR: Parcelable.Creator<PaymentAccount> = parcelableCreator(::PaymentAccount) } constructor(parcel: Parcel): this( parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readBoolean() ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(id) parcel.writeString(mungedAccountNum) parcel.writeString(nickname) parcel.writeString(financialInstitution) parcel.writeBoolean(isCreditCard) } open fun isCreditCard() = isCreditCard fun getImage() = if (isCreditCard()) R.drawable.icon_credit_card else R.drawable.icon_bank open fun getFormattedAccountNumber() = if (isCreditCard) "•••• •••• •••• $mungedAccountNum" else "••••••$mungedAccountNum" }
apache-2.0
1c4faac1e41d12c6f2cb7cc4b1873211
27.93617
123
0.755703
3.557592
false
true
false
false
iPoli/iPoli-android
app/src/test/java/io/ipoli/android/quest/show/usecase/AddPomodoroUseCaseSpek.kt
1
4346
package io.ipoli.android.quest.show.usecase import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import io.ipoli.android.TestUtil import io.ipoli.android.common.datetime.plusMinutes import io.ipoli.android.quest.Quest import io.ipoli.android.quest.TimeRange import io.ipoli.android.quest.data.persistence.QuestRepository import io.ipoli.android.quest.show.longBreaks import io.ipoli.android.quest.show.pomodoros import io.ipoli.android.quest.show.shortBreaks import org.amshove.kluent.`should be equal to` import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.threeten.bp.Instant /** * Created by Polina Zhelyazkova <[email protected]> * on 1/19/18. */ class AddPomodoroUseCaseSpek : Spek({ describe("AddPomodoroUseCase") { fun executeUseCase( quest: Quest ): Quest { val questRepoMock = mock<QuestRepository> { on { findById(any()) } doReturn quest on { save(any<Quest>()) } doAnswer { invocation -> invocation.getArgument(0) } } return AddPomodoroUseCase( questRepoMock, SplitDurationForPomodoroTimerUseCase() ) .execute(AddPomodoroUseCase.Params(quest.id)) } val simpleQuest = TestUtil.quest val now = Instant.now() it("should add duration of 1 pomodoro with short break") { val result = executeUseCase( simpleQuest.copy( duration = 1.pomodoros() + 1.shortBreaks() ) ) result.duration.`should be equal to`(2.pomodoros() + 2.shortBreaks()) } it("should add pomodoro duration to actual duration") { val result = executeUseCase( simpleQuest.copy( duration = 10, timeRanges = listOf( TimeRange( TimeRange.Type.POMODORO_WORK, 1.pomodoros(), now, now.plusMinutes(1.pomodoros().toLong()) ), TimeRange( TimeRange.Type.POMODORO_SHORT_BREAK, 1.shortBreaks(), now, now.plusMinutes(1.shortBreaks().toLong()) ) ) ) ) result.duration.`should be equal to`(2.pomodoros() + 2.shortBreaks()) } it("should add pomodoro duration to short duration quest") { val result = executeUseCase( simpleQuest.copy( duration = 10, timeRanges = listOf() ) ) result.duration.`should be equal to`(1.pomodoros() + 1.shortBreaks() + 10) } it("should add pomodoro duration with long break") { val timeRanges = mutableListOf<TimeRange>() for (i: Int in 1..4) { if (i % 2 == 1) { timeRanges.add( TimeRange( TimeRange.Type.POMODORO_WORK, 1.pomodoros(), now, now.plusMinutes(1.pomodoros().toLong()) ) ) } else { timeRanges.add( TimeRange( TimeRange.Type.POMODORO_SHORT_BREAK, 1.shortBreaks(), now, now.plusMinutes(1.shortBreaks().toLong()) ) ) } } val result = executeUseCase( simpleQuest.copy( duration = 3.pomodoros() + 3.shortBreaks(), timeRanges = timeRanges ) ) result.duration.`should be equal to`(4.pomodoros() + 3.shortBreaks() + 1.longBreaks()) } } })
gpl-3.0
68cacc8860b28e461a7d5ad512f4a54a
33.776
98
0.491717
5.32598
false
false
false
false
jk1/intellij-community
platform/platform-impl/src/com/intellij/util/io/netty.kt
4
11918
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.io import com.google.common.net.InetAddresses import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Conditions import com.intellij.util.Url import com.intellij.util.Urls import com.intellij.util.net.NetUtils import io.netty.bootstrap.Bootstrap import io.netty.bootstrap.BootstrapUtil import io.netty.bootstrap.ServerBootstrap import io.netty.buffer.ByteBuf import io.netty.channel.* import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.oio.OioEventLoopGroup import io.netty.channel.socket.ServerSocketChannel import io.netty.channel.socket.nio.NioServerSocketChannel import io.netty.channel.socket.oio.OioServerSocketChannel import io.netty.channel.socket.oio.OioSocketChannel import io.netty.handler.codec.http.HttpHeaderNames import io.netty.handler.codec.http.HttpMethod import io.netty.handler.codec.http.HttpRequest import io.netty.handler.ssl.SslHandler import io.netty.resolver.ResolvedAddressTypes import io.netty.util.concurrent.GenericFutureListener import org.jetbrains.ide.PooledThreadExecutor import org.jetbrains.io.NettyUtil import java.io.IOException import java.net.InetAddress import java.net.InetSocketAddress import java.net.NetworkInterface import java.net.Socket import java.util.concurrent.ThreadFactory import java.util.concurrent.TimeUnit import java.util.function.Consumer // used in Go fun oioClientBootstrap(): Bootstrap { val bootstrap = Bootstrap().group(OioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(OioSocketChannel::class.java) bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true) return bootstrap } inline fun Bootstrap.handler(crossinline task: (Channel) -> Unit): Bootstrap { handler(object : ChannelInitializer<Channel>() { override fun initChannel(channel: Channel) { task(channel) } }) return this } fun serverBootstrap(group: EventLoopGroup): ServerBootstrap { val bootstrap = ServerBootstrap() .group(group) .channel(group.serverSocketChannelClass()) bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) return bootstrap } private fun EventLoopGroup.serverSocketChannelClass(): Class<out ServerSocketChannel> = when { this is NioEventLoopGroup -> NioServerSocketChannel::class.java this is OioEventLoopGroup -> OioServerSocketChannel::class.java // SystemInfo.isMacOSSierra && this is KQueueEventLoopGroup -> KQueueServerSocketChannel::class.java else -> throw Exception("Unknown event loop group type: ${this.javaClass.name}") } inline fun ChannelFuture.addChannelListener(crossinline listener: (future: ChannelFuture) -> Unit) { addListener(GenericFutureListener<ChannelFuture> { listener(it) }) } // if NIO, so, it is shared and we must not shutdown it fun EventLoop.shutdownIfOio() { if (this is OioEventLoopGroup) { @Suppress("USELESS_CAST") (this as OioEventLoopGroup).shutdownGracefully(1L, 2L, TimeUnit.NANOSECONDS) } } // Event loop will be shut downed only if OIO fun Channel.closeAndShutdownEventLoop() { val eventLoop = eventLoop() try { close().awaitUninterruptibly() } finally { eventLoop.shutdownIfOio() } } /** * Synchronously connects to remote address. */ @JvmOverloads fun Bootstrap.connectRetrying(remoteAddress: InetSocketAddress, maxAttemptCount: Int = NettyUtil.DEFAULT_CONNECT_ATTEMPT_COUNT, stopCondition: Condition<Void>? = null): ConnectToChannelResult { try { return doConnect(this, remoteAddress, maxAttemptCount, stopCondition ?: Conditions.alwaysFalse<Void>()) } catch (e: Throwable) { return ConnectToChannelResult(e) } } private fun doConnect(bootstrap: Bootstrap, remoteAddress: InetSocketAddress, maxAttemptCount: Int, stopCondition: Condition<Void>): ConnectToChannelResult { if (ApplicationManager.getApplication().isDispatchThread) { logger("com.intellij.util.io.netty").error("Synchronous connection to socket shouldn't be performed on EDT.") } var attemptCount = 0 if (bootstrap.config().group() !is OioEventLoopGroup) { return connectNio(bootstrap, remoteAddress, maxAttemptCount, stopCondition, attemptCount) } bootstrap.validate() while (true) { try { val channel = OioSocketChannel(Socket(remoteAddress.address, remoteAddress.port)) BootstrapUtil.initAndRegister(channel, bootstrap).sync() return ConnectToChannelResult(channel) } catch (e: IOException) { when { stopCondition.value(null) -> return ConnectToChannelResult() maxAttemptCount == -1 -> { sleep(300)?.let { return ConnectToChannelResult(it) } attemptCount++ } ++attemptCount < maxAttemptCount -> { sleep(attemptCount * NettyUtil.MIN_START_TIME)?.let { return ConnectToChannelResult(it) } } else -> return ConnectToChannelResult(e) } } } } private fun connectNio(bootstrap: Bootstrap, remoteAddress: InetSocketAddress, maxAttemptCount: Int, stopCondition: Condition<Void>, _attemptCount: Int): ConnectToChannelResult { var attemptCount = _attemptCount while (true) { val future = bootstrap.connect(remoteAddress).awaitUninterruptibly() if (future.isSuccess) { if (!future.channel().isOpen) { continue } return ConnectToChannelResult(future.channel()) } else if (stopCondition.value(null)) { return ConnectToChannelResult() } else if (maxAttemptCount == -1) { sleep(300)?.let { return ConnectToChannelResult(it) } attemptCount++ } else if (++attemptCount < maxAttemptCount) { sleep(attemptCount * NettyUtil.MIN_START_TIME)?.let { return ConnectToChannelResult(it) } } else { @SuppressWarnings("ThrowableResultOfMethodCallIgnored") val cause = future.cause() if (cause == null) { return ConnectToChannelResult("Cannot connect: unknown error") } else { return ConnectToChannelResult(cause) } } } } private fun sleep(time: Int): String? { try { //noinspection BusyWait Thread.sleep(time.toLong()) } catch (ignored: InterruptedException) { return "Interrupted" } return null } val Channel.uriScheme: String get() = if (pipeline().get(SslHandler::class.java) == null) "http" else "https" val HttpRequest.host: String? get() = headers().getAsString(HttpHeaderNames.HOST) val HttpRequest.origin: String? get() = headers().getAsString(HttpHeaderNames.ORIGIN) val HttpRequest.referrer: String? get() = headers().getAsString(HttpHeaderNames.REFERER) val HttpRequest.userAgent: String? get() = headers().getAsString(HttpHeaderNames.USER_AGENT) inline fun <T> ByteBuf.releaseIfError(task: () -> T): T { try { return task() } catch (e: Exception) { try { release() } finally { throw e } } } fun isLocalHost(host: String, onlyAnyOrLoopback: Boolean, hostsOnly: Boolean = false): Boolean { if (NetUtils.isLocalhost(host)) { return true } // if IP address, it is safe to use getByName (not affected by DNS rebinding) if (onlyAnyOrLoopback && !InetAddresses.isInetAddress(host)) { return false } fun InetAddress.isLocal() = isAnyLocalAddress || isLoopbackAddress || NetworkInterface.getByInetAddress(this) != null try { val address = InetAddress.getByName(host) if (!address.isLocal()) { return false } // be aware - on windows hosts file doesn't contain localhost // hosts can contain remote addresses, so, we check it if (hostsOnly && !InetAddresses.isInetAddress(host)) { return io.netty.resolver.HostsFileEntriesResolver.DEFAULT.address(host, ResolvedAddressTypes.IPV4_PREFERRED).let { it != null && it.isLocal() } } else { return true } } catch (ignored: IOException) { return false } } @JvmOverloads fun HttpRequest.isLocalOrigin(onlyAnyOrLoopback: Boolean = true, hostsOnly: Boolean = false): Boolean { return parseAndCheckIsLocalHost(origin, onlyAnyOrLoopback, hostsOnly) && parseAndCheckIsLocalHost(referrer, onlyAnyOrLoopback, hostsOnly) } private fun isTrustedChromeExtension(url: Url): Boolean { return url.scheme == "chrome-extension" && (url.authority == "hmhgeddbohgjknpmjagkdomcpobmllji" || url.authority == "offnedcbhjldheanlbojaefbfbllddna") } private val Url.host: String? get() = authority?.let { val portIndex = it.indexOf(':') if (portIndex > 0) it.substring(0, portIndex) else it } @JvmOverloads fun parseAndCheckIsLocalHost(uri: String?, onlyAnyOrLoopback: Boolean = true, hostsOnly: Boolean = false): Boolean { if (uri == null || uri == "about:blank") { return true } try { val parsedUri = Urls.parse(uri, false) ?: return false val host = parsedUri.host return host != null && (isTrustedChromeExtension(parsedUri) || isLocalHost(host, onlyAnyOrLoopback, hostsOnly)) } catch (ignored: Exception) { } return false } fun HttpRequest.isRegularBrowser(): Boolean = userAgent?.startsWith("Mozilla/5.0") ?: false // forbid POST requests from browser without Origin fun HttpRequest.isWriteFromBrowserWithoutOrigin(): Boolean { val method = method() return origin.isNullOrEmpty() && isRegularBrowser() && (method == HttpMethod.POST || method == HttpMethod.PATCH || method == HttpMethod.PUT || method == HttpMethod.DELETE) } fun ByteBuf.readUtf8(): String = toString(Charsets.UTF_8) fun ByteBuf.writeUtf8(data: CharSequence): Int = writeCharSequence(data, Charsets.UTF_8) @Suppress("FunctionName") fun MultiThreadEventLoopGroup(workerCount: Int, threadFactory: ThreadFactory): MultithreadEventLoopGroup { // if (SystemInfo.isMacOSSierra && SystemProperties.getBooleanProperty("native.net.io", false)) { // try { // return KQueueEventLoopGroup(workerCount, threadFactory) // } // catch (e: Throwable) { // logger<BuiltInServer>().warn("Cannot use native event loop group", e) // } // } return NioEventLoopGroup(workerCount, threadFactory) } @Suppress("FunctionName") fun MultiThreadEventLoopGroup(workerCount: Int): MultithreadEventLoopGroup { // if (SystemInfo.isMacOSSierra && SystemProperties.getBooleanProperty("native.net.io", false)) { // try { // return KQueueEventLoopGroup(workerCount, PooledThreadExecutor.INSTANCE) // } // catch (e: Throwable) { // // error instead of warn to easy spot it // logger<BuiltInServer>().error("Cannot use native event loop group", e) // } // } return NioEventLoopGroup(workerCount, PooledThreadExecutor.INSTANCE) } class ConnectToChannelResult { val channel: Channel? private val message: String? private val throwable: Throwable? constructor(channel: Channel? = null) : this(channel, null, null) constructor(message: String): this(null, message, null) constructor(error: Throwable) : this(null, null, error) private constructor(channel: Channel?, message: String?, throwable: Throwable?) { this.channel = channel this.message = message this.throwable = throwable } fun handleError(consumer: Consumer<String>) : ConnectToChannelResult { if (message != null) { consumer.accept(message) } return this } fun handleThrowable(consumer: Consumer<Throwable>) : ConnectToChannelResult { if (throwable != null) { consumer.accept(throwable) } return this } }
apache-2.0
83f936ac8368a14077a1a252e4754118
31.654795
173
0.712536
4.50586
false
false
false
false
jimandreas/BottomNavigationView-plus-LeakCanary
app/src/main/java/com/jimandreas/android/designlibdemo/CheesesActivity.kt
2
1749
package com.jimandreas.android.designlibdemo import android.content.Intent import android.os.Bundle import android.support.design.widget.BottomNavigationView import android.support.design.widget.CollapsingToolbarLayout import android.widget.ImageView import com.bumptech.glide.Glide import com.jimandreas.android.base.BottomNavActivity // todo: implement the new cheeses activity here class CheesesActivity : BottomNavActivity() { private lateinit var ctl: CollapsingToolbarLayout private lateinit var bottomNavigationView: BottomNavigationView override val activityMenuID: Int get() = WHOAMI_NAVBAR_MENUID override val contentViewId: Int get() = R.layout.activity_cheeses2 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setContentView(R.layout.activity_cheeses2); ctl = findViewById(R.id.collapsing_toolbar) bottomNavigationView = findViewById(R.id.bottom_navigation) ctl.title = resources.getString(R.string.text_cheeses) supportFragmentManager.beginTransaction() .replace(R.id.cheese_container, CheeseListFragment()) .commit() loadBackdrop() } private fun loadBackdrop() { val imageView: ImageView = findViewById(R.id.cheeses_backdrop) Glide.with(this) .load(R.drawable.parmigiano_reggiano_factory) .centerCrop() .into(imageView) } override fun onBackPressed() { val intent = Intent(this, MainActivityKotlin::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } } private const val WHOAMI_NAVBAR_MENUID = R.id.action_cheeses
apache-2.0
50790f21957ffe67b3901cc0094214be
30.8
70
0.708977
4.639257
false
false
false
false
AoDevBlue/AnimeUltimeTv
app/src/main/java/blue/aodev/animeultimetv/presentation/common/BaseCardPresenter.kt
1
2351
package blue.aodev.animeultimetv.presentation.common import android.content.Context import android.support.v17.leanback.widget.ImageCardView import android.support.v17.leanback.widget.Presenter import android.support.v4.content.ContextCompat import android.view.View import android.view.ViewGroup import android.widget.ImageView import blue.aodev.animeultimetv.R abstract class BaseCardPresenter( val cardImageWidth: Int, val cardImageHeight: Int ) : Presenter() { private var hasResources = false protected var selectedBackgroundColor = -1 protected var defaultBackgroundColor = -1 override fun onCreateViewHolder(parent: ViewGroup): ViewHolder { if (!hasResources) { initResources(parent.context) hasResources = true } val cardView = object : ImageCardView(parent.context) { override fun setSelected(selected: Boolean) { updateCardBackgroundColor(this, selected) super.setSelected(selected) } } cardView.isFocusable = true cardView.isFocusableInTouchMode = true // Setup image cardView.setMainImageDimensions(cardImageWidth, cardImageHeight) cardView.setMainImageScaleType(ImageView.ScaleType.FIT_XY) updateCardBackgroundColor(cardView, false) return ViewHolder(cardView) } private fun initResources(context: Context) { defaultBackgroundColor = ContextCompat.getColor(context, R.color.card_background_default) selectedBackgroundColor = ContextCompat.getColor(context, R.color.card_background_selected) } private fun updateCardBackgroundColor(view: ImageCardView, selected: Boolean) { val color = if (selected) selectedBackgroundColor else defaultBackgroundColor // Both background colors should be set because the view's // background is temporarily visible during animations. view.setBackgroundColor(color) view.findViewById<View>(R.id.info_field).setBackgroundColor(color) } override fun onUnbindViewHolder(viewHolder: ViewHolder) { val cardView = viewHolder.view as ImageCardView // Remove references to images so that the garbage collector can free up memory. cardView.badgeImage = null cardView.mainImage = null } }
mit
9adc9a9e686111794efb060d66881623
34.636364
99
0.71544
5.21286
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/proteins/Protein.kt
1
2981
package graphics.scenery.proteins import graphics.scenery.Mesh import graphics.scenery.proteins.Protein.MyProtein.fromFile import graphics.scenery.proteins.Protein.MyProtein.fromID import graphics.scenery.utils.LazyLogger import org.biojava.nbio.structure.Structure import org.biojava.nbio.structure.StructureException import org.biojava.nbio.structure.StructureIO import org.biojava.nbio.structure.io.PDBFileReader import java.io.FileNotFoundException import java.io.IOException import java.nio.file.InvalidPathException /** * Constructs a protein from a pdb-file. * @author Justin Buerger <[email protected]> * [fromID] loads a pbd-file with an ID. See also: https://www.rcsb.org/pages/help/advancedsearch/pdbIDs * [fromFile] loads a pdb-file from memory. */ class Protein(val structure: Structure): Mesh("Protein") { companion object MyProtein { private val proteinLogger by LazyLogger() fun fromID(id: String): Protein { //print("Please enter the PDB-ID: ") //val id = readLine() try { StructureIO.getStructure(id) } catch (struc: IOException) { proteinLogger.error("Something went wrong during the loading process of the pdb file, " + "maybe a typo in the pdb entry or you chose a deprecated one?" + "Here is the trace: \n" + struc.printStackTrace()) } catch(struc: StructureException) { proteinLogger.error("Something went wrong during the loading of the pdb file."+ "Here is the trace: \n" + struc.printStackTrace()) } catch(struc: NullPointerException) { proteinLogger.error("Something is broken in BioJava. You can try to update the version.") } finally { val struc = StructureIO.getStructure(id) val protein = Protein(struc) return protein } } fun fromFile(path: String): Protein { val reader = PDBFileReader() //print("Please enter the path of your PDB-File: ") //val readPath = readLine() try { reader.getStructure(path) } catch (struc: InvalidPathException) { proteinLogger.info("Path was invalid, maybe this helps: ${struc.reason} " + "or the index: ${struc.index}") } catch(struc: FileNotFoundException) { proteinLogger.error("The pdb file is not in the directory") } catch(struc: Exception) { proteinLogger.error("Something about the pdb file is wrong. This is not an invalid path problem nor is" + "it a file-not-found-problem.") } finally { val struc = reader.getStructure(path) return Protein(struc) } } } }
lgpl-3.0
2261ca3113a66e3cbabcea71f18141d1
38.223684
121
0.600805
4.694488
false
false
false
false
mdanielwork/intellij-community
platform/built-in-server/testSrc/org/jetbrains/ide/BinaryRequestHandlerTest.kt
4
3945
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.ide import com.intellij.testFramework.ProjectRule import com.intellij.util.concurrency.Semaphore import com.intellij.util.io.handler import com.intellij.util.net.loopbackSocketAddress import io.netty.buffer.ByteBuf import io.netty.buffer.Unpooled import io.netty.channel.ChannelHandler import io.netty.channel.ChannelHandlerContext import junit.framework.TestCase import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.io.ChannelExceptionHandler import org.jetbrains.io.Decoder import org.jetbrains.io.MessageDecoder import org.jetbrains.io.oioClientBootstrap import org.junit.ClassRule import org.junit.Test import java.util.* import java.util.concurrent.TimeUnit // we don't handle String in efficient way - because we want to test readContent/readChars also internal class BinaryRequestHandlerTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } @Test fun test() { val text = "Hello!" val result = AsyncPromise<String>() val bootstrap = oioClientBootstrap().handler { it.pipeline().addLast(object : Decoder() { override fun messageReceived(context: ChannelHandlerContext, input: ByteBuf) { val requiredLength = 4 + text.length val response = readContent(input, context, requiredLength) { buffer, _, _ -> buffer.toString(buffer.readerIndex(), requiredLength, Charsets.UTF_8) } if (response != null) { result.setResult(response) } } }, ChannelExceptionHandler.getInstance()) } val port = BuiltInServerManager.getInstance().waitForStart().port val channel = bootstrap.connect(loopbackSocketAddress(port)).syncUninterruptibly().channel() val buffer = channel.alloc().buffer() buffer.writeByte('C'.toInt()) buffer.writeByte('H'.toInt()) buffer.writeLong(MyBinaryRequestHandler.ID.mostSignificantBits) buffer.writeLong(MyBinaryRequestHandler.ID.leastSignificantBits) val message = Unpooled.copiedBuffer(text, Charsets.UTF_8) buffer.writeShort(message.readableBytes()) channel.write(buffer) channel.writeAndFlush(message).await(5, TimeUnit.SECONDS) try { result.onError { error -> TestCase.fail(error.message) } if (result.state == Promise.State.PENDING) { val semaphore = Semaphore() semaphore.down() result.onProcessed { semaphore.up() } if (!semaphore.waitForUnsafe(5000)) { TestCase.fail("Time limit exceeded") return } } TestCase.assertEquals("got-$text", result.get()) } finally { channel.close() } } class MyBinaryRequestHandler : BinaryRequestHandler() { companion object { val ID: UUID = UUID.fromString("E5068DD6-1DB7-437C-A3FC-3CA53B6E1AC9") } override fun getId(): UUID { return ID } override fun getInboundHandler(context: ChannelHandlerContext): ChannelHandler { return MyDecoder() } private class MyDecoder : MessageDecoder() { private var state = State.HEADER private enum class State { HEADER, CONTENT } override fun messageReceived(context: ChannelHandlerContext, input: ByteBuf) { while (true) { when (state) { State.HEADER -> { val buffer = getBufferIfSufficient(input, 2, context) ?: return contentLength = buffer.readUnsignedShort() state = State.CONTENT } State.CONTENT -> { val messageText = readChars(input) ?: return state = State.HEADER context.writeAndFlush(Unpooled.copiedBuffer("got-$messageText", Charsets.UTF_8)) } } } } } } }
apache-2.0
46bda602ad92344bc6836a05ccbb4ba7
31.61157
158
0.680101
4.603267
false
true
false
false
Tickaroo/tikxml
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/element/polymorphism/Organisation.kt
1
1450
/* * Copyright (C) 2015 Hannes Dorfmann * Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.annotationprocessing.element.polymorphism import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml /** * @author Hannes Dorfmann */ @Xml class Organisation : Writer() { @PropertyElement var address: String? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Organisation) return false if (!super.equals(other)) return false val that = other as Organisation? return if (address != null) address == that!!.address else that!!.address == null } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + if (address != null) address!!.hashCode() else 0 return result } }
apache-2.0
94600fa353ec4a3cfe36b551bb6a70d0
29.208333
89
0.686897
4.252199
false
false
false
false
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/utils/MidnightTimer.kt
1
2278
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker 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 org.isoron.uhabits.core.utils import org.isoron.uhabits.core.AppScope import java.util.LinkedList import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit import javax.inject.Inject /** * A class that emits events when a new day starts. */ @AppScope open class MidnightTimer @Inject constructor() { private val listeners: MutableList<MidnightListener> = LinkedList() private lateinit var executor: ScheduledExecutorService @Synchronized fun addListener(listener: MidnightListener) { this.listeners.add(listener) } @Synchronized fun onPause(): MutableList<Runnable>? = executor.shutdownNow() @Synchronized fun onResume( delayOffsetInMillis: Long = DateUtils.SECOND_LENGTH, testExecutor: ScheduledExecutorService? = null ) { executor = testExecutor ?: Executors.newSingleThreadScheduledExecutor() executor.scheduleAtFixedRate( { notifyListeners() }, DateUtils.millisecondsUntilTomorrowWithOffset() + delayOffsetInMillis, DateUtils.DAY_LENGTH, TimeUnit.MILLISECONDS ) } @Synchronized fun removeListener(listener: MidnightListener) = this.listeners.remove(listener) @Synchronized private fun notifyListeners() { for (l in listeners) { l.atMidnight() } } fun interface MidnightListener { fun atMidnight() } }
gpl-3.0
68507587e290edc2210898552d28dada
31.070423
84
0.713219
4.704545
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt
3
10614
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.introduceParameter import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.editor.impl.DocumentMarkupModel import com.intellij.openapi.editor.markup.EffectType import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.editor.markup.MarkupModel import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.ui.JBColor import com.intellij.ui.NonFocusableCheckBox import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.unifier.toRange import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractKotlinInplaceIntroducer import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinInplaceVariableIntroducer import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.getValueParameterList import org.jetbrains.kotlin.psi.psiUtil.getValueParameters import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.supertypes import java.awt.Color import javax.swing.JCheckBox class KotlinInplaceParameterIntroducer( val originalDescriptor: IntroduceParameterDescriptor, val parameterType: KotlinType, val suggestedNames: Array<out String>, project: Project, editor: Editor ) : AbstractKotlinInplaceIntroducer<KtParameter>( null, originalDescriptor.originalRange.elements.single() as KtExpression, originalDescriptor.occurrencesToReplace.map { it.elements.single() as KtExpression }.toTypedArray(), INTRODUCE_PARAMETER, project, editor ) { companion object { private val LOG = Logger.getInstance(KotlinInplaceParameterIntroducer::class.java) } enum class PreviewDecorator { FOR_ADD() { override val textAttributes: TextAttributes = with(TextAttributes()) { effectType = EffectType.ROUNDED_BOX effectColor = JBColor.RED this } }, FOR_REMOVAL() { override val textAttributes: TextAttributes = with(TextAttributes()) { effectType = EffectType.STRIKEOUT effectColor = Color.BLACK this } }; protected abstract val textAttributes: TextAttributes fun applyToRange(range: TextRange, markupModel: MarkupModel) { markupModel.addRangeHighlighter( range.startOffset, range.endOffset, 0, textAttributes, HighlighterTargetArea.EXACT_RANGE ) } } private inner class Preview(addedParameter: KtParameter?, currentName: String?) { private val _rangesToRemove = ArrayList<TextRange>() var addedRange: TextRange? = null private set var text: String = "" private set val rangesToRemove: List<TextRange> get() = _rangesToRemove init { val templateState = TemplateManagerImpl.getTemplateState(myEditor) val currentType = if (templateState?.template != null) { templateState.getVariableValue(KotlinInplaceVariableIntroducer.TYPE_REFERENCE_VARIABLE_NAME)?.text } else null val builder = StringBuilder() with(descriptor) { (callable as? KtFunction)?.receiverTypeReference?.let { receiverTypeRef -> builder.append(receiverTypeRef.text).append('.') if (!descriptor.withDefaultValue && receiverTypeRef in parametersToRemove) { _rangesToRemove.add(TextRange(0, builder.length)) } } builder.append(callable.name) val parameters = callable.getValueParameters() builder.append("(") for (i in parameters.indices) { val parameter = parameters[i] val parameterText = if (parameter == addedParameter) { val parameterName = currentName ?: parameter.name val parameterType = currentType ?: parameter.typeReference!!.text descriptor = descriptor.copy(newParameterName = parameterName!!, newParameterTypeText = parameterType) val modifier = if (valVar != KotlinValVar.None) "${valVar.keywordName} " else "" val defaultValue = if (withDefaultValue) { " = ${if (newArgumentValue is KtProperty) newArgumentValue.name else newArgumentValue.text}" } else "" "$modifier$parameterName: $parameterType$defaultValue" } else parameter.text builder.append(parameterText) val range = TextRange(builder.length - parameterText.length, builder.length) if (parameter == addedParameter) { addedRange = range } else if (!descriptor.withDefaultValue && parameter in parametersToRemove) { _rangesToRemove.add(range) } if (i < parameters.lastIndex) { builder.append(", ") } } builder.append(")") if (addedRange == null) { LOG.error("Added parameter not found: ${callable.getElementTextWithContext()}") } } text = builder.toString() } } private var descriptor = originalDescriptor private var replaceAllCheckBox: JCheckBox? = null init { initFormComponents { addComponent(previewComponent) val defaultValueCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.introduce.default.value")) defaultValueCheckBox.isSelected = descriptor.withDefaultValue defaultValueCheckBox.addActionListener { descriptor = descriptor.copy(withDefaultValue = defaultValueCheckBox.isSelected) updateTitle(variable) } addComponent(defaultValueCheckBox) val occurrenceCount = descriptor.occurrencesToReplace.size if (occurrenceCount > 1) { val replaceAllCheckBox = NonFocusableCheckBox( KotlinBundle.message("checkbox.text.replace.all.occurrences.0", occurrenceCount)) replaceAllCheckBox.isSelected = true addComponent(replaceAllCheckBox) [email protected] = replaceAllCheckBox } } } override fun getActionName() = "IntroduceParameter" override fun checkLocalScope() = descriptor.callable override fun getVariable() = originalDescriptor.callable.getValueParameters().lastOrNull() override fun suggestNames(replaceAll: Boolean, variable: KtParameter?) = suggestedNames override fun createFieldToStartTemplateOn(replaceAll: Boolean, names: Array<out String>): KtParameter { return runWriteAction { with(descriptor) { val parameterList = callable.getValueParameterList() ?: (callable as KtClass).createPrimaryConstructorParameterListIfAbsent() val parameter = KtPsiFactory(myProject).createParameter("$newParameterName: $newParameterTypeText") parameterList.addParameter(parameter) } } } override fun deleteTemplateField(psiField: KtParameter) { if (psiField.isValid) { (psiField.parent as? KtParameterList)?.removeParameter(psiField) } } override fun isReplaceAllOccurrences() = replaceAllCheckBox?.isSelected ?: true override fun setReplaceAllOccurrences(allOccurrences: Boolean) { replaceAllCheckBox?.isSelected = allOccurrences } override fun getComponent() = myWholePanel override fun updateTitle(addedParameter: KtParameter?, currentName: String?) { val preview = Preview(addedParameter, currentName) val document = previewEditor.document runWriteAction { document.setText(preview.text) } val markupModel = DocumentMarkupModel.forDocument(document, myProject, true) markupModel.removeAllHighlighters() preview.rangesToRemove.forEach { PreviewDecorator.FOR_REMOVAL.applyToRange(it, markupModel) } preview.addedRange?.let { PreviewDecorator.FOR_ADD.applyToRange(it, markupModel) } revalidate() } override fun getRangeToRename(element: PsiElement): TextRange { if (element is KtProperty) return element.nameIdentifier!!.textRange.shiftRight(-element.startOffset) return super.getRangeToRename(element) } override fun createMarker(element: PsiElement): RangeMarker { if (element is KtProperty) return super.createMarker(element.nameIdentifier) return super.createMarker(element) } override fun performIntroduce() { getDescriptorToRefactor(isReplaceAllOccurrences).performRefactoring() } private fun getDescriptorToRefactor(replaceAll: Boolean): IntroduceParameterDescriptor { val originalRange = expr.toRange() return descriptor.copy( originalRange = originalRange, occurrencesToReplace = if (replaceAll) occurrences.map { it.toRange() } else listOf(originalRange), argumentValue = expr!! ) } fun switchToDialogUI() { stopIntroduce(myEditor) KotlinIntroduceParameterDialog( myProject, myEditor, getDescriptorToRefactor(true), myNameSuggestions.toTypedArray(), listOf(parameterType) + parameterType.supertypes(), KotlinIntroduceParameterHelper.Default ).show() } }
apache-2.0
7104003063c13d7ca1ffbcb9261f8051
39.980695
158
0.662333
5.942889
false
false
false
false
android/snippets
compose/snippets/src/main/java/com/example/compose/snippets/graphics/BrushExampleSnippets.kt
1
10660
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.example.compose.snippets.graphics import android.graphics.RuntimeShader import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.center import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.ImageShader import androidx.compose.ui.graphics.LinearGradientShader import androidx.compose.ui.graphics.RadialGradientShader import androidx.compose.ui.graphics.Shader import androidx.compose.ui.graphics.ShaderBrush import androidx.compose.ui.graphics.TileMode import androidx.compose.ui.graphics.drawscope.inset import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.imageResource import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.compose.snippets.R import org.intellij.lang.annotations.Language /* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The snippets in this file relate to the documentation at * https://developr.android.com/jetpack/compose/graphics/draw/brush */ @Composable fun BrushExamplesScreen() { Column(Modifier.verticalScroll(rememberScrollState())) { GraphicsBrushCanvasUsage() GraphicsBrushColorStopUsage() GraphicsBrushTileMode() GraphicsBrushSize() GraphicsBrushSizeRecreationExample() GraphicsImageBrush() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { ShaderBrushExample() } } } @Preview @Composable fun GraphicsBrushCanvasUsage() { // [START android_compose_brush_basic_canvas] val brush = Brush.horizontalGradient(listOf(Color.Red, Color.Blue)) Canvas( modifier = Modifier.size(200.dp), onDraw = { drawCircle(brush) } ) // [END android_compose_brush_basic_canvas] } @Preview @Composable fun GraphicsBrushColorStopUsage() { // [START android_compose_brush_color_stop] val colorStops = arrayOf( 0.0f to Color.Yellow, 0.2f to Color.Red, 1f to Color.Blue ) Box( modifier = Modifier .requiredSize(200.dp) .background(Brush.horizontalGradient(colorStops = colorStops)) ) // [END android_compose_brush_color_stop] } @Preview @Composable fun GraphicsBrushTileMode() { // [START android_compose_brush_tile_mode] val listColors = listOf(Color.Yellow, Color.Red, Color.Blue) val tileSize = with(LocalDensity.current) { 50.dp.toPx() } Box( modifier = Modifier .requiredSize(200.dp) .background( Brush.horizontalGradient( listColors, endX = tileSize, tileMode = TileMode.Repeated ) ) ) // [END android_compose_brush_tile_mode] } @Composable @Preview fun GraphicsBrushSize() { // [START android_compose_graphics_brush_size] val listColors = listOf(Color.Yellow, Color.Red, Color.Blue) val customBrush = remember { object : ShaderBrush() { override fun createShader(size: Size): Shader { return LinearGradientShader( colors = listColors, from = Offset.Zero, to = Offset(size.width / 4f, 0f), tileMode = TileMode.Mirror ) } } } Box( modifier = Modifier .requiredSize(200.dp) .background(customBrush) ) // [END android_compose_graphics_brush_size] } @Composable @Preview fun GraphicsBrushSizeRadialGradientBefore() { // [START android_compose_graphics_brush_size_radial_before] Box( modifier = Modifier .fillMaxSize() .background( Brush.radialGradient( listOf(Color(0xFF2be4dc), Color(0xFF243484)) ) ) ) // [END android_compose_graphics_brush_size_radial_before] } @Preview @Composable fun GraphicsBrushSizeRadialGradientAfter() { // [START android_compose_graphics_brush_size_radial_after] val largeRadialGradient = object : ShaderBrush() { override fun createShader(size: Size): Shader { val biggerDimension = maxOf(size.height, size.width) return RadialGradientShader( colors = listOf(Color(0xFF2be4dc), Color(0xFF243484)), center = size.center, radius = biggerDimension / 2f, colorStops = listOf(0f, 0.95f) ) } } Box( modifier = Modifier .fillMaxSize() .background(largeRadialGradient) ) // [END android_compose_graphics_brush_size_radial_after] } @Preview @Composable fun GraphicsBrushSizeRecreationExample() { // [START android_compose_graphics_brush_recreation] val colorStops = arrayOf( 0.0f to Color.Yellow, 0.2f to Color.Red, 1f to Color.Blue ) val brush = Brush.horizontalGradient(colorStops = colorStops) Box( modifier = Modifier .requiredSize(200.dp) .drawBehind { drawRect(brush = brush) // will allocate a shader to occupy the 200 x 200 dp drawing area inset(10f) { /* Will allocate a shader to occupy the 180 x 180 dp drawing area as the inset scope reduces the drawing area by 10 pixels on the left, top, right, bottom sides */ drawRect(brush = brush) inset(5f) { /* will allocate a shader to occupy the 170 x 170 dp drawing area as the inset scope reduces the drawing area by 5 pixels on the left, top, right, bottom sides */ drawRect(brush = brush) } } } ) // [END android_compose_graphics_brush_recreation] } @OptIn(ExperimentalTextApi::class) @Preview @Composable fun GraphicsImageBrush() { // [START android_compose_graphics_brush_image] val imageBrush = ShaderBrush(ImageShader(ImageBitmap.imageResource(id = R.drawable.dog))) // Use ImageShader Brush with background Box( modifier = Modifier .requiredSize(200.dp) .background(imageBrush) ) // Use ImageShader Brush with TextStyle Text( text = "Hello Android!", style = TextStyle( brush = imageBrush, fontWeight = FontWeight.ExtraBold, fontSize = 36.sp ) ) // Use ImageShader Brush with DrawScope#drawCircle() Canvas(onDraw = { drawCircle(imageBrush) }, modifier = Modifier.size(200.dp)) // [END android_compose_graphics_brush_image] } // [START android_compose_brush_custom_shader] @Language("AGSL") val CUSTOM_SHADER = """ uniform float2 resolution; layout(color) uniform half4 color; layout(color) uniform half4 color2; half4 main(in float2 fragCoord) { float2 uv = fragCoord/resolution.xy; float mixValue = distance(uv, vec2(0, 1)); return mix(color, color2, mixValue); } """.trimIndent() // [END android_compose_brush_custom_shader] // [START android_compose_brush_custom_shader_usage] val Coral = Color(0xFFF3A397) val LightYellow = Color(0xFFF8EE94) @RequiresApi(Build.VERSION_CODES.TIRAMISU) @Composable @Preview fun ShaderBrushExample() { Box(modifier = Modifier .drawWithCache { val shader = RuntimeShader(CUSTOM_SHADER) val shaderBrush = ShaderBrush(shader) shader.setFloatUniform("resolution", size.width, size.height) onDrawBehind { shader.setColorUniform( "color", android.graphics.Color.valueOf( LightYellow.red, LightYellow.green, LightYellow .blue, LightYellow.alpha ) ) shader.setColorUniform( "color2", android.graphics.Color.valueOf(Coral.red, Coral.green, Coral.blue, Coral.alpha) ) drawRect(shaderBrush) } } .fillMaxWidth() .height(200.dp) ) } // [END android_compose_brush_custom_shader_usage]
apache-2.0
3390ba4cc718d1154e9ab88c3918844b
31.699387
105
0.655253
4.381422
false
false
false
false
dahlstrom-g/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/ModuleGraph.kt
2
10346
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty") package com.intellij.ide.plugins import com.intellij.util.graph.DFSTBuilder import com.intellij.util.graph.Graph import com.intellij.util.lang.Java11Shim import org.jetbrains.annotations.ApiStatus import java.util.* @ApiStatus.Internal interface ModuleGraph : Graph<IdeaPluginDescriptorImpl> { fun getDependencies(descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> fun getDependents(descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> } @ApiStatus.Internal open class ModuleGraphBase protected constructor( private val modules: Collection<IdeaPluginDescriptorImpl>, private val directDependencies: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, private val directDependents: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, ) : ModuleGraph { override fun getNodes(): Collection<IdeaPluginDescriptorImpl> = Collections.unmodifiableCollection(modules) override fun getDependencies(descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> { return getOrEmpty(directDependencies, descriptor) } override fun getIn(descriptor: IdeaPluginDescriptorImpl): Iterator<IdeaPluginDescriptorImpl> = getDependencies(descriptor).iterator() override fun getDependents(descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> { return getOrEmpty(directDependents, descriptor) } override fun getOut(descriptor: IdeaPluginDescriptorImpl): Iterator<IdeaPluginDescriptorImpl> = getDependents(descriptor).iterator() fun builder() = DFSTBuilder(this, null, true) internal fun sorted(builder: DFSTBuilder<IdeaPluginDescriptorImpl> = builder()): SortedModuleGraph { return SortedModuleGraph( topologicalComparator = toCoreAwareComparator(builder.comparator()), modules = modules, directDependencies = directDependencies, directDependents = directDependents, ) } } internal fun createModuleGraph(plugins: Collection<IdeaPluginDescriptorImpl>): ModuleGraphBase { val moduleMap = HashMap<String, IdeaPluginDescriptorImpl>(plugins.size * 2) val modules = ArrayList<IdeaPluginDescriptorImpl>(moduleMap.size) for (module in plugins) { moduleMap.put(module.pluginId.idString, module) for (v1Module in module.modules) { moduleMap.put(v1Module.idString, module) } modules.add(module) for (item in module.content.modules) { val subModule = item.requireDescriptor() modules.add(subModule) moduleMap.put(item.name, subModule) } } val hasAllModules = moduleMap.containsKey(PluginManagerCore.ALL_MODULES_MARKER.idString) val result = Collections.newSetFromMap<IdeaPluginDescriptorImpl>(IdentityHashMap()) val directDependencies = IdentityHashMap<IdeaPluginDescriptorImpl, List<IdeaPluginDescriptorImpl>>(modules.size) for (module in modules) { val implicitDep = if (hasAllModules) getImplicitDependency(module, moduleMap) else null if (implicitDep != null) { if (module === implicitDep) { PluginManagerCore.getLogger().error("Plugin $module depends on self") } else { result.add(implicitDep) } } collectDirectDependenciesInOldFormat(module, moduleMap, result) collectDirectDependenciesInNewFormat(module, moduleMap, result) if (module.moduleName != null && module.pluginId != PluginManagerCore.CORE_ID) { // add main as implicit dependency val main = moduleMap.get(module.pluginId.idString)!! assert(main !== module) result.add(main) } if (!result.isEmpty()) { directDependencies.put(module, Java11Shim.INSTANCE.copyOfCollection(result)) result.clear() } } val directDependents = IdentityHashMap<IdeaPluginDescriptorImpl, ArrayList<IdeaPluginDescriptorImpl>>(modules.size) val edges = Collections.newSetFromMap<Map.Entry<IdeaPluginDescriptorImpl, IdeaPluginDescriptorImpl>>(HashMap()) for (module in modules) { for (inNode in getOrEmpty(directDependencies, module)) { if (edges.add(AbstractMap.SimpleImmutableEntry(inNode, module))) { // not a duplicate edge directDependents.computeIfAbsent(inNode) { ArrayList() }.add(module) } } } return object : ModuleGraphBase( modules, directDependencies, directDependents, ) {} } private fun toCoreAwareComparator(comparator: Comparator<IdeaPluginDescriptorImpl>): Comparator<IdeaPluginDescriptorImpl> { // there is circular reference between core and implementation-detail plugin, as not all such plugins extracted from core, // so, ensure that core plugin is always first (otherwise not possible to register actions - parent group not defined) // don't use sortWith here - avoid loading kotlin stdlib return Comparator { o1, o2 -> when { o1.moduleName == null && o1.pluginId == PluginManagerCore.CORE_ID -> -1 o2.moduleName == null && o2.pluginId == PluginManagerCore.CORE_ID -> 1 else -> comparator.compare(o1, o2) } } } private fun getOrEmpty(map: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, descriptor: IdeaPluginDescriptorImpl): Collection<IdeaPluginDescriptorImpl> { return map.getOrDefault(descriptor, Collections.emptyList()) } class SortedModuleGraph( val topologicalComparator: Comparator<IdeaPluginDescriptorImpl>, modules: Collection<IdeaPluginDescriptorImpl>, directDependencies: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, directDependents: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, ) : ModuleGraphBase( modules = modules.sortedWith(topologicalComparator), directDependencies = copySorted(directDependencies, topologicalComparator), directDependents = copySorted(directDependents, topologicalComparator) ) private fun copySorted( map: Map<IdeaPluginDescriptorImpl, Collection<IdeaPluginDescriptorImpl>>, comparator: Comparator<IdeaPluginDescriptorImpl>, ): Map<IdeaPluginDescriptorImpl, List<IdeaPluginDescriptorImpl>> { val result = IdentityHashMap<IdeaPluginDescriptorImpl, List<IdeaPluginDescriptorImpl>>(map.size) for (element in map.entries) { result.put(element.key, element.value.sortedWith(comparator)) } return result } /** * In 191.* and earlier builds Java plugin was part of the platform, so any plugin installed in IntelliJ IDEA might be able to use its * classes without declaring explicit dependency on the Java module. This method is intended to add implicit dependency on the Java plugin * for such plugins to avoid breaking compatibility with them. */ private fun getImplicitDependency(descriptor: IdeaPluginDescriptorImpl, idMap: Map<String, IdeaPluginDescriptorImpl>): IdeaPluginDescriptorImpl? { // skip our plugins as expected to be up-to-date whether bundled or not if (descriptor.isBundled || descriptor.packagePrefix != null || descriptor.implementationDetail) { return null } val pluginId = descriptor.pluginId if (PluginManagerCore.CORE_ID == pluginId || PluginManagerCore.JAVA_PLUGIN_ID == pluginId || PluginManagerCore.hasModuleDependencies(descriptor)) { return null } // If a plugin does not include any module dependency tags in its plugin.xml, it's assumed to be a legacy plugin // and is loaded only in IntelliJ IDEA, so it may use classes from Java plugin. return idMap.get(PluginManagerCore.JAVA_MODULE_ID.idString) } val knownNotFullyMigratedPluginIds: Set<String> = hashSetOf( // Migration started with converting intellij.notebooks.visualization to a platform plugin, but adding a package prefix to Pythonid // or com.jetbrains.pycharm.ds.customization is a difficult task that can't be done by a single shot. "Pythonid", "com.jetbrains.pycharm.ds.customization", ) private fun collectDirectDependenciesInOldFormat(rootDescriptor: IdeaPluginDescriptorImpl, idMap: Map<String, IdeaPluginDescriptorImpl>, result: MutableSet<IdeaPluginDescriptorImpl>) { for (dependency in rootDescriptor.pluginDependencies) { // check for missing optional dependency val dep = idMap.get(dependency.pluginId.idString) ?: continue if (dep.pluginId != PluginManagerCore.CORE_ID) { // ultimate plugin it is combined plugin, where some included XML can define dependency on ultimate explicitly and for now not clear, // can be such requirements removed or not if (rootDescriptor === dep) { if (rootDescriptor.pluginId != PluginManagerCore.CORE_ID) { PluginManagerCore.getLogger().error("Plugin $rootDescriptor depends on self") } } else { // e.g. `.env` plugin in an old format and doesn't explicitly specify dependency on a new extracted modules dep.content.modules.mapTo(result) { it.requireDescriptor() } result.add(dep) } } if (knownNotFullyMigratedPluginIds.contains(rootDescriptor.pluginId.idString)) { idMap.get(PluginManagerCore.CORE_ID.idString)!!.content.modules.mapTo(result) { it.requireDescriptor() } } dependency.subDescriptor?.let { collectDirectDependenciesInOldFormat(it, idMap, result) } } for (moduleId in rootDescriptor.incompatibilities) { idMap.get(moduleId.idString)?.let { result.add(it) } } } private fun collectDirectDependenciesInNewFormat(module: IdeaPluginDescriptorImpl, idMap: Map<String, IdeaPluginDescriptorImpl>, result: MutableCollection<IdeaPluginDescriptorImpl>) { for (item in module.dependencies.modules) { val descriptor = idMap.get(item.name) if (descriptor != null) { result.add(descriptor) } } for (item in module.dependencies.plugins) { val descriptor = idMap.get(item.id.idString) // fake v1 module maybe located in a core plugin if (descriptor != null && descriptor.pluginId != PluginManagerCore.CORE_ID) { result.add(descriptor) } } }
apache-2.0
3f1b4f314323daa0795d021b1f7ee33c
42.1125
139
0.741349
5.134491
false
false
false
false
kdwink/intellij-community
platform/diff-impl/tests/com/intellij/diff/DiffTestCase.kt
5
6990
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff import com.intellij.diff.comparison.ComparisonManagerImpl import com.intellij.diff.comparison.iterables.DiffIterableUtil import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.Couple import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.testFramework.UsefulTestCase import com.intellij.util.containers.HashMap import com.intellij.util.text.CharSequenceSubSequence import junit.framework.ComparisonFailure import java.util.* import java.util.concurrent.atomic.AtomicLong abstract class DiffTestCase : UsefulTestCase() { companion object { private val DEFAULT_CHAR_COUNT = 12 private val DEFAULT_CHAR_TABLE: Map<Int, Char> = { val map = HashMap<Int, Char>() listOf('\n', '\n', '\t', ' ', ' ', '.', '<', '!').forEachIndexed { i, c -> map.put(i, c) } map }() } val RNG: Random = Random() private var gotSeedException = false val INDICATOR: ProgressIndicator = DumbProgressIndicator.INSTANCE val MANAGER: ComparisonManagerImpl = ComparisonManagerImpl() override fun setUp() { super.setUp() DiffIterableUtil.setVerifyEnabled(true) } override fun tearDown() { DiffIterableUtil.setVerifyEnabled(Registry.`is`("diff.verify.iterable")) super.tearDown() } // // Assertions // fun assertTrue(actual: Boolean, message: String = "") { assertTrue(message, actual) } fun assertEquals(expected: Any?, actual: Any?, message: String = "") { assertEquals(message, expected, actual) } fun assertEquals(expected: CharSequence?, actual: CharSequence?, message: String = "") { if (!StringUtil.equals(expected, actual)) throw ComparisonFailure(message, expected?.toString(), actual?.toString()) } fun assertEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) { if (ignoreSpaces) { assertTrue(StringUtil.equalsIgnoreWhitespaces(chunk1, chunk2)) } else { if (skipLastNewline) { if (StringUtil.equals(chunk1, chunk2)) return if (StringUtil.equals(stripNewline(chunk1), chunk2)) return if (StringUtil.equals(chunk1, stripNewline(chunk2))) return assertTrue(false) } else { assertTrue(StringUtil.equals(chunk1, chunk2)) } } } // // Parsing // fun textToReadableFormat(text: CharSequence?): String { if (text == null) return "null" return "'" + text.toString().replace('\n', '*').replace('\t', '+') + "'" } fun parseSource(string: CharSequence): String = string.toString().replace('_', '\n') fun parseMatching(before: String, after: String): Couple<BitSet> { return Couple.of(parseMatching(before), parseMatching(after)) } fun parseMatching(matching: String): BitSet { val set = BitSet() matching.filterNot { it == '.' }.forEachIndexed { i, c -> if (c != ' ') set.set(i) } return set } // // Misc // fun getLineCount(document: Document): Int { return Math.max(1, document.lineCount) } infix fun Int.until(a: Int): IntRange = this..a - 1 // // AutoTests // fun doAutoTest(seed: Long, runs: Int, test: (DebugData) -> Unit) { RNG.setSeed(seed) var lastSeed: Long = -1 val debugData = DebugData() for (i in 1..runs) { if (i % 1000 == 0) println(i) try { lastSeed = getCurrentSeed() test(debugData) debugData.reset() } catch (e: Throwable) { println("Seed: " + seed) println("Runs: " + runs) println("I: " + i) println("Current seed: " + lastSeed) debugData.dump() throw e } } } fun generateText(maxLength: Int, charCount: Int, predefinedChars: Map<Int, Char>): String { val length = RNG.nextInt(maxLength + 1) val builder = StringBuilder(length) for (i in 1..length) { val rnd = RNG.nextInt(charCount) val char = predefinedChars[rnd] ?: (rnd + 97).toChar() builder.append(char) } return builder.toString() } fun generateText(maxLength: Int): String { return generateText(maxLength, DEFAULT_CHAR_COUNT, DEFAULT_CHAR_TABLE) } fun getCurrentSeed(): Long { if (gotSeedException) return -1 try { val seedField = RNG.javaClass.getDeclaredField("seed") seedField.setAccessible(true) val seedFieldValue = seedField.get(RNG) as AtomicLong return seedFieldValue.get() xor 0x5DEECE66DL } catch (e: Exception) { gotSeedException = true System.err.println("Can't get random seed: " + e.message) return -1 } } private fun stripNewline(text: CharSequence): CharSequence? { return when (StringUtil.endsWithChar(text, '\n') ) { true -> CharSequenceSubSequence(text, 0, text.length - 1) false -> null } } class DebugData() { private val data: MutableList<Pair<String, Any>> = ArrayList() fun put(key: String, value: Any) { data.add(Pair(key, value)) } fun reset() { data.clear() } fun dump() { data.forEach { println(it.first + ": " + it.second) } } } // // Helpers // open class Trio<T : Any>(val data1: T, val data2: T, val data3: T) { companion object { fun <V : Any> from(f: (ThreeSide) -> V): Trio<V> = Trio(f(ThreeSide.LEFT), f(ThreeSide.BASE), f(ThreeSide.RIGHT)) } fun <V : Any> map(f: (T) -> V): Trio<V> = Trio(f(data1), f(data2), f(data3)) fun <V : Any> map(f: (T, ThreeSide) -> V): Trio<V> = Trio(f(data1, ThreeSide.LEFT), f(data2, ThreeSide.BASE), f(data3, ThreeSide.RIGHT)) fun forEach(f: (T, ThreeSide) -> Unit): Unit { f(data1, ThreeSide.LEFT) f(data2, ThreeSide.BASE) f(data3, ThreeSide.RIGHT) } operator fun invoke(side: ThreeSide): T = side.select(data1, data2, data3) as T override fun toString(): String { return "($data1, $data2, $data3)" } override fun equals(other: Any?): Boolean { return other is Trio<*> && other.data1 == data1 && other.data2 == data2 && other.data3 == data3 } override fun hashCode(): Int { return data1.hashCode() * 37 * 37 + data2.hashCode() * 37 + data3.hashCode() } } }
apache-2.0
e30421322468a5040fcb5f7c6618e427
28.37395
140
0.653791
3.902848
false
false
false
false
DreierF/MyTargets
app/src/androidTest/java/de/dreier/mytargets/features/settings/SettingsActivityTest.kt
1
6958
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.features.settings import androidx.annotation.StringRes import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.Espresso.onData import androidx.test.espresso.Espresso.onView import androidx.test.espresso.Espresso.pressBack import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.closeSoftKeyboard import androidx.test.espresso.action.ViewActions.replaceText import androidx.test.espresso.contrib.RecyclerViewActions.scrollTo import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import de.dreier.mytargets.R import de.dreier.mytargets.features.settings.backup.provider.EBackupLocation import de.dreier.mytargets.shared.SharedApplicationInstance import de.dreier.mytargets.test.base.UITestBase import de.dreier.mytargets.test.utils.assertions.RecyclerViewAssertions.itemHasSummary import de.dreier.mytargets.test.utils.matchers.MatcherUtils.matchToolbarTitle import de.dreier.mytargets.test.utils.matchers.ParentViewMatcher.isOnForegroundFragment import de.dreier.mytargets.test.utils.matchers.ViewMatcher.clickOnPreference import org.hamcrest.Matchers.* import org.junit.* import org.junit.Assert.assertEquals import org.junit.runner.RunWith import org.threeten.bp.LocalDate import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.format.FormatStyle @RunWith(AndroidJUnit4::class) @Ignore class SettingsActivityTest : UITestBase() { @get:Rule var activityTestRule = ActivityTestRule( SettingsActivity::class.java ) private val activity: SettingsActivity get() = activityTestRule.activity @Before fun setUp() { SharedApplicationInstance.sharedPreferences .edit() .clear() .apply() SettingsManager.inputTargetZoom = 3.0f SettingsManager.inputArrowDiameterScale = 1.0f SettingsManager.backupLocation = EBackupLocation.INTERNAL_STORAGE } @Test fun settingsActivityTest() { matchToolbarTitle(activity.getString(R.string.preferences)) clickOnPreference(R.string.profile) matchToolbarTitle(activity.getString(R.string.profile)) clickOnPreference(R.string.first_name) enterText("Joe") matchPreferenceSummary(R.string.first_name, "Joe") assertEquals(SettingsManager.profileFirstName, "Joe") clickOnPreference(R.string.last_name) enterText("Doe") matchPreferenceSummary(R.string.last_name, "Doe") assertEquals(SettingsManager.profileLastName, "Doe") clickOnPreference(R.string.birthday) enterDate(1990, 2, 11) matchPreferenceSummary( R.string.birthday, DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) .format(LocalDate.of(1990, 2, 11)) ) clickOnPreference(R.string.club) enterText("Archery Club") matchPreferenceSummary(R.string.club, "Archery Club") assertEquals(SettingsManager.profileClub, "Archery Club") pressBack() clickOnPreference(R.string.overview) matchToolbarTitle(activity.getString(R.string.overview)) pressBack() clickOnPreference(R.string.input) matchToolbarTitle(activity.getString(R.string.input)) matchPreferenceSummary(R.string.target_zoom, "3.0x") clickOnPreference(R.string.target_zoom) selectFromList("5.0x") matchPreferenceSummary(R.string.target_zoom, "5.0x") assertEquals(SettingsManager.inputTargetZoom, 5.0f) matchPreferenceSummary(R.string.arrow_diameter_scale, "1.0x") clickOnPreference(R.string.arrow_diameter_scale) selectFromList("3.5x") matchPreferenceSummary(R.string.arrow_diameter_scale, "3.5x") assertEquals(SettingsManager.inputArrowDiameterScale, 3.5f) pressBack() matchToolbarTitle(activity.getString(R.string.preferences)) clickOnPreference(R.string.scoreboard) matchToolbarTitle(activity.getString(R.string.scoreboard)) pressBack() matchToolbarTitle(activity.getString(R.string.preferences)) clickOnPreference(R.string.timer) matchToolbarTitle(activity.getString(R.string.timer)) matchPreferenceSummary( R.string.timer_waiting_time, activity .resources.getQuantityString(R.plurals.second, 20, 20) ) matchPreferenceSummary( R.string.timer_shooting_time, activity .resources.getQuantityString(R.plurals.second, 120, 120) ) matchPreferenceSummary( R.string.timer_warning_time, activity .resources.getQuantityString(R.plurals.second, 30, 30) ) pressBack() // FIXME allowPermissionsIfNeeded does not seem to work/Is not called // clickOnPreference(4); // allowPermissionsIfNeeded(getActivity(), READ_EXTERNAL_STORAGE); // matchToolbarTitle(getActivity().getString(R.string.backup_action)); // pressBack(); clickOnPreference(R.string.language) selectFromList("Spanish (Español)") matchToolbarTitle("Opciones") clickOnPreference(R.string.language) selectFromList("Standard (recommended)") matchToolbarTitle("Options") } @After fun tearDown() { SharedApplicationInstance.sharedPreferences .edit() .clear() .apply() } private fun enterText(text: String) { onView(withId(android.R.id.edit)) .perform(replaceText(text), closeSoftKeyboard()) onView( allOf( withId(android.R.id.button1), withText(android.R.string.ok), isDisplayed() ) ).perform(click()) } private fun selectFromList(text: String) { onData(hasToString(startsWith(text))) .inAdapterView(withId(R.id.select_dialog_listview)) .perform(click()) } private fun matchPreferenceSummary(@StringRes text: Int, expectedSummary: String) { onView(allOf(withId(android.R.id.list), isOnForegroundFragment())) .perform(scrollTo<RecyclerView.ViewHolder>(hasDescendant(withText(text)))) .check(itemHasSummary(text, expectedSummary)) } }
gpl-2.0
741d3b734da023d96e7be45cb5efd786
34.314721
87
0.701739
4.656627
false
true
false
false
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter4/infix.kt
4
439
package com.packt.chapter4 class Age(val value: Int) { infix fun max(other: Age): Age = if (value > other.value) this else other } fun foo() { val sam = Age(37) val stef = Age(36) val oldest = sam max stef } fun toVsPair() { val pair1 = Pair("london", "uk") val pair2 = "london" to "uk" val map1 = mapOf(Pair("London", "UK"), Pair("Bucharest", "Romania")) val map2 = mapOf("London" to "UK", "Bucharest" to "Romania") }
mit
3723e9536e33b45f804b39cfc9619539
21
75
0.626424
2.74375
false
false
false
false
micgn/stock-charts
stock-server/src/main/java/de/mg/stock/server/logic/ChartBuilder.kt
1
8812
/* * Copyright 2016 Michael Gnatz. * * 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 de.mg.stock.server.logic import de.mg.stock.dto.* import de.mg.stock.server.model.DayPrice import de.mg.stock.server.model.Stock import de.mg.stock.server.util.DateTimeProvider import java.lang.Math.round import java.time.LocalDate import java.time.LocalDateTime import java.time.temporal.ChronoUnit import java.util.* import javax.ejb.Singleton import javax.inject.Inject @Singleton class ChartBuilder { @Inject lateinit private var dateTimeProvider: DateTimeProvider fun createOne(stock: Stock, points: Int, sinceParam: Optional<LocalDate>, percentages: Boolean): ChartDataDTO { val since: LocalDate? = sinceParam.orElse(null) val dto = ChartDataDTO(stock.name, dateTimeProvider.now()) val dayPoints = if (stock.instantPrices.isNotEmpty()) (points * 0.8).toInt() else points val instantPoints = if (stock.instantPrices.isNotEmpty()) (points * 0.2).toInt() else 0 val firstInstantPrice = stock.instantPrices.minBy { it.time }?.time ?: LocalDateTime.MAX val isAfterSinceAndBeforeInstantPrices = { dp: DayPrice -> val isAfterSince = since == null || dp.day.isAfter(since) || dp.day.isEqual(since) isAfterSince && dp.day.plus(1, ChronoUnit.DAYS).atStartOfDay().isBefore(firstInstantPrice) } val dayItems = stock.dayPrices.filter(isAfterSinceAndBeforeInstantPrices).sortedBy { it.day }.map { dp -> ChartItemDTO(dateTime = dp.day.atStartOfDay(), minLong = dp.min, maxLong = dp.max, averageLong = average(dp.min, dp.max), instantPrice = false) }.toMutableList() aggregate(dayItems, dayPoints) val instantItems = stock.instantPrices.sortedBy { it.time }.map { ip -> ChartItemDTO(dateTime = ip.time, minLong = ip.min, maxLong = ip.max, averageLong = average(ip.min, ip.max), instantPrice = true) }.toMutableList() aggregate(instantItems, instantPoints) dto.items.addAll(dayItems) dto.items.addAll(instantItems) if (percentages) transformToPercentages(dto.items) return dto } fun createAggregated(stocks: List<Stock>, stockWeights: List<Int>, points: Int, sinceParam: Optional<LocalDate>): ChartDataDTO { val since: LocalDate? = sinceParam.orElse(null) if (stocks.size < 2) throw RuntimeException("at least 2 stocks need to be aggregated") if (stocks.size != stockWeights.size) throw RuntimeException("different amounts of stocks and stock weights") val avgPercentsPerDate: Map<LocalDate, List<Double>> = avgPercentsPerDate(stocks, since) val aggregatedItemList = avgPercentsPerDate.keys.map { date -> val averagePercents = avgPercentsPerDate[date] ?: listOf() val aggregatedAvgPercent = averagePercents.mapIndexed { index, percent -> percent * stockWeights[index] / 100.0 }.sum() val aggregatedAvgPercentLong = round(aggregatedAvgPercent * 100.0 * 100.0) ChartItemDTO(dateTime = date.atStartOfDay(), averageLong = aggregatedAvgPercentLong, instantPrice = false) }.sortedBy { it.dateTime }.toMutableList() aggregate(aggregatedItemList, points) val dto = ChartDataDTO("aggregated", dateTimeProvider.now()) dto.items.addAll(aggregatedItemList) return dto } fun createAllInOne(stocks: List<Stock>, points: Int, since: LocalDate): AllInOneChartDto { val avgPercentsPerDate = avgPercentsPerDate(stocks, since) val items = avgPercentsPerDate.keys.map { date -> val averagePercents = avgPercentsPerDate[date] ?: listOf() val item = AllInOneChartItemDto() item.dateTime = date.atStartOfDay() for ((index, avg) in averagePercents.withIndex()) { val avgLong = round(avg * 100.0 * 100.0) val symbol = StocksEnum.of(stocks[index].symbol) item.addAverageLong(symbol, avgLong) } item }.sortedBy { it.dateTime }.toMutableList() // TODO aggregation to max points, if needed val dto = AllInOneChartDto() dto.items = items return dto } private fun avgPercentsPerDate(stocks: List<Stock>, since: LocalDate?): Map<LocalDate, List<Double>> { // create several item lists after since date val avgPerDateList = stocks.map { it.dayPrices. filter { dp -> since == null || dp.day.isAfter(since) }. map { dp -> dp.day to dp.average }.toMap() } // find intersection dates val intersectionDates = mutableSetOf<LocalDate>() avgPerDateList[0].keys.forEach { dayPrice -> intersectionDates.add(LocalDate.ofYearDay(dayPrice.year, dayPrice.dayOfYear)) } avgPerDateList.forEachIndexed { index, items -> if (index != 0) intersectionDates.retainAll(items.keys) } if (intersectionDates.size == 0) throw RuntimeException("no intersection found") // find first averages, needed for calculating percentages val firstDate = intersectionDates.min() val firstAverages = avgPerDateList.map { avgPerDate -> avgPerDate[firstDate] } if (firstAverages.contains(null)) throw RuntimeException("missing first average for percentage calculation") val avgPercentsPerDate = intersectionDates.map { date -> val averages = avgPerDateList.mapIndexed { index, avgPerDate -> val avg = avgPerDate[date] ?: 0 val first = firstAverages[index] ?: 0 val avgPercent = 1.0 * (avg - first) / first avgPercent } date to averages }.toMap() return avgPercentsPerDate } private fun aggregate(items: MutableList<ChartItemDTO>, pointsNeeded: Int): Unit { fun aggregate(updateItem: ChartItemDTO, mergeItem: ChartItemDTO): Unit { updateItem.maxLong = max(updateItem.maxLong, mergeItem.maxLong) updateItem.minLong = min(updateItem.minLong, mergeItem.minLong) updateItem.averageLong = average(updateItem.averageLong, mergeItem.averageLong) val diff = updateItem.dateTime.until(mergeItem.dateTime, ChronoUnit.SECONDS) val medium = updateItem.dateTime.plus(diff / 2, ChronoUnit.SECONDS) updateItem.dateTime = medium } var index = 0 while (items.size > pointsNeeded) { if (index + 1 < items.size) { aggregate(items[index], items[index + 1]) items.removeAt(index + 1) index += 1 } else { index = 0 } } } private fun transformToPercentages(items: List<ChartItemDTO>) { if (items.isEmpty()) return val first = items[0] val firstAvg: Double = if (first.averageLong != null) first.averageLong!!.toDouble() else if (first.minLong != null && first.maxLong != null) (first.minLong!! + first.maxLong!!) / 2.0 else throw RuntimeException("no first element for calculating percentages") items.forEach { item -> item.minLong = percent(firstAvg, item.minLong) item.maxLong = percent(firstAvg, item.maxLong) item.averageLong = percent(firstAvg, item.averageLong) } } } private fun percent(first: Double, value: Long?): Long = if (first == 0.0 || value == null || value == 0L) 0 else { val percent = (value.toDouble() - first) / first round(percent * 100.0 * 100.0) } private fun average(l1: Long?, l2: Long?): Long? = if (l1 == null) l2 else if (l2 == null) l1 else round((l1 + l2) / 2.0) private fun max(l1: Long?, l2: Long?): Long? = if (l1 == null) l2 else if (l2 == null) l1 else Math.max(l1, l2) private fun min(l1: Long?, l2: Long?): Long? = if (l1 == null) l2 else if (l2 == null) l1 else Math.min(l1, l2)
apache-2.0
aeb5cc8aa495346a09c4a37485ee5127
36.65812
139
0.628915
4.439295
false
false
false
false
arturbosch/sonar-kotlin
src/test/kotlin/io/gitlab/arturbosch/detekt/sonar/sensor/DetektSensorSpec.kt
1
2381
package io.gitlab.arturbosch.detekt.sonar.sensor import io.gitlab.arturbosch.detekt.sonar.foundation.LANGUAGE_KEY import io.gitlab.arturbosch.detekt.sonar.foundation.PATH_FILTERS_KEY import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.sonar.api.batch.fs.internal.DefaultFileSystem import org.sonar.api.batch.fs.internal.DefaultInputFile import org.sonar.api.batch.fs.internal.TestInputFileBuilder import org.sonar.api.batch.sensor.internal.SensorContextTester import org.sonar.api.config.internal.MapSettings import org.sonar.api.measures.FileLinesContext import org.sonar.api.measures.FileLinesContextFactory import org.spekframework.spek2.Spek import java.io.File class DetektSensorSpec : Spek({ val resourcesDir = File(RESOURCES_PATH) val sourceDir = File(RESOURCES_PATH, KOTLIN_PATH) val settings = MapSettings().setProperty(PATH_FILTERS_KEY, KOTLIN_PATH) lateinit var context: SensorContextTester lateinit var fileSystem: DefaultFileSystem lateinit var fileLinesContextFactory: FileLinesContextFactory lateinit var sensor: DetektSensor lateinit var fileLinesContext: FileLinesContext beforeEachTest { // Recreating all mutable objects to avoid retaining states across tests context = SensorContextTester.create(resourcesDir.absoluteFile).setSettings(settings) fileSystem = context.fileSystem() sensor = DetektSensor() fileLinesContextFactory = mockk() fileLinesContext = mockk() every { fileLinesContextFactory.createFor(any()) } returns fileLinesContext } fun addMockFile(filePath: String): DefaultInputFile { val sourceFile = File(sourceDir, filePath) val kotlinFile = TestInputFileBuilder(RESOURCES_PATH, "$KOTLIN_PATH/$filePath") .setLanguage(LANGUAGE_KEY) .initMetadata(sourceFile.readText()) .build() fileSystem.add(kotlinFile) return kotlinFile } test("executes detekt") { val file = addMockFile("KotlinFile.kt") sensor.execute(context) val issues = context.allIssues().filter { it.primaryLocation().inputComponent() == file } assertThat(issues).hasSize(7) } }) { companion object { const val RESOURCES_PATH = "src/test/resources" const val KOTLIN_PATH = "kotlin" } }
lgpl-3.0
a1a25e6a4ae98d7483c1c0152918abc7
35.075758
97
0.736245
4.450467
false
true
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/JAVA_LANG_STRING_ENTITY.kt
2
12991
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.snapshots.demo2_0_0 import org.apache.causeway.client.kroviz.snapshots.Response object JAVA_LANG_STRING_ENTITY : Response() { override val url = "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity" override val str = """ { "links": [ { "rel": "self", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.apache.causeway.restfulobjects:rels/layout", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/layout", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/layout-bs3\"" } ], "canonicalName": "demoapp.dom.types.javalang.strings.jdo.JavaLangStringJdo", "members": { "mixinProperty": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/mixinProperty", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "description": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/description", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "readWriteProperty": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/readWriteProperty", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "readOnlyPropertyDerivedLabelPositionLeft": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/readOnlyPropertyDerivedLabelPositionLeft", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "readOnlyPropertyDerivedLabelPositionTop": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/readOnlyPropertyDerivedLabelPositionTop", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "readOnlyPropertyDerivedLabelPositionRight": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/readOnlyPropertyDerivedLabelPositionRight", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "readOnlyPropertyDerivedLabelPositionNone": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/readOnlyPropertyDerivedLabelPositionNone", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "logicalTypeName": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/logicalTypeName", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "objectIdentifier": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/objectIdentifier", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "datanucleusVersionLong": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/datanucleusVersionLong", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "datanucleusVersionTimestamp": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/datanucleusVersionTimestamp", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "readOnlyOptionalProperty": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/readOnlyOptionalProperty", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "readWriteOptionalProperty": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/readWriteOptionalProperty", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "readOnlyProperty": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/readOnlyProperty", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "sources": { "rel": "urn:org.restfulobjects:rels/property", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/properties/sources", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\"" }, "actionReturningCollection": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/actionReturningCollection", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "updateReadOnlyOptionalProperty": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/updateReadOnlyOptionalProperty", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "clearHints": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/clearHints", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "updateReadOnlyProperty": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/updateReadOnlyProperty", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "updateReadOnlyPropertyWithChoices": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/updateReadOnlyPropertyWithChoices", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "actionReturning": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/actionReturning", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "inspectMetamodel": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/inspectMetamodel", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "stopImpersonating": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/stopImpersonating", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "downloadLayoutXml": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/downloadLayoutXml", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "impersonateWithRoles": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/impersonateWithRoles", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "downloadMetamodelXml": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/downloadMetamodelXml", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "downloadJdoMetadata": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/downloadJdoMetadata", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "impersonate": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/impersonate", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "recentCommands": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/recentCommands", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "openRestApi": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/openRestApi", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" }, "rebuildMetamodel": { "rel": "urn:org.restfulobjects:rels/action", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/actions/rebuildMetamodel", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\"" } }, "typeActions": { "isSubtypeOf": { "rel": "urn:org.restfulobjects:rels/invoke;typeaction=\"isSubtypeOf\"", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/type-actions/isSubtypeOf/invoke", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/type-action-result\"", "arguments": { "supertype": { "href": null } } }, "isSupertypeOf": { "rel": "urn:org.restfulobjects:rels/invoke;typeaction=\"isSupertypeOf\"", "href": "http://localhost:8080/restful/domain-types/demo.JavaLangStringEntity/type-actions/isSupertypeOf/invoke", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/type-action-result\"", "arguments": { "subtype": { "href": null } } } }, "extensions": { "friendlyName": "Java Lang String Jdo", "pluralName": "Java Lang String Jdos", "isService": false } } """ }
apache-2.0
8f1e6faf68904c99e5cd357d24c3e0d7
48.583969
138
0.690247
3.992317
false
false
false
false
breandan/idear
src/main/java/org/openasr/idear/ide/IDEService.kt
2
2093
package org.openasr.idear.ide import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.playback.commands.ActionCommand import com.intellij.openapi.util.ActionCallback object IDEService { /** * @param actionId - see [com.intellij.openapi.actionSystem.IdeActions] */ fun invokeAction(actionId: String): ActionCallback = with(ActionManager.getInstance()) { var callback: ActionCallback? = null ApplicationManager.getApplication().invokeAndWait { callback = tryToExecute(getAction(actionId), ActionCommand.getInputEvent(actionId), null, null, true) } return callback!! } fun invokeAction(actionId: AnAction): ActionCallback = with(ActionManager.getInstance()) { var callback: ActionCallback? = null ApplicationManager.getApplication().invokeAndWait { callback = tryToExecute(actionId, ActionCommand.getInputEvent(null), null, null, true) } return callback!! } fun type(vararg keys: Int) = Keyboard.type(*keys) fun pressShift() = Keyboard.pressShift() fun releaseShift() = Keyboard.releaseShift() fun type(vararg keys: Char) = Keyboard.type(*keys) fun type(string: String) = Keyboard.type(string) fun getEditor(dataContext: DataContext? = null) = if (dataContext != null) CommonDataKeys.EDITOR.getData(dataContext) else FileEditorManager.getInstance(ProjectManager .getInstance().openProjects[0]).run { selectedTextEditor ?: allEditors[0] as Editor } fun getProject(dataContext: DataContext? = null) = getEditor(dataContext)?.project }
apache-2.0
cdc0a4727a474888e64d535d9bffc145
38.490566
86
0.636885
5.285354
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/grammar/BaseHaskellParser.kt
1
3670
package org.jetbrains.grammar import com.intellij.psi.tree.IElementType import com.intellij.lang.PsiBuilder import com.intellij.lang.PsiBuilder.Marker import org.jetbrains.grammar.dumb.Rule import com.intellij.lang.ASTNode import org.jetbrains.haskell.parser.rules.BaseParser import java.util.ArrayList import org.jetbrains.grammar.dumb.NonTerminalTree import org.jetbrains.grammar.dumb.TerminalTree import org.jetbrains.grammar.dumb.Variant import org.jetbrains.grammar.dumb.Term import org.jetbrains.grammar.dumb.LazyLLParser import org.jetbrains.haskell.parser.getCachedTokens import org.jetbrains.haskell.parser.token.NEW_LINE import org.jetbrains.grammar.dumb.Terminal import org.jetbrains.haskell.parser.HaskellTokenType import org.jetbrains.grammar.dumb.NonTerminal import org.jetbrains.grammar.dumb.TerminalVariant import org.jetbrains.grammar.dumb.NonTerminalVariant abstract class BaseHaskellParser(val builder: PsiBuilder?) { companion object { var cache : Map<String, Rule>? = null } abstract fun getGrammar() : Map<String, Rule> fun mark() : Marker { return builder!!.mark() } fun parse(root: IElementType): ASTNode { val marker = builder!!.mark() val cachedTokens = getCachedTokens(builder) marker.rollbackTo() val rootMarker = mark() if (cache == null) { val grammar = getGrammar() findFirst(grammar) cache = grammar } val tree = LazyLLParser(cache!!, cachedTokens).parse() if (tree != null) { parserWithTree(tree) } while (!builder.eof()) { builder.advanceLexer() } rootMarker.done(root) return builder.treeBuilt } fun parserWithTree(tree: NonTerminalTree) { val type = tree.elementType val builderNotNull = builder!! val marker = if (type != null) builderNotNull.mark() else null for (child in tree.children) { when (child) { is NonTerminalTree -> parserWithTree(child) is TerminalTree -> { if (child.haskellToken != HaskellLexerTokens.VOCURLY && child.haskellToken != HaskellLexerTokens.VCCURLY) { if (child.haskellToken == builderNotNull.tokenType) { builderNotNull.advanceLexer() } else if (child.haskellToken != HaskellLexerTokens.SEMI) { throw RuntimeException() } } } } } marker?.done(type!!) } fun findFirst(grammar : Map<String, Rule>) { for (rule in grammar.values) { rule.makeAnalysis(grammar) } for (rule in grammar.values) { rule.makeDeepAnalysis(grammar) } } fun end(): TerminalVariant { return TerminalVariant(null) } fun end(elementType: IElementType): TerminalVariant { return TerminalVariant(elementType) } fun many(str : String, vararg next : Variant): NonTerminalVariant { val list = next.toList() return NonTerminalVariant(NonTerminal(str), list) } fun many(tokenType : HaskellTokenType, vararg next : Variant): NonTerminalVariant { val list = next.toList() return NonTerminalVariant(Terminal(tokenType), list) } fun nonTerm(rule : String): NonTerminal { return NonTerminal(rule) } fun addVar(variants : MutableList<Variant>, variant : Variant): Variant { variants.add(variant) return variant } }
apache-2.0
3c187118c2e7d56743115288d7a96010
28.604839
87
0.627793
4.693095
false
false
false
false
youdonghai/intellij-community
python/educational-core/student/src/com/jetbrains/edu/learning/editor/StudyChoiceVariantsPanel.kt
1
4517
package com.jetbrains.edu.learning.editor import com.intellij.ide.ui.LafManager import com.intellij.ide.ui.LafManagerListener import com.intellij.ide.ui.laf.darcula.DarculaLookAndFeelInfo import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.util.ui.UIUtil import com.jetbrains.edu.learning.courseFormat.Task import javafx.application.Platform import javafx.beans.value.ObservableValue import javafx.embed.swing.JFXPanel import javafx.geometry.Insets import javafx.scene.Group import javafx.scene.Scene import javafx.scene.control.ButtonBase import javafx.scene.control.CheckBox import javafx.scene.control.RadioButton import javafx.scene.control.ToggleGroup import javafx.scene.layout.VBox import javafx.scene.paint.Color import javafx.scene.text.Font import java.util.* import javax.swing.JScrollPane import javax.swing.ScrollPaneConstants class StudyChoiceVariantsPanel(task: Task) : JScrollPane() { private val LEFT_INSET = 15.0 private val RIGHT_INSET = 10.0 private val TOP_INSET = 15.0 private val BOTTOM_INSET = 10.0 private val buttons: ArrayList<ButtonBase> = ArrayList() init { val jfxPanel = JFXPanel() LafManager.getInstance().addLafManagerListener(StudyLafManagerListener(jfxPanel)) Platform.runLater { val group = Group() val scene = Scene(group, getSceneBackground()) jfxPanel.scene = scene val vBox = VBox() vBox.spacing = 10.0 vBox.padding = Insets(TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET) if (task.isMultipleChoice) { for ((index, variant) in task.choiceVariants.withIndex()) { val isSelected = task.selectedVariants.contains(index) val checkBox = CheckBox(variant) checkBox.isSelected = isSelected checkBox.selectedProperty().addListener(createSelectionListener(task, index)) setUpButtonStyle(checkBox, scene) vBox.children.add(checkBox) buttons.add(checkBox) } } else { val toggleGroup = ToggleGroup() for ((index, variant) in task.choiceVariants.withIndex()) { val isSelected = task.selectedVariants.contains(index) val radioButton = RadioButton(variant) radioButton.toggleGroup = toggleGroup radioButton.isSelected = isSelected radioButton.selectedProperty().addListener(createSelectionListener(task, index)) setUpButtonStyle(radioButton, scene) vBox.children.add(radioButton) buttons.add(radioButton) } } group.children.add(vBox) } setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) setViewportView(jfxPanel) } private fun getSceneBackground(): Color{ val isDarcula = LafManager.getInstance().currentLookAndFeel is DarculaLookAndFeelInfo val panelBackground = if (isDarcula) UIUtil.getPanelBackground() else UIUtil.getTextFieldBackground() return Color.rgb(panelBackground.red, panelBackground.green, panelBackground.blue) } private fun createSelectionListener(task: Task, index: Int): (ObservableValue<out Boolean>, Boolean, Boolean) -> Unit { return { observableValue, wasSelected, isSelected -> if (isSelected) { task.selectedVariants.add(index) } else { task.selectedVariants.remove(index) } } } private fun setUpButtonStyle(button: ButtonBase, scene: Scene) { button.isWrapText = true button.maxWidthProperty().bind(scene.widthProperty().subtract(LEFT_INSET).subtract(RIGHT_INSET)) button.font = Font.font((EditorColorsManager.getInstance().globalScheme.editorFontSize + 2).toDouble()) setButtonLaf(button) } private fun setButtonLaf(button: ButtonBase) { val darcula = LafManager.getInstance().currentLookAndFeel is DarculaLookAndFeelInfo val stylesheetPath = if (darcula) "/style/buttonsDarcula.css" else "/style/buttons.css" button.stylesheets.removeAll() button.stylesheets.add(javaClass.getResource(stylesheetPath).toExternalForm()) } private inner class StudyLafManagerListener(val jfxPanel: JFXPanel) : LafManagerListener { override fun lookAndFeelChanged(manager: LafManager) { Platform.runLater { val panelBackground = UIUtil.getPanelBackground() jfxPanel.scene.fill = Color.rgb(panelBackground.red, panelBackground.green, panelBackground.blue) for (button in buttons) { setButtonLaf(button) } jfxPanel.repaint() } } } }
apache-2.0
c9a17ac9a3f4463541afe27aa73af820
36.330579
121
0.727031
4.581136
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2018/Day17.kt
1
3878
package com.nibado.projects.advent.y2018 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Point import com.nibado.projects.advent.Rectangle import com.nibado.projects.advent.collect.CharMap import com.nibado.projects.advent.resourceRegex import java.util.* import kotlin.math.max object Day17 : Day { private val regex = "(x|y)=([0-9]+), (x|y)=([0-9]+)\\.\\.([0-9]+)".toRegex() private val input = resourceRegex(2018, 17, regex) .map { it.drop(1) } .map { (a1, v1, a2, v2a, v2b) -> Scan(a1[0], v1.toInt(), a2[0], IntRange(v2a.toInt(), v2b.toInt())) } val map : CharMap by lazy { buildMap().also { flow(it) } } private fun buildMap(): CharMap { val max = input.map { it.rect().right }.reduce { a, p -> Point(max(a.x, p.x), max(a.y, p.y)) } val map = CharMap(max.x + 1, max.y + 1, '.', '#') for (s in input) { if (s.axis1 == 'x') { map.drawVertical(s.value1, s.value2) } else { map.drawHorizontal(s.value1, s.value2) } } return map } private fun flow(map: CharMap) { val down = Point(0, 1) val consider = Stack<Point>() consider += Point(500, 0) + down while (consider.isNotEmpty()) { val cur = consider.pop() map[cur] = '|' if (!map.inBounds(cur + down)) { continue } if (map.canPlace(cur + down)) { consider += cur + down continue } else { val flow = map.flow(cur) val c = if (flow.contained) '~' else '|' flow.points.forEach { map[it] = c } if (flow.contained) { if (map.inBounds(cur.up())) { consider += cur.up() } } else { consider += flow.points.filter { map.inBounds(it.down()) && map[it.down()] == '.' } } } } } private fun CharMap.flow(p: Point): Flow { val points = mutableListOf<Point>() points += p fun scan(p: Point, dir: Point, points: MutableList<Point>) : Boolean { var cur = p while(true) { cur += dir if(!inBounds(cur)) { return false } if(get(cur) == '#') { return true } val below = cur.down() if(inBounds(below) && get(below) in setOf('#', '~')) { points += cur } else if(get(below) != '|'){ points += cur return false } else { return false } } } val wallLeft = scan(p, Point(-1, 0), points) val wallRight = scan(p, Point(1, 0), points) return Flow(points, wallLeft && wallRight) } private fun CharMap.canPlace(p: Point) = inBounds(p) && this[p] == '.' private fun CharMap.minY() = map.points { c -> c == '#' }.minByOrNull { it.y }!!.y override fun part1() = map.minY().let { minY -> map.points { it == '~' || it == '|'}.count { it.y >= minY } } override fun part2() = map.minY().let { minY -> map.points { it == '~'}.count { it.y >= minY } } data class Scan(val axis1: Char, val value1: Int, val axis2: Char, val value2: IntRange) { fun rect() = if (axis1 == 'x') { Rectangle(Point(value1, value2.start), Point(value1, value2.endInclusive)) } else { Rectangle(Point(value2.start, value1), Point(value2.endInclusive, value1)) } } data class Flow(val points: List<Point>, val contained: Boolean) }
mit
e1b29eccbda537cc2b44b0b9c1b2f9f2
31.596639
113
0.472151
3.866401
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/persistence/storage/dao/PersistentItemDaoImpl.kt
2
4623
package org.stepic.droid.persistence.storage.dao import android.content.ContentValues import android.database.Cursor import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.Single import org.stepic.droid.di.storage.StorageSingleton import org.stepic.droid.persistence.model.DownloadTask import org.stepic.droid.persistence.model.PersistentItem import org.stepic.droid.persistence.model.Structure import org.stepic.droid.persistence.model.isCorrect import org.stepic.droid.persistence.storage.structure.DBStructurePersistentItem import org.stepic.droid.storage.dao.DaoBase import org.stepic.droid.storage.dao.IDao import org.stepic.droid.storage.operations.DatabaseOperations import org.stepic.droid.util.getBoolean import javax.inject.Inject @StorageSingleton class PersistentItemDaoImpl @Inject constructor( databaseOperations: DatabaseOperations ): DaoBase<PersistentItem>(databaseOperations), IDao<PersistentItem>, PersistentItemDao { override fun getDbName() = DBStructurePersistentItem.PERSISTENT_ITEMS override fun getDefaultPrimaryColumn() = DBStructurePersistentItem.Columns.ORIGINAL_PATH // actually ORIGINAL_PATH + STEP override fun getDefaultPrimaryValue(persistentObject: PersistentItem): String = persistentObject.task.originalPath override fun getContentValues(persistentObject: PersistentItem) = ContentValues().apply { put(DBStructurePersistentItem.Columns.ORIGINAL_PATH, persistentObject.task.originalPath) put(DBStructurePersistentItem.Columns.LOCAL_FILE_NAME, persistentObject.localFileName) put(DBStructurePersistentItem.Columns.LOCAL_FILE_DIR, persistentObject.localFileDir) put(DBStructurePersistentItem.Columns.IS_IN_APP_INTERNAL_DIR, if (persistentObject.isInAppInternalDir) 1 else 0) put(DBStructurePersistentItem.Columns.DOWNLOAD_ID, persistentObject.downloadId) put(DBStructurePersistentItem.Columns.STATUS, persistentObject.status.name) put(DBStructurePersistentItem.Columns.COURSE, persistentObject.task.structure.course) put(DBStructurePersistentItem.Columns.SECTION, persistentObject.task.structure.section) put(DBStructurePersistentItem.Columns.UNIT, persistentObject.task.structure.unit) put(DBStructurePersistentItem.Columns.LESSON, persistentObject.task.structure.lesson) put(DBStructurePersistentItem.Columns.STEP, persistentObject.task.structure.step) } override fun parsePersistentObject(cursor: Cursor) = PersistentItem( localFileName = cursor.getString(cursor.getColumnIndex(DBStructurePersistentItem.Columns.LOCAL_FILE_NAME)), localFileDir = cursor.getString(cursor.getColumnIndex(DBStructurePersistentItem.Columns.LOCAL_FILE_DIR)), isInAppInternalDir = cursor.getBoolean(DBStructurePersistentItem.Columns.IS_IN_APP_INTERNAL_DIR), downloadId = cursor.getLong(cursor.getColumnIndex(DBStructurePersistentItem.Columns.DOWNLOAD_ID)), status = PersistentItem.Status.valueOf(cursor.getString(cursor.getColumnIndex(DBStructurePersistentItem.Columns.STATUS))), task = DownloadTask( originalPath = cursor.getString(cursor.getColumnIndex(DBStructurePersistentItem.Columns.ORIGINAL_PATH)), structure = Structure( course = cursor.getLong(cursor.getColumnIndex(DBStructurePersistentItem.Columns.COURSE)), section = cursor.getLong(cursor.getColumnIndex(DBStructurePersistentItem.Columns.SECTION)), unit = cursor.getLong(cursor.getColumnIndex(DBStructurePersistentItem.Columns.UNIT)), lesson = cursor.getLong(cursor.getColumnIndex(DBStructurePersistentItem.Columns.LESSON)), step = cursor.getLong(cursor.getColumnIndex(DBStructurePersistentItem.Columns.STEP)) ) ) ) override fun getItems(selector: Map<String, String>): Single<List<PersistentItem>> = Single.fromCallable { if (selector.isEmpty()) getAll() else getAll(selector) } override fun getItem(selector: Map<String, String>): Maybe<PersistentItem> = Maybe.create { emitter -> get(selector)?.let(emitter::onSuccess) ?: emitter.onComplete() } override fun getAllCorrectItems(): Observable<List<PersistentItem>> = Observable.fromCallable { val statuses = PersistentItem.Status.values().filter(PersistentItem.Status::isCorrect).joinToString { "'${it.name}'" } getAllInRange(DBStructurePersistentItem.Columns.STATUS, statuses) } }
apache-2.0
7688be90465853ab7f328ae235d75313
58.282051
141
0.758382
5.21195
false
false
false
false
allotria/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/configuration/PackageSearchGeneralConfiguration.kt
1
1398
package com.jetbrains.packagesearch.intellij.plugin.configuration import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.project.Project import com.intellij.util.xmlb.annotations.OptionTag @State( name = "PackageSearchGeneralConfiguration", storages = [(Storage(PackageSearchGeneralConfiguration.StorageFileName))] ) class PackageSearchGeneralConfiguration : BaseState(), PersistentStateComponent<PackageSearchGeneralConfiguration> { companion object { const val StorageFileName = "packagesearch.xml" fun getInstance(project: Project): PackageSearchGeneralConfiguration = ServiceManager.getService(project, PackageSearchGeneralConfiguration::class.java) } override fun getState(): PackageSearchGeneralConfiguration? = this override fun loadState(state: PackageSearchGeneralConfiguration) { this.copyFrom(state) } @get:OptionTag("REFRESH_PROJECT") var refreshProject by property(true) @get:OptionTag("ALLOW_CHECK_FOR_PACKAGE_UPGRADES") var allowCheckForPackageUpgrades by property(true) @get:OptionTag("AUTO_SCROLL_TO_SOURCE") var autoScrollToSource by property(true) }
apache-2.0
f78ead3bc8ace07c1f86ffc6ba86cd72
35.789474
116
0.79113
5.216418
false
true
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/ide/actions/runAnything/RunAnythingContextRecentDirectoryCache.kt
2
1134
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions.runAnything import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.util.xmlb.XmlSerializerUtil import com.intellij.util.xmlb.annotations.XCollection @State(name = "RunAnythingContextRecentDirectoryCache", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)]) class RunAnythingContextRecentDirectoryCache : PersistentStateComponent<RunAnythingContextRecentDirectoryCache.State> { private val mySettings = State() override fun getState(): State { return mySettings } override fun loadState(state: State) { XmlSerializerUtil.copyBean(state, mySettings) } class State { @XCollection(elementName = "recentPaths") val paths: MutableList<String> = mutableListOf() } companion object { fun getInstance(project: Project): RunAnythingContextRecentDirectoryCache { return ServiceManager.getService(project, RunAnythingContextRecentDirectoryCache::class.java) } } }
apache-2.0
0a8d6666f022ba05bfb447c6d661edbe
34.46875
140
0.785714
4.887931
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/completion/reppolicy/RepPolicyCompletionContributor.kt
1
4108
package com.aemtools.completion.reppolicy import com.aemtools.common.constant.const import com.aemtools.completion.model.editconfig.XmlAttributeDefinition import com.aemtools.common.util.findParentByType import com.aemtools.service.ServiceFacade import com.intellij.codeInsight.completion.CompletionContributor import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.completion.XmlAttributeInsertHandler import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.patterns.PlatformPatterns import com.intellij.psi.impl.source.xml.XmlTagImpl import com.intellij.psi.xml.XmlAttribute import com.intellij.psi.xml.XmlTag import com.intellij.psi.xml.XmlToken import com.intellij.util.ProcessingContext /** * @author Dmytro Troynikov. */ class RepPolicyCompletionContributor : CompletionContributor { constructor() { extend(CompletionType.BASIC, PlatformPatterns.psiElement(), RepPolicyCompletionProvider()) } } private class RepPolicyCompletionProvider : CompletionProvider<CompletionParameters>() { private val repPolicyRepository = ServiceFacade.getRepPolicyRepository() override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { if (!accept(parameters)) { return } val currentElement = parameters.position as XmlToken val currentPositionType = extractCurrentPositionType(currentElement) val variantsGenerator = variantsProviders[currentPositionType] ?: return result.addAllElements(variantsGenerator(parameters, currentElement)) } private val variantsForName: (CompletionParameters, XmlToken) -> List<LookupElement> = { _, token -> val tag = token.findParentByType(XmlTag::class.java) val tagDefinition = repPolicyRepository.getTagDefinitionByName((tag as XmlTagImpl).name) val tagAttributes = tag.attributes.map { it.name } val attributes = tagDefinition.attributes.filter { !tagAttributes.contains(it.name) } attributes.map { LookupElementBuilder.create(it.name).withInsertHandler( XmlAttributeInsertHandler() ) } } private val variantsForValue: (CompletionParameters, XmlToken) -> List<LookupElement> = { _, token -> val tag = token.findParentByType(XmlTag::class.java) val tagDefinition = repPolicyRepository.getTagDefinitionByName((tag as XmlTagImpl).name) val attributeName = (token.findParentByType(XmlAttribute::class.java) as XmlAttribute).name val attributeDefinition: XmlAttributeDefinition? = tagDefinition.attributes.find { it.name == attributeName } attributeDefinition?.values.orEmpty().map { LookupElementBuilder.create(it) } } private val variantsForTagName: (CompletionParameters, XmlToken) -> List<LookupElement> = { _, token -> val parentTag = token.findParentByType(XmlTag::class.java) ?.findParentByType(XmlTag::class.java) val tagDefinition = repPolicyRepository.getTagDefinitionByName( (parentTag as XmlTagImpl).name) tagDefinition.childNodes.map { LookupElementBuilder.create(it) } } private fun extractCurrentPositionType(token: XmlToken): String { val currentPositionType = token.tokenType.toString() if (currentPositionType == const.xml.XML_ATTRIBUTE_NAME && (token.findParentByType(XmlTag::class.java) as XmlTagImpl).name.contains( const.IDEA_STRING_CARET_PLACEHOLDER)) { return const.xml.XML_TAG_NAME } return currentPositionType } private fun accept(parameters: CompletionParameters): Boolean { return const.REP_POLICY == parameters.originalFile.name } private val variantsProviders = mapOf( const.xml.XML_ATTRIBUTE_NAME to variantsForName, const.xml.XML_ATTRIBUTE_VALUE to variantsForValue, const.xml.XML_TAG_NAME to variantsForTagName ) }
gpl-3.0
ce7e8772677e1d8170fa23fca49b42bd
36.688073
113
0.775316
4.850059
false
false
false
false
ncipollo/android-viper
viper/src/main/kotlin/viper/view/adapters/ViperRecyclerAdapter.kt
1
3638
package viper.view.adapters import android.os.Bundle import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import rx.Observable import rx.subjects.PublishSubject import viper.presenters.ActivityPresenter import viper.presenters.CollectionPresenter /** * A recycler adapter which removes some of the boiler plate needed to bind the presenter * and the adapter. * Created by Nick Cipollo on 11/7/16. */ class ViperRecyclerAdapter<ListItem, VH : ViperViewHolder<ListItem>, P : CollectionPresenter<*, ListItem, *>>(val vhBuilder: (ViewGroup, Int) -> VH) : CollectionAdapter<P>, RecyclerView.Adapter<VH>() { constructor(vhBuilder: (ViewGroup) -> VH) : this({ parent, type -> vhBuilder(parent) }) private val actionSubject: PublishSubject<AdapterAction> = PublishSubject.create<AdapterAction>() override val actionObserver: Observable<AdapterAction> get() = actionSubject.asObservable() override var presenter: P? = null override val activityPresenter: ActivityPresenter<*, *>? get() = presenter?.activityPresenter override val args: Bundle get() = presenter?.args ?: Bundle() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH { val vh = vhBuilder(parent, viewType) vh.actionSubject = actionSubject return vh } override fun onBindViewHolder(holder: VH, position: Int) { presenter?.getListItem(position)?.let { holder.bindListItem(it) } } override fun getItemCount(): Int = presenter?.count ?: 0 override fun onCollectionUpdated() = notifyDataSetChanged() override fun onItemUpdated(itemIndex: Int) = notifyItemChanged(itemIndex) override fun onViewAttachedToWindow(holder: VH) { val index = holder.adapterPosition if (index != RecyclerView.NO_POSITION) { presenter?.positionMovedOnScreen(index) } } override fun onViewDetachedFromWindow(holder: VH) { val index = holder.adapterPosition if (index != RecyclerView.NO_POSITION) { presenter?.positionMovedOffScreen(index) } } } /** * A view holder which is intended to be used with the ViperRecyclerAdapter. Subclasses may * override onTakeView to setup references to the pertinent views, then bindListItem to * associate the presenter item with the view. */ open class ViperViewHolder<in ListItem>(val view: View) : RecyclerView.ViewHolder(view) { internal lateinit var actionSubject: PublishSubject<AdapterAction> constructor(layoutId: Int, parent: ViewGroup) : this(LayoutInflater.from(parent.context) .inflate(layoutId, parent, false)) init { takeView(view) } private fun takeView(view: View) = onTakeView(view) /** * Called when the view holder has an inflated root view. This can be used to obtain * references to the appropriate views. */ open fun onTakeView(view: View) = Unit /** * Called when data from the list item should be bound to the view. */ open fun bindListItem(item: ListItem) = Unit /** * Subclasses may call this method to send an action to the presenter. This will typically be * tied to an event from one of the held views. */ fun sendAction(actionId: Int = CollectionPresenter.ACTION_ITEM_SELECTED) { val itemIndex = adapterPosition if (itemIndex != RecyclerView.NO_POSITION) { actionSubject.onNext(AdapterAction(actionId, itemIndex)) } } }
mit
1f61b3ddc4b154e5bb2d945ff0aa2506
31.20354
101
0.68994
4.688144
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/SelectContentStep.kt
1
1377
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl.content import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.ui.content.Content import com.intellij.ui.content.TabbedContent import javax.swing.Icon open class SelectContentStep : BaseListPopupStep<Content> { constructor(contents: Array<Content>) : super(null, *contents) constructor(contents: List<Content>) : super(null, contents) override fun isSpeedSearchEnabled(): Boolean = true override fun getIconFor(value: Content): Icon? = value.icon override fun getTextFor(value: Content): String { return value.asMultiTabbed()?.titlePrefix ?: value.displayName ?: super.getTextFor(value) } override fun hasSubstep(value: Content): Boolean = value.asMultiTabbed() != null override fun onChosen(value: Content, finalChoice: Boolean): PopupStep<*>? { val tabbed = value.asMultiTabbed() if (tabbed == null) { value.manager?.setSelectedContentCB(value, true, true) return PopupStep.FINAL_CHOICE } else { return SelectContentTabStep(tabbed) } } private fun Content.asMultiTabbed(): TabbedContent? = if (this is TabbedContent && hasMultipleTabs()) this else null }
apache-2.0
fdb6ab7dfed9819a83d9755bbbd04da1
37.25
140
0.748003
4.122754
false
false
false
false
io53/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/gateway/GatewaySender.kt
1
1696
package com.ruuvi.station.gateway import android.content.Context import android.location.Location import android.util.Log import com.google.gson.GsonBuilder import com.koushikdutta.ion.Ion import com.ruuvi.station.app.preferences.Preferences import com.ruuvi.station.database.tables.RuuviTagEntity import com.ruuvi.station.gateway.data.ScanEvent import com.ruuvi.station.gateway.data.ScanLocation import timber.log.Timber class GatewaySender(private val context: Context, private val preferences: Preferences) { private val gson = GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create() fun sendData(tag: RuuviTagEntity, location: Location?) { val backendUrl = preferences.gatewayUrl if (backendUrl.isNotEmpty()) { Timber.d("sendData for [${tag.name}] (${tag.id}) to ${tag.gatewayUrl}") var scanLocation: ScanLocation? = null location?.let { scanLocation = ScanLocation( it.latitude, it.longitude, it.accuracy ) } Ion.getDefault(context).configure().gson = gson val eventBatch = ScanEvent(context) eventBatch.location = scanLocation eventBatch.tags.add(tag) Ion.with(context) .load(backendUrl) .setLogging("HTTP_LOGS", Log.DEBUG) .setJsonPojoBody(eventBatch) .asJsonObject() .setCallback { e, _ -> if (e != null) { Timber.e(e, "Batch sending failed to $backendUrl") } } } } }
mit
271819805e15d894521fec8b1984afb8
34.354167
89
0.591392
4.510638
false
false
false
false
leafclick/intellij-community
platform/platform-api/src/com/intellij/openapi/rd/DisposableEx.kt
1
2017
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.rd import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.use import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rd.util.lifetime.LifetimeDefinition import com.jetbrains.rd.util.lifetime.isAlive import com.jetbrains.rd.util.lifetime.onTermination @Deprecated("Use implementation from `intellij.platform.util.ex` instead.", ReplaceWith("disposable.use(block)")) inline fun using(disposable: Disposable, block: () -> Unit): Unit = disposable.use { block() } fun Disposable.defineNestedLifetime(): LifetimeDefinition { val lifetimeDefinition = Lifetime.Eternal.createNested() if (Disposer.isDisposing(this) || Disposer.isDisposed(this)) { lifetimeDefinition.terminate() return lifetimeDefinition } this.attach { if (lifetimeDefinition.lifetime.isAlive) lifetimeDefinition.terminate() } return lifetimeDefinition } fun Disposable.createLifetime(): Lifetime = this.defineNestedLifetime().lifetime fun Disposable.doIfAlive(action: (Lifetime) -> Unit) { val disposableLifetime: Lifetime? if(Disposer.isDisposed(this)) return try { disposableLifetime = this.createLifetime() } catch(t : Throwable){ //do nothing, there is no other way to handle disposables return } action(disposableLifetime) } fun Lifetime.createNestedDisposable(debugName: String = "lifetimeToDisposable"): Disposable { val d = Disposer.newDisposable(debugName) this.onTermination { Disposer.dispose(d) } return d } fun Disposable.attachChild(disposable: Disposable) { Disposer.register(this, disposable) } @Suppress("ObjectLiteralToLambda") // non-object lambdas fuck up the disposer fun Disposable.attach(disposable: () -> Unit) { Disposer.register(this, object : Disposable { override fun dispose() { disposable() } }) }
apache-2.0
b0cca7e04344fd506b9a2f0cd1da8407
31.532258
140
0.762023
4.264271
false
false
false
false
kpi-ua/ecampus-client-android
app/src/main/java/com/goldenpiedevs/schedule/app/ui/view/KeyboardHelper.ext.kt
1
2162
package com.goldenpiedevs.schedule.app.ui.view import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.appcompat.app.AppCompatActivity fun AppCompatActivity.hideSoftKeyboard() { try { val inputMethodManager = getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager val v = currentFocus if (v != null) { inputMethodManager.hideSoftInputFromWindow(v.windowToken, 0) } } catch (e: Exception) { } } fun androidx.fragment.app.Fragment.hideSoftKeyboard() { try { val imm = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view!!.windowToken, 0) } catch (e: Exception) { } } fun AppCompatActivity.showSoftKeyboard() { try { val inputMethodManager = getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.showSoftInput(currentFocus, 0) } catch (e: Exception) { } } fun Context.showSoftKeyboard(editText: EditText) { try { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED) } catch (e: Exception) { } } fun Context.hideSoftKeyboard(editText: EditText?) { try { val inputMethodManager = getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager if (editText != null) { inputMethodManager.hideSoftInputFromWindow(editText.windowToken, 0) } } catch (e: Exception) { } } fun Context.hideSoftKeyboard(vararg views: View) { try { val inputMethodManager = getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager for (view in views) { inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) } } catch (e: Exception) { } } fun AppCompatActivity.hideSoftKeyboard(vararg views: View) { hideSoftKeyboard() for (view in views) { view.clearFocus() } }
apache-2.0
297f6f45429258000c11fd8f377e7cd5
27.460526
111
0.703515
4.741228
false
false
false
false
LouisCAD/Splitties
modules/resources/src/androidMain/kotlin/splitties/resources/DimenResources.kt
1
4988
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NOTHING_TO_INLINE") @file:OptIn(InternalSplittiesApi::class) package splitties.resources import android.content.Context import android.util.TypedValue import android.view.View import androidx.annotation.AttrRes import androidx.annotation.DimenRes import androidx.fragment.app.Fragment import splitties.experimental.InternalSplittiesApi import splitties.init.appCtx inline fun Context.dimen(@DimenRes dimenResId: Int): Float = resources.getDimension(dimenResId) inline fun Fragment.dimen(@DimenRes dimenResId: Int) = context!!.dimen(dimenResId) inline fun View.dimen(@DimenRes dimenResId: Int) = context.dimen(dimenResId) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appDimen(@DimenRes dimenResId: Int) = appCtx.dimen(dimenResId) inline fun Context.dimenPxSize( @DimenRes dimenResId: Int ): Int = resources.getDimensionPixelSize(dimenResId) inline fun Fragment.dimenPxSize(@DimenRes dimenResId: Int) = context!!.dimenPxSize(dimenResId) inline fun View.dimenPxSize(@DimenRes dimenResId: Int) = context.dimenPxSize(dimenResId) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appDimenPxSize(@DimenRes dimenResId: Int) = appCtx.dimenPxSize(dimenResId) inline fun Context.dimenPxOffset( @DimenRes dimenResId: Int ): Int = resources.getDimensionPixelOffset(dimenResId) inline fun Fragment.dimenPxOffset(@DimenRes dimenResId: Int) = context!!.dimenPxOffset(dimenResId) inline fun View.dimenPxOffset(@DimenRes dimenResId: Int) = context.dimenPxOffset(dimenResId) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appDimenPxOffset(@DimenRes dimenResId: Int) = appCtx.dimenPxOffset(dimenResId) private fun TypedValue.checkOfDimensionType() { require(type == TypedValue.TYPE_DIMENSION) { unexpectedThemeAttributeTypeErrorMessage(expectedKind = "dimension") } } // Styled resources below fun Context.styledDimen(@AttrRes attr: Int): Float = withResolvedThemeAttribute(attr) { checkOfDimensionType() TypedValue.complexToDimension(data, resources.displayMetrics) } inline fun Fragment.styledDimen(@AttrRes attr: Int) = context!!.styledDimen(attr) inline fun View.styledDimen(@AttrRes attr: Int) = context.styledDimen(attr) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appStyledDimen(@AttrRes attr: Int) = appCtx.styledDimen(attr) fun Context.styledDimenPxSize(@AttrRes attr: Int): Int = withResolvedThemeAttribute(attr) { checkOfDimensionType() TypedValue.complexToDimensionPixelSize(data, resources.displayMetrics) } inline fun Fragment.styledDimenPxSize(@AttrRes attr: Int) = context!!.styledDimenPxSize(attr) inline fun View.styledDimenPxSize(@AttrRes attr: Int) = context.styledDimenPxSize(attr) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appStyledDimenPxSize(@AttrRes attr: Int) = appCtx.styledDimenPxSize(attr) fun Context.styledDimenPxOffset( @AttrRes attr: Int ): Int = withResolvedThemeAttribute(attr) { checkOfDimensionType() TypedValue.complexToDimensionPixelOffset(data, resources.displayMetrics) } inline fun Fragment.styledDimenPxOffset(@AttrRes attr: Int) = context!!.styledDimenPxOffset(attr) inline fun View.styledDimenPxOffset(@AttrRes attr: Int) = context.styledDimenPxOffset(attr) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appStyledDimenPxOffset(@AttrRes attr: Int) = appCtx.styledDimenPxOffset(attr)
apache-2.0
9fe51856fa5bd4803e81f17f70327254
37.666667
109
0.779471
4.497746
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/ResetPasswordViewModel.kt
1
7449
package com.kickstarter.viewmodels import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.models.OptimizelyFeature import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.rx.transformers.Transformers.errors import com.kickstarter.libs.rx.transformers.Transformers.values import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.extensions.isEmail import com.kickstarter.models.User import com.kickstarter.services.apiresponses.ErrorEnvelope import com.kickstarter.ui.IntentKey import com.kickstarter.ui.activities.ResetPasswordActivity import com.kickstarter.ui.data.ResetPasswordScreenState import rx.Notification import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface ResetPasswordViewModel { interface Inputs { /** Call when the email field changes. */ fun email(emailInput: String) /** Call when the reset password button is clicked. */ fun resetPasswordClick() } interface Outputs { /** Emits a boolean that determines if the form is in the progress of being submitted. */ fun isFormSubmitting(): Observable<Boolean> /** Emits a boolean that determines if the form validation is passing. */ fun isFormValid(): Observable<Boolean> /** Emits when password reset is completed successfully. */ fun resetLoginPasswordSuccess(): Observable<Void> /** Emits when password reset is completed successfully. */ fun resetFacebookLoginPasswordSuccess(): Observable<Void> /** Emits when password reset fails. */ fun resetError(): Observable<String> /** Fill the view's email address when it's supplied from the intent. */ fun prefillEmail(): Observable<String> /** Fill the view's for forget or reset password state */ fun resetPasswordScreenStatus(): Observable<ResetPasswordScreenState> } class ViewModel(val environment: Environment) : ActivityViewModel<ResetPasswordActivity>(environment), Inputs, Outputs { private val client = requireNotNull(environment.apiClient()) private val email = PublishSubject.create<String>() private val resetPasswordClick = PublishSubject.create<Void>() private val isFormSubmitting = PublishSubject.create<Boolean>() private val isFormValid = PublishSubject.create<Boolean>() private val resetLoginPasswordSuccess = PublishSubject.create<Void>() private val resetFacebookLoginPasswordSuccess = PublishSubject.create<Void>() private val resetError = PublishSubject.create<ErrorEnvelope>() private val prefillEmail = BehaviorSubject.create<String>() private val resetPasswordScreenStatus = BehaviorSubject.create<ResetPasswordScreenState>() private val ERROR_GENERIC = "Something went wrong, please try again." val inputs: Inputs = this val outputs: Outputs = this // TODO removed with feature flag ANDROID_FACEBOOK_LOGIN_REMOVE private var resetPasswordScreenState: ResetPasswordScreenState? = null init { intent() .filter { it.hasExtra(IntentKey.EMAIL) } .map { it.getStringExtra(IntentKey.EMAIL) } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .compose(bindToLifecycle()) .subscribe { this.prefillEmail.onNext(it) resetPasswordScreenState = ResetPasswordScreenState.ForgetPassword resetPasswordScreenStatus.onNext(ResetPasswordScreenState.ForgetPassword) } val resetFacebookPasswordFlag = intent() .filter { it.hasExtra(IntentKey.RESET_PASSWORD_FACEBOOK_LOGIN) && environment.optimizely()?.isFeatureEnabled( OptimizelyFeature.Key.ANDROID_FACEBOOK_LOGIN_REMOVE ) == true } .map { it.getBooleanExtra(IntentKey.RESET_PASSWORD_FACEBOOK_LOGIN, false) } resetFacebookPasswordFlag .compose(bindToLifecycle()) .subscribe { if (it) { resetPasswordScreenState = ResetPasswordScreenState.ResetPassword resetPasswordScreenStatus.onNext(ResetPasswordScreenState.ResetPassword) } else { resetPasswordScreenState = ResetPasswordScreenState.ForgetPassword resetPasswordScreenStatus.onNext(ResetPasswordScreenState.ForgetPassword) } } this.email .map { it.isEmail() } .compose(bindToLifecycle()) .subscribe(this.isFormValid) val resetPasswordNotification = this.email .compose<String>(Transformers.takeWhen(this.resetPasswordClick)) .switchMap(this::submitEmail) .share() resetPasswordNotification .compose(values()) .compose(bindToLifecycle()) .subscribe { when (resetPasswordScreenState) { ResetPasswordScreenState.ResetPassword -> resetFacebookLoginPasswordSuccess.onNext( null ) else -> success() } } resetPasswordNotification .compose(errors()) .map { ErrorEnvelope.fromThrowable(it) } .compose(bindToLifecycle()) .subscribe(this.resetError) } private fun success() { this.resetLoginPasswordSuccess.onNext(null) } private fun submitEmail(email: String): Observable<Notification<User>> { return this.client.resetPassword(email) .doOnSubscribe { this.isFormSubmitting.onNext(true) } .doAfterTerminate { this.isFormSubmitting.onNext(false) } .materialize() .share() } override fun email(emailInput: String) { this.email.onNext(emailInput) } override fun resetPasswordClick() { this.resetPasswordClick.onNext(null) } override fun isFormSubmitting(): Observable<Boolean> { return this.isFormSubmitting } override fun isFormValid(): Observable<Boolean> { return this.isFormValid } override fun resetLoginPasswordSuccess(): Observable<Void> { return this.resetLoginPasswordSuccess } override fun resetFacebookLoginPasswordSuccess(): Observable<Void> { return this.resetFacebookLoginPasswordSuccess } override fun resetError(): Observable<String> { return this.resetError .takeUntil(this.resetLoginPasswordSuccess) .map { it?.errorMessage() ?: ERROR_GENERIC } } override fun prefillEmail(): BehaviorSubject<String> = this.prefillEmail override fun resetPasswordScreenStatus(): Observable<ResetPasswordScreenState> = this.resetPasswordScreenStatus } }
apache-2.0
fa4e2f5295bbfe1cf0319f45a4252464
38.412698
124
0.62948
5.987942
false
false
false
false
mtransitapps/mtransit-for-android
src/main/java/org/mtransit/android/ui/poi/POIFragment.kt
1
46945
//@file:JvmName("POIFragment") // ANALYTICS package org.mtransit.android.ui.poi // //import android.content.Context //import android.content.res.Configuration //import android.graphics.Color //import android.hardware.Sensor //import android.hardware.SensorEvent //import android.hardware.SensorEventListener //import android.location.Location //import android.os.Bundle //import android.view.Menu //import android.view.MenuInflater //import android.view.MenuItem //import android.view.View //import androidx.core.os.bundleOf //import androidx.core.view.isVisible //import androidx.fragment.app.viewModels //import androidx.viewbinding.ViewBinding //import com.google.android.gms.maps.model.LatLng //import com.google.android.gms.maps.model.LatLngBounds //import dagger.hilt.android.AndroidEntryPoint //import org.mtransit.android.R //import org.mtransit.android.ad.IAdManager.RewardedAdListener //import org.mtransit.android.commons.Constants //import org.mtransit.android.commons.LocationUtils //import org.mtransit.android.commons.MTLog //import org.mtransit.android.commons.StoreUtils //import org.mtransit.android.commons.ThreadSafeDateFormatter //import org.mtransit.android.commons.data.News //import org.mtransit.android.commons.data.POI //import org.mtransit.android.commons.data.POIStatus //import org.mtransit.android.commons.data.RouteTripStop //import org.mtransit.android.commons.data.ServiceUpdate //import org.mtransit.android.commons.provider.NewsProviderContract //import org.mtransit.android.data.AgencyProperties //import org.mtransit.android.data.POIArrayAdapter //import org.mtransit.android.data.POIManager //import org.mtransit.android.data.ScheduleProviderProperties //import org.mtransit.android.databinding.FragmentPoiBinding //import org.mtransit.android.databinding.LayoutPoiAppUpdateBinding //import org.mtransit.android.databinding.LayoutPoiRewardedAdBinding //import org.mtransit.android.databinding.LayoutPoiServiceUpdateBinding //import org.mtransit.android.datasource.DataSourcesRepository //import org.mtransit.android.provider.FavoriteManager //import org.mtransit.android.provider.FavoriteManager.FavoriteUpdateListener //import org.mtransit.android.provider.permission.LocationPermissionProvider //import org.mtransit.android.provider.sensor.MTSensorManager //import org.mtransit.android.provider.sensor.MTSensorManager.CompassListener //import org.mtransit.android.task.ServiceUpdateLoader //import org.mtransit.android.task.StatusLoader //import org.mtransit.android.ui.MTActivityWithLocation //import org.mtransit.android.ui.MTActivityWithLocation.UserLocationListener //import org.mtransit.android.ui.MainActivity //import org.mtransit.android.ui.fragment.ABFragment //import org.mtransit.android.ui.map.MapFragment.Companion.newInstance //import org.mtransit.android.ui.nearby.NearbyFragment //import org.mtransit.android.ui.news.NewsListFragment //import org.mtransit.android.ui.schedule.ScheduleFragment //import org.mtransit.android.ui.view.MapViewController //import org.mtransit.android.ui.view.POIDataProvider //import org.mtransit.android.ui.view.POINewsViewController //import org.mtransit.android.ui.view.POIServiceUpdateViewController //import org.mtransit.android.ui.view.POIStatusDetailViewController //import org.mtransit.android.ui.view.POIViewController //import org.mtransit.android.ui.view.common.EventObserver //import org.mtransit.android.util.FragmentUtils //import org.mtransit.android.util.LinkUtils //import org.mtransit.android.util.MapUtils //import org.mtransit.android.util.UITimeUtils //import org.mtransit.android.util.UITimeUtils.TimeChangedReceiver //import org.mtransit.android.util.UITimeUtils.TimeChangedReceiver.TimeChangedListener //import javax.inject.Inject // //@AndroidEntryPoint //class POIFragment : ABFragment(R.layout.fragment_poi), UserLocationListener, POIDataProvider, TimeChangedListener, FavoriteUpdateListener { // // companion object { // private val LOG_TAG = POIFragment::class.java.simpleName // // private const val PKG_COMMON = "org.mtransit.android." // // private const val TRACKING_SCREEN_NAME = "POI" // // private val rewardedAdDateFormatter = ThreadSafeDateFormatter.getDateInstance(ThreadSafeDateFormatter.MEDIUM) // // @JvmStatic // fun newInstance(poi: POI): POIFragment { // return newInstance(poi.authority, poi.uuid) // } // // @JvmStatic // fun newInstance(agencyAuthority: String, uuid: String): POIFragment { // return POIFragment().apply { // arguments = bundleOf( // POIViewModel.EXTRA_AUTHORITY to agencyAuthority, // POIViewModel.EXTRA_POI_UUID to uuid, // ) // } // } // } // // private var theLogTag: String = LOG_TAG // // override fun getLogTag(): String = this.theLogTag // // override fun getScreenName(): String = viewModel.uuid.value?.let { "$TRACKING_SCREEN_NAME/$it" } ?: TRACKING_SCREEN_NAME // // private val viewModel by viewModels<POIViewModel>() // // @Inject // lateinit var sensorManager: MTSensorManager // // @Inject // lateinit var dataSourcesRepository: DataSourcesRepository // // @Inject // lateinit var favoriteManager: FavoriteManager // // @Inject // lateinit var statusLoader: StatusLoader // // @Inject // lateinit var serviceUpdateLoader: ServiceUpdateLoader // // @Inject // lateinit var locationPermissionProvider: LocationPermissionProvider // // private var binding: FragmentPoiBinding? = null // private var thisPoiBinding: ViewBinding? = null // private var rtsScheduleBtn: View? = null // private var poiStatusDetailBinding: ViewBinding? = null // private var poiServiceUpdateBinding: ViewBinding? = null // private var poiAppUpdateBinding: LayoutPoiAppUpdateBinding? = null // private var poiNewsBinding: ViewBinding? = null // // // private var newsMoreBtn: View? = null // private var poiRewardedAdBinding: LayoutPoiRewardedAdBinding? = null // // private var nearbyMoreBtn: View? = null // // private val mapMarkerProvider = object : MapViewController.MapMarkerProvider { // // override fun getPOMarkers(): Collection<MapViewController.POIMarker>? = null // // override fun getPOIs() = viewModel.poimV?.let { listOf(it) } // // override fun getClosestPOI() = viewModel.poimV // // override fun getPOI(uuid: String?) = viewModel.poimV?.let { poim -> // if (poim.poi.uuid == uuid) poim else null // } // } // // private val mapListener = object : MapViewController.MapListener { // // override fun onMapClick(position: LatLng) { // if (!FragmentUtils.isFragmentReady(this@POIFragment)) { // return // } // // val poim: POIManager = viewModel.poimV ?: return // val poi: POI = viewModel.poi.value ?: return // val activity = activity ?: return // (activity as MainActivity).addFragmentToStack( // // newInstance( // LocationUtils.getNewLocation(poi.lat, poi.lng), // poi.uuid, // poi.dataSourceTypeId // ), // this@POIFragment // ) // } // // override fun onCameraChange(latLngBounds: LatLngBounds) { // // DO NOTHING // } // // override fun onMapReady() { // // DO NOTHING // } // } // // private val mapViewController: MapViewController by lazy { // MapViewController( // logTag, // mapMarkerProvider, // mapListener, // false, // true, // false, // false, // false, // false, // 32, // 0, // true, // false, // true, // true, // false, // this.dataSourcesRepository // ).apply { // setLocationPermissionGranted(locationPermissionProvider.permissionsGranted(requireContext())) // } // } // // private val adapter: POIArrayAdapter by lazy { // POIArrayAdapter( // this, // this.sensorManager, // this.dataSourcesRepository, // this.favoriteManager, // this.statusLoader, // this.serviceUpdateLoader // ).apply { // logTag = logTag // // setShowExtra(false) // setLocation(viewModel.deviceLocation.value) // } // } // // private val onSensorTaskCompleted = object : MTSensorManager.SensorTaskCompleted { // // override fun onSensorTaskCompleted(result: Boolean, orientation: Int, now: Long) { // viewModel.onSensorTaskCompleted(result, orientation, now) // if (result && isResumed) { // updatePOIDistanceAndCompass() // } // } // } // // private val compassListener = object : CompassListener { // override fun updateCompass(orientation: Float, force: Boolean) { // viewModel.updateCompass(orientation, force, onSensorTaskCompleted) // } // } // // private val sensorEventListener = object : SensorEventListener { // override fun onSensorChanged(event: SensorEvent?) { // event?.let { viewModel.onSensorChanged(this@POIFragment, it, compassListener) } // } // // override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { // // DO NOTHING // } // } // // private val rewardedAdListener = object : RewardedAdListener { // override fun onRewardedAdStatusChanged() { // viewModel.onRewardedAdStatusChanged() // } // // override fun skipRewardedAd() = viewModel.skipRewardedAd() // } // // override fun onAttach(context: Context) { // super.onAttach(context) // mapViewController.apply { // setDataSourcesRepository(dataSourcesRepository) // onAttach(requireActivity()) // setLocationPermissionGranted(locationPermissionProvider.permissionsGranted(context)) // } // } // // override fun onCreate(savedInstanceState: Bundle?) { // super.onCreate(savedInstanceState) // setHasO ptionsMenu(true) // mapViewController.onCreate(savedInstanceState) // } // // override fun onViewCreated(view: View, savedInstanceState: Bundle?) { // super.onViewCreated(view, savedInstanceState) // mapViewController.onViewCreated(view, savedInstanceState) // binding = FragmentPoiBinding.bind(view).apply { // thisPoiStub.setOnInflateListener { _, inflated -> // // // T ODO which stub? thisPoiBinding = LayoutEmptyBinding.bind(inflated) // updatePOIView(poiView = inflated) // updatePOIStatusView(poiView = inflated) // updatePOIColorView(poiView = inflated) // updatePOIDistanceAndCompass(poiView = inflated) // updatePOIServiceUpdatesView(poiView = inflated) // } // poiStatusDetailStub.setOnInflateListener { _, inflated -> // rtsScheduleBtn = inflated.findViewById<View>(R.id.fullScheduleBtn)?.apply { // setOnClickListener { // viewModel.poimV?.let { poim -> // (poim.poi as? RouteTripStop)?.let { // (activity as? MainActivity)?.addFragmentToStack( // ScheduleFragment.newInstance(poim, dataSourcesRepository), // this@POIFragment // ) // } // } // } // setupRTSFullScheduleBtn(rtsScheduleBtn = this) // } // updateStatusDetailView(statusDetailView = inflated) // updateStatusDetailColorView(statusDetailView = inflated) // } // poiServiceUpdateStub.setOnInflateListener { _, inflated -> // poiServiceUpdateBinding = LayoutPoiServiceUpdateBinding.bind(inflated) // updateServiceUpdateView(serviceUpdateView = inflated) // } // poiAppUpdateStub.setOnInflateListener { _, inflated -> // poiAppUpdateBinding = LayoutPoiAppUpdateBinding.bind(inflated).apply { // appUpdateBtn.setOnClickListener { // viewModel.agency.value?.let { agency -> // activity?.let { activity -> // viewModel.onClickAppUpdatePOI(agency) // StoreUtils.viewAppPage(activity, agency.pkg, activity.getString(R.string.google_play)) // } // } // } // refreshAppUpdateLayout(poiAppUpdateBinding = this) // } // } // poiNewsStub.setOnInflateListener { _, inflated -> // // poiNewsBinding = LayoutPoiNewsBinding.bind(inflated) // val newsMoreBtn = inflated.findViewById<View>(R.id.moreBtn) // newsMoreBtn.apply { // setOnClickListener { // viewModel.poimV?.let { poim -> // (activity as? MainActivity)?.addFragmentToStack( // NewsListFragment.newInstance( // poim.getColor { viewModel.agency.value }, // poim.getNewOneLineDescription(viewModel.agency.value), // // POIManager.getNewOneLineDescription(poim.poi, dataSourcesRepository), // listOf(poim.poi.authority), // null, // NewsProviderContract.Filter.getNewTargetFilter(poim.poi).targets // ), // this@POIFragment // ) // } // } // isVisible = true // } // updateNewsView(newsView = inflated) // } // poiRewardedAdStub.setOnInflateListener { _, inflated -> // poiRewardedAdBinding = LayoutPoiRewardedAdBinding.bind(inflated).apply { // rewardedAdsBtn.apply { // setOnClickListener { rewardedAdsBtn -> // if (viewModel.onRewardedAdClick(this@POIFragment) == false) { // rewardedAdsBtn.isEnabled = false // avoid double-click // } // } // } // refreshRewardedLayout(poiRewardedAdBinding = this) // } // } // adapter.setManualScrollView(scrollview) // adapter.setManualLayout(poiNearbyPoisList) // // if (adapter.isInitialized) { // // showNearbyList() // // } else { // // hideNearbyList(true) // // } // // binding?.apply { // poiNearbyPoisTitle.moreBtn.apply { // setOnClickListener { // viewModel.poimV?.let { poim -> // val agency = viewModel.agency.value // (activity as? MainActivity)?.addFragmentToStack( // NearbyFr agment.newFixedOnInstance(poim, agency), // this@POIFragment // ) // } // } // isVisible = !Constants.FORCE_NEARBY_POI_LIST_OFF // } // poiNearbyPoisTitle.root.isVisible = !Constants.FORCE_NEARBY_POI_LIST_OFF && adapter.isInitialized // poiNearbyPoisList.isVisible = !Constants.FORCE_NEARBY_POI_LIST_OFF && adapter.isInitialized // // } // } // viewModel.uuid.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - uuid") // theLogTag = it?.let { "${LOG_TAG}-${it.substringAfter(PKG_COMMON)}" } ?: LOG_TAG // }) // viewModel.agency.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - agency") // it?.let { // val context = view.context // // viewModel.poimV?.let { poim -> // // POIStatusDetailViewController.updateView(context, getPOIStatusView(), poim, this) // // } // updateStatusDetailView() // abController?.setABTitle(this, getABTitle(context), false) // abController?.setABReady(this, isABReady, true) // //refreshAppUpdateLayout(it) // } // refreshAppUpdateLayout(agency = it) // }) // viewModel.poiTypeAndStatus.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - poiTypeAndStatus") // // val context = view.context // // val poim = viewModel.poimV // updatePOIView(poiTypeAndStatus = it) // updatePOIColorView(poiTypeAndStatus = it) // updatePOIDistanceAndCompass(poiTypeAndStatus = it) // updatePOIStatusView(poiTypeAndStatus = it) // updatePOIServiceUpdatesView(poiTypeAndStatus = it) // updateStatusDetailView(poiTypeAndStatus = it) // updateStatusDetailColorView(poiTypeAndStatus = it) // // updateServiceUpdateView(poi) // // POIViewController.updateView(context, getPOIView(it), poim, this) // }) // viewModel.poi.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - poi") // updatePOIView(poiN = it) // updateStatusDetailView(poi = it) // updateFavMenuItem(poi = it) // }) // viewModel.poiColor.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - poiColor") // // viewModel.poiTypeAndStatus.value?.let { (poiType, poiStatusType) -> // // POIViewController.updatePOIColorView(getPOIView(), poiType, poiStatusType, it, this) // // } // updatePOIColorView(poiColor = it) // updateStatusDetailColorView(poiColor = it) // }) // viewModel.poiDistanceTrigger.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - poiDistanceTrigger") // // DO NOTHING // }) // viewModel.poiDistanceAndString.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - poiDistanceAndString") // updatePOIDistanceAndCompass(poiDistanceAndString = it) // }) // viewModel.poiStatus.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - poiStatus") // updatePOIStatusView(poiStatusN = it) // updateStatusDetailView(poiStatus = it) // }) // viewModel.poiServiceUpdates.observe(viewLifecycleOwner, { // updatePOIServiceUpdatesView(poiServiceUpdates = it) // updateServiceUpdateView(poiServiceUpdates = it) // }) // viewModel.poimTrigger.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - poimTrigger") // // DO NOTHING // }) // // TODO // @Suppress("DEPRECATION") // FIXME // viewModel.poim.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - poim") // it?.let { // // TODO test all , it's a mess ... try to fix it POIManager is hard to work with? can we use it in MVVM ? // // TODO kind of starting to work but not working very well ... POIM + MVVM = ! // // TODO Maybe just refactor Java code to extract small ViewModel to remove loader and stabilize before opening this can of worm // // val context = view.context // // adapter.clear() // // TO DO ? resetFavorite() // mapViewController.notifyMarkerChanged(mapMarkerProvider) // mapViewController.showMap(view) // // updatePOIView(poimN = poim) // // if (isShowingStatus) { // // poim.setStatusLoaderListener(this@POIFragment) // TOD O ? // viewModel.refreshStatus(context, this@POIFragment) // // } // // if (isShowingServiceUpdates) { // // poim.setServiceUpdateLoaderListener(this@POIFragment) // TO DO ? // viewModel.refreshServiceUpdate(context, this@POIFragment) // // } // // POIViewController.updateView(context, getPOIView(poim), poim, this) // // updateStatusDetailView(poimN = poim) // // POIStatusDetailViewController.updateView(context, getPOIStatusView(), poim, this) // // POIServiceUpdateViewController.updateView(getPOIServiceUpdateView(), poim, this) // // updateServiceUpdateView(poimN = poim) // // POINewsViewController.updateView(getPOINewsView(), viewModel.latestNewsArticleList.value) // // TODO ? updateNewsView() // // updateFavMenuItem(poim = poim) // activity?.invalidateOptionsMenu() // add/remove star from action bar // // setupRTSFullScheduleBtn() // // setupMoreNewsButton() // // setupMoreNearbyButton() // // setupNearbyList() // } // }) // viewModel.scheduleProviders.observe(viewLifecycleOwner, { // // val poim = viewModel.poimV // // getPOIStatusViewBinding(poim) as? POI // setupRTSFullScheduleBtn(scheduleProviders = it) // }) // viewModel.poiFavorite.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - poiFavorite") // it?.let { // // val poim = viewModel.poimV // updateFavMenuItem(poiFavorite = it) // activity?.invalidateOptionsMenu() // add/remove star from action bar // // POIViewController.updateView(view.context, getPOIView(poim), poim, this) // // updatePOIView(context = view.context) // } // }) // viewModel.dataSourceRemovedEvent.observe(viewLifecycleOwner, EventObserver { removed -> // MTLog.v(this, "onChanged($removed) - dataSourceRemovedEvent") // if (removed) { // (activity as MainActivity?)?.popFragmentFromStack(this) // close this fragment // } // }) // viewModel.deviceLocation.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - deviceLocation") // context?.let { context -> // mapViewController.setLocationPermissionGranted(locationPermissionProvider.permissionsGranted(context)) // } // mapViewController.onDeviceLocationChanged(it) // // TODO if (!this.compassUpdatesEnabled) { // // sensorManager.registerCompassListener(this); // // this.compassUpdatesEnabled = true; // // } // viewModel.updatePOIDistanceWithString(deviceLocation = it) // // viewModel.poimV?.let { poim -> // // POIViewController.updatePOIDistanceAndCompass(getPOIView(poim), poim, this); // // } // updatePOIDistanceAndCompass() // // POIManager poim = getPoimOrNull(); // // if (poim != null) { // // LocationUtils.updateDistanceWithString(requireContext(), poim, newLocation); // // POIViewController.updatePOIDistanceAndCompass(getPOIView(getView()), poim, this); // // } // adapter.setLocation(it) // // }) // if (!Constants.FORCE_NEARBY_POI_LIST_OFF) { // viewModel.nearbyPOIs.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged(${it?.size}) - nearbyPOIs") // it?.let { nearbyPOIs -> // adapter.apply { // setPois(nearbyPOIs) // updateDistanceNowAsync(viewModel.deviceLocation.value) // initManual() // // if (poisCount > 0) { // // showNearbyList() // // } else { // // hideNearbyList(false) // // } // } // } // // ?: run { hideNearbyList(false) } // // if (it.isNullOrEmpty()) { // // hideNearbyList(false) // // } else { // // showNearbyList() // // } // binding?.apply { // poiNearbyPoisTitle.root.isVisible = !it.isNullOrEmpty() // poiNearbyPoisList.isVisible = !it.isNullOrEmpty() // } // }) // } // viewModel.rewardedAdStatus.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - rewardedAdStatus") // refreshRewardedLayout(status = it) // }) // // viewModel.rewardedAdAmount.observe(viewLifecycleOwner, { // // refreshRewardedLayout(rewardedAmount = it) // // }) // // viewModel.rewardedAdNowUntilInMs.observe(viewLifecycleOwner, { // // refreshRewardedLayout(rewardedNowUntilInMs = it) // // }) // viewModel.latestNewsArticleList.observe(viewLifecycleOwner, { // MTLog.v(this, "onChanged($it) - rewardedAdStatus") // updateNewsView(news = it) // }) // } // // private fun updatePOIView( // poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value, // poiN: POI? = viewModel.poi.value, // poiView: View? = getPOIView(poiTypeAndStatus), // ) { // poiN?.let { poi -> // POIViewController.updatePOIView(poiView, poi, this) // } // } // // private fun updatePOIColorView( // poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value, // poiColor: Int? = viewModel.poiColor.value, // poiView: View? = getPOIView(poiTypeAndStatus), // ) { // poiTypeAndStatus?.let { (poiType, poiStatusType) -> // POIViewController.updatePOIColorView(poiView, poiType, poiStatusType, poiColor, this) // } // } // // private fun updatePOIStatusView( // poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value, // poiStatusN: POIStatus? = viewModel.poiStatus.value, // poiView: View? = getPOIView(poiTypeAndStatus), // ) { // poiStatusN?.let { poiStatus -> // POIViewController.updatePOIStatus(poiView, poiStatus, this) // } // } // // private fun updatePOIServiceUpdatesView( // poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value, // poiServiceUpdates: List<ServiceUpdate>? = viewModel.poiServiceUpdates.value, // poiView: View? = getPOIView(poiTypeAndStatus), // ) { // // poiStatusN?.let { poiStatus -> // // POIViewController.updatePOIServiceUpdate(poiView, poiServiceUpdates, this) // POIViewController.updateServiceUpdatesView(poiView, poiServiceUpdates, this) // // } // } // // // // TO DO // // private fun updatePOIMView( // // poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value, // // poimN: POIManager? = viewModel.poimV, // // poiView: View? = getPOIView(poiTypeAndStatus), // // ) { // // poimN?.let { poim -> // // POIViewController.updateView(poiView, poim, this) // // } // // } // // // private fun updatePOIDistanceAndCompass( // poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value, // poiDistanceAndString: Pair<Float, CharSequence?>? = viewModel.poiDistanceAndString.value, // poiView: View? = getPOIView(poiTypeAndStatus), // ) { // poiTypeAndStatus?.let { (poiType, poiStatusType) -> // // TO DO: // // - this method is too big w/ too big dependency #POIM // // - split in multiple methods than can be called w/ poi OR distance OR status type OR .... // POIViewController.updatePOIDistanceAndCompass(poiView, poiType, poiStatusType, poiDistanceAndString?.first, poiDistanceAndString?.second, this) // } // } // // private fun updateStatusDetailView( // poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value, // poiStatus: POIStatus? = viewModel.poiStatus.value, // poi: POI? = viewModel.poi.value, // statusDetailView: View? = getPOIStatusView(poiTypeAndStatus), // ) { // MTLog.v(this, "updateStatusDetailView($statusDetailView, $poiStatus)") // poiTypeAndStatus?.let { (_, poiStatusType) -> // // TO DO: // // - updateView = init view holder + updateView // // ==> call init view holder w/ view + poim/status (+color?) // // => call update view w/ view holder directly stored in this class // // XOR: // // => keep calling one method to rule them all // POIStatusDetailViewController.updateView(statusDetailView, poiStatusType, poiStatus, poi, this) // } // } // // private fun updateStatusDetailColorView( // poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value, // poiColor: Int? = viewModel.poiColor.value, // statusDetailView: View? = getPOIStatusView(poiTypeAndStatus), // ) { // MTLog.v(this, "updateStatusDetailColorView($statusDetailView, $poiColor)") // poiTypeAndStatus?.let { (_, statusType) -> // POIStatusDetailViewController.updateColorView(statusDetailView, statusType, poiColor, this) // } // } // // private fun updateServiceUpdateView( // // poimN: POIManager? = viewModel.poimV, // poiServiceUpdates: List<ServiceUpdate>? = viewModel.poiServiceUpdates.value, // serviceUpdateView: View? = getPOIServiceUpdateView(), // ) { // // poimN?.let { poim -> // POIServiceUpdateViewController.updateView(serviceUpdateView, poiServiceUpdates, this) // // } // } // // private fun updateNewsView( // news: List<News>? = viewModel.latestNewsArticleList.value, // newsView: View? = getPOINewsView(), // ) { // // poimN?.let { poim -> // POINewsViewController.updateView(newsView, news) // // } // } // // private fun getPOIView(poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value) = getPOIViewBinding(poiTypeAndStatus)?.root // // private fun getPOIViewBinding(poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value): ViewBinding? { // return thisPoiBinding ?: binding?.let { binding -> // poiTypeAndStatus?.let { poiTypeAndStatus -> // POIViewController.getLayoutViewBinding(poiTypeAndStatus.first, poiTypeAndStatus.second, binding.thisPoiStub) // } // }?.also { thisPoiBinding = it } // } // // private fun getPOIStatusView(poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value) = getPOIStatusViewBinding(poiTypeAndStatus)?.root // // private fun getPOIStatusViewBinding(poiTypeAndStatus: Pair<Int, Int>? = viewModel.poiTypeAndStatus.value): ViewBinding? { // return poiStatusDetailBinding ?: binding?.let { binding -> // poiTypeAndStatus?.let { poiTypeAndStatus -> // POIStatusDetailViewController.getLayoutViewBinding(poiTypeAndStatus.first, binding.poiStatusDetailStub) // } // }?.also { poiStatusDetailBinding = it } // } // // private fun getPOIServiceUpdateView() = getPOIServiceUpdateViewBinding()?.root // // private fun getPOIServiceUpdateViewBinding(): ViewBinding? { // return poiServiceUpdateBinding ?: binding?.let { binding -> // POIServiceUpdateViewController.getLayoutViewBinding(binding.poiServiceUpdateStub) // }?.also { poiServiceUpdateBinding = it } // } // // private fun getPOINewsView() = getPOINewsViewBinding()?.root // // private fun getPOINewsViewBinding(): ViewBinding? { // return poiNewsBinding ?: binding?.let { binding -> // POINewsViewController.getLayoutViewBinding(binding.poiNewsStub) // }?.also { poiNewsBinding = it } // } // // private fun setupRTSFullScheduleBtn( // rtsScheduleBtn: View? = this.rtsScheduleBtn, // scheduleProviders: List<ScheduleProviderProperties>? = viewModel.scheduleProviders.value, // ) { // rtsScheduleBtn?.isVisible = !scheduleProviders.isNullOrEmpty() // } // // private fun refreshAppUpdateLayout( // poiAppUpdateBinding: LayoutPoiAppUpdateBinding? = this.poiAppUpdateBinding, // agency: AgencyProperties? = viewModel.agency.value, // ) { // poiAppUpdateBinding?.apply { // agency?.apply { // if (updateAvailable) { // if (!root.isVisible) { // viewModel.onShowedAppUpdatePOI(this) // root.isVisible = true // } // } else { // if (root.isVisible) { // viewModel.onHiddenAppUpdatePOI(this) // root.isVisible = false // } // } // } ?: run { // root.isVisible = false // } // } ?: run { binding?.poiAppUpdateStub?.inflate() } // } // // private fun refreshRewardedLayout( // poiRewardedAdBinding: LayoutPoiRewardedAdBinding? = this.poiRewardedAdBinding, // status: RewardedAdStatus? = viewModel.rewardedAdStatus.value, // ) { // poiRewardedAdBinding?.apply { // rewardedAdsTitleLayout.rewardAdTitle.apply { // text = if (status?.rewardedNow == true) { // getString( // R.string.watch_rewarded_ad_title_text_and_date, // rewardedAdDateFormatter.formatThreadSafe(status.rewardedUntilInMs) // ) // } else { // getString( // R.string.watch_rewarded_ad_title_text // ) // } // isVisible = status != null // } // rewardedAdsBtn.apply { // text = status?.rewardedAmount?.let { rewardedAmount -> // getString( // if (status.rewardedNow) R.string.watch_rewarded_ad_btn_more_and_days else R.string.watch_rewarded_ad_btn_and_days, // rewardedAmount // ) // } // isEnabled = status?.let { it.availableToShow && it.rewardedAmount > 0 } ?: false // keep but disable // if (status?.availableToShow == true) { // only if NOT paying user // isVisible = true // GONE by default but never hidden once visible // } // } // root.isVisible = status?.availableToShow == true // } ?: run { binding?.poiRewardedAdStub?.inflate() } // } // // override fun onStatusLoaded(status: POIStatus) { // MTLog.v(this, "onStatusLoaded($status)") // // TO DO this status needs to be added to view model POI Manager // // // // context?.let { context -> // viewModel.onStatusLoaded(status) // TODO ? // // POIViewController.updatePOIStatus(getPOIView(), status, this) // updatePOIStatusView(poiStatusN = status) // // POIStatusDetailViewController.updatePOIStatus(getPOIStatusView(), status, this, viewModel.poimV) // updateStatusDetailView(poiStatus = status) // // } // } // // override fun onServiceUpdatesLoaded(targetUUID: String, serviceUpdates: List<ServiceUpdate>?) { // MTLog.v(this, "onServiceUpdatesLoaded($targetUUID, $serviceUpdates)") // // T ODO this serviceUpdates needs to be added to view model POI Manager // // // // context?.let { context -> // viewModel.onServiceUpdatesLoaded(serviceUpdates) // TODO ? // // POIViewController.updateServiceUpdatesView(getPOIView(), serviceUpdates, this) // updatePOIServiceUpdatesView(poiServiceUpdates = serviceUpdates) // // POIServiceUpdateViewController.updateServiceUpdate(getPOIServiceUpdateView(), serviceUpdates, this) // updateServiceUpdateView(poiServiceUpdates = serviceUpdates) // // } // } // // override fun onURLClick(url: String) = // LinkUtils.open(requireActivity(), url, getString(R.string.web_browser), true) // // private var nowToTheMinute = -1L // // override fun getNowToTheMinute(): Long { // MTLog.v(this, "getNowToTheMinute()") // if (this.nowToTheMinute < 0L) { // resetNowToTheMinute() // enableTimeChangedReceiver() // } // return this.nowToTheMinute // } // // override fun onTimeChanged() { // resetNowToTheMinute() // } // // private var timeChangedReceiverEnabled = false // // private fun enableTimeChangedReceiver() { // MTLog.v(this, "enableTimeChangedReceiver()") // if (!timeChangedReceiverEnabled) { // timeChangedReceiverEnabled = true // context?.registerReceiver(timeChangedReceiver, UITimeUtils.TIME_CHANGED_INTENT_FILTER) // } // } // // private fun disableTimeChangedReceiver() { // MTLog.v(this, "disableTimeChangedReceiver()") // if (timeChangedReceiverEnabled) { // context?.unregisterReceiver(timeChangedReceiver) // timeChangedReceiverEnabled = false // nowToTheMinute = -1L // } // } // // private val timeChangedReceiver = TimeChangedReceiver(this) // // private fun resetNowToTheMinute() { // // TO DO actually needs to call POIM .getStatus/ServiceUpdate to trigger data refresh!!! // MTLog.v(this, "resetNowToTheMinute()") // MTLog.i(this, "Refreshing UI data...") // nowToTheMinute = UITimeUtils.currentTimeToTheMinuteMillis() // // val view = view // // val poim: POIManager = getPoimOrNull() // // viewModel.poimV?.let { poim -> // // if (poim != null) { // // val poiView = getPOIView() // // POIViewController.updatePOIStatus(poiView, poim, this) // viewModel.refreshStatus(context, this@POIFragment) // // poim.setStatusLoaderListener(this@POIFragment) // // poim.getStatus(context, providesStatusLoader()) // viewModel.refreshServiceUpdate(context, this@POIFragment) // // poim.setServiceUpdateLoaderListener(this@POIFragment) // // poim.getServiceUpdates(context, providesServiceUpdateLoader()) // // POIViewController.updatePOIServiceUpdate(poiView, poim, this) // // POIStatusDetailViewController.updateView(context, getPOIStatusView(), poim, this) // // updateStatusDetailView(poimN = poim) // // POIServiceUpdateViewController.updateView(getPOIServiceUpdateView(), poim, this) // // updateServiceUpdateView(poimN = poim) // // } // updateServiceUpdateView() // updateStatusDetailView() // // viewModel.latestNewsArticleList.value?.let { // // val news: ArrayList<News> = getNewsOrNull() // // if (news != null) { // // POINewsViewController.updateView(getPOINewsView(), news) // updateNewsView() // "X minutes ago on www.news.com" // // } // } // // override fun onSaveInstanceState(outState: Bundle) { // mapViewController.onSaveInstanceState(outState) // super.onSaveInstanceState(outState) // } // // override fun onDetach() { // super.onDetach() // this.mapViewController.onDetach() // } // // override fun onConfigurationChanged(newConfig: Configuration) { // super.onConfigurationChanged(newConfig) // mapViewController.onConfigurationChanged(newConfig) // } // // override fun onResume() { // super.onResume() // adapter.onResume(this, viewModel.deviceLocation.value) // mapViewController.onResume() // mapViewController.showMap(view) // (activity as? MTActivityWithLocation)?.let { onUserLocationChanged(it.lastLocation) } // viewModel.onResumeRewardedAd(this, rewardedAdListener) // sensorManager.registerCompassListener(sensorEventListener) // } // // override fun onUserLocationChanged(newLocation: Location?) { // viewModel.onDeviceLocationChanged(newLocation) // // TODO ? // } // // private var addRemoveFavoriteMenuItem: MenuItem? = null // // override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { // super.onCreateOptionsMenu(menu, inflater) // inflater.inflate(R.menu.menu_poi, menu) // addRemoveFavoriteMenuItem = menu.findItem(R.id.menu_add_remove_favorite) // updateFavMenuItem() // } // // private fun updateFavMenuItem( // poi: POI? = viewModel.poi.value, // poiFavorite: Boolean? = viewModel.poiFavorite.value, // ) { // MTLog.v(this, "updateFavMenuItem($poi, $poiFavorite)") // this.addRemoveFavoriteMenuItem?.let { addRemoveFavoriteMenuItem -> // // val isFav = poim?.let { poim -> viewModel.isFavorite(poim) } ?: false // addRemoveFavoriteMenuItem.apply { // val isFav = poiFavorite ?: false // MTLog.d(this@POIFragment, "updateFavMenuItem() > isFav: $isFav") // val isFavoritable = poi?.let { POIManager.isFavoritable(it) } // MTLog.d(this@POIFragment, "updateFavMenuItem() > isFavoritable: $isFavoritable") // setIcon(if (isFav) R.drawable.ic_star_black_24dp else R.drawable.ic_star_border_black_24dp) // setTitle( // if (isFav) { // if (favoriteManager.isUsingFavoriteFolders) R.string.menu_action_edit_favorite else R.string.menu_action_remove_favorite // } else { // R.string.menu_action_add_favorite // } // ) // isVisible = isFavoritable == true && poiFavorite != null // } // } // } // // override fun onOptionsItemSelected(item: MenuItem): Boolean { // return when (item.itemId) { // R.id.menu_add_remove_favorite -> { // viewModel.poi.value?.let { poi -> // if (POIManager.isFavoritable(poi)) { // this.favoriteManager.addRemoveFavorite(requireActivity(), poi.uuid, this) // } else true // handled // } ?: false // } // R.id.menu_show_directions -> { // viewModel.poi.value?.let { poi -> // viewModel.onShowDirectionClick() // MapUtils.showDirection(requireActivity(), poi.lat, poi.lng, null, null, poi.name) // return true // handled // } ?: false // } // else -> super.onOptionsItemSelected(item) // } // } // // override fun onFavoriteUpdated() { // this.viewModel.onFavoriteUpdated() // context?.let { // // POIViewController.updateView(it, getPOIView(), viewModel.poimV, this) // updatePOIView() // } // } // // override fun onPause() { // super.onPause() // // T ODO if (this.compassUpdatesEnabled) { // sensorManager.unregisterSensorListener(sensorEventListener) // // this.compassUpdatesEnabled = false; // // } // disableTimeChangedReceiver() // mapViewController.onPause() // adapter.onPause() // viewModel.onPauseRewardedAd() // } // // override fun onLowMemory() { // super.onLowMemory() // mapViewController.onLowMemory() // } // // override fun onDestroyView() { // super.onDestroyView() // mapViewController.onDestroyView() // rtsScheduleBtn = null // thisPoiBinding = null // poiStatusDetailBinding = null // poiRewardedAdBinding = null // poiNewsBinding = null // // newsMoreBtn = null // poiAppUpdateBinding = null // poiServiceUpdateBinding = null // binding = null // } // // override fun onDestroy() { // super.onDestroy() // mapViewController.onDestroy() // adapter.onDestroy() // } // // override fun isABReady() = viewModel.agency.value != null // // override fun getABTitle(context: Context?) = viewModel.agency.value?.shortName ?: context?.getString(R.string.ellipsis) ?: super.getABTitle(null) // // override fun getABBgColor(context: Context?) = Color.TRANSPARENT // // override fun isShowingFavorite() = false // shown in the action bar // // override fun isShowingStatus() = true // // override fun isShowingExtra() = true // // override fun isShowingServiceUpdates() = true // // override fun providesDataSourcesRepository() = this.dataSourcesRepository // // override fun providesStatusLoader() = this.statusLoader // // override fun providesServiceUpdateLoader() = this.serviceUpdateLoader // // override fun isClosestPOI(uuid: String) = false // // override fun isFavorite(uuid: String) = viewModel.isFavorite(uuid) // // override fun getLocation() = viewModel.deviceLocation.value // // override fun hasLocation() = location != null // // // private val locationDeclination = 0f // // // override fun getLocationDeclination() = viewModel.locationDeclination.value // //this.locationDeclination // // // private var lastCompassInDegree: Int? = null // // // override fun getLastCompassInDegree() = viewModel.lastCompassInDegree.value // // override fun hasLastCompassInDegree() = lastCompassInDegree != null //}
apache-2.0
969920184f333f2b7734e8d499427e3f
43.967433
157
0.58805
4.599295
false
false
false
false
petuhovskiy/JValuer-CLI
src/main/kotlin/com/petukhovsky/jvaluer/cli/cmd/Run.kt
1
3800
package com.petukhovsky.jvaluer.cli.cmd import com.fasterxml.jackson.module.kotlin.readValue import com.petukhovsky.jvaluer.cli.* import com.petukhovsky.jvaluer.commons.data.PathData import com.petukhovsky.jvaluer.commons.invoker.DefaultInvoker import com.petukhovsky.jvaluer.commons.lang.Language import com.petukhovsky.jvaluer.commons.run.RunInOut import com.petukhovsky.jvaluer.commons.run.RunLimits import com.petukhovsky.jvaluer.commons.source.Source import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardCopyOption object Run : Command { override fun command(args: Array<String>) { val cmd = parseArgs(args, paramOf("-type"), paramOf("-lang"), paramOf("-tl"), paramOf("-ml"), paramOf("-i"), paramOf("-o"), paramFlagOf("-script") ) val script = buildRunScript(cmd) ?: return if (cmd.enabled("-script")) { println(objectMapper.writeValueAsString(script)) return } script.execute() } override fun printHelp() { println("usage:") println(" jv run <file> [-type <type>] [-lang <lang_id>] [-tl <time-limit>] [-ml <memory-limit>] " + "[-i <exe:in>] [-o <exe:out>] [-script]") println() println("Args:") println(" -type 'auto', 'exe', 'src'") println(" -lang Find language by id") println() println(" -tl Time limit. 1s(second), 2m(minutes), 123ms(milliseconds)") println(" -ml Memory limit. bytes(b), kilobytes(k, kb), mebibytes(m, mib, mb)") println() println(" -i Input source. For example, (default) stdin:input.txt means pipe input.txt > stdin") println(" -o Output destination. For example, (default) stdout:output.txt means pipe stdout > output.txt") println() println(" -script Produces script without executing") } } fun parseColon(s: String?): Pair<String, String>? { if (s == null) return null if (':' !in s) return Pair(s, s) val index = s.indexOf(":") return Pair(s.substring(0..(index - 1)), s.substring(index + 1)) } class RunScript( val exe: ExeInfo, val `in`: String = "input.txt", val out: String? = "output.txt" ) : Script() { override fun execute() { val myExe = exe.toExecutable() ?: return val limits = exe.createLimits() val result = runExe( myExe, PathData(resolve(this.`in`)), limits, exe.io ) if (this.out == "stdout") { //TODO println("Out:") println(result.out.string) } else result.out.copyIfNotNull(resolve(this.out ?: return)) } override fun applyLocation(dir: Path?) { super.applyLocation(dir) exe.applyLocation(dir) } } fun buildRunScript(cmd: PrettyArgs): RunScript? { if (cmd.list.size != 1) { println("Enter exactly one file") return null } val file = cmd.list[0] val i = parseColon(cmd.getOne("-i")) val o = parseColon(cmd.getOne("-o")) if (i?.second == "stdin") { println("Can't read input data from stdin yet..") return null } return RunScript( ExeInfo( file, FileType.valueOf(cmd.getOne("-type") ?: "auto"), cmd.getOne("-lang"), cmd.getOne("-tl"), cmd.getOne("-ml"), i?.first ?: "stdin", o?.first ?: "stdout" ), i?.second ?: "input.txt", o?.second ?: "output.txt" ) }
mit
82f2a9dc3326e0026e2822b9a59efe74
32.052174
121
0.551316
3.995794
false
false
false
false
nonylene/PhotoLinkViewer-Core
photolinkviewer-core/src/main/java/net/nonylene/photolinkviewer/core/fragment/OptionFragment.kt
1
22269
package net.nonylene.photolinkviewer.core.fragment import android.Manifest import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.app.Activity import android.app.Dialog import android.app.DownloadManager import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.ConnectivityManager import android.net.Uri import android.os.Bundle import android.os.Environment import android.os.Handler import android.os.Looper import android.preference.PreferenceManager import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v4.app.DialogFragment import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v4.view.ViewCompat import android.support.v4.view.animation.FastOutSlowInInterpolator import android.support.v7.app.AlertDialog import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.TextView import android.widget.Toast import butterknife.bindView import net.nonylene.photolinkviewer.core.PLVQualityPreferenceActivity import net.nonylene.photolinkviewer.core.PhotoLinkViewer import net.nonylene.photolinkviewer.core.R import net.nonylene.photolinkviewer.core.adapter.OptionFragmentRecyclerAdapter import net.nonylene.photolinkviewer.core.dialog.SaveDialogFragment import net.nonylene.photolinkviewer.core.event.BaseShowFragmentEvent import net.nonylene.photolinkviewer.core.event.DownloadButtonEvent import net.nonylene.photolinkviewer.core.event.RotateEvent import net.nonylene.photolinkviewer.core.event.SnackbarEvent import net.nonylene.photolinkviewer.core.model.OptionButton import net.nonylene.photolinkviewer.core.tool.* import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import twitter4j.* import twitter4j.auth.AccessToken import java.io.File @Suppress("RemoveCurlyBracesFromTemplate") /** * @see OptionFragment.createArguments */ class OptionFragment : Fragment() { private val baseView: View by bindView(R.id.option_base_view) private val baseButton: FloatingActionButton by bindView(R.id.basebutton) private val rotateLeftButton: FloatingActionButton by bindView(R.id.rotate_leftbutton) private val rotateRightButton: FloatingActionButton by bindView(R.id.rotate_rightbutton) private var lastSaveInfos: List<SaveDialogFragment.Info>? = null private var lastSaveDir: String? = null private var plvUrlsForSave: List<PLVUrl>? = null private val preferences by lazy { PreferenceManager.getDefaultSharedPreferences(activity) } private var applicationContext: Context? = null private val fastOutSlowInInterpolator = FastOutSlowInInterpolator() private var downloadPLVUrlStack: List<PLVUrl>? = null private var isOpen = false set(value) { field = value if (value) { ViewCompat.setRotation(baseButton, 0f) ViewCompat.animate(baseButton).rotationBy(180f).duration = 150 } else { ViewCompat.setRotation(baseButton, 180f) ViewCompat.animate(baseButton).rotationBy(180f).duration = 150 } adapter.adapterModelList = getFilteredOptionButtonsFromPreference(plvUrlsForSave != null) } // by default, animation does not run if not isLaidOut(). private fun FloatingActionButton.showWithAnimation() { alpha = 0f scaleY = 0f scaleX = 0f animate() .scaleX(1f) .scaleY(1f) .alpha(1f) .setDuration(200) .setInterpolator(fastOutSlowInInterpolator) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { visibility = View.VISIBLE } }) } private val adapter = OptionFragmentRecyclerAdapter { button -> onOptionButtonClick(button) } companion object { private val LIKE_CODE = 1 private val RETWEET_CODE = 2 private val STORAGE_PERMISSION_REQUEST = 3 private val SAVE_DIALOG_CODE = 4 private val TWITTER_ENABLED_KEY = "is_twitter_enabled" private val TWITTER_ID_KEY = "twitter_id_long" private val TWITTER_DEFAULT_SCREEN_KEY = "twitter_default_screen" private val URL_KEY = "url" /** * arguments for normal sites */ fun createArguments(url: String): Bundle { return Bundle().apply { putString(URL_KEY, url) } } /** * arguments for twitter sites. Twitter options will be available by using this. * @param tweetId Tweet id used in retweet and favorite feature. * @param twitterDefaultScreenName Twitter screen name used as default account. * @see OptionFragment.TwitterDialogFragment */ fun createArguments(url: String, tweetId: Long, twitterDefaultScreenName: String): Bundle { return Bundle().apply { putString(URL_KEY, url) putBoolean(TWITTER_ENABLED_KEY, true) putLong(TWITTER_ID_KEY, tweetId) putString(TWITTER_DEFAULT_SCREEN_KEY, twitterDefaultScreenName) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) applicationContext = activity.applicationContext } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.plv_core_option_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val recyclerView = view.findViewById(R.id.recycler_view) as RecyclerView adapter.setHasStableIds(true) recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(context).apply { reverseLayout = true } with(recyclerView.itemAnimator) { addDuration = 200 removeDuration = 200 } // adapter -> empty list baseButton.setOnClickListener { // see setter isOpen = !isOpen } rotateRightButton.setOnClickListener { EventBus.getDefault().post(RotateEvent(true)) } rotateLeftButton.setOnClickListener { EventBus.getDefault().post(RotateEvent(false)) } } fun onOptionButtonClick(optionButton: OptionButton) { when (optionButton) { OptionButton.PREFERENCE -> { startActivity(Intent(activity, PhotoLinkViewer.getPreferenceActivityClass())) } OptionButton.OPEN_OTHER_APP -> { // get uri from bundle val intent = Intent(Intent.ACTION_VIEW, Uri.parse(arguments.getString(URL_KEY))) // open intent chooser startActivity(Intent.createChooser(intent, getString(R.string.plv_core_intent_title))) } OptionButton.TWEET_LIKE -> { TwitterDialogFragment().apply { arguments = [email protected] setTargetFragment(this@OptionFragment, LIKE_CODE) show([email protected], "like") } } OptionButton.TWEET_RETWEET -> { TwitterDialogFragment().apply { arguments = [email protected] setTargetFragment(this@OptionFragment, RETWEET_CODE) show([email protected], "retweet") } } OptionButton.DOWNLOAD -> { plvUrlsForSave?.let { plvUrls -> // download directly val info = getSaveFragmentInfos(plvUrls) if (preferences.isSkipDialog()) { saveOrRequestPermission(info.dirName, info.infoList) } else { // open dialog SaveDialogFragment().apply { arguments = SaveDialogFragment.createArguments(info.dirName, info.quality, info.infoList.toCollection(arrayListOf())) setTargetFragment(this@OptionFragment, SAVE_DIALOG_CODE) show([email protected], "Save") } } } } OptionButton.COPY_URL -> { val url = arguments.getString(URL_KEY) val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboard.primaryClip = ClipData.newPlainText("Copy url", arguments.getString(URL_KEY)) Toast.makeText(applicationContext!!, applicationContext!!.getString(R.string.plv_core_copied).format(url), Toast.LENGTH_LONG).show() } OptionButton.SHARE -> { val url = arguments.getString(URL_KEY) val intent = Intent(Intent.ACTION_SEND) .setType("text/plain") .putExtra(Intent.EXTRA_TEXT, url) startActivity(Intent.createChooser(intent, "Share url")) } OptionButton.QUALITY -> { startActivity(Intent(activity, PLVQualityPreferenceActivity::class.java)) } OptionButton.ADD_BUTTON -> { // nothing } } } override fun onResume() { super.onResume() EventBus.getDefault().register(this) adapter.adapterModelList = getFilteredOptionButtonsFromPreference(plvUrlsForSave != null) } override fun onPause() { EventBus.getDefault().unregister(this) super.onPause() } class TwitterDialogFragment : DialogFragment() { private var requestCode: Int = 0 companion object { val SCREEN_NAME_KEY = "screen_name" } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { // get request code requestCode = targetRequestCode // get twitter id val id_long = arguments.getLong(TWITTER_ID_KEY) val screenName = arguments.getString(SCREEN_NAME_KEY) // get account_list val screen_list = PhotoLinkViewer.twitterTokenMap.keys.toList() // array_list to adapter val adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_item, screen_list).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } // get view val view = View.inflate(activity, R.layout.plv_core_spinner_dialog, null) val textView = view.findViewById(R.id.spinner_text) as TextView val spinner = (view.findViewById(R.id.accounts_spinner) as Spinner).apply { setAdapter(adapter) setSelection(screen_list.indexOf(screenName)) } val builder = AlertDialog.Builder(activity) // change behave for request code when (requestCode) { LIKE_CODE -> { textView.text = getString(R.string.plv_core_like_dialog_message) builder.setTitle(getString(R.string.plv_core_like_dialog_title)) } RETWEET_CODE -> { textView.text = getString(R.string.plv_core_retweet_dialog_message) builder.setTitle(getString(R.string.plv_core_retweet_dialog_title)) } } return builder .setView(view) .setPositiveButton(getString(android.R.string.ok), { dialog, which -> val screen_name = screen_list[spinner.selectedItemPosition] targetFragment.onActivityResult(requestCode, Activity.RESULT_OK, Intent().putExtra(SCREEN_NAME_KEY, screen_name).putExtra(TWITTER_ID_KEY, id_long)) }) .setNegativeButton(getString(android.R.string.cancel), null) .create() } } // eventBus catch event @Suppress("unused") @Subscribe(sticky = true) fun onEvent(downloadButtonEvent: DownloadButtonEvent) { EventBus.getDefault().removeStickyEvent(downloadButtonEvent) // save to stack for base view download event if (downloadButtonEvent.addToStack) downloadPLVUrlStack = downloadButtonEvent.plvUrls setDlButton(downloadButtonEvent.plvUrls) } // eventBus catch event @Suppress("unused") @Subscribe fun onEvent(baseShowFragmentEvent: BaseShowFragmentEvent) { if (fragmentManager.findFragmentByTag(BaseShowFragment.SHOW_FRAGMENT_TAG) != baseShowFragmentEvent.fragment) return if (baseShowFragmentEvent.isToBeShown) { rotateRightButton.showWithAnimation() rotateLeftButton.showWithAnimation() } else { if (downloadPLVUrlStack != null) { // restore plvurl stack for base view download event setDlButton(downloadPLVUrlStack!!) } else { removeDLButton() } rotateRightButton.hide() rotateLeftButton.hide() } } // eventBus catch event @Suppress("unused") @Subscribe fun onEvent(snackbarEvent: SnackbarEvent) { Snackbar.make(baseView, snackbarEvent.message, Snackbar.LENGTH_LONG).apply { snackbarEvent.actionMessage?.let { setAction(it, snackbarEvent.actionListener) } }.show() } private fun setDlButton(plvUrls: List<PLVUrl>) { plvUrlsForSave = plvUrls adapter.adapterModelList = getFilteredOptionButtonsFromPreference(true) } private fun removeDLButton() { adapter.adapterModelList = getFilteredOptionButtonsFromPreference(false) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { STORAGE_PERMISSION_REQUEST -> { if (grantResults.getOrNull(0) == PackageManager.PERMISSION_GRANTED) { save(lastSaveDir!!, lastSaveInfos!!) } else { Toast.makeText(applicationContext!!, applicationContext!!.getString(R.string.plv_core_permission_denied), Toast.LENGTH_LONG).show() } } } } private fun saveOrRequestPermission(dirName: String, infoList: List<SaveDialogFragment.Info>) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { lastSaveInfos = infoList lastSaveDir = dirName requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), STORAGE_PERMISSION_REQUEST) } else { save(dirName, infoList) } } private fun save(dirName: String, infoList: List<SaveDialogFragment.Info>) { val downloadManager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager val stringBuilder = StringBuilder().apply { append(applicationContext!!.getString(R.string.plv_core_download_photo_title)) } infoList.forEach { info -> val uri = Uri.parse(info.downloadUrl) val filename = info.fileName val path = File(dirName, filename) // save file val request = DownloadManager.Request(uri) .setDestinationUri(Uri.fromFile(path)) .setTitle("PhotoLinkViewer") .setDescription(filename) .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE or DownloadManager.Request.NETWORK_WIFI) // notify if (preferences.isLeaveNotify()) { request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) } downloadManager.enqueue(request) stringBuilder.append("\n${path},") } // remove last ',' stringBuilder.deleteCharAt(stringBuilder.length - 1) Toast.makeText(applicationContext!!, stringBuilder.toString(), Toast.LENGTH_LONG).show() } /** * @param plvUrls same sites */ private fun getSaveFragmentInfos(plvUrls: List<PLVUrl>): SaveFragmentInfo { val plvUrl = plvUrls[0] // set download directory val baseDir = Environment.getExternalStorageDirectory().resolve(preferences.getDownloadDir()) val dirType = preferences.getDownloadDirType() val dir = when (dirType) { DownloadDirType.MKDIR -> baseDir.resolve(plvUrl.siteName) DownloadDirType.MKDIR_USERNAME -> { if (plvUrl.username != null) { baseDir.resolve(plvUrl.siteName).resolve(plvUrl.username) } else { baseDir.resolve(plvUrl.siteName) } } DownloadDirType.NODIR, DownloadDirType.NODIR_USERNAME -> baseDir } dir.mkdirs() //check wifi connecting and setting or not var isWifi = false if (preferences.isWifiEnabled()) { // get wifi status val manager = activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager isWifi = manager.activeNetworkInfo?.type == ConnectivityManager.TYPE_WIFI } val original = preferences.isOriginalEnabled(isWifi) val infos = plvUrls.map { var fileName = when (dirType) { DownloadDirType.MKDIR, DownloadDirType.MKDIR_USERNAME -> it.fileName DownloadDirType.NODIR -> "${it.siteName}-${it.fileName}" DownloadDirType.NODIR_USERNAME -> { if (plvUrl.username != null) { "${it.siteName}-${it.username}-${it.fileName}" } else { "${it.siteName}-${it.fileName}" } } } it.type?.let { fileName += "." + it } SaveDialogFragment.Info(fileName, if (original) it.biggestUrl!! else it.displayUrl!!, it.thumbUrl!!) } return SaveFragmentInfo(dir.toString(), if (original) "biggest" else plvUrl.quality, infos) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == SAVE_DIALOG_CODE) { data?.let { saveOrRequestPermission(it.getStringExtra(SaveDialogFragment.DIR_KEY), it.getParcelableArrayListExtra(SaveDialogFragment.INFO_KEY)) } } else { val applicationContext = activity.applicationContext // request code > like or retweet // result code > row_id // intent > id_long val id_long = data!!.getLongExtra(TWITTER_ID_KEY, -1) val screenName = data.getStringExtra(TwitterDialogFragment.SCREEN_NAME_KEY) val twitter = AsyncTwitterFactory().instance with(PhotoLinkViewer.getTwitterKeys()) { twitter.setOAuthConsumer(consumerKey, consumerSecret) } with(PhotoLinkViewer.twitterTokenMap[screenName]!!) { twitter.oAuthAccessToken = AccessToken(accessToken, accessTokenSecret) } twitter.addListener(object : TwitterAdapter() { override fun onException(e: TwitterException?, twitterMethod: TwitterMethod?) { val message = "${getString(R.string.plv_core_twitter_error_toast)}: ${e!!.statusCode}\n(${e.errorMessage})" Handler(Looper.getMainLooper()).post { Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show() } } override fun createdFavorite(status: Status?) { Handler(Looper.getMainLooper()).post { Toast.makeText(applicationContext, applicationContext.getString(R.string.plv_core_twitter_like_toast), Toast.LENGTH_LONG).show() } } override fun retweetedStatus(status: Status?) { Handler(Looper.getMainLooper()).post { Toast.makeText(applicationContext, applicationContext.getString(R.string.plv_core_twitter_retweet_toast), Toast.LENGTH_LONG).show() } } }) when (requestCode) { LIKE_CODE -> twitter.createFavorite(id_long) RETWEET_CODE -> twitter.retweetStatus(id_long) } } } /** * this method see [isOpen] */ private fun getFilteredOptionButtonsFromPreference(includeDownload: Boolean): List<OptionButton> { return PreferenceManager.getDefaultSharedPreferences(context).getOptionButtons().filter { isOpen && when (it) { OptionButton.DOWNLOAD -> includeDownload OptionButton.TWEET_LIKE, OptionButton.TWEET_RETWEET -> arguments.getBoolean(TWITTER_ENABLED_KEY) else -> true } } } data class SaveFragmentInfo(val dirName: String, val quality: String?, val infoList: List<SaveDialogFragment.Info>) }
gpl-2.0
01535da3d8fd176bf87bfb097e879053
40.859023
155
0.624276
5.257082
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/applicators/ApplicabilityRanges.kt
3
2597
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.fir.applicators import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet import org.jetbrains.kotlin.idea.fir.api.applicator.applicabilityRange import org.jetbrains.kotlin.idea.fir.api.applicator.applicabilityRanges import org.jetbrains.kotlin.idea.fir.api.applicator.applicabilityTarget import org.jetbrains.kotlin.idea.util.nameIdentifierTextRangeInThis import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* object ApplicabilityRanges { val SELF = applicabilityTarget<PsiElement> { it } val CALLABLE_RETURN_TYPE = applicabilityTarget<KtCallableDeclaration> { decalration -> decalration.typeReference?.typeElement } val VISIBILITY_MODIFIER = modifier(KtTokens.VISIBILITY_MODIFIERS) private fun modifier(tokens: TokenSet) = applicabilityTarget<KtModifierListOwner> { declaration -> declaration.modifierList?.getModifier(tokens) } val VALUE_ARGUMENT_EXCLUDING_LAMBDA = applicabilityRanges<KtValueArgument> { element -> val expression = element.getArgumentExpression() ?: return@applicabilityRanges emptyList() if (expression is KtLambdaExpression) { // Use OUTSIDE of curly braces only as applicability ranges for lambda. // If we use the text range of the curly brace elements, it will include the inside of the braces. // This matches FE 1.0 behavior (see AddNameToArgumentIntention). listOfNotNull(TextRange(0, 0), TextRange(element.textLength, element.textLength)) } else { listOf(TextRange(0, element.textLength)) } } val DECLARATION_WITHOUT_INITIALIZER = applicabilityRange<KtCallableDeclaration> { val selfRange = TextRange(0, it.textLength) if (it !is KtDeclarationWithInitializer) return@applicabilityRange selfRange val initializer = it.initializer ?: return@applicabilityRange selfRange // The IDE seems to treat the end offset inclusively when checking if the caret is within the range. Hence we do minus one here // so that the intention is available from the following highlighted range. // val i = 1 // ^^^^^^^^ TextRange(0, initializer.startOffsetInParent - 1) } val DECLARATION_NAME = applicabilityTarget<KtNamedDeclaration> { element -> element.nameIdentifier } }
apache-2.0
3f0a73109b72291a428e90b750ef6444
47.111111
158
0.737004
4.881579
false
false
false
false
java-graphics/assimp
src/main/kotlin/assimp/format/fbx/fbxBinaryTokenizer.kt
2
9637
package assimp.format.fbx import assimp.pos import glm_.* import kool.BYTES import kool.rem import java.nio.ByteBuffer import kotlin.reflect.KMutableProperty0 /* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2017, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ /** @file FBXBinaryTokenizer.cpp * @brief Implementation of a fake lexer for binary fbx files - * we emit tokens so the parser needs almost no special handling * for binary files. */ //enum Flag //{ // e_unknown_0 = 1 << 0, // e_unknown_1 = 1 << 1, // e_unknown_2 = 1 << 2, // e_unknown_3 = 1 << 3, // e_unknown_4 = 1 << 4, // e_unknown_5 = 1 << 5, // e_unknown_6 = 1 << 6, // e_unknown_7 = 1 << 7, // e_unknown_8 = 1 << 8, // e_unknown_9 = 1 << 9, // e_unknown_10 = 1 << 10, // e_unknown_11 = 1 << 11, // e_unknown_12 = 1 << 12, // e_unknown_13 = 1 << 13, // e_unknown_14 = 1 << 14, // e_unknown_15 = 1 << 15, // e_unknown_16 = 1 << 16, // e_unknown_17 = 1 << 17, // e_unknown_18 = 1 << 18, // e_unknown_19 = 1 << 19, // e_unknown_20 = 1 << 20, // e_unknown_21 = 1 << 21, // e_unknown_22 = 1 << 22, // e_unknown_23 = 1 << 23, // e_flag_field_size_64_bit = 1 << 24, // Not sure what is // e_unknown_25 = 1 << 25, // e_unknown_26 = 1 << 26, // e_unknown_27 = 1 << 27, // e_unknown_28 = 1 << 28, // e_unknown_29 = 1 << 29, // e_unknown_30 = 1 << 30, // e_unknown_31 = 1 << 31 //}; // //bool check_flag(uint32_t flags, Flag to_check) //{ // return (flags & to_check) != 0; //} // signal tokenization error, this is always unrecoverable. Throws DeadlyImportError. fun tokenizeError(message: String, offset: Int): Nothing = throw Exception(Util.addOffset("FBX-Tokenize", message, offset)) fun tokenizeError(message: String, input: ByteBuffer): Nothing = tokenizeError(message, input.pos) fun ByteBuffer.readString(beginOut: KMutableProperty0<Int>? = null, endOut: KMutableProperty0<Int>? = null, longLength: Boolean = false, allowNull: Boolean = false): Int { val lenLen = if (longLength) 4 else 1 if (remaining() < lenLen) tokenizeError("cannot ReadString, out of bounds reading length", this) val length = if (longLength) int else get().i if (remaining() < length) tokenizeError("cannot ReadString, length is out of bounds", this) val b = pos beginOut?.set(pos) pos += length endOut?.set(pos) if (!allowNull) for (i in 0 until length) if (get(b + i) == 0.b) tokenizeError("failed ReadString, unexpected NUL character in string", this) return length } fun ByteBuffer.readData(beginOut: KMutableProperty0<Int>, endOut: KMutableProperty0<Int>) { if (remaining() < 1) tokenizeError("cannot ReadData, out of bounds reading length", this) val type = get(pos).c beginOut.set(pos++) when (type) { // 16 bit int 'Y' -> pos += Short.BYTES // 1 bit bool flag (yes/no) 'C' -> pos++ // 32 bit int or float 'I', 'F' -> pos += Int.BYTES // double 'D' -> pos += Double.BYTES // 64 bit int 'L' -> pos += Long.BYTES // note: do not write cursor += ReadWord(...cursor) as this would be UB // raw binary data 'R' -> { val length = int pos += length } // array of * 'b', 'c', 'f', 'd', 'l', 'i' -> { val length = int val encoding = int val compLen = int // compute length based on type and check against the stored value if (encoding == 0) { val stride = when (type) { 'b', 'c' -> 1 'f', 'i' -> 4 'd', 'l' -> 8 else -> throw Exception("invalid type") } if (length * stride != compLen) tokenizeError("cannot ReadData, calculated data stride differs from what the file claims", this) } // zip/deflate algorithm (encoding==1)? take given length. anything else? die else if (encoding != 1) tokenizeError("cannot ReadData, unknown encoding", this) pos += compLen } // string 'S' -> readString(longLength = true, allowNull = true) // 0 characters can legally happen in such strings else -> tokenizeError("cannot ReadData, unexpected type code: $type", this) } if (pos > capacity()) tokenizeError("cannot ReadData, the remaining size is too small for the data type: $type", this) // the type code is contained in the returned range endOut.set(pos) } fun readScope(outputTokens: ArrayList<Token>, input: ByteBuffer, end: Int, is64bits: Boolean): Boolean { // the first word contains the offset at which this block ends val endOffset = if (is64bits) input.double.i else input.int /* we may get 0 if reading reached the end of the file - fbx files have a mysterious extra footer which I don't know how to extract any information from, but at least it always starts with a 0. */ if (endOffset == 0) return false if (endOffset > end) tokenizeError("block offset is out of range", input) else if (endOffset < input.pos) tokenizeError("block offset is negative out of range", input) // the second data word contains the number of properties in the scope val propCount = if (is64bits) input.double.i else input.int // the third data word contains the length of the property list val propLength = if (is64bits) input.double.i else input.int // now comes the name of the scope/key input.readString(::sBeg, ::sEnd) outputTokens.add(Token(sBeg, sEnd, TokenType.KEY, input.pos)) // now come the individual properties val beginCursor = input.pos repeat(propCount) { val begin = input.pos input.readData(::sBeg, ::sEnd) outputTokens.add(Token(sBeg, sEnd, TokenType.DATA, input.pos)) if (it != propCount - 1) outputTokens.add(Token(input.pos, input.pos + 1, TokenType.COMMA, input.pos)) } if (input.pos - beginCursor != propLength) tokenizeError("property length not reached, something is wrong", input) /* at the end of each nested block, there is a NUL record to indicate that the sub-scope exists (i.e. to distinguish between P: and P : {}) this NUL record is 13 bytes long on 32 bit version and 25 bytes long on 64 bit. */ val sentinelBlockLength = (if (is64bits) Long.BYTES else Int.BYTES) * 3 + 1 if (input.pos < endOffset) { if (endOffset - input.pos < sentinelBlockLength) tokenizeError("insufficient padding bytes at block end", input) outputTokens.add(Token(input.pos, input.pos + 1, TokenType.OPEN_BRACKET, input.pos)) // XXX this is vulnerable to stack overflowing .. while (input.pos < endOffset - sentinelBlockLength) readScope(outputTokens, input, endOffset - sentinelBlockLength, is64bits) outputTokens.add(Token(input.pos, input.pos + 1, TokenType.CLOSE_BRACKET, input.pos)) for (i in 0 until sentinelBlockLength) if (input.get(input.pos + i) != 0.b) tokenizeError("failed to read nested block sentinel, expected all bytes to be 0", input) input.pos += sentinelBlockLength } if (input.pos != endOffset) tokenizeError("scope length not reached, something is wrong", input) return true } private var sBeg = -1 private var sEnd = -1 // TODO: Test FBX Binary files newer than the 7500 version to check if the 64 bits address behaviour is consistent fun tokenizeBinary(outputTokens: ArrayList<Token>, input: ByteBuffer) { if (input.rem < 0x1b) tokenizeError("file is too short", 0) /*Result ignored*/ input.get() /*Result ignored*/ input.get() /*Result ignored*/ input.get() /*Result ignored*/ input.get() /*Result ignored*/ input.get() val version = input.int val is64bits = version >= 7500 while (true) if (!readScope(outputTokens, input, input.capacity(), is64bits)) break }
bsd-3-clause
8bc845c4129b8920a16389209f49428f
35.923372
171
0.638165
3.889023
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/viewmodels/RewardListViewModel.kt
1
3077
/* * Copyright 2020 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.app.playhvz.firebase.viewmodels import android.util.Log import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import com.app.playhvz.app.EspressoIdlingResource import com.app.playhvz.app.HvzData import com.app.playhvz.firebase.classmodels.Reward import com.app.playhvz.firebase.operations.RewardDatabaseOperations import com.app.playhvz.firebase.utils.DataConverterUtil import kotlinx.coroutines.runBlocking class RewardListViewModel : ViewModel() { companion object { private val TAG = RewardListViewModel::class.qualifiedName } private var rewardList: HvzData<List<Reward>> = HvzData(listOf()) /** Listens to all reward updates and returns a LiveData object. */ fun getAllRewardsInGame( gameId: String ): LiveData<List<Reward>> { rewardList.docIdListeners[gameId] = RewardDatabaseOperations.getRewardCollectionReference(gameId) .addSnapshotListener { querySnapshot, e -> if (e != null) { Log.w(TAG, "Listen to reward collection failed. ", e) rewardList.value = emptyList() return@addSnapshotListener } if (querySnapshot == null || querySnapshot.isEmpty || querySnapshot.documents.isEmpty()) { rewardList.value = emptyList() return@addSnapshotListener } val updatedList: MutableList<Reward> = mutableListOf() for (rewardSnapshot in querySnapshot.documents) { updatedList.add(DataConverterUtil.convertSnapshotToReward(rewardSnapshot)) } rewardList.value = updatedList } return rewardList } /** ONE TIME gets the current count of unused claim codes. */ fun getCurrentClaimedCount( gameId: String, rewardId: String, onSuccess: (rewardId: String, unusedCount: Int, total: Int) -> Unit ) { val success = { unusedCount: Int, total: Int -> onSuccess.invoke(rewardId, unusedCount, total) } val fail = {} runBlocking { EspressoIdlingResource.increment() RewardDatabaseOperations.asyncGetCurrentClaimCodeCount(gameId, rewardId, success, fail) EspressoIdlingResource.decrement() } } }
apache-2.0
67b632d5d029f687288fa7e30db7d68d
38.461538
110
0.652259
5.069193
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/Cell.kt
1
28611
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.layout import com.intellij.BundleBase import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.ui.UINumericRange import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.util.bind import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.ui.emptyText import com.intellij.openapi.ui.panel.ComponentPanelBuilder import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.NlsContexts.* import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.* import com.intellij.ui.components.* import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.util.Function import com.intellij.util.execution.ParametersListUtil import com.intellij.util.ui.JBFont import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import java.awt.Component import java.awt.Dimension import java.awt.event.* import java.util.* import javax.swing.* import javax.swing.text.JTextComponent import kotlin.jvm.internal.CallableReference import kotlin.reflect.KMutableProperty0 @DslMarker annotation class CellMarker data class PropertyBinding<V>(val get: () -> V, val set: (V) -> Unit) @PublishedApi @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") internal fun <T> createPropertyBinding(prop: KMutableProperty0<T>, propType: Class<T>): PropertyBinding<T> { if (prop is CallableReference) { val name = prop.name val receiver = (prop as CallableReference).boundReceiver if (receiver != null) { val baseName = name.removePrefix("is") val nameCapitalized = StringUtil.capitalize(baseName) val getterName = if (name.startsWith("is")) name else "get$nameCapitalized" val setterName = "set$nameCapitalized" val receiverClass = receiver::class.java try { val getter = receiverClass.getMethod(getterName) val setter = receiverClass.getMethod(setterName, propType) return PropertyBinding({ getter.invoke(receiver) as T }, { setter.invoke(receiver, it) }) } catch (e: Exception) { // ignore } try { val field = receiverClass.getDeclaredField(name) field.isAccessible = true return PropertyBinding({ field.get(receiver) as T }, { field.set(receiver, it) }) } catch (e: Exception) { // ignore } } } return PropertyBinding(prop.getter, prop.setter) } @Deprecated("Use MutableProperty and Kotlin UI DSL 2") fun <T> PropertyBinding<T>.toNullable(): PropertyBinding<T?> { return PropertyBinding<T?>({ get() }, { set(it!!) }) } inline fun <reified T : Any> KMutableProperty0<T>.toBinding(): PropertyBinding<T> { return createPropertyBinding(this, T::class.javaPrimitiveType ?: T::class.java) } inline fun <reified T : Any> KMutableProperty0<T?>.toNullableBinding(defaultValue: T): PropertyBinding<T> { return PropertyBinding({ get() ?: defaultValue }, { set(it) }) } class ValidationInfoBuilder(val component: JComponent) { fun error(@DialogMessage message: String): ValidationInfo = ValidationInfo(message, component) fun warning(@DialogMessage message: String): ValidationInfo = ValidationInfo(message, component).asWarning().withOKEnabled() } @JvmDefaultWithCompatibility interface CellBuilder<out T : JComponent> { val component: T fun comment(@DetailedDescription text: String, maxLineLength: Int = ComponentPanelBuilder.MAX_COMMENT_WIDTH, forComponent: Boolean = false): CellBuilder<T> fun focused(): CellBuilder<T> fun withValidationOnApply(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T> fun withValidationOnInput(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T> fun onApply(callback: () -> Unit): CellBuilder<T> fun onReset(callback: () -> Unit): CellBuilder<T> fun onIsModified(callback: () -> Boolean): CellBuilder<T> /** * All components of the same group share will get the same BoundSize (min/preferred/max), * which is that of the biggest component in the group */ @Deprecated("Use Kotlin UI DSL Version 2, see Cell.widthGroup()") fun sizeGroup(name: String): CellBuilder<T> @Deprecated("Use Kotlin UI DSL Version 2") fun growPolicy(growPolicy: GrowPolicy): CellBuilder<T> fun constraints(vararg constraints: CCFlags): CellBuilder<T> /** * If this method is called, the value of the component will be stored to the backing property only if the component is enabled. */ fun applyIfEnabled(): CellBuilder<T> @ApiStatus.Experimental fun accessibleName(@Nls name: String): CellBuilder<T> { component.accessibleContext.accessibleName = name return this } @ApiStatus.Experimental fun accessibleDescription(@Nls description: String): CellBuilder<T> { component.accessibleContext.accessibleDescription = description return this } fun <V> withBinding( componentGet: (T) -> V, componentSet: (T, V) -> Unit, modelBinding: PropertyBinding<V> ): CellBuilder<T> { onApply { if (shouldSaveOnApply()) modelBinding.set(componentGet(component)) } onReset { componentSet(component, modelBinding.get()) } onIsModified { shouldSaveOnApply() && componentGet(component) != modelBinding.get() } return this } fun withGraphProperty(property: GraphProperty<*>): CellBuilder<T> fun enabled(isEnabled: Boolean) fun enableIf(predicate: ComponentPredicate): CellBuilder<T> fun visible(isVisible: Boolean) fun visibleIf(predicate: ComponentPredicate): CellBuilder<T> fun withErrorOnApplyIf(@DialogMessage message: String, callback: (T) -> Boolean): CellBuilder<T> { withValidationOnApply { if (callback(it)) error(message) else null } return this } @ApiStatus.Internal fun shouldSaveOnApply(): Boolean fun withLargeLeftGap(): CellBuilder<T> fun withLeftGap(): CellBuilder<T> @Deprecated("Prefer not to use hardcoded values") @ApiStatus.ScheduledForRemoval fun withLeftGap(gapLeft: Int): CellBuilder<T> } @Deprecated("Use Kotlin UI DSL Version 2") internal interface CheckboxCellBuilder { @Deprecated("Use Kotlin UI DSL Version 2") fun actsAsLabel() } @Deprecated("Use Kotlin UI DSL Version 2") fun <T : JCheckBox> CellBuilder<T>.actsAsLabel(): CellBuilder<T> { (this as CheckboxCellBuilder).actsAsLabel() return this } fun <T : JComponent> CellBuilder<T>.applyToComponent(task: T.() -> Unit): CellBuilder<T> { return also { task(component) } } @Deprecated("Use Kotlin UI DSL Version 2") internal interface ScrollPaneCellBuilder { @Deprecated("Use Kotlin UI DSL Version 2") fun noGrowY() } @Deprecated("Use Kotlin UI DSL Version 2") fun <T : JScrollPane> CellBuilder<T>.noGrowY(): CellBuilder<T> { (this as ScrollPaneCellBuilder).noGrowY() return this } fun <T : JTextComponent> CellBuilder<T>.withTextBinding(modelBinding: PropertyBinding<String>): CellBuilder<T> { return withBinding(JTextComponent::getText, JTextComponent::setText, modelBinding) } fun <T : AbstractButton> CellBuilder<T>.withSelectedBinding(modelBinding: PropertyBinding<Boolean>): CellBuilder<T> { return withBinding(AbstractButton::isSelected, AbstractButton::setSelected, modelBinding) } val CellBuilder<AbstractButton>.selected get() = component.selected const val UNBOUND_RADIO_BUTTON = "unbound.radio.button" // separate class to avoid row related methods in the `cell { } ` @CellMarker abstract class Cell : BaseBuilder { /** * Sets how keen the component should be to grow in relation to other component **in the same cell**. Use `push` in addition if need. * If this constraint is not set the grow weight is set to 0 and the component will not grow (unless some automatic rule is not applied (see [com.intellij.ui.layout.panel])). * Grow weight will only be compared against the weights for the same cell. */ val growX = CCFlags.growX val growY = CCFlags.growY val grow = CCFlags.grow /** * Makes the column that the component is residing in grow with `weight`. */ val pushX = CCFlags.pushX /** * Makes the row that the component is residing in grow with `weight`. */ val pushY = CCFlags.pushY val push = CCFlags.push fun label(@Label text: String, style: UIUtil.ComponentStyle? = null, fontColor: UIUtil.FontColor? = null, bold: Boolean = false): CellBuilder<JLabel> { val label = Label(text, style, fontColor, bold) return component(label) } fun label(@Label text: String, font: JBFont, fontColor: UIUtil.FontColor? = null): CellBuilder<JLabel> { val label = Label(text, fontColor = fontColor, font = font) return component(label) } fun link(@LinkLabel text: String, style: UIUtil.ComponentStyle? = null, action: () -> Unit): CellBuilder<JComponent> { val result = Link(text, style, action) return component(result) } fun browserLink(@LinkLabel text: String, url: String): CellBuilder<JComponent> { val result = BrowserLink(text, url) return component(result) } @Deprecated("Use Kotlin UI DSL Version 2") fun buttonFromAction(@Button text: String, @NonNls actionPlace: String, action: AnAction): CellBuilder<JButton> { val button = JButton(BundleBase.replaceMnemonicAmpersand(text)) button.addActionListener { ActionUtil.invokeAction(action, button, actionPlace, null, null) } return component(button) } fun button(@Button text: String, actionListener: (event: ActionEvent) -> Unit): CellBuilder<JButton> { val button = JButton(BundleBase.replaceMnemonicAmpersand(text)) button.addActionListener(actionListener) return component(button) } inline fun checkBox(@Checkbox text: String, isSelected: Boolean = false, @DetailedDescription comment: String? = null, crossinline actionListener: (event: ActionEvent, component: JCheckBox) -> Unit): CellBuilder<JBCheckBox> { return checkBox(text, isSelected, comment) .applyToComponent { addActionListener(ActionListener { actionListener(it, this) }) } } @JvmOverloads fun checkBox(@Checkbox text: String, isSelected: Boolean = false, @DetailedDescription comment: String? = null): CellBuilder<JBCheckBox> { val result = JBCheckBox(text, isSelected) return result(comment = comment) } fun checkBox(@Checkbox text: String, prop: KMutableProperty0<Boolean>, @DetailedDescription comment: String? = null): CellBuilder<JBCheckBox> { return checkBox(text, prop.toBinding(), comment) } fun checkBox(@Checkbox text: String, getter: () -> Boolean, setter: (Boolean) -> Unit, @DetailedDescription comment: String? = null): CellBuilder<JBCheckBox> { return checkBox(text, PropertyBinding(getter, setter), comment) } private fun checkBox(@Checkbox text: String, modelBinding: PropertyBinding<Boolean>, @DetailedDescription comment: String?): CellBuilder<JBCheckBox> { val component = JBCheckBox(text, modelBinding.get()) return component(comment = comment).withSelectedBinding(modelBinding) } fun checkBox(@Checkbox text: String, property: GraphProperty<Boolean>, @DetailedDescription comment: String? = null): CellBuilder<JBCheckBox> { val component = JBCheckBox(text, property.get()) return component(comment = comment).withGraphProperty(property).applyToComponent { component.bind(property) } } open fun radioButton(@RadioButton text: String, @Nls comment: String? = null): CellBuilder<JBRadioButton> { val component = JBRadioButton(text) component.putClientProperty(UNBOUND_RADIO_BUTTON, true) return component(comment = comment) } @Deprecated("Use Kotlin UI DSL Version 2") open fun radioButton(@RadioButton text: String, getter: () -> Boolean, setter: (Boolean) -> Unit, @Nls comment: String? = null): CellBuilder<JBRadioButton> { val component = JBRadioButton(text, getter()) return component(comment = comment).withSelectedBinding(PropertyBinding(getter, setter)) } @Deprecated("Use Kotlin UI DSL Version 2") open fun radioButton(@RadioButton text: String, prop: KMutableProperty0<Boolean>, @Nls comment: String? = null): CellBuilder<JBRadioButton> { val component = JBRadioButton(text, prop.get()) return component(comment = comment).withSelectedBinding(prop.toBinding()) } fun <T> comboBox(model: ComboBoxModel<T>, getter: () -> T?, setter: (T?) -> Unit, renderer: ListCellRenderer<T?>? = null): CellBuilder<ComboBox<T>> { return comboBox(model, PropertyBinding(getter, setter), renderer) } fun <T> comboBox(model: ComboBoxModel<T>, modelBinding: PropertyBinding<T?>, renderer: ListCellRenderer<T?>? = null): CellBuilder<ComboBox<T>> { return component(ComboBox(model)) .applyToComponent { this.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() } selectedItem = modelBinding.get() } .withBinding( { component -> component.selectedItem as T? }, { component, value -> component.setSelectedItem(value) }, modelBinding ) } inline fun <reified T : Any> comboBox( model: ComboBoxModel<T>, prop: KMutableProperty0<T>, renderer: ListCellRenderer<T?>? = null ): CellBuilder<ComboBox<T>> { return comboBox(model, prop.toBinding().toNullable(), renderer) } fun <T> comboBox( model: ComboBoxModel<T>, property: GraphProperty<T>, renderer: ListCellRenderer<T?>? = null ): CellBuilder<ComboBox<T>> { return comboBox(model, PropertyBinding(property::get, property::set).toNullable(), renderer) .withGraphProperty(property) .applyToComponent { bind(property) } } fun textField(prop: KMutableProperty0<String>, columns: Int? = null): CellBuilder<JBTextField> = textField(prop.toBinding(), columns) fun textField(getter: () -> String, setter: (String) -> Unit, columns: Int? = null) = textField(PropertyBinding(getter, setter), columns) fun textField(binding: PropertyBinding<String>, columns: Int? = null): CellBuilder<JBTextField> { return component(JBTextField(binding.get(), columns ?: 0)) .withTextBinding(binding) } fun textField(property: GraphProperty<String>, columns: Int? = null): CellBuilder<JBTextField> { return textField(property::get, property::set, columns) .withGraphProperty(property) .applyToComponent { bind(property) } } fun textArea(prop: KMutableProperty0<String>, rows: Int? = null, columns: Int? = null): CellBuilder<JBTextArea> = textArea(prop.toBinding(), rows, columns) fun textArea(getter: () -> String, setter: (String) -> Unit, rows: Int? = null, columns: Int? = null) = textArea(PropertyBinding(getter, setter), rows, columns) fun textArea(binding: PropertyBinding<String>, rows: Int? = null, columns: Int? = null): CellBuilder<JBTextArea> { return component(JBTextArea(binding.get(), rows ?: 0, columns ?: 0)) .withTextBinding(binding) } fun textArea(property: GraphProperty<String>, rows: Int? = null, columns: Int? = null): CellBuilder<JBTextArea> { return textArea(property::get, property::set, rows, columns) .withGraphProperty(property) .applyToComponent { bind(property) } } fun scrollableTextArea(prop: KMutableProperty0<String>, rows: Int? = null): CellBuilder<JBTextArea> = scrollableTextArea(prop.toBinding(), rows) fun scrollableTextArea(getter: () -> String, setter: (String) -> Unit, rows: Int? = null) = scrollableTextArea(PropertyBinding(getter, setter), rows) private fun scrollableTextArea(binding: PropertyBinding<String>, rows: Int? = null): CellBuilder<JBTextArea> { val textArea = JBTextArea(binding.get(), rows ?: 0, 0) val scrollPane = JBScrollPane(textArea) return component(textArea, scrollPane) .withTextBinding(binding) } fun scrollableTextArea(property: GraphProperty<String>, rows: Int? = null): CellBuilder<JBTextArea> { return scrollableTextArea(property::get, property::set, rows) .withGraphProperty(property) .applyToComponent { bind(property) } } @JvmOverloads @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") fun intTextField(prop: KMutableProperty0<Int>, columns: Int? = null, range: IntRange? = null): CellBuilder<JBTextField> { val binding = prop.toBinding() return textField( { binding.get().toString() }, { value -> value.toIntOrNull()?.let { intValue -> binding.set(range?.let { intValue.coerceIn(it.first, it.last) } ?: intValue) } }, columns ).withValidationOnInput { val value = it.text.toIntOrNull() when { value == null -> error(UIBundle.message("please.enter.a.number")) range != null && value !in range -> error(UIBundle.message("please.enter.a.number.from.0.to.1", range.first, range.last)) else -> null } } } fun spinner(prop: KMutableProperty0<Int>, minValue: Int, maxValue: Int, step: Int = 1): CellBuilder<JBIntSpinner> { val spinner = JBIntSpinner(prop.get(), minValue, maxValue, step) return component(spinner).withBinding(JBIntSpinner::getNumber, JBIntSpinner::setNumber, prop.toBinding()) } fun spinner(getter: () -> Int, setter: (Int) -> Unit, minValue: Int, maxValue: Int, step: Int = 1): CellBuilder<JBIntSpinner> { val spinner = JBIntSpinner(getter(), minValue, maxValue, step) return component(spinner).withBinding(JBIntSpinner::getNumber, JBIntSpinner::setNumber, PropertyBinding(getter, setter)) } fun textFieldWithHistoryWithBrowseButton( getter: () -> String, setter: (String) -> Unit, @DialogTitle browseDialogTitle: String, project: Project? = null, fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), historyProvider: (() -> List<String>)? = null, fileChosen: ((chosenFile: VirtualFile) -> String)? = null ): CellBuilder<TextFieldWithHistoryWithBrowseButton> { val textField = textFieldWithHistoryWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, historyProvider, fileChosen) val modelBinding = PropertyBinding(getter, setter) textField.text = modelBinding.get() return component(textField) .withBinding(TextFieldWithHistoryWithBrowseButton::getText, TextFieldWithHistoryWithBrowseButton::setText, modelBinding) } fun textFieldWithBrowseButton( @DialogTitle browseDialogTitle: String? = null, value: String? = null, project: Project? = null, fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), fileChosen: ((chosenFile: VirtualFile) -> String)? = null ): CellBuilder<TextFieldWithBrowseButton> { val textField = textFieldWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, fileChosen) if (value != null) textField.text = value return component(textField) } fun textFieldWithBrowseButton( prop: KMutableProperty0<String>, @DialogTitle browseDialogTitle: String? = null, project: Project? = null, fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), fileChosen: ((chosenFile: VirtualFile) -> String)? = null ): CellBuilder<TextFieldWithBrowseButton> { val modelBinding = prop.toBinding() return textFieldWithBrowseButton(modelBinding, browseDialogTitle, project, fileChooserDescriptor, fileChosen) } fun textFieldWithBrowseButton( getter: () -> String, setter: (String) -> Unit, @DialogTitle browseDialogTitle: String? = null, project: Project? = null, fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), fileChosen: ((chosenFile: VirtualFile) -> String)? = null ): CellBuilder<TextFieldWithBrowseButton> { val modelBinding = PropertyBinding(getter, setter) return textFieldWithBrowseButton(modelBinding, browseDialogTitle, project, fileChooserDescriptor, fileChosen) } fun textFieldWithBrowseButton( modelBinding: PropertyBinding<String>, @DialogTitle browseDialogTitle: String? = null, project: Project? = null, fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), fileChosen: ((chosenFile: VirtualFile) -> String)? = null ): CellBuilder<TextFieldWithBrowseButton> { val textField = textFieldWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, fileChosen) textField.text = modelBinding.get() return component(textField) .constraints(growX) .withBinding(TextFieldWithBrowseButton::getText, TextFieldWithBrowseButton::setText, modelBinding) } fun textFieldWithBrowseButton( property: GraphProperty<String>, emptyTextProperty: GraphProperty<String>, @DialogTitle browseDialogTitle: String? = null, project: Project? = null, fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), fileChosen: ((chosenFile: VirtualFile) -> String)? = null ): CellBuilder<TextFieldWithBrowseButton> { return textFieldWithBrowseButton(property, browseDialogTitle, project, fileChooserDescriptor, fileChosen) .applyToComponent { emptyText.bind(emptyTextProperty) } .applyToComponent { emptyText.text = emptyTextProperty.get() } } fun textFieldWithBrowseButton( property: GraphProperty<String>, @DialogTitle browseDialogTitle: String? = null, project: Project? = null, fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), fileChosen: ((chosenFile: VirtualFile) -> String)? = null ): CellBuilder<TextFieldWithBrowseButton> { return textFieldWithBrowseButton(property::get, property::set, browseDialogTitle, project, fileChooserDescriptor, fileChosen) .withGraphProperty(property) .applyToComponent { bind(property) } } fun gearButton(vararg actions: AnAction): CellBuilder<JComponent> { val label = JLabel(LayeredIcon.GEAR_WITH_DROPDOWN) label.disabledIcon = AllIcons.General.GearPlain object : ClickListener() { override fun onClick(e: MouseEvent, clickCount: Int): Boolean { if (!label.isEnabled) return true JBPopupFactory.getInstance() .createActionGroupPopup(null, DefaultActionGroup(*actions), DataManager.getInstance().getDataContext(label), true, null, 10) .showUnderneathOf(label) return true } }.installOn(label) return component(label) } fun expandableTextField(getter: () -> String, setter: (String) -> Unit, parser: Function<in String, out MutableList<String>> = ParametersListUtil.DEFAULT_LINE_PARSER, joiner: Function<in MutableList<String>, String> = ParametersListUtil.DEFAULT_LINE_JOINER) : CellBuilder<ExpandableTextField> { return ExpandableTextField(parser, joiner)() .withBinding({ editor -> editor.text.orEmpty() }, { editor, value -> editor.text = value }, PropertyBinding(getter, setter)) } fun expandableTextField(prop: KMutableProperty0<String>, parser: Function<in String, out MutableList<String>> = ParametersListUtil.DEFAULT_LINE_PARSER, joiner: Function<in MutableList<String>, String> = ParametersListUtil.DEFAULT_LINE_JOINER) : CellBuilder<ExpandableTextField> { return expandableTextField(prop::get, prop::set, parser, joiner) } fun expandableTextField(prop: GraphProperty<String>, parser: Function<in String, out MutableList<String>> = ParametersListUtil.DEFAULT_LINE_PARSER, joiner: Function<in MutableList<String>, String> = ParametersListUtil.DEFAULT_LINE_JOINER) : CellBuilder<ExpandableTextField> { return expandableTextField(prop::get, prop::set, parser, joiner) .withGraphProperty(prop) .applyToComponent { bind(prop) } } /** * @see LayoutBuilder.titledRow */ @JvmOverloads fun panel(@BorderTitle title: String, wrappedComponent: Component, hasSeparator: Boolean = true): CellBuilder<JPanel> { val panel = Panel(title, hasSeparator) panel.add(wrappedComponent) return component(panel) } fun scrollPane(component: Component): CellBuilder<JScrollPane> { return component(JBScrollPane(component)) } @Deprecated("Use Kotlin UI DSL Version 2") fun comment(@DetailedDescription text: String, maxLineLength: Int = -1): CellBuilder<JLabel> { return component(ComponentPanelBuilder.createCommentComponent(text, true, maxLineLength, true)) } @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") fun commentNoWrap(@DetailedDescription text: String): CellBuilder<JLabel> { return component(ComponentPanelBuilder.createNonWrappingCommentComponent(text)) } @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") fun placeholder(): CellBuilder<JComponent> { return component(JPanel().apply { minimumSize = Dimension(0, 0) preferredSize = Dimension(0, 0) maximumSize = Dimension(0, 0) }) } abstract fun <T : JComponent> component(component: T): CellBuilder<T> abstract fun <T : JComponent> component(component: T, viewComponent: JComponent): CellBuilder<T> operator fun <T : JComponent> T.invoke( vararg constraints: CCFlags, growPolicy: GrowPolicy? = null, @DetailedDescription comment: String? = null ): CellBuilder<T> = component(this).apply { constraints(*constraints) if (comment != null) comment(comment) if (growPolicy != null) growPolicy(growPolicy) } } class InnerCell(val cell: Cell) : Cell() { override fun <T : JComponent> component(component: T): CellBuilder<T> { return cell.component(component) } override fun <T : JComponent> component(component: T, viewComponent: JComponent): CellBuilder<T> { return cell.component(component, viewComponent) } @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") override fun withButtonGroup(title: String?, buttonGroup: ButtonGroup, body: () -> Unit) { cell.withButtonGroup(title, buttonGroup, body) } } fun <T> listCellRenderer(renderer: SimpleListCellRenderer<T?>.(value: T, index: Int, isSelected: Boolean) -> Unit): SimpleListCellRenderer<T?> { return object : SimpleListCellRenderer<T?>() { override fun customize(list: JList<out T?>, value: T?, index: Int, selected: Boolean, hasFocus: Boolean) { if (value != null) { renderer(this, value, index, selected) } } } } @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") fun Cell.slider(min: Int, max: Int, minorTick: Int, majorTick: Int): CellBuilder<JSlider> { val slider = JSlider() UIUtil.setSliderIsFilled(slider, true) slider.paintLabels = true slider.paintTicks = true slider.paintTrack = true slider.minimum = min slider.maximum = max slider.minorTickSpacing = minorTick slider.majorTickSpacing = majorTick return slider() } @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") fun <T : JSlider> CellBuilder<T>.labelTable(table: Hashtable<Int, JComponent>.() -> Unit): CellBuilder<T> { component.labelTable = Hashtable<Int, JComponent>().apply(table) return this } @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") fun <T : JSlider> CellBuilder<T>.withValueBinding(modelBinding: PropertyBinding<Int>): CellBuilder<T> { return withBinding(JSlider::getValue, JSlider::setValue, modelBinding) } fun UINumericRange.asRange(): IntRange = min..max
apache-2.0
eb07da7240424d97f239427d763e9674
40.050215
176
0.719444
4.66205
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/DiagnosticSuppressorForDebugger.kt
4
851
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.core import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.psi.KtCodeFragment import org.jetbrains.kotlin.resolve.diagnostics.DiagnosticSuppressor class DiagnosticSuppressorForDebugger : DiagnosticSuppressor { override fun isSuppressed(diagnostic: Diagnostic): Boolean { val element = diagnostic.psiElement val containingFile = element.containingFile if (containingFile is KtCodeFragment) { val diagnosticFactory = diagnostic.factory return diagnosticFactory == Errors.UNSAFE_CALL } return false } }
apache-2.0
0b332ef8ca0c9d7fa2b69cfb028bf5c4
37.681818
158
0.759107
5.005882
false
false
false
false
Lizhny/BigDataFortuneTelling
baseuilib/src/main/java/com/bdft/baseuilib/widget/indicator/DotWidget.kt
1
13427
package com.bdft.baseuilib.widget.indicator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.OvalShape import android.graphics.drawable.shapes.RoundRectShape import android.graphics.drawable.shapes.Shape import android.text.TextUtils import android.util.AttributeSet import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.animation.AlphaAnimation import android.view.animation.Animation import android.view.animation.DecelerateInterpolator import android.widget.FrameLayout import com.bdft.baselibrary.utils.ui.UIUtils import com.socks.library.KLog /** * ${} * Created by spark_lizhy on 2017/10/28. */ class DotWidget @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.textViewStyle ) : View(context, attrs, defStyleAttr) { private val TAG = "DotWidget" private val DEAFULT_DOT_COLOR = Color.RED private val DEAFULT_DOT_REDIUS = 10 private val DEAFULT_DOT_SIZE = 10 private val DEAFULT_DOT_TEXT_COLOR = Color.WHITE private lateinit var mTargetView: View private lateinit var mContainer: FrameLayout private lateinit var mMarginRect: Rect /** * 显示模式 * <p/> * GRAVITY_TOP_LEFT 顶部居左 * <p/> * GRAVITY_TOP_RIGHT 顶部居右 * <p/> * GRAVITY_BOTTOM_LEFT 底部居左 * <p/> * GRAVITY_BOTTOM_RIGHT 底部居右 * <p/> * GRAVITY_CENTER 居中 * <p/> * GRAVITY_CENTER_VERTICAL 垂直居中 * <p/> * GRAVITY_CENTER_HORIZONTAL 水平居中 * <p/> * GRAVITY_LEFT_CENTER 左边居中 * <p/> * GRAVITY_RIGHT_CENTER 右边居中 * <p/> */ public enum class DotGravity { GRAVITY_TOP_LEFT, GRAVITY_TOP_RIGHT, GRAVITY_BOTTOM_LEFT, GRAVITY_BOTTOM_RIGHT, GRAVITY_CENTER, GRAVITY_CENTER_VERTICAL, GRAVITY_CENTER_HORIZONTAL, GRAVITY_LEFT_CENTER, GRAVITY_RIGHT_CENTER } lateinit private var mDotGravity: DotGravity public enum class Mode { ROUND_RECT, CIRCLE } private var mode = Mode.CIRCLE private var mDotColor = DEAFULT_DOT_COLOR private var mDotSize = DEAFULT_DOT_SIZE private var mDotRadius = DEAFULT_DOT_REDIUS private var mDotTextColor = DEAFULT_DOT_TEXT_COLOR private var mDotTextSize = 0 private var mDotBackground: ShapeDrawable?=null private var mDotText = "" private var mIsShowing = false private var mNeedReDraw = false private lateinit var mFadeIn: AlphaAnimation private lateinit var mFadeOut: AlphaAnimation constructor(context: Context, target: View) : this(context) { initView(target) } private fun initView(target: View?) { if (target == null) return mTargetView = target mDotGravity = DotGravity.GRAVITY_TOP_RIGHT mMarginRect = Rect() mIsShowing = false buildDefaultAnim() } private fun buildDefaultAnim() { mFadeIn = AlphaAnimation(0f, 1f) mFadeIn.interpolator = DecelerateInterpolator() mFadeIn.duration = 450 mFadeIn.setAnimationListener(mAnimListener) mFadeOut = AlphaAnimation(0f, 1f) mFadeOut.interpolator = DecelerateInterpolator() mFadeOut.duration = 450 mFadeOut.setAnimationListener(mAnimListener) } private fun addDot(target: View) { val targetViewParams = target.layoutParams val newTargetViewParams = ViewGroup.LayoutParams(targetViewParams.width, targetViewParams.height) targetViewParams.width = ViewGroup.LayoutParams.WRAP_CONTENT targetViewParams.height = ViewGroup.LayoutParams.WRAP_CONTENT //new 一个容器 mContainer = FrameLayout(context) mContainer.clipToPadding = false val parent = target.parent as ViewGroup val index = parent.indexOfChild(target) //去掉目标View parent.removeView(target) parent.addView(mContainer, index, targetViewParams) //容器添加目标View mContainer.addView(target, newTargetViewParams) visibility = GONE //容器添加DotWidget(红点) mContainer.addView(this) parent.invalidate() } public fun show() { show(false) } public fun show(needAnim: Boolean) { show(needAnim, mFadeIn) } private fun show(needAnim: Boolean, animation: Animation?) { if (mIsShowing) return if (background == null || mNeedReDraw || mDotBackground == null) { mDotBackground = getDotBackground() background = mDotBackground } initDotParams(mDotSize) mTargetView.visibility = VISIBLE if (needAnim) { clearAnimation() startAnimation(animation) } else { alpha = 1F visibility = VISIBLE mIsShowing = true } mNeedReDraw = false } public fun hide() { hide(false) } public fun hide(needAnim: Boolean) { hide(needAnim, mFadeOut) } private fun hide(needAnim: Boolean, animation: Animation?) { if (!isShown) return if (needAnim) { clearAnimation() startAnimation(animation) } else { alpha = 0F visibility = GONE mIsShowing = false } } public fun toggle() { toggle(false) } public fun toggle(needAnim: Boolean) { toggle(needAnim, mFadeIn, mFadeOut) } private fun toggle(needAnim: Boolean, enterAnim: Animation?, exitAnim: Animation?) { if (isShown) { hide(needAnim && exitAnim != null, exitAnim) } else { show(needAnim && enterAnim != null, enterAnim) } } public fun setDotMatgin(left: Int, top: Int, right: Int, bottom: Int) { val absLeft = Math.abs(UIUtils.dip2Px(left)).toInt() val absTop = Math.abs(UIUtils.dip2Px(top)).toInt() val absRight = Math.abs(UIUtils.dip2Px(right)).toInt() val absBottom = Math.abs(UIUtils.dip2Px(bottom)).toInt() when (mDotGravity) { DotGravity.GRAVITY_TOP_LEFT -> applyDotMargin(absRight, absTop, 0, 0) DotGravity.GRAVITY_TOP_RIGHT -> applyDotMargin(0, absTop, absLeft, 0) DotGravity.GRAVITY_BOTTOM_LEFT -> applyDotMargin(absRight, 0, 0, absBottom) DotGravity.GRAVITY_BOTTOM_RIGHT -> applyDotMargin(0, 0, absLeft, absBottom) DotGravity.GRAVITY_LEFT_CENTER -> applyDotMargin(absRight, 0, 0, 0) DotGravity.GRAVITY_RIGHT_CENTER -> applyDotMargin(0, 0, absLeft, 0) else -> { } } } public fun getDotMargin(): Rect { val rect = Rect() rect.left = UIUtils.px2Dip(Math.abs(mMarginRect.left)).toInt() rect.top = UIUtils.px2Dip(Math.abs(mMarginRect.top)).toInt() rect.right = UIUtils.px2Dip(Math.abs(mMarginRect.right)).toInt() rect.bottom = UIUtils.px2Dip(Math.abs(mMarginRect.bottom)).toInt() KLog.d(TAG, "getDotMargin: \n" + rect.toString()) return rect } public fun setDotGravity(dotGravity: DotGravity) { this.mDotGravity = dotGravity } public fun getDotGravity(): DotGravity { return mDotGravity } public fun setMode(mode: Mode) { this.mode = mode } public fun getMode(): Mode { return mode } public fun setDotColor(dotColor: Int) { this.mDotColor = dotColor mNeedReDraw = true } public fun getDotColor(): Int { return mDotColor } public fun setDotSize(dotSize: Int) { this.mDotSize = dotSize mNeedReDraw = true } public fun getDotSize(): Int { return mDotSize } public fun setDotRadius(dotRadius: Int) { this.mDotRadius = dotRadius mNeedReDraw = true } public fun getDotRadius(): Int { return mDotRadius } public fun setDotText(dotText: String) { this.mDotText = dotText mNeedReDraw = true } public fun getDotText(): String { return mDotText } public fun setDotTextColor(dotTextColor: Int) { this.mDotTextColor = dotTextColor mNeedReDraw = true } public fun getDotTextColor(): Int { return mDotTextColor } public fun setDotTextSize(dotTextSize: Int) { this.mDotTextSize = dotTextSize mNeedReDraw = true } public fun getDotTextSize(): Int { return mDotTextSize } /** * 更新dot和容器的大小 * <p/> * 原理如下: * 当dot在左边,那么源控件就是相对于dot的右边,因此想移动dot一般而言都是设置dotMarginRight,然而容器container已经限制死了大小 * 因此需要将container进行扩展,使用padding,同时clipToPadding设置为false,使dot可以正常显示。而dot因为其gravity,因此只需要marginLeft为负值即可 */ private fun applyDotMargin(left: Int, top: Int, right: Int, bottom: Int) { mMarginRect.left = -left mMarginRect.top = -top mMarginRect.right = -right mMarginRect.bottom = -bottom mContainer.setPadding(left, top, right, bottom) KLog.d(TAG, "applyDotMargin:\n" + mMarginRect.toString()) } public fun getTargetView(): View { return mTargetView } public fun setTargetView(targetView: View) { this.mTargetView = targetView } private fun initDotParams(mDotSize: Int) { val dotWeightWidth = UIUtils.dip2Px(mDotSize).toInt() val dotParams = FrameLayout.LayoutParams(dotWeightWidth, dotWeightWidth) when (mDotGravity) { DotGravity.GRAVITY_TOP_LEFT -> dotParams.gravity = Gravity.TOP and Gravity.START DotGravity.GRAVITY_TOP_RIGHT -> dotParams.gravity = Gravity.TOP and Gravity.END DotGravity.GRAVITY_BOTTOM_LEFT -> dotParams.gravity = Gravity.BOTTOM and Gravity.START DotGravity.GRAVITY_BOTTOM_RIGHT -> dotParams.gravity = Gravity.BOTTOM and Gravity.END DotGravity.GRAVITY_CENTER -> dotParams.gravity = Gravity.CENTER DotGravity.GRAVITY_CENTER_VERTICAL -> dotParams.gravity = Gravity.CENTER_VERTICAL DotGravity.GRAVITY_CENTER_HORIZONTAL -> dotParams.gravity = Gravity.CENTER_HORIZONTAL DotGravity.GRAVITY_LEFT_CENTER -> dotParams.gravity = Gravity.CENTER_VERTICAL and Gravity.START DotGravity.GRAVITY_RIGHT_CENTER -> dotParams.gravity = Gravity.CENTER_VERTICAL and Gravity.END } dotParams.setMargins(mMarginRect.left, mMarginRect.top, mMarginRect.right, mMarginRect.bottom) this.layoutParams = dotParams } private fun getDotBackground(): ShapeDrawable { val drawable: ShapeDrawable when (mode) { Mode.ROUND_RECT -> { val radius = UIUtils.dip2Px(mDotRadius) val outerRect = floatArrayOf( radius, radius, radius, radius, radius, radius, radius, radius) val rrs = RoundRectShape(outerRect, null, null) drawable = InnerShapeDrawableWithText(rrs, mDotText) drawable.paint.color = mDotColor } Mode.CIRCLE -> { val os = OvalShape() drawable = InnerShapeDrawableWithText(os, mDotText) drawable.paint.color = mDotColor } } return drawable } inner class InnerShapeDrawableWithText(s: Shape?) : ShapeDrawable(s) { private lateinit var text: String private var textPaint = Paint(Paint.ANTI_ALIAS_FLAG) constructor(s: Shape?, text: String) : this(s) { this.text = text } init { textPaint.color = mDotColor if (mDotTextSize != 0) { textPaint.textSize = mDotTextSize.toFloat() } } override fun onDraw(shape: Shape?, canvas: Canvas, paint: Paint?) { super.onDraw(shape, canvas, paint) if (!TextUtils.isEmpty(text)) { val rect = bounds if (mDotTextSize == 0) { mDotTextSize = (rect.width() * 0.5).toInt() textPaint.textSize = mDotTextSize.toFloat() } //保证文字居中 val fontMetrics = textPaint.fontMetricsInt val baseLine = rect.top + (rect.bottom - rect.top + fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top textPaint.textAlign = Paint.Align.CENTER canvas.drawText(text, rect.centerX().toFloat(), baseLine.toFloat(), textPaint) } } } private var mAnimListener = object : Animation.AnimationListener { override fun onAnimationRepeat(p0: Animation?) { } override fun onAnimationEnd(p0: Animation?) { mIsShowing = !mIsShowing visibility = if (mIsShowing) { VISIBLE } else { GONE } } override fun onAnimationStart(p0: Animation?) { } } }
apache-2.0
a2c200b3a9de3fb2ee0b2978e4eee62e
29.814118
127
0.626193
4.472336
false
false
false
false
GunoH/intellij-community
xml/xml-psi-impl/src/com/intellij/documentation/mdn/MdnDocumentedSymbol.kt
2
1420
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.documentation.mdn import com.intellij.webSymbols.WebSymbol import com.intellij.webSymbols.documentation.WebSymbolDocumentation abstract class MdnDocumentedSymbol : WebSymbol { private val mdnDoc by lazy(LazyThreadSafetyMode.NONE) { getMdnDocumentation() } protected abstract fun getMdnDocumentation(): MdnSymbolDocumentation? override val deprecated: Boolean get() = mdnDoc?.isDeprecated ?: false override val experimental: Boolean get() = mdnDoc?.isExperimental ?: false override val description: String? get() = mdnDoc?.description override val docUrl: String? get() = mdnDoc?.url override val descriptionSections: Map<String, String> get() = mdnDoc?.sections ?: emptyMap() override val documentation: WebSymbolDocumentation? get() = this.mdnDoc?.let { mdnDoc -> val documentation = super.documentation return documentation?.with( deprecated = false, // already contained in MDN documentation sections experimental = false, // already contained in MDN documentation sections footnote = mdnDoc.footnote ?.let { it + (documentation.footnote?.let { prev -> "<br>$prev" } ?: "") } ?: documentation.footnote, ) } ?: super.documentation }
apache-2.0
4c28c871fb6fa88ce42141ef0e319d7b
32.809524
120
0.702817
5.035461
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/migLayout/MigLayoutRow.kt
1
24300
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.layout.migLayout import com.intellij.icons.AllIcons import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.OnePixelDivider import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.ui.panel.ComponentPanelBuilder import com.intellij.openapi.util.NlsContexts import com.intellij.ui.HideableTitledSeparator import com.intellij.ui.SeparatorComponent import com.intellij.ui.TitledSeparator import com.intellij.ui.UIBundle import com.intellij.ui.components.DialogPanel import com.intellij.ui.components.JBRadioButton import com.intellij.ui.components.Label import com.intellij.ui.layout.* import com.intellij.util.SmartList import net.miginfocom.layout.* import org.jetbrains.annotations.Nls import javax.swing.* import javax.swing.border.LineBorder import javax.swing.text.JTextComponent import kotlin.math.max import kotlin.reflect.KMutableProperty0 internal class MigLayoutRow(private val parent: MigLayoutRow?, override val builder: MigLayoutBuilder, val labeled: Boolean = false, val noGrid: Boolean = false, private val indent: Int /* level number (nested rows) */, private val incrementsIndent: Boolean = parent != null) : Row() { companion object { private const val COMPONENT_ENABLED_STATE_KEY = "MigLayoutRow.enabled" private const val COMPONENT_VISIBLE_STATE_KEY = "MigLayoutRow.visible" // as static method to ensure that members of current row are not used private fun createCommentRow(parent: MigLayoutRow, component: JComponent, indent: Int, isParentRowLabeled: Boolean, forComponent: Boolean, columnIndex: Int, anchorComponent: JComponent? = null) { val cc = CC() val commentRow = parent.createChildRow() commentRow.isComment = true commentRow.addComponent(component, cc) if (forComponent) { cc.horizontal.gapBefore = BoundSize.NULL_SIZE cc.skip = columnIndex } else if (isParentRowLabeled) { cc.horizontal.gapBefore = BoundSize.NULL_SIZE cc.skip() } else if (anchorComponent == null || anchorComponent is JToggleButton) { cc.horizontal.gapBefore = gapToBoundSize(indent + parent.spacing.indentLevel, true) } else { cc.horizontal.gapBefore = gapToBoundSize(indent, true) } } // as static method to ensure that members of current row are not used private fun configureSeparatorRow(row: MigLayoutRow, @NlsContexts.Separator title: String?) { val separatorComponent = if (title == null) SeparatorComponent(0, OnePixelDivider.BACKGROUND, null) else TitledSeparator(title) row.addTitleComponent(separatorComponent, isEmpty = title == null) } } val components: MutableList<JComponent> = SmartList() var rightIndex = Int.MAX_VALUE private var lastComponentConstraintsWithSplit: CC? = null private var columnIndex = -1 internal var subRows: MutableList<MigLayoutRow>? = null private set var gapAfter: String? = null set(value) { field = value rowConstraints?.gapAfter = if (value == null) null else ConstraintParser.parseBoundSize(value, true, false) } var rowConstraints: DimConstraint? = null private var componentIndexWhenCellModeWasEnabled = -1 private val spacing: SpacingConfiguration get() = builder.spacing private var isTrailingSeparator = false private var isComment = false override fun withButtonGroup(title: String?, buttonGroup: ButtonGroup, body: () -> Unit) { if (title != null) { label(title) gapAfter = "${spacing.radioGroupTitleVerticalGap}px!" } builder.withButtonGroup(buttonGroup, body) } override fun checkBoxGroup(title: String?, body: () -> Unit) { if (title != null) { label(title) gapAfter = "${spacing.radioGroupTitleVerticalGap}px!" } body() } override var enabled = true set(value) { if (field == value) { return } field = value for (c in components) { if (!value) { if (!c.isEnabled) { // current state of component differs from current row state - preserve current state to apply it when row state will be changed c.putClientProperty(COMPONENT_ENABLED_STATE_KEY, false) } } else { if (c.getClientProperty(COMPONENT_ENABLED_STATE_KEY) == false) { // remove because for active row component state can be changed and we don't want to add listener to update value accordingly c.putClientProperty(COMPONENT_ENABLED_STATE_KEY, null) // do not set to true, preserve old component state continue } } c.isEnabled = value } } override var visible = true set(value) { if (field == value) { return } field = value for ((index, c) in components.withIndex()) { builder.componentConstraints[c]?.hideMode = if (index == components.size - 1 && value) 2 else 3 if (!value) { c.putClientProperty(COMPONENT_VISIBLE_STATE_KEY, if (c.isVisible) null else false) } else { if (c.getClientProperty(COMPONENT_VISIBLE_STATE_KEY) == false) { c.putClientProperty(COMPONENT_VISIBLE_STATE_KEY, null) continue } } c.isVisible = value } } override var subRowsEnabled = true set(value) { if (field == value) { return } field = value subRows?.forEach { it.enabled = value it.subRowsEnabled = value } components.firstOrNull()?.parent?.repaint() // Repaint all dependent components in sync } override var subRowsVisible = true set(value) { if (field == value) { return } field = value subRows?.forEach { it.visible = value it.subRowsVisible = value if (it != subRows!!.last()) { it.gapAfter = if (value) null else "0px!" } } } override var subRowIndent: Int = -1 internal val isLabeledIncludingSubRows: Boolean get() = labeled || (subRows?.any { it.isLabeledIncludingSubRows } ?: false) internal val columnIndexIncludingSubRows: Int get() = max(columnIndex, subRows?.asSequence()?.map { it.columnIndexIncludingSubRows }?.maxOrNull() ?: -1) override fun createChildRow(label: JLabel?, isSeparated: Boolean, noGrid: Boolean, title: String?): MigLayoutRow { return createChildRow(indent, label, isSeparated, noGrid, title) } private fun createChildRow(indent: Int, label: JLabel? = null, isSeparated: Boolean = false, noGrid: Boolean = false, @NlsContexts.Separator title: String? = null, incrementsIndent: Boolean = true): MigLayoutRow { val subRows = getOrCreateSubRowsList() val newIndent = if (!this.incrementsIndent) indent else indent + spacing.indentLevel val row = MigLayoutRow(this, builder, labeled = label != null, noGrid = noGrid, indent = if (subRowIndent >= 0) subRowIndent * spacing.indentLevel else newIndent, incrementsIndent = incrementsIndent) if (isSeparated) { val separatorRow = MigLayoutRow(this, builder, indent = newIndent, noGrid = true) configureSeparatorRow(separatorRow, title) separatorRow.enabled = subRowsEnabled separatorRow.subRowsEnabled = subRowsEnabled separatorRow.visible = subRowsVisible separatorRow.subRowsVisible = subRowsVisible row.getOrCreateSubRowsList().add(separatorRow) } var insertIndex = subRows.size if (insertIndex > 0 && subRows[insertIndex-1].isTrailingSeparator) { insertIndex-- } if (insertIndex > 0 && subRows[insertIndex-1].isComment) { insertIndex-- } subRows.add(insertIndex, row) row.enabled = subRowsEnabled row.subRowsEnabled = subRowsEnabled row.visible = subRowsVisible row.subRowsVisible = subRowsVisible if (label != null) { row.addComponent(label) } return row } private fun <T : JComponent> addTitleComponent(titleComponent: T, isEmpty: Boolean) { val cc = CC() if (isEmpty) { cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap * 2, false) isTrailingSeparator = true } else { // TitledSeparator doesn't grow by default opposite to SeparatorComponent cc.growX() } addComponent(titleComponent, cc) } override fun titledRow(@NlsContexts.Separator title: String, init: Row.() -> Unit): Row { return createBlockRow(title, true, init) } override fun blockRow(init: Row.() -> Unit): Row { return createBlockRow(null, false, init) } private fun createBlockRow(@NlsContexts.Separator title: String?, isSeparated: Boolean, init: Row.() -> Unit): Row { val parentRow = createChildRow(indent = indent, title = title, isSeparated = isSeparated, incrementsIndent = isSeparated) parentRow.init() val result = parentRow.createChildRow() result.placeholder() result.largeGapAfter() return result } override fun hideableRow(title: String, incrementsIndent: Boolean, init: Row.() -> Unit): Row { val titledSeparator = HideableTitledSeparator(title) val separatorRow = createChildRow() separatorRow.addTitleComponent(titledSeparator, isEmpty = false) builder.hideableRowNestingLevel++ try { val panelRow = createChildRow(indent, incrementsIndent = incrementsIndent) panelRow.init() titledSeparator.row = panelRow titledSeparator.collapse() return panelRow } finally { builder.hideableRowNestingLevel-- } } override fun nestedPanel(title: String?, init: LayoutBuilder.() -> Unit): CellBuilder<DialogPanel> { val nestedBuilder = createLayoutBuilder() nestedBuilder.init() val panel = DialogPanel(title, layout = null) nestedBuilder.builder.build(panel, arrayOf()) builder.validateCallbacks.addAll(nestedBuilder.builder.validateCallbacks) builder.componentValidateCallbacks.putAll(nestedBuilder.builder.componentValidateCallbacks) mergeCallbacks(builder.customValidationRequestors, nestedBuilder.builder.customValidationRequestors) mergeCallbacks(builder.applyCallbacks, nestedBuilder.builder.applyCallbacks) mergeCallbacks(builder.resetCallbacks, nestedBuilder.builder.resetCallbacks) mergeCallbacks(builder.isModifiedCallbacks, nestedBuilder.builder.isModifiedCallbacks) lateinit var panelBuilder: CellBuilder<DialogPanel> row { panelBuilder = panel(CCFlags.growX) } return panelBuilder } private fun <K, V> mergeCallbacks(map: MutableMap<K, MutableList<V>>, nestedMap: Map<K, List<V>>) { for ((requestor, callbacks) in nestedMap) { map.getOrPut(requestor) { mutableListOf() }.addAll(callbacks) } } private fun getOrCreateSubRowsList(): MutableList<MigLayoutRow> { var subRows = subRows if (subRows == null) { // subRows in most cases > 1 subRows = ArrayList() this.subRows = subRows } return subRows } // cell mode not tested with "gear" button, wait first user request override fun setCellMode(value: Boolean, isVerticalFlow: Boolean, fullWidth: Boolean) { if (value) { assert(componentIndexWhenCellModeWasEnabled == -1) componentIndexWhenCellModeWasEnabled = components.size } else { val firstComponentIndex = componentIndexWhenCellModeWasEnabled componentIndexWhenCellModeWasEnabled = -1 val componentCount = components.size - firstComponentIndex if (componentCount == 0) return val component = components.get(firstComponentIndex) val cc = component.constraints // do not add split if cell empty or contains the only component if (componentCount > 1) { cc.split(componentCount) } if (fullWidth) { cc.spanX(LayoutUtil.INF) } if (isVerticalFlow) { cc.flowY() // because when vertical buttons placed near scroll pane, it wil be centered by baseline (and baseline not applicable for grow elements, so, will be centered) cc.alignY("top") } } } override fun <T : JComponent> component(component: T): CellBuilder<T> { addComponent(component) return CellBuilderImpl(builder, this, component) } override fun <T : JComponent> component(component: T, viewComponent: JComponent): CellBuilder<T> { addComponent(viewComponent) return CellBuilderImpl(builder, this, component, viewComponent) } internal fun addComponent(component: JComponent, cc: CC = CC()) { components.add(component) builder.componentConstraints.put(component, cc) if (!visible) { component.isVisible = false } if (!enabled) { component.isEnabled = false } if (!shareCellWithPreviousComponentIfNeeded(component, cc)) { // increase column index if cell mode not enabled or it is a first component of cell if (componentIndexWhenCellModeWasEnabled == -1 || componentIndexWhenCellModeWasEnabled == (components.size - 1)) { columnIndex++ } } if (labeled && components.size == 2 && component.border is LineBorder) { builder.componentConstraints.get(components.first())?.vertical?.gapBefore = builder.defaultComponentConstraintCreator.vertical1pxGap } if (component is JRadioButton) { builder.topButtonGroup?.add(component) } builder.defaultComponentConstraintCreator.addGrowIfNeeded(cc, component, spacing) if (!noGrid && indent > 0 && components.size == 1) { cc.horizontal.gapBefore = gapToBoundSize(indent, true) } if (builder.hideableRowNestingLevel > 0) { cc.hideMode = 3 } // if this row is not labeled and: // a. previous row is labeled and first component is a "Remember" checkbox, skip one column (since this row doesn't have a label) // b. some previous row is labeled and first component is a checkbox, span (since this checkbox should span across label and content cells) if (!labeled && components.size == 1 && component is JCheckBox) { val siblings = parent!!.subRows if (siblings != null && siblings.size > 1) { if (siblings.get(siblings.size - 2).labeled && component.text == UIBundle.message("auth.remember.cb")) { cc.skip(1) cc.horizontal.gapBefore = BoundSize.NULL_SIZE } else if (siblings.any { it.labeled }) { cc.spanX(2) } } } // MigLayout doesn't check baseline if component has grow if (labeled && component is JScrollPane && component.viewport.view is JTextArea) { val labelCC = components.get(0).constraints labelCC.alignY("top") val labelTop = component.border?.getBorderInsets(component)?.top ?: 0 if (labelTop != 0) { labelCC.vertical.gapBefore = gapToBoundSize(labelTop, false) } } } private val JComponent.constraints: CC get() = builder.componentConstraints.getOrPut(this) { CC() } fun addCommentRow(@Nls comment: String, maxLineLength: Int, forComponent: Boolean) { addCommentRow(comment, maxLineLength, forComponent, null) } // not using @JvmOverloads to maintain binary compatibility fun addCommentRow(@Nls comment: String, maxLineLength: Int, forComponent: Boolean, anchorComponent: JComponent?) { val commentComponent = ComponentPanelBuilder.createCommentComponent(comment, true, maxLineLength, true) addCommentRow(commentComponent, forComponent, anchorComponent) } // not using @JvmOverloads to maintain binary compatibility fun addCommentRow(component: JComponent, forComponent: Boolean) { addCommentRow(component, forComponent, null) } fun addCommentRow(component: JComponent, forComponent: Boolean, anchorComponent: JComponent?) { gapAfter = "${spacing.commentVerticalTopGap}px!" val isParentRowLabeled = labeled createCommentRow(this, component, indent, isParentRowLabeled, forComponent, columnIndex, anchorComponent) } private fun shareCellWithPreviousComponentIfNeeded(component: JComponent, componentCC: CC): Boolean { if (components.size > 1 && component is JLabel && component.icon === AllIcons.General.GearPlain) { componentCC.horizontal.gapBefore = builder.defaultComponentConstraintCreator.horizontalUnitSizeGap if (lastComponentConstraintsWithSplit == null) { val prevComponent = components.get(components.size - 2) val prevCC = prevComponent.constraints prevCC.split++ lastComponentConstraintsWithSplit = prevCC } else { lastComponentConstraintsWithSplit!!.split++ } return true } else { lastComponentConstraintsWithSplit = null return false } } override fun alignRight() { if (rightIndex != Int.MAX_VALUE) { throw IllegalStateException("right allowed only once") } rightIndex = components.size } override fun largeGapAfter() { gapAfter = "${spacing.largeVerticalGap}px!" } override fun createRow(label: String?): Row { return createChildRow(label = label?.let { Label(it) }) } override fun createNoteOrCommentRow(component: JComponent): Row { val cc = CC() cc.vertical.gapBefore = gapToBoundSize(if (subRows == null) spacing.verticalGap else spacing.largeVerticalGap, false) cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap, false) val row = createChildRow(label = null, noGrid = true) row.addComponent(component, cc) return row } override fun radioButton(text: String, comment: String?): CellBuilder<JBRadioButton> { val result = super.radioButton(text, comment) attachSubRowsEnabled(result.component) return result } override fun radioButton(text: String, prop: KMutableProperty0<Boolean>, comment: String?): CellBuilder<JBRadioButton> { return super.radioButton(text, prop, comment).also { attachSubRowsEnabled(it.component) } } override fun onGlobalApply(callback: () -> Unit): Row { builder.applyCallbacks.getOrPut(null, { SmartList() }).add(callback) return this } override fun onGlobalReset(callback: () -> Unit): Row { builder.resetCallbacks.getOrPut(null, { SmartList() }).add(callback) return this } override fun onGlobalIsModified(callback: () -> Boolean): Row { builder.isModifiedCallbacks.getOrPut(null, { SmartList() }).add(callback) return this } private val labeledComponents = listOf(JTextComponent::class, JComboBox::class, JSpinner::class, JSlider::class) /** * Assigns next to label REASONABLE component with the label */ override fun row(label: JLabel?, separated: Boolean, init: Row.() -> Unit): Row { val result = super.row(label, separated, init) if (label != null && result is MigLayoutRow && result.components.size > 1) { val component = result.components[1] if (labeledComponents.any { clazz -> clazz.isInstance(component) }) { label.labelFor = component } } return result } } private class CellBuilderImpl<T : JComponent>( private val builder: MigLayoutBuilder, private val row: MigLayoutRow, override val component: T, private val viewComponent: JComponent = component ) : CellBuilder<T>, CheckboxCellBuilder, ScrollPaneCellBuilder { private var applyIfEnabled = false private var property: GraphProperty<*>? = null override fun withGraphProperty(property: GraphProperty<*>): CellBuilder<T> { this.property = property return this } override fun comment(text: String, maxLineLength: Int, forComponent: Boolean): CellBuilder<T> { row.addCommentRow(text, maxLineLength, forComponent, viewComponent) return this } override fun commentComponent(component: JComponent, forComponent: Boolean): CellBuilder<T> { row.addCommentRow(component, forComponent, viewComponent) return this } override fun focused(): CellBuilder<T> { builder.preferredFocusedComponent = viewComponent return this } override fun withValidationOnApply(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T> { builder.validateCallbacks.add { callback(ValidationInfoBuilder(component.origin), component) } return this } override fun withValidationOnInput(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T> { builder.componentValidateCallbacks[component.origin] = { callback(ValidationInfoBuilder(component.origin), component) } property?.let { builder.customValidationRequestors.getOrPut(component.origin, { SmartList() }).add(it::afterPropagation) } return this } override fun onApply(callback: () -> Unit): CellBuilder<T> { builder.applyCallbacks.getOrPut(component, { SmartList() }).add(callback) return this } override fun onReset(callback: () -> Unit): CellBuilder<T> { builder.resetCallbacks.getOrPut(component, { SmartList() }).add(callback) return this } override fun onIsModified(callback: () -> Boolean): CellBuilder<T> { builder.isModifiedCallbacks.getOrPut(component, { SmartList() }).add(callback) return this } override fun enabled(isEnabled: Boolean) { viewComponent.isEnabled = isEnabled } override fun enableIf(predicate: ComponentPredicate): CellBuilder<T> { viewComponent.isEnabled = predicate() predicate.addListener { viewComponent.isEnabled = it } return this } override fun visible(isVisible: Boolean) { viewComponent.isVisible = isVisible } override fun visibleIf(predicate: ComponentPredicate): CellBuilder<T> { viewComponent.isVisible = predicate() predicate.addListener { viewComponent.isVisible = it } return this } override fun applyIfEnabled(): CellBuilder<T> { applyIfEnabled = true return this } override fun shouldSaveOnApply(): Boolean { return !(applyIfEnabled && !viewComponent.isEnabled) } override fun actsAsLabel() { builder.updateComponentConstraints(viewComponent) { spanX = 1 } } override fun noGrowY() { builder.updateComponentConstraints(viewComponent) { growY(0.0f) pushY(0.0f) } } override fun sizeGroup(name: String): CellBuilderImpl<T> { builder.updateComponentConstraints(viewComponent) { sizeGroup(name) } return this } override fun growPolicy(growPolicy: GrowPolicy): CellBuilder<T> { builder.updateComponentConstraints(viewComponent) { builder.defaultComponentConstraintCreator.applyGrowPolicy(this, growPolicy) } return this } override fun constraints(vararg constraints: CCFlags): CellBuilder<T> { builder.updateComponentConstraints(viewComponent) { overrideFlags(this, constraints) } return this } override fun withLargeLeftGap(): CellBuilder<T> { builder.updateComponentConstraints(viewComponent) { horizontal.gapBefore = gapToBoundSize(builder.spacing.largeHorizontalGap, true) } return this } override fun withLeftGap(): CellBuilder<T> { builder.updateComponentConstraints(viewComponent) { horizontal.gapBefore = gapToBoundSize(builder.spacing.horizontalGap, true) } return this } override fun withLeftGap(gapLeft: Int): CellBuilder<T> { builder.updateComponentConstraints(viewComponent) { horizontal.gapBefore = gapToBoundSize(gapLeft, true) } return this } } private val JComponent.origin: JComponent get() { return when (this) { is TextFieldWithBrowseButton -> textField else -> this } }
apache-2.0
eee9b23e713e8b5698ac309d1a84f802
33.616809
166
0.683745
4.795737
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/LambdaCallsBehaviour.kt
5
2135
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.slicer import com.intellij.slicer.SliceUsage import com.intellij.util.Processor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.psi.KtElement data class LambdaCallsBehaviour(private val sliceProducer: SliceProducer) : KotlinSliceAnalysisMode.Behaviour { override fun processUsages( element: KtElement, parent: KotlinSliceUsage, uniqueProcessor: Processor<in SliceUsage> ) { val processor = object : Processor<SliceUsage> { override fun process(sliceUsage: SliceUsage): Boolean { if (sliceUsage is KotlinSliceUsage && sliceUsage.mode.currentBehaviour === this@LambdaCallsBehaviour) { val sliceElement = sliceUsage.element ?: return true val resolvedCall = (sliceElement as? KtElement)?.resolveToCall() if (resolvedCall != null && resolvedCall.resultingDescriptor.isImplicitInvokeFunction()) { val originalMode = sliceUsage.mode.dropBehaviour() val newSliceUsage = KotlinSliceUsage(resolvedCall.call.callElement, parent, originalMode, true) return sliceProducer.produceAndProcess(newSliceUsage, originalMode, parent, uniqueProcessor) } } return uniqueProcessor.process(sliceUsage) } } OutflowSlicer(element, processor, parent).processChildren(parent.forcedExpressionMode) } override val slicePresentationPrefix: String get() = KotlinBundle.message("slicer.text.tracking.lambda.calls") override val testPresentationPrefix: String get() = buildString { append("[LAMBDA CALLS") sliceProducer.testPresentation?.let { append(" ") append(it) } append("] ") } }
apache-2.0
c63e3d175d5b1c6e9f42a36bbdf1b6f8
45.413043
158
0.660422
5.391414
false
false
false
false
GunoH/intellij-community
platform/built-in-server/src/org/jetbrains/io/fastCgi/FastCgiService.kt
7
6986
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.io.fastCgi import com.intellij.concurrency.ConcurrentCollectionFactory import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.util.Consumer import com.intellij.util.io.addChannelListener import com.intellij.util.io.handler import io.netty.bootstrap.Bootstrap import io.netty.buffer.ByteBuf import io.netty.buffer.Unpooled import io.netty.channel.Channel import io.netty.handler.codec.http.* import org.jetbrains.builtInWebServer.PathInfo import org.jetbrains.builtInWebServer.SingleConnectionNetService import org.jetbrains.builtInWebServer.liveReload.WebServerPageConnectionService import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.errorIfNotMessage import org.jetbrains.io.* import java.util.concurrent.atomic.AtomicInteger internal val LOG = logger<FastCgiService>() // todo send FCGI_ABORT_REQUEST if client channel disconnected abstract class FastCgiService(project: Project) : SingleConnectionNetService(project) { private val requestIdCounter = AtomicInteger() private val requests = ConcurrentCollectionFactory.createConcurrentIntObjectMap<ClientInfo>() override fun configureBootstrap(bootstrap: Bootstrap, errorOutputConsumer: Consumer<String>) { bootstrap.handler { it.pipeline().addLast("fastCgiDecoder", FastCgiDecoder(errorOutputConsumer, this@FastCgiService)) it.pipeline().addLast("exceptionHandler", ChannelExceptionHandler.getInstance()) } } override fun addCloseListener(it: Channel) { super.addCloseListener(it) it.closeFuture().addChannelListener { requestIdCounter.set(0) if (!requests.isEmpty) { val waitingClients = requests.elements().toList() requests.clear() for (client in waitingClients) { sendBadGateway(client.channel, client.extraHeaders) } } } } fun send(fastCgiRequest: FastCgiRequest, content: ByteBuf) { val notEmptyContent: ByteBuf? if (content.isReadable) { content.retain() notEmptyContent = content notEmptyContent.touch() } else { notEmptyContent = null } try { val promise: Promise<*> val handler = processHandler.resultIfFullFilled if (handler == null) { promise = processHandler.get() } else { val channel = processChannel.get() if (channel == null || !channel.isOpen) { // channel disconnected for some reason promise = connectAgain() } else { fastCgiRequest.writeToServerChannel(notEmptyContent, channel) return } } promise .onSuccess { fastCgiRequest.writeToServerChannel(notEmptyContent, processChannel.get()!!) } .onError { LOG.errorIfNotMessage(it) handleError(fastCgiRequest, notEmptyContent) } } catch (e: Throwable) { LOG.error(e) handleError(fastCgiRequest, notEmptyContent) } } private fun handleError(fastCgiRequest: FastCgiRequest, content: ByteBuf?) { try { if (content != null && content.refCnt() != 0) { content.release() } } finally { requests.remove(fastCgiRequest.requestId)?.let { sendBadGateway(it.channel, it.extraHeaders) } } } fun allocateRequestId(channel: Channel, pathInfo: PathInfo, request: FullHttpRequest, extraHeaders: HttpHeaders): Int { var requestId = requestIdCounter.getAndIncrement() if (requestId >= java.lang.Short.MAX_VALUE) { requestIdCounter.set(0) requestId = requestIdCounter.getAndDecrement() } requests.put(requestId, ClientInfo(channel, pathInfo, request, extraHeaders)) return requestId } fun responseReceived(id: Int, buffer: ByteBuf?) { val client = requests.remove(id) if (client == null || !client.channel.isActive) { buffer?.release() return } val channel = client.channel if (buffer == null) { HttpResponseStatus.BAD_GATEWAY.send(channel) return } val extraSuffix = WebServerPageConnectionService.instance.fileRequested(client.request, false, client.pathInfo::getOrResolveVirtualFile) val bufferWithExtraSuffix = if (extraSuffix == null) buffer else { Unpooled.wrappedBuffer(buffer, Unpooled.copiedBuffer(extraSuffix, Charsets.UTF_8)) } val httpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, bufferWithExtraSuffix) try { parseHeaders(httpResponse, bufferWithExtraSuffix) httpResponse.addServer() if (!HttpUtil.isContentLengthSet(httpResponse)) { HttpUtil.setContentLength(httpResponse, bufferWithExtraSuffix.readableBytes().toLong()) } httpResponse.headers().add(client.extraHeaders) } catch (e: Throwable) { bufferWithExtraSuffix.release() try { LOG.error(e) } finally { HttpResponseStatus.INTERNAL_SERVER_ERROR.send(channel) } return } channel.writeAndFlush(httpResponse) } } private fun sendBadGateway(channel: Channel, extraHeaders: HttpHeaders) { try { if (channel.isActive) { HttpResponseStatus.BAD_GATEWAY.send(channel, extraHeaders = extraHeaders) } } catch (e: Throwable) { NettyUtil.log(e, LOG) } } private fun parseHeaders(response: HttpResponse, buffer: ByteBuf) { val builder = StringBuilder() while (buffer.isReadable) { builder.setLength(0) var key: String? = null var valueExpected = true while (true) { val b = buffer.readByte().toInt() if (b < 0 || b.toChar() == '\n') { break } if (b.toChar() != '\r') { if (valueExpected && b.toChar() == ':') { valueExpected = false key = builder.toString() builder.setLength(0) MessageDecoder.skipWhitespace(buffer) } else { builder.append(b.toChar()) } } } if (builder.isEmpty()) { // end of headers return } // skip standard headers if (key.isNullOrEmpty() || key.startsWith("http", ignoreCase = true) || key.startsWith("X-Accel-", ignoreCase = true)) { continue } val value = builder.toString() if (key.equals("status", ignoreCase = true)) { val index = value.indexOf(' ') if (index == -1) { LOG.warn("Cannot parse status: $value") response.status = HttpResponseStatus.OK } else { response.status = HttpResponseStatus.valueOf(Integer.parseInt(value.substring(0, index))) } } else if (!(key.startsWith("http") || key.startsWith("HTTP"))) { response.headers().add(key, value) } } } private class ClientInfo(val channel: Channel, val pathInfo: PathInfo, var request: FullHttpRequest, val extraHeaders: HttpHeaders)
apache-2.0
7a15374677c886dbadd7afc012d9cc32
30.191964
140
0.675064
4.521683
false
false
false
false
Fotoapparat/Fotoapparat
fotoapparat/src/main/java/io/fotoapparat/selector/PreviewFpsRangeSelectors.kt
1
2491
package io.fotoapparat.selector import io.fotoapparat.parameter.FpsRange import io.fotoapparat.util.CompareFpsRangeByBounds typealias FpsRangeSelector = Iterable<FpsRange>.() -> FpsRange? /** * @param fps The specified FPS * @return Selector function which selects FPS range that contains the specified FPS. * Prefers fixed rates over non fixed ones. */ fun containsFps(fps: Float): FpsRangeSelector = firstAvailable( exactFixedFps(fps), filtered( selector = highestNonFixedFps(), predicate = { range -> fps.toFpsIntRepresentation() in range } ) ) /** * @param fps The specified FPS * @return Selector function which selects FPS range that contains only the specified FPS. */ fun exactFixedFps(fps: Float): FpsRangeSelector = filtered( selector = highestFixedFps(), predicate = { it.min == fps.toFpsIntRepresentation() } ) /** * @return Selector function which selects FPS range with max FPS. * Prefers non fixed rates over fixed ones. */ fun highestFps(): FpsRangeSelector = firstAvailable( highestNonFixedFps(), highestFixedFps() ) /** * @return Selector function which selects FPS range with max FPS and non fixed rate. */ fun highestNonFixedFps(): FpsRangeSelector = filtered( selector = highestRangeFps(), predicate = { !it.isFixed } ) /** * @return Selector function which selects FPS range with max FPS and fixed rate. */ fun highestFixedFps(): FpsRangeSelector = filtered( selector = highestRangeFps(), predicate = { it.isFixed } ) /** * @return Selector function which selects FPS range with min FPS. * Prefers non fixed rates over fixed ones. */ fun lowestFps(): FpsRangeSelector = firstAvailable( lowestNonFixedFps(), lowestFixedFps() ) /** * @return Selector function which selects FPS range with min FPS and non fixed rate. */ fun lowestNonFixedFps(): FpsRangeSelector = filtered( selector = lowestRangeFps(), predicate = { !it.isFixed } ) /** * @return Selector function which selects FPS range with min FPS and fixed rate. */ fun lowestFixedFps(): FpsRangeSelector = filtered( selector = lowestRangeFps(), predicate = { it.isFixed } ) private fun highestRangeFps(): FpsRangeSelector = { maxWith(CompareFpsRangeByBounds) } private fun lowestRangeFps(): FpsRangeSelector = { minWith(CompareFpsRangeByBounds) } private fun Float.toFpsIntRepresentation() = (this * 1000).toInt()
apache-2.0
f77d781019dd5e0523af3a50e6d600de
28.666667
90
0.70012
4.595941
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinParameterInfo.kt
2
13170
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature import com.intellij.psi.PsiReference import com.intellij.refactoring.changeSignature.ParameterInfo import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.core.copied import org.jetbrains.kotlin.idea.core.setDefaultValue import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.util.isPrimaryConstructorOfDataClass import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.addRemoveModifier.setModifierList import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.descriptorUtil.isAnnotationConstructor import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.AbstractTypeChecker import org.jetbrains.kotlin.types.AbstractTypeCheckerContext import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.checker.ClassicTypeCheckerContext import org.jetbrains.kotlin.types.isError class KotlinParameterInfo( val callableDescriptor: CallableDescriptor, val originalIndex: Int = -1, private var name: String, val originalTypeInfo: KotlinTypeInfo = KotlinTypeInfo(false), var defaultValueForCall: KtExpression? = null, var defaultValueAsDefaultParameter: Boolean = false, var valOrVar: KotlinValVar = defaultValOrVar(callableDescriptor), val modifierList: KtModifierList? = null, ) : ParameterInfo { private var _defaultValueForParameter: KtExpression? = null fun setDefaultValueForParameter(expression: KtExpression?) { _defaultValueForParameter = expression } val defaultValue: KtExpression? get() = defaultValueForCall?.takeIf { defaultValueAsDefaultParameter } ?: _defaultValueForParameter var currentTypeInfo: KotlinTypeInfo = originalTypeInfo val defaultValueParameterReferences: Map<PsiReference, DeclarationDescriptor> by lazy { collectDefaultValueParameterReferences(defaultValueForCall) } private fun collectDefaultValueParameterReferences(defaultValueForCall: KtExpression?): Map<PsiReference, DeclarationDescriptor> { val file = defaultValueForCall?.containingFile as? KtFile ?: return emptyMap() if (!file.isPhysical && file.analysisContext == null) return emptyMap() return CollectParameterRefsVisitor(callableDescriptor, defaultValueForCall).run() } override fun getOldIndex(): Int = originalIndex val isNewParameter: Boolean get() = originalIndex == -1 override fun getDefaultValue(): String? = null override fun getName(): String = name override fun setName(name: String?) { this.name = name ?: "" } override fun getTypeText(): String = currentTypeInfo.render() val isTypeChanged: Boolean get() = !currentTypeInfo.isEquivalentTo(originalTypeInfo) override fun isUseAnySingleVariable(): Boolean = false override fun setUseAnySingleVariable(b: Boolean) { throw UnsupportedOperationException() } fun renderType(parameterIndex: Int, inheritedCallable: KotlinCallableDefinitionUsage<*>): String { val defaultRendering = currentTypeInfo.render() val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return defaultRendering val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return defaultRendering val parameter = currentBaseFunction.valueParameters[parameterIndex] if (parameter.isVararg) return defaultRendering val parameterType = parameter.type if (parameterType.isError) return defaultRendering val originalType = inheritedCallable.originalCallableDescriptor.valueParameters.getOrNull(originalIndex)?.type val typeToRender = originalType?.takeIf { val checker = OverridingTypeCheckerContext.createChecker(inheritedCallable.originalCallableDescriptor, currentBaseFunction) AbstractTypeChecker.equalTypes(checker as AbstractTypeCheckerContext, originalType.unwrap(), parameterType.unwrap()) } ?: parameterType return typeToRender.renderTypeWithSubstitution(typeSubstitutor, defaultRendering, true) } fun getInheritedName(inheritedCallable: KotlinCallableDefinitionUsage<*>): String { if (!inheritedCallable.isInherited) return name val baseFunction = inheritedCallable.baseFunction val baseFunctionDescriptor = baseFunction.originalCallableDescriptor val inheritedFunctionDescriptor = inheritedCallable.originalCallableDescriptor val inheritedParameterDescriptors = inheritedFunctionDescriptor.valueParameters if (originalIndex < 0 || originalIndex >= baseFunctionDescriptor.valueParameters.size || originalIndex >= inheritedParameterDescriptors.size ) return name val inheritedParamName = inheritedParameterDescriptors[originalIndex].name.asString() val oldParamName = baseFunctionDescriptor.valueParameters[originalIndex].name.asString() return when { oldParamName == inheritedParamName && inheritedFunctionDescriptor !is AnonymousFunctionDescriptor -> name else -> inheritedParamName } } fun requiresExplicitType(inheritedCallable: KotlinCallableDefinitionUsage<*>): Boolean { val inheritedFunctionDescriptor = inheritedCallable.originalCallableDescriptor if (inheritedFunctionDescriptor !is AnonymousFunctionDescriptor) return true if (originalIndex < 0) return !inheritedCallable.hasExpectedType val inheritedParameterDescriptor = inheritedFunctionDescriptor.valueParameters[originalIndex] val parameter = DescriptorToSourceUtils.descriptorToDeclaration(inheritedParameterDescriptor) as? KtParameter ?: return false return parameter.typeReference != null } private fun getOriginalParameter(inheritedCallable: KotlinCallableDefinitionUsage<*>): KtParameter? { return (inheritedCallable.declaration as? KtFunction)?.valueParameters?.getOrNull(originalIndex) } private fun buildNewParameter(inheritedCallable: KotlinCallableDefinitionUsage<*>, parameterIndex: Int): KtParameter { val psiFactory = KtPsiFactory(inheritedCallable.project) val buffer = StringBuilder() if (modifierList != null) { buffer.append(modifierList.text).append(' ') } if (valOrVar != KotlinValVar.None) { buffer.append(valOrVar).append(' ') } buffer.append(getInheritedName(inheritedCallable).quoteIfNeeded()) if (requiresExplicitType(inheritedCallable)) { buffer.append(": ").append(renderType(parameterIndex, inheritedCallable)) } if (!inheritedCallable.isInherited) { defaultValue?.let { buffer.append(" = ").append(it.text) } } return psiFactory.createParameter(buffer.toString()) } fun getDeclarationSignature(parameterIndex: Int, inheritedCallable: KotlinCallableDefinitionUsage<*>): KtParameter { val originalParameter = getOriginalParameter(inheritedCallable) ?: return buildNewParameter(inheritedCallable, parameterIndex) val psiFactory = KtPsiFactory(originalParameter) val newParameter = originalParameter.copied() modifierList?.let { newParameter.setModifierList(it) } if (valOrVar != newParameter.valOrVarKeyword.toValVar()) { newParameter.setValOrVar(valOrVar) } val newName = getInheritedName(inheritedCallable) if (newParameter.name != newName) { newParameter.setName(newName.quoteIfNeeded()) } if (newParameter.typeReference != null || requiresExplicitType(inheritedCallable)) { newParameter.typeReference = psiFactory.createType(renderType(parameterIndex, inheritedCallable)) } if (!inheritedCallable.isInherited) { defaultValue?.let { newParameter.setDefaultValue(it) } } return newParameter } private class CollectParameterRefsVisitor( private val callableDescriptor: CallableDescriptor, private val expressionToProcess: KtExpression ) : KtTreeVisitorVoid() { private val refs = LinkedHashMap<PsiReference, DeclarationDescriptor>() private val bindingContext = expressionToProcess.analyze(BodyResolveMode.PARTIAL) private val project = expressionToProcess.project fun run(): Map<PsiReference, DeclarationDescriptor> { expressionToProcess.accept(this) return refs } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val ref = expression.mainReference val descriptor = targetToCollect(expression, ref) ?: return refs[ref] = descriptor } private fun targetToCollect(expression: KtSimpleNameExpression, ref: KtReference): DeclarationDescriptor? { val descriptor = ref.resolveToDescriptors(bindingContext).singleOrNull() if (descriptor is ValueParameterDescriptor) { return takeIfOurParameter(descriptor) } if (descriptor is PropertyDescriptor && callableDescriptor is ConstructorDescriptor) { val parameter = DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) if (parameter is KtParameter) { return takeIfOurParameter(bindingContext[BindingContext.VALUE_PARAMETER, parameter]) } } val resolvedCall = expression.getResolvedCall(bindingContext) ?: return null (resolvedCall.resultingDescriptor as? ReceiverParameterDescriptor)?.let { return if (takeIfOurReceiver(it.containingDeclaration) != null) it else null } takeIfOurReceiver(resolvedCall.extensionReceiver as? ImplicitReceiver)?.let { return it } takeIfOurReceiver(resolvedCall.dispatchReceiver as? ImplicitReceiver)?.let { return it } return null } private fun compareDescriptors(currentDescriptor: DeclarationDescriptor?, originalDescriptor: DeclarationDescriptor?): Boolean { return compareDescriptors(project, currentDescriptor, originalDescriptor) } private fun takeIfOurParameter(parameter: DeclarationDescriptor?): ValueParameterDescriptor? { return (parameter as? ValueParameterDescriptor) ?.takeIf { compareDescriptors(it.containingDeclaration, callableDescriptor) } } private fun takeIfOurReceiver(receiverDescriptor: DeclarationDescriptor?): DeclarationDescriptor? { return receiverDescriptor?.takeIf { compareDescriptors(it, callableDescriptor.extensionReceiverParameter?.containingDeclaration) || compareDescriptors(it, callableDescriptor.dispatchReceiverParameter?.containingDeclaration) } } private fun takeIfOurReceiver(receiver: ImplicitReceiver?): DeclarationDescriptor? { return takeIfOurReceiver(receiver?.declarationDescriptor) } } } private fun defaultValOrVar(callableDescriptor: CallableDescriptor): KotlinValVar = if (callableDescriptor.isAnnotationConstructor() || callableDescriptor.isPrimaryConstructorOfDataClass) KotlinValVar.Val else KotlinValVar.None private class OverridingTypeCheckerContext(private val matchingTypeConstructors: Map<TypeConstructor, TypeConstructor>) : ClassicTypeCheckerContext(errorTypeEqualsToAnything = true) { override fun areEqualTypeConstructors(a: TypeConstructor, b: TypeConstructor): Boolean = super.areEqualTypeConstructors(a, b) || run { val img1 = matchingTypeConstructors[a] val img2 = matchingTypeConstructors[b] img1 != null && img1 == b || img2 != null && img2 == a } companion object { fun createChecker(superDescriptor: CallableDescriptor, subDescriptor: CallableDescriptor): OverridingTypeCheckerContext { return OverridingTypeCheckerContext(subDescriptor.typeParameters.zip(superDescriptor.typeParameters).associate { it.first.typeConstructor to it.second.typeConstructor }) } } }
apache-2.0
32958d2357e0c3a0b3b6e0ee8020b4db
45.702128
158
0.740395
6.322612
false
false
false
false
smmribeiro/intellij-community
plugins/editorconfig/src/org/editorconfig/language/util/EditorConfigDescriptorUtil.kt
15
2449
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.util import org.editorconfig.language.schema.descriptors.EditorConfigDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigConstantDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigDeclarationDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigUnionDescriptor import kotlin.reflect.KClass import kotlin.reflect.full.safeCast object EditorConfigDescriptorUtil { fun collectDeclarations(descriptor: EditorConfigDescriptor, id: String): List<EditorConfigDeclarationDescriptor> { val result = mutableListOf<EditorConfigDeclarationDescriptor>() fun collectInternal(descriptor: EditorConfigDescriptor) { if (descriptor is EditorConfigDeclarationDescriptor) { if (descriptor.id == id) { result.add(descriptor) } } descriptor.children.forEach(::collectInternal) } collectInternal(descriptor) return result } inline fun <reified T : EditorConfigDescriptor> getParentOfType(descriptor: EditorConfigDescriptor) = getParentOfType(descriptor, T::class) tailrec fun <T : EditorConfigDescriptor> getParentOfType(descriptor: EditorConfigDescriptor, cls: KClass<T>): T? { val casted = cls.safeCast(descriptor) if (casted != null) return casted val parent = descriptor.parent ?: return null return getParentOfType(parent, cls) } fun isConstant(descriptor: EditorConfigDescriptor): Boolean = when (descriptor) { is EditorConfigConstantDescriptor -> true is EditorConfigUnionDescriptor -> descriptor.children.all(::isConstant) else -> false } fun isVariable(descriptor: EditorConfigDescriptor): Boolean = when (descriptor) { is EditorConfigDeclarationDescriptor -> true is EditorConfigUnionDescriptor -> descriptor.children.all(::isVariable) else -> false } fun collectConstants(descriptor: EditorConfigDescriptor): List<String> { val result = mutableListOf<String>() fun collectInternal(descriptor: EditorConfigDescriptor) { when (descriptor) { is EditorConfigConstantDescriptor -> result.add(descriptor.text) else -> descriptor.children.forEach { collectInternal(it) } } } collectInternal(descriptor) return result } }
apache-2.0
9e42be53d8598ac4b824361ef6181644
37.873016
140
0.761127
5.232906
false
true
false
false
80998062/Fank
presentation/src/main/java/com/sinyuk/fanfou/viewmodel/TimelineViewModel.kt
1
3033
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.viewmodel import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.Transformations.map import android.arch.lifecycle.Transformations.switchMap import android.arch.lifecycle.ViewModel import com.sinyuk.fanfou.domain.DO.Status import com.sinyuk.fanfou.domain.PAGE_SIZE import com.sinyuk.fanfou.domain.TIMELINE_CONTEXT import com.sinyuk.fanfou.domain.TIMELINE_FAVORITES import com.sinyuk.fanfou.domain.repo.Listing import com.sinyuk.fanfou.domain.repo.timeline.TimelineRepository import com.sinyuk.fanfou.domain.repo.timeline.tiled.TiledTimelineRepository import javax.inject.Inject /** * Created by sinyuk on 2017/12/6. * */ class TimelineViewModel @Inject constructor(private val repo: TimelineRepository, private val remote: TiledTimelineRepository) : ViewModel() { companion object { const val TAG = "TimelineViewModel" } data class RelativeUrl(val path: String, val id: String, val query: String? = null) private var relativeUrl: MutableLiveData<RelativeUrl> = MutableLiveData() fun setRelativeUrl(path: String, id: String, query: String? = null) { setRelativeUrl(RelativeUrl(path, id, query)) } @Suppress("MemberVisibilityCanBePrivate") fun setRelativeUrl(url: RelativeUrl) = if (url == relativeUrl.value) { false } else { relativeUrl.value = url true } private val repoResult: LiveData<Listing<Status>> = map(relativeUrl, { if (it.path == TIMELINE_FAVORITES || it.path == TIMELINE_CONTEXT) { remote.statuses(path = it.path, pageSize = PAGE_SIZE, uniqueId = it.id) } else { repo.statuses(path = it.path, pageSize = PAGE_SIZE, uniqueId = it.id) } }) val statuses = switchMap(repoResult, { it.pagedList })!! val networkState = switchMap(repoResult, { it.networkState })!! val refreshState = switchMap(repoResult, { it.refreshState })!! fun retry() { val listing = repoResult.value listing?.retry?.invoke() } fun refresh() { repoResult.value?.refresh?.invoke() } fun createFavorite(id: String) = repo.createFavorite(id) fun destroyFavorite(id: String) = repo.destroyFavorite(id) fun delete(id: String) = repo.delete(id) }
mit
d71af9a4b578182a1ef28e56c6587945
31.978261
104
0.690406
4.017219
false
false
false
false
dinosaurwithakatana/freight
freight-processor/src/main/kotlin/io/dwak/freight/processor/model/FieldBinding.kt
1
1423
package io.dwak.freight.processor.model import io.dwak.freight.annotation.Extra import io.dwak.freight.processor.extension.hasAnnotationWithName import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.ExecutableElement import javax.lang.model.type.TypeMirror class FieldBinding(element: Element): Binding { override val name: String override val type: TypeMirror override val kind: ElementKind internal val key: String internal val builderMethodName: String internal val isRequired: Boolean init { val extraInstance = element.getAnnotation(Extra::class.java) kind = element.kind name = element.simpleName.toString() type = if (kind == ElementKind.FIELD) { element.asType() } else { (element as ExecutableElement).parameters[0].asType() } if (extraInstance.value.isNotEmpty()) { key = extraInstance.value builderMethodName = key } else { key = name.toUpperCase() builderMethodName = name } isRequired = !element.hasAnnotationWithName("Nullable") } override fun toString(): String { @Suppress("ConvertToStringTemplate") return "FieldBinding(builderMethodName='$builderMethodName', " + "name='$name', " + "type=$type, " + "key='$key', " + "kind=$kind, " + "isRequired=$isRequired)" } }
apache-2.0
7d766075d1579967a3f90390f240e2c0
25.867925
68
0.681658
4.378462
false
false
false
false
saksmt/karaf-runner
src/main/java/run/smt/karafrunner/modules/api/AbstractModule.kt
1
1338
package run.smt.karafrunner.modules.api import org.kohsuke.args4j.CmdLineException import org.kohsuke.args4j.CmdLineParser import org.kohsuke.args4j.Option import run.smt.karafrunner.io.exception.UserErrorException import run.smt.karafrunner.io.output.error import run.smt.karafrunner.modules.impl.VersionModule import run.smt.karafrunner.modules.impl.util.TextProvidingModule abstract class AbstractModule : Module { @Option(name = "--help", aliases = arrayOf("-h"), required = false) private var showHelp = false @Option(name = "--version", aliases = arrayOf("-V"), required = false) private var showVersion = false override fun run(arguments: List<String>) { val parser = CmdLineParser(this) try { parser.parseArgument(arguments) if (showHelp) { TextProvidingModule(Thread.currentThread().contextClassLoader.getResource("help.txt").readText()) .run(arguments) return } if (showVersion) { VersionModule().run(arguments) return } doRun() } catch (e: UserErrorException) { error(e.message) } catch (e: CmdLineException) { error(e.localizedMessage) } } protected abstract fun doRun(); }
mit
5f659cff39f181f191b154bffcbb27cc
32.475
113
0.636024
4.445183
false
false
false
false
mars-sim/mars-sim
mars-sim-core/src/main/kotlin/com/beust/nnk/NeuralNetwork.kt
1
7238
package com.beust.nnk import kotlin.random.Random import java.io.Serializable //import java.util.Random //import java.util.* /** * A simple neural network with one hidden layer. Learning rate, momemntum and activation function are * all hardcoded in this example but should ideally be configurable. * * @author Cédric Beust <[email protected]> * @since 5/02/2016 */ class NeuralNetwork(val inputSize: Int, val hiddenSize: Int, val outputSize: Int, val hiddenNonLinearity: NonLinearity = NonLinearities.TANH.value, val outputNonLinearity: NonLinearity = NonLinearities.LEAKYRELU.value) : Serializable { val actualInputSize = inputSize + 1 // Add one for the bias node // Activations for nodes val activationInput = Vector(actualInputSize, { -> 1.0f }) val activationHidden = Vector(hiddenSize, { -> 1.0f }) val activationOutput = Vector(outputSize, { -> 1.0f }) // Weights // Make sure our initial weights are not going to send our values into the saturated area of the // non linearity function, so spread them gently around 0. In theory, this should be a ratio function // of the fan-in (previous layer size) and fan-out (next layer size) but let's just hardcode for now val weightInput = Matrix(actualInputSize, hiddenSize, { -> rand(-0.2f, 0.2f) }) val weightOutput = Matrix(hiddenSize, outputSize, { -> rand(-0.2f, 0.2f) }) // Weights for momentum val momentumInput = Matrix(actualInputSize, hiddenSize) val momentumOutput = Matrix(hiddenSize, outputSize) /** Fix the random seed for reproducible numbers while debugging */ companion object { val random = Random(1) } fun rand(min: Float, max: Float) = random.nextFloat() * (max - min) + min /** * Run the graph with the given inputs. * * @return the outputs as a vector. */ fun runGraph(inputs: List<Float>, logLevel: Int) : Vector { if (inputs.size != actualInputSize -1) { throw RuntimeException("Expected ${actualInputSize - 1} inputs but got ${inputs.size}") } // Input activations (note: -1 since we don't count the bias node) repeat(actualInputSize - 1) { activationInput[it] = inputs[it] } // Hidden activations repeat(hiddenSize) { j -> var sum = 0.0f repeat(actualInputSize) { i -> // val w: List<Float> = weightInput[i] log(logLevel, " sum += ai[$i] ${activationInput[i]} * wi[i][j] ${weightInput[i][j]}") sum += activationInput[i] * weightInput[i][j] } activationHidden[j] = hiddenNonLinearity.activate(sum) log(logLevel, " final sum going into ah[$j]: " + activationHidden[j]) } // Output activations repeat(outputSize) { k -> var sum = 0.0f repeat(hiddenSize) { j -> log(logLevel, " sum += ah[$j] ${activationHidden[j]} * wo[$j][$k] ${weightOutput[j][k]}") log(logLevel, " = " + activationHidden[j] * weightOutput[j][k]) sum += activationHidden[j] * weightOutput[j][k] } activationOutput[k] = outputNonLinearity.activate(sum) log(logLevel, " activate(sum $sum) = " + activationOutput) } return activationOutput } /** * Use the targets to backpropagate through the graph, starting with the output, then the hidden * layer and then the input. * * @return the error */ fun backPropagate(targets: List<Float>, learningRate: Float, momentum: Float) : Float { if (targets.size != outputSize) { throw RuntimeException("Expected $outputSize targets but got ${targets.size}") } // Calculate error terms for output val outputDeltas = Vector(outputSize) repeat(outputSize) { k -> val error = targets[k] - activationOutput[k] outputDeltas[k] = outputNonLinearity.activateDerivative(activationOutput[k]) * error } // Calculate error terms for hidden layers val hiddenDeltas = Vector(hiddenSize) repeat(hiddenSize) { j -> var error = 0.0f repeat(outputSize) { k -> error += outputDeltas[k] * weightOutput[j][k] } hiddenDeltas[j] = hiddenNonLinearity.activateDerivative(activationHidden[j]) * error } // Update output weights repeat(hiddenSize) { j -> repeat(outputSize) { k -> val change = outputDeltas[k] * activationHidden[j] log(3, " weightOutput[$j][$k] changing from " + weightOutput[j][k] + " to " + (weightOutput[j][k] + learningRate * change + momentum * momentumOutput[j][k])) weightOutput[j][k] = weightOutput[j][k] + learningRate * change + momentum * momentumOutput[j][k] momentumOutput[j][k] = change } } // Update input weights repeat(actualInputSize) { i -> repeat(hiddenSize) { j -> val change = hiddenDeltas[j] * activationInput[i] log(3, " weightInput[$i][$j] changing from " + weightInput[i][j] + " to " + (weightInput[i][j] + learningRate * change + momentum * momentumInput[i][j])) weightInput[i][j] = weightInput[i][j] + learningRate * change + momentum * momentumInput[i][j] momentumInput[i][j] = change } } // Calculate error var error = 0.0 repeat(targets.size) { k -> val diff = targets[k] - activationOutput[k] error += 0.5 * diff * diff } log(3, " new error: " + error) return error.toFloat() } /** * Train the graph with the given NetworkData, which contains pairs of inputs and expected outputs. */ fun train(networkDatas: List<NetworkData>, iterations: Int, learningRate: Float = 0.5f, momentum: Float = 0.1f) { repeat(iterations) { iteration -> var error = 0.0f networkDatas.forEach { pattern -> log(3, " Current input: " + pattern.inputs) runGraph(pattern.inputs, logLevel = 3) val bp = backPropagate(pattern.expectedOutputs, learningRate, momentum) error += bp } if (iteration % 100 == 0) { log(3, " Iteration $iteration Error: $error") } } } fun test(networkDatas: List<NetworkData>) { networkDatas.forEach { // log(1, it.inputs.toString() + " -> " + runGraph(it.inputs, logLevel = 3) // ) } } fun dump() { log(2, "Input weights:\n" + weightInput.dump()) log(2, "Output weights:\n" + weightOutput.dump()) } } // class Vector2(val size: Int, val defaultValue: () -> Float = { -> 0.0f }) : Matrix(size, 1, defaultValue) { // operator fun set(it: Int, value: Float) { // this[it][0] = value // } // override operator fun get(i: Int) = this[i][0] // }
gpl-3.0
1ae053d7964e93a799f7ceec3515b255
36.890052
114
0.573304
4.159195
false
false
false
false
hazuki0x0/YuzuBrowser
module/download/src/main/java/jp/hazuki/yuzubrowser/download/core/downloader/Downloader.kt
1
2302
/* * Copyright (C) 2017-2021 Hazuki * * 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 jp.hazuki.yuzubrowser.download.core.downloader import android.content.Context import androidx.documentfile.provider.DocumentFile import jp.hazuki.yuzubrowser.download.DOWNLOAD_TMP_TYPE import jp.hazuki.yuzubrowser.download.core.data.DownloadFileInfo import jp.hazuki.yuzubrowser.download.core.data.DownloadRequest import okhttp3.OkHttpClient interface Downloader { var downloadListener: DownloadListener? fun download(): Boolean fun cancel() = Unit fun pause() = Unit fun abort() = Unit companion object { fun getDownloader(context: Context, okHttpClient: OkHttpClient, info: DownloadFileInfo, request: DownloadRequest): Downloader { return if (info.url.startsWith("data:")) { val semicolon = info.url.indexOf(';') if (info.url.startsWith(DOWNLOAD_TMP_TYPE, semicolon)) { Base64TmpDownloader(context, info, request) } else { Base64Downloader(context, info, request) } } else if (info.url.startsWith("http:", true) || info.url.startsWith("https:", true)) { OkHttpDownloader(context, okHttpClient, info, request) } else { UniversalDownloader(context, info, request) } } } interface DownloadListener { fun onStartDownload(info: DownloadFileInfo) fun onFileDownloaded(info: DownloadFileInfo, downloadedFile: DocumentFile) fun onFileDownloadAbort(info: DownloadFileInfo) fun onFileDownloadFailed(info: DownloadFileInfo, cause: String? = null) fun onFileDownloading(info: DownloadFileInfo, progress: Long) } }
apache-2.0
0a995b8669bb464498db4d798bd696d9
33.358209
135
0.683753
4.697959
false
false
false
false
JetBrains/teamcity-azure-plugin
plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/utils/ArmTemplateBuilder.kt
1
17447
/* * Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.utils import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonProcessingException import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import com.intellij.openapi.diagnostic.Logger import jetbrains.buildServer.clouds.azure.arm.AzureConstants import jetbrains.buildServer.clouds.azure.arm.connector.models.JsonValue import jetbrains.buildServer.util.StringUtil import java.util.* /** * Allows to customize ARM template. */ class ArmTemplateBuilder(template: String) { private val mapper = ObjectMapper() private var root: ObjectNode private val parameters = linkedMapOf<String, JsonValue>() init { mapper.enable(JsonParser.Feature.ALLOW_COMMENTS) val reader = mapper.reader() root = reader.readTree(template) as ObjectNode } @Suppress("unused") fun addParameter(name: String, type: String, description: String): ArmTemplateBuilder { val parameters = (root["parameters"] as? ObjectNode) ?: root.putObject("parameters") parameters.putPOJO(name, object : Any() { val type = type val metadata = object : Any() { val description = description } }) return this } fun setTags(resourceName: String, tags: Map<String, String>): ArmTemplateBuilder { val resources = root["resources"] as ArrayNode val resource = resources.filterIsInstance<ObjectNode>() .first { it["name"].asText() == resourceName } val element = (resource["tags"] as? ObjectNode) ?: resource.putObject("tags") element.apply { for ((key, value) in tags) { this.put(key, value) } } return this } @Suppress("unused", "MayBeConstant") fun setPublicIp(): ArmTemplateBuilder { (root["variables"] as ObjectNode).apply { this.put("pipName", "[concat(parameters('vmName'), '-pip')]") } (root["resources"] as ArrayNode).apply { this.filterIsInstance<ObjectNode>() .first { it["name"].asText() == "[variables('nicName')]" } .apply { this.putPOJO("dependsOn", listOf("[concat('Microsoft.Network/publicIPAddresses/', variables('pipName'))]")) (this["properties"]["ipConfigurations"][0]["properties"] as ObjectNode).apply { this.putPOJO("publicIPAddress", object : Any() { val id = "[resourceId('Microsoft.Network/publicIPAddresses', variables('pipName'))]" }) } } this.addPOJO(object : Any() { val apiVersion = "2016-09-01" val type = "Microsoft.Network/publicIPAddresses" val name = "[variables('pipName')]" val location = "[variables('location')]" val properties = object : Any() { val publicIPAllocationMethod = "Dynamic" } }) } return this } @Suppress("unused", "MayBeConstant") fun setVhdImage(): ArmTemplateBuilder { (root["resources"] as ArrayNode).apply { this.filterIsInstance<ObjectNode>() .first { it["name"].asText() == "[parameters('vmName')]" } .apply { (this["properties"]["storageProfile"]["osDisk"] as ObjectNode).apply { this.putPOJO("image", object : Any() { val uri = "[parameters('imageUrl')]" }) this.putPOJO("vhd", object : Any() { val uri = "[concat('https://', split(parameters('imageUrl'),'/')[2], '/vhds/', parameters('vmName'), '-os.vhd')]" }) } } } return this } @Suppress("unused", "MayBeConstant") fun setCustomImage(): ArmTemplateBuilder { (root["resources"] as ArrayNode).apply { this.filterIsInstance<ObjectNode>() .first { it["name"].asText() == "[parameters('vmName')]" } .apply { (this["properties"]["storageProfile"] as ObjectNode).apply { this.putPOJO("imageReference", object : Any() { val id = "[parameters('imageId')]" }) } } } return this } @Suppress("unused") fun setStorageAccountType(storageAccountType: String?): ArmTemplateBuilder { if (!storageAccountType.isNullOrEmpty()) { (root["resources"] as ArrayNode).apply { this.filterIsInstance<ObjectNode>() .first { it["name"].asText() == "[parameters('vmName')]" } .apply { (this["properties"]["storageProfile"]["osDisk"] as ObjectNode).apply { this.putPOJO("managedDisk", object : Any() { val storageAccountType = storageAccountType }) } } } } return this } fun setCustomData(customData: String): ArmTemplateBuilder { (root["resources"] as ArrayNode).apply { this.filterIsInstance<ObjectNode>() .first { it["name"].asText() == "[parameters('vmName')]" } .apply { val properties = (this["properties"] as? ObjectNode) ?: this.putObject("properties") val osProfile = (properties["osProfile"] as? ObjectNode) ?: properties.putObject("osProfile") osProfile.put("customData", customData) } } return this } fun setParameterValue(name: String, value: String): ArmTemplateBuilder { parameters[name] = JsonValue(value) return this } @Suppress("unused") fun addContainer(name: String, customEnvironmentVariables: List<Pair<String, String>> = Collections.emptyList()): ArmTemplateBuilder { val properties = getPropertiesOfResource("type", "Microsoft.ContainerInstance/containerGroups") val containers = (properties["containers"] as? ArrayNode) ?: properties.putArray("containers") val environmentVariables = mutableListOf( object { val name = "SERVER_URL" val value = "[parameters('teamcityUrl')]" }, object { val name = "AGENT_NAME" val value = name } ) environmentVariables.addAll(customEnvironmentVariables .filter { it.first != "SERVER_URL" && it.second != "SERVER_URL" } .map { object { val name = it.first val value = it.second } }) containers.addPOJO(object { val name = name val properties = object { val image = "[parameters('imageId')]" val environmentVariables = environmentVariables.toList() val resources = object { val requests = object { val cpu = "[parameters('numberCores')]" val memoryInGb = "[parameters('memory')]" } } } }) reloadTemplate() return this } @Suppress("unused", "MayBeConstant") fun addContainerCredentials(server: String, username: String, password: String): ArmTemplateBuilder { val properties = getPropertiesOfResource("type", "Microsoft.ContainerInstance/containerGroups") val credentials = (properties["imageRegistryCredentials"] as? ArrayNode) ?: properties.putArray("imageRegistryCredentials") credentials.addPOJO(object { val server = server val username = username val password = password }) reloadTemplate() return this } fun addContainerNetwork(): ArmTemplateBuilder { addParameter("networkId", "String", "Virtual Network name for the container.") addParameter("subnetName", "String", "Sub network name for the container.") (root["variables"] as ObjectNode).apply { this.put("netProfileName", "[concat(parameters('containerName'), '-net-profile')]") this.put("netConfigName", "[concat(parameters('containerName'), '-net-config')]") this.put("netIPConfigName", "[concat(parameters('containerName'), '-net-ip-config')]") this.put("subnetRef", "[concat(parameters('networkId'), '/subnets/', parameters('subnetName'))]") } (root["resources"] as ArrayNode).apply { this.addPOJO(object { val apiVersion = "2019-11-01" val type = "Microsoft.Network/networkProfiles" val name = "[variables('netProfileName')]" val location = "[variables('location')]" val properties = object { val containerNetworkInterfaceConfigurations = arrayOf( object { val name = "[variables('netConfigName')]" val properties = object { val ipConfigurations = arrayOf( object { val name = "[variables('netIPConfigName')]" val properties = object { val subnet = object { val id = "[variables('subnetRef')]" } } }) } } ) } }) } val container = (root["resources"].filterIsInstance<ObjectNode>().first { it["type"].asText() == "Microsoft.ContainerInstance/containerGroups" }) container .putArray("dependsOn") .add("[resourceId('Microsoft.Network/networkProfiles', variables('netProfileName'))]") val containerNetworkProfileRef = container["properties"] as ObjectNode containerNetworkProfileRef .putObject("networkProfile") .put("id", "[resourceId('Microsoft.Network/networkProfiles', variables('netProfileName'))]") return this } @Suppress("unused", "MayBeConstant") fun addContainerVolumes(resourceName: String, name: String): ArmTemplateBuilder { val properties = getPropertiesOfResource(resourceName) val containers = containersFromProperties(properties) (containers.firstOrNull() as? ObjectNode)?.let { val props = (it["properties"] as? ObjectNode) ?: it.putObject("properties") val volumeMounts = (props["volumeMounts"] as? ArrayNode) ?: props.putArray("volumeMounts") volumeMounts.addPOJO(object { val name = name val mountPath = "/var/lib/waagent/" val readOnly = true }) volumeMounts.addPOJO(object { val name = "$name-plugins" val mountPath = "/opt/buildagent/plugins/" }) volumeMounts.addPOJO(object { val name = "$name-logs" val mountPath = "/opt/buildagent/logs/" }) volumeMounts.addPOJO(object { val name = "$name-system" val mountPath = "/opt/buildagent/system/.teamcity-agent/" }) volumeMounts.addPOJO(object { val name = "$name-tools" val mountPath = "/opt/buildagent/tools/" }) } val volumes = (properties["volumes"] as? ArrayNode) ?: properties.putArray("volumes") volumes.addPOJO(object { val name = name val azureFile = object { val shareName = name val storageAccountName = "[parameters('storageAccountName')]" val storageAccountKey = "[parameters('storageAccountKey')]" } }) for (volume in AzureConstants.CONTAINER_VOLUMES) { volumes.addPOJO(object { val name = "$name-$volume" val azureFile = object { val shareName = "$name-$volume" val storageAccountName = "[parameters('storageAccountName')]" val storageAccountKey = "[parameters('storageAccountKey')]" } }) } return this.addParameter("storageAccountName", "String", "") .addParameter("storageAccountKey", "SecureString", "") } private fun containersFromProperties(properties: ObjectNode) = (properties["containers"] as? ArrayNode) ?: properties.putArray("containers") @Suppress("unused") fun addContainerEnvironment(resourceName: String, environment: Map<String, String>): ArmTemplateBuilder { val properties = getPropertiesOfResource(resourceName) val containers = (properties["containers"] as? ArrayNode) ?: properties.putArray("containers") (containers.firstOrNull() as? ObjectNode)?.let { val props = (it["properties"] as? ObjectNode) ?: it.putObject("properties") val envVars = (props["environmentVariables"] as? ArrayNode) ?: props.putArray("environmentVariables") environment.forEach { envVars.addPOJO(object { val name = it.key val value = it.value }) } } return this } @Suppress("unused", "MayBeConstant") fun enableAcceleratedNerworking(): ArmTemplateBuilder { val properties = getPropertiesOfResource("type", "Microsoft.Network/networkInterfaces") properties.put("enableAcceleratedNetworking", true) return this } fun serializeParameters(): String { return try { mapper.writeValueAsString(parameters) } catch (e: JsonProcessingException) { StringUtil.EMPTY } } private fun getPropertiesOfResource(resourceName: String): ObjectNode { return getPropertiesOfResource("name", resourceName) } private fun getPropertiesOfResource(fieldName: String, fieldValue: String): ObjectNode { val resources = root["resources"] as ArrayNode val groups = resources.filterIsInstance<ObjectNode>().first { it[fieldName].asText() == fieldValue } return (groups["properties"] as? ObjectNode) ?: groups.putObject("properties") } private fun reloadTemplate() { val reader = mapper.reader() root = reader.readTree(mapper.writeValueAsString(root)) as ObjectNode } override fun toString(): String = mapper.writeValueAsString(root) fun logDetails() { if (!LOG.isDebugEnabled) return LOG.debug("Deployment template: \n" + toString()) val deploymentParameters = "Deployment parameters:" + parameters.entries.joinToString("\n") { (key, value) -> val parameter = if (key == "adminPassword") "*****" else value.value " - '$key' = '$parameter'" } LOG.debug(deploymentParameters) } fun setupSpotInstance(enableSpotPrice: Boolean?, spotPrice: Int?): ArmTemplateBuilder { val properties = getPropertiesOfResource("type", "Microsoft.Compute/virtualMachines") properties.put("priority", "Spot") properties.put("evictionPolicy", "Deallocate") val billingProfile = properties.putObject("billingProfile") if (enableSpotPrice == true && spotPrice != null) { billingProfile.put("maxPrice", spotPrice / PRICE_DIVIDER) } else { billingProfile.put("maxPrice", -1) } return this } companion object { private val LOG = Logger.getInstance(ArmTemplateBuilder::class.java.name) private val PRICE_DIVIDER = 100000F } }
apache-2.0
6d0d762a62aa45d7ee17f61d8c878d56
40.148585
153
0.546512
5.510739
false
false
false
false
seventhroot/elysium
bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/database/table/RPKPaymentGroupInviteTable.kt
1
6315
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.payments.bukkit.database.table import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.payments.bukkit.RPKPaymentsBukkit import com.rpkit.payments.bukkit.database.jooq.rpkit.Tables.RPKIT_PAYMENT_GROUP_INVITE import com.rpkit.payments.bukkit.group.RPKPaymentGroup import com.rpkit.payments.bukkit.group.RPKPaymentGroupProvider import com.rpkit.payments.bukkit.group.invite.RPKPaymentGroupInvite import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType /** * Represents payment group invite table. */ class RPKPaymentGroupInviteTable( database: Database, private val plugin: RPKPaymentsBukkit ): Table<RPKPaymentGroupInvite>(database, RPKPaymentGroupInvite::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_payment_group_invite.id.enabled")) { database.cacheManager.createCache("rpk-payments-bukkit.rpkit_payment_group_invite.id", CacheConfigurationBuilder .newCacheConfigurationBuilder(Int::class.javaObjectType, RPKPaymentGroupInvite::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_payment_group_invite.id.size")))) } else { null } override fun create() { database.create .createTableIfNotExists(RPKIT_PAYMENT_GROUP_INVITE) .column(RPKIT_PAYMENT_GROUP_INVITE.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_PAYMENT_GROUP_INVITE.PAYMENT_GROUP_ID, SQLDataType.INTEGER) .column(RPKIT_PAYMENT_GROUP_INVITE.CHARACTER_ID, SQLDataType.INTEGER) .constraints( constraint("pk_rpkit_payment_group_invite").primaryKey(RPKIT_PAYMENT_GROUP_INVITE.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "0.4.0") } } override fun insert(entity: RPKPaymentGroupInvite): Int { database.create .insertInto( RPKIT_PAYMENT_GROUP_INVITE, RPKIT_PAYMENT_GROUP_INVITE.PAYMENT_GROUP_ID, RPKIT_PAYMENT_GROUP_INVITE.CHARACTER_ID ) .values( entity.paymentGroup.id, entity.character.id ) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) return id } override fun update(entity: RPKPaymentGroupInvite) { database.create .update(RPKIT_PAYMENT_GROUP_INVITE) .set(RPKIT_PAYMENT_GROUP_INVITE.PAYMENT_GROUP_ID, entity.paymentGroup.id) .set(RPKIT_PAYMENT_GROUP_INVITE.CHARACTER_ID, entity.character.id) .where(RPKIT_PAYMENT_GROUP_INVITE.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) } override fun get(id: Int): RPKPaymentGroupInvite? { if (cache?.containsKey(id) == true) { return cache[id] } else { val result = database.create .select( RPKIT_PAYMENT_GROUP_INVITE.PAYMENT_GROUP_ID, RPKIT_PAYMENT_GROUP_INVITE.CHARACTER_ID ) .from(RPKIT_PAYMENT_GROUP_INVITE) .where(RPKIT_PAYMENT_GROUP_INVITE.ID.eq(id)) .fetchOne() ?: return null val paymentGroupProvider = plugin.core.serviceManager.getServiceProvider(RPKPaymentGroupProvider::class) val paymentGroupId = result.get(RPKIT_PAYMENT_GROUP_INVITE.PAYMENT_GROUP_ID) val paymentGroup = paymentGroupProvider.getPaymentGroup(paymentGroupId) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val characterId = result.get(RPKIT_PAYMENT_GROUP_INVITE.CHARACTER_ID) val character = characterProvider.getCharacter(characterId) if (paymentGroup != null && character != null) { val paymentGroupInvite = RPKPaymentGroupInvite( id, paymentGroup, character ) cache?.put(id, paymentGroupInvite) return paymentGroupInvite } else { database.create .deleteFrom(RPKIT_PAYMENT_GROUP_INVITE) .where(RPKIT_PAYMENT_GROUP_INVITE.ID.eq(id)) .execute() cache?.remove(id) return null } } } fun get(paymentGroup: RPKPaymentGroup): List<RPKPaymentGroupInvite> { val results = database.create .select(RPKIT_PAYMENT_GROUP_INVITE.ID) .from(RPKIT_PAYMENT_GROUP_INVITE) .where(RPKIT_PAYMENT_GROUP_INVITE.PAYMENT_GROUP_ID.eq(paymentGroup.id)) .fetch() return results .map { result -> get(result.get(RPKIT_PAYMENT_GROUP_INVITE.ID)) } .filterNotNull() } override fun delete(entity: RPKPaymentGroupInvite) { database.create .deleteFrom(RPKIT_PAYMENT_GROUP_INVITE) .where(RPKIT_PAYMENT_GROUP_INVITE.ID.eq(entity.id)) .execute() cache?.remove(entity.id) } }
apache-2.0
a9aa91b33639e3c5082ad6284fc3425b
41.106667
120
0.620744
4.769637
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/gene/sql/geometric/SqlCircleGene.kt
1
3150
package org.evomaster.core.search.gene.sql.geometric import org.evomaster.core.search.gene.* import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.OutputFormat import org.evomaster.core.search.gene.numeric.FloatGene import org.evomaster.core.search.gene.root.CompositeFixedGene import org.evomaster.core.search.gene.utils.GeneUtils import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy import org.slf4j.Logger import org.slf4j.LoggerFactory class SqlCircleGene( name: String, val c: SqlPointGene = SqlPointGene(name = "c"), // radius cannot be negative val r: FloatGene = FloatGene(name = "r", min = 0f, minInclusive = true) ) : CompositeFixedGene(name, mutableListOf(c, r)) { companion object { val log: Logger = LoggerFactory.getLogger(SqlCircleGene::class.java) } override fun isLocallyValid() : Boolean{ return getViewOfChildren().all { it.isLocallyValid() } } override fun copyContent(): Gene = SqlCircleGene( name, c.copy() as SqlPointGene, r.copy() as FloatGene ) override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) { c.randomize(randomness, tryToForceNewValue) r.randomize(randomness, tryToForceNewValue) } override fun getValueAsPrintableString( previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean ): String { return "\"${getValueAsRawString()}\"" } override fun getValueAsRawString(): String { return "(${c.getValueAsRawString()}, ${r.getValueAsRawString()})" } override fun copyValueFrom(other: Gene) { if (other !is SqlCircleGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } this.c.copyValueFrom(other.c) this.r.copyValueFrom(other.r) } override fun containsSameValueAs(other: Gene): Boolean { if (other !is SqlCircleGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } return this.c.containsSameValueAs(other.c) && this.r.containsSameValueAs(other.r) } override fun bindValueBasedOn(gene: Gene): Boolean { return when { gene is SqlCircleGene -> { c.bindValueBasedOn(gene.c) && r.bindValueBasedOn(gene.r) } else -> { LoggingUtil.uniqueWarn(log, "cannot bind CircleGene with ${gene::class.java.simpleName}") false } } } override fun customShouldApplyShallowMutation( randomness: Randomness, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { return false } }
lgpl-3.0
03d3e1e97a96a80b09f668138789fd07
32.168421
105
0.666032
4.992076
false
false
false
false
ibinti/intellij-community
platform/platform-impl/src/com/intellij/util/io/netty.kt
3
11562
/* * 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.util.io import com.google.common.net.InetAddresses import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Conditions import com.intellij.openapi.util.SystemInfo import com.intellij.util.SystemProperties import com.intellij.util.Url import com.intellij.util.Urls import com.intellij.util.net.NetUtils import io.netty.bootstrap.Bootstrap import io.netty.bootstrap.BootstrapUtil import io.netty.bootstrap.ServerBootstrap import io.netty.buffer.ByteBuf import io.netty.channel.* import io.netty.channel.kqueue.KQueueEventLoopGroup import io.netty.channel.kqueue.KQueueServerSocketChannel import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.oio.OioEventLoopGroup import io.netty.channel.socket.ServerSocketChannel import io.netty.channel.socket.nio.NioServerSocketChannel import io.netty.channel.socket.oio.OioServerSocketChannel import io.netty.channel.socket.oio.OioSocketChannel import io.netty.handler.codec.http.HttpHeaderNames import io.netty.handler.codec.http.HttpMethod import io.netty.handler.codec.http.HttpRequest import io.netty.handler.ssl.SslHandler import io.netty.resolver.ResolvedAddressTypes import io.netty.util.concurrent.GenericFutureListener import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.ide.PooledThreadExecutor import org.jetbrains.io.BuiltInServer import org.jetbrains.io.NettyUtil import java.io.IOException import java.net.InetAddress import java.net.InetSocketAddress import java.net.NetworkInterface import java.net.Socket import java.util.concurrent.ThreadFactory import java.util.concurrent.TimeUnit // used in Go fun oioClientBootstrap(): Bootstrap { val bootstrap = Bootstrap().group(OioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(OioSocketChannel::class.java) bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true) return bootstrap } inline fun Bootstrap.handler(crossinline task: (Channel) -> Unit): Bootstrap { handler(object : ChannelInitializer<Channel>() { override fun initChannel(channel: Channel) { task(channel) } }) return this } fun serverBootstrap(group: EventLoopGroup): ServerBootstrap { val bootstrap = ServerBootstrap() .group(group) .channel(group.serverSocketChannelClass()) bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) return bootstrap } private fun EventLoopGroup.serverSocketChannelClass(): Class<out ServerSocketChannel> = when { this is NioEventLoopGroup -> NioServerSocketChannel::class.java this is OioEventLoopGroup -> OioServerSocketChannel::class.java SystemInfo.isMacOSSierra && this is KQueueEventLoopGroup -> KQueueServerSocketChannel::class.java else -> throw Exception("Unknown event loop group type: ${this.javaClass.name}") } inline fun ChannelFuture.addChannelListener(crossinline listener: (future: ChannelFuture) -> Unit) { addListener(GenericFutureListener<ChannelFuture> { listener(it) }) } // if NIO, so, it is shared and we must not shutdown it fun EventLoop.shutdownIfOio() { if (this is OioEventLoopGroup) { @Suppress("USELESS_CAST") (this as OioEventLoopGroup).shutdownGracefully(1L, 2L, TimeUnit.NANOSECONDS) } } // Event loop will be shut downed only if OIO fun Channel.closeAndShutdownEventLoop() { val eventLoop = eventLoop() try { close().awaitUninterruptibly() } finally { eventLoop.shutdownIfOio() } } @JvmOverloads fun Bootstrap.connect(remoteAddress: InetSocketAddress, promise: AsyncPromise<*>? = null, maxAttemptCount: Int = NettyUtil.DEFAULT_CONNECT_ATTEMPT_COUNT, stopCondition: Condition<Void>? = null): Channel? { try { return doConnect(this, remoteAddress, promise, maxAttemptCount, stopCondition ?: Conditions.alwaysFalse<Void>()) } catch (e: Throwable) { promise?.setError(e) return null } } private fun doConnect(bootstrap: Bootstrap, remoteAddress: InetSocketAddress, promise: AsyncPromise<*>?, maxAttemptCount: Int, stopCondition: Condition<Void>): Channel? { var attemptCount = 0 if (bootstrap.config().group() !is OioEventLoopGroup) { return connectNio(bootstrap, remoteAddress, promise, maxAttemptCount, stopCondition, attemptCount) } bootstrap.validate() while (true) { try { val channel = OioSocketChannel(Socket(remoteAddress.address, remoteAddress.port)) BootstrapUtil.initAndRegister(channel, bootstrap).sync() return channel } catch (e: IOException) { if (stopCondition.value(null) || promise != null && promise.state != Promise.State.PENDING) { return null } else if (maxAttemptCount == -1) { if (sleep(promise, 300)) { return null } attemptCount++ } else if (++attemptCount < maxAttemptCount) { if (sleep(promise, attemptCount * NettyUtil.MIN_START_TIME)) { return null } } else { promise?.setError(e) return null } } } } private fun connectNio(bootstrap: Bootstrap, remoteAddress: InetSocketAddress, promise: AsyncPromise<*>?, maxAttemptCount: Int, stopCondition: Condition<Void>, _attemptCount: Int): Channel? { var attemptCount = _attemptCount while (true) { val future = bootstrap.connect(remoteAddress).awaitUninterruptibly() if (future.isSuccess) { if (!future.channel().isOpen) { continue } return future.channel() } else if (stopCondition.value(null) || promise != null && promise.state == Promise.State.REJECTED) { return null } else if (maxAttemptCount == -1) { if (sleep(promise, 300)) { return null } attemptCount++ } else if (++attemptCount < maxAttemptCount) { if (sleep(promise, attemptCount * NettyUtil.MIN_START_TIME)) { return null } } else { @SuppressWarnings("ThrowableResultOfMethodCallIgnored") val cause = future.cause() if (promise != null) { if (cause == null) { promise.setError("Cannot connect: unknown error") } else { promise.setError(cause) } } return null } } } fun sleep(promise: AsyncPromise<*>?, time: Int): Boolean { try { //noinspection BusyWait Thread.sleep(time.toLong()) } catch (ignored: InterruptedException) { promise?.setError("Interrupted") return true } return false } val Channel.uriScheme: String get() = if (pipeline().get(SslHandler::class.java) == null) "http" else "https" val HttpRequest.host: String? get() = headers().getAsString(HttpHeaderNames.HOST) val HttpRequest.origin: String? get() = headers().getAsString(HttpHeaderNames.ORIGIN) val HttpRequest.referrer: String? get() = headers().getAsString(HttpHeaderNames.REFERER) val HttpRequest.userAgent: String? get() = headers().getAsString(HttpHeaderNames.USER_AGENT) inline fun <T> ByteBuf.releaseIfError(task: () -> T): T { try { return task() } catch (e: Exception) { try { release() } finally { throw e } } } fun isLocalHost(host: String, onlyAnyOrLoopback: Boolean, hostsOnly: Boolean = false): Boolean { if (NetUtils.isLocalhost(host)) { return true } // if IP address, it is safe to use getByName (not affected by DNS rebinding) if (onlyAnyOrLoopback && !InetAddresses.isInetAddress(host)) { return false } fun InetAddress.isLocal() = isAnyLocalAddress || isLoopbackAddress || NetworkInterface.getByInetAddress(this) != null try { val address = InetAddress.getByName(host) if (!address.isLocal()) { return false } // be aware - on windows hosts file doesn't contain localhost // hosts can contain remote addresses, so, we check it if (hostsOnly && !InetAddresses.isInetAddress(host)) { return io.netty.resolver.HostsFileEntriesResolver.DEFAULT.address(host, ResolvedAddressTypes.IPV4_PREFERRED).let { it != null && it.isLocal() } } else { return true } } catch (ignored: IOException) { return false } } @JvmOverloads fun HttpRequest.isLocalOrigin(onlyAnyOrLoopback: Boolean = true, hostsOnly: Boolean = false) = parseAndCheckIsLocalHost(origin, onlyAnyOrLoopback, hostsOnly) && parseAndCheckIsLocalHost(referrer, onlyAnyOrLoopback, hostsOnly) private fun isTrustedChromeExtension(url: Url): Boolean { return url.scheme == "chrome-extension" && (url.authority == "hmhgeddbohgjknpmjagkdomcpobmllji" || url.authority == "offnedcbhjldheanlbojaefbfbllddna") } private val Url.host: String? get() = authority?.let { val portIndex = it.indexOf(':') if (portIndex > 0) it.substring(0, portIndex) else it } @JvmOverloads fun parseAndCheckIsLocalHost(uri: String?, onlyAnyOrLoopback: Boolean = true, hostsOnly: Boolean = false): Boolean { if (uri == null || uri == "about:blank") { return true } try { val parsedUri = Urls.parse(uri, false) ?: return false val host = parsedUri.host return host != null && (isTrustedChromeExtension(parsedUri) || isLocalHost(host, onlyAnyOrLoopback, hostsOnly)) } catch (ignored: Exception) { } return false } fun HttpRequest.isRegularBrowser() = userAgent?.startsWith("Mozilla/5.0") ?: false // forbid POST requests from browser without Origin fun HttpRequest.isWriteFromBrowserWithoutOrigin(): Boolean { val method = method() return origin.isNullOrEmpty() && isRegularBrowser() && (method == HttpMethod.POST || method == HttpMethod.PATCH || method == HttpMethod.PUT || method == HttpMethod.DELETE) } fun ByteBuf.readUtf8(): String = toString(Charsets.UTF_8) fun ByteBuf.writeUtf8(data: CharSequence) = writeCharSequence(data, Charsets.UTF_8) fun MultiThreadEventLoopGroup(workerCount: Int, threadFactory: ThreadFactory): MultithreadEventLoopGroup { if (SystemInfo.isMacOSSierra && SystemProperties.getBooleanProperty("native.net.io", false)) { try { return KQueueEventLoopGroup(workerCount, threadFactory) } catch (e: Throwable) { logger<BuiltInServer>().warn("Cannot use native event loop group", e) } } return NioEventLoopGroup(workerCount, threadFactory) } fun MultiThreadEventLoopGroup(workerCount: Int): MultithreadEventLoopGroup { if (SystemInfo.isMacOSSierra && SystemProperties.getBooleanProperty("native.net.io", false)) { try { return KQueueEventLoopGroup(workerCount, PooledThreadExecutor.INSTANCE) } catch (e: Throwable) { // error instead of warn to easy spot it logger<BuiltInServer>().error("Cannot use native event loop group", e) } } return NioEventLoopGroup(workerCount, PooledThreadExecutor.INSTANCE) }
apache-2.0
0ef083a427a9ac4d78db1ee3174ed16b
32.131805
225
0.712161
4.445213
false
false
false
false
chrisdoc/kotlin-koans
src/i_introduction/_5_String_Templates/StringTemplates.kt
1
1194
package i_introduction._5_String_Templates import util.TODO import util.doc5 fun example1(a: Any, b: Any) = "This is some text in which variables ($a, $b) appear." fun example2(a: Any, b: Any) = "You can write it in a Java way as well. Like this: " + a + ", " + b + "!" fun example3(c: Boolean, x: Int, y: Int) = "Any expression can be used: ${if (c) x else y}" fun example4() = """ You can use raw strings to write multiline text. There is no escaping here, so raw strings are useful for writing regex patterns, you don't need to escape a backslash by a backslash. String template entries (${42}) are allowed here. """ fun getPattern() = """\d{2}\.\d{2}\.\d{4}""" fun example() = "13.06.1992".matches(getPattern().toRegex()) //true val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)" fun todoTask5(): Nothing = TODO( """ Task 5. Copy the body of 'getPattern()' to the 'task5()' function and rewrite it in such a way that it matches '13 JUN 1992'. Use the 'month' variable. """, documentation = doc5(), references = { getPattern(); month }) fun task5(): String { return """\d{2} $month \d{4}""" }
mit
d04ef42ed4f3188920995940730424bb
28.85
91
0.621441
3.262295
false
false
false
false
commons-app/apps-android-commons
app/src/main/java/fr/free/nrw/commons/recentlanguages/RecentLanguagesAdapter.kt
1
2668
package fr.free.nrw.commons.recentlanguages import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import fr.free.nrw.commons.R import fr.free.nrw.commons.databinding.RowItemLanguagesSpinnerBinding import fr.free.nrw.commons.utils.LangCodeUtils import org.apache.commons.lang3.StringUtils import java.util.HashMap /** * Array adapter for recent languages */ class RecentLanguagesAdapter constructor( context: Context, var recentLanguages: List<Language>, private val selectedLanguages: HashMap<*, String> ) : ArrayAdapter<String?>(context, R.layout.row_item_languages_spinner) { /** * Selected language code in UploadMediaDetailAdapter * Used for marking selected ones */ var selectedLangCode = "" override fun isEnabled(position: Int) = recentLanguages[position].languageCode.let { it.isNotEmpty() && !selectedLanguages.containsValue(it) && it != selectedLangCode } override fun getCount() = recentLanguages.size override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val binding: RowItemLanguagesSpinnerBinding var rowView = convertView if (rowView == null) { val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater binding = RowItemLanguagesSpinnerBinding.inflate(layoutInflater, parent, false) rowView = binding.root } else { binding = RowItemLanguagesSpinnerBinding.bind(rowView) } val languageCode = recentLanguages[position].languageCode val languageName = recentLanguages[position].languageName binding.tvLanguage.let { it.isEnabled = isEnabled(position) if (languageCode.isEmpty()) { it.text = StringUtils.capitalize(languageName) it.textAlignment = View.TEXT_ALIGNMENT_CENTER } else { it.text = "${StringUtils.capitalize(languageName)}" + " [${LangCodeUtils.fixLanguageCode(languageCode)}]" } } return rowView } /** * Provides code of a language from recent languages for a specific position */ fun getLanguageCode(position: Int): String { return recentLanguages[position].languageCode } /** * Provides name of a language from recent languages for a specific position */ fun getLanguageName(position: Int): String { return recentLanguages[position].languageName } }
apache-2.0
3110ec4dbefab169176bab358ea49779
33.662338
91
0.676162
5.062619
false
false
false
false
cketti/okhttp
samples/guide/src/test/kotlin/okhttp3/AllMainsTest.kt
1
2730
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.io.File import java.lang.reflect.InvocationTargetException import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) @Ignore class AllMainsTest(val className: String) { @Test fun runMain() { val mainMethod = Class.forName(className) .methods.find { it.name == "main" } try { if (mainMethod != null) { if (mainMethod.parameters.isEmpty()) { mainMethod.invoke(null) } else { mainMethod.invoke(null, arrayOf<String>()) } } else { System.err.println("No main for $className") } } catch (ite: InvocationTargetException) { if (!expectedFailure(className, ite.cause!!)) { throw ite.cause!! } } } @Suppress("UNUSED_PARAMETER") private fun expectedFailure( className: String, cause: Throwable ): Boolean { return when (className) { "okhttp3.recipes.CheckHandshake" -> true // by design "okhttp3.recipes.RequestBodyCompression" -> true // expired token else -> false } } companion object { private val prefix = if (File("samples").exists()) "" else "../../" @JvmStatic @Parameterized.Parameters(name = "{0}") fun data(): List<String> { val mainFiles = mainFiles() return mainFiles.map { val suffix = it.path.replace("${prefix}samples/guide/src/main/java/", "") suffix.replace("(.*)\\.java".toRegex()) { mr -> mr.groupValues[1].replace('/', '.') }.replace("(.*)\\.kt".toRegex()) { mr -> mr.groupValues[1].replace('/', '.') + "Kt" } }.sorted() } private fun mainFiles(): List<File> { val directories = listOf( "$prefix/samples/guide/src/main/java/okhttp3/guide", "$prefix/samples/guide/src/main/java/okhttp3/recipes", "$prefix/samples/guide/src/main/java/okhttp3/recipes/kt" ).map { File(it) } return directories.flatMap { it.listFiles().orEmpty().filter { f -> f.isFile }.toList() } } } }
apache-2.0
8294ccfc177cf5af6d68e6d2031092bc
29.333333
81
0.628205
3.997072
false
false
false
false
eugeis/ee
ee-lang/src/main/kotlin/ee/lang/gen/kt/KotlinTests.kt
1
4094
package ee.lang.gen.kt import ee.common.ext.joinSurroundIfNotEmptyToString import ee.common.ext.toUnderscoredUpperCase import ee.lang.* import ee.lang.gen.java.junit fun <T : EnumTypeI<*>> T.toKotlinEnumParseAndIsMethodsTests( c: GenerationContext, derived: String = LangDerivedKind.API): String { val name = c.n(this, derived).capitalize() val toByName = "to${name}ByName" var prev = literals().last() return """ class ${name}EnumParseAndIsMethodsTests { @${c.n(junit.Test, derived)} fun testStringTo${name}_Normal() { $name.values().forEach { item -> //check normal ${c.n(k.test.assertSame, derived)}(item, item.name.$toByName()) } } @${c.n(junit.Test, derived)} fun testStringTo${name}_CaseNotSensitive() { $name.values().forEach { item -> //check case not sensitive ${c.n(k.test.assertSame, derived)}(item, item.name.toLowerCase().$toByName()) ${c.n(k.test.assertSame, derived)}(item, item.name.toUpperCase().$toByName()) } //check null to default value ${c.n(k.test.assertSame, derived)}(null.$toByName(), $name.${literals().first().toKotlin()}) //check unknown to default value ${c.n(k.test.assertSame, derived)}("".$toByName(), $name.${literals().first().toKotlin()}) } @${c.n(junit.Test, derived)} fun testStringTo${name}_NullOrWrongToDefault() { //check null to default value ${c.n(k.test.assertSame, derived)}(null.$toByName(), $name.${literals().first().toKotlin()}) //check empty to default value ${c.n(k.test.assertSame, derived)}("".$toByName(), $name.${literals().first().toKotlin()}) //check unknown to default value ${c.n(k.test.assertSame, derived)}("$@%".$toByName(), $name.${literals().first().toKotlin()}) }${literals().joinToString(nL) { lit -> val litCap = lit.toKotlin() val prevCap = prev.toKotlin() prev = lit """ @${c.n(junit.Test, derived)} fun testIs${lit.toKotlin()}() { //normal ${c.n(k.test.assertTrue, derived)}($name.$litCap.${lit.toKotlinIsMethod()}) //wrong ${c.n(k.test.assertFalse, derived)}($name.$prevCap.${lit.toKotlinIsMethod()}) } """ }} } """ } fun <T : CompilationUnitI<*>> T.toKotlinFieldTest( c: GenerationContext, derived: String = LangDerivedKind.IMPL, api: String = LangDerivedKind.API, dataClass: Boolean = this is BasicI<*> && superUnits().isEmpty() && superUnitFor().isEmpty()): String { if (generics().isNotEmpty()) return "" val name = c.n(this, derived).capitalize() val timeProps = primaryConstructor().params().filter { it.type() == n.Date }.associateBy({ it.name() }) { it.name() } return """ class ${name}FieldTests { @${c.n(junit.Test, derived)} fun test${name}_Normal() {${timeProps.values.joinSurroundIfNotEmptyToString(nL, prefix = nL) { " val $it = Date()" }} val item = $name${primaryConstructor().toKotlinCallValue(c, derived, externalVariables = timeProps, resolveLiteralValue = true)}${ propsAll().joinSurroundIfNotEmptyToString(nL, prefix = nL, postfix = nL) { " ${c.n(k.test.assertEquals, derived)}(${ it.toKotlinValueInit(c, derived, value = timeProps[it.name()] ?: it.value(), resolveLiteralValue = true)}, item.${it.name()})" }} } @${c.n(junit.Test, derived)} fun test${name}_Default() { val item = $name.EMPTY${ propsAll().joinSurroundIfNotEmptyToString(nL, prefix = nL, postfix = nL) { if (!it.isNullable() && it.type() == n.Date) { " ${c.n(k.test.assertTrue, derived)}(${ it.toKotlinValueInit(c, derived)}.time - item.${it.name()}.time <= 5000)" } else { " ${c.n(k.test.assertEquals, derived)}(${ it.toKotlinValueInit(c, derived, resolveLiteralValue = true)}, item.${it.name()})" } }} } }""" }
apache-2.0
54225a9761fe4d40ca3e19cb9c2072bc
35.238938
111
0.584758
3.862264
false
true
false
false
joatca/WebShare
app/src/main/java/com/coffree/webshare/MainActivity.kt
1
5068
/* This file is part of Web Share. Web Share 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. Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>. Copyright 2016 Fraser McCrossan */ package com.coffree.webshare import android.content.Intent import android.net.Uri import android.support.v7.app.AppCompatActivity import android.os.Bundle import java.net.MalformedURLException import java.net.URL import org.jetbrains.anko.* import java.util.* class MainActivity : AppCompatActivity() { val TAG = "MainActivity" val services: Map<String, (String, String) -> String> = mapOf( "Facebook" to { u, t -> "https://www.facebook.com/sharer.php?u=$u" }, // FB only takes the link "Twitter" to { u, t -> "https://twitter.com/intent/tweet?text=$t${Uri.encode(" ")}$u" }, // Twitter can take all the text "Google+" to { u, t -> "https://plus.google.com/share?url=$u" }, // G+ also only takes the link "Reddit" to { u, t -> "https://www.reddit.com/submit?url=$u&title=$t"}, // Reddit can take a title "LinkedIn" to { u, t -> "https://www.linkedin.com/shareArticle?mini=true&url=$u&title=$t&summary=&source=" } ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Intent.ACTION_SEND.equals(intent.action) && intent.type != null && "text/plain".equals(intent.type)) { shareToWeb() } else { showMainScreen() } } fun shareToWeb() { // find first URL and other non-URL words var url: String = "" var words = ArrayList<String>() intent.getStringExtra(Intent.EXTRA_TEXT).splitToSequence(" ").forEach { word -> if (url.length == 0) { try { val urlObject = URL(word) url = word } catch (e: MalformedURLException) { words.add(word) } } else { words.add(word) } } val text = Uri.encode(words.joinToString(separator = " ")) val prefs = getPreferences(MODE_PRIVATE) val enabledServices = services.filterKeys { name -> prefs.getBoolean(name, false) }.toList() if (enabledServices.size == 1) { val (name, lamb) = enabledServices[0] webIntent(lamb.invoke(url, text)) } else if (enabledServices.size >= 1) { val enabledNames = enabledServices.map { it.component1() } selector("", enabledNames) { i -> val(name, lamb) = enabledServices[i] webIntent(lamb.invoke(url, text)) } } else { // else no services are enabled, might as well show the config screen longToast(R.string.no_services_enabled) showMainScreen() } } fun webIntent(url: String?) { val uri = Uri.parse(url) val i = Intent(Intent.ACTION_VIEW) i.data = uri startActivity(i) finish() } fun showMainScreen() { val vmargin = dip(5) val hmargin = dip(8) val checkHmargin = dip(10) verticalLayout { textView { textResource = R.string.service_select textSize = 18f }.lparams(width = matchParent) { verticalMargin = vmargin horizontalMargin = hmargin } textView { textResource = R.string.service_explain textSize = 14f }.lparams(width = matchParent) { bottomMargin = vmargin horizontalMargin = hmargin } verticalLayout { val prefs = getPreferences(MODE_PRIVATE) services.forEach { val (name, lamb) = it checkBox(name) { textSize = 18f setChecked(prefs.getBoolean(name, false)) onCheckedChange { button, b -> getPreferences(MODE_PRIVATE).edit().let { prefs -> prefs.putBoolean(name, isChecked) prefs.commit() } } }.lparams(width = matchParent) { topMargin = vmargin horizontalMargin = checkHmargin } } } } } }
gpl-3.0
c97ee47ce98f5b692fe0b6ebad7b9f79
36.264706
133
0.543607
4.598911
false
false
false
false
luoyuan800/NeverEnd
server_core/src/cn/luo/yuan/maze/server/model/User.kt
1
664
package cn.luo.yuan.maze.server.model import cn.luo.yuan.maze.utils.EncodeLong import cn.luo.yuan.maze.utils.Field import cn.luo.yuan.maze.utils.StringUtils import java.io.Serializable /** * Created by gluo on 7/4/2017. */ class User : Serializable { companion object { private const val serialVersionUID: Long = Field.SERVER_VERSION } private val pass = EncodeLong(111) fun getPass():Long{ return pass.value } fun setPass(pass:Int){ this.pass.value = pass.toLong() } var name: String? = null var login: Boolean = false var sing = StringUtils.EMPTY_STRING var battleInterval = 5 }
bsd-3-clause
a002d61401aebc0c17ee7e4aef79dff4
21.896552
71
0.667169
3.628415
false
false
false
false
nlefler/Glucloser
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/models/parcelable/BloodSugarParcelable.kt
1
1269
package com.nlefler.glucloser.a.models.parcelable import android.os.Parcel import android.os.Parcelable import java.util.* /** * Created by Nathan Lefler on 1/4/15. */ public class BloodSugarParcelable() : Parcelable { var id: String = UUID.randomUUID().toString() var value: Int = 0 var date: Date = Date() /** Parcelable */ protected constructor(parcel: Parcel) : this() { id = parcel.readString() value = parcel.readInt() val time = parcel.readLong() if (time > 0) { date = Date(time) } } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(id) dest.writeInt(value) dest.writeLong(date.time) } companion object { @JvmField val CREATOR: Parcelable.Creator<BloodSugarParcelable> = object : Parcelable.Creator<BloodSugarParcelable> { override fun createFromParcel(`in`: Parcel): BloodSugarParcelable { return BloodSugarParcelable(`in`) } override fun newArray(size: Int): Array<BloodSugarParcelable> { return Array(size, {i -> BloodSugarParcelable() }) } } } }
gpl-2.0
50129d948120934802ebc4554154302f
26.586957
125
0.606777
4.46831
false
false
false
false
nisrulz/android-examples
CustomOnboardingIntro/app/src/main/java/github/nisrulz/example/customonboardingintro/IntroFragment.kt
1
2235
package github.nisrulz.example.customonboardingintro import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment class IntroFragment : Fragment() { private var mBackgroundColor = 0 private var mPage = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.apply { if (!containsKey(BACKGROUND_COLOR)) { throw RuntimeException("Fragment must contain a \"$BACKGROUND_COLOR\" argument!") } mBackgroundColor = getInt(BACKGROUND_COLOR) if (!containsKey(PAGE)) { throw RuntimeException("Fragment must contain a \"$PAGE\" argument!") } mPage = getInt(PAGE) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Select a layout based on the current page val layoutResId: Int = when (mPage) { 0 -> R.layout.fragment_intro1 else -> R.layout.fragment_intro2 } // Inflate the layout resource file val view = activity?.layoutInflater?.inflate(layoutResId, container, false) // Set the current page index as the View's tag (useful in the PageTransformer) view?.tag = mPage return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Set the background color of the root view to the color specified in newInstance() val background = view.findViewById<View>(R.id.intro_background) background.setBackgroundColor(mBackgroundColor) } companion object { private const val BACKGROUND_COLOR = "backgroundColor" private const val PAGE = "page" fun newInstance(backgroundColor: Int, page: Int): IntroFragment { val frag = IntroFragment() val b = Bundle() b.putInt(BACKGROUND_COLOR, backgroundColor) b.putInt(PAGE, page) frag.arguments = b return frag } } }
apache-2.0
74e43689c3ad14ab4ab0e034f8775bf3
31.882353
97
0.634899
5.091116
false
false
false
false
fabmax/calculator
app/src/main/kotlin/de/fabmax/calc/RotationSensor.kt
1
4446
package de.fabmax.calc import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager /** * Acceleration sensor handler for detecting screen rotations */ class RotationSensor : SensorEventListener { private val mFilter = Filter() private var mSnappedIn = true var rotation = 0f val upDirection = Vec3f(0f, 1f, 0f) fun onResume(context: Context) { val sensorMgr = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager val accel = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) if (accel != null) { sensorMgr.registerListener(this, accel, SensorManager.SENSOR_DELAY_GAME) } } fun onPause(context: Context) { val sensorMgr = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager sensorMgr.unregisterListener(this) } /** * Normalized orientation: 1 = portrait, 0 = landscape */ val normalizedHV: Float get() { val r = Math.abs(rotation) if (r < PI_2) { return 1 - r / PI_2 } else { return (r - PI_2) / PI_2 } } /** * Here happens most of the magic: Camera up direction is computed based on the phone's * acceleration sensor. Also up direction snaps in when the orientation is close to a * 90° angle or the phone is to horizontal. */ override fun onSensorChanged(event: SensorEvent) { val x = event.values[0] val y = event.values[1] val z = event.values[2] val m = Math.sqrt((x * x + y * y).toDouble()).toFloat() val thresh = when(mSnappedIn) { true -> ROT_THRESH else -> ROT_THRESH / 4 } val zThresh = when(mSnappedIn) { true -> MAG_THRESH_Z_SNAPPED else -> MAG_THRESH_Z } var a = (Math.atan2(x.toDouble(), y.toDouble())).toFloat() if (m > MAG_THRESH && z < zThresh) { // if magnitude is large enough, determine screen orientation from acceleration vector if (Math.abs(a) < thresh) { a = 0f } else if (Math.abs(a - PI_2) < thresh) { a = PI_2 } else if (Math.abs(a + PI_2) < thresh) { a = -PI_2 } else if (Math.abs(a - PI) < thresh) { a = PI } else if (Math.abs(a + PI) < thresh) { a = -PI } } else { // else lock screen orientation to nearest 90° step if (Math.abs(rotation) < PI_4) { a = 0f } else if (Math.abs(rotation - PI_2) < PI_4) { a = PI_2 } else if (Math.abs(rotation + PI_2) < PI_4) { a = -PI_2 } else if (Math.abs(rotation - PI) < PI_4) { a = PI } else if (Math.abs(rotation + PI) < PI_4) { a = -PI } } mSnappedIn = Math.abs((a % PI_2).toDouble()) < 0.0001 rotation = mFilter.update(a) upDirection.x = Math.sin(rotation.toDouble()).toFloat() upDirection.y = Math.cos(rotation.toDouble()).toFloat() upDirection.z = 0f } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) { // ignored } private inner class Filter { var mBuf = FloatArray(12) var mIdx = 0 fun update(f: Float): Float { mBuf[mIdx++] = f if (mIdx >= mBuf.size) { mIdx = 0 } val first = mBuf[0] var out = first for (i in 1..mBuf.size - 1) { var x = mBuf[i] if (Math.abs(x - first) > PI) { if (x < 0) { x += PI * 2 } else { x -= PI * 2 } } out += x } return out / mBuf.size } } companion object { private val PI = Math.PI.toFloat() private val PI_2 = PI / 2 private val PI_4 = PI / 4 private val ROT_THRESH = Math.toRadians(30.0).toFloat() private val MAG_THRESH = 5.0f private val MAG_THRESH_Z = 8.0f private val MAG_THRESH_Z_SNAPPED = 5.0f } }
apache-2.0
567871c122321cc5c0872bb160d7bed2
30.295775
98
0.508101
4.043676
false
false
false
false
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/flow/context/SetupContexts.kt
1
2814
package io.particle.mesh.setup.flow.context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.particle.mesh.common.android.livedata.castAndPost import io.particle.mesh.common.logged import io.particle.mesh.setup.connection.ProtocolTransceiver import io.particle.mesh.setup.flow.Clearable import io.particle.mesh.setup.flow.FlowIntent import io.particle.mesh.setup.flow.FlowType import io.particle.mesh.setup.flow.Scopes import mu.KotlinLogging class SetupContexts( var scopes: Scopes = Scopes(), val ble: BLEContext = BLEContext(), val cellular: CellularContext = CellularContext(), val cloud: CloudConnectionContext = CloudConnectionContext(), val device: DeviceContext = DeviceContext(), val mesh: MeshContext = MeshContext(), val wifi: WifiContext = WifiContext() ) : Clearable { private val log = KotlinLogging.logger {} var targetDevice = SetupDevice(DeviceRole.SETUP_TARGET) var commissioner = SetupDevice(DeviceRole.COMMISSIONER) var flowIntent: FlowIntent? by log.logged() var currentFlow: List<FlowType> by log.logged(emptyList()) var hasEthernet: Boolean? by log.logged() var meshNetworkFlowAdded: Boolean by log.logged(false) var singleStepCongratsMessage by log.logged("") var snackbarMessage by log.logged("") // FIXME: this should go. See notes on StepDetermineFlowAfterPreflow val getReadyNextButtonClickedLD: LiveData<Boolean?> = MutableLiveData() override fun clearState() { log.info { "clearState()" } val clearables = listOf( ble, cellular, cloud, device, mesh, wifi ) for (c in clearables) { c.clearState() } val liveDatas = listOf( getReadyNextButtonClickedLD ) for (ld in liveDatas) { ld.castAndPost(null) } // targetDevice.transceiverLD.value?.disconnect() // commissioner.transceiverLD.value?.disconnect() targetDevice = SetupDevice(DeviceRole.SETUP_TARGET) commissioner = SetupDevice(DeviceRole.COMMISSIONER) flowIntent = null singleStepCongratsMessage = "" snackbarMessage = "" currentFlow = emptyList() hasEthernet = null meshNetworkFlowAdded = false scopes.cancelChildren() } fun requireTargetXceiver(): ProtocolTransceiver { return targetDevice.transceiverLD.value!! } fun requireCommissionerXceiver(): ProtocolTransceiver { return commissioner.transceiverLD.value!! } fun updateGetReadyNextButtonClicked(clicked: Boolean) { log.info { "updateGetReadyNextButtonClicked()" } getReadyNextButtonClickedLD.castAndPost(clicked) } }
apache-2.0
e3f8621dab5af196e0e2572188b4f94e
29.597826
75
0.686212
4.598039
false
false
false
false
iZettle/wrench
wrench-app/src/main/java/com/izettle/wrench/applicationlist/ApplicationViewModel.kt
1
1485
package com.izettle.wrench.applicationlist import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.paging.LivePagedListBuilder import androidx.paging.PagedList import com.izettle.wrench.database.WrenchApplication import com.izettle.wrench.database.WrenchApplicationDao class ApplicationViewModel internal constructor(applicationDao: WrenchApplicationDao) : ViewModel() { private val mediatedApplications: MediatorLiveData<PagedList<WrenchApplication>> private val listEmpty: MutableLiveData<Boolean> = MutableLiveData() internal val applications: LiveData<PagedList<WrenchApplication>> get() = mediatedApplications internal val isListEmpty: LiveData<Boolean> get() = listEmpty init { listEmpty.value = true val applications = LivePagedListBuilder(applicationDao.getApplications(), PagedList.Config.Builder() .setEnablePlaceholders(true) .setPageSize(10) .setPrefetchDistance(10) .build()).build() mediatedApplications = MediatorLiveData() mediatedApplications.addSource(applications) { wrenchApplications -> listEmpty.value = wrenchApplications == null || wrenchApplications.size == 0 mediatedApplications.setValue(wrenchApplications) } } }
mit
da6a9b8acefa5fc189e06dacde56c5c9
32.75
88
0.717172
5.689655
false
false
false
false
moxi/weather-app-demo
weather-model/src/main/java/org/rcgonzalezf/weather/common/models/db/weather/WeatherInfoEntity.kt
1
1083
package org.rcgonzalezf.weather.common.models.db.weather import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import org.rcgonzalezf.weather.common.models.db.weather.WeatherInfoDao.Companion.DATE_TIME import org.rcgonzalezf.weather.common.models.db.weather.WeatherInfoDao.Companion.WEATHER_INFO_TABLE import java.util.UUID @Entity(tableName = WEATHER_INFO_TABLE) data class WeatherInfoEntity( @PrimaryKey var id: String = UUID.randomUUID().toString(), @ColumnInfo var cityId:Int = 0, @ColumnInfo var weatherId: Int = 0, @ColumnInfo var cityName: String? = null, @ColumnInfo var speed: Double = 0.0, @ColumnInfo var temperature: Double = 0.0, @ColumnInfo var humidity: String? = null, @ColumnInfo(name = DATE_TIME) var dateTime: String? = null, @ColumnInfo var country: String? = null, @ColumnInfo var deg: Double = 0.0, @ColumnInfo var description: String? = null )
mit
287ab326c26250df28dd85dc48d4a9ed
30.852941
99
0.658356
4.165385
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/objects/mesh/SmoothMeshTriangle.kt
1
2163
package net.dinkla.raytracer.objects.mesh import net.dinkla.raytracer.hits.Hit import net.dinkla.raytracer.math.* /** * Created by IntelliJ IDEA. * User: Jörn Dinkla * Date: 16.05.2010 * Time: 10:04:22 * To change this template use File | Settings | File Templates. */ class SmoothMeshTriangle : MeshTriangle { constructor(mesh: Mesh) : super(mesh) {} constructor(mesh: Mesh, i0: Int, i1: Int, i2: Int) : super(mesh, i0, i1, i2) {} override fun hit(ray: Ray, sr: Hit): Boolean { val v0 = mesh.vertices[index0] val v1 = mesh.vertices[index1] val v2 = mesh.vertices[index2] val a = v0.x - v1.x val b = v0.x - v2.x val c = ray.direction.x val d = v0.x - ray.origin.x val e = v0.y - v1.y val f = v0.y - v2.y val g = ray.direction.y val h = v0.y - ray.origin.y val i = v0.z - v1.z val j = v0.z - v2.z val k = ray.direction.z val l = v0.z - ray.origin.z val m = f * k - g * j val n = h * k - g * l val p = f * l - h * j val q = g * i - e * k val s = e * j - f * i val invDenom = 1.0 / (a * m + b * q + c * s) val e1 = d * m - b * n - c * p val beta = e1 * invDenom if (beta < 0.0) return false val r = e * l - h * i val e2 = a * n + d * q + c * r val gamma = e2 * invDenom if (gamma < 0.0) return false if (beta + gamma > 1.0) return false val e3 = a * p - b * r + d * s val t = e3 * invDenom if (t < MathUtils.K_EPSILON) return false sr.t = t sr.normal = interpolateNormal(beta, gamma) // for smooth shading //sr.localHitPoint = ray.linear(t); return true } protected fun interpolateNormal(beta: Double, gamma: Double): Normal { val v1 = mesh.normals[index0].times(1.0 - beta - gamma) val v2 = mesh.normals[index1].times(beta) val v3 = mesh.normals[index2].times(gamma) val normal = Normal(v1.plus(v2).plus(v3)) return normal.normalize() } }
apache-2.0
7d7e1bcec38a9a9518e470d659c3e10d
25.365854
83
0.515264
3.075391
false
false
false
false
zensum/franz
src/main/kotlin/engine/mock/MockConsumerBase.kt
1
1513
package franz.engine.mock import franz.JobStateException import franz.JobStatus import franz.Message import franz.engine.ConsumerActor import franz.engine.WorkerFunction import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.runBlocking abstract class MockConsumerActorBase<T, U> : ConsumerActor<T, U> { data class Result( val throwable: Throwable?, val status: JobStatus ) private val internalResults: MutableList<Result> = mutableListOf() fun results() = internalResults.toList() protected var handlers = mutableListOf<(Message<T, U>) -> Unit>() override fun start() = Unit override fun stop() = Unit override fun setJobStatus(msg: Message<T, U>, status: JobStatus) { internalResults.add(Result(throwable = null, status = status)) } private fun setException(e: Throwable) { internalResults.add(Result(e, JobStatus.TransientFailure)) } override fun createWorker(fn: WorkerFunction<T, U>, scope: CoroutineScope) { worker(this, fn) } private inline fun tryJobStatus(fn: () -> JobStatus) = try { fn() } catch(ex: JobStateException){ ex.result } catch (ex: Exception) { JobStatus.TransientFailure } private fun worker(consumer: ConsumerActor<T, U>, fn: WorkerFunction<T, U>) { consumer.subscribe { setJobStatus(it, tryJobStatus { runBlocking{fn(it) } }) } } fun createFactory() = MockConsumerActorFactory(this) }
mit
9122477c6e7faa6514a651b859f7b172
27.037037
81
0.677462
4.298295
false
false
false
false
lookout/clouddriver
clouddriver-elasticsearch-aws/src/main/kotlin/com/netflix/spinnaker/clouddriver/elasticsearch/ElasticSearchClient.kt
1
3688
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.clouddriver.elasticsearch import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spinnaker.clouddriver.elasticsearch.model.ElasticSearchException import com.netflix.spinnaker.clouddriver.elasticsearch.model.Model import com.netflix.spinnaker.clouddriver.elasticsearch.model.ModelType import io.searchbox.client.JestClient import io.searchbox.core.Bulk import io.searchbox.core.BulkResult import io.searchbox.core.Index import io.searchbox.indices.CreateIndex import io.searchbox.indices.DeleteIndex import io.searchbox.indices.aliases.AddAliasMapping import io.searchbox.indices.aliases.GetAliases import io.searchbox.indices.aliases.ModifyAliases import java.io.IOException class ElasticSearchClient(private val objectMapper : ObjectMapper, private val jestClient: JestClient) { fun getPreviousIndexes(prefix: String): Set<String> { try { val result = jestClient.execute(GetAliases.Builder().build()) val r = objectMapper.readValue(result.jsonString, Map::class.java) as Map<String, Any> return r.keys.filter { k -> k.startsWith(prefix) }.toSet() } catch (e: IOException) { throw ElasticSearchException("Unable to fetch previous indexes (prefix: $prefix)", e) } } fun createIndex(prefix: String): String { val newIndexName = "${prefix}_${System.currentTimeMillis()}" try { jestClient.execute(CreateIndex.Builder(newIndexName).build()) return newIndexName } catch (e: IOException) { throw ElasticSearchException("Unable to create index (index: $newIndexName)", e) } } fun createAlias(index: String, alias: String) { try { jestClient.execute( ModifyAliases.Builder( AddAliasMapping.Builder(index, alias).build() ).build() ) } catch (e: IOException) { throw ElasticSearchException("Unable to create alias (index: $index, alias: $alias)", e) } } fun deleteIndex(index: String) { try { jestClient.execute( DeleteIndex.Builder(index).build() ) } catch (e: IOException) { throw ElasticSearchException("Unable to delete index (index: $index)", e) } } fun <T : Model> store(index: String, type: ModelType, partition: List<T>) { var builder: Bulk.Builder = Bulk.Builder().defaultIndex(index) for (serverGroupModel in partition) { builder = builder.addAction( Index.Builder(objectMapper.convertValue(serverGroupModel, Map::class.java)) .index(index) .type(type.toString()) .id(serverGroupModel.id) .build() ) } val bulk = builder.build() try { val jestResult = jestClient.execute<BulkResult>(bulk) if (!jestResult.isSucceeded) { throw ElasticSearchException( java.lang.String.format("Failed to index server groups, reason: '%s'", jestResult.getErrorMessage()) ) } } catch (e: IOException) { throw ElasticSearchException( java.lang.String.format("Failed to index server groups, reason: '%s'", e.message) ) } } }
apache-2.0
30efdd882f1c8f61bdd101bae8f39646
34.12381
110
0.702007
4.210046
false
false
false
false
Kotlin/dokka
plugins/base/src/test/kotlin/model/ExtensionsTest.kt
1
4568
package model import org.jetbrains.dokka.base.transformers.documentables.CallableExtensions import org.jetbrains.dokka.model.* import org.junit.jupiter.api.Test import utils.AbstractModelTest import org.jetbrains.dokka.model.properties.WithExtraProperties class ExtensionsTest : AbstractModelTest("/src/main/kotlin/classes/Test.kt", "classes") { private fun <T : WithExtraProperties<R>, R : Documentable> T.checkExtension(name: String = "extension") = with(extra[CallableExtensions]?.extensions) { this notNull "extensions" this counts 1 (this?.single() as? DFunction)?.name equals name } @Test fun `should be extension for subclasses`() { inlineModelTest( """ |open class A |open class B: A() |open class C: B() |open class D: C() |fun B.extension() = "" """ ) { with((this / "classes" / "B").cast<DClass>()) { checkExtension() } with((this / "classes" / "C").cast<DClass>()) { checkExtension() } with((this / "classes" / "D").cast<DClass>()) { checkExtension() } with((this / "classes" / "A").cast<DClass>()) { extra[CallableExtensions] equals null } } } @Test fun `should be extension for interfaces`() { inlineModelTest( """ |interface I |interface I2 : I |open class A: I2 |fun I.extension() = "" """ ) { with((this / "classes" / "A").cast<DClass>()) { checkExtension() } with((this / "classes" / "I2").cast<DInterface>()) { checkExtension() } with((this / "classes" / "I").cast<DInterface>()) { checkExtension() } } } @Test fun `should be extension for external classes`() { inlineModelTest( """ |abstract class A<T>: AbstractList<T>() |fun<T> AbstractCollection<T>.extension() {} | |class B:Exception() |fun Throwable.extension() = "" """ ) { with((this / "classes" / "A").cast<DClass>()) { checkExtension() } with((this / "classes" / "B").cast<DClass>()) { checkExtension() } } } @Test fun `should be extension for typealias`() { inlineModelTest( """ |open class A |open class B: A() |open class C: B() |open class D: C() |typealias B2 = B |fun B2.extension() = "" """ ) { with((this / "classes" / "B").cast<DClass>()) { checkExtension() } with((this / "classes" / "C").cast<DClass>()) { checkExtension() } with((this / "classes" / "D").cast<DClass>()) { checkExtension() } with((this / "classes" / "A").cast<DClass>()) { extra[CallableExtensions] equals null } } } @Test fun `should be extension for java classes`() { val testConfiguration = dokkaConfiguration { suppressObviousFunctions = false sourceSets { sourceSet { sourceRoots = listOf("src/main/kotlin/") classpath += jvmStdlibPath!! } } } testInline( """ |/src/main/kotlin/classes/Test.kt | package classes | fun A.extension() = "" | |/src/main/kotlin/classes/A.java | package classes; | public class A {} | | /src/main/kotlin/classes/B.java | package classes; | public class B extends A {} """, configuration = testConfiguration ) { documentablesTransformationStage = { it.run { with((this / "classes" / "B").cast<DClass>()) { checkExtension() } with((this / "classes" / "A").cast<DClass>()) { checkExtension() } } } } } }
apache-2.0
11f7bfce1253cc32bdaca2cde5ca02a8
29.059211
109
0.44155
4.938378
false
true
false
false
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/workers/UploadWorker.kt
1
4014
package us.mikeandwan.photos.workers import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import androidx.hilt.work.HiltWorker import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import androidx.work.workDataOf import dagger.assisted.Assisted import dagger.assisted.AssistedInject import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import us.mikeandwan.photos.R import us.mikeandwan.photos.api.PhotoApiClient import us.mikeandwan.photos.domain.FileStorageRepository import us.mikeandwan.photos.domain.NotificationPreferenceRepository import us.mikeandwan.photos.ui.main.MainActivity import us.mikeandwan.photos.utils.NOTIFICATION_CHANNEL_ID_UPLOAD_FILES import us.mikeandwan.photos.utils.PendingIntentFlagHelper import java.io.File @HiltWorker class UploadWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted params: WorkerParameters, private val apiClient: PhotoApiClient, private val preferenceRepository: NotificationPreferenceRepository, private val notificationManager: NotificationManager, private val fileStorageRepository: FileStorageRepository ): CoroutineWorker(appContext, params) { companion object { const val KEY_FILENAME = "filename" const val KEY_FAILURE_REASON = "failure_reason" const val MAX_RETRIES = 8 } override suspend fun doWork(): Result = withContext(Dispatchers.IO) { val file = inputData.getString(KEY_FILENAME) val fileToUpload = getValidatedFile(file) ?: return@withContext Result.failure( workDataOf(KEY_FAILURE_REASON to "invalid file: $file") ) try { apiClient.uploadFile(fileToUpload) fileToUpload.delete() showNotification(true) fileStorageRepository.refreshPendingUploads() Result.success() } catch(error: Throwable) { if(runAttemptCount < MAX_RETRIES) { Result.retry() } else { showNotification(false) fileToUpload.delete() fileStorageRepository.refreshPendingUploads() Result.failure( workDataOf(KEY_FAILURE_REASON to error.message) ) } } } private fun getValidatedFile(filename: String?): File? { if (filename == null || filename.isBlank() || !File(filename).exists()) { return null } return File(filename) } private suspend fun showNotification(wasSuccessful: Boolean) { val i = Intent(applicationContext, MainActivity::class.java) val pendingIntentFlag = PendingIntentFlagHelper.getMutableFlag(PendingIntent.FLAG_UPDATE_CURRENT) val detailsIntent = PendingIntent.getActivity(applicationContext, 0, i, pendingIntentFlag) val title = if(wasSuccessful) "Media Uploaded!" else "Upload Failed" val msg = if(wasSuccessful) "File uploaded. Go to files.mikeandwan.us to manage your files." else "File was not able to be uploaded after multiple attempts. Please try again later." val builder = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL_ID_UPLOAD_FILES) .setSmallIcon(R.drawable.ic_status_notification) .setContentTitle(title) .setContentText(msg) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(detailsIntent) .setAutoCancel(true) .setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE) if (preferenceRepository.getDoVibrate().first()) { builder.setVibrate(longArrayOf(300, 300)) } val notification = builder.build() notificationManager.notify(0, notification) } }
mit
a1a78343e48371b2bc3fbfcedc463cc1
37.605769
191
0.696313
5.126437
false
false
false
false
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/adapter/DiffAdapter.kt
2
2381
package com.commit451.gitlab.adapter import androidx.recyclerview.widget.RecyclerView import android.view.ViewGroup import com.commit451.gitlab.R import com.commit451.gitlab.model.api.Diff import com.commit451.gitlab.model.api.RepositoryCommit import com.commit451.gitlab.viewHolder.DiffHeaderViewHolder import com.commit451.gitlab.viewHolder.DiffViewHolder import java.util.* /** * Shows a bunch of diffs */ class DiffAdapter(private val repositoryCommit: RepositoryCommit, private val listener: Listener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { private const val TYPE_HEADER = 0 const val TYPE_ITEM = 1 private const val HEADER_COUNT = 1 } private val values: ArrayList<Diff> = ArrayList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { when (viewType) { TYPE_HEADER -> return DiffHeaderViewHolder.inflate(parent) TYPE_ITEM -> { val holder = DiffViewHolder.inflate(parent) holder.itemView.setOnClickListener { v -> val position = v.getTag(R.id.list_position) as Int listener.onDiffClicked(getValueAt(position)) } return holder } } throw IllegalStateException("No known view holder for $viewType") } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is DiffHeaderViewHolder) { holder.bind(repositoryCommit) } else if (holder is DiffViewHolder) { val diff = getValueAt(position) holder.bind(diff) holder.itemView.setTag(R.id.list_position, position) } } override fun getItemCount(): Int { return values.size + HEADER_COUNT } override fun getItemViewType(position: Int): Int { if (position == 0) { return TYPE_HEADER } else { return TYPE_ITEM } } fun getValueAt(position: Int): Diff { return values[position - HEADER_COUNT] } fun setData(diffs: Collection<Diff>?) { values.clear() if (diffs != null) { values.addAll(diffs) } notifyDataSetChanged() } interface Listener { fun onDiffClicked(diff: Diff) } }
apache-2.0
4611a60df1f8a4018d2e8fe20e3ede53
29.139241
149
0.633767
4.641326
false
false
false
false
talhacohen/android
app/src/main/java/com/etesync/syncadapter/utils/FileUtils.kt
1
5223
package com.etesync.syncadapter.utils import android.annotation.SuppressLint import android.content.ContentUris import android.content.Context import android.database.Cursor import android.net.Uri import android.os.Build import android.os.Environment import android.provider.DocumentsContract import android.provider.MediaStore import java.io.File object FileUtils { /** * Get a file path from a Uri. This will get the the path for Storage Access * Framework Documents, as well as the _data field for the MediaStore and * other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @author paulburke */ @SuppressLint("NewApi") fun getPath(context: Context, uri: Uri?): String? { if (uri == null) { return null } val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { val docId = DocumentsContract.getDocumentId(uri) val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val type = split[0] if ("primary".equals(type, ignoreCase = true)) { return Environment.getExternalStorageDirectory().toString() + "/" + split[1] } // TODO handle non-primary volumes } else if (isDownloadsDocument(uri)) { val id = DocumentsContract.getDocumentId(uri) val contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id)) return getDataColumn(context, contentUri, null, null) } else if (isMediaDocument(uri)) { val docId = DocumentsContract.getDocumentId(uri) val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val type = split[0] var contentUri: Uri? = null if ("image" == type) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI } else if ("video" == type) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI } else if ("audio" == type) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI } val selection = "_id=?" val selectionArgs = arrayOf(split[1]) return getDataColumn(context, contentUri, selection, selectionArgs) }// MediaProvider // DownloadsProvider } else if ("content".equals(uri.scheme!!, ignoreCase = true)) { val path = getDataColumn(context, uri, null, null) if (path != null) { val file = File(path) if (!file.canRead()) { return null } } return path } else if ("file".equals(uri.scheme!!, ignoreCase = true)) { return uri.path }// File // MediaStore (and general) return null } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? { var cursor: Cursor? = null val column = "_data" val projection = arrayOf(column) try { cursor = context.contentResolver.query(uri!!, projection, selection, selectionArgs, null) if (cursor != null && cursor.moveToFirst()) { val column_index = cursor.getColumnIndexOrThrow(column) return cursor.getString(column_index) } } catch (e: Exception) { return null } finally { cursor?.close() } return null } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ fun isExternalStorageDocument(uri: Uri): Boolean { return "com.android.externalstorage.documents" == uri.authority } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ fun isDownloadsDocument(uri: Uri): Boolean { return "com.android.providers.downloads.documents" == uri.authority } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ fun isMediaDocument(uri: Uri): Boolean { return "com.android.providers.media.documents" == uri.authority } }
gpl-3.0
27305e5e0a2207c13129ed443d9dc2d6
34.773973
102
0.582424
4.840593
false
false
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/entity/ability/spell/SpellEffect.kt
1
4057
/* * The MIT License * * Copyright 2015 Nathan Templon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.jupiter.europa.entity.ability.spell import com.badlogic.ashley.core.Entity import com.badlogic.gdx.utils.Json import com.badlogic.gdx.utils.JsonValue import com.jupiter.europa.entity.ability.Ability import com.jupiter.europa.entity.component.Owned import com.jupiter.europa.entity.effects.AbilityGrantingEffect import com.jupiter.europa.entity.traits.Qualifications import com.jupiter.europa.entity.traits.Qualifier /** * Created by nathan on 8/2/15. */ public class SpellEffect() : AbilityGrantingEffect(), Owned { public constructor(spellClass: Class<out Ability>) : this() { this.spellClass = spellClass } private var spellClass: Class<out Ability>? = null get() = this.$spellClass set(value) { if (value == null) { this.$spellClass = null this._qualifier = DEFAULT_QUALIFIER } else if (value.isAnnotationPresent(javaClass<Spell>())) { this.$spellClass = value val annotations = value.getAnnotationsByType(javaClass<Spell>()) this._qualifier = Qualifications.any(*annotations.map { annotation -> Qualifications.level(annotation.characterClass, annotation.level) }.toTypedArray()) } else { throw IllegalArgumentException("The provided class must be a spell!") } } private var _qualifier: Qualifier = DEFAULT_QUALIFIER override val qualifier: Qualifier get() = this._qualifier override var owner: Entity? = null get() = this.$owner set(value) { this.$owner = value val spellClass = this.spellClass if (spellClass != null && value != null) { this.ability = SpellFactory.create(spellClass, value) } else { this.ability = null } } // Effect Implementation override fun onAdd(entity: Entity) { this.owner = entity super<AbilityGrantingEffect>.onAdd(entity) } override fun onRemove() { super<AbilityGrantingEffect>.onRemove() this.owner = null } // Serializable (Json) Implementation override fun write(json: Json) { val writeClass = this.spellClass if (writeClass != null) { json.writeValue(CLASS_NAME_KEY, writeClass.getName()) } } override fun read(json: Json, jsonData: JsonValue) { if (jsonData.has(CLASS_NAME_KEY)) { val readClass = Class.forName(jsonData.get(CLASS_NAME_KEY).asString()) if (javaClass<Ability>().isAssignableFrom(readClass)) { this.spellClass = readClass as Class<out Ability> } } } companion object { public val CLASS_NAME_KEY: String = "spell-class" private val DEFAULT_QUALIFIER = Qualifications.ACCEPT } }
mit
ee1fe5a114cf8035b48e80b89af38b68
34.286957
85
0.657136
4.631279
false
false
false
false
SimpleTimeTracking/StandaloneClient
src/main/kotlin/org/stt/time/DurationRounder.kt
1
767
package org.stt.time import java.time.Duration import javax.inject.Singleton @Singleton class DurationRounder { private var intervalMillis: Long = 0 private var tieBreakMillis: Long = 0 fun setInterval(interval: Duration) { intervalMillis = interval.toMillis() tieBreakMillis = intervalMillis / 2 } fun roundDuration(duration: Duration): Duration { val millisToRound = duration.toMillis() val segments = millisToRound / intervalMillis var result = segments * intervalMillis val delta = millisToRound - result if (delta == tieBreakMillis && segments % 2 == 1L || delta > tieBreakMillis) { result += intervalMillis } return Duration.ofMillis(result) } }
gpl-3.0
8746cc5fde683c73125ce3dbb49a0db1
25.448276
86
0.662321
4.763975
false
false
false
false
dexbleeker/hamersapp
hamersapp/src/main/java/nl/ecci/hamers/utils/Utils.kt
1
2813
package nl.ecci.hamers.utils import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.Context.INPUT_METHOD_SERVICE import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.text.Html import android.text.Spanned import android.view.inputmethod.InputMethodManager import android.widget.Toast import nl.ecci.hamers.ui.activities.MainActivity import org.apache.commons.codec.binary.Hex import org.apache.commons.codec.digest.DigestUtils import java.text.ParseException import java.text.SimpleDateFormat import java.util.* object Utils { var alertDialog: AlertDialog? = null const val unknown = "Unknown" const val notFound = -1 /** * Get app version */ fun getAppVersion(context: Context?): String? { return try { context?.packageManager?.getPackageInfo(context.packageName, 0)?.versionName } catch (e: PackageManager.NameNotFoundException) { "" } } /** * Hides the soft keyboard */ fun hideKeyboard(activity: Activity?) { if (activity != null) { if (activity.currentFocus != null) { val inputMethodManager = activity.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(activity.currentFocus!!.windowToken, 0) } } } fun showToast(context: Context?, text: String, duration: Int) { if (context != null) Toast.makeText(context, text, duration).show() } fun getIdFromUri(uri: Uri): Int { val path = uri.path return Integer.parseInt(path!!.substring(path.lastIndexOf('/') + 1)) } fun md5(message: String): String = String(Hex.encodeHex(DigestUtils.md5(message))) fun stringArrayToCharSequenceArray(stringArray: Array<Any>): Array<CharSequence?> { val charSequenceArray = arrayOfNulls<CharSequence>(stringArray.size) for (i in stringArray.indices) charSequenceArray[i] = stringArray[i] as String return charSequenceArray } /** * Parse date */ fun parseDate(dateString: String): Date { var date = Date() try { // Event date if (dateString.isNotBlank()) { val inputFormat = SimpleDateFormat("dd-MM-yyyy HH:mm", MainActivity.locale) date = inputFormat.parse(dateString) } } catch (ignored: ParseException) { } return date } /** * To HTML */ fun toHtml(s: String?) : Spanned { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) return Html.fromHtml(s, Html.FROM_HTML_MODE_COMPACT) return Html.fromHtml(s) } }
gpl-3.0
5b369f87924c59390628736734a5d8cc
28.925532
110
0.647707
4.5008
false
false
false
false
DigitalPhantom/PhantomWeatherAndroid
app/src/main/java/net/digitalphantom/app/weatherapp/fragments/SettingsFragment.kt
1
4466
/** * The MIT License (MIT) * * Copyright (c) 2015 - 2022 Yoel Nunez <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package net.digitalphantom.app.weatherapp.fragments import net.digitalphantom.app.weatherapp.R import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.content.SharedPreferences import android.os.Bundle import android.content.Intent import net.digitalphantom.app.weatherapp.WeatherActivity import android.view.MenuItem import androidx.preference.EditTextPreference import androidx.preference.Preference import androidx.preference.Preference.OnPreferenceChangeListener import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreferenceCompat class SettingsFragment : PreferenceFragmentCompat(), OnPreferenceChangeListener, OnSharedPreferenceChangeListener { private lateinit var preferences: SharedPreferences private lateinit var geolocationEnabledPreference: SwitchPreferenceCompat private lateinit var manualLocationPreference: EditTextPreference override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.app_preferences, rootKey) preferences = preferenceManager.sharedPreferences!! preferences.registerOnSharedPreferenceChangeListener(this) geolocationEnabledPreference = findPreference(getString(R.string.pref_geolocation_enabled))!! manualLocationPreference = findPreference(getString(R.string.pref_manual_location))!! bindPreferenceSummaryToValue(manualLocationPreference) bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_temperature_unit))) if (!preferences.getBoolean(getString(R.string.pref_needs_setup), false)) { val editor = preferences.edit() editor.putBoolean(getString(R.string.pref_needs_setup), false) editor.apply() } onSharedPreferenceChanged(preferences, geolocationEnabledPreference.key) setHasOptionsMenu(true) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, WeatherActivity::class.java)) return true } return super.onOptionsItemSelected(item) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, preferenceKey: String) { if (preferenceKey == geolocationEnabledPreference.key) { manualLocationPreference.isEnabled = geolocationEnabledPreference.isChecked == false } } private fun bindPreferenceSummaryToValue(preference: androidx.preference.Preference?) = preference?.apply { onPreferenceChangeListener = this@SettingsFragment onPreferenceChange(preference, preferences.getString(preference.key, null)!!) } override fun onPreferenceChange(preference: Preference, value: Any?): Boolean { val stringValue = value.toString() when (preference) { is androidx.preference.ListPreference -> { val index = preference.findIndexOfValue(stringValue) preference.summary = if (index >= 0) preference.entries[index] else null } is EditTextPreference -> { preference.summary = stringValue } } return true } }
mit
81369d10f1164e1422b5967755acc436
42.368932
115
0.743618
5.39372
false
false
false
false