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
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/TryCatchInsideFinally.kt
9
483
// WITH_STDLIB fun test(cn: Cn?): String? { var query: Q? = null var result: String? = null if (cn != null) { try { query = cn.query() result = query.data() } catch(e:Exception) {} finally { try { query?.close() } catch (e:Exception) {} } } return result } interface Cn { fun query(): Q } interface Q { fun data(): String fun close() }
apache-2.0
19c8598b2a3578113787445a0e5f09b1
17.615385
34
0.434783
3.959016
false
false
false
false
tensorflow/examples
lite/examples/model_personalization/android/app/src/main/java/org/tensorflow/lite/examples/modelpersonalization/fragments/PermissionsFragment.kt
1
2828
/* * Copyright 2022 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tensorflow.lite.examples.modelpersonalization.fragments import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.os.Bundle import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.Navigation import org.tensorflow.lite.examples.modelpersonalization.R private val PERMISSIONS_REQUIRED = arrayOf(Manifest.permission.CAMERA) class PermissionsFragment : Fragment() { private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { Toast.makeText(context, "Permission request granted", Toast.LENGTH_LONG).show() navigateToCamera() } else { Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) when { ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED -> { navigateToCamera() } else -> { requestPermissionLauncher.launch( Manifest.permission.CAMERA ) } } } private fun navigateToCamera() { lifecycleScope.launchWhenStarted { Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate( PermissionsFragmentDirections.actionPermissionsToCamera() ) } } companion object { /** Convenience method used to check if all permissions required by this app are granted */ fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED } } }
apache-2.0
f7ba0be855ca66782c94dc897c328e08
34.797468
99
0.678571
5.315789
false
false
false
false
siosio/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/ClassPathXmlPathResolver.kt
1
3790
// 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.ide.plugins import com.intellij.platform.util.plugins.DataLoader import com.intellij.platform.util.plugins.LocalFsDataLoader import java.nio.file.Files internal class ClassPathXmlPathResolver(private val classLoader: ClassLoader, private val isRunningFromSources: Boolean) : PathResolver { override val isFlat: Boolean get() = true override fun loadXIncludeReference(readInto: RawPluginDescriptor, readContext: ReadModuleContext, dataLoader: DataLoader, base: String?, relativePath: String): Boolean { val path = PluginXmlPathResolver.toLoadPath(relativePath, base) readModuleDescriptor(inputStream = classLoader.getResourceAsStream(path) ?: return false, readContext = readContext, pathResolver = this, dataLoader = dataLoader, includeBase = PluginXmlPathResolver.getChildBase(base = base, relativePath = relativePath), readInto = readInto, locationSource = dataLoader.toString()) return true } override fun resolveModuleFile(readContext: ReadModuleContext, dataLoader: DataLoader, path: String, readInto: RawPluginDescriptor?): RawPluginDescriptor { var resource = classLoader.getResourceAsStream(path) if (resource == null) { if (path == "intellij.profiler.clion") { val descriptor = RawPluginDescriptor() descriptor.`package` = "com.intellij.profiler.clion" return descriptor } if (isRunningFromSources && path.startsWith("intellij.") && dataLoader is LocalFsDataLoader) { try { resource = Files.newInputStream(dataLoader.basePath.parent.resolve("${path.substring(0, path.length - 4)}/$path")) } catch (e: Exception) { throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader, classLoader=$classLoader). " + "Please ensure that project is built (Build -> Build Project).", e) } } if (resource == null) { throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader, classLoader=$classLoader)") } } return readModuleDescriptor(inputStream = resource, readContext = readContext, pathResolver = this, dataLoader = dataLoader, includeBase = null, readInto = readInto, locationSource = dataLoader.toString()) } override fun resolvePath(readContext: ReadModuleContext, dataLoader: DataLoader, relativePath: String, readInto: RawPluginDescriptor?): RawPluginDescriptor? { val path = PluginXmlPathResolver.toLoadPath(relativePath, null) val resource = classLoader.getResourceAsStream(path) return readModuleDescriptor(inputStream = resource ?: return null, readContext = readContext, pathResolver = this, dataLoader = dataLoader, includeBase = null, readInto = readInto, locationSource = dataLoader.toString()) } }
apache-2.0
16cba70e05d5e9d216f918806e35f119
48.233766
158
0.571768
6.41286
false
false
false
false
Briseus/Lurker
app/src/main/java/torille/fi/lurkforreddit/data/models/view/SearchResult.kt
1
407
package torille.fi.lurkforreddit.data.models.view import android.os.Parcelable import kotlinx.android.parcel.Parcelize /** * Data class for showing search result */ @Parcelize data class SearchResult( val title: CharSequence = "", val subscriptionInfo: String = "", val infoText: String = "", val description: CharSequence = "", val subreddit: Subreddit = Subreddit() ) : Parcelable
mit
d573b96704fbf93fa982e7304132bea4
24.4375
49
0.717445
4.423913
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/buttons/FavoriteButton.kt
1
1651
package io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons import android.content.Context import android.content.res.TypedArray import android.graphics.drawable.Drawable import android.util.AttributeSet import android.util.TypedValue import android.widget.ImageView import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext class FavoriteButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.MirkoButtonStyle ) : ImageView(context, attrs, defStyleAttr) { var favoriteDrawable: Drawable var favoriteOutlineDrawable: Drawable var typedArray: TypedArray var isFavorite: Boolean get() = isSelected set(value) { if (value) { isSelected = true setImageDrawable(favoriteDrawable) } else { isSelected = false setImageDrawable(favoriteOutlineDrawable) } } init { val typedValue = TypedValue() getActivityContext()!!.theme?.resolveAttribute(R.attr.buttonStatelist, typedValue, true) setBackgroundResource(typedValue.resourceId) typedArray = context.obtainStyledAttributes( arrayOf( R.attr.favoriteDrawable ).toIntArray() ) favoriteDrawable = typedArray.getDrawable(0)!! typedArray.recycle() typedArray = context.obtainStyledAttributes(arrayOf(R.attr.favoriteOutlineDrawable).toIntArray()) favoriteOutlineDrawable = typedArray.getDrawable(0)!! typedArray.recycle() } }
mit
a75c0740ee01583971bac7f45f84309c
33.416667
105
0.690491
5.308682
false
false
false
false
jwren/intellij-community
plugins/ide-features-trainer/src/training/ui/FeaturesTrainerSettingsPanel.kt
3
2335
// 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 training.ui import com.intellij.ide.util.PropertiesComponent import com.intellij.lang.Language import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.layout.* import training.lang.LangManager import training.learn.CourseManager import training.learn.LearnBundle import training.statistic.StatisticBase import training.util.SHOW_NEW_LESSONS_NOTIFICATION import training.util.getActionById import training.util.resetPrimaryLanguage import javax.swing.DefaultComboBoxModel private class FeaturesTrainerSettingsPanel : BoundConfigurable(LearnBundle.message("learn.options.panel.name"), null) { override fun createPanel(): DialogPanel = panel { val languagesExtensions = LangManager.getInstance().supportedLanguagesExtensions.sortedBy { it.language } if (languagesExtensions.isNotEmpty()) { row { label(LearnBundle.message("learn.option.main.language")) val options = languagesExtensions.mapNotNull { Language.findLanguageByID(it.language) } .map { LanguageOption(it) }.toTypedArray() comboBox<LanguageOption>(DefaultComboBoxModel(options), { val languageName = LangManager.getInstance().state.languageName options.find { it.id == languageName } ?: options[0] }, { language -> resetPrimaryLanguage(languagesExtensions.first { it.language == language?.id }.instance) } ) } } row { buttonFromAction(LearnBundle.message("learn.option.reset.progress"), "settings", getActionById("ResetLearningProgressAction")) } row { checkBox(LearnBundle.message("settings.checkbox.show.notifications.new.lessons"), { PropertiesComponent.getInstance().getBoolean(SHOW_NEW_LESSONS_NOTIFICATION, true) }, { StatisticBase.logShowNewLessonsNotificationState(-1, CourseManager.instance.previousOpenedVersion, it) PropertiesComponent.getInstance().setValue(SHOW_NEW_LESSONS_NOTIFICATION, it, true) }) } } private data class LanguageOption(val language: Language) { override fun toString(): String = language.displayName val id get() = language.id } }
apache-2.0
506e85a31245e29364e1d70d6599e5dc
44.784314
140
0.743897
4.707661
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/entity/AlLogEntry.kt
1
638
package alraune.entity import alraune.* import aplight.GelFill import vgrechka.* @GelFill @LightEntity(table = "AlLogEntry") class AlLogEntry : LightEntityBase() { var dataPile by notNull<AlLogEntryDataPile>() object Meta } class AlLogEntryDataPile { var level by notNull<AlLog.Level>() var message by notNull<String>() var throwableStackTrace: String? = null var tags = listOf<String>() var incidentCode: String? = null } // TODO:vgrechka Generate this shit val AlLogEntry.Meta.table get() = "AlLogEntry" val AlLogEntry.Meta.id get() = "id" val AlLogEntry.Meta.dataPile get() = AlLogEntry::dataPile.name
apache-2.0
1708476bc74d0f97d11bc24922bb077e
23.538462
62
0.730408
3.820359
false
false
false
false
square/okhttp
okhttp/src/jvmTest/java/okhttp3/internal/tls/HostnameVerifierTest.kt
2
40098
/* * 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 okhttp3.internal.tls import java.io.ByteArrayInputStream import java.security.cert.CertificateFactory import java.security.cert.X509Certificate import java.util.stream.Stream import javax.net.ssl.SSLSession import javax.security.auth.x500.X500Principal import okhttp3.FakeSSLSession import okhttp3.OkHttpClient import okhttp3.internal.canParseAsIpAddress import okhttp3.internal.platform.Platform.Companion.isAndroid import okhttp3.testing.PlatformRule import okhttp3.tls.HeldCertificate import okhttp3.tls.internal.TlsUtil.localhost import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension /** * Tests for our hostname verifier. Most of these tests are from AOSP, which itself includes tests * from the Apache HTTP Client test suite. */ class HostnameVerifierTest { private val verifier = OkHostnameVerifier @RegisterExtension var platform = PlatformRule() @Test fun verify() { val session = FakeSSLSession() assertThat(verifier.verify("localhost", session)).isFalse } @Test fun verifyCn() { // CN=foo.com val session = session( """ -----BEGIN CERTIFICATE----- MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8 BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQC3jRmEya6sQCkmieULcvx8zz1euCk9 fSez7BEtki8+dmfMXe3K7sH0lI8f4jJR0rbSCjpmCQLYmzC3NxBKeJOW0RcjNBpO c2JlGO9auXv2GDP4IYiXElLJ6VSqc8WvDikv0JmCCWm0Zga+bZbR/EWN5DeEtFdF 815CLpJZNcYwiYwGy/CVQ7w2TnXlG+mraZOz+owr+cL6J/ZesbdEWfjoS1+cUEhE HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse } @Test fun verifyNonAsciiCn() { // CN=&#x82b1;&#x5b50;.co.jp val session = session( """ -----BEGIN CERTIFICATE----- MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0 IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t 7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD qUYxqJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwG CWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV HQ4EFgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLS rNuzA1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBALJ27i3okV/KvlDp6KMID3gd ITl68PyItzzx+SquF8gahMh016NX73z/oVZoVUNdftla8wPUB1GwIkAnGkhQ9LHK spBdbRiCj0gMmLCsX8SrjFvr7cYb2cK6J/fJe92l1tg/7Y4o7V/s4JBe/cy9U9w8 a0ctuDmEBCgC784JMDtT67klRfr/2LlqWhlOEq7pUFxRLbhpquaAHSOjmIcWnVpw 9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA= -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("\u82b1\u5b50.co.jp", session)).isFalse assertThat(verifier.verify("a.\u82b1\u5b50.co.jp", session)).isFalse } @Test fun verifySubjectAlt() { // CN=foo.com, subjectAlt=bar.com val session = session( """ -----BEGIN CERTIFICATE----- MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8 BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCG SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz A1LKh6YNPg0wEgYDVR0RBAswCYIHYmFyLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA dQyprNZBmVnvuVWjV42sey/PTfkYShJwy1j0/jcFZR/ypZUovpiHGDO1DgL3Y3IP zVQ26uhUsSw6G0gGRiaBDe/0LUclXZoJzXX1qpS55OadxW73brziS0sxRgGrZE/d 3g5kkio6IED47OP6wYnlmZ7EKP9cqjWwlnvHnnUcZ2SscoLNYs9rN9ccp8tuq2by 88OyhKwGjJfhOudqfTNZcDzRHx4Fzm7UsVaycVw4uDmhEHJrAsmMPpj/+XRK9/42 2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr VbWx/uETImUu+NZg22ewEw== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isTrue assertThat(verifier.verify("a.bar.com", session)).isFalse } /** * Ignored due to incompatibilities between Android and Java on how non-ASCII subject alt names * are parsed. Android fails to parse these, which means we fall back to the CN. The RI does parse * them, so the CN is unused. */ @Test fun verifyNonAsciiSubjectAlt() { // Expecting actual: // ["bar.com", "花子.co.jp"] // to contain exactly (and in same order): // ["bar.com", "������.co.jp"] platform.assumeNotBouncyCastle() // CN=foo.com, subjectAlt=bar.com, subjectAlt=&#x82b1;&#x5b50;.co.jp // (hanako.co.jp in kanji) val session = session( """ -----BEGIN CERTIFICATE----- MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8 BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBnjCBmzAJBgNVHRMEAjAAMCwGCWCG SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz A1LKh6YNPg0wIAYDVR0RBBkwF4IHYmFyLmNvbYIM6Iqx5a2QLmNvLmpwMA0GCSqG SIb3DQEBBQUAA4IBAQBeZs7ZIYyKtdnVxVvdLgwySEPOE4pBSXii7XYv0Q9QUvG/ ++gFGQh89HhABzA1mVUjH5dJTQqSLFvRfqTHqLpxSxSWqMHnvRM4cPBkIRp/XlMK PlXadYtJLPTgpbgvulA1ickC9EwlNYWnowZ4uxnfsMghW4HskBqaV+PnQ8Zvy3L0 12c7Cg4mKKS5pb1HdRuiD2opZ+Hc77gRQLvtWNS8jQvd/iTbh6fuvTKfAOFoXw22 sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+ -----END CERTIFICATE----- """.trimIndent() ) val peerCertificate = session.peerCertificates[0] as X509Certificate if (isAndroid || platform.isConscrypt()) { assertThat(certificateSANs(peerCertificate)).containsExactly("bar.com") } else { assertThat(certificateSANs(peerCertificate)).containsExactly("bar.com", "������.co.jp") } assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse // these checks test alternative subjects. The test data contains an // alternative subject starting with a japanese kanji character. This is // not supported by Android because the underlying implementation from // harmony follows the definition from rfc 1034 page 10 for alternative // subject names. This causes the code to drop all alternative subjects. assertThat(verifier.verify("bar.com", session)).isTrue assertThat(verifier.verify("a.bar.com", session)).isFalse assertThat(verifier.verify("a.\u82b1\u5b50.co.jp", session)).isFalse } @Test fun verifySubjectAltOnly() { // subjectAlt=foo.com val session = session( """ -----BEGIN CERTIFICATE----- MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0 IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8 ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5 5c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86tso4gkJIFiza 0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0wEgYDVR0RBAsw CYIHZm9vLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEAjl78oMjzFdsMy6F1sGg/IkO8 tF5yUgPgFYrs41yzAca7IQu6G9qtFDJz/7ehh/9HoG+oqCCIHPuIOmS7Sd0wnkyJ Y7Y04jVXIb3a6f6AgBkEFP1nOT0z6kjT7vkA5LJ2y3MiDcXuRNMSta5PYVnrX8aZ yiqVUNi40peuZ2R8mAUSBvWgD7z2qWhF8YgDb7wWaFjg53I36vWKn90ZEti3wNCw qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isTrue assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("foo.com", session)).isTrue assertThat(verifier.verify("a.foo.com", session)).isFalse } @Test fun verifyMultipleCn() { // CN=foo.com, CN=bar.com, CN=&#x82b1;&#x5b50;.co.jp val session = session( """ -----BEGIN CERTIFICATE----- MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0 IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB TcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYxqJUlPGlMqrKb 3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQf Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86 tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0w DQYJKoZIhvcNAQEFBQADggEBAGuZb8ai1NO2j4v3y9TLZvd5s0vh5/TE7n7RX+8U y37OL5k7x9nt0mM1TyAKxlCcY+9h6frue8MemZIILSIvMrtzccqNz0V1WKgA+Orf uUrabmn+CxHF5gpy6g1Qs2IjVYWA5f7FROn/J+Ad8gJYc1azOWCLQqSyfpNRLSvY EriQFEV63XvkJ8JrG62b+2OT2lqT4OO07gSPetppdlSa8NBSKP6Aro9RIX1ZjUZQ SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE= -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("a.bar.com", session)).isFalse assertThat(verifier.verify("\u82b1\u5b50.co.jp", session)).isFalse assertThat(verifier.verify("a.\u82b1\u5b50.co.jp", session)).isFalse } @Test fun verifyWilcardCn() { // CN=*.foo.com val session = session( """ -----BEGIN CERTIFICATE----- MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0 ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1 JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6 q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCG SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz A1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBAH0ipG6J561UKUfgkeW7GvYwW98B N1ZooWX+JEEZK7+Pf/96d3Ij0rw9ACfN4bpfnCq0VUNZVSYB+GthQ2zYuz7tf/UY A6nxVgR/IjG69BmsBl92uFO7JTNtHztuiPqBn59pt+vNx4yPvno7zmxsfI7jv0ww yfs+0FNm7FwdsC1k47GBSOaGw38kuIVWqXSAbL4EX9GkryGGOKGNh0qvAENCdRSB G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc= -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("www.foo.com", session)).isFalse assertThat(verifier.verify("\u82b1\u5b50.foo.com", session)).isFalse assertThat(verifier.verify("a.b.foo.com", session)).isFalse } @Test fun verifyWilcardCnOnTld() { // It's the CA's responsibility to not issue broad-matching certificates! // CN=*.co.jp val session = session( """ -----BEGIN CERTIFICATE----- MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8 BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQA0sWglVlMx2zNGvUqFC73XtREwii53 CfMM6mtf2+f3k/d8KXhLNySrg8RRlN11zgmpPaLtbdTLrmG4UdAHHYr8O4y2BBmE 1cxNfGxxechgF8HX10QV4dkyzp6Z1cfwvCeMrT5G/V1pejago0ayXx+GPLbWlNeZ S+Kl0m3p+QplXujtwG5fYcIpaGpiYraBLx3Tadih39QN65CnAh/zRDhLCUzKyt9l UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.co.jp", session)).isFalse assertThat(verifier.verify("\u82b1\u5b50.co.jp", session)).isFalse } /** * Previously ignored due to incompatibilities between Android and Java on how non-ASCII subject * alt names are parsed. Android fails to parse these, which means we fall back to the CN. * The RI does parse them, so the CN is unused. */ @Test fun testWilcardNonAsciiSubjectAlt() { // Expecting actual: // ["*.bar.com", "*.花子.co.jp"] // to contain exactly (and in same order): // ["*.bar.com", "*.������.co.jp"] platform.assumeNotBouncyCastle() // CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.&#x82b1;&#x5b50;.co.jp // (*.hanako.co.jp in kanji) val session = session( """ -----BEGIN CERTIFICATE----- MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0 ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1 JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6 q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo4GiMIGfMAkGA1UdEwQCMAAwLAYJ YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud DgQWBBSfFHe/Pzq2yjiCQkgWLNrQy16H2DAfBgNVHSMEGDAWgBR7mtqPkJlOUtKs 27MDUsqHpg0+DTAkBgNVHREEHTAbggkqLmJhci5jb22CDiou6Iqx5a2QLmNvLmpw MA0GCSqGSIb3DQEBBQUAA4IBAQBobWC+D5/lx6YhX64CwZ26XLjxaE0S415ajbBq DK7lz+Rg7zOE3GsTAMi+ldUYnhyz0wDiXB8UwKXl0SDToB2Z4GOgqQjAqoMmrP0u WB6Y6dpkfd1qDRUzI120zPYgSdsXjHW9q2H77iV238hqIU7qCvEz+lfqqWEY504z hYNlknbUnR525ItosEVwXFBJTkZ3Yw8gg02c19yi8TAh5Li3Ad8XQmmSJMWBV4XK qFr0AIZKBlg6NZZFf/0dP9zcKhzSriW27bY0XfzA6GSiRDXrDjgXq6baRT6YwgIg pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3 -----END CERTIFICATE----- """.trimIndent() ) val peerCertificate = session.peerCertificates[0] as X509Certificate if (isAndroid || platform.isConscrypt()) { assertThat(certificateSANs(peerCertificate)).containsExactly("*.bar.com") } else { assertThat(certificateSANs(peerCertificate)) .containsExactly("*.bar.com", "*.������.co.jp") } // try the foo.com variations assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("www.foo.com", session)).isFalse assertThat(verifier.verify("\u82b1\u5b50.foo.com", session)).isFalse assertThat(verifier.verify("a.b.foo.com", session)).isFalse // these checks test alternative subjects. The test data contains an // alternative subject starting with a japanese kanji character. This is // not supported by Android because the underlying implementation from // harmony follows the definition from rfc 1034 page 10 for alternative // subject names. This causes the code to drop all alternative subjects. assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("www.bar.com", session)).isTrue assertThat(verifier.verify("\u82b1\u5b50.bar.com", session)).isFalse assertThat(verifier.verify("a.b.bar.com", session)).isFalse } @Test fun subjectAltUsesLocalDomainAndIp() { // cat cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:localhost.localdomain,DNS:localhost,IP:127.0.0.1 // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=localhost' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val certificate = certificate( """ -----BEGIN CERTIFICATE----- MIIBWDCCAQKgAwIBAgIJANS1EtICX2AZMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV BAMTCWxvY2FsaG9zdDAgFw0xMjAxMDIxOTA4NThaGA8yMTExMTIwOTE5MDg1OFow FDESMBAGA1UEAxMJbG9jYWxob3N0MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPpt atK8r4/hf4hSIs0os/BSlQLbRBaK9AfBReM4QdAklcQqe6CHsStKfI8pp0zs7Ptg PmMdpbttL0O7mUboBC8CAwEAAaM1MDMwMQYDVR0RBCowKIIVbG9jYWxob3N0Lmxv Y2FsZG9tYWlugglsb2NhbGhvc3SHBH8AAAEwDQYJKoZIhvcNAQEFBQADQQD0ntfL DCzOCv9Ma6Lv5o5jcYWVxvBSTsnt22hsJpWD1K7iY9lbkLwl0ivn73pG2evsAn9G X8YKH52fnHsCrhSD -----END CERTIFICATE----- """.trimIndent() ) assertThat(certificate.subjectX500Principal).isEqualTo( X500Principal("CN=localhost") ) val session = FakeSSLSession(certificate) assertThat(verifier.verify("localhost", session)).isTrue assertThat(verifier.verify("localhost.localdomain", session)).isTrue assertThat(verifier.verify("local.host", session)).isFalse assertThat(verifier.verify("127.0.0.1", session)).isTrue assertThat(verifier.verify("127.0.0.2", session)).isFalse } @Test fun wildcardsCannotMatchIpAddresses() { // openssl req -x509 -nodes -days 36500 -subj '/CN=*.0.0.1' -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBkjCCATygAwIBAgIJAMdemqOwd/BEMA0GCSqGSIb3DQEBBQUAMBIxEDAOBgNV BAMUByouMC4wLjEwIBcNMTAxMjIwMTY0NDI1WhgPMjExMDExMjYxNjQ0MjVaMBIx EDAOBgNVBAMUByouMC4wLjEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAqY8c9Qrt YPWCvb7lclI+aDHM6fgbJcHsS9Zg8nUOh5dWrS7AgeA25wyaokFl4plBbbHQe2j+ cCjsRiJIcQo9HwIDAQABo3MwcTAdBgNVHQ4EFgQUJ436TZPJvwCBKklZZqIvt1Yt JjEwQgYDVR0jBDswOYAUJ436TZPJvwCBKklZZqIvt1YtJjGhFqQUMBIxEDAOBgNV BAMUByouMC4wLjGCCQDHXpqjsHfwRDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEB BQUAA0EAk9i88xdjWoewqvE+iMC9tD2obMchgFDaHH0ogxxiRaIKeEly3g0uGxIt fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("127.0.0.1", session)).isFalse } /** * Earlier implementations of Android's hostname verifier required that wildcard names wouldn't * match "*.com" or similar. This was a nonstandard check that we've since dropped. It is the CA's * responsibility to not hand out certificates that match so broadly. */ @Test fun wildcardsDoesNotNeedTwoDots() { // openssl req -x509 -nodes -days 36500 -subj '/CN=*.com' -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBjDCCATagAwIBAgIJAOVulXCSu6HuMA0GCSqGSIb3DQEBBQUAMBAxDjAMBgNV BAMUBSouY29tMCAXDTEwMTIyMDE2NDkzOFoYDzIxMTAxMTI2MTY0OTM4WjAQMQ4w DAYDVQQDFAUqLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDJd8xqni+h7Iaz ypItivs9kPuiJUqVz+SuJ1C05SFc3PmlRCvwSIfhyD67fHcbMdl+A/LrIjhhKZJe 1joO0+pFAgMBAAGjcTBvMB0GA1UdDgQWBBS4Iuzf5w8JdCp+EtBfdFNudf6+YzBA BgNVHSMEOTA3gBS4Iuzf5w8JdCp+EtBfdFNudf6+Y6EUpBIwEDEOMAwGA1UEAxQF Ki5jb22CCQDlbpVwkruh7jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA0EA U6LFxmZr31lFyis2/T68PpjAppc0DpNQuA2m/Y7oTHBDi55Fw6HVHCw3lucuWZ5d qUYo4ES548JdpQtcLrW2sA== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("google.com", session)).isFalse } @Test fun subjectAltName() { // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:bar.com,DNS:baz.com // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBPTCB6KADAgECAgkA7zoHaaqNGHQwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE AxMHZm9vLmNvbTAgFw0xMDEyMjAxODM5MzZaGA8yMTEwMTEyNjE4MzkzNlowEjEQ MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC+gmoSxF+8 hbV+rgRQqHIJd50216OWQJbU3BvdlPbca779NYO4+UZWTFdBM8BdQqs3H4B5Agvp y7HeSff1F7XRAgMBAAGjHzAdMBsGA1UdEQQUMBKCB2Jhci5jb22CB2Jhei5jb20w DQYJKoZIhvcNAQEFBQADQQBXpZZPOY2Dy1lGG81JTr8L4or9jpKacD7n51eS8iqI oTznPNuXHU5bFN0AAGX2ij47f/EahqTpo5RdS95P4sVm -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isTrue assertThat(verifier.verify("baz.com", session)).isTrue assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("quux.com", session)).isFalse } @Test fun subjectAltNameWithWildcard() { // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:bar.com,DNS:*.baz.com // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBPzCB6qADAgECAgkAnv/7Jv5r7pMwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE AxMHZm9vLmNvbTAgFw0xMDEyMjAxODQ2MDFaGA8yMTEwMTEyNjE4NDYwMVowEjEQ MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDAz2YXnyog YdYLSFr/OEgSumtwqtZKJTB4wqTW/eKbBCEzxnyUMxWZIqUGu353PzwfOuWp2re3 nvVV+QDYQlh9AgMBAAGjITAfMB0GA1UdEQQWMBSCB2Jhci5jb22CCSouYmF6LmNv bTANBgkqhkiG9w0BAQUFAANBAB8yrSl8zqy07i0SNYx2B/FnvQY734pxioaqFWfO Bqo1ZZl/9aPHEWIwBrxYNVB0SGu/kkbt/vxqOjzzrkXukmI= -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isTrue assertThat(verifier.verify("a.baz.com", session)).isTrue assertThat(verifier.verify("baz.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("a.bar.com", session)).isFalse assertThat(verifier.verify("quux.com", session)).isFalse } @Test fun subjectAltNameWithIPAddresses() { // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=IP:0:0:0:0:0:0:0:1,IP:2a03:2880:f003:c07:face:b00c::2,IP:0::5,IP:192.168.1.1 // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBaDCCARKgAwIBAgIJALxN+AOBVGwQMA0GCSqGSIb3DQEBCwUAMBIxEDAOBgNV BAMMB2Zvby5jb20wIBcNMjAwMzIyMTEwNDI4WhgPMjEyMDAyMjcxMTA0MjhaMBIx EDAOBgNVBAMMB2Zvby5jb20wXDANBgkqhkiG9w0BAQEFAANLADBIAkEAlnVbVfQ9 4aYjrPCcFuxOpjXuvyOc9Hcha4K7TfXyfsrjhAvCjCBIT/TiLOUVF3sx4yoCAtX8 wmt404tTbKD6UwIDAQABo0kwRzBFBgNVHREEPjA8hxAAAAAAAAAAAAAAAAAAAAAB hxAqAyiA8AMMB/rOsAwAAAAChxAAAAAAAAAAAAAAAAAAAAAFhwTAqAEBMA0GCSqG SIb3DQEBCwUAA0EAPSOYHJh7hB4ElBqTCAFW+T5Y7mXsv9nQjBJ7w0YIw83V2PEI 3KbBIyGTrqHD6lG8QGZy+yNkIcRlodG8OfQRUg== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("::1", session)).isTrue assertThat(verifier.verify("::2", session)).isFalse assertThat(verifier.verify("::5", session)).isTrue assertThat(verifier.verify("2a03:2880:f003:c07:face:b00c::2", session)).isTrue assertThat(verifier.verify("2a03:2880:f003:c07:face:b00c:0:2", session)).isTrue assertThat(verifier.verify("2a03:2880:f003:c07:FACE:B00C:0:2", session)).isTrue assertThat(verifier.verify("2a03:2880:f003:c07:face:b00c:0:3", session)).isFalse assertThat(verifier.verify("127.0.0.1", session)).isFalse assertThat(verifier.verify("192.168.1.1", session)).isTrue assertThat(verifier.verify("::ffff:192.168.1.1", session)).isTrue assertThat(verifier.verify("0:0:0:0:0:FFFF:C0A8:0101", session)).isTrue } @Test fun generatedCertificate() { val heldCertificate = HeldCertificate.Builder() .commonName("Foo Corp") .addSubjectAlternativeName("foo.com") .build() val session = session(heldCertificate.certificatePem()) assertThat(verifier.verify("foo.com", session)).isTrue assertThat(verifier.verify("bar.com", session)).isFalse } @Test fun specialKInHostname() { // https://github.com/apache/httpcomponents-client/commit/303e435d7949652ea77a6c50df1c548682476b6e // https://www.gosecure.net/blog/2020/10/27/weakness-in-java-tls-host-verification/ val heldCertificate = HeldCertificate.Builder() .commonName("Foo Corp") .addSubjectAlternativeName("k.com") .addSubjectAlternativeName("tel.com") .build() val session = session(heldCertificate.certificatePem()) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isTrue assertThat(verifier.verify("K.com", session)).isTrue assertThat(verifier.verify("\u2121.com", session)).isFalse assertThat(verifier.verify("℡.com", session)).isFalse // These should ideally be false, but we know that hostname is usually already checked by us assertThat(verifier.verify("\u212A.com", session)).isFalse // Kelvin character below assertThat(verifier.verify("K.com", session)).isFalse } @Test fun specialKInCert() { // https://github.com/apache/httpcomponents-client/commit/303e435d7949652ea77a6c50df1c548682476b6e // https://www.gosecure.net/blog/2020/10/27/weakness-in-java-tls-host-verification/ val heldCertificate = HeldCertificate.Builder() .commonName("Foo Corp") .addSubjectAlternativeName("\u2121.com") .addSubjectAlternativeName("\u212A.com") .build() val session = session(heldCertificate.certificatePem()) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isFalse assertThat(verifier.verify("K.com", session)).isFalse assertThat(verifier.verify("tel.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isFalse } @Test fun specialKInExternalCert() { // OpenJDK related test. platform.assumeNotConscrypt() // Expecting actual: // ["℡.com", "K.com"] // to contain exactly (and in same order): // ["���.com", "���.com"] platform.assumeNotBouncyCastle() // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:℡.com,DNS:K.com // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBSDCB86ADAgECAhRLR4TGgXBegg0np90FZ1KPeWpDtjANBgkqhkiG9w0BAQsF ADASMRAwDgYDVQQDDAdmb28uY29tMCAXDTIwMTAyOTA2NTkwNVoYDzIxMjAxMDA1 MDY1OTA1WjASMRAwDgYDVQQDDAdmb28uY29tMFwwDQYJKoZIhvcNAQEBBQADSwAw SAJBALQcTVW9aW++ClIV9/9iSzijsPvQGEu/FQOjIycSrSIheZyZmR8bluSNBq0C 9fpalRKZb0S2tlCTi5WoX8d3K30CAwEAAaMfMB0wGwYDVR0RBBQwEoIH4oShLmNv bYIH4oSqLmNvbTANBgkqhkiG9w0BAQsFAANBAA1+/eDvSUGv78iEjNW+1w3OPAwt Ij1qLQ/YI8OogZPMk7YY46/ydWWp7UpD47zy/vKmm4pOc8Glc8MoDD6UADs= -----END CERTIFICATE----- """.trimIndent() ) val peerCertificate = session.peerCertificates[0] as X509Certificate if (isAndroid) { assertThat(certificateSANs(peerCertificate)).containsExactly() } else { assertThat(certificateSANs(peerCertificate)).containsExactly("���.com", "���.com") } assertThat(verifier.verify("tel.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isFalse assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isFalse assertThat(verifier.verify("K.com", session)).isFalse } private fun certificateSANs(peerCertificate: X509Certificate): Stream<String> { val subjectAlternativeNames = peerCertificate.subjectAlternativeNames return if (subjectAlternativeNames == null) { Stream.empty() } else { subjectAlternativeNames.stream().map { c: List<*> -> c[1] as String } } } @Test fun replacementCharacter() { // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:℡.com,DNS:K.com // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBSDCB86ADAgECAhRLR4TGgXBegg0np90FZ1KPeWpDtjANBgkqhkiG9w0BAQsF ADASMRAwDgYDVQQDDAdmb28uY29tMCAXDTIwMTAyOTA2NTkwNVoYDzIxMjAxMDA1 MDY1OTA1WjASMRAwDgYDVQQDDAdmb28uY29tMFwwDQYJKoZIhvcNAQEBBQADSwAw SAJBALQcTVW9aW++ClIV9/9iSzijsPvQGEu/FQOjIycSrSIheZyZmR8bluSNBq0C 9fpalRKZb0S2tlCTi5WoX8d3K30CAwEAAaMfMB0wGwYDVR0RBBQwEoIH4oShLmNv bYIH4oSqLmNvbTANBgkqhkiG9w0BAQsFAANBAA1+/eDvSUGv78iEjNW+1w3OPAwt Ij1qLQ/YI8OogZPMk7YY46/ydWWp7UpD47zy/vKmm4pOc8Glc8MoDD6UADs= -----END CERTIFICATE----- """.trimIndent() ) // Replacement characters are deliberate, from certificate loading. assertThat(verifier.verify("���.com", session)).isFalse assertThat(verifier.verify("℡.com", session)).isFalse } @Test fun thatCatchesErrorsWithBadSession() { val localVerifier = OkHttpClient().hostnameVerifier // Since this is public API, okhttp3.internal.tls.OkHostnameVerifier.verify is also assertThat(verifier).isInstanceOf(OkHostnameVerifier::class.java) val session = localhost().sslContext().createSSLEngine().session assertThat(localVerifier.verify("\uD83D\uDCA9.com", session)).isFalse } @Test fun verifyAsIpAddress() { // IPv4 assertThat("127.0.0.1".canParseAsIpAddress()).isTrue assertThat("1.2.3.4".canParseAsIpAddress()).isTrue // IPv6 assertThat("::1".canParseAsIpAddress()).isTrue assertThat("2001:db8::1".canParseAsIpAddress()).isTrue assertThat("::192.168.0.1".canParseAsIpAddress()).isTrue assertThat("::ffff:192.168.0.1".canParseAsIpAddress()).isTrue assertThat("FEDC:BA98:7654:3210:FEDC:BA98:7654:3210".canParseAsIpAddress()).isTrue assertThat("1080:0:0:0:8:800:200C:417A".canParseAsIpAddress()).isTrue assertThat("1080::8:800:200C:417A".canParseAsIpAddress()).isTrue assertThat("FF01::101".canParseAsIpAddress()).isTrue assertThat("0:0:0:0:0:0:13.1.68.3".canParseAsIpAddress()).isTrue assertThat("0:0:0:0:0:FFFF:129.144.52.38".canParseAsIpAddress()).isTrue assertThat("::13.1.68.3".canParseAsIpAddress()).isTrue assertThat("::FFFF:129.144.52.38".canParseAsIpAddress()).isTrue // Hostnames assertThat("go".canParseAsIpAddress()).isFalse assertThat("localhost".canParseAsIpAddress()).isFalse assertThat("squareup.com".canParseAsIpAddress()).isFalse assertThat("www.nintendo.co.jp".canParseAsIpAddress()).isFalse } private fun certificate(certificate: String): X509Certificate { return CertificateFactory.getInstance("X.509") .generateCertificate(ByteArrayInputStream(certificate.toByteArray())) as X509Certificate } private fun session(certificate: String): SSLSession = FakeSSLSession(certificate(certificate)) }
apache-2.0
7209a762dff3c057498c11b7c7a03593
48.065031
102
0.775533
3.039295
false
false
false
false
kotlinx/kotlinx.html
src/jvmMain/kotlin/dom-jvm.kt
1
6435
package kotlinx.html.dom import kotlinx.html.* import kotlinx.html.consumers.* import org.w3c.dom.* import org.w3c.dom.events.* import org.xml.sax.* import java.io.* import java.util.* import javax.xml.parsers.* import javax.xml.transform.* import javax.xml.transform.dom.* import javax.xml.transform.stream.* class HTMLDOMBuilder(val document : Document) : TagConsumer<Element> { private val path = arrayListOf<Element>() private var lastLeaved : Element? = null private val documentBuilder: DocumentBuilder by lazy { DocumentBuilderFactory.newInstance().newDocumentBuilder() } override fun onTagStart(tag: Tag) { val element = when { tag.namespace != null -> document.createElementNS(tag.namespace!!, tag.tagName) else -> document.createElement(tag.tagName) } tag.attributesEntries.forEach { element.setAttribute(it.key, it.value) } if (path.isNotEmpty()) { path.last().appendChild(element) } path.add(element) } override fun onTagAttributeChange(tag: Tag, attribute: String, value: String?) { if (path.isEmpty()) { throw IllegalStateException("No current tag") } path.last().let { node -> if (value == null) { node.removeAttribute(attribute) } else { node.setAttribute(attribute, value) } } } override fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit) { throw UnsupportedOperationException("You can't assign lambda event handler on JVM") } override fun onTagEnd(tag: Tag) { if (path.isEmpty() || path.last().tagName.toLowerCase() != tag.tagName.toLowerCase()) { throw IllegalStateException("We haven't entered tag ${tag.tagName} but trying to leave") } val element = path.removeAt(path.lastIndex) element.setIdAttributeName() lastLeaved = element } override fun onTagContent(content: CharSequence) { if (path.isEmpty()) { throw IllegalStateException("No current DOM node") } path.last().appendChild(document.createTextNode(content.toString())) } override fun onTagComment(content: CharSequence) { if (path.isEmpty()) { throw IllegalStateException("No current DOM node") } path.last().appendChild(document.createComment(content.toString())) } override fun onTagContentEntity(entity: Entities) { if (path.isEmpty()) { throw IllegalStateException("No current DOM node") } path.last().appendChild(document.createEntityReference(entity.name)) } override fun finalize() = lastLeaved ?: throw IllegalStateException("No tags were emitted") override fun onTagContentUnsafe(block: Unsafe.() -> Unit) { UnsafeImpl.block() } private val UnsafeImpl = object : Unsafe { override operator fun String.unaryPlus() { val element = documentBuilder .parse(InputSource(StringReader("<unsafeRoot>" + this + "</unsafeRoot>"))) .documentElement val importNode = document.importNode(element, true) check(importNode.nodeName == "unsafeRoot") { "the document factory hasn't created an unsafeRoot node"} val last = path.last() while (importNode.hasChildNodes()) { last.appendChild(importNode.removeChild(importNode.firstChild)) } } } private fun Element.setIdAttributeName() { if (hasAttribute("id")) { setIdAttribute("id", true) } } } fun Document.createHTMLTree() : TagConsumer<Element> = HTMLDOMBuilder(this) val Document.create : TagConsumer<Element> get() = HTMLDOMBuilder(this) fun Node.append(block : TagConsumer<Element>.() -> Unit) : List<Element> = ArrayList<Element>().let { result -> ownerDocumentExt.createHTMLTree().onFinalize { it, partial -> if (!partial) { appendChild(it); result.add(it) } }.block() result } fun Node.prepend(block: TagConsumer<Element>.() -> Unit) : List<Element> = ArrayList<Element>().let { result -> ownerDocumentExt.createHTMLTree().onFinalize { it, partial -> if (!partial) { insertBefore(it, firstChild) result.add(it) } }.block() result } val Node.append: TagConsumer<Element> get() = ownerDocumentExt.createHTMLTree().onFinalize { it, partial -> if (!partial) { appendChild(it) } } val Node.prepend: TagConsumer<Element> get() = ownerDocumentExt.createHTMLTree().onFinalize { it, partial -> if (!partial) { insertBefore(it, firstChild) }} private val Node.ownerDocumentExt: Document get() = when { this is Document -> this else -> ownerDocument ?: throw IllegalArgumentException("node has no ownerDocument") } fun createHTMLDocument() : TagConsumer<Document> = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument().let { document -> HTMLDOMBuilder(document).onFinalizeMap { it, partial -> if (!partial) {document.appendChild(it)}; document } } inline fun document(block : Document.() -> Unit) : Document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument().let { document -> document.block() document } fun Writer.write(document : Document, prettyPrint : Boolean = true) : Writer { write("<!DOCTYPE html>\n") write(document.documentElement, prettyPrint) return this } fun Writer.write(element: Element, prettyPrint : Boolean = true) : Writer { val transformer = TransformerFactory.newInstance().newTransformer() transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes") transformer.setOutputProperty(OutputKeys.METHOD, "html") transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") if (prettyPrint) { transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2") transformer.setOutputProperty(OutputKeys.INDENT, "yes") } transformer.transform(DOMSource(element), StreamResult(this)) return this } fun Element.serialize(prettyPrint : Boolean = true) : String = StringWriter().write(this, prettyPrint).toString() fun Document.serialize(prettyPrint : Boolean = true) : String = StringWriter().write(this, prettyPrint).toString()
apache-2.0
205bb06968774fae92829d3f2428fc4b
33.05291
151
0.653768
4.589872
false
false
false
false
fvasco/pinpoi
app/src/main/java/io/github/fvasco/pinpoi/util/BackupManager.kt
1
3233
package io.github.fvasco.pinpoi.util import android.util.Log import io.github.fvasco.pinpoi.dao.AbstractDao import java.io.* import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream /** * Create and restore backup * @author Francesco Vasco */ class BackupManager(private vararg val daos: AbstractDao) { @Throws(IOException::class) fun create(outputStream: OutputStream) { Log.i(BackupManager::class.java.simpleName, "Create backup $outputStream") ZipOutputStream(outputStream).use { zipOutputStream -> for (dao in daos) { synchronized(dao) { val databaseFile: File dao.open() val database = dao.database!! try { databaseFile = File(database.path) } finally { database.close() dao.close() } val zipEntry = ZipEntry(databaseFile.name) zipOutputStream.putNextEntry(zipEntry) val databaseInputStream = FileInputStream(databaseFile) try { dao.lock() databaseInputStream.copyTo(zipOutputStream) } finally { try { databaseInputStream.close() } finally { dao.reset() } } zipOutputStream.closeEntry() } } } } @Throws(IOException::class) fun restore(fileInputStream: InputStream) { Log.i(BackupManager::class.java.simpleName, "Restore backup $fileInputStream") ZipInputStream(fileInputStream).use { zipInputStream -> var zipEntry = zipInputStream.nextEntry while (zipEntry != null) { for (dao in daos) { synchronized(dao) { val databasePath: File dao.open() val database = dao.database!! try { databasePath = File(database.path) } finally { database.close() dao.close() } val databaseName = databasePath.name if (databaseName == zipEntry.name) { try { Log.i(BackupManager::class.java.simpleName, "restore database $databaseName") FileOutputStream(databasePath).use { databaseOutputStream -> dao.lock() ZipGuardInputStream(zipInputStream).copyTo(databaseOutputStream) } } finally { dao.reset() } } } } zipEntry = zipInputStream.nextEntry } } } }
gpl-3.0
f91bf7caddd9a0795fe554efb5264cf5
36.593023
109
0.450974
6.314453
false
false
false
false
GunoH/intellij-community
platform/feedback/src/com/intellij/feedback/new_ui/state/NewUIInfoService.kt
2
1662
// 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.feedback.new_ui.state import com.intellij.openapi.components.* import com.intellij.openapi.util.registry.Registry import kotlinx.datetime.Clock import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime import kotlinx.serialization.Serializable @Service(Service.Level.APP) @State(name = "NewUIInfoState", storages = [Storage(StoragePathMacros.NON_ROAMABLE_FILE, deprecated = true), Storage("NewUIInfoService.xml")]) class NewUIInfoService : PersistentStateComponent<NewUIInfoState> { companion object { @JvmStatic fun getInstance(): NewUIInfoService = service() } private var state = NewUIInfoState() override fun getState(): NewUIInfoState = state override fun loadState(state: NewUIInfoState) { this.state = state } fun updateEnableNewUIDate() { if (state.enableNewUIDate == null) { state.enableNewUIDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) } } fun updateDisableNewUIDate() { if (state.disableNewUIDate == null) { state.disableNewUIDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) } } } @Serializable data class NewUIInfoState( var numberNotificationShowed: Int = 0, var feedbackSent: Boolean = false, var enableNewUIDate: LocalDateTime? = if (Registry.get("ide.experimental.ui").asBoolean()) Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) else null, var disableNewUIDate: LocalDateTime? = null )
apache-2.0
11b47e31924ffdf7f85687e87ffeb92d
32.26
120
0.759928
4.328125
false
false
false
false
danielgindi/android-helpers
Helpers/src/main/java/com/dg/controls/ButtonEx.kt
1
1986
package com.dg.controls import android.content.Context import android.content.res.TypedArray import android.graphics.Paint import android.graphics.Typeface import android.util.AttributeSet import androidx.appcompat.widget.AppCompatButton import com.dg.R import com.dg.helpers.FontHelper @Suppress("unused") class ButtonEx : AppCompatButton { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setCustomFontFamily(context, attrs) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { setCustomFontFamily(context, attrs) } private fun setCustomFontFamily(context: Context, attrs: AttributeSet) { if (isInEditMode) { return } val fontFamily: String? var styledAttributes: TypedArray? = null try { styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.ButtonEx) fontFamily = styledAttributes!!.getString(R.styleable.ButtonEx_customFontFamily) } finally { styledAttributes?.recycle() } if (fontFamily != null && !fontFamily.isEmpty()) { paintFlags = this.paintFlags or Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG setCustomFont(fontFamily) } } @Deprecated("This version was a mistake", replaceWith = ReplaceWith("setCustomFont(fontFamily)")) fun setCustomFont(context: Context, fontFamily: String): Boolean { return setCustomFont(fontFamily) } fun setCustomFont(fontFamily: String): Boolean { val typeface: Typeface? = FontHelper.getFont(context, fontFamily) return if (typeface != null) { setTypeface(typeface) true } else { false } } }
mit
bcb29e70c181933eeab4f1617ed24e9c
25.837838
101
0.631923
4.977444
false
false
false
false
GunoH/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/storage/UniqueFilesProvider.kt
8
3607
// Copyright 2000-2022 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.stats.completion.storage import com.intellij.openapi.application.PathManager import java.io.File import java.io.FileFilter import java.nio.file.Files /** * If you want to implement some other type of logging this is a goto class to temporarily store data locally, until it * will be sent to log service. * * @baseFileName, files will be named ${baseFileName}_{intIndex} * @rootDirectoryPath, root directory where folder named @logsDirectory will be created and all files will be stored * @logsDirectoryName, name of directory in root directory which will be used to store files */ open class UniqueFilesProvider(private val baseFileName: String, private val rootDirectoryPath: String, private val logsDirectoryName: String, private val storageSizeLimit: Int = MAX_STORAGE_SEND_SIZE) : FilePathProvider { companion object { private const val MAX_STORAGE_SEND_SIZE = 30 * 1024 * 1024 fun extractChunkNumber(filename: String): Int? { return filename.substringAfter("_").substringBefore(".gz").toIntOrNull() } } override fun cleanupOldFiles() { val files = getDataFiles() val storageSize = files.fold(0L) { totalSize, file -> totalSize + file.length() } if (storageSize > storageSizeLimit) { var currentSize = storageSize val iterator = files.iterator() while (iterator.hasNext() && currentSize > storageSizeLimit) { val file = iterator.next() val fileSize = file.length() Files.delete(file.toPath()) currentSize -= fileSize } } } override fun getUniqueFile(): File { val dir = getStatsDataDirectory() val currentMaxIndex = listChunks().maxOfOrNull { it.number } val newIndex = if (currentMaxIndex != null) currentMaxIndex + 1 else 0 return File(dir, "${baseFileName}_$newIndex.gz") } override fun getDataFiles(): List<File> { return listChunks().map { it.file } } override fun getStatsDataDirectory(): File { val dir = File(rootDirectoryPath, logsDirectoryName) if (!dir.exists()) { dir.mkdirs() } return dir } private fun listChunks(): List<Chunk> { return getStatsDataDirectory().filesOnly().mapNotNull { it.asChunk() }.sortedBy { it.number }.toList() } private fun File.filesOnly(): Sequence<File> { val files: Array<out File>? = this.listFiles(FileFilter { it.isFile }) if (files == null) { val diagnostics = when { !exists() -> "file does not exist" !isDirectory -> "file is not a directory" isFile -> "file should be a directory but it is a file" else -> "unknown error" } throw Exception("Invalid directory path: ${this.relativeTo(File(PathManager.getSystemPath()))}. Info: $diagnostics") } return files.asSequence() } private fun File.asChunk(): Chunk? { if (!isFile) return null val filename = name if (!filename.startsWith(baseFileName)) return null val number = extractChunkNumber(filename) return if (number == null) null else Chunk(this, number) } private data class Chunk(val file: File, val number: Int) }
apache-2.0
571f2ee1bda9a0a13f87ae0e94f81ce3
36.978947
140
0.62351
4.802929
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/excludedFromImportsAndCompletion.kt
2
2027
// 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.core import com.intellij.codeInsight.JavaProjectCodeInsightSettings import com.intellij.openapi.project.Project import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.psi.KtFile private val exclusions = listOf( "kotlin.jvm.internal", "kotlin.coroutines.experimental.intrinsics", "kotlin.coroutines.intrinsics", "kotlin.coroutines.experimental.jvm.internal", "kotlin.coroutines.jvm.internal", "kotlin.reflect.jvm.internal" ) private fun shouldBeHiddenAsInternalImplementationDetail(fqName: String, locationFqName: String) = exclusions.any { fqName.startsWith(it) } && (locationFqName.isBlank() || !fqName.startsWith(locationFqName)) /** * We do not want to show nothing from "kotlin.coroutines.experimental" when release coroutines are available, * since in 1.3 this package is obsolete. * * However, we still want to show this package when release coroutines are not available. */ private fun usesOutdatedCoroutinesPackage(fqName: String, inFile: KtFile): Boolean = fqName.startsWith("kotlin.coroutines.experimental.") && inFile.languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines) fun DeclarationDescriptor.isExcludedFromAutoImport(project: Project, inFile: KtFile?): Boolean { val fqName = importableFqName?.asString() ?: return false return JavaProjectCodeInsightSettings.getSettings(project).isExcluded(fqName) || (inFile != null && usesOutdatedCoroutinesPackage(fqName, inFile)) || shouldBeHiddenAsInternalImplementationDetail(fqName, inFile?.packageFqName?.asString() ?: "") }
apache-2.0
a23b9e01b5a16df5bcc59600a3e37c3e
47.261905
158
0.77109
4.724942
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/create/GHPRTemplateLoader.kt
10
1496
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.toolwindow.create import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import java.nio.file.Files import java.nio.file.Paths import java.util.concurrent.CompletableFuture object GHPRTemplateLoader { private val LOG = logger<GHPRTemplateLoader>() private val paths = listOf( ".github/pull_request_template.md", "pull_request_template.md", "docs/pull_request_template.md" ) fun readTemplate(project: Project): CompletableFuture<String?> { return ProgressManager.getInstance().submitIOTask(EmptyProgressIndicator()) { doLoad(project) } } @RequiresBackgroundThread private fun doLoad(project: Project): String? { val basePath = project.basePath ?: return null try { val files = paths.map { Paths.get(basePath, it) } val fileContent = files.find(Files::exists)?.let(Files::readString) if (fileContent != null) return fileContent } catch (e: Exception) { LOG.warn("Failed to read PR template", e) } return null } }
apache-2.0
b0960f8c8f729ee9d0c02cfd25927ed5
33.813953
140
0.754011
4.311239
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesStatisticsCollector.kt
1
2322
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.find.findUsages import com.intellij.ide.util.scopeChooser.ScopeIdMapper import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.internal.statistic.eventLog.events.ObjectEventData import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project import com.intellij.usages.impl.UsageViewStatisticsCollector class FindUsagesStatisticsCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { @JvmField val GROUP = EventLogGroup("find.usages", 2) const val OPTIONS_EVENT_ID = "options" private val SEARCHABLE_SCOPE_EVENT_FIELD = EventFields.StringValidatedByCustomRule("searchScope", UsageViewStatisticsCollector.SCOPE_RULE_ID) private val SEARCH_FOR_TEXT_OCCURRENCES_FIELD = EventFields.Boolean("isSearchForTextOccurrences") private val IS_USAGES_FIELD = EventFields.Boolean("isUsages") private val ADDITIONAL = EventFields.createAdditionalDataField(GROUP.id, OPTIONS_EVENT_ID) private val OPEN_IN_NEW_TAB = EventFields.Boolean("openInNewTab") private val FIND_USAGES_OPTIONS = GROUP.registerVarargEvent(OPTIONS_EVENT_ID, SEARCH_FOR_TEXT_OCCURRENCES_FIELD, IS_USAGES_FIELD, OPEN_IN_NEW_TAB, SEARCHABLE_SCOPE_EVENT_FIELD, ADDITIONAL) @JvmStatic fun logOptions(project: Project, options: FindUsagesOptions, openInNewTab: Boolean) { val data: MutableList<EventPair<*>> = mutableListOf( SEARCH_FOR_TEXT_OCCURRENCES_FIELD.with(options.isSearchForTextOccurrences), IS_USAGES_FIELD.with(options.isUsages), OPEN_IN_NEW_TAB.with(openInNewTab), SEARCHABLE_SCOPE_EVENT_FIELD.with(ScopeIdMapper.instance.getScopeSerializationId(options.searchScope.displayName)), ) if (options is FusAwareFindUsagesOptions) { data.add(ADDITIONAL.with(ObjectEventData(options.additionalUsageData))) } FIND_USAGES_OPTIONS.log(project, *data.toTypedArray()) } } }
apache-2.0
8f819ee1954885e7e585ddc4749adbaf
44.54902
145
0.77304
4.439771
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/CreateExpectedFix.kt
2
12801
// 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.quickfix.expectactual import com.intellij.codeInsight.intention.IntentionAction import com.intellij.ide.util.MemberChooser import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.ui.showOkNoDialog import com.intellij.openapi.util.NlsSafe import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.project.implementedModules import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.overrideImplement.makeActual import org.jetbrains.kotlin.idea.core.overrideImplement.makeNotActual import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.core.util.DescriptorMemberChooserObject import org.jetbrains.kotlin.idea.quickfix.KotlinIntentionActionsFactory import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.liftToExpected import org.jetbrains.kotlin.idea.util.module import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.getSuperNames import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.utils.addToStdlib.safeAs sealed class CreateExpectedFix<D : KtNamedDeclaration>( declaration: D, targetExpectedClass: KtClassOrObject?, commonModule: Module, generateIt: KtPsiFactory.(Project, TypeAccessibilityChecker, D) -> D? ) : AbstractCreateDeclarationFix<D>(declaration, commonModule, generateIt) { private val targetExpectedClassPointer = targetExpectedClass?.createSmartPointer() override fun getText() = KotlinBundle.message("create.expected.0.in.common.module.1", elementType, module.name) final override fun invoke(project: Project, editor: Editor?, file: KtFile) { val targetExpectedClass = targetExpectedClassPointer?.element val expectedFile = targetExpectedClass?.containingKtFile ?: getOrCreateImplementationFile() ?: return doGenerate(project, editor, originalFile = file, targetFile = expectedFile, targetClass = targetExpectedClass) } override fun findExistingFileToCreateDeclaration( originalFile: KtFile, originalDeclaration: KtNamedDeclaration ): KtFile? { for (otherDeclaration in originalFile.declarations) { if (otherDeclaration === originalDeclaration) continue if (!otherDeclaration.hasActualModifier()) continue val expectedDeclaration = otherDeclaration.liftToExpected() ?: continue if (expectedDeclaration.module != module) continue return expectedDeclaration.containingKtFile } return null } companion object : KotlinIntentionActionsFactory() { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val d = DiagnosticFactory.cast(diagnostic, Errors.ACTUAL_WITHOUT_EXPECT) val declaration = d.psiElement as? KtNamedDeclaration ?: return emptyList() val compatibility = d.b // For function we allow it, because overloads are possible if (compatibility.isNotEmpty() && declaration !is KtFunction) return emptyList() val (actualDeclaration, expectedContainingClass) = findFirstActualWithExpectedClass(declaration) if (compatibility.isNotEmpty() && actualDeclaration !is KtFunction) return emptyList() // If there is already an expected class, we suggest only for its module, // otherwise we suggest for all relevant expected modules val expectedModules = expectedContainingClass?.module?.let { listOf(it) } ?: actualDeclaration.module?.implementedModules ?: return emptyList() return when (actualDeclaration) { is KtClassOrObject -> expectedModules.map { CreateExpectedClassFix(actualDeclaration, expectedContainingClass, it) } is KtProperty, is KtParameter, is KtFunction -> expectedModules.map { CreateExpectedCallableMemberFix( actualDeclaration as KtCallableDeclaration, expectedContainingClass, it ) } else -> emptyList() } } } } private tailrec fun findFirstActualWithExpectedClass(declaration: KtNamedDeclaration): Pair<KtNamedDeclaration, KtClassOrObject?> { val containingClass = declaration.containingClassOrObject val expectedContainingClass = containingClass?.liftToExpected() as? KtClassOrObject return if (containingClass != null && expectedContainingClass == null) findFirstActualWithExpectedClass(containingClass) else declaration to expectedContainingClass } class CreateExpectedClassFix( klass: KtClassOrObject, outerExpectedClass: KtClassOrObject?, commonModule: Module ) : CreateExpectedFix<KtClassOrObject>(klass, outerExpectedClass, commonModule, block@{ project, checker, element -> val originalElements = element.collectDeclarationsForAddActualModifier(withSelf = false).toList() val existingClasses = checker.findAndApplyExistingClasses(originalElements + klass) if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null val (members, declarationsWithNonExistentClasses) = originalElements.partition { checker.isCorrectAndHaveAccessibleModifiers(it) } if (!showUnknownTypeInDeclarationDialog(project, declarationsWithNonExistentClasses)) return@block null val membersForSelection = members.filter { !it.isAlwaysActual() && if (it is KtParameter) it.hasValOrVar() else true } val selectedElements = when { membersForSelection.all(KtDeclaration::hasActualModifier) -> membersForSelection isUnitTestMode() -> membersForSelection.filter(KtDeclaration::hasActualModifier) else -> { val prefix = klass.fqName?.asString()?.plus(".") ?: "" chooseMembers(project, membersForSelection, prefix) ?: return@block null } }.asSequence().plus(klass).plus(members.filter(KtNamedDeclaration::isAlwaysActual)).flatMap(KtNamedDeclaration::selected).toSet() val selectedClasses = checker.findAndApplyExistingClasses(selectedElements) val resultDeclarations = if (selectedClasses != existingClasses) { if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null val (resultDeclarations, withErrors) = selectedElements.partition { checker.isCorrectAndHaveAccessibleModifiers(it) } if (!showUnknownTypeInDeclarationDialog(project, withErrors)) return@block null resultDeclarations } else selectedElements project.executeWriteCommand(KotlinBundle.message("repair.actual.members")) { repairActualModifiers(originalElements + klass, resultDeclarations.toSet()) } generateClassOrObject(project, true, element, checker) }) private fun showUnknownTypeInDeclarationDialog( project: Project, declarationsWithNonExistentClasses: Collection<KtNamedDeclaration> ): Boolean { if (declarationsWithNonExistentClasses.isEmpty()) return true @NlsSafe val message = escapeXml( declarationsWithNonExistentClasses.joinToString( prefix = "${KotlinBundle.message("these.declarations.cannot.be.transformed")}\n", separator = "\n", transform = ::getExpressionShortText ) ) TypeAccessibilityChecker.testLog?.append("$message\n") return isUnitTestMode() || showOkNoDialog( KotlinBundle.message("unknown.types.title"), message, project ) } private fun KtDeclaration.canAddActualModifier() = when (this) { is KtEnumEntry, is KtClassInitializer -> false is KtParameter -> hasValOrVar() else -> true } /*** * @return null if close without OK */ private fun chooseMembers(project: Project, collection: Collection<KtNamedDeclaration>, prefixToRemove: String): List<KtNamedDeclaration>? { val classMembers = collection.mapNotNull { it.resolveToDescriptorIfAny()?.let { descriptor -> Member(prefixToRemove, it, descriptor) } } val filter = if (collection.any(KtDeclaration::hasActualModifier)) { { declaration: KtDeclaration -> declaration.hasActualModifier() } } else { { true } } return MemberChooser( classMembers.toTypedArray(), true, true, project ).run { title = KotlinBundle.message("choose.actual.members.title") setCopyJavadocVisible(false) selectElements(classMembers.filter { filter((it.element as KtNamedDeclaration)) }.toTypedArray()) show() if (!isOK) null else selectedElements?.map { it.element as KtNamedDeclaration }.orEmpty() } } private class Member(val prefix: String, element: KtElement, descriptor: DeclarationDescriptor) : DescriptorMemberChooserObject(element, descriptor) { override fun getText(): String { val text = super.getText() return if (descriptor is ClassDescriptor) { @NlsSafe val p = prefix text.removePrefix(p) } else { text } } } fun KtClassOrObject.collectDeclarationsForAddActualModifier(withSelf: Boolean = true): Sequence<KtNamedDeclaration> { val thisSequence: Sequence<KtNamedDeclaration> = if (withSelf) sequenceOf(this) else emptySequence() val primaryConstructorSequence: Sequence<KtNamedDeclaration> = primaryConstructorParameters.asSequence() + primaryConstructor.let { if (it != null) sequenceOf(it) else emptySequence() } return thisSequence + primaryConstructorSequence + declarations.asSequence().flatMap { if (it.canAddActualModifier()) when (it) { is KtClassOrObject -> it.collectDeclarationsForAddActualModifier() is KtNamedDeclaration -> sequenceOf(it) else -> emptySequence() } else emptySequence() } } private fun repairActualModifiers( originalElements: Collection<KtNamedDeclaration>, selectedElements: Collection<KtNamedDeclaration> ) { if (originalElements.size == selectedElements.size) for (original in originalElements) { original.makeActualWithParents() } else for (original in originalElements) { if (original in selectedElements) original.makeActualWithParents() else original.makeNotActual() } } private tailrec fun KtDeclaration.makeActualWithParents() { makeActual() containingClassOrObject?.takeUnless(KtDeclaration::hasActualModifier)?.makeActualWithParents() } private fun KtNamedDeclaration.selected(): Sequence<KtNamedDeclaration> { val additionalSequence = safeAs<KtParameter>()?.parent?.parent?.safeAs<KtPrimaryConstructor>()?.let { sequenceOf(it) } ?: emptySequence() return sequenceOf(this) + additionalSequence + containingClassOrObject?.selected().orEmpty() } class CreateExpectedCallableMemberFix( declaration: KtCallableDeclaration, targetExpectedClass: KtClassOrObject?, commonModule: Module ) : CreateExpectedFix<KtNamedDeclaration>(declaration, targetExpectedClass, commonModule, block@{ project, checker, element -> if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null val descriptor = element.toDescriptor() as? CallableMemberDescriptor checker.existingTypeNames = targetExpectedClass?.getSuperNames()?.toSet().orEmpty() descriptor?.let { generateCallable( project, true, element, descriptor, targetExpectedClass, checker = checker ) } })
apache-2.0
b8f36965467d01f0e387398cfa5260fe
42.989691
158
0.724631
5.517672
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/findUsages/OptionsParser.kt
2
8264
// 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.findUsages import com.intellij.find.findUsages.* import com.intellij.openapi.project.Project import com.intellij.psi.* import org.jetbrains.kotlin.idea.findUsages.KotlinClassFindUsagesOptions import org.jetbrains.kotlin.idea.findUsages.KotlinFunctionFindUsagesOptions import org.jetbrains.kotlin.idea.findUsages.KotlinPropertyFindUsagesOptions import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.test.InTextDirectivesUtils internal enum class OptionsParser { CLASS { override fun parse(text: String, project: Project): FindUsagesOptions { return KotlinClassFindUsagesOptions(project).apply { isUsages = false isSearchForTextOccurrences = false searchConstructorUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "constructorUsages" -> searchConstructorUsages = true "derivedInterfaces" -> isDerivedInterfaces = true "derivedClasses" -> isDerivedClasses = true "functionUsages" -> isMethodsUsages = true "propertyUsages" -> isFieldsUsages = true "expected" -> searchExpected = true else -> throw IllegalStateException("Invalid option: $s") } } } } }, FUNCTION { override fun parse(text: String, project: Project): FindUsagesOptions { return KotlinFunctionFindUsagesOptions(project).apply { isUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "overrides" -> { isOverridingMethods = true isImplementingMethods = true } "overloadUsages" -> { isIncludeOverloadUsages = true isUsages = true } "expected" -> { searchExpected = true isUsages = true } else -> throw IllegalStateException("Invalid option: $s") } } } } }, PROPERTY { override fun parse(text: String, project: Project): FindUsagesOptions { return KotlinPropertyFindUsagesOptions(project).apply { isUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "overrides" -> searchOverrides = true "skipRead" -> isReadAccess = false "skipWrite" -> isWriteAccess = false "expected" -> searchExpected = true else -> throw IllegalStateException("Invalid option: $s") } } } } }, JAVA_CLASS { override fun parse(text: String, project: Project): FindUsagesOptions { return KotlinClassFindUsagesOptions(project).apply { isUsages = false searchConstructorUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "derivedInterfaces" -> isDerivedInterfaces = true "derivedClasses" -> isDerivedClasses = true "implementingClasses" -> isImplementingClasses = true "methodUsages" -> isMethodsUsages = true "fieldUsages" -> isFieldsUsages = true else -> throw IllegalStateException("Invalid option: $s") } } } } }, JAVA_METHOD { override fun parse(text: String, project: Project): FindUsagesOptions { return JavaMethodFindUsagesOptions(project).apply { isUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "overrides" -> { isOverridingMethods = true isImplementingMethods = true } else -> throw IllegalStateException("Invalid option: $s") } } } } }, JAVA_FIELD { override fun parse(text: String, project: Project): FindUsagesOptions { return JavaVariableFindUsagesOptions(project).apply { for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "skipRead" -> isReadAccess = false "skipWrite" -> isWriteAccess = false else -> throw IllegalStateException("Invalid option: `$s`") } } } } }, JAVA_PACKAGE { override fun parse(text: String, project: Project): FindUsagesOptions { return JavaPackageFindUsagesOptions(project).apply { for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue throw IllegalStateException("Invalid option: `$s`") } } } }, DEFAULT { override fun parse(text: String, project: Project): FindUsagesOptions { return FindUsagesOptions(project).apply { for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue throw IllegalStateException("Invalid option: `$s`") } } } }; abstract fun parse(text: String, project: Project): FindUsagesOptions companion object { protected fun parseCommonOptions(options: JavaFindUsagesOptions, s: String): Boolean { if (parseCommonOptions(options as FindUsagesOptions, s)) { return true } return when (s) { "skipImports" -> { options.isSkipImportStatements = true true } else -> false } } protected fun parseCommonOptions(options: FindUsagesOptions, s: String): Boolean { return when (s) { "usages" -> { options.isUsages = true true } "textOccurrences" -> { options.isSearchForTextOccurrences = true true } else -> false } } fun getParserByPsiElementClass(klass: Class<out PsiElement>): OptionsParser? { return when (klass) { KtNamedFunction::class.java -> FUNCTION KtProperty::class.java, KtParameter::class.java -> PROPERTY KtClass::class.java -> CLASS PsiMethod::class.java -> JAVA_METHOD PsiClass::class.java -> JAVA_CLASS PsiField::class.java -> JAVA_FIELD PsiPackage::class.java -> JAVA_PACKAGE KtTypeParameter::class.java -> DEFAULT else -> null } } } }
apache-2.0
58ca35d24cf8268378c8b11383af969f
39.714286
158
0.510407
6.255867
false
false
false
false
davidkrauser/MicroPost
app/src/main/java/org/krauser/micropost/CreatePostActivity.kt
1
3082
package org.krauser.micropost import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.InputType import android.view.Window import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.TextView import android.widget.Toast import butterknife.BindView import butterknife.ButterKnife import butterknife.OnEditorAction import butterknife.OnTextChanged private const val MAX_POST_TEXT_LENGTH: Int = 300 private const val POST_TEXT_STORE_NAME: String = "POST_TEXT_STORE" private const val AUTH_TOKEN_STORE_NAME: String = "AUTH_TOKEN_STORE" class CreatePostActivity : AppCompatActivity(), CreatePostPresenter.View { @BindView(R.id.post_input) lateinit internal var postInput: EditText @BindView(R.id.length_view) lateinit internal var lengthView: TextView @BindView(R.id.token_input) lateinit internal var tokenInput: EditText lateinit private var presenter: CreatePostPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) setContentView(R.layout.activity_micro_post) val authTokenStore = PersistedStore(AUTH_TOKEN_STORE_NAME, getPreferences(Context.MODE_PRIVATE)) val postTextStore = PersistedStore(POST_TEXT_STORE_NAME, getPreferences(Context.MODE_PRIVATE)) presenter = CreatePostPresenter(authTokenStore, postTextStore) ButterKnife.bind(this) presenter.onAttach(this) postInput.imeOptions = EditorInfo.IME_ACTION_SEND postInput.setRawInputType( InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) } @OnEditorAction(R.id.post_input) internal fun onEditorAction(actionId: Int): Boolean { if (actionId == EditorInfo.IME_ACTION_SEND) { postInput.isEnabled = false presenter.onSendAction() return true } else { return false } } @OnTextChanged(R.id.post_input) internal fun onPostInputChanged(text: CharSequence) { presenter.onPostTextChange(text.toString()) } @OnTextChanged(R.id.token_input) internal fun onTokenInputChanged(text: CharSequence) { presenter.onAuthTokenChange(text.toString()) } override fun showSendError() { Toast.makeText(this, R.string.send_failure_message, Toast.LENGTH_SHORT).show() postInput.isEnabled = true } override fun showNoTokenError() { postInput.isEnabled = true } override fun showEmptyMessageError() { postInput.isEnabled = true } override fun showSendSuccess() { finish() } override fun showPostText(postText: String) { postInput.setText(postText) } override fun showPostTextLength(length: Int) { lengthView.text = "${MAX_POST_TEXT_LENGTH - length}" } override fun showAuthToken(authToken: String) { tokenInput.setText(authToken) if (authToken.isEmpty()) { tokenInput.requestFocus() } else { postInput.requestFocus() } } }
mit
cedf0a64f51b5a295c2328f9bf2ba511
28.352381
83
0.744322
4.142473
false
false
false
false
tlaukkan/kotlin-web-vr
client/src/lib/threejs/Extra/Geometries.kt
1
694
package lib.threejs.Extra import lib.threejs.Geometry @native("THREE.BoxGeometry") class BoxGeometry( x: Double, y: Double, z: Double ) : Geometry() @native("THREE.SphereGeometry") class SphereGeometry( radius: Double = noImpl, widthSegments: Int = noImpl, heightSegments: Int = noImpl, phiStart: Double = noImpl, phiLength: Double = noImpl, thetaStart: Double = noImpl, thetaLength: Double = noImpl ) : Geometry() @native("THREE.ShapeGeometry") class ShapeGeometry( shapes: Array<Shape>, options: Any = noImpl ) : Geometry() { fun addShapeList(shapes: Array<Shape>, options: Any): Unit = noImpl fun addShape(shapes: Array<Shape>, options: Any): Unit = noImpl }
mit
a986365fb802707622fbb5d2d84cdaeb
24.703704
69
0.711816
3.671958
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/basicsettings/BasicRequestSettingsActivity.kt
1
4540
package ch.rmy.android.http_shortcuts.activities.editor.basicsettings import android.os.Bundle import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import ch.rmy.android.framework.extensions.bindViewModel import ch.rmy.android.framework.extensions.collectEventsWhileActive import ch.rmy.android.framework.extensions.collectViewStateWhileActive import ch.rmy.android.framework.extensions.doOnTextChanged import ch.rmy.android.framework.extensions.initialize import ch.rmy.android.framework.ui.BaseIntentBuilder import ch.rmy.android.framework.viewmodel.ViewModelEvent import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.activities.BaseActivity import ch.rmy.android.http_shortcuts.activities.editor.basicsettings.models.InstalledBrowser import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent import ch.rmy.android.http_shortcuts.data.models.ShortcutModel import ch.rmy.android.http_shortcuts.databinding.ActivityBasicRequestSettingsBinding import kotlinx.coroutines.launch class BasicRequestSettingsActivity : BaseActivity() { private val viewModel: BasicRequestSettingsViewModel by bindViewModel() private lateinit var binding: ActivityBasicRequestSettingsBinding private var installedBrowsers: List<InstalledBrowser> = emptyList() set(value) { if (field != value) { field = value binding.inputBrowserPackageName.setItemsFromPairs( listOf(DEFAULT_BROWSER_OPTION to getString(R.string.placeholder_browser_package_name)) + value.map { it.packageName to (it.appName ?: it.packageName) } ) } } override fun inject(applicationComponent: ApplicationComponent) { applicationComponent.inject(this) } override fun onCreated(savedState: Bundle?) { viewModel.initialize() initViews() initUserInputBindings() initViewModelBindings() } private fun initViews() { binding = applyBinding(ActivityBasicRequestSettingsBinding.inflate(layoutInflater)) setTitle(R.string.section_basic_request) binding.inputMethod.setItemsFromPairs( METHODS.map { it to it } ) } private fun initUserInputBindings() { lifecycleScope.launch { binding.inputMethod.selectionChanges.collect(viewModel::onMethodChanged) } binding.inputUrl.doOnTextChanged { viewModel.onUrlChanged(binding.inputUrl.rawString) } lifecycleScope.launch { binding.inputBrowserPackageName.selectionChanges.collect { viewModel.onBrowserPackageNameChanged(it.takeUnless { it == DEFAULT_BROWSER_OPTION } ?: "") } } binding.variableButtonUrl.setOnClickListener { viewModel.onUrlVariableButtonClicked() } } private fun initViewModelBindings() { collectViewStateWhileActive(viewModel) { viewState -> binding.inputMethod.isVisible = viewState.methodVisible binding.inputMethod.selectedItem = viewState.method binding.inputUrl.rawString = viewState.url installedBrowsers = viewState.browserPackageNameOptions binding.inputBrowserPackageName.selectedItem = viewState.browserPackageName binding.inputBrowserPackageName.isVisible = viewState.browserPackageNameVisible setDialogState(viewState.dialogState, viewModel) } collectEventsWhileActive(viewModel, ::handleEvent) } override fun handleEvent(event: ViewModelEvent) { when (event) { is BasicRequestSettingsEvent.InsertVariablePlaceholder -> { binding.inputUrl.insertVariablePlaceholder(event.variablePlaceholder) } else -> super.handleEvent(event) } } override fun onBackPressed() { viewModel.onBackPressed() } class IntentBuilder : BaseIntentBuilder(BasicRequestSettingsActivity::class) companion object { private val METHODS = listOf( ShortcutModel.METHOD_GET, ShortcutModel.METHOD_POST, ShortcutModel.METHOD_PUT, ShortcutModel.METHOD_DELETE, ShortcutModel.METHOD_PATCH, ShortcutModel.METHOD_HEAD, ShortcutModel.METHOD_OPTIONS, ShortcutModel.METHOD_TRACE, ) private const val DEFAULT_BROWSER_OPTION = "default" } }
mit
bb9888472059e1e440d5d87ae29e4d81
35.910569
108
0.697357
5.404762
false
false
false
false
myunusov/maxur-mserv
maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/runner/Kotlin.kt
1
1545
package org.maxur.mserv.frame.runner import org.maxur.mserv.frame.domain.Holder import org.maxur.mserv.frame.service.properties.PropertiesFactoryHoconImpl import org.maxur.mserv.frame.service.properties.PropertiesFactoryJsonImpl import org.maxur.mserv.frame.service.properties.PropertiesFactoryYamlImpl object Kotlin { fun runner(init: KRunner.() -> Unit) = KRunner(init) } class KRunner() : MicroServiceRunner() { var name: String = "Anonymous" set(value) { nameHolder = Holder.string(value) } constructor(init: KRunner.() -> Unit) : this() { init() } fun withoutProperties() { properties += PropertiesBuilder.NullPropertiesBuilder } fun file(init: PropertiesBuilder.BasePropertiesBuilder.() -> Unit) = PropertiesBuilder.BasePropertiesBuilder().apply { init() } fun service(init: ServiceBuilder.() -> Unit) = ServiceBuilder().apply { init() } fun rest(init: ServiceBuilder.() -> Unit) = ServiceBuilder().apply { type = "Grizzly" properties = ":webapp" init() } } fun hocon(init: PredefinedPropertiesBuilder.() -> Unit = {}) = object : PredefinedPropertiesBuilder("hocon", PropertiesFactoryHoconImpl(), init) {} fun json(init: PredefinedPropertiesBuilder.() -> Unit = {}) = object : PredefinedPropertiesBuilder("json", PropertiesFactoryJsonImpl(), init) {} fun yaml(init: PredefinedPropertiesBuilder.() -> Unit = {}) = object : PredefinedPropertiesBuilder("yaml", PropertiesFactoryYamlImpl(), init) {}
apache-2.0
c66c6a5c5905ec09652bf42e56dac978
32.608696
90
0.688026
4.439655
false
false
false
false
Magneticraft-Team/ModelLoader
src/main/kotlin/com/cout970/modelloader/api/ModelConfig.kt
1
5858
package com.cout970.modelloader.api import net.minecraft.client.renderer.model.IBakedModel import net.minecraft.client.renderer.model.IUnbakedModel import net.minecraft.client.renderer.model.ModelResourceLocation import net.minecraft.client.renderer.model.ModelRotation import net.minecraft.util.Direction import net.minecraft.util.ResourceLocation /** * Configuration that tells the library how to load a model. */ data class ModelConfig @JvmOverloads constructor( val location: ResourceLocation, val itemTransforms: ItemTransforms = ItemTransforms.DEFAULT, val rotation: ModelRotation = ModelRotation.X0_Y0, val bake: Boolean = true, val animate: Boolean = false, val mutable: Boolean = false, val itemRenderer: Boolean = false, val preBake: ((ModelResourceLocation, IUnbakedModel) -> IUnbakedModel)? = null, val postBake: ((ModelResourceLocation, IBakedModel) -> IBakedModel)? = null, val partFilter: ((String)-> Boolean)? = null ) { /** * Marks the location where the model file is stored */ fun withLocation(location: ResourceLocation) = copy(location = location) /** * Marks the transformations to apply in several item views */ fun withItemTransforms(itemTransforms: ItemTransforms) = copy(itemTransforms = itemTransforms) /** * Marks a rotation to apply to the model before baking */ fun withRotation(rotation: ModelRotation) = copy(rotation = rotation) /** * Marks a rotation using a Direction component */ fun withDirection(dir: Direction) = copy(rotation = DIRECTION_TO_ROTATION.getValue(dir)) /** * Indicates that this model must be baked, this allow the model to be used for an item or a blockstate */ fun withBake(bake: Boolean) = copy(bake = bake) /** * Indicates that this model must be analyzed to create animated models */ fun withAnimation(animate: Boolean) = copy(animate = animate) /** * Indicates that this model should be processed to generate a [MutableModel] */ fun withMutable(mutable: Boolean) = copy(mutable = mutable) /** * Marks the generated bakedmodel so Minecraft knows that the item with that model needs to use an ItemRenderer */ fun withItemRenderer(itemRenderer: Boolean) = copy(itemRenderer = itemRenderer) /** * Binds a callback that will receive the model after is gets loaded * * You must return a new model instead of editing the argument, * because models are loaded only once and shared for several ModelConfigs registrations */ fun withPreBake(preBake: ((ModelResourceLocation, IUnbakedModel) -> IUnbakedModel)?) = copy(preBake = preBake) /** * Binds a callback that will receive the model after is gets baked * * You can return the same model with changes or return a different instance, for example, wrapping the model */ fun withPostBake(postBake: ((ModelResourceLocation, IBakedModel) -> IBakedModel)?) = copy(postBake = postBake) /** * Binds a callback that filters which parts to keep in the model */ fun withPartFilter(partFilter: ((String)-> Boolean)?) = copy(partFilter = partFilter) /** * Combines withDirection and withRotation, allowing to use a direction for rotation * and apply an extra rotation over it */ fun withDirection(dir: Direction, rot: ModelRotation): ModelConfig { return withRotation(DIRECTION_TO_ROTATION.getValue(dir) + rot) } companion object { /** * Rotations per direction */ @JvmField val DIRECTION_TO_ROTATION = mapOf( Direction.DOWN to ModelRotation.X0_Y0, Direction.UP to ModelRotation.X180_Y0, Direction.NORTH to ModelRotation.X90_Y0, Direction.SOUTH to ModelRotation.X270_Y0, Direction.WEST to ModelRotation.X270_Y270, Direction.EAST to ModelRotation.X270_Y90 ) /** * Adds 2 rotations together */ operator fun ModelRotation.plus(other: ModelRotation): ModelRotation { val x = this.getX() + other.getX() val y = this.getY() + other.getY() return ModelRotation.getModelRotation(x, y) } /** * Gets the X component of a rotation */ fun ModelRotation.getX() = when (this) { ModelRotation.X0_Y0 -> 0 ModelRotation.X0_Y90 -> 0 ModelRotation.X0_Y180 -> 0 ModelRotation.X0_Y270 -> 0 ModelRotation.X90_Y0 -> 90 ModelRotation.X90_Y90 -> 90 ModelRotation.X90_Y180 -> 90 ModelRotation.X90_Y270 -> 90 ModelRotation.X180_Y0 -> 180 ModelRotation.X180_Y90 -> 180 ModelRotation.X180_Y180 -> 180 ModelRotation.X180_Y270 -> 180 ModelRotation.X270_Y0 -> 270 ModelRotation.X270_Y90 -> 270 ModelRotation.X270_Y180 -> 270 ModelRotation.X270_Y270 -> 270 } /** * Gets the Y component of a rotation */ fun ModelRotation.getY() = when (this) { ModelRotation.X0_Y0 -> 0 ModelRotation.X0_Y90 -> 90 ModelRotation.X0_Y180 -> 180 ModelRotation.X0_Y270 -> 270 ModelRotation.X90_Y0 -> 0 ModelRotation.X90_Y90 -> 90 ModelRotation.X90_Y180 -> 180 ModelRotation.X90_Y270 -> 270 ModelRotation.X180_Y0 -> 0 ModelRotation.X180_Y90 -> 90 ModelRotation.X180_Y180 -> 180 ModelRotation.X180_Y270 -> 270 ModelRotation.X270_Y0 -> 0 ModelRotation.X270_Y90 -> 90 ModelRotation.X270_Y180 -> 180 ModelRotation.X270_Y270 -> 270 } } }
gpl-2.0
0b73321c9589f4addff2f8230dec0839
35.391304
115
0.636224
4.468345
false
false
false
false
developer--/before_after_slider
beforeafterslider/src/main/java/com/github/developer__/BeforeAfterSlider.kt
1
2457
package com.github.developer__ import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.LayoutInflater import android.widget.RelativeLayout import com.github.developer__.asycn.ClipDrawableProcessorTask import com.github.developer__.extensions.loadImage import com.github.developer__.extensions.stayVisibleOrGone import kotlinx.android.synthetic.main.slider_layout.view.* /** * Created by Jemo on 12/5/16. */ class BeforeAfterSlider : RelativeLayout, ClipDrawableProcessorTask.OnAfterImageLoaded{ constructor(context: Context): super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { val attr = context.theme.obtainStyledAttributes(attrs, R.styleable.BeforeAfterSlider,0,0) try { val thumbDrawable = attr.getDrawable(R.styleable.BeforeAfterSlider_slider_thumb) val beforeImage = attr.getDrawable(R.styleable.BeforeAfterSlider_before_image) val afterImageUrl = attr.getDrawable(R.styleable.BeforeAfterSlider_after_image) setSliderThumb(thumbDrawable) setBeforeImage(beforeImage) setAfterImage(afterImageUrl) }finally { attr.recycle() } } init { LayoutInflater.from(context).inflate(R.layout.slider_layout, this) } /** * set original image */ fun setBeforeImage(imageUri: String): BeforeAfterSlider { before_image_view_id.loadImage(imageUri) return this } fun setBeforeImage(imgDrawable: Drawable?): BeforeAfterSlider { before_image_view_id.loadImage(imgDrawable) return this } /** * set changed image */ fun setAfterImage(imageUri: String) { ClipDrawableProcessorTask<String>(after_image_view_id, seekbar_id, context, this).execute(imageUri) } /** * set changed image */ fun setAfterImage(imageDrawable: Drawable?) { ClipDrawableProcessorTask<Drawable>(after_image_view_id, seekbar_id, context, this).execute(imageDrawable) } /** * set thumb */ fun setSliderThumb(thumb: Drawable?){ thumb?.let { seekbar_id.thumb = thumb } } /** * fired up after second image loading will be finished */ override fun onLoadedFinished(loadedSuccess: Boolean) { seekbar_id.stayVisibleOrGone(loadedSuccess) } }
apache-2.0
1953be38f1feae88dd529c7e9ed66c20
28.25
114
0.684575
4.379679
false
false
false
false
solokot/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/fragments/ViewPagerFragment.kt
1
5461
package com.simplemobiletools.gallery.pro.fragments import android.provider.MediaStore import android.provider.MediaStore.Files import android.provider.MediaStore.Images import android.view.MotionEvent import androidx.exifinterface.media.ExifInterface import androidx.fragment.app.Fragment import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.gallery.pro.R import com.simplemobiletools.gallery.pro.extensions.config import com.simplemobiletools.gallery.pro.helpers.* import com.simplemobiletools.gallery.pro.models.Medium import java.io.File abstract class ViewPagerFragment : Fragment() { var listener: FragmentListener? = null private var mTouchDownTime = 0L private var mTouchDownX = 0f private var mTouchDownY = 0f private var mCloseDownThreshold = 100f private var mIgnoreCloseDown = false abstract fun fullscreenToggled(isFullscreen: Boolean) interface FragmentListener { fun fragmentClicked() fun videoEnded(): Boolean fun goToPrevItem() fun goToNextItem() fun launchViewVideoIntent(path: String) fun isSlideShowActive(): Boolean } fun getMediumExtendedDetails(medium: Medium): String { val file = File(medium.path) if (context?.getDoesFilePathExist(file.absolutePath) == false) { return "" } val path = "${file.parent.trimEnd('/')}/" val exif = try { ExifInterface(medium.path) } catch (e: Exception) { return "" } val details = StringBuilder() val detailsFlag = context!!.config.extendedDetails if (detailsFlag and EXT_NAME != 0) { medium.name.let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_PATH != 0) { path.let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_SIZE != 0) { file.length().formatSize().let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_RESOLUTION != 0) { context!!.getResolution(file.absolutePath)?.formatAsResolution().let { if (it?.isNotEmpty() == true) details.appendln(it) } } if (detailsFlag and EXT_LAST_MODIFIED != 0) { getFileLastModified(file).let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_DATE_TAKEN != 0) { exif.getExifDateTaken(context!!).let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_CAMERA_MODEL != 0) { exif.getExifCameraModel().let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_EXIF_PROPERTIES != 0) { exif.getExifProperties().let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_GPS != 0) { getLatLonAltitude(medium.path).let { if (it.isNotEmpty()) details.appendln(it) } } return details.toString().trim() } fun getPathToLoad(medium: Medium) = if (context?.isPathOnOTG(medium.path) == true) medium.path.getOTGPublicPath(context!!) else medium.path private fun getFileLastModified(file: File): String { val projection = arrayOf(Images.Media.DATE_MODIFIED) val uri = Files.getContentUri("external") val selection = "${MediaStore.MediaColumns.DATA} = ?" val selectionArgs = arrayOf(file.absolutePath) val cursor = context!!.contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { return if (cursor.moveToFirst()) { val dateModified = cursor.getLongValue(Images.Media.DATE_MODIFIED) * 1000L dateModified.formatDate(context!!) } else { file.lastModified().formatDate(context!!) } } return "" } private fun getLatLonAltitude(path: String): String { var result = "" val exif = try { ExifInterface(path) } catch (e: Exception) { return "" } val latLon = FloatArray(2) if (exif.getLatLong(latLon)) { result = "${latLon[0]}, ${latLon[1]}" } val altitude = exif.getAltitude(0.0) if (altitude != 0.0) { result += ", ${altitude}m" } return result.trimStart(',').trim() } protected fun handleEvent(event: MotionEvent) { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { mTouchDownTime = System.currentTimeMillis() mTouchDownX = event.x mTouchDownY = event.y } MotionEvent.ACTION_POINTER_DOWN -> mIgnoreCloseDown = true MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { val diffX = mTouchDownX - event.x val diffY = mTouchDownY - event.y val downGestureDuration = System.currentTimeMillis() - mTouchDownTime if (!mIgnoreCloseDown && Math.abs(diffY) > Math.abs(diffX) && diffY < -mCloseDownThreshold && downGestureDuration < MAX_CLOSE_DOWN_GESTURE_DURATION && context?.config?.allowDownGesture == true) { activity?.finish() activity?.overridePendingTransition(0, R.anim.slide_down) } mIgnoreCloseDown = false } } } }
gpl-3.0
bb68bd4b7f365b144f091f31abc3c931
34.00641
211
0.609229
4.569874
false
false
false
false
juanavelez/crabzilla
crabzilla-web-pg-client/src/main/java/io/github/crabzilla/webpgc/webpgc.kt
1
6707
package io.github.crabzilla.webpgc import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import io.github.crabzilla.framework.DomainEvent import io.github.crabzilla.framework.Entity import io.github.crabzilla.framework.EntityJsonAware import io.github.crabzilla.framework.UnitOfWork import io.github.crabzilla.internal.UnitOfWorkEvents import io.vertx.config.ConfigRetriever import io.vertx.config.ConfigRetrieverOptions import io.vertx.config.ConfigStoreOptions import io.vertx.core.* import io.vertx.core.http.HttpServer import io.vertx.core.json.Json import io.vertx.core.json.JsonObject import io.vertx.core.logging.SLF4JLogDelegateFactory import io.vertx.ext.web.RoutingContext import org.slf4j.LoggerFactory import java.io.IOException import java.net.ServerSocket private val log = LoggerFactory.getLogger("webpgc") fun getConfig(vertx: Vertx, configFile: String) : Future<JsonObject> { // slf4j setup System.setProperty(io.vertx.core.logging.LoggerFactory.LOGGER_DELEGATE_FACTORY_CLASS_NAME, SLF4JLogDelegateFactory::class.java.name) LoggerFactory.getLogger(io.vertx.core.logging.LoggerFactory::class.java) // Jackson setup Json.mapper .registerModule(Jdk8Module()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // get config val future: Future<JsonObject> = Future.future() configRetriever(vertx, configFile).getConfig { gotConfig -> if (gotConfig.succeeded()) { val config = gotConfig.result() log.info("*** config:\n${config.encodePrettily()}") val readHttpPort = config.getInteger("READ_HTTP_PORT") val nextFreeReadHttpPort = nextFreePort(readHttpPort, readHttpPort + 20) config.put("READ_HTTP_PORT", nextFreeReadHttpPort) log.info("*** next free READ_HTTP_PORT: $nextFreeReadHttpPort") val writeHttpPort = config.getInteger("WRITE_HTTP_PORT") val nextFreeWriteHttpPort = nextFreePort(writeHttpPort, writeHttpPort + 20) config.put("WRITE_HTTP_PORT", nextFreeWriteHttpPort) log.info("*** next free WRITE_HTTP_PORT: $nextFreeWriteHttpPort") future.complete(config) } else { future.fail(gotConfig.cause()) } } return future } private fun configRetriever(vertx: Vertx, configFile: String): ConfigRetriever { val envOptions = ConfigStoreOptions() .setType("file") .setFormat("properties") .setConfig(JsonObject().put("path", configFile)) val options = ConfigRetrieverOptions().addStore(envOptions) return ConfigRetriever.create(vertx, options) } fun deploy(vertx: Vertx, verticle: String, deploymentOptions: DeploymentOptions): Future<String> { val future: Future<String> = Future.future() vertx.deployVerticle(verticle, deploymentOptions, future) return future } fun deploySingleton(vertx: Vertx, verticle: String, dOpt: DeploymentOptions, processId: String): Future<String> { val future: Future<String> = Future.future() vertx.eventBus().send<String>(verticle, processId) { isWorking -> if (isWorking.succeeded()) { log.info("No need to start $verticle: " + isWorking.result().body()) } else { log.info("*** Deploying $verticle") vertx.deployVerticle(verticle, dOpt) { wasDeployed -> if (wasDeployed.succeeded()) { log.info("$verticle started") future.complete("singleton ${wasDeployed.result()}") } else { log.error("$verticle not started", wasDeployed.cause()) future.fail(wasDeployed.cause()) } } } } return future } fun deployHandler(vertx: Vertx): Handler<AsyncResult<CompositeFuture>> { return Handler { deploys -> if (deploys.succeeded()) { val deploymentIds = deploys.result().list<String>() log.info("Verticles were successfully deployed") Runtime.getRuntime().addShutdownHook(object : Thread() { override fun run() { for (id in deploymentIds) { if (id.startsWith("singleton")) { log.info("Keeping singleton deployment $id") } else { log.info("Undeploying $id") vertx.undeploy(id) } } log.info("Closing vertx") vertx.close() } }) } else { log.error("When deploying", deploys.cause()) } } } fun listenHandler(future: Future<Void>): Handler<AsyncResult<HttpServer>> { return Handler { startedFuture -> if (startedFuture.succeeded()) { log.info("Server started on port " + startedFuture.result().actualPort()) future.complete() } else { log.error("oops, something went wrong during server initialization", startedFuture.cause()) future.fail(startedFuture.cause()) } } } private fun nextFreePort(from: Int, to: Int): Int { var port = from while (true) { if (isLocalPortFree(port)) { return port } else { if (port == to) { throw IllegalStateException("Could not find any from available from $from to $to"); } else { port += 1 } } } } private fun isLocalPortFree(port: Int): Boolean { return try { log.info("Trying port $port...") ServerSocket(port).close() true } catch (e: IOException) { false } } fun toUnitOfWorkEvents(json: JsonObject, jsonFunctions: Map<String, EntityJsonAware<out Entity>>): UnitOfWorkEvents? { val uowId = json.getLong("uowId") val entityName = json.getString(UnitOfWork.JsonMetadata.ENTITY_NAME) val entityId = json.getInteger(UnitOfWork.JsonMetadata.ENTITY_ID) val eventsArray = json.getJsonArray(UnitOfWork.JsonMetadata.EVENTS) val jsonAware = jsonFunctions[entityName] if (jsonAware == null) { log.error("JsonAware for $entityName wasn't found") return null } val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index -> val jsonObject = eventsArray.getJsonObject(index) val eventName = jsonObject.getString(UnitOfWork.JsonMetadata.EVENT_NAME) val eventJson = jsonObject.getJsonObject(UnitOfWork.JsonMetadata.EVENTS_JSON_CONTENT) val domainEvent = jsonAware.eventFromJson(eventName, eventJson) domainEvent } val events: List<Pair<String, DomainEvent>> = List(eventsArray.size(), jsonToEventPair) return UnitOfWorkEvents(uowId, entityId, events) } fun errorHandler(paramName: String) : Handler<RoutingContext> { return Handler { WebCommandVerticle.log.error(it.failure().message, it.failure()) when (it.failure()) { is NumberFormatException -> it.response().setStatusCode(400).end("path param $paramName must be a number") else -> { it.failure().printStackTrace() it.response().setStatusCode(500).end("server error") } } } }
apache-2.0
97b8c3f7bef2f632e4850281c4af5ad6
34.115183
118
0.698524
4.097129
false
true
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/api/chat/ChatMessagesEndpoint.kt
2
924
package me.proxer.library.api.chat import me.proxer.library.ProxerCall import me.proxer.library.api.Endpoint import me.proxer.library.entity.chat.ChatMessage /** * Endpoint for retrieving messages in a chat room. * * This behaves differently based on the parameter messageId: * 1) messageId = 0: Returns the last messages from the chat room. * 2) messageId != 0: Returns all messages older than that passed from the chat room. * * @author Ruben Gees */ class ChatMessagesEndpoint internal constructor( private val internalApi: InternalApi, private val roomId: String ) : Endpoint<List<ChatMessage>> { private var messageId: String? = null /** * Sets the message id to load from. */ fun messageId(messageId: String?) = this.apply { this.messageId = messageId } override fun build(): ProxerCall<List<ChatMessage>> { return internalApi.messages(roomId, messageId) } }
gpl-3.0
3ced753a9137cac23f3ebfb81e4203cd
28.806452
85
0.719697
4.238532
false
false
false
false
cretz/asmble
compiler/src/main/kotlin/asmble/compile/jvm/Linker.kt
1
11289
package asmble.compile.jvm import asmble.annotation.WasmExport import asmble.annotation.WasmExternalKind import asmble.annotation.WasmImport import asmble.annotation.WasmModule import org.objectweb.asm.Handle import org.objectweb.asm.Opcodes import org.objectweb.asm.Type import org.objectweb.asm.tree.* import java.lang.invoke.MethodHandle open class Linker { fun link(ctx: Context) { // Quick check to prevent duplicate names ctx.classes.groupBy { it.name }.values.forEach { require(it.size == 1) { "Duplicate module name: ${it.first().name}"} } // Common items ctx.cls.superName = Object::class.ref.asmName ctx.cls.version = Opcodes.V1_8 ctx.cls.access += Opcodes.ACC_PUBLIC addConstructor(ctx) addDefaultMaxMemField(ctx) // Go over each module and add its creation and instance methods ctx.classes.forEach { addCreationMethod(ctx, it) addInstanceField(ctx, it) addInstanceMethod(ctx, it) } TODO() } fun addConstructor(ctx: Context) { // Just the default empty constructor ctx.cls.methods.plusAssign( Func( access = Opcodes.ACC_PUBLIC, name = "<init>", params = emptyList(), ret = Void::class.ref, insns = listOf( VarInsnNode(Opcodes.ALOAD, 0), MethodInsnNode(Opcodes.INVOKESPECIAL, Object::class.ref.asmName, "<init>", "()V", false), InsnNode(Opcodes.RETURN) ) ).toMethodNode() ) } fun addDefaultMaxMemField(ctx: Context) { (Int.MAX_VALUE / Mem.PAGE_SIZE).let { maxAllowed -> require(ctx.defaultMaxMemPages <= maxAllowed) { "Page size ${ctx.defaultMaxMemPages} over max allowed $maxAllowed" } } ctx.cls.fields.plusAssign(FieldNode( // Make it volatile since it will be publicly mutable Opcodes.ACC_PUBLIC + Opcodes.ACC_VOLATILE, "defaultMaxMem", "I", null, ctx.defaultMaxMemPages * Mem.PAGE_SIZE )) } fun addCreationMethod(ctx: Context, mod: ModuleClass) { // The creation method accepts everything needed for import in order of // imports. For creating a mod w/ self-built memory, we use a default max // mem field on the linkage class if there isn't a default already. val params = mod.importClasses(ctx) var func = Func( access = Opcodes.ACC_PROTECTED, name = "create" + mod.name.javaIdent.capitalize(), params = params.map(ModuleClass::ref), ret = mod.ref ) // The stack here on out is for building params to constructor... // The constructor we'll use is: // * Mem-class based constructor if it's an import // * Max-mem int based constructor if mem is self-built and doesn't have a no-mem-no-max ctr // * Should be only single constructor with imports when there's no mem val memClassCtr = mod.cls.constructors.find { it.parameters.firstOrNull()?.type?.ref == ctx.mem.memType } val constructor = if (memClassCtr == null) mod.cls.constructors.singleOrNull() else { // Use the import annotated one if there if (memClassCtr.parameters.first().isAnnotationPresent(WasmImport::class.java)) memClassCtr else { // If there is a non-int-starting constructor, we want to use that val nonMaxMemCtr = mod.cls.constructors.find { it != memClassCtr && it.parameters.firstOrNull()?.type != Integer.TYPE } if (nonMaxMemCtr != null) nonMaxMemCtr else { // Use the max-mem constructor and put the int on the stack func = func.addInsns( VarInsnNode(Opcodes.ALOAD, 0), FieldInsnNode(Opcodes.GETFIELD, ctx.cls.name, "defaultMaxMem", "I") ) mod.cls.constructors.find { it.parameters.firstOrNull()?.type != Integer.TYPE } } } } if (constructor == null) error("Unable to find suitable constructor for ${mod.cls}") // Now just go over the imports and put them on the stack func = constructor.parameters.fold(func) { func, param -> param.getAnnotation(WasmImport::class.java).let { import -> when (import.kind) { // Invoke the mem handle to get the mem // TODO: for imported memory, fail if import.limit < limits.init * page size at runtime // TODO: for imported memory, fail if import.cap > limits.max * page size at runtime WasmExternalKind.MEMORY -> func.addInsns( VarInsnNode(Opcodes.ALOAD, 1 + params.indexOfFirst { it.name == import.module }), ctx.resolveImportHandle(import).let { memGet -> MethodInsnNode(Opcodes.INVOKEVIRTUAL, memGet.owner, memGet.name, memGet.desc, false) } ) // Bind the method WasmExternalKind.FUNCTION -> func.addInsns( LdcInsnNode(ctx.resolveImportHandle(import)), VarInsnNode(Opcodes.ALOAD, 1 + params.indexOfFirst { it.name == import.module }), MethodHandle::bindTo.invokeVirtual() ) // Bind the getter WasmExternalKind.GLOBAL -> func.addInsns( LdcInsnNode(ctx.resolveImportHandle(import)), VarInsnNode(Opcodes.ALOAD, 1 + params.indexOfFirst { it.name == import.module }), MethodHandle::bindTo.invokeVirtual() ) // Invoke to get handle array // TODO: for imported table, fail if import.size < limits.init * page size at runtime // TODO: for imported table, fail if import.size > limits.max * page size at runtime WasmExternalKind.TABLE -> func.addInsns( VarInsnNode(Opcodes.ALOAD, 1 + params.indexOfFirst { it.name == import.module }), ctx.resolveImportHandle(import).let { tblGet -> MethodInsnNode(Opcodes.INVOKEVIRTUAL, tblGet.owner, tblGet.name, tblGet.desc, false) } ) } } } // Now with all items on the stack we can instantiate and return func = func.addInsns( TypeInsnNode(Opcodes.NEW, mod.ref.asmName), InsnNode(Opcodes.DUP), MethodInsnNode( Opcodes.INVOKESPECIAL, mod.ref.asmName, "<init>", constructor.ref.asmDesc, false ), InsnNode(Opcodes.ARETURN) ) ctx.cls.methods.plusAssign(func.toMethodNode()) } fun addInstanceField(ctx: Context, mod: ModuleClass) { // Simple protected field that is lazily populated (but doesn't need to be volatile) ctx.cls.fields.plusAssign( FieldNode(Opcodes.ACC_PROTECTED, "instance" + mod.name.javaIdent.capitalize(), mod.ref.asmDesc, null, null) ) } fun addInstanceMethod(ctx: Context, mod: ModuleClass) { // The instance method accepts no parameters. It lazily populates a field by calling the // creation method. The parameters for the creation method are the imports that are // accessed via their instance methods. The entire method is synchronized as that is the // most straightforward way to thread-safely lock the lazy population for now. val params = mod.importClasses(ctx) var func = Func( access = Opcodes.ACC_PUBLIC + Opcodes.ACC_SYNCHRONIZED, name = mod.name.javaIdent, ret = mod.ref ) val alreadyThereLabel = LabelNode() func = func.addInsns( VarInsnNode(Opcodes.ALOAD, 0), FieldInsnNode(Opcodes.GETFIELD, ctx.cls.name, "instance" + mod.name.javaIdent.capitalize(), mod.ref.asmDesc), JumpInsnNode(Opcodes.IFNONNULL, alreadyThereLabel), VarInsnNode(Opcodes.ALOAD, 0) ) func = params.fold(func) { func, importMod -> func.addInsns( VarInsnNode(Opcodes.ALOAD, 0), MethodInsnNode(Opcodes.INVOKEVIRTUAL, importMod.ref.asmName, importMod.name.javaIdent, importMod.ref.asMethodRetDesc(), false) ) } func = func.addInsns( FieldInsnNode(Opcodes.PUTFIELD, ctx.cls.name, "instance" + mod.name.javaIdent.capitalize(), mod.ref.asmDesc), alreadyThereLabel, VarInsnNode(Opcodes.ALOAD, 0), FieldInsnNode(Opcodes.GETFIELD, ctx.cls.name, "instance" + mod.name.javaIdent.capitalize(), mod.ref.asmDesc), InsnNode(Opcodes.ARETURN) ) ctx.cls.methods.plusAssign(func.toMethodNode()) } class ModuleClass(val cls: Class<*>, overrideName: String? = null) { val name = overrideName ?: cls.getDeclaredAnnotation(WasmModule::class.java)?.name ?: error("No module name available for class $cls") val ref = TypeRef(Type.getType(cls)) fun importClasses(ctx: Context): List<ModuleClass> { // Try to find constructor with mem class first, otherwise there should be only one val constructorWithImports = cls.constructors.find { it.parameters.firstOrNull()?.type?.ref == ctx.mem.memType } ?: cls.constructors.singleOrNull() ?: error("Unable to find suitable constructor for $cls") return constructorWithImports.parameters.toList().mapNotNull { it.getAnnotation(WasmImport::class.java)?.module }.distinct().map(ctx::namedModuleClass) } } data class Context( val classes: List<ModuleClass>, val className: String, val cls: ClassNode = ClassNode().also { it.name = className.replace('.', '/') }, val mem: Mem = ByteBufferMem, val defaultMaxMemPages: Int = 10 ) { fun namedModuleClass(name: String) = classes.find { it.name == name } ?: error("No module named '$name'") fun resolveImportMethod(import: WasmImport) = namedModuleClass(import.module).cls.methods.find { method -> method.getAnnotation(WasmExport::class.java)?.value == import.field && method.ref.asmDesc == import.desc } ?: error("Unable to find export named '${import.field}' in module '${import.module}'") fun resolveImportHandle(import: WasmImport) = resolveImportMethod(import).let { method -> Handle(Opcodes.INVOKEVIRTUAL, method.declaringClass.ref.asmName, method.name, method.ref.asmDesc, false) } } companion object : Linker() }
mit
684f62748d46961f3cfad1cb1904a35b
45.270492
119
0.581274
4.799745
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/lists/Memberships.kt
1
6785
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.lists import jp.nephy.penicillin.core.request.action.CursorJsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.Lists import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.models.cursor.CursorLists /** * Returns the lists the specified user has been added to. If user_id or screen_name are not provided, the memberships for the authenticating user are returned. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships) * * @param count The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. * @param cursor Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. It is recommended to always use cursors when the method supports them. See [Cursoring](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param filterToOwnedLists When set to true , t or 1 , will return just lists the authenticating user owns, and the user represented by user_id or screen_name is a member of. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorLists] model. */ fun Lists.memberships( count: Int? = null, cursor: Long? = null, filterToOwnedLists: Boolean? = null, vararg options: Option ) = membershipsInternal(null, null, count, cursor, filterToOwnedLists, *options) /** * Returns the lists the specified user has been added to. If user_id or screen_name are not provided, the memberships for the authenticating user are returned. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships) * * @param userId The ID of the user for whom to return results. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param count The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. * @param cursor Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. It is recommended to always use cursors when the method supports them. See [Cursoring](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param filterToOwnedLists When set to true , t or 1 , will return just lists the authenticating user owns, and the user represented by user_id or screen_name is a member of. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorLists] model. */ fun Lists.membershipsByUserId( userId: Long, count: Int? = null, cursor: Long? = null, filterToOwnedLists: Boolean? = null, vararg options: Option ) = membershipsInternal(userId, null, count, cursor, filterToOwnedLists, *options) /** * Returns the lists the specified user has been added to. If user_id or screen_name are not provided, the memberships for the authenticating user are returned. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships) * * @param screenName The screen name of the user for whom to return results. Helpful for disambiguating when a valid screen name is also a user ID. * @param count The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. * @param cursor Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. It is recommended to always use cursors when the method supports them. See [Cursoring](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param filterToOwnedLists When set to true , t or 1 , will return just lists the authenticating user owns, and the user represented by user_id or screen_name is a member of. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorLists] model. */ fun Lists.membershipsByScreenName( screenName: String, count: Int? = null, cursor: Long? = null, filterToOwnedLists: Boolean? = null, vararg options: Option ) = membershipsInternal(null, screenName, count, cursor, filterToOwnedLists, *options) private fun Lists.membershipsInternal( userId: Long? = null, screenName: String? = null, count: Int? = null, cursor: Long? = null, filterToOwnedLists: Boolean? = null, vararg options: Option ) = client.session.get("/1.1/lists/memberships.json") { parameters( "user_id" to userId, "screen_name" to screenName, "count" to count, "cursor" to cursor, "filter_to_owned_lists" to filterToOwnedLists, *options ) }.cursorJsonObject<CursorLists>() /** * Shorthand property to [Lists.memberships]. * @see Lists.memberships */ val Lists.memberships get() = memberships()
mit
5c2c3437250e041b6228eb8db3b019ed
55.541667
380
0.755048
4.243277
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/shows/tools/ShowStatus.kt
1
2947
package com.battlelancer.seriesguide.shows.tools import android.content.Context import android.widget.TextView import androidx.core.content.ContextCompat import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.util.Utils /** * Show status valued as stored in the database in [com.battlelancer.seriesguide.provider.SeriesGuideContract.Shows.STATUS]. */ // Compare with https://www.themoviedb.org/bible/tv#59f7403f9251416e7100002b // Note: used to order shows by status, so ensure similar are next to each other. interface ShowStatus { companion object { const val IN_PRODUCTION = 5 const val PILOT = 4 const val PLANNED = 2 /** * Episodes are to be released. */ const val RETURNING = 1 /** * Typically all episodes released, with a planned ending. */ const val ENDED = 0 const val UNKNOWN = -1 /** * Typically all episodes released, but abruptly ended. */ const val CANCELED = -2 /** * Decodes the [ShowTools.Status] and returns the localized text representation. * May be `null` if status is unknown. */ fun getStatus(context: Context, encodedStatus: Int): String? { return when (encodedStatus) { IN_PRODUCTION -> context.getString(R.string.show_status_in_production) PILOT -> context.getString(R.string.show_status_pilot) CANCELED -> context.getString(R.string.show_status_canceled) PLANNED -> context.getString(R.string.show_isUpcoming) RETURNING -> context.getString(R.string.show_isalive) ENDED -> context.getString(R.string.show_isnotalive) else -> { // status unknown, display nothing null } } } /** * Gets the show status from [getStatus] and sets a status dependant text color on the * given view. * * @param encodedStatus Detection based on [ShowStatus]. */ fun setStatusAndColor(view: TextView, encodedStatus: Int) { view.text = getStatus(view.context, encodedStatus) if (encodedStatus == RETURNING) { view.setTextColor( ContextCompat.getColor( view.context, Utils.resolveAttributeToResourceId( view.context.theme, R.attr.colorSecondary ) ) ) } else { view.setTextColor( ContextCompat.getColor( view.context, Utils.resolveAttributeToResourceId( view.context.theme, android.R.attr.textColorSecondary ) ) ) } } } }
apache-2.0
e15573a5db287100ee4f893f4f965c96
34.95122
124
0.561249
4.969646
false
false
false
false
AlekseyZhelo/LBM
LWJGL_APP/src/main/java/com/alekseyzhelo/lbm/gui/lwjgl/color/colormap/DiscreteColormaps.kt
1
1116
package com.alekseyzhelo.lbm.gui.lwjgl.color.colormap import com.alekseyzhelo.lbm.gui.lwjgl.color.FloatColor import com.alekseyzhelo.lbm.gui.lwjgl.util.ResourcesUtil /** * @author Aleks on 03-07-2016. */ object CoolwarmDiscreteColormap : Colormap { private val r: FloatArray private val g: FloatArray private val b: FloatArray private val range: Int init { val fileEntries = ResourcesUtil.loadCSVResource("/colormaps/CoolWarmFloat257.csv") val skippedFirst = fileEntries.subList(1, fileEntries.size) range = skippedFirst.size - 1 r = FloatArray(range + 1) g = FloatArray(range + 1) b = FloatArray(range + 1) for (i in 0..range) { r[i] = skippedFirst[i][1].toFloat() g[i] = skippedFirst[i][2].toFloat() b[i] = skippedFirst[i][3].toFloat() } } override fun getColor(normalized: Float): FloatColor { val index = (normalized * range).toInt() return FloatColor(r[index], g[index], b[index]) } override fun getName(): String { return "coolwarm" } }
apache-2.0
6f0ff043fd4f3fa754bb483a610b3971
26.925
90
0.629928
3.848276
false
false
false
false
michaeimm/kmn_bot-tool
app/src/main/java/tw/shounenwind/kmnbottool/skeleton/BaseActivity.kt
1
4503
package tw.shounenwind.kmnbottool.skeleton import android.annotation.SuppressLint import android.app.ActivityOptions import android.content.Intent import android.os.Build import android.util.Pair import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.google.android.material.appbar.AppBarLayout import kotlinx.coroutines.* import tw.shounenwind.kmnbottool.R import tw.shounenwind.kmnbottool.util.LogUtil import tw.shounenwind.kmnbottool.widget.ProgressDialog @SuppressLint("Registered") open class BaseActivity : AppCompatActivity() { private var progressDialog: ProgressDialog? = null protected var mainScope: CoroutineScope? = MainScope() override fun setContentView(layoutResID: Int) { super.setContentView(layoutResID) bindToolbar() } override fun setContentView(view: View?) { super.setContentView(view) bindToolbar() } override fun setContentView(view: View?, params: ViewGroup.LayoutParams?) { super.setContentView(view, params) bindToolbar() } private fun bindToolbar(){ findViewById<Toolbar>(R.id.toolbar)?.apply { setSupportActionBar(this) } } fun bindToolbarHomeButton(){ supportActionBar?.apply { setHomeButtonEnabled(true) setDisplayHomeAsUpEnabled(true) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> { super.onOptionsItemSelected(item) } } } fun startActivityWithTransition(intent: Intent) { val appBarLayout = findViewById<AppBarLayout>(R.id.appbar) if (appBarLayout != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT != Build.VERSION_CODES.N && Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1) { val options = ActivityOptions.makeSceneTransitionAnimation( this, appBarLayout, appBarLayout.transitionName ) startActivity(intent, options.toBundle()) } else { startActivity(intent) } } fun startActivityWithTransition(intent: Intent, vararg pairs: Pair<View, String>) { val appBarLayout = findViewById<AppBarLayout>(R.id.appbar) if (appBarLayout != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT != Build.VERSION_CODES.N && Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1) { val options = ActivityOptions.makeSceneTransitionAnimation( this, Pair.create(appBarLayout, appBarLayout.transitionName), *pairs ) startActivity(intent, options.toBundle()) } else { startActivity(intent) } } fun startActivityForResultWithTransition(intent: Intent, responseCode: Int) { val appBarLayout = findViewById<AppBarLayout>(R.id.appbar) if (appBarLayout != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT != Build.VERSION_CODES.N && Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1) { val options = ActivityOptions.makeSceneTransitionAnimation( this, appBarLayout, appBarLayout.transitionName ) startActivityForResult(intent, responseCode, options.toBundle()) } else { startActivityForResult(intent, responseCode) } } protected suspend fun showProgressDialog(text: String) = withContext(Dispatchers.Main) { progressDialog = ProgressDialog(this@BaseActivity).apply { setContent(text) setCancelable(false) show() } } protected suspend fun dismissProgressDialog() = withContext(Dispatchers.Main) { LogUtil.catchAndPrint { progressDialog!!.dismiss() } } override fun onDestroy() { mainScope?.cancel() mainScope = null super.onDestroy() } }
apache-2.0
6c1946b5ff75562177f9e691e1aca0af
32.362963
92
0.618254
5.279015
false
false
false
false
santirivera92/wtnv-android
app/src/main/java/com/razielsarafan/wtnv/controller/fragment/TranscriptFragment.kt
1
2151
package com.razielsarafan.wtnv.controller.fragment import android.os.Bundle import android.support.v4.app.Fragment import android.text.Html import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.razielsarafan.wtnv.R import com.razielsarafan.wtnv.api.WTNVApi import com.razielsarafan.wtnv.model.Transcript import retrofit.Callback import retrofit.RetrofitError import retrofit.client.Response class TranscriptFragment : Fragment(), Callback<Transcript> { private var textViewTranscript: TextView? = null private var transcript: String? = null private var transcriptId: String = "" override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater!!.inflate(R.layout.fragment_transcript, container, false) textViewTranscript = v.findViewById(R.id.textViewTranscript) as TextView textViewTranscript?.movementMethod = LinkMovementMethod.getInstance() WTNVApi.getInstance(activity).getTranscriptForInterface(transcriptId, this) bind() return v } override fun success(s: Transcript, response: Response?) { transcript = "<br>${s.value}<br>${cecilspeaks}<br>".replace("\n", "<br>") bind() } private fun bind() { if (transcript != null && textViewTranscript != null) { textViewTranscript?.text = Html.fromHtml(transcript) } } override fun failure(error: RetrofitError) { error.printStackTrace() } companion object { private val cecilspeaks = "These transcripts have been kindly made by <a href=\"http://cecilspeaks.tumblr.com\">tumblr user cecilspeaks</a>. It would probably be cool if you followed them or sent them some thank you notes, as they gave me permission to use them free of charge." fun getInstance(transcriptId: String): TranscriptFragment { val fragment = TranscriptFragment() fragment.transcriptId = transcriptId return fragment } } }
gpl-2.0
ca1ecccc900fcd664b6a31bac1cdb367
36.086207
286
0.717806
4.371951
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-rolling-bukkit/src/main/kotlin/com/rpkit/rolling/bukkit/command/turnorder/TurnOrderRemoveCommand.kt
1
2827
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.rolling.bukkit.command.turnorder import com.rpkit.core.command.RPKCommandExecutor import com.rpkit.core.command.result.* import com.rpkit.core.command.sender.RPKCommandSender import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import com.rpkit.rolling.bukkit.RPKRollingBukkit import com.rpkit.rolling.bukkit.command.result.InvalidTurnOrderFailure import com.rpkit.rolling.bukkit.turnorder.RPKTurnOrderService import java.util.concurrent.CompletableFuture class TurnOrderRemoveCommand(private val plugin: RPKRollingBukkit) : RPKCommandExecutor { override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<out CommandResult> { if (!sender.hasPermission("rpkit.rolling.command.turnorder.remove")) { sender.sendMessage(plugin.messages.noPermissionTurnOrderRemove) return CompletableFuture.completedFuture(NoPermissionFailure("rpkit.rolling.command.turnorder.remove")) } if (args.isEmpty()) { sender.sendMessage(plugin.messages.turnOrderRemoveUsage) return CompletableFuture.completedFuture(IncorrectUsageFailure()) } val turnOrderService = Services[RPKTurnOrderService::class.java] if (turnOrderService == null) { sender.sendMessage(plugin.messages.noTurnOrderService) return CompletableFuture.completedFuture(MissingServiceFailure(RPKTurnOrderService::class.java)) } var argOffset = 0 var turnOrder = if (args.size > 1) { turnOrderService.getTurnOrder(args[0]) } else null if (turnOrder == null && sender is RPKMinecraftProfile) { turnOrder = turnOrderService.getActiveTurnOrder(sender) } else { argOffset = 1 } if (turnOrder == null) { sender.sendMessage(plugin.messages.turnOrderRemoveInvalidTurnOrder) return CompletableFuture.completedFuture(InvalidTurnOrderFailure()) } args.drop(argOffset).forEach(turnOrder::remove) sender.sendMessage(plugin.messages.turnOrderRemoveValid) return CompletableFuture.completedFuture(CommandSuccess) } }
apache-2.0
da28c1af24629161b151d30753b100c2
45.360656
117
0.732932
4.727425
false
false
false
false
rori-dev/lunchbox
backend-spring-kotlin/src/main/kotlin/lunchbox/domain/resolvers/LunchResolverAokCafeteria.kt
1
3981
package lunchbox.domain.resolvers import lunchbox.domain.models.LunchOffer import lunchbox.domain.models.LunchProvider.AOK_CAFETERIA import lunchbox.util.date.DateValidator import lunchbox.util.html.HtmlParser import lunchbox.util.string.StringParser import org.jsoup.nodes.Element import org.springframework.stereotype.Component import java.net.URL import java.time.DayOfWeek import java.time.LocalDate import java.time.Month @Component class LunchResolverAokCafeteria( val dateValidator: DateValidator, val htmlParser: HtmlParser ) : LunchResolver { override val provider = AOK_CAFETERIA override fun resolve(): List<LunchOffer> = resolve(URL("${provider.menuUrl}/speiseplan/16/ajax/")) fun resolve(htmlUrl: URL): List<LunchOffer> { val site = htmlParser.parse(htmlUrl) val weekDates = site.select(".child") .mapNotNull { StringParser.parseLocalDate(it.text()) } .map { it.with(DayOfWeek.MONDAY) } val weekDivs = site.select("div[class*=child_menu]") val offers = mutableListOf<LunchOffer>() for ((date, weekDiv) in weekDates.zip(weekDivs)) offers += resolveByWeek(date, weekDiv) return offers } private fun resolveByWeek(date: LocalDate, weekDiv: Element): List<LunchOffer> { val day2node = weekDiv.children().chunked(2).filter { it.size > 1 } val offers = mutableListOf<LunchOffer>() for ((dayElem, offersDiv) in day2node) { val day = calcDay(dayElem, date) ?: return emptyList() offers += resolveByDay(day, offersDiv) } return offers } private fun calcDay(dateElem: Element, date: LocalDate): LocalDate? { val weekdayString = dateElem.select(".day").text() val weekday = Weekday.values().find { weekdayString.startsWith(it.label) } if (weekday != null) return date.plusDays(weekday.order) val shortDate = dateElem.select(".short-date").text() val year = if (shortDate.trim().endsWith("01.") && date.month == Month.DECEMBER) date.year + 1 else date.year return StringParser.parseLocalDate("$shortDate$year") } private fun resolveByDay(day: LocalDate, offersDiv: Element): List<LunchOffer> { val offerDivs = offersDiv.select(".day-usual") val offers = mutableListOf<LunchOffer>() for (offerElem in offerDivs) { val typ = offerElem.selectFirst("span")?.text() ?: "" val name = offerElem.select("span:nth-of-type(2)").text() if (!typ.contains("Tagesgericht") && !typ.contains("Menü")) continue if (name.isEmpty() || listOf("Ferien", "Betriebsferien", "Weihnachten", "Ostern", "Ostermontag", "Pfingstmontag").contains(name) ) continue val zusatzstoffe = offerElem.select("small").text() var (title, description) = StringParser.splitOfferName( name, listOf(" auf ", " mit ", " von ", " im ", " in ", " an ", ", ", " (", " und ") ) description = clearDescription(description) val tags = parseTags(name, typ, zusatzstoffe) offers += LunchOffer(0, title, description, day, null, tags, provider.id) } return offers } private fun clearDescription(description: String): String = description .replace(Regex("^, "), "") .replace("(", "") .replace(")", ",") .replace(Regex(",([^ ])"), ", $1") .replace(", , ", ", ") .trim() private fun parseTags(name: String, typ: String, zusatzstoffe: String): Set<String> { val result = mutableSetOf<String>() if (name.contains("vegan", ignoreCase = true)) result += "vegan" else if (name.contains("vegetarisch", ignoreCase = true) || zusatzstoffe.contains("V")) result += "vegetarisch" if (typ.contains("vorbestellen", ignoreCase = true)) result += "auf Vorbestellung" return result } enum class Weekday( val label: String, val order: Long ) { MONTAG("Mo", 0), DIENSTAG("Di", 1), MITTWOCH("Mi", 2), DONNERSTAG("Do", 3), FREITAG("Fr", 4); } }
mit
24a4df36aa424f1130b6679782d29263
31.096774
114
0.655276
3.716153
false
false
false
false
klose911/klose911.github.io
src/kotlin/src/tutorial/functional/Functions.kt
1
1836
package tutorial.functional fun foo(bar: Int = 0, baz: Int) { /*……*/ } fun foo(bar: Int = 0, baz: Int = 1, qux: () -> Unit) { /*……*/ } fun foo(vararg strings: String) { /*……*/ } fun double(x: Int) = x * 2 fun <T> asList(vararg ts: T): List<T> { val result = ArrayList<T>() for (t in ts) // ts is an Array result.add(t) return result } infix fun Int.shl(x: Int): Int { //…… return 1 } class MyStringCollection { infix fun add(s: String) { /*……*/ } fun build() { this add "abc" // 正确 add("abc") // 正确 //add "abc" // 错误:必须指定接收者 } } //fun dfs(graph: Graph) { // val visited = HashSet<Vertex>() // fun dfs(current: Vertex) { // if (!visited.add(current)) return // for (v in current.neighbors) // dfs(v) // } // // dfs(graph.vertices[0]) //} val eps = 1E-10 // "good enough", could be 10^-15 private fun findFixPointIteration(): Double { var x = 1.0 while (true) { val y = Math.cos(x) if (Math.abs(x - y) < eps) return x x = Math.cos(x) } } tailrec fun findFixPointTailRec(x: Double = 1.0): Double = if (Math.abs(x - Math.cos(x)) < eps) x else findFixPointTailRec(Math.cos(x)) fun main() { foo(baz = 1) // 使用默认值 bar = 0 foo(1) { println("hello") } // 使用默认值 baz = 1 foo(qux = { println("hello") }) // 使用两个默认值 bar = 0 与 baz = 1 foo { println("hello") } // 使用两个默认值 bar = 0 与 baz = 1 foo(strings = *arrayOf("a", "b", "c")) // 用中缀表示法调用该函数 1 shl 2 // 等同于这样 1.shl(2) println("normal iteration: " + findFixPointIteration()) println("tail recursion: " + findFixPointTailRec()) }
bsd-2-clause
8754f7c05faf67872da80c9ae03d9c35
19.047059
80
0.525822
2.968641
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/TriggeredCommand.kt
1
3168
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.gifs.GifSequenceWriter import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.MiscUtils import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.api.commands.Command import net.perfectdreams.loritta.morenitta.utils.extensions.readImage import java.awt.Color import java.awt.image.BufferedImage import java.io.File import javax.imageio.stream.FileImageOutputStream class TriggeredCommand(loritta: LorittaBot) : AbstractCommand(loritta, "triggered", category = net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { override fun getDescriptionKey() = LocaleKeyData("commands.command.triggered.description") override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY // TODO: Fix Usage override fun needsToUploadFiles(): Boolean { return true } override suspend fun run(context: CommandContext,locale: BaseLocale) { val contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; } val input = contextImage val triggeredLabel = readImage(File(LorittaBot.ASSETS, "triggered.png")) // scale val subtractW = input.width / 16 val subtractH = input.height / 16 val inputWidth = input.width - subtractW val inputHeight = input.height - subtractH // ogWidth --- input.width // ogHeight --- x val a1 = triggeredLabel.height * inputWidth val labelHeight = a1 / triggeredLabel.width val scaledTriggeredLabel = triggeredLabel.getScaledInstance(inputWidth, labelHeight, BufferedImage.SCALE_SMOOTH) val base = BufferedImage(inputWidth, inputHeight + scaledTriggeredLabel.getHeight(null), BufferedImage.TYPE_INT_ARGB) val tint = BufferedImage(base.width, inputHeight, BufferedImage.TYPE_INT_ARGB) val color = Color(255, 0, 0, 60) val graphics = base.graphics val tintGraphics = tint.graphics tintGraphics.color = color tintGraphics.fillRect(0, 0, tint.width, tint.height) var fileName = LorittaBot.TEMP + "triggered-" + System.currentTimeMillis() + ".gif" val outputFile = File(fileName) var output = FileImageOutputStream(outputFile) val writer = GifSequenceWriter(output, BufferedImage.TYPE_INT_ARGB, 4, true) for (i in 0..5) { var offsetX = LorittaBot.RANDOM.nextInt(0, subtractW) var offsetY = LorittaBot.RANDOM.nextInt(0, subtractH) val subimage = input.getSubimage(offsetX, offsetY, inputWidth, inputHeight) graphics.drawImage(subimage, 0, 0, null) graphics.drawImage(tint, 0, 0, null) graphics.drawImage(scaledTriggeredLabel, 0, inputHeight, null) writer.writeToSequence(base) } writer.close() output.close() loritta.gifsicle.optimizeGIF(outputFile) context.sendFile(outputFile, "triggered.gif", context.getAsMention(true)) outputFile.delete() } }
agpl-3.0
93427953c83323913c4635973960e1c4
37.180723
162
0.785038
3.887117
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/counter/CounterUtils.kt
1
638
package net.perfectdreams.loritta.morenitta.utils.counter object CounterUtils { fun generatePrettyCounter(count: Int, list: List<String>, padding: Int): String { var counter = "" for (char in count.toString()) { val emote = list[char.toString().toInt()] counter += emote } val paddingCount = padding - count.toString().length if (paddingCount > 0) { for (i in 0 until paddingCount) { counter = list[0] + counter } } return counter } fun getEmojis(theme: CounterThemes): List<String> { return theme.emotes ?: throw UnsupportedOperationException("Theme ${theme.name} doesn't have emotes!") } }
agpl-3.0
4f067d60946a701b15a8a5440762b2e0
21.821429
104
0.684953
3.564246
false
false
false
false
vsch/SmartData
src/com/vladsch/smart/SmartCharArraySequence.kt
1
6451
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * 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 com.vladsch.smart import com.intellij.openapi.util.text.CharSequenceWithStringHash import com.intellij.util.text.CharSequenceBackedByArray /** * NOTE: if original is not null then editing and non-raw access is directed to it though super class calls so that this * class doubles as a fast access proxy with tracking preserved because all affected requests will be directed to the original * */ open class SmartCharArraySequence(original: SmartCharSequenceBase<*>?, chars: CharArray, startIndex: Int = 0, endIndex: Int = chars.size) : SmartCharSequenceBase<SmartCharArraySequence>(), CharSequenceBackedByArray, CharSequenceWithStringHash { @JvmOverloads constructor(chars: CharArray, start: Int = 0, end: Int = chars.size) : this(null, chars, start, end) @JvmOverloads constructor(chars: String, start: Int = 0, end: Int = chars.length) : this(null, chars.toCharArray(), start, end) final protected val myOriginal: SmartCharSequenceBase<*>? = original final protected val myVersion: SmartVersion = if (original != null) SmartCacheVersion(original.version) else SmartImmutableVersion() final protected val myChars: CharArray = chars final protected val myStart: Int = startIndex final protected val myEnd: Int = endIndex init { if (myStart < 0 || myEnd > myChars.size) { throw IllegalArgumentException("TrackingCharArraySequence(chars, " + myStart + ", " + myEnd + ") is outside data source range [0, " + myChars.size + ")") } } override fun addStats(stats: SmartCharSequence.Stats) { stats.segments++ } /* * raw access, never via proxy or in proxy via original */ override fun properSubSequence(startIndex: Int, endIndex: Int): SmartCharArraySequence { return SmartCharArraySequence(myOriginal, myChars, myStart + startIndex, myStart + endIndex) } override fun charAtImpl(index: Int): Char = myChars[myStart + index] override fun getCharsImpl(dst: CharArray, dstOffset: Int) = getChars(dst, dstOffset) override fun getCharsImpl(): CharArray = chars override fun toString(): String { return String(myChars, myStart, myEnd - myStart) } // always on original override fun getCachedProxy(): SmartCharSequence = if (myOriginal != null) super.getCachedProxy() else this /* * use proxy if fresh otherwise raw access */ override val freshProxyOrNull: SmartCharArraySequence? get() = this override fun getChars(): CharArray { if (myStart == 0) return myChars val chars = CharArray(length) System.arraycopy(myChars, myStart, chars, 0, length) return chars } override fun getChars(dst: CharArray, dstOffset: Int) { // if (dstOffset + length > dst.size) { // val tmp = 0 // } System.arraycopy(myChars, myStart, dst, dstOffset, length) } override fun get(index: Int): Char = myChars[myStart + index] override fun subSequence(startIndex: Int, endIndex: Int): SmartCharArraySequence { if (myOriginal != null) return super.subSequence(startIndex, endIndex) checkBounds(startIndex, endIndex) if (startIndex == 0 && endIndex == length) return this return properSubSequence(startIndex, endIndex) } /* * Implementation */ override fun getVersion(): SmartVersion = myVersion override val length: Int get() = myEnd - myStart override fun trackedSourceLocation(index: Int): TrackedLocation { checkIndex(index) if (myOriginal != null) { val trackedLocation = myOriginal.trackedSourceLocation(index + myStart) if (myStart == 0) return trackedLocation return trackedLocation.withIndex(trackedLocation.index - myStart) .withPrevClosest(trackedLocation.prevIndex - myStart) .withNextClosest(trackedLocation.nextIndex - myStart) } return TrackedLocation(index, myStart + index, myChars) } override fun trackedLocation(source: Any?, offset: Int): TrackedLocation? { if (myOriginal != null) { val trackedLocation = myOriginal.trackedLocation(source, offset) if (trackedLocation != null && trackedLocation.index >= myStart && trackedLocation.index < myEnd) { if (myStart == 0) return trackedLocation return trackedLocation.withIndex(trackedLocation.index - myStart) .withPrevClosest(trackedLocation.prevIndex - myStart) .withNextClosest(trackedLocation.nextIndex - myStart) } } return if ((source == null || source === myChars) && offset >= myStart && offset < myEnd) TrackedLocation(offset - myStart, offset, myChars) else null } override fun splicedWith(other: CharSequence?): SmartCharSequence? { if (myOriginal != null) return myOriginal.splicedWith(other) if (other is SmartCharArraySequence) { if (myChars == other.myChars && myEnd == other.myStart) { return SmartCharArraySequence(myChars, myStart, other.myEnd) } } return null } override fun getMarkers(id: String?): List<TrackedLocation> { if (myOriginal != null) return myOriginal.getMarkers(id) return TrackedLocation.EMPTY_LIST } override fun reversed(): SmartCharSequence { if (myOriginal != null) return myOriginal.reversed() return SmartReversedCharSequence(myChars, myStart, myEnd) } }
apache-2.0
f753ab7d44072a7ee0e3664a430a6679
39.829114
244
0.681755
4.905703
false
false
false
false
pardom/redux-kotlin
lib/src/main/kotlin/redux/Middleware.kt
1
1707
package redux import redux.api.Dispatcher import redux.api.Reducer import redux.api.Store import redux.api.Store.Creator import redux.api.Store.Enhancer import redux.api.Store.Subscriber import redux.api.enhancer.Middleware /* * Copyright (C) 2016 Michael Pardo * * 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. */ fun <S : Any> applyMiddleware(vararg middlewares: Middleware<S>): Enhancer<S> { return Enhancer { next -> Creator { reducer, initialState -> object : Store<S> { private val store = next.create(reducer, initialState) private val rootDispatcher = middlewares.foldRight(store as Dispatcher) { middleware, next -> Dispatcher { action -> middleware.dispatch(this, next, action) } } override fun dispatch(action: Any) = rootDispatcher.dispatch(action) override fun getState() = store.state override fun replaceReducer(reducer: Reducer<S>) = store.replaceReducer(reducer) override fun subscribe(subscriber: Subscriber) = store.subscribe(subscriber) } } } }
apache-2.0
f05dac0a57170fb37ce20c7f8d7d5c7a
34.5625
109
0.661394
4.515873
false
false
false
false
luoyuan800/NeverEnd
dataModel/src/cn/luo/yuan/maze/model/dlc/SkillDLC.kt
1
1066
package cn.luo.yuan.maze.model.dlc import cn.luo.yuan.maze.model.IDModel import cn.luo.yuan.maze.model.goods.Goods import cn.luo.yuan.maze.model.skill.Skill import cn.luo.yuan.maze.utils.Field import cn.luo.yuan.maze.utils.StringUtils /** * Copyright @Luo * Created by Gavin Luo on 8/15/2017. */ class SkillDLC : SingleItemDLC, Cloneable { override fun getItem(): IDModel? { return skill } companion object { private const val serialVersionUID = Field.SERVER_VERSION } var skill: Skill? = null set(value){ field = value title = skill!!.name desc = skill!!.displayName } private var delete = false override fun isDelete(): Boolean { return delete } override fun markDelete() { delete = true } override var title: String = StringUtils.EMPTY_STRING override var desc: String = StringUtils.EMPTY_STRING override var debrisCost: Int = 0 override fun clone(): DLC { return super.clone() as SkillDLC } }
bsd-3-clause
ddd15dbe20fbf394ff14cc81a9371cda
21.680851
65
0.637899
3.876364
false
false
false
false
marvec/engine
lumeer-core/src/main/kotlin/io/lumeer/core/adapter/PusherAdapter.kt
2
14707
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.lumeer.core.adapter import io.lumeer.api.model.* import io.lumeer.api.model.Collection import io.lumeer.api.model.common.Resource import io.lumeer.core.facade.PusherFacade import io.lumeer.core.facade.PusherFacade.ObjectWithParent import io.lumeer.core.facade.PusherFacade.ResourceId import io.lumeer.storage.api.dao.CollectionDao import io.lumeer.storage.api.dao.LinkTypeDao import io.lumeer.storage.api.dao.ViewDao import org.marvec.pusher.data.BackupDataEvent import org.marvec.pusher.data.Event class PusherAdapter( private val appId: AppId?, private val facadeAdapter: FacadeAdapter, private val resourceAdapter: ResourceAdapter, private val permissionAdapter: PermissionAdapter, private val viewDao: ViewDao, private val linkTypeDao: LinkTypeDao, private val collectionDao: CollectionDao, ) { fun checkLinkTypePermissionsChange(organization: Organization, project: Project?, user: User, originalLinkType: LinkType, updatedLinkType: LinkType): List<Event> { val rolesDifference = permissionAdapter.getLinkTypeReadersDifference(organization, project, originalLinkType, updatedLinkType) val changedUsers = rolesDifference.changedUsers().toMutableSet().minus(user.id) val removedReadersNotifications = rolesDifference.removedUsers .map { userId -> createEventForRemove(originalLinkType.javaClass.simpleName, ResourceId(appId, originalLinkType.id, organization.id.orEmpty(), project?.id.orEmpty()), userId) } .toMutableList() if (changedUsers.isEmpty()) { return removedReadersNotifications } val allLinkTypes = linkTypeDao.allLinkTypes.filter { it.id != originalLinkType.id } val allViews = viewDao.allViews val allCollections = collectionDao.allCollections val linkTypesBefore = allLinkTypes.plus(originalLinkType) val linkTypesAfter = allLinkTypes.plus(updatedLinkType) changedUsers.forEach { userId -> removedReadersNotifications.addAll(createCollectionsChangeNotifications(organization, project, Pair(linkTypesBefore, linkTypesAfter), Pair(allCollections, allCollections), Pair(allViews, allViews), userId)) } return removedReadersNotifications } fun checkCollectionsPermissionsChange(organization: Organization, project: Project?, user: User, originalCollection: Collection, updatedCollection: Collection): List<Event> { val rolesDifference = permissionAdapter.getResourceReadersDifference(organization, project, originalCollection, updatedCollection) val changedUsers = rolesDifference.changedUsers().toMutableSet().minus(user.id) val removedReadersNotifications = rolesDifference.removedUsers .map { userId -> createEventForRemove(originalCollection.javaClass.simpleName, ResourceId(appId, originalCollection.id, organization.id.orEmpty(), project?.id.orEmpty()), userId) } .toMutableList() if (changedUsers.isEmpty()) { return removedReadersNotifications } val allLinkTypes = linkTypeDao.allLinkTypes val allViews = viewDao.allViews val allCollections = collectionDao.allCollections.filter { it.id != originalCollection.id } val collectionsBefore = allCollections.plus(originalCollection) val collectionsAfter = allCollections.plus(updatedCollection) changedUsers.forEach { userId -> removedReadersNotifications.addAll(createLinksChangeNotifications(organization, project, Pair(allLinkTypes, allLinkTypes), Pair(collectionsBefore, collectionsAfter), Pair(allViews, allViews), userId)) } return removedReadersNotifications } fun checkViewPermissionsChange(organization: Organization, project: Project?, user: User, originalView: View?, updatedView: View): List<Event> { if (originalView == null) { return listOf() } val rolesDifference = permissionAdapter.getResourceReadersDifference(organization, project, originalView, updatedView) val changedUsers = rolesDifference.changedUsers().toMutableSet().minus(user.id) val removedReadersNotifications = rolesDifference.removedUsers .map { userId -> createEventForRemove(originalView.javaClass.simpleName, ResourceId(appId, originalView.id, organization.id.orEmpty(), project?.id.orEmpty()), userId) } .toMutableList() if (changedUsers.isEmpty()) { return removedReadersNotifications } val allViews = viewDao.allViews.filter { it.id != originalView.id } val allCollections = collectionDao.allCollections val allLinkTypes = linkTypeDao.allLinkTypes val viewsBefore = allViews.plus(originalView) val viewsAfter = allViews.plus(updatedView) changedUsers.forEach { userId -> removedReadersNotifications.addAll(createCollectionsAndLinksChangeNotifications(organization, project, Pair(allLinkTypes, allLinkTypes), Pair(allCollections, allCollections), Pair(viewsBefore, viewsAfter), userId)) } return removedReadersNotifications } private fun createCollectionsChangeNotifications(organization: Organization, project: Project?, linkTypes: Pair<List<LinkType>, List<LinkType>>, collections: Pair<List<Collection>, List<Collection>>, views: Pair<List<View>, List<View>>, userId: String): List<Event> { val collectionsBefore = resourceAdapter.getAllCollections(organization, project, linkTypes.first, views.first, collections.first, userId).toMutableList() val collectionsAfter = resourceAdapter.getAllCollections(organization, project, linkTypes.second, views.second, collections.second, userId).toMutableList() val notifications = mutableListOf<Event>() val lostCollections = collectionsBefore.toMutableSet().minus(collectionsAfter) val gainedCollections = collectionsAfter.toMutableSet().minus(collectionsBefore) lostCollections.forEach { notifications.add(createEventForRemove(it.javaClass.simpleName, ResourceId(appId, it.id, organization.id.orEmpty(), project?.id.orEmpty()), userId)) } gainedCollections.forEach { notifications.add(createEventForWorkspaceObject(organization, project, filterUserRoles(organization, project, userId, it), it.id, PusherFacade.UPDATE_EVENT_SUFFIX, userId)) } return notifications } private fun createLinksChangeNotifications(organization: Organization, project: Project?, linkTypes: Pair<List<LinkType>, List<LinkType>>, collections: Pair<List<Collection>, List<Collection>>, views: Pair<List<View>, List<View>>, userId: String): List<Event> { val linkTypesBefore = resourceAdapter.getAllLinkTypes(organization, project, linkTypes.first, views.first, collections.first, userId).toMutableList() val linkTypesAfter = resourceAdapter.getAllLinkTypes(organization, project, linkTypes.second, views.second, collections.second, userId).toMutableList() val notifications = mutableListOf<Event>() val lostLinkTypes = linkTypesBefore.toMutableSet().minus(linkTypesAfter) val gainedLinkTypes = linkTypesAfter.toMutableSet().minus(linkTypesBefore) lostLinkTypes.forEach { notifications.add(createEventForRemove(it.javaClass.simpleName, ResourceId(appId, it.id, organization.id.orEmpty(), project?.id.orEmpty()), userId)) } gainedLinkTypes.forEach { notifications.add(createEventForWorkspaceObject(organization, project, filterUserRoles(organization, project, userId, it), it.id, PusherFacade.UPDATE_EVENT_SUFFIX, userId)) } return notifications } private fun createCollectionsAndLinksChangeNotifications(organization: Organization, project: Project?, linkTypes: Pair<List<LinkType>, List<LinkType>>, collections: Pair<List<Collection>, List<Collection>>, views: Pair<List<View>, List<View>>, userId: String): List<Event> { println("createCollectionsAndLinksChangeNotifications " + userId) return createCollectionsChangeNotifications(organization, project, linkTypes, collections, views, userId).plus(createLinksChangeNotifications(organization, project, linkTypes, collections, views, userId)) } fun createEvent(organization: Organization?, project: Project?, any: Any, event: String, userId: String): Event { return if (any is Document) { createEventForWorkspaceObject(organization, project, any, any.id, event, userId) } else if (any is LinkType) { createEventForWorkspaceObject(organization, project, any, any.id, event, userId) } else if (any is LinkInstance) { createEventForWorkspaceObject(organization, project, any, any.id, event, userId) } else if (any is Resource) { createEventForResource(organization, project, any, event, userId) } else if (any is ResourceComment) { createEventForWorkspaceObject(organization, project, any, any.id, event, userId) } else if (any is ObjectWithParent) { if (any.`object` is Resource) { createEventForNestedResource(organization, project, any, event, userId) } else { createEventForObjectWithParent(any, event, userId) } } else { createEventForObject(any, event, userId) } } fun createEventForWorkspaceObject(organization: Organization?, project: Project?, any: Any, id: String, event: String, userId: String): Event { val organizationId = organization?.id.orEmpty() val projectId = project?.id.orEmpty() if (PusherFacade.REMOVE_EVENT_SUFFIX == event) { return createEventForRemove(any.javaClass.simpleName, ResourceId(appId, id, organizationId, projectId), userId) } val normalMessage = if (any is LinkType) { ObjectWithParent(appId, filterUserRoles(organization, project, userId, any), organizationId, projectId) } else { ObjectWithParent(appId, any, organizationId, projectId) } val extraId = when (any) { is Document -> { any.collectionId } is LinkInstance -> { any.linkTypeId } is ResourceComment -> { any.resourceType.toString() + '/' + any.resourceId } else -> null } val alternateMessage = ResourceId(appId, id, organizationId, projectId, extraId) return createEventForObjectWithParent(normalMessage, alternateMessage, event, userId) } fun createEventForRemove(className: String, any: ResourceId, userId: String): Event { return Event(PusherFacade.eventChannel(userId), className + PusherFacade.REMOVE_EVENT_SUFFIX, any, null) } fun createEventForResource(organization: Organization?, project: Project?, resource: Resource, event: String, userId: String): Event { return if (PusherFacade.REMOVE_EVENT_SUFFIX == event) { createEventForRemove(resource.javaClass.simpleName, getResourceId(organization, project, resource), userId) } else createEventForObject(filterUserRoles(organization, project, userId, resource), getResourceId(organization, project, resource), event, userId) } fun createEventForObject(any: Any, event: String, userId: String): Event { return Event(eventChannel(userId), any.javaClass.simpleName + event, any) } fun createEventForObject(`object`: Any, backupObject: Any, event: String, userId: String): BackupDataEvent { return BackupDataEvent(eventChannel(userId), `object`.javaClass.simpleName + event, `object`, backupObject, null) } private fun createEventForNestedResource(organization: Organization?, project: Project?, objectWithParent: ObjectWithParent, event: String, userId: String): Event { val resource = objectWithParent.`object` as Resource if (PusherFacade.REMOVE_EVENT_SUFFIX == event) { return createEventForRemove(resource.javaClass.simpleName, getResourceId(organization, project, resource), userId) } val filteredResource = filterUserRoles(organization, project, userId, resource) val newObjectWithParent = ObjectWithParent(appId, filteredResource, objectWithParent.organizationId, objectWithParent.projectId) newObjectWithParent.correlationId = objectWithParent.correlationId return createEventForObjectWithParent(newObjectWithParent, getResourceId(organization, project, resource), event, userId) } fun createEventForObjectWithParent(objectWithParent: ObjectWithParent, event: String, userId: String): Event { return Event(eventChannel(userId), objectWithParent.`object`.javaClass.simpleName + event, objectWithParent) } fun createEventForObjectWithParent(objectWithParent: ObjectWithParent, backupObject: Any, event: String, userId: String): BackupDataEvent { return BackupDataEvent(eventChannel(userId), objectWithParent.`object`.javaClass.simpleName + event, objectWithParent, backupObject, null) } private fun getResourceId(organization: Organization?, project: Project?, resource: Resource): ResourceId { if (resource is Organization) { return ResourceId(appId, resource.getId(), null, null) } else if (resource is Project) { return ResourceId(appId, resource.getId(), organization?.id.orEmpty(), null) } return ResourceId(appId, resource.id, organization?.id.orEmpty(), project?.id.orEmpty()) } private fun <T : Resource> filterUserRoles(organization: Organization?, project: Project?, userId: String, resource: T): T { return facadeAdapter.mapResource(organization, project, resource.copy(), permissionAdapter.getUser(userId)) } private fun filterUserRoles(organization: Organization?, project: Project?, userId: String, linkType: LinkType): LinkType { return facadeAdapter.mapLinkType(organization, project, LinkType(linkType), permissionAdapter.getUser(userId)) } companion object { @JvmStatic fun eventChannel(userId: String): String { return PusherFacade.PRIVATE_CHANNEL_PREFIX + userId } } }
gpl-3.0
fd7eca95a76733b2a6505b73d45a0ca7
51.713262
278
0.741892
5.069631
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleTransposer.kt
2
2125
package com.cout970.magneticraft.systems.tilemodules import com.cout970.magneticraft.api.internal.pneumatic.PneumaticBuffer import com.cout970.magneticraft.misc.tileentity.getCap import com.cout970.magneticraft.misc.tileentity.shouldTick import com.cout970.magneticraft.misc.vector.createAABBUsing import com.cout970.magneticraft.misc.vector.toVec3d import com.cout970.magneticraft.misc.world.isClient import com.cout970.magneticraft.registry.ITEM_HANDLER import com.cout970.magneticraft.systems.tileentities.IModule import com.cout970.magneticraft.systems.tileentities.IModuleContainer import net.minecraft.entity.item.EntityItem import net.minecraft.util.EnumFacing class ModuleTransposer( val buffer: PneumaticBuffer, val itemFilter: ModuleItemFilter, val facing: () -> EnumFacing, override val name: String = "module_transposer" ) : IModule { override lateinit var container: IModuleContainer override fun update() { if (world.isClient || buffer.blocked || !container.shouldTick(5)) return val frontPos = pos.offset(facing().opposite) val inventory = world.getCap(ITEM_HANDLER, frontPos, facing()) if (inventory != null) { for (slot in 0 until inventory.slots) { val stack = inventory.extractItem(slot, 64, true) if (stack.isEmpty) continue if (!itemFilter.filterAllowStack(stack)) continue buffer.add(inventory.extractItem(slot, 64, false)) return } return } val start = frontPos.toVec3d() val end = start.addVector(1.0, 1.0, 1.0) val aabb = start.createAABBUsing(end) val items = world.getEntitiesWithinAABB(EntityItem::class.java, aabb) .filter { !it.isDead } .toMutableSet() while (items.isNotEmpty()) { val target = items.first() if (itemFilter.filterAllowStack(target.item)) { buffer.add(target.item) target.setDead() break } items.remove(target) } } }
gpl-2.0
a3edae28edcd982bb09613431b9d1191
33.852459
80
0.664
4.327902
false
false
false
false
mp911de/lettuce
src/main/kotlin/io/lettuce/core/api/coroutines/RedisTransactionalCoroutinesCommandsImpl.kt
1
1652
/* * Copyright 2020-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.api.coroutines import io.lettuce.core.ExperimentalLettuceCoroutinesApi import io.lettuce.core.TransactionResult import io.lettuce.core.api.reactive.RedisTransactionalReactiveCommands import kotlinx.coroutines.reactive.awaitLast /** * Coroutine executed commands (based on reactive commands) for Transactions. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 */ @ExperimentalLettuceCoroutinesApi internal class RedisTransactionalCoroutinesCommandsImpl<K : Any, V : Any>(private val ops: RedisTransactionalReactiveCommands<K, V>) : RedisTransactionalCoroutinesCommands<K, V> { override suspend fun discard(): String = ops.discard().awaitLast() override suspend fun exec(): TransactionResult = ops.exec().awaitLast() override suspend fun multi(): String = ops.multi().awaitLast() override suspend fun watch(vararg keys: K): String = ops.watch(*keys).awaitLast() override suspend fun unwatch(): String = ops.unwatch().awaitLast() }
apache-2.0
8f090fde1a03b0c58b8fba78fbb350f2
34.148936
179
0.753027
4.393617
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl-integ-tests/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/GradleKotlinDslIntegrationTest.kt
1
26271
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.integration import okhttp3.HttpUrl import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.gradle.integtests.fixtures.RepoScriptBlockUtil.jcenterRepository import org.gradle.kotlin.dsl.embeddedKotlinVersion import org.gradle.kotlin.dsl.fixtures.DeepThought import org.gradle.kotlin.dsl.fixtures.LightThought import org.gradle.kotlin.dsl.fixtures.ZeroThought import org.gradle.kotlin.dsl.fixtures.containsMultiLineString import org.gradle.kotlin.dsl.support.normaliseLineSeparators import org.gradle.test.fixtures.dsl.GradleDsl import org.gradle.test.fixtures.file.LeaksFileHandles import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertNotEquals import org.junit.Test class GradleKotlinDslIntegrationTest : AbstractPluginIntegrationTest() { @Test fun `given a buildscript block, it will be used to compute the runtime classpath`() { checkBuildscriptBlockIsUsedToComputeRuntimeClasspathAfter { it } } @Test fun `given a buildscript block separated by CRLF, it will be used to compute the runtime classpath`() { checkBuildscriptBlockIsUsedToComputeRuntimeClasspathAfter { it.replace("\r\n", "\n").replace("\n", "\r\n") } } private fun checkBuildscriptBlockIsUsedToComputeRuntimeClasspathAfter(buildscriptTransformation: (String) -> String) { withClassJar("fixture.jar", DeepThought::class.java) withBuildScript(""" buildscript { dependencies { classpath(files("fixture.jar")) } } task("compute") { doLast { val computer = ${DeepThought::class.qualifiedName}() val answer = computer.compute() println("*" + answer + "*") } } """.let(buildscriptTransformation)) assert( build("compute").output.contains("*42*")) } @Test fun `given a script plugin with a buildscript block, it will be used to compute its classpath`() { withClassJar("fixture.jar", DeepThought::class.java) withFile("other.gradle.kts", """ buildscript { dependencies { classpath(files("fixture.jar")) } } task("compute") { doLast { val computer = ${DeepThought::class.qualifiedName}() val answer = computer.compute() println("*" + answer + "*") } } """) withBuildScript(""" apply(from = "other.gradle.kts") """) assert( build("compute").output.contains("*42*")) } @Test fun `given a buildSrc dir, it will be added to the compilation classpath`() { withFile("buildSrc/src/main/groovy/build/DeepThought.groovy", """ package build class DeepThought { def compute() { 42 } } """) withBuildScript(""" task("compute") { doLast { val computer = build.DeepThought() val answer = computer.compute() println("*" + answer + "*") } } """) assert( build("compute").output.contains("*42*")) } @Test fun `given a Kotlin project in buildSrc, it will be added to the compilation classpath`() { requireGradleDistributionOnEmbeddedExecuter() withKotlinBuildSrc() withFile("buildSrc/src/main/kotlin/build/DeepThought.kt", """ package build class DeepThought() { fun compute(handler: (Int) -> Unit) { handler(42) } } """) withFile("buildSrc/src/main/kotlin/build/DeepThoughtPlugin.kt", """ package build import org.gradle.api.* import org.gradle.kotlin.dsl.* class DeepThoughtPlugin : Plugin<Project> { override fun apply(project: Project) { project.run { task("compute") { doLast { DeepThought().compute { answer -> println("*" + answer + "*") } } } } } } """) withBuildScript(""" buildscript { // buildSrc types are available within buildscript // and must always be fully qualified build.DeepThought().compute { answer -> println("buildscript: " + answer) } } apply<build.DeepThoughtPlugin>() """) val output = build("compute").output assert(output.contains("buildscript: 42")) assert(output.contains("*42*")) } @Test fun `can compile against a different (but compatible) version of the Kotlin compiler`() { requireGradleDistributionOnEmbeddedExecuter() val differentKotlinVersion = "1.3.30" val expectedKotlinCompilerVersionString = "1.3.30" assertNotEquals(embeddedKotlinVersion, differentKotlinVersion) withBuildScript(""" import org.jetbrains.kotlin.config.KotlinCompilerVersion import org.jetbrains.kotlin.gradle.tasks.KotlinCompile buildscript { repositories { jcenter() } dependencies { classpath(kotlin("gradle-plugin", version = "$differentKotlinVersion")) } } apply(plugin = "kotlin") tasks.withType<KotlinCompile> { // can configure the Kotlin compiler kotlinOptions.suppressWarnings = true } task("print-kotlin-version") { doLast { val compileOptions = tasks.filterIsInstance<KotlinCompile>().joinToString(prefix="[", postfix="]") { it.name + "=" + it.kotlinOptions.suppressWarnings } println(KotlinCompilerVersion.VERSION + compileOptions) } } """) assertThat( build("print-kotlin-version").output, containsString("$expectedKotlinCompilerVersionString[compileKotlin=true, compileTestKotlin=true]")) } @Test fun `can apply base plugin via plugins block`() { withBuildScript(""" plugins { id("base") } task("plugins") { doLast { println(plugins.map { "*" + it::class.simpleName + "*" }) } } """) assertThat( build("plugins").output, containsString("*BasePlugin*")) } @Test fun `can use Closure only APIs`() { withBuildScript(""" gradle.buildFinished(closureOf<org.gradle.BuildResult> { println("*" + action + "*") // <- BuildResult.getAction() }) """) assert( build("build").output.contains("*Build*")) } @Test fun `given an exception thrown during buildscript block execution, its stack trace should contain correct file and line info`() { withBuildScript(""" // line 1 // line 2 // line 3 buildscript { // line 4 throw IllegalStateException() // line 5 } """) assertThat( buildFailureOutput(), containsString("build.gradle.kts:5")) } @Test fun `given a script with more than one buildscript block, it throws exception with offending block line number`() { withBuildScript(""" // line 1 buildscript {} // line 2 buildscript {} // line 3 """) assertThat( buildFailureOutput(), containsString("build.gradle.kts:3:13: Unexpected `buildscript` block found. Only one `buildscript` block is allowed per script.")) } @Test fun `given a script with more than one plugins block, it throws exception with offending block line number`() { withBuildScript(""" // line 1 plugins {} // line 2 plugins {} // line 3 """) assertThat( buildFailureOutput(), containsString("build.gradle.kts:3:13: Unexpected `plugins` block found. Only one `plugins` block is allowed per script.")) } @Test fun `given a buildscript block compilation error, it reports correct error location`() { assertCorrectLocationIsReportedForErrorIn("buildscript") } @Test fun `given a plugins block compilation error, it reports correct error location`() { assertCorrectLocationIsReportedForErrorIn("plugins") } private fun assertCorrectLocationIsReportedForErrorIn(block: String) { val buildFile = withBuildScript(""" $block { val module = "foo:bar:${'$'}fooBarVersion" } """) assertThat( buildFailureOutput("tasks"), containsString("e: $buildFile:3:44: Unresolved reference: fooBarVersion")) } @Test fun `sub-project build script inherits parent project compilation classpath`() { withClassJar("fixture.jar", DeepThought::class.java) withBuildScript(""" buildscript { dependencies { classpath(files("fixture.jar")) } } """) withSettings("include(\"sub-project\")") withBuildScriptIn("sub-project", """ task("compute") { doLast { val computer = ${DeepThought::class.qualifiedName}() val answer = computer.compute() println("*" + answer + "*") } } """) assert( build(":sub-project:compute").output.contains("*42*")) } @Test fun `given non-existing build script file name set in settings do not fail`() { withSettings("rootProject.buildFileName = \"does-not-exist.gradle.kts\"") build("help") } @Test fun `build with groovy settings and kotlin-dsl build script succeeds`() { withFile("settings.gradle", """ println 'Groovy DSL Settings' """) withBuildScript(""" println("Kotlin DSL Build Script") """) assertThat( build("help").output, allOf( containsString("Groovy DSL Settings"), containsString("Kotlin DSL Build Script"))) } @Test fun `build script can use jdk8 extensions`() { assumeJavaLessThan9() withBuildScript(""" // without kotlin-stdlib-jdk8 we get: // > Retrieving groups by name is not supported on this platform. val regex = Regex("(?<bla>.*)") val groups = regex.matchEntire("abc")?.groups println("*" + groups?.get("bla")?.value + "*") """) assertThat( build("help").output, containsString("*abc*")) } @Test fun `settings script can use buildscript dependencies`() { withSettings(""" buildscript { ${jcenterRepository(GradleDsl.KOTLIN)} dependencies { classpath("org.apache.commons:commons-lang3:3.6") } } println(org.apache.commons.lang3.StringUtils.reverse("Gradle")) """) assertThat( build("help").output, containsString("eldarG")) } @Test fun `script plugin can by applied to either Project or Settings`() { withFile("common.gradle.kts", """ println("Target is Settings? ${"$"}{Settings::class.java.isAssignableFrom(this::class.java)}") println("Target is Project? ${"$"}{Project::class.java.isAssignableFrom(this::class.java)}") """) withSettings(""" apply(from = "common.gradle.kts") """) assertThat( build("help").output, allOf( containsString("Target is Settings? true"), containsString("Target is Project? false"))) withSettings("") withBuildScript(""" apply(from = "common.gradle.kts") """) assertThat( build("help").output, allOf( containsString("Target is Settings? false"), containsString("Target is Project? true"))) } @Test fun `scripts can use the gradle script api`() { fun usageFor(target: String) = """ logger.error("Error logging from $target") require(logging is LoggingManager, { "logging" }) require(resources is ResourceHandler, { "resources" }) require(relativePath("src/../settings.gradle.kts") == "settings.gradle.kts", { "relativePath(path)" }) require(uri("settings.gradle.kts").toString().endsWith("settings.gradle.kts"), { "uri(path)" }) require(file("settings.gradle.kts").isFile, { "file(path)" }) require(files("settings.gradle.kts").files.isNotEmpty(), { "files(paths)" }) require(fileTree(".").contains(file("settings.gradle.kts")), { "fileTree(path)" }) require(copySpec {} != null, { "copySpec {}" }) require(mkdir("some").isDirectory, { "mkdir(path)" }) require(delete("some"), { "delete(path)" }) require(delete {} != null, { "delete {}" }) """ withSettings(usageFor("Settings")) withBuildScript(usageFor("Project")) assertThat( build("help").error, allOf( containsString("Error logging from Settings"), containsString("Error logging from Project"))) } @Test fun `automatically applies build scan plugin when --scan is provided on command-line and a script is applied in the buildscript block`() { withBuildScript(""" buildscript { rootProject.apply(from = rootProject.file("gradle/dependencies.gradle.kts")) } buildScan { termsOfServiceUrl = "https://gradle.com/terms-of-service" termsOfServiceAgree = "yes" } """) withFile("gradle/dependencies.gradle.kts") canPublishBuildScan() } @Test fun `can use shorthand notation for bound callable references with inline functions in build scripts`() { withBuildScript(""" fun foo(it: Any) = true // The inline modifier is important. This does not fail when this is no inline function. inline fun bar(f: (Any) -> Boolean) = print("*" + f(Unit) + "*") bar(::foo) """) assertThat( build().output, containsString("*true*")) } @Test fun `script compilation error message`() { val buildFile = withBuildScript("foo") assertThat( buildFailureOutput().normaliseLineSeparators(), containsString(""" FAILURE: Build failed with an exception. * Where: Build file '${buildFile.canonicalPath}' line: 1 * What went wrong: Script compilation error: Line 1: foo ^ Unresolved reference: foo 1 error """.replaceIndent()) ) } @Test fun `multiline script compilation error message`() { withBuildScript("publishing { }") assertThat( buildFailureOutput().normaliseLineSeparators(), containsString(""" * What went wrong: Script compilation errors: Line 1: publishing { } ^ Expression 'publishing' cannot be invoked as a function. The function 'invoke()' is not found Line 1: publishing { } ^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:${' '} public val PluginDependenciesSpec.publishing: PluginDependencySpec defined in org.gradle.kotlin.dsl 2 errors """.replaceIndent())) } @Test fun `multiple script compilation errors message`() { val buildFile = withBuildScript("println(foo)\n\n\n\n\nprintln(\"foo\").bar.bazar\n\n\n\nprintln(cathedral)") assertThat( buildFailureOutput().normaliseLineSeparators(), allOf( containsString(""" FAILURE: Build failed with an exception. * Where: Build file '${buildFile.canonicalPath}' line: 1 * What went wrong: Script compilation errors: """.replaceIndent()), containsString(""" | Line 01: println(foo) | ^ Unresolved reference: foo """.trimMargin()), containsString(""" | Line 06: println("foo").bar.bazar | ^ Unresolved reference: bar """.trimMargin()), containsString(""" | Line 10: println(cathedral) | ^ Unresolved reference: cathedral """.trimMargin()))) } @Test fun `given a remote buildscript, file paths are resolved relative to root project dir`() { val remoteScript = """ apply(from = "./gradle/answer.gradle.kts") """ withFile("gradle/answer.gradle.kts", """ val answer by extra { "42" } """) MockWebServer().use { server -> server.enqueue(MockResponse().setBody(remoteScript)) server.start() val remoteScriptUrl = server.safeUrl("/remote.gradle.kts") withBuildScript(""" apply(from = "$remoteScriptUrl") val answer: String by extra println("*" + answer + "*") """) assert(build().output.contains("*42*")) } } private fun MockWebServer.safeUrl(path: String, scheme: String = "http"): HttpUrl? { return HttpUrl.Builder() .scheme(scheme) .host("127.0.0.1") .port(port) .build() .resolve(path) } @Test fun `given a script from a jar, file paths are resolved relative to root project dir`() { val scriptFromJar = """ apply(from = "./gradle/answer.gradle.kts") """ withZip( "fixture.jar", sequenceOf("common.gradle.kts" to scriptFromJar.toByteArray())) withFile("gradle/answer.gradle.kts", """ val answer by extra { "42" } """) withBuildScript(""" buildscript { dependencies { classpath(files("fixture.jar")) } } apply(from = project.buildscript.classLoader.getResource("common.gradle.kts").toURI()) val answer: String by extra println("*" + answer + "*") """) assert(build().output.contains("*42*")) } @Test fun `script handler belongs to the current script`() { val init = withFile("some.init.gradle.kts", """ println("init: ${'$'}{initscript.sourceFile}") """) val settings = withSettings(""" println("settings: ${'$'}{buildscript.sourceFile}") """) val other = withFile("other.gradle.kts", """ println("other: ${'$'}{buildscript.sourceFile}") """) val main = withBuildScript(""" apply(from = "other.gradle.kts") println("main: ${'$'}{buildscript.sourceFile}") """) assertThat( build("-I", init.absolutePath, "help", "-q").output, containsMultiLineString(""" init: ${init.absolutePath} settings: ${settings.absolutePath} other: ${other.absolutePath} main: ${main.absolutePath} """)) } @Test fun `can cross configure buildscript`() { withClassJar("zero.jar", ZeroThought::class.java) withClassJar("light.jar", LightThought::class.java) withClassJar("deep.jar", DeepThought::class.java) val init = withFile("some.init.gradle.kts", """ projectsLoaded { rootProject.buildscript { dependencies { classpath(files("zero.jar")) } } } """) withSettings(""" include("sub") gradle.projectsLoaded { rootProject.buildscript { dependencies { classpath(files("light.jar")) } } } """) withBuildScript(""" project(":sub") { buildscript { dependencies { classpath(files("../deep.jar")) } } } """) withFile("sub/build.gradle.kts", """ task("think") { doLast { val zero = ${ZeroThought::class.qualifiedName}() val light = ${LightThought::class.qualifiedName}() val deep = ${DeepThought::class.qualifiedName}() println("*" + zero.compute() + "*") println("*" + light.compute() + "*") println("*" + deep.compute() + "*") } } """) assertThat( build("-I", init.absolutePath, ":sub:think").output, containsMultiLineString(""" *0* *23* *42* """)) } @Test @LeaksFileHandles("Kotlin Compiler Daemon working directory") fun `given generic extension types they can be accessed and configured`() { requireGradleDistributionOnEmbeddedExecuter() withDefaultSettingsIn("buildSrc") withFile("buildSrc/build.gradle.kts", """ plugins { `kotlin-dsl` } gradlePlugin { plugins { register("my") { id = "my" implementationClass = "my.MyPlugin" } } } $repositoriesBlock """) withFile("buildSrc/src/main/kotlin/my/MyPlugin.kt", """ package my import org.gradle.api.* import org.gradle.kotlin.dsl.* class Book(val name: String) class MyPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { extensions.add(typeOf<MutableMap<String, String>>(), "mapOfString", mutableMapOf("foo" to "bar")) extensions.add(typeOf<MutableMap<String, Int>>(), "mapOfInt", mutableMapOf("deep" to 42)) extensions.add(typeOf<NamedDomainObjectContainer<Book>>(), "books", container(Book::class)) } } """) withBuildScript(""" plugins { id("my") } configure<MutableMap<String, String>> { put("bazar", "cathedral") } require(the<MutableMap<String, String>>() == mapOf("foo" to "bar", "bazar" to "cathedral")) configure<MutableMap<String, Int>> { put("zero", 0) } require(the<MutableMap<String, Int>>() == mapOf("deep" to 42, "zero" to 0)) require(the<MutableMap<*, *>>() == mapOf("foo" to "bar", "bazar" to "cathedral")) configure<NamedDomainObjectContainer<my.Book>> { create("The Dosadi experiment") } require(the<NamedDomainObjectContainer<my.Book>>().size == 1) """) build("help") } @Test fun `can use kotlin java8 inline-only methods`() { withBuildScript(""" task("test") { doLast { println(project.properties.getOrDefault("non-existent-property", "default-value")) } } """) assertThat( build("-q", "test").output.trim(), equalTo("default-value") ) } @Test fun `can apply script plugin with package name`() { withFile("gradle/script.gradle.kts", """ package gradle task("ok") { doLast { println("ok!") } } """) withBuildScript(""" apply(from = "gradle/script.gradle.kts") """) assertThat( build("-q", "ok").output.trim(), equalTo("ok!") ) } }
apache-2.0
56d0cb6d56cba7bb7f3ad9b17b7c1114
29.512195
143
0.522553
5.407781
false
false
false
false
tom-kita/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/activity/AccountActivity.kt
1
8394
package com.bl_lia.kirakiratter.presentation.activity import android.os.Bundle import android.support.design.widget.AppBarLayout import android.support.design.widget.CollapsingToolbarLayout import android.support.design.widget.Snackbar import android.support.v4.content.ContextCompat import android.text.method.LinkMovementMethod import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewTreeObserver import com.bl_lia.kirakiratter.App import com.bl_lia.kirakiratter.R import com.bl_lia.kirakiratter.domain.entity.Account import com.bl_lia.kirakiratter.domain.entity.Relationship import com.bl_lia.kirakiratter.domain.extension.asHtml import com.bl_lia.kirakiratter.domain.extension.preparedErrorMessage import com.bl_lia.kirakiratter.presentation.fragment.AccountFragment import com.bl_lia.kirakiratter.presentation.internal.di.component.AccountComponent import com.bl_lia.kirakiratter.presentation.internal.di.component.DaggerAccountComponent import com.bl_lia.kirakiratter.presentation.internal.di.module.ActivityModule import com.bl_lia.kirakiratter.presentation.presenter.AccountPresenter import com.bl_lia.kirakiratter.presentation.transform.AvatarTransformation import com.squareup.picasso.Picasso import com.trello.rxlifecycle2.components.support.RxAppCompatActivity import io.reactivex.Single import jp.wasabeef.picasso.transformations.BlurTransformation import kotlinx.android.synthetic.main.activity_account.* import javax.inject.Inject class AccountActivity : RxAppCompatActivity() { companion object { val INTENT_PARAM_ACCOUNT = "intent_param_account" } @Inject lateinit var presenter: AccountPresenter private var relationship: Relationship? = null private var isOtherAccount: Boolean = false private val account: Single<Account> by lazy { presenter.verifyCredentials() .map { me -> if (intent.hasExtra(INTENT_PARAM_ACCOUNT)) { val account = intent.getSerializableExtra(INTENT_PARAM_ACCOUNT) as Account isOtherAccount = me.id != account.id account } else { me } } } private val component: AccountComponent by lazy{ DaggerAccountComponent.builder() .applicationComponent((application as App).component) .activityModule(ActivityModule(this)) .build() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_account) component.inject(this) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) if (savedInstanceState == null) { account.compose(bindToLifecycle()).subscribe { account, error -> supportFragmentManager.beginTransaction().apply { val fragment = AccountFragment.newInstance(account) replace(R.id.layout_list, fragment) }.commit() } } initView() } private fun initView() { account.subscribe { account, error -> if (error != null) { showError(error) return@subscribe } layout_appbar.addOnOffsetChangedListener(AppBarOffsetChangedListener(layout_collapsing_toolbar, account.preparedDisplayName ?: " ")) Picasso.with(this) .load(account.avatar) .transform(AvatarTransformation(ContextCompat.getColor(this, R.color.content_border))) .into(image_avatar) if (account.header?.isNotEmpty() ?: false) { Picasso.with(this) .load(account.header) .transform(BlurTransformation(this)) .into(image_header) } text_accont_name.text = account.preparedDisplayName text_account_description.text = account.note?.asHtml() text_account_description.movementMethod = LinkMovementMethod.getInstance() presenter.relationship(account) .subscribe { rel, error -> if (error != null) { showError(error) return@subscribe } relationship = rel text_followed_you.visibility = if (rel.followedBy) View.VISIBLE else View.GONE invalidateOptionsMenu() } image_header.viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { loadHeaderImage(image_header.width, image_header.height) image_header.viewTreeObserver.removeOnGlobalLayoutListener(this) } }) } } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { if (relationship != null && isOtherAccount) { if (relationship?.following ?: false) { menu?.removeItem(R.id.menu_follow) } else { menu?.removeItem(R.id.menu_unfollow) } } else { menu?.clear() } return super.onPrepareOptionsMenu(menu) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_account, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item != null) { when (item.itemId) { R.id.menu_follow -> { account.flatMap { account -> presenter.follow(account) }.subscribe { rel, error -> if (error != null) { showError(error) return@subscribe } relationship = rel invalidateOptionsMenu() } return true } R.id.menu_unfollow -> { account.flatMap { account -> presenter.unfollow(account) }.subscribe { rel, error -> if (error != null) { showError(error) return@subscribe } relationship = rel invalidateOptionsMenu() } return true } android.R.id.home -> { onBackPressed() return true } else -> return false } } else { return false } } private fun loadHeaderImage(width: Int, height: Int) { account.subscribe { account -> if (account.header?.isNotEmpty() ?: false) { Picasso.with(this) .load(account.header) .resize(width, height) .centerCrop() .transform(BlurTransformation(this)) .into(image_header) } } } private fun showError(error: Throwable) { Snackbar.make(layout_content, error.preparedErrorMessage(this), Snackbar.LENGTH_LONG).show() } internal class AppBarOffsetChangedListener(val collapsingLayout: CollapsingToolbarLayout, val title: String) : AppBarLayout.OnOffsetChangedListener { private var isShow: Boolean = false private var scrollRange: Int = -1 override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) { if (scrollRange == -1) { scrollRange = appBarLayout?.totalScrollRange ?: -1 } if (scrollRange + (verticalOffset) == 0) { collapsingLayout.title = title isShow = true } else { collapsingLayout.title = " " isShow = false } } } }
mit
ce59889ee896deb11bde9dabba714538
35.820175
153
0.571241
5.55894
false
false
false
false
mozilla-mobile/focus-android
app/src/androidTest/java/org/mozilla/focus/activity/robots/SearchRobot.kt
1
5821
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.activity.robots import androidx.test.uiautomator.By import androidx.test.uiautomator.UiSelector import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.mozilla.focus.R import org.mozilla.focus.helpers.TestHelper.getStringResource import org.mozilla.focus.helpers.TestHelper.mDevice import org.mozilla.focus.helpers.TestHelper.packageName import org.mozilla.focus.helpers.TestHelper.pressEnterKey import org.mozilla.focus.helpers.TestHelper.waitingTime import org.mozilla.focus.idlingResources.SessionLoadedIdlingResource class SearchRobot { fun verifySearchBarIsDisplayed() = assertTrue(searchBar.exists()) fun typeInSearchBar(searchString: String) { assertTrue(searchBar.waitForExists(waitingTime)) searchBar.clearTextField() searchBar.text = searchString } // Would you like to turn on search suggestions? Yes No // fresh install only fun allowEnableSearchSuggestions() { if (searchSuggestionsTitle.waitForExists(waitingTime)) { searchSuggestionsButtonYes.waitForExists(waitingTime) searchSuggestionsButtonYes.click() } } // Would you like to turn on search suggestions? Yes No // fresh install only fun denyEnableSearchSuggestions() { if (searchSuggestionsTitle.waitForExists(waitingTime)) { searchSuggestionsButtonNo.waitForExists(waitingTime) searchSuggestionsButtonNo.click() } } fun verifySearchSuggestionsAreShown() { suggestionsList.waitForExists(waitingTime) assertTrue(suggestionsList.childCount >= 1) } fun verifySearchSuggestionsAreNotShown() { assertFalse(suggestionsList.exists()) } fun verifySearchEditBarContainsText(text: String) { mDevice.findObject(UiSelector().textContains(text)).waitForExists(waitingTime) assertTrue(searchBar.text.equals(text)) } fun verifySearchEditBarIsEmpty() { searchBar.waitForExists(waitingTime) assertTrue(searchBar.text.equals(getStringResource(R.string.urlbar_hint))) } fun clickToolbar() { toolbar.waitForExists(waitingTime) toolbar.click() } fun longPressSearchBar() { searchBar.waitForExists(waitingTime) searchBar.longClick() } fun clearSearchBar() = clearSearchButton.click() fun verifySearchSuggestionsContain(title: String) { assertTrue( suggestionsList.getChild(UiSelector().textContains(title)).waitForExists(waitingTime), ) } class Transition { private lateinit var sessionLoadedIdlingResource: SessionLoadedIdlingResource fun loadPage(url: String, interact: BrowserRobot.() -> Unit): BrowserRobot.Transition { val geckoEngineView = mDevice.findObject(UiSelector().resourceId("$packageName:id/engineView")) val trackingProtectionDialog = mDevice.findObject(UiSelector().resourceId("$packageName:id/message")) sessionLoadedIdlingResource = SessionLoadedIdlingResource() searchScreen { typeInSearchBar(url) } pressEnterKey() runWithIdleRes(sessionLoadedIdlingResource) { assertTrue( BrowserRobot().progressBar.waitUntilGone(waitingTime), ) assertTrue( geckoEngineView.waitForExists(waitingTime) || trackingProtectionDialog.waitForExists(waitingTime), ) } BrowserRobot().interact() return BrowserRobot.Transition() } fun pasteAndLoadLink(interact: BrowserRobot.() -> Unit): BrowserRobot.Transition { var currentTries = 0 while (currentTries++ < 3) { try { mDevice.findObject(UiSelector().textContains("Paste")).waitForExists(waitingTime) val pasteText = mDevice.findObject(By.textContains("Paste")) pasteText.click() mDevice.pressEnter() break } catch (e: NullPointerException) { SearchRobot().longPressSearchBar() } } BrowserRobot().interact() return BrowserRobot.Transition() } } } fun searchScreen(interact: SearchRobot.() -> Unit): SearchRobot.Transition { SearchRobot().interact() return SearchRobot.Transition() } private val searchBar = mDevice.findObject(UiSelector().resourceId("$packageName:id/mozac_browser_toolbar_edit_url_view")) private val toolbar = mDevice.findObject(UiSelector().resourceId("$packageName:id/mozac_browser_toolbar_url_view")) private val searchSuggestionsTitle = mDevice.findObject( UiSelector() .resourceId("$packageName:id/enable_search_suggestions_title") .enabled(true), ) private val searchSuggestionsButtonYes = mDevice.findObject( UiSelector() .resourceId("$packageName:id/enable_search_suggestions_button") .enabled(true), ) private val searchSuggestionsButtonNo = mDevice.findObject( UiSelector() .resourceId("$packageName:id/disable_search_suggestions_button") .enabled(true), ) private val suggestionsList = mDevice.findObject( UiSelector() .resourceId("$packageName:id/search_suggestions_view"), ) private val clearSearchButton = mDevice.findObject(UiSelector().resourceId("$packageName:id/mozac_browser_toolbar_clear_view"))
mpl-2.0
dde5a91a69851122f7184b5ef3cff712
34.066265
127
0.678749
5.178826
false
false
false
false
JavaEden/OrchidCore
plugins/OrchidPosts/src/test/kotlin/com/eden/orchid/posts/PostsGeneratorTest.kt
1
7127
package com.eden.orchid.posts import com.eden.orchid.testhelpers.OrchidIntegrationTest import com.eden.orchid.testhelpers.nothingRendered import com.eden.orchid.testhelpers.pageWasRendered import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import strikt.api.expectThat @DisplayName("Tests page-rendering behavior of Posts generator") class PostsGeneratorTest : OrchidIntegrationTest(PostsModule()) { @Test @DisplayName("Files, formatted correctly in the `posts` directory, gets rendered correctly without any configuration.") fun test01() { resource("posts/2018-01-01-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/2018/1/1/post-one/index.html") } @Test @DisplayName("Files, formatted correctly in the `posts/{year}` directory, gets rendered correctly without any configuration.") fun test02() { resource("posts/2018/01-01-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/2018/1/1/post-one/index.html") } @Test @DisplayName("Files, formatted correctly in the `posts/{year}/{month}` directory, get rendered correctly without any configuration.") fun test03() { resource("posts/2018/01/01-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/2018/1/1/post-one/index.html") } @Test @DisplayName("Files, formatted correctly in the `posts/{year}/{month}/{day}` directory, get rendered correctly without any configuration.") fun test04() { resource("posts/2018/01/01/post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/2018/1/1/post-one/index.html") } @Test @DisplayName("The `permalink` can be set in a post's options.") fun test05() { resource("posts/2018-01-01-post-one.md", "", mapOf("permalink" to "blog/:year/:month/:slug")) val testResults = execute() expectThat(testResults).pageWasRendered("/blog/2018/1/post-one/index.html") } @Test @DisplayName("The `permalink` can be set in `defaultOptions`, which is applied to all posts by default.") fun test06() { configObject("posts", """{"defaultConfig": {"permalink": "blog/:year/:month/:slug"}}""") resource("posts/2018-01-01-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/blog/2018/1/post-one/index.html") } @Test @DisplayName("The `permalink` in a post's options overrides the one set in `defaultOptions`.") fun test07() { configObject("posts", """{"defaultConfig": {"permalink": "defaultConfig/:year/:month/:slug"}}""") resource("posts/2018-01-01-post-one.md", "", mapOf("permalink" to "postConfig/:year/:month/:slug")) val testResults = execute() expectThat(testResults).pageWasRendered("/postConfig/2018/1/post-one/index.html") } @Test @DisplayName("Posts supports multiple categories. Setting a category as a string value uses all category defaults.") fun tet08() { configObject("posts", """{"categories": ["cat1", "cat2"]}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/cat1/2018/1/1/post-one/index.html") expectThat(testResults).pageWasRendered("/cat2/2018/2/2/post-one/index.html") } @Test @DisplayName("Posts supports multiple categories. You can list each category as an Object to customize its options.") fun test09() { configObject("posts", """{"categories": [{"cat1": {}}, {"cat2": {}}]}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/cat1/2018/1/1/post-one/index.html") expectThat(testResults).pageWasRendered("/cat2/2018/2/2/post-one/index.html") } @Test @DisplayName("Posts supports multiple categories. Rather than a list for the categories, you can use a single Object, where each key points to the options for the value, to query easily.") fun test10() { configObject("posts", """ {"categories": {"cat1": {}, "cat2": {}}}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/cat1/2018/1/1/post-one/index.html") expectThat(testResults).pageWasRendered("/cat2/2018/2/2/post-one/index.html") } @Test @DisplayName("Categories can be hierarchical, by using a path rather than just a key.") fun test11() { configObject("posts", """{"categories": ["cat1", "cat1/cat2"]}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat1/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/cat1/2018/1/1/post-one/index.html") expectThat(testResults).pageWasRendered("/cat1/cat2/2018/2/2/post-one/index.html") } @Test @DisplayName("Hierarchical categories must have every category level individually-defined.") fun test12() { configObject("posts", """{"categories": ["cat1", "cat2/cat3"]}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat1/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).nothingRendered() } @Test @DisplayName("Authors can be specified both in post config, and as files in the 'posts/authors/' directory.") fun test13() { configObject("posts", """{"authors": ["author-one"]}""") resource("posts/authors/author-two.md", "", "{}") val testResults = execute() expectThat(testResults).pageWasRendered("/authors/author-one/index.html") expectThat(testResults).pageWasRendered("/authors/author-two/index.html") } @Test @DisplayName("Authors can be specified both in post config as objects as well as Strings.") fun test14() { configObject("posts", """{"authors": ["Author One", {"name": "Author Two", "email": "[email protected]"}]}""") val testResults = execute() expectThat(testResults).pageWasRendered("/authors/author-one/index.html") expectThat(testResults).pageWasRendered("/authors/author-two/index.html") } @Test @DisplayName("The Posts generator finishes successfully when there are no resources for it.") fun test15() { val testResults = execute() expectThat(testResults).nothingRendered() } @Test @DisplayName("The Wiki generator finishes successfully when there are no resources for it, when using multiple categories.") fun test16() { configObject("posts", """{"categories": ["cat1", "cat2/cat3"]}""") val testResults = execute() expectThat(testResults).nothingRendered() } }
mit
7a472b6fa5ea894bec56558d33e9ac20
40.196532
192
0.660446
4.095977
false
true
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/repositories/shows/TraktShowDataSource.kt
1
2760
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.repositories.shows import app.tivi.data.bodyOrThrow import app.tivi.data.entities.TiviShow import app.tivi.data.mappers.TraktShowToTiviShow import com.uwetrottmann.trakt5.enums.Extended import com.uwetrottmann.trakt5.enums.IdType import com.uwetrottmann.trakt5.enums.Type import com.uwetrottmann.trakt5.services.Search import com.uwetrottmann.trakt5.services.Shows import retrofit2.awaitResponse import javax.inject.Inject import javax.inject.Provider class TraktShowDataSource @Inject constructor( private val showService: Provider<Shows>, private val searchService: Provider<Search>, private val mapper: TraktShowToTiviShow ) : ShowDataSource { override suspend fun getShow(show: TiviShow): TiviShow { var traktId = show.traktId if (traktId == null && show.tmdbId != null) { // We need to fetch the search for the trakt id traktId = searchService.get() .idLookup( IdType.TMDB, show.tmdbId.toString(), Type.SHOW, Extended.NOSEASONS, 1, 1 ) .awaitResponse() .let { it.body()?.getOrNull(0)?.show?.ids?.trakt } } if (traktId == null) { traktId = searchService.get() .textQueryShow( show.title, null /* years */, null /* genres */, null /* lang */, show.country /* countries */, null /* runtime */, null /* ratings */, null /* certs */, show.network /* networks */, null /* status */, Extended.NOSEASONS, 1, 1 ) .awaitResponse() .let { it.body()?.firstOrNull()?.show?.ids?.trakt } } return if (traktId != null) { showService.get() .summary(traktId.toString(), Extended.FULL) .awaitResponse() .let { mapper.map(it.bodyOrThrow()) } } else { throw IllegalArgumentException("Trakt ID for show does not exist: [$show]") } } }
apache-2.0
93d7174d0e67c8ee6bd924b1281935c9
35.8
106
0.602899
4.638655
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsNamingInspection.kt
2
10877
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.inspections.fixes.RenameFix import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* /** * Base class for naming inspections. Implements the core logic of checking names * and registering problems. */ abstract class RsNamingInspection( val elementType: String, val styleName: String, val lint: RsLint, elementTitle: String = elementType ) : RsLocalInspectionTool() { val dispName = elementTitle + " naming convention" override fun getDisplayName() = dispName fun inspect(id: PsiElement?, holder: ProblemsHolder, fix: Boolean = true) { if (id == null) return val (isOk, suggestedName) = checkName(id.text) if (isOk || suggestedName == null || lint.levelFor(id) == RsLintLevel.ALLOW) return val fixEl = id.parent val fixes = if (fix && fixEl is PsiNamedElement) arrayOf(RenameFix(fixEl, suggestedName)) else emptyArray() holder.registerProblem( id, "$elementType `${id.text}` should have $styleName case name such as `$suggestedName`", *fixes) } abstract fun checkName(name: String): Pair<Boolean, String?> } /** * Checks if the name is CamelCase. */ open class RsCamelCaseNamingInspection( elementType: String, elementTitle: String = elementType ) : RsNamingInspection(elementType, "a camel", RsLint.NonCamelCaseTypes, elementTitle) { override fun checkName(name: String): Pair<Boolean, String?> { val str = name.trim('_') if (!str.isEmpty() && str[0].canStartWord && '_' !in str) { return Pair(true, null) } return Pair(false, if (str.isEmpty()) "CamelCase" else suggestName(name)) } private fun suggestName(name: String): String { val result = StringBuilder(name.length) var wasUnderscore = true var startWord = true for (char in name) { when { char == '_' -> wasUnderscore = true wasUnderscore || startWord && char.canStartWord -> { result.append(char.toUpperCase()) wasUnderscore = false startWord = false } else -> { startWord = char.isLowerCase() result.append(char.toLowerCase()) } } } return if (result.isEmpty()) "CamelCase" else result.toString() } private val Char.canStartWord: Boolean get() = isUpperCase() || isDigit() } /** * Checks if the name is snake_case. */ open class RsSnakeCaseNamingInspection(elementType: String) : RsNamingInspection(elementType, "a snake", RsLint.NonSnakeCase) { override fun checkName(name: String): Pair<Boolean, String?> { val str = name.trim('_') if (!str.isEmpty() && str.all { !it.isLetter() || it.isLowerCase() }) { return Pair(true, null) } return Pair(false, if (str.isEmpty()) "snake_case" else name.toSnakeCase(false)) } } /** * Checks if the name is UPPER_CASE. */ open class RsUpperCaseNamingInspection(elementType: String) : RsNamingInspection(elementType, "an upper", RsLint.NonUpperCaseGlobals) { override fun checkName(name: String): Pair<Boolean, String?> { val str = name.trim('_') if (!str.isEmpty() && str.all { !it.isLetter() || it.isUpperCase() }) { return Pair(true, null) } return Pair(false, if (str.isEmpty()) "UPPER_CASE" else name.toSnakeCase(true)) } } fun String.toSnakeCase(upper: Boolean): String { val result = StringBuilder(length + 3) // 3 is a reasonable margin for growth when `_`s are added result.append(takeWhile { it == '_' || it == '\'' }) // Preserve prefix var firstPart = true drop(result.length).splitToSequence('_').forEach pit@ { part -> if (part.isEmpty()) return@pit if (!firstPart) { result.append('_') } firstPart = false var newWord = false var firstWord = true part.forEach { char -> if (newWord && char.isUpperCase()) { if (!firstWord) { result.append('_') } newWord = false } else { newWord = char.isLowerCase() } result.append(if (upper) char.toUpperCase() else char.toLowerCase()) firstWord = false } } return result.toString() } // // Concrete inspections // class RsArgumentNamingInspection : RsSnakeCaseNamingInspection("Argument") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitPatBinding(el: RsPatBinding) { if (el.parent?.parent is RsValueParameter) { inspect(el.identifier, holder) } } } } class RsConstNamingInspection : RsUpperCaseNamingInspection("Constant") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitConstant(el: RsConstant) { if (el.kind == RsConstantKind.CONST) { inspect(el.identifier, holder) } } } } class RsStaticConstNamingInspection : RsUpperCaseNamingInspection("Static constant") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitConstant(el: RsConstant) { if (el.kind != RsConstantKind.CONST) { inspect(el.identifier, holder) } } } } class RsEnumNamingInspection : RsCamelCaseNamingInspection("Type", "Enum") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitEnumItem(el: RsEnumItem) = inspect(el.identifier, holder) } } class RsEnumVariantNamingInspection : RsCamelCaseNamingInspection("Enum variant") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitEnumVariant(el: RsEnumVariant) = inspect(el.identifier, holder) } } class RsFunctionNamingInspection : RsSnakeCaseNamingInspection("Function") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitFunction(el: RsFunction) { if (el.owner is RsFunctionOwner.Free) { inspect(el.identifier, holder) } } } } class RsMethodNamingInspection : RsSnakeCaseNamingInspection("Method") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitFunction(el: RsFunction) = when (el.owner) { is RsFunctionOwner.Trait, is RsFunctionOwner.Impl -> inspect(el.identifier, holder) else -> Unit } } } class RsLifetimeNamingInspection : RsSnakeCaseNamingInspection("Lifetime") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitLifetimeParameter(el: RsLifetimeParameter) = inspect(el, holder, false) } } class RsMacroNamingInspection : RsSnakeCaseNamingInspection("Macro") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitMacroDefinition(el: RsMacroDefinition) = inspect(el.nameIdentifier, holder, false) } } class RsModuleNamingInspection : RsSnakeCaseNamingInspection("Module") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitModDeclItem(el: RsModDeclItem) = inspect(el.identifier, holder) override fun visitModItem(el: RsModItem) = inspect(el.identifier, holder) } } class RsStructNamingInspection : RsCamelCaseNamingInspection("Type", "Struct") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitStructItem(el: RsStructItem) = inspect(el.identifier, holder) } } class RsFieldNamingInspection : RsSnakeCaseNamingInspection("Field") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitFieldDecl(el: RsFieldDecl) = inspect(el.identifier, holder) } } class RsTraitNamingInspection : RsCamelCaseNamingInspection("Trait") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTraitItem(el: RsTraitItem) = inspect(el.identifier, holder) } } class RsTypeAliasNamingInspection : RsCamelCaseNamingInspection("Type", "Type alias") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTypeAlias(el: RsTypeAlias) { if (el.owner is RsTypeAliasOwner.Free) { inspect(el.identifier, holder) } } } } class RsAssocTypeNamingInspection : RsCamelCaseNamingInspection("Type", "Associated type") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTypeAlias(el: RsTypeAlias) { if (el.owner is RsTypeAliasOwner.Trait) { inspect(el.identifier, holder, false) } } } } class RsTypeParameterNamingInspection : RsCamelCaseNamingInspection("Type parameter") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTypeParameter(el: RsTypeParameter) = inspect(el.identifier, holder) } } class RsVariableNamingInspection : RsSnakeCaseNamingInspection("Variable") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitPatBinding(el: RsPatBinding) { val pattern = PsiTreeUtil.getTopmostParentOfType(el, RsPat::class.java) ?: return when (pattern.parent) { is RsLetDecl -> inspect(el.identifier, holder) } } } }
mit
848b3c23227b39c67523dc3d4b1addd0
35.996599
135
0.628022
4.844989
false
false
false
false
gyulavoros/kotlin-todomvc
frontend/src/main/kotlin/co/makery/todomvc/frontend/template.kt
1
885
package co.makery.todomvc.frontend import kotlinx.html.* import kotlinx.html.dom.create import kotlinx.html.js.li import org.w3c.dom.HTMLElement import kotlin.browser.document class Template { private fun defaultTemplate(todo: Todo): HTMLElement = document.create.li { val completed = if (todo.completed) "completed" else "" attributes.put("data-id", todo.id) classes += completed div(classes = "view") { checkBoxInput(classes = "toggle") { checked = todo.completed } label { +todo.title } button(classes = "destroy") } } fun show(todos: List<Todo>): String = todos.joinToString("\n", transform = { todo -> defaultTemplate(todo).outerHTML }) fun itemCounter(activeCount: Int): String { val plural = if (activeCount == 1) "" else "s" return document.create.strong { +"$activeCount" }.outerHTML + " item $plural left" } }
mit
9796063ac7ffe8be71d465d7f9bc9805
29.517241
86
0.680226
3.734177
false
false
false
false
miquelbeltran/android-discogsbrowser
collection/collection-ui/src/main/java/work/beltran/discogsbrowser/collection/adapter/AlbumDiffCallback.kt
1
1069
package work.beltran.discogsbrowser.collection.adapter import androidx.recyclerview.widget.DiffUtil class AlbumDiffCallback( private val oldList: List<CollectionItem>, private val newList: List<CollectionItem> ) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val oldItem = oldList[oldItemPosition] val newItem = newList[newItemPosition] return when { oldItem is CollectionItem.LoadingItem && newItem is CollectionItem.LoadingItem -> true oldItem is CollectionItem.AlbumItem && newItem is CollectionItem.AlbumItem -> { oldItem.album.id == newItem.album.id } else -> false } } override fun getOldListSize(): Int { return oldList.size } override fun getNewListSize(): Int { return newList.size } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition] == newList[newItemPosition] } }
gpl-3.0
7bfc6ea11b1fdfe28d580832360899a9
32.4375
98
0.678204
5.371859
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/extensions/Context.kt
1
4142
@file:Suppress("NOTHING_TO_INLINE", "unused") package com.boardgamegeek.extensions import android.app.Activity import android.content.* import android.content.pm.PackageManager import android.graphics.Bitmap import android.os.Build import android.text.Html import android.text.SpannedString import android.text.TextUtils import android.widget.Toast import androidx.annotation.DrawableRes import androidx.annotation.PluralsRes import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.appcompat.content.res.AppCompatResources import androidx.core.graphics.drawable.toBitmap import androidx.core.os.bundleOf import androidx.preference.PreferenceManager import com.boardgamegeek.R import com.boardgamegeek.auth.Authenticator import com.boardgamegeek.provider.BggContract fun Context.preferences(name: String? = null): SharedPreferences = if (name.isNullOrEmpty()) PreferenceManager.getDefaultSharedPreferences(this) else this.getSharedPreferences(name, Context.MODE_PRIVATE) @Suppress("DEPRECATION") fun Context.getText(@StringRes id: Int, vararg args: Any): CharSequence { val encodedArgs = encodeArgs(args) val htmlString = String.format(Html.toHtml(SpannedString(getText(id))), *encodedArgs.toTypedArray()) return Html.fromHtml(htmlString).trimTrailingWhitespace() } @Suppress("DEPRECATION") fun Context.getQuantityText(@PluralsRes id: Int, quantity: Int, vararg args: Any?): CharSequence { val encodedArgs = encodeArgs(args) val htmlString = String.format(Html.toHtml(SpannedString(resources.getQuantityText(id, quantity))), *encodedArgs.toTypedArray()) return Html.fromHtml(htmlString).trimTrailingWhitespace() } private fun encodeArgs(args: Array<out Any?>): List<Any?> { val encodedArgs = mutableListOf<Any?>() for (i in args.indices) { val arg = args[i] encodedArgs.add(if (arg is String) TextUtils.htmlEncode(arg) else arg) } return encodedArgs } /** * Get the version name of the package, or "?.?" if not found. */ fun Context.versionName(): String { return try { packageManager.getPackageInfo(packageName, 0).versionName } catch (e: PackageManager.NameNotFoundException) { "?.?" } } fun Context.cancelSync() { this.cancelNotification(NotificationTags.SYNC_PROGRESS) Authenticator.getAccount(this)?.let { account -> ContentResolver.cancelSync(account, BggContract.CONTENT_AUTHORITY) } } inline fun <reified T : Activity> Context.startActivity(vararg params: Pair<String, Any?>) = startActivity(T::class.java, params) fun Context.startActivity(activity: Class<out Activity>, params: Array<out Pair<String, Any?>>) { startActivity(createIntent(activity, params)) } inline fun <reified T : Any> Context.intentFor(vararg params: Pair<String, Any?>): Intent = createIntent(T::class.java, params) fun <T> Context.createIntent(clazz: Class<out T>, params: Array<out Pair<String, Any?>>): Intent { val intent = Intent(this, clazz) if (params.isNotEmpty()) intent.putExtras(bundleOf(*params)) return intent } inline fun Context.toast(message: Int): Toast = Toast .makeText(this, message, Toast.LENGTH_SHORT) .apply { show() } inline fun Context.toast(message: CharSequence): Toast = Toast .makeText(this, message, Toast.LENGTH_SHORT) .apply { show() } inline fun Context.longToast(message: Int): Toast = Toast .makeText(this, message, Toast.LENGTH_LONG) .apply { show() } fun Context.showDialog(message: String, okButtonResId: Int = R.string.ok, okListener: DialogInterface.OnClickListener) { AlertDialog.Builder(this) .setMessage(message) .setCancelable(true) .setNegativeButton(R.string.cancel, null) .setPositiveButton(okButtonResId, okListener) .show() } fun Context.getBitmap(@DrawableRes resId: Int, tintColor: Int? = null): Bitmap { return AppCompatResources.getDrawable(this, resId)!!.apply { if (tintColor != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setTint(tintColor) } }.toBitmap() }
gpl-3.0
76dbb23447a41dddb49f709bd6c4685c
33.516667
132
0.732979
4.158635
false
false
false
false
WijayaPrinting/wp-javafx
openpss/src/com/hendraanggrian/openpss/schema/GlobalSetting.kt
1
1058
package com.hendraanggrian.openpss.schema import com.hendraanggrian.openpss.nosql.Document import com.hendraanggrian.openpss.nosql.Schema import com.hendraanggrian.openpss.nosql.StringId import kotlin.reflect.KProperty import kotlinx.nosql.string object GlobalSettings : Schema<GlobalSetting>("global_settings", GlobalSetting::class) { val key = string("key") val value = string("value") val LANGUAGE = "language" to "en-US" // or equivalent to Language.EN_US.fullCode val INVOICE_HEADERS = "invoice_headers" to "" } data class GlobalSetting( val key: String, var value: String ) : Document<GlobalSettings> { companion object { val KEY_LANGUAGE by GlobalSettings.LANGUAGE val KEY_INVOICE_HEADERS by GlobalSettings.INVOICE_HEADERS private operator fun Pair<String, String>.getValue( thisRef: Any?, property: KProperty<*> ): String = first } override lateinit var id: StringId<GlobalSettings> inline val valueList: List<String> get() = value.split("|") }
apache-2.0
3751e9b9d6ad76297ad8982092caaec1
28.388889
88
0.708885
4.318367
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/persistence/BloggingRemindersDao.kt
2
1301
package org.wordpress.android.fluxc.persistence import androidx.room.Dao import androidx.room.Entity import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.PrimaryKey import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface BloggingRemindersDao { @Query("SELECT * FROM BloggingReminders") fun getAll(): Flow<List<BloggingReminders>> @Query("SELECT * FROM BloggingReminders WHERE localSiteId = :siteId") fun liveGetBySiteId(siteId: Int): Flow<BloggingReminders?> @Query("SELECT * FROM BloggingReminders WHERE localSiteId = :siteId") suspend fun getBySiteId(siteId: Int): List<BloggingReminders> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(type: BloggingReminders): Long @Entity(tableName = "BloggingReminders") data class BloggingReminders( @PrimaryKey val localSiteId: Int, val monday: Boolean = false, val tuesday: Boolean = false, val wednesday: Boolean = false, val thursday: Boolean = false, val friday: Boolean = false, val saturday: Boolean = false, val sunday: Boolean = false, val hour: Int = 10, val minute: Int = 0, val isPromptRemindersOptedIn: Boolean = false ) }
gpl-2.0
cc035b5a93b9d69fa7a19c0c77d38433
31.525
73
0.707148
4.679856
false
false
false
false
scorsero/scorsero-client-android
app/src/main/java/io/github/dmi3coder/scorsero/score/ScoreCreationPresenter.kt
1
1121
package io.github.dmi3coder.scorsero.score import io.github.dmi3coder.scorsero.MainApplication import io.github.dmi3coder.scorsero.data.Score import io.github.dmi3coder.scorsero.data.source.ScoreRepository import io.github.dmi3coder.scorsero.score.ScoreCreationContract.ViewState import java.util.Date import javax.inject.Inject /** * Created by dim3coder on 11:59 PM 7/4/17. */ class ScoreCreationPresenter( var view: ScoreCreationContract.View) : ScoreCreationContract.Presenter { @Inject lateinit var repository: ScoreRepository var operationScore: Score? = null override fun start() { this.start(Score()) } override fun start(score: Score) { operationScore = score view.setPresenter(this) view.setScore(operationScore) } override fun processScore(scoreData: Score?, state: ViewState) { if (scoreData!!.creationDate == null) scoreData.creationDate = Date().time if (scoreData.id == null) { repository.insert(scoreData) } else { repository.update(scoreData) } view.clear() operationScore = Score() view.setScore(operationScore) } }
gpl-3.0
13742c958c40a6effaf936af6a63e7e2
25.714286
78
0.736842
3.812925
false
false
false
false
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Energy/Filler/FillerContainer.kt
1
2425
package antimattermod.core.Energy.Filler import antimattermod.core.Energy.Filler.TileFiller import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.InventoryPlayer import net.minecraft.inventory.Container import net.minecraft.inventory.IInventory import net.minecraft.inventory.Slot import net.minecraft.item.ItemStack /** * @author kojin15. */ class FillerContainer(private val x: Int, private val y: Int, private val z: Int, private val tile: TileFiller, private val playerInventory: InventoryPlayer) : Container() { init { for (i in 0..5) { for (j in 0..3) { this.addSlotToContainer(Slot(tile, j + i * 4, 186 + j * 18, 8 + i * 18)) } } this.addSlotToContainer(patternSlot(tile, 24, 80, 14)) for (i in 0..2) { for (j in 0..8) { this.addSlotToContainer(Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 108 + i * 18)) } } for (i in 0..8) { this.addSlotToContainer(Slot(playerInventory, i, 8 + i * 18, 166)) } } val fillerSize = 24 val playerSize = 27 val hotbarSize = 9 val fillerIndex = 0 val playerIndex = fillerIndex + fillerSize val hotbarIndex = playerIndex + playerSize override fun canInteractWith(player: EntityPlayer?): Boolean { return true } override fun transferStackInSlot(player: EntityPlayer?, clickedIndex: Int): ItemStack? { var itemstack: ItemStack? = null val slot: Slot = this.inventorySlots[clickedIndex] as Slot if (slot.hasStack) { val baseStack = slot.stack itemstack = baseStack.copy() if (clickedIndex < playerIndex) { if (!this.mergeItemStack(baseStack, playerIndex, hotbarIndex + hotbarSize, true)) return null } else if (!this.mergeItemStack(baseStack, fillerIndex, fillerIndex + fillerSize, false)) return null if (baseStack.stackSize == 0) slot.putStack(null) else slot.onSlotChanged() } return itemstack } class patternSlot(iInventory: IInventory, id: Int, x: Int, y: Int) : Slot(iInventory, id, x, y) { override fun canTakeStack(p_82869_1_: EntityPlayer?): Boolean { return false } override fun isItemValid(p_75214_1_: ItemStack?): Boolean { return false } } }
gpl-3.0
bcfe027bbcca30f3ee3b018ede3c8544
30.102564
173
0.623505
4.061977
false
false
false
false
mercadopago/px-android
example/src/main/java/com/mercadopago/FakeKycActivity.kt
1
1653
package com.mercadopago import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.TextView import android.widget.Toast import com.mercadopago.example.R class FakeKycActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_fake_kyc) val callback = intent.data?.getQueryParameter(QUERY_CALLBACK) findViewById<TextView>(R.id.initiative).text = intent.data?.getQueryParameter(QUERY_INITIATIVE) ?: "NO INITIATIVE" findViewById<TextView>(R.id.callback).text = callback ?: "NO CALLBACK" findViewById<View>(R.id.yes_button).setOnClickListener { if (callback.isNullOrEmpty()) { Toast.makeText(this, "No callback to call", Toast.LENGTH_SHORT).show() return@setOnClickListener } val intent = Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(callback) } val isIntentSafe = packageManager.queryIntentActivities(intent, 0).size > 0 if (isIntentSafe) { startActivity(intent) finish() } else { Toast.makeText(this, "No one listening to callback", Toast.LENGTH_SHORT).show() } } findViewById<View>(R.id.no_button).setOnClickListener { finish() } } companion object { private const val QUERY_INITIATIVE = "initiative" private const val QUERY_CALLBACK = "callback" } }
mit
90f69adae8663c7a146550e8db319b7b
33.458333
122
0.653962
4.516393
false
false
false
false
mercadopago/px-android
px-checkout/src/main/java/com/mercadopago/android/px/internal/extensions/BaseExtensions.kt
1
1166
package com.mercadopago.android.px.internal.extensions import android.app.Activity import android.graphics.Rect import android.view.View internal fun CharSequence?.isNotNullNorEmpty() = !isNullOrEmpty() internal fun CharSequence?.orIfEmpty(fallback: String) = if (isNotNullNorEmpty()) this!! else fallback internal fun View.gone() = apply { visibility = View.GONE } internal fun View.visible() = apply { visibility = View.VISIBLE } internal fun View.invisible() = apply { visibility = View.INVISIBLE } internal fun Any?.runIfNull(action: ()->Unit) { if(this == null) { action.invoke() } } internal fun Activity.addKeyBoardListener( onKeyBoardOpen: (() -> Unit)? = null, onKeyBoardClose: (() -> Unit)? = null ) { window.decorView.rootView?.apply { viewTreeObserver?.addOnGlobalLayoutListener { val r = Rect() getWindowVisibleDisplayFrame(r) val heightDiff = rootView.height - (r.bottom - r.top) if (heightDiff > rootView.height * 0.15) { onKeyBoardOpen?.invoke() } else { onKeyBoardClose?.invoke() } } } }
mit
b640cb7c002df6c8e0daca7997342e2c
27.463415
102
0.643225
4.271062
false
false
false
false
debop/debop4k
debop4k-data-mongodb/src/main/kotlin/debop4k/mongodb/spring/cache/MongodbCacheManager.kt
1
2550
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.mongodb.spring.cache import debop4k.core.io.serializers.Serializers import debop4k.core.loggerOf import org.eclipse.collections.impl.map.mutable.ConcurrentHashMap import org.springframework.beans.factory.DisposableBean import org.springframework.cache.Cache import org.springframework.cache.CacheManager import org.springframework.data.mongodb.core.MongoTemplate /** * MongoDB를 저장소로 사용하는 Spring @Cacheable용 Cache 관리자입니다. * Spring Application Context 에 MongoCacheManager를 Bean으로 등록하셔야 합니다. * <p> * <pre><code> * @Bean * public MongoCacheMaanger mongoCacheManager() { * return new MongoCacheManager(mongo, 120); * } * </code></pre> * * @author [email protected] */ class MongodbCacheManager @JvmOverloads constructor(val mongo: MongoTemplate, val expirationInSeconds: Long = 60 * 60 * 1000L) : CacheManager, DisposableBean { private val log = loggerOf(javaClass) val valueSerializer = Serializers.FST val caches = ConcurrentHashMap<String, Cache>() val expires = ConcurrentHashMap<String, Long>() override fun getCacheNames(): MutableCollection<String>? = caches.keys override fun getCache(name: String?): Cache { return caches.getIfAbsentPut(name!!) { key -> val expiration = computeExpiration(key) MongodbCache(key, mongo, expiration, valueSerializer) } } override fun destroy() { log.debug("MongoDB를 저장소로 사용하는 CacheManager를 제거합니다...") if (caches.notEmpty()) { try { caches.values.forEach { it.clear() } caches.clear() expires.clear() } catch(ignored: Exception) { log.warn("MongodbCacheManager를 제거하는데 실패했습니다.", ignored) } } } private fun computeExpiration(name: String): Long = expires.getIfAbsentPut(name, expirationInSeconds) }
apache-2.0
88421871efa3a2f7c3dc307a75727fb3
31.986486
107
0.721311
3.986928
false
false
false
false
FHannes/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/PropertiesTasksCompletionContributor.kt
13
4437
/* * 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 org.jetbrains.plugins.gradle.codeInsight 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.lookup.LookupElementBuilder import com.intellij.icons.AllIcons import com.intellij.lang.ASTNode import com.intellij.openapi.util.Ref import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext import icons.ExternalSystemIcons import icons.GradleIcons import org.jetbrains.plugins.gradle.service.resolve.GradleExtensionsContributor import org.jetbrains.plugins.gradle.service.resolve.GradleExtensionsContributor.Companion.getDocumentation import org.jetbrains.plugins.groovy.dsl.holders.NonCodeMembersHolder import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightVariable /** * @author Vladislav.Soroka * @since 12/12/2016 */ class PropertiesTasksCompletionContributor : AbstractGradleCompletionContributor() { class PropertiesTasksCompletionProvider : CompletionProvider<CompletionParameters>() { override fun addCompletions(params: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val position = params.position val prevSibling = position.prevSibling if (prevSibling is ASTNode && prevSibling.elementType == GroovyTokenTypes.mDOT) return val extensionsData = GradleExtensionsContributor.getExtensionsFor(position) ?: return for (gradleProp in extensionsData.findAllProperties()) { val docRef = Ref.create<String>() val propVar = object : GrLightVariable(position.manager, gradleProp.name, gradleProp.typeFqn, position) { override fun getNavigationElement(): PsiElement { val navigationElement = super.getNavigationElement() navigationElement.putUserData(NonCodeMembersHolder.DOCUMENTATION, docRef.get()) return navigationElement } } docRef.set(getDocumentation(gradleProp, propVar)) val elementBuilder = LookupElementBuilder.create(propVar, gradleProp.name) .withIcon(AllIcons.Nodes.Property) .withPresentableText(gradleProp.name) .withTailText(" via ext", true) .withTypeText(propVar.type.presentableText, GradleIcons.Gradle, false) result.addElement(elementBuilder) } for (gradleTask in extensionsData.tasks) { val docRef = Ref.create<String>() val taskVar = object : GrLightVariable(position.manager, gradleTask.name, gradleTask.typeFqn, position) { override fun getNavigationElement(): PsiElement { val navigationElement = super.getNavigationElement() navigationElement.putUserData(NonCodeMembersHolder.DOCUMENTATION, docRef.get()) return navigationElement } } docRef.set(getDocumentation(gradleTask, taskVar)) val elementBuilder = LookupElementBuilder.create(taskVar, gradleTask.name) .withIcon(ExternalSystemIcons.Task) .withPresentableText(gradleTask.name) .withTailText(" task", true) .withTypeText(taskVar.type.presentableText) result.addElement(elementBuilder) } } } init { extend(CompletionType.BASIC, PATTERN, PropertiesTasksCompletionProvider()) } companion object { private val PATTERN = psiElement().and(GRADLE_FILE_PATTERN).withParent(GrReferenceExpression::class.java) } }
apache-2.0
4b7546544519d73ad68df29153e7fb9c
43.828283
113
0.746676
4.985393
false
false
false
false
googlesamples/mlkit
android/vision-quickstart/app/src/main/java/com/google/mlkit/vision/demo/kotlin/textdetector/TextRecognitionProcessor.kt
1
4286
/* * Copyright 2020 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.vision.demo.kotlin.textdetector import android.content.Context import android.util.Log import com.google.android.gms.tasks.Task import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.demo.GraphicOverlay import com.google.mlkit.vision.demo.kotlin.VisionProcessorBase import com.google.mlkit.vision.demo.preference.PreferenceUtils import com.google.mlkit.vision.text.Text import com.google.mlkit.vision.text.TextRecognition import com.google.mlkit.vision.text.TextRecognizer import com.google.mlkit.vision.text.TextRecognizerOptionsInterface /** Processor for the text detector demo. */ class TextRecognitionProcessor( private val context: Context, textRecognizerOptions: TextRecognizerOptionsInterface ) : VisionProcessorBase<Text>(context) { private val textRecognizer: TextRecognizer = TextRecognition.getClient(textRecognizerOptions) private val shouldGroupRecognizedTextInBlocks: Boolean = PreferenceUtils.shouldGroupRecognizedTextInBlocks(context) private val showLanguageTag: Boolean = PreferenceUtils.showLanguageTag(context) private val showConfidence: Boolean = PreferenceUtils.shouldShowTextConfidence(context) override fun stop() { super.stop() textRecognizer.close() } override fun detectInImage(image: InputImage): Task<Text> { return textRecognizer.process(image) } override fun onSuccess(text: Text, graphicOverlay: GraphicOverlay) { Log.d(TAG, "On-device Text detection successful") logExtrasForTesting(text) graphicOverlay.add( TextGraphic( graphicOverlay, text, shouldGroupRecognizedTextInBlocks, showLanguageTag, showConfidence ) ) } override fun onFailure(e: Exception) { Log.w(TAG, "Text detection failed.$e") } companion object { private const val TAG = "TextRecProcessor" private fun logExtrasForTesting(text: Text?) { if (text != null) { Log.v(MANUAL_TESTING_LOG, "Detected text has : " + text.textBlocks.size + " blocks") for (i in text.textBlocks.indices) { val lines = text.textBlocks[i].lines Log.v( MANUAL_TESTING_LOG, String.format("Detected text block %d has %d lines", i, lines.size) ) for (j in lines.indices) { val elements = lines[j].elements Log.v( MANUAL_TESTING_LOG, String.format("Detected text line %d has %d elements", j, elements.size) ) for (k in elements.indices) { val element = elements[k] Log.v( MANUAL_TESTING_LOG, String.format("Detected text element %d says: %s", k, element.text) ) Log.v( MANUAL_TESTING_LOG, String.format( "Detected text element %d has a bounding box: %s", k, element.boundingBox!!.flattenToString() ) ) Log.v( MANUAL_TESTING_LOG, String.format( "Expected corner point size is 4, get %d", element.cornerPoints!!.size ) ) for (point in element.cornerPoints!!) { Log.v( MANUAL_TESTING_LOG, String.format( "Corner point for element %d is located at: x - %d, y = %d", k, point.x, point.y ) ) } } } } } } } }
apache-2.0
0d30114ed0c3b80a0b4954e76206472d
33.564516
95
0.622958
4.530655
false
true
false
false
TeamAmaze/AmazeFileManager
app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialogTest.kt
1
15169
/* * Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.ui.dialogs import android.content.Intent import android.os.Environment import android.view.View.INVISIBLE import android.view.View.VISIBLE import androidx.appcompat.widget.AppCompatCheckBox import androidx.appcompat.widget.AppCompatTextView import androidx.core.text.HtmlCompat import androidx.preference.PreferenceManager import com.afollestad.materialdialogs.DialogAction import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.internal.MDButton import com.amaze.filemanager.R import com.amaze.filemanager.application.AppConfig import com.amaze.filemanager.asynchronous.services.EncryptService import com.amaze.filemanager.asynchronous.services.EncryptService.TAG_SOURCE import com.amaze.filemanager.filesystem.HybridFileParcelable import com.amaze.filemanager.filesystem.RandomPathGenerator import com.amaze.filemanager.filesystem.files.CryptUtil.AESCRYPT_EXTENSION import com.amaze.filemanager.filesystem.files.CryptUtil.CRYPT_EXTENSION import com.amaze.filemanager.filesystem.files.EncryptDecryptUtils import com.amaze.filemanager.test.getString import com.amaze.filemanager.ui.activities.MainActivity import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.ENCRYPT_PASSWORD_FINGERPRINT import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.ENCRYPT_PASSWORD_MASTER import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_CRYPT_FINGERPRINT import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_CRYPT_FINGERPRINT_DEFAULT import com.amaze.filemanager.ui.views.WarnableTextInputLayout import com.google.android.material.textfield.TextInputEditText import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Before import org.junit.Test import org.robolectric.shadows.ShadowDialog import java.io.File import kotlin.random.Random class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { private val randomizer = Random(System.currentTimeMillis()) private lateinit var file: File private lateinit var tilFileSaveAs: WarnableTextInputLayout private lateinit var editTextFileSaveAs: TextInputEditText private lateinit var checkboxUseAze: AppCompatCheckBox private lateinit var textViewCryptInfo: AppCompatTextView private lateinit var okButton: MDButton /** * MainActivity setup. */ @Before override fun setUp() { super.setUp() file = File( Environment.getExternalStorageDirectory(), RandomPathGenerator.generateRandomPath( randomizer, 16 ) ) } /** * Post test cleanup. */ @After override fun tearDown() { super.tearDown() PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit().putBoolean( PREFERENCE_CRYPT_FINGERPRINT, PREFERENCE_CRYPT_FINGERPRINT_DEFAULT ).apply() } /** * Test case when fingerprint encrypt option is enabled. * * Ensure optional checkbox is disabled - Fingerprint encryption cannot do AESCrypt. */ @Test fun testWhenFingerprintOptionEnabled() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, true) .apply() performTest( testContent = { _, _, _ -> assertEquals("${file.name}$CRYPT_EXTENSION", editTextFileSaveAs.text.toString()) assertEquals(INVISIBLE, checkboxUseAze.visibility) assertEquals(INVISIBLE, textViewCryptInfo.visibility) }, callback = object : EncryptDecryptUtils.EncryptButtonCallbackInterface { override fun onButtonPressed(intent: Intent, password: String) { assertEquals(ENCRYPT_PASSWORD_FINGERPRINT, password) assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) assertFalse(intent.getBooleanExtra(EncryptService.TAG_AESCRYPT, true)) assertEquals( "${file.name}$CRYPT_EXTENSION", intent.getStringExtra(EncryptService.TAG_ENCRYPT_TARGET) ) } } ) } /** * Test filename validation when fingerprint option enabled. * Shall never let but .aze go through */ @Test fun testFilenameValidationWhenFingerprintOptionEnabled() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, true) .apply() performTest(testContent = { _, _, _ -> editTextFileSaveAs.setText("${file.name}.error") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aze), tilFileSaveAs.error ) editTextFileSaveAs.setText("${file.name}.aes") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aze), tilFileSaveAs.error ) }) } /** * Test filename validation when fingerprint option enabled. * Shall never let but .aze go through */ @Test fun testFilenameValidationWhenFingerprintOptionDisabled() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, false) .apply() performTest( password = ENCRYPT_PASSWORD_MASTER, testContent = { _, _, _ -> editTextFileSaveAs.setText("${file.name}.error") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aes), tilFileSaveAs.error ) editTextFileSaveAs.setText("${file.name}.aze") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aes), tilFileSaveAs.error ) checkboxUseAze.isChecked = true assertTrue(okButton.isEnabled) assertNull(tilFileSaveAs.error) } ) } /** * Test case when fingerprint option is disabled. * * Must be master password then. Sorry, no validation at this point - upstream is responsible * for that. */ @Test fun testWhenFingerprintOptionDisabled() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, false) .apply() performTest( password = ENCRYPT_PASSWORD_MASTER, testContent = { _, _, _ -> assertEquals("${file.name}$AESCRYPT_EXTENSION", editTextFileSaveAs.text.toString()) assertEquals(VISIBLE, checkboxUseAze.visibility) assertEquals(VISIBLE, textViewCryptInfo.visibility) }, callback = object : EncryptDecryptUtils.EncryptButtonCallbackInterface { override fun onButtonPressed(intent: Intent, password: String) { assertEquals(ENCRYPT_PASSWORD_MASTER, password) assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) assertTrue(intent.getBooleanExtra(EncryptService.TAG_AESCRYPT, false)) assertEquals( "${file.name}$AESCRYPT_EXTENSION", intent.getStringExtra(EncryptService.TAG_ENCRYPT_TARGET) ) } } ) } /** * Test invalid password put into the dialog argument, which shall never happen. */ @Test(expected = IllegalArgumentException::class) fun testWithInvalidFixedPasswordArgument() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, false) .apply() performTest( password = "abcdefgh", testContent = { _, _, _ -> } ) } /** * Test logic when aze encryption checkbox is ticked. */ @Test fun testAzecryptCheckbox() { performTest( password = ENCRYPT_PASSWORD_MASTER, testContent = { _, _, _ -> checkboxUseAze.isChecked = true assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_azecrypt_desc), HtmlCompat.FROM_HTML_MODE_COMPACT ) .toString(), textViewCryptInfo.text.toString() ) assertTrue(ShadowDialog.getShownDialogs().size == 2) assertTrue(ShadowDialog.getLatestDialog() is MaterialDialog) (ShadowDialog.getLatestDialog() as MaterialDialog).run { assertEquals(getString(R.string.warning), titleView.text) assertEquals( getString(R.string.crypt_warning_key), contentView?.text.toString() ) assertEquals( getString(R.string.warning_never_show), getActionButton(DialogAction.NEGATIVE).text ) assertEquals( getString(R.string.warning_confirm), getActionButton(DialogAction.POSITIVE).text ) assertTrue(getActionButton(DialogAction.POSITIVE).performClick()) } assertEquals(2, ShadowDialog.getShownDialogs().size) assertFalse(ShadowDialog.getLatestDialog().isShowing) assertTrue(true == editTextFileSaveAs.text?.endsWith(CRYPT_EXTENSION)) checkboxUseAze.isChecked = false assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_aescrypt_desc), HtmlCompat.FROM_HTML_MODE_COMPACT ) .toString(), textViewCryptInfo.text.toString() ) assertEquals(2, ShadowDialog.getShownDialogs().size) assertFalse(ShadowDialog.getLatestDialog().isShowing) assertTrue(true == editTextFileSaveAs.text?.endsWith(AESCRYPT_EXTENSION)) checkboxUseAze.isChecked = true assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_azecrypt_desc), HtmlCompat.FROM_HTML_MODE_COMPACT ) .toString(), textViewCryptInfo.text.toString() ) assertEquals(3, ShadowDialog.getShownDialogs().size) assertTrue(ShadowDialog.getLatestDialog().isShowing) assertTrue(true == editTextFileSaveAs.text?.endsWith(CRYPT_EXTENSION)) (ShadowDialog.getLatestDialog() as MaterialDialog) .getActionButton(DialogAction.NEGATIVE).performClick() assertEquals(3, ShadowDialog.getShownDialogs().size) assertFalse(ShadowDialog.getLatestDialog().isShowing) assertTrue( PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false) ) checkboxUseAze.isChecked = false assertEquals(3, ShadowDialog.getShownDialogs().size) // no new dialog checkboxUseAze.isChecked = true assertEquals(3, ShadowDialog.getShownDialogs().size) } ) } private fun performTest( testContent: (dialog: MaterialDialog, intent: Intent, activity: MainActivity) -> Unit, password: String = ENCRYPT_PASSWORD_FINGERPRINT, callback: EncryptDecryptUtils.EncryptButtonCallbackInterface = object : EncryptDecryptUtils.EncryptButtonCallbackInterface {} ) { scenario.onActivity { activity -> Intent().putExtra(TAG_SOURCE, HybridFileParcelable(file.absolutePath)).let { intent -> EncryptWithPresetPasswordSaveAsDialog.show( activity, intent, activity, password, callback ) ShadowDialog.getLatestDialog()?.run { assertTrue(this is MaterialDialog) (this as MaterialDialog).let { editTextFileSaveAs = findViewById<TextInputEditText>( R.id.edit_text_encrypt_save_as ) tilFileSaveAs = findViewById<WarnableTextInputLayout>( R.id.til_encrypt_save_as ) checkboxUseAze = findViewById<AppCompatCheckBox>(R.id.checkbox_use_aze) textViewCryptInfo = findViewById<AppCompatTextView>( R.id.text_view_crypt_info ) okButton = getActionButton(DialogAction.POSITIVE) testContent.invoke(it, intent, activity) } } ?: fail("Dialog cannot be seen?") } } } }
gpl-3.0
84ebfde7eafbacf70a7a6bbfbb5e6d19
42.09375
119
0.616191
5.728474
false
true
false
false
cout970/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/conveyorbelt/BitMap.kt
2
2605
package com.cout970.magneticraft.systems.tilemodules.conveyorbelt import com.cout970.magneticraft.AABB import com.cout970.magneticraft.IVector2 import com.cout970.magneticraft.misc.vector.vec2Of open class BitMap(val map: BooleanArray = BooleanArray(16 * 16)) : IBitMap { override operator fun get(x: Int, y: Int): Boolean { val index = x + y * 16 if (index < 0 || index >= 16 * 16) return false return map[index] } override operator fun set(x: Int, y: Int, value: Boolean) { val index = x + y * 16 if (index < 0 || index >= 16 * 16) return map[index] = value } override fun mark(box: AABB) { mark(vec2Of(box.minX, box.minZ) * 16, vec2Of(box.maxX, box.maxZ) * 16) } override fun mark(start: IVector2, end: IVector2) { for (i in Math.floor(start.x).toInt() until Math.ceil(end.x).toInt()) { for (j in Math.floor(start.y).toInt() until Math.ceil(end.y).toInt()) { this[i, j] = true } } } override fun unmark(box: AABB) { unmark(vec2Of(box.minX, box.minZ) * 16, vec2Of(box.maxX, box.maxZ) * 16) } override fun unmark(start: IVector2, end: IVector2) { for (i in Math.floor(start.x).toInt() until Math.ceil(end.x).toInt()) { for (j in Math.floor(start.y).toInt() until Math.ceil(end.y).toInt()) { this[i, j] = false } } } // Returns true if there and empty space in the hitbox area override fun test(box: AABB): Boolean { return test(vec2Of(box.minX, box.minZ) * 16, vec2Of(box.maxX, box.maxZ) * 16) } override fun test(start: IVector2, end: IVector2): Boolean { for (i in Math.floor(start.x).toInt() until Math.ceil(end.x).toInt()) { for (j in Math.floor(start.y).toInt() until Math.ceil(end.y).toInt()) { if (this[i, j]) return false } } return true } override fun clear() { for (i in 0 until 16 * 16) { map[i] = false } } override fun copy(): BitMap { return BitMap(map.clone()) } override fun toString(): String { return buildString { append("BitMap(\n") for (i in 0 until 16) { for (j in 0 until 16) { if (this@BitMap[i, j]) { append("#") } else { append("_") } } append('\n') } append(")") } } }
gpl-2.0
c89aeb5c16a386ecdaf6f087a4ea8e6d
29.658824
85
0.519386
3.638268
false
false
false
false
wiltonlazary/kotlin-native
build-tools/src/main/kotlin/org/jetbrains/kotlin/XcRunRuntimeUtils.kt
1
2622
package org.jetbrains.kotlin import com.google.gson.annotations.Expose import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.konan.target.Xcode import kotlin.math.min /** * Compares two strings assuming that both are representing numeric version strings. * Examples of numeric version strings: "12.4.1.2", "9", "0.5". */ private fun compareStringsAsVersions(version1: String, version2: String): Int { val version1 = version1.split('.').map { it.toInt() } val version2 = version2.split('.').map { it.toInt() } val minimalLength = min(version1.size, version2.size) for (index in 0 until minimalLength) { if (version1[index] < version2[index]) return -1 if (version1[index] > version2[index]) return 1 } return version1.size.compareTo(version2.size) } /** * Returns parsed output of `xcrun simctl list runtimes -j`. */ private fun Xcode.getSimulatorRuntimeDescriptors(): List<SimulatorRuntimeDescriptor> = gson.fromJson(simulatorRuntimes, ListRuntimesReport::class.java).runtimes /** * Returns first available simulator runtime for [target] with at least [osMinVersion] OS version. * */ fun Xcode.getLatestSimulatorRuntimeFor(target: KonanTarget, osMinVersion: String): SimulatorRuntimeDescriptor? { val osName = when (target) { KonanTarget.IOS_X64 -> "iOS" KonanTarget.WATCHOS_X64, KonanTarget.WATCHOS_X86 -> "watchOS" KonanTarget.TVOS_X64 -> "tvOS" else -> error("Unexpected simulator target: $target") } return getSimulatorRuntimeDescriptors().firstOrNull { it.checkAvailability() && it.name.startsWith(osName) && compareStringsAsVersions(it.version, osMinVersion) >= 0 } } // Result of `xcrun simctl list runtimes -j`. data class ListRuntimesReport( @Expose val runtimes: List<SimulatorRuntimeDescriptor> ) data class SimulatorRuntimeDescriptor( @Expose val version: String, // bundlePath field may not exist in the old Xcode (prior to 10.3). @Expose val bundlePath: String? = null, @Expose val isAvailable: Boolean? = null, @Expose val availability: String? = null, @Expose val name: String, @Expose val identifier: String, @Expose val buildversion: String ) { /** * Different Xcode/macOS combinations give different fields that checks * runtime availability. This method is an umbrella for these fields. */ fun checkAvailability(): Boolean { if (isAvailable == true) return true if (availability?.contains("unavailable") == true) return false return false } }
apache-2.0
b12248e7228e946050a94b763dd4f5f0
38.134328
160
0.699466
4.135647
false
false
false
false
nemerosa/ontrack
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/sync/SCMCatalogSyncSettingsProvider.kt
1
1537
package net.nemerosa.ontrack.extension.scm.catalog.sync import net.nemerosa.ontrack.model.settings.SettingsProvider import net.nemerosa.ontrack.model.support.SettingsRepository import net.nemerosa.ontrack.model.support.getBoolean import net.nemerosa.ontrack.model.support.getString import org.springframework.stereotype.Component /** * Reading the SCM catalog sync settings. */ @Component class SCMCatalogSyncSettingsProvider( private val settingsRepository: SettingsRepository, ) : SettingsProvider<SCMCatalogSyncSettings> { override fun getSettings() = SCMCatalogSyncSettings( syncEnabled = settingsRepository.getBoolean( SCMCatalogSyncSettings::syncEnabled, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_ENABLED ), orphanDisablingEnabled = settingsRepository.getBoolean( SCMCatalogSyncSettings::orphanDisablingEnabled, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_ORPHAN_DISABLED ), scm = settingsRepository.getString( SCMCatalogSyncSettings::scm, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_SCM ), config = settingsRepository.getString( SCMCatalogSyncSettings::config, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_CONFIG ), repository = settingsRepository.getString( SCMCatalogSyncSettings::repository, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_REPOSITORY ), ) override fun getSettingsClass(): Class<SCMCatalogSyncSettings> = SCMCatalogSyncSettings::class.java }
mit
adb8a0ccde3775f6aa99285263bebf0b
35.619048
103
0.724789
5.392982
false
true
false
false
LarsKrogJensen/graphql-kotlin
src/main/kotlin/graphql/execution/ExecutorServiceExecutionStrategy.kt
1
2587
package graphql.execution import graphql.ExecutionResult import graphql.ExecutionResultImpl import graphql.GraphQLException import graphql.language.Field import graphql.schema.GraphQLObjectType import java.util.LinkedHashMap import java.util.concurrent.* /** * * ExecutorServiceExecutionStrategy uses an [ExecutorService] to parallelize the resolve. * Due to the nature of [.execute] implementation, [ExecutorService] * MUST have the following 2 characteristics: * * * 1. The underlying [java.util.concurrent.ThreadPoolExecutor] MUST have a reasonable `maximumPoolSize` * * 2. The underlying [java.util.concurrent.ThreadPoolExecutor] SHALL NOT use its task queue. * * * Failure to follow 1. and 2. can result in a very large number of threads created or hanging. (deadlock) * See `graphql.execution.ExecutorServiceExecutionStrategyTest` for example usage. */ class ExecutorServiceExecutionStrategy(val executorService: ExecutorService) : AbstractExecutionStrategy() { override fun execute(executionContext: ExecutionContext, parentType: GraphQLObjectType, source: Any, fields: Map<String, List<Field>>): CompletionStage<ExecutionResult> { val futures = fields.asSequence() .associateBy({ it.key }) { executorService.submit( Callable { resolveField(executionContext, parentType, source, it.value) }) } try { val promise = CompletableFuture<ExecutionResult>() val results = LinkedHashMap<String, Any?>() for ((fieldName, future) in futures) { future.get().thenAccept({ executionResult -> results.put(fieldName, executionResult?.data()) // Last one to finish completes the promise if (results.size == futures.keys.size) { promise.complete(ExecutionResultImpl(results, executionContext.errors())) } }) } return promise } catch (e: InterruptedException) { throw GraphQLException(e) } catch (e: ExecutionException) { throw GraphQLException(e) } } }
mit
1c77b6c76393f66c8b91523e33cc5d4f
40.063492
137
0.564747
6.101415
false
false
false
false
cbeust/kobalt
src/main/kotlin/com/beust/kobalt/app/remote/SparkServer.kt
2
2894
package com.beust.kobalt.app.remote import com.beust.kobalt.api.ITemplate import com.beust.kobalt.app.Templates import com.beust.kobalt.internal.PluginInfo import com.google.common.collect.ListMultimap import com.google.gson.Gson import org.slf4j.Logger import spark.ResponseTransformer import spark.Route import spark.Spark import java.util.concurrent.Executors class SparkServer(val cleanUpCallback: () -> Unit, val pluginInfo : PluginInfo) : KobaltServer.IServer { companion object { lateinit var cleanUpCallback: () -> Unit val URL_QUIT = "/quit" lateinit var watchDog: WatchDog } init { SparkServer.cleanUpCallback = cleanUpCallback } class JsonTransformer : ResponseTransformer { val gson = Gson() override fun render(model: Any) = gson.toJson(model) } private fun jsonRoute(path: String, route: Route) = Spark.get(path, "application/json", route, JsonTransformer()) val log: Logger = org.slf4j.LoggerFactory.getLogger("SparkServer") override fun run(port: Int) { val threadPool = Executors.newFixedThreadPool(2) watchDog = WatchDog(port, 60 * 10 /* 10 minutes */, log) threadPool.submit { watchDog.run() } log.debug("Server running") Spark.port(port) Spark.webSocket("/v1/getDependencyGraph", GetDependencyGraphHandler::class.java) Spark.get("/ping") { req, res -> watchDog.rearm() log.debug(" Received ping") """ { "result" : "ok" } """ } Spark.get(URL_QUIT, { req, res -> log.debug(" Received quit") threadPool.let { executor -> executor.submit { Thread.sleep(1000) Spark.stop() executor.shutdown() } KobaltServer.OK } }) jsonRoute("/v0/getTemplates", Route { request, response -> TemplatesData.create(Templates().getTemplates(pluginInfo)) }) Spark.init() } } class ProgressCommand(val progress: Int? = null, val message: String? = null) { companion object { val NAME = "ProgressCommand" } } class WebSocketCommand(val commandName: String, val errorMessage: String? = null, val payload: String) class TemplateData(val pluginName: String, val templates: List<String>) class TemplatesData(val templates: List<TemplateData>) { companion object { fun create(map: ListMultimap<String, ITemplate>) : TemplatesData { val templateList = arrayListOf<TemplateData>() map.keySet().forEach { pluginName -> val list = map[pluginName].map { it.templateName } templateList.add(TemplateData(pluginName, list)) } return TemplatesData(templateList) } } }
apache-2.0
254fca499e6f3c95809f99278a531695
30.802198
104
0.618176
4.411585
false
false
false
false
DankBots/Mega-Gnar
src/main/kotlin/gg/octave/bot/commands/music/search/Play.kt
1
8912
package gg.octave.bot.commands.music.search import com.jagrosh.jdautilities.menu.Selector import com.jagrosh.jdautilities.menu.SelectorBuilder import gg.octave.bot.Launcher import gg.octave.bot.listeners.FlightEventAdapter import gg.octave.bot.music.MusicLimitException import gg.octave.bot.music.MusicManager import gg.octave.bot.music.TrackContext import gg.octave.bot.music.TrackScheduler import gg.octave.bot.utils.extensions.config import gg.octave.bot.utils.extensions.data import gg.octave.bot.utils.extensions.selfMember import gg.octave.bot.utils.extensions.voiceChannel import gg.octave.bot.utils.getDisplayValue import me.devoxin.flight.api.Context import me.devoxin.flight.api.annotations.Command import me.devoxin.flight.api.annotations.Greedy import me.devoxin.flight.api.entities.Cog import net.dv8tion.jda.api.EmbedBuilder import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit class Play : Cog { @Command(aliases = ["p"], description = "Plays music in a voice channel.") fun play(ctx: Context, @Greedy query: String?) { val botChannel = ctx.selfMember!!.voiceState?.channel val userChannel = ctx.voiceChannel if (botChannel != null && botChannel != userChannel) { return ctx.send("The bot is already playing music in another channel.") } val manager = Launcher.players.getExisting(ctx.guild) if (query == null) { if (manager == null) { return ctx.send("There's no music player in this guild.\n\uD83C\uDFB6` ${ctx.trigger}play (song/url)` to start playing some music!") } when { manager.player.isPaused -> { manager.player.isPaused = false ctx.send { setTitle("Play Music") setDescription("Music is no longer paused.") } } manager.player.playingTrack != null -> { ctx.send("Music is already playing. Are you trying to queue a track? Try adding a search term with this command!") } manager.scheduler.queue.isEmpty() -> { ctx.send { setTitle("Empty Queue") setDescription("There is no music queued right now. Add some songs with `${ctx.trigger}play (song/url)`.") } } } return } val args = query.split(" +".toRegex()).toTypedArray() prompt(ctx, manager).handle { _, _ -> if (ctx.data.music.isVotePlay && !FlightEventAdapter.isDJ(ctx, false)) { val newManager = try { Launcher.players.get(ctx.guild) } catch (e: MusicLimitException) { return@handle e.sendToContext(ctx) } startPlayVote(ctx, newManager, args, false, "") } else { play(ctx, args, false, "") } }.exceptionally { ctx.send("An error occurred!") it.printStackTrace() return@exceptionally } } private fun prompt(ctx: Context, manager: MusicManager?): CompletableFuture<Void> { val future = CompletableFuture<Void>() val oldQueue = TrackScheduler.getQueueForGuild(ctx.guild!!.id) if (manager == null && !oldQueue.isEmpty()) { SelectorBuilder(Launcher.eventWaiter) .setType(Selector.Type.MESSAGE) .title { "Would you like to keep your old queue?" } .description { "Thanks for using Octave!" } .addOption("Yes, keep it.") { ctx.send("Kept old queue. Playing new song first and continuing with your queue...") future.complete(null) }.addOption("No, start a new queue.") { oldQueue.clear() ctx.send("Scrapped old queue. A new queue will start.") future.complete(null) }.build().display(ctx.textChannel!!) } else { future.complete(null) } return future } companion object { fun play(ctx: Context, args: Array<String>, isSearchResult: Boolean, uri: String) { val manager = try { Launcher.players.get(ctx.guild) } catch (e: MusicLimitException) { return e.sendToContext(ctx) } val config = ctx.config //Reset expire time if play has been called. manager.scheduler.queue.clearExpire() val query = when { "https://" in args[0] || "http://" in args[0] || args[0].startsWith("spotify:") -> { args[0].removePrefix("<").removeSuffix(">") } isSearchResult -> uri else -> "ytsearch:${args.joinToString(" ").trim()}" } val trackContext = TrackContext(ctx.author.idLong, ctx.textChannel!!.idLong) manager.loadAndPlay( ctx, query, trackContext, if (!isSearchResult) "You can search and pick results using ${config.prefix}youtube or ${config.prefix}soundcloud while in a channel." else null ) } fun startPlayVote(ctx: Context, manager: MusicManager, args: Array<String>, isSearchResult: Boolean, uri: String) { if (manager.isVotingToPlay) { return ctx.send("There is already a vote going on!") } val data = ctx.data val voteSkipCooldown = if (data.music.votePlayCooldown <= 0) { ctx.config.votePlayCooldown.toMillis() } else { data.music.votePlayCooldown } if (System.currentTimeMillis() - manager.lastPlayVoteTime < voteSkipCooldown) { return ctx.send("You must wait $voteSkipCooldown before starting a new vote.") } val votePlayDuration = if (data.music.votePlayDuration == 0L) { data.music.votePlayDuration } else { ctx.config.votePlayDuration.toMillis() } val votePlayDurationText = if (data.music.votePlayDuration == 0L) { ctx.config.votePlayDurationText } else { getDisplayValue(data.music.votePlayDuration) } manager.lastPlayVoteTime = System.currentTimeMillis() manager.isVotingToPlay = true val channel = ctx.selfMember!!.voiceState!!.channel ?: ctx.voiceChannel!! val halfPeople = channel.members.filter { !it.user.isBot }.size / 2 ctx.messageChannel.sendMessage(EmbedBuilder().apply { setTitle("Vote Play") setDescription( buildString { append(ctx.author.asMention) append(" has voted to **play** a track!") append(" React with :thumbsup:\n") append("If there are more than $halfPeople vote(s) within $votePlayDurationText, the track will be queued.") } ) }.build()) .submit() .thenCompose { m -> m.addReaction("👍") .submit() .thenApply { m } } .thenCompose { it.editMessage(EmbedBuilder(it.embeds[0]) .apply { setDescription("Voting has ended! Check the newer messages for results.") clearFields() }.build() ).submitAfter(votePlayDuration, TimeUnit.MILLISECONDS) }.thenAccept { m -> val votes = m.reactions.firstOrNull { it.reactionEmote.name == "👍" }?.count?.minus(1) ?: 0 ctx.send { setTitle("Vote Skip") setDescription( buildString { if (votes > halfPeople) { appendln("The vote has passed! The song will be queued.") play(ctx, args, isSearchResult, uri) } else { appendln("The vote has failed! The song will not be queued.") } } ) addField("Results", "__$votes Play Votes__", false) } }.whenComplete { _, _ -> manager.isVotingToPlay = false } } } }
mit
be3e4d979c8c3ba8805fb7cee50ef32d
39.666667
160
0.525488
5.040181
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/jobs/FilesUploadWorker.kt
1
10354
/* * * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2022 Tobias Kaminsky * Copyright (C) 2022 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.nextcloud.client.jobs import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.work.Worker import androidx.work.WorkerParameters import com.nextcloud.client.account.User import com.nextcloud.client.account.UserAccountManager import com.nextcloud.client.device.PowerManagementService import com.nextcloud.client.network.ConnectivityService import com.nextcloud.client.utils.FileUploaderDelegate import com.owncloud.android.R import com.owncloud.android.datamodel.FileDataStorageManager import com.owncloud.android.datamodel.ThumbnailsCacheManager import com.owncloud.android.datamodel.UploadsStorageManager import com.owncloud.android.db.OCUpload import com.owncloud.android.lib.common.OwnCloudAccount import com.owncloud.android.lib.common.OwnCloudClientManagerFactory import com.owncloud.android.lib.common.network.OnDatatransferProgressListener import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.files.FileUtils import com.owncloud.android.operations.UploadFileOperation import com.owncloud.android.ui.activity.UploadListActivity import com.owncloud.android.ui.notifications.NotificationUtils import com.owncloud.android.utils.theme.ViewThemeUtils import java.io.File @Suppress("LongParameterList") class FilesUploadWorker( val uploadsStorageManager: UploadsStorageManager, val connectivityService: ConnectivityService, val powerManagementService: PowerManagementService, val userAccountManager: UserAccountManager, val viewThemeUtils: ViewThemeUtils, val localBroadcastManager: LocalBroadcastManager, val context: Context, params: WorkerParameters ) : Worker(context, params), OnDatatransferProgressListener { private var lastPercent = 0 private val notificationBuilder: NotificationCompat.Builder = NotificationUtils.newNotificationBuilder(context, viewThemeUtils) private val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager private val fileUploaderDelegate = FileUploaderDelegate() override fun doWork(): Result { val accountName = inputData.getString(ACCOUNT) if (accountName.isNullOrEmpty()) { Log_OC.w(TAG, "User was null for file upload worker") return Result.failure() // user account is needed } // get all pending uploads var currentAndPendingUploadsForAccount = uploadsStorageManager.getCurrentAndPendingUploadsForAccount(MAX_UPLOADS_QUERY, accountName) while (currentAndPendingUploadsForAccount.isNotEmpty()) { Log_OC.d(TAG, "Handling ${currentAndPendingUploadsForAccount.size} uploads for account $accountName") handlePendingUploads(currentAndPendingUploadsForAccount, accountName) currentAndPendingUploadsForAccount = uploadsStorageManager.getCurrentAndPendingUploadsForAccount(MAX_UPLOADS_QUERY, accountName) } Log_OC.d(TAG, "No more pending uploads for account $accountName, stopping work") return Result.success() } private fun handlePendingUploads(uploads: Array<OCUpload>, accountName: String) { val user = userAccountManager.getUser(accountName) for (upload in uploads) { // create upload file operation if (user.isPresent) { val uploadFileOperation = createUploadFileOperation(upload, user.get()) val result = upload(uploadFileOperation, user.get()) fileUploaderDelegate.sendBroadcastUploadFinished( uploadFileOperation, result, uploadFileOperation.oldFile?.storagePath, context, localBroadcastManager ) } else { // user not present anymore, remove upload uploadsStorageManager.removeUpload(upload.uploadId) } } } /** * from @{link FileUploader#retryUploads()} */ private fun createUploadFileOperation(upload: OCUpload, user: User): UploadFileOperation { return UploadFileOperation( uploadsStorageManager, connectivityService, powerManagementService, user, null, upload, upload.nameCollisionPolicy, upload.localAction, context, upload.isUseWifiOnly, upload.isWhileChargingOnly, true, FileDataStorageManager(user, context.contentResolver) ).apply { addDataTransferProgressListener(this@FilesUploadWorker) } } @Suppress("TooGenericExceptionCaught") private fun upload(uploadFileOperation: UploadFileOperation, user: User): RemoteOperationResult<Any?> { lateinit var uploadResult: RemoteOperationResult<Any?> // start notification createNotification(uploadFileOperation) try { val storageManager = uploadFileOperation.storageManager // always get client from client manager, to get fresh credentials in case of update val ocAccount = OwnCloudAccount(user.toPlatformAccount(), context) val uploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context) uploadResult = uploadFileOperation.execute(uploadClient) // generate new Thumbnail val task = ThumbnailsCacheManager.ThumbnailGenerationTask(storageManager, user) val file = File(uploadFileOperation.originalStoragePath) val remoteId: String? = uploadFileOperation.file.remoteId task.execute(ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, remoteId)) } catch (e: Exception) { Log_OC.e(TAG, "Error uploading", e) uploadResult = RemoteOperationResult<Any?>(e) } finally { uploadsStorageManager.updateDatabaseUploadResult(uploadResult, uploadFileOperation) // cancel notification notificationManager.cancel(FOREGROUND_SERVICE_ID) } return uploadResult } /** * adapted from [com.owncloud.android.files.services.FileUploader.notifyUploadStart] */ private fun createNotification(uploadFileOperation: UploadFileOperation) { notificationBuilder .setOngoing(true) .setSmallIcon(R.drawable.notification_icon) .setTicker(context.getString(R.string.uploader_upload_in_progress_ticker)) .setProgress(MAX_PROGRESS, 0, false) .setContentText( String.format( context.getString(R.string.uploader_upload_in_progress_content), 0, uploadFileOperation.fileName ) ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD) } // includes a pending intent in the notification showing the details val intent = UploadListActivity.createIntent( uploadFileOperation.file, uploadFileOperation.user, Intent.FLAG_ACTIVITY_CLEAR_TOP, context ) notificationBuilder.setContentIntent( PendingIntent.getActivity( context, System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_IMMUTABLE ) ) if (!uploadFileOperation.isInstantPicture && !uploadFileOperation.isInstantVideo) { notificationManager.notify(FOREGROUND_SERVICE_ID, notificationBuilder.build()) } // else wait until the upload really start (onTransferProgress is called), so that if it's discarded // due to lack of Wifi, no notification is shown // TODO generalize for automated uploads } /** * see [com.owncloud.android.files.services.FileUploader.onTransferProgress] */ override fun onTransferProgress( progressRate: Long, totalTransferredSoFar: Long, totalToTransfer: Long, fileAbsoluteName: String ) { val percent = (MAX_PROGRESS * totalTransferredSoFar.toDouble() / totalToTransfer.toDouble()).toInt() if (percent != lastPercent) { notificationBuilder.setProgress(MAX_PROGRESS, percent, false) val fileName: String = fileAbsoluteName.substring(fileAbsoluteName.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1) val text = String.format(context.getString(R.string.uploader_upload_in_progress_content), percent, fileName) notificationBuilder.setContentText(text) notificationManager.notify(FOREGROUND_SERVICE_ID, notificationBuilder.build()) } lastPercent = percent } companion object { val TAG: String = FilesUploadWorker::class.java.simpleName private const val MAX_UPLOADS_QUERY = 100 private const val FOREGROUND_SERVICE_ID: Int = 412 private const val MAX_PROGRESS: Int = 100 const val ACCOUNT = "data_account" } }
gpl-2.0
614bc5551942d52d8b59fe5f8040d59b
40.75
120
0.696349
5.415272
false
false
false
false
groupdocs-comparison/GroupDocs.Comparison-for-Java
Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/usecase/GetLocalFilesUseCase.kt
1
2081
package com.groupdocs.ui.usecase import com.groupdocs.ui.util.InternalServerException import io.micronaut.context.annotation.Bean import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.nio.file.Files import java.nio.file.Path @Bean class GetLocalFilesUseCase { suspend operator fun invoke(directory: Path): List<LocalStorageEntry> = withContext(Dispatchers.IO) { if (Files.notExists(directory)) { throw GetLocalFilesException("Directory does not exist: ${directory.fileName}") } try { val entries = mutableListOf<LocalStorageEntry>() Files.newDirectoryStream(directory).use { directoryStream -> directoryStream.forEach { path -> val entry: LocalStorageEntry = when (Files.isDirectory(path)) { true -> { LocalStorageEntry.Directory( name = path.fileName.toString(), parentPath = directory ) } else -> { LocalStorageEntry.File( name = path.fileName.toString(), parentPath = directory, size = Files.size(path) ) } } entries.add(entry) } } entries } catch (e: Exception) { throw GetLocalFilesException("can't get content of $directory", e) } } } sealed class LocalStorageEntry(val name: String, val parentPath: Path) { class File(name: String, val size: Long, parentPath: Path) : LocalStorageEntry(name, parentPath) class Directory(name: String, parentPath: Path) : LocalStorageEntry(name, parentPath) val fullPath get() = parentPath.resolve(name) } class GetLocalFilesException(message: String, e: Throwable? = null) : InternalServerException(message, e)
mit
e6b2586dbda3b553256beeae05c6ab5b
39.038462
105
0.558866
5.519894
false
false
false
false
kesco/SlideBack-Xposed
app/src/main/kotlin/com/kesco/xposed/slideback/view/recycleview/LineDividerItemDecoration.kt
1
1991
package com.kesco.xposed.slideback.view.recycleview import android.R import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.support.v7.widget.RecyclerView import android.view.View /** * [RecyclerView]的分隔线,注意只支持垂直方向 * @author Kesco Lin */ public class LineDividerItemDecoration(ctx: Context, resId: Int = 0) : RecyclerView.ItemDecoration() { private val DEFAULT_ATTRS = intArrayOf(R.attr.listDivider) protected var divider: Drawable init { if (resId != 0) { divider = ctx.getDrawable(resId) } else { val a = ctx.obtainStyledAttributes(DEFAULT_ATTRS) divider = a.getDrawable(0) a.recycle() } } override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val endLeft = parent.paddingLeft val endRight = parent.width val left = endLeft val right = endRight - parent.paddingRight val childCount = parent.childCount for (i in 0..childCount - 1) { val child = parent.getChildAt(i) if (child.visibility != View.VISIBLE) { continue } val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + divider.intrinsicHeight if (i == childCount - 1) { divider.setBounds(endLeft, top, endRight, bottom) } else { divider.setBounds(left, top, right, bottom) } divider.draw(c) } } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { if (parent.getChildLayoutPosition(view) < 1) { return } outRect.top = divider.intrinsicHeight } }
mit
a2e6b28833e1589c8194868b3eea5356
29.230769
109
0.625954
4.435666
false
false
false
false
yukuku/androidbible
Alkitab/src/main/java/yuku/alkitab/datatransfer/process/Serializer.kt
1
414
package yuku.alkitab.datatransfer.process import kotlinx.serialization.json.Json object Serializer { val exportJson = Json { classDiscriminator = "kind" encodeDefaults = false prettyPrint = true @Suppress("EXPERIMENTAL_API_USAGE") prettyPrintIndent = " " } val importJson = Json { classDiscriminator = "kind" ignoreUnknownKeys = true } }
apache-2.0
16a39e0b84a44e214310ae55f4592cb7
22
43
0.640097
4.758621
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/holder/UserViewHolder.kt
1
11109
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.view.holder import android.support.v7.widget.RecyclerView.ViewHolder import android.view.View import android.view.View.OnClickListener import android.view.View.OnLongClickListener import android.widget.RelativeLayout import kotlinx.android.synthetic.main.list_item_user.view.* import org.mariotaku.ktextension.hideIfEmpty import org.mariotaku.ktextension.spannable import de.vanita5.twittnuker.R import de.vanita5.twittnuker.adapter.iface.IUsersAdapter import de.vanita5.twittnuker.adapter.iface.IUsersAdapter.* import de.vanita5.twittnuker.extension.loadProfileImage import de.vanita5.twittnuker.extension.model.hasSameHost import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.util.Utils import de.vanita5.twittnuker.util.Utils.getUserTypeIconRes import java.util.* class UserViewHolder( itemView: View, private val adapter: IUsersAdapter<*>, private val simple: Boolean = false, private val showFollow: Boolean = false ) : ViewHolder(itemView), OnClickListener, OnLongClickListener { private val itemContent = itemView.itemContent private val profileImageView = itemView.profileImage private val profileTypeView = itemView.profileType private val nameView = itemView.name private val externalIndicator = itemView.externalIndicator private val descriptionView = itemView.description private val locationView = itemView.location private val urlView = itemView.url private val statusesCountView = itemView.statusesCount private val followersCountView = itemView.followersCount private val friendsCountView = itemView.friendsCount private val acceptRequestButton = itemView.acceptRequest private val denyRequestButton = itemView.denyRequest private val unblockButton = itemView.unblock private val unmuteButton = itemView.unmute private val followButton = itemView.follow private val actionsProgressContainer = itemView.actionsProgressContainer private val actionsContainer = itemView.actionsContainer private val processingRequestProgress = itemView.processingRequest private val countsContainer = itemView.countsContainer private var userClickListener: UserClickListener? = null private var requestClickListener: RequestClickListener? = null private var friendshipClickListener: FriendshipClickListener? = null init { if (simple) { externalIndicator.visibility = View.GONE descriptionView.visibility = View.GONE locationView.visibility = View.GONE urlView.visibility = View.GONE countsContainer.visibility = View.GONE itemView.profileImageContainer.layoutParams.apply { (this as RelativeLayout.LayoutParams).clearVerticalRules() this.addRule(RelativeLayout.CENTER_VERTICAL) } nameView.layoutParams.apply { (this as RelativeLayout.LayoutParams).clearVerticalRules() this.addRule(RelativeLayout.CENTER_VERTICAL) } actionsProgressContainer.layoutParams.apply { (this as RelativeLayout.LayoutParams).clearVerticalRules() this.addRule(RelativeLayout.CENTER_VERTICAL) } } } fun display(user: ParcelableUser) { val context = itemView.context val manager = adapter.userColorNameManager val twitter = adapter.twitterWrapper itemContent.drawStart(manager.getUserColor(user.key)) val userTypeRes = getUserTypeIconRes(user.is_verified, user.is_protected) if (userTypeRes != 0) { profileTypeView.setImageResource(userTypeRes) } else { profileTypeView.setImageDrawable(null) } nameView.name = user.name nameView.screenName = "@${user.screen_name}" nameView.updateText(adapter.bidiFormatter) if (adapter.profileImageEnabled) { profileImageView.visibility = View.VISIBLE adapter.requestManager.loadProfileImage(context, user, adapter.profileImageStyle, profileImageView.cornerRadius, profileImageView.cornerRadiusRatio, adapter.profileImageSize).into(profileImageView) } else { profileImageView.visibility = View.GONE } val accountKey = user.account_key if (accountKey != null && twitter.isUpdatingRelationship(accountKey, user.key)) { processingRequestProgress.visibility = View.VISIBLE actionsContainer.visibility = View.GONE } else { processingRequestProgress.visibility = View.GONE actionsContainer.visibility = View.VISIBLE } if (accountKey != null && user.key.hasSameHost(accountKey)) { externalIndicator.visibility = View.GONE } else { externalIndicator.visibility = View.VISIBLE externalIndicator.text = context.getString(R.string.external_user_host_format, user.key.host) } followButton.setImageResource(if (user.is_following) R.drawable.ic_action_confirm else R.drawable.ic_action_add) followButton.isActivated = user.is_following val isMySelf = accountKey == user.key if (requestClickListener != null && !isMySelf) { acceptRequestButton.visibility = View.VISIBLE denyRequestButton.visibility = View.VISIBLE } else { acceptRequestButton.visibility = View.GONE denyRequestButton.visibility = View.GONE } if (friendshipClickListener != null && !isMySelf) { if (user.extras?.blocking ?: false) { followButton.visibility = View.GONE unblockButton.visibility = View.VISIBLE } else { if (showFollow) { followButton.visibility = View.VISIBLE } else { followButton.visibility = View.GONE } unblockButton.visibility = View.GONE } unmuteButton.visibility = if (user.extras?.muting ?: false) View.VISIBLE else View.GONE } else { followButton.visibility = View.GONE unblockButton.visibility = View.GONE unmuteButton.visibility = View.GONE } if (!simple) { descriptionView.spannable = user.description_unescaped descriptionView.hideIfEmpty() locationView.spannable = user.location locationView.hideIfEmpty() urlView.spannable = user.url_expanded urlView.hideIfEmpty() val locale = Locale.getDefault() statusesCountView.text = Utils.getLocalizedNumber(locale, user.statuses_count) followersCountView.text = Utils.getLocalizedNumber(locale, user.followers_count) friendsCountView.text = Utils.getLocalizedNumber(locale, user.friends_count) } } override fun onClick(v: View) { when (v.id) { R.id.itemContent -> { userClickListener?.onUserClick(this, layoutPosition) } R.id.acceptRequest -> { requestClickListener?.onAcceptClicked(this, layoutPosition) } R.id.denyRequest -> { requestClickListener?.onDenyClicked(this, layoutPosition) } R.id.follow -> { friendshipClickListener?.onFollowClicked(this, layoutPosition) } R.id.unblock -> { friendshipClickListener?.onUnblockClicked(this, layoutPosition) } R.id.unmute -> { friendshipClickListener?.onUnmuteClicked(this, layoutPosition) } } } override fun onLongClick(v: View): Boolean { when (v.id) { R.id.itemContent -> { return userClickListener?.onUserLongClick(this, layoutPosition) ?: false } } return false } fun setOnClickListeners() { setUserClickListener(adapter.userClickListener) setActionClickListeners(adapter.requestClickListener, adapter.friendshipClickListener) } private fun setActionClickListeners(requestClickListener: RequestClickListener?, friendshipClickListener: FriendshipClickListener?) { this.requestClickListener = requestClickListener this.friendshipClickListener = friendshipClickListener if (requestClickListener != null || friendshipClickListener != null) { nameView.twoLine = true actionsProgressContainer.visibility = View.VISIBLE } else { nameView.twoLine = false actionsProgressContainer.visibility = View.GONE } nameView.updateText() acceptRequestButton.setOnClickListener(this) denyRequestButton.setOnClickListener(this) followButton.setOnClickListener(this) unblockButton.setOnClickListener(this) unmuteButton.setOnClickListener(this) } fun setTextSize(textSize: Float) { descriptionView.textSize = textSize externalIndicator.textSize = textSize nameView.setPrimaryTextSize(textSize) nameView.setSecondaryTextSize(textSize * 0.75f) locationView.textSize = textSize urlView.textSize = textSize statusesCountView.textSize = textSize followersCountView.textSize = textSize friendsCountView.textSize = textSize } fun setUserClickListener(listener: UserClickListener?) { userClickListener = listener (itemContent as View).setOnClickListener(this) itemContent.setOnLongClickListener(this) } fun setupViewOptions() { profileImageView.style = adapter.profileImageStyle setTextSize(adapter.textSize) } private fun RelativeLayout.LayoutParams.clearVerticalRules() { intArrayOf(RelativeLayout.ABOVE, RelativeLayout.BELOW, RelativeLayout.ALIGN_BASELINE, RelativeLayout.ALIGN_TOP, RelativeLayout.ALIGN_BOTTOM).forEach { verb -> addRule(verb, 0) } } }
gpl-3.0
648e27d7a556d661e20a74472abc0fc5
39.845588
120
0.674588
5.274929
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/BaseAccountPreferenceFragment.kt
1
4837
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.os.Bundle import android.preference.PreferenceActivity.EXTRA_SHOW_FRAGMENT import android.text.TextUtils import android.view.Menu import android.view.MenuInflater import android.widget.CompoundButton import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.ACCOUNT_PREFERENCES_NAME_PREFIX import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_ACCOUNT import de.vanita5.twittnuker.constant.SharedPreferenceConstants.KEY_NAME_FIRST import de.vanita5.twittnuker.model.AccountDetails abstract class BaseAccountPreferenceFragment : BasePreferenceFragment() { protected val account: AccountDetails? get() { return arguments?.getParcelable(EXTRA_ACCOUNT) } protected abstract val preferencesResource: Int protected abstract val switchPreferenceDefault: Boolean protected abstract val switchPreferenceKey: String? private val preferenceChangeListener = OnSharedPreferenceChangeListener { _, key -> if (key == switchPreferenceKey) { updatePreferenceScreen() } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { val pm = preferenceManager val account: AccountDetails = arguments.getParcelable(EXTRA_ACCOUNT) ?: return val preferenceName = "$ACCOUNT_PREFERENCES_NAME_PREFIX${account.key}" pm.sharedPreferencesName = preferenceName addPreferencesFromResource(preferencesResource) val prefs = pm.sharedPreferences prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener) val activity = activity val intent = activity.intent if (intent.hasExtra(EXTRA_SHOW_FRAGMENT)) { val nameFirst = prefs.getBoolean(KEY_NAME_FIRST, true) val name = userColorNameManager.getDisplayName(account.key, account.user.name, account.user.screen_name, nameFirst) activity.title = name } updatePreferenceScreen() } override fun onDestroy() { val pm = preferenceManager val prefs = pm.sharedPreferences prefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener) super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { val switchKey = switchPreferenceKey if (!TextUtils.isEmpty(switchKey)) { inflater.inflate(R.menu.menu_switch_preference, menu) val actionView = menu.findItem(R.id.toggle).actionView val toggle = actionView.findViewById<CompoundButton>(android.R.id.toggle) val prefs = preferenceManager.sharedPreferences toggle.setOnCheckedChangeListener { _, isChecked -> val editor = prefs.edit() if (prefs.getBoolean(switchPreferenceKey, switchPreferenceDefault) != isChecked) { editor.putBoolean(switchPreferenceKey, isChecked) editor.apply() onSwitchPreferenceChanged(isChecked) updatePreferenceScreen() } } toggle.isChecked = prefs.getBoolean(switchKey, switchPreferenceDefault) } super.onCreateOptionsMenu(menu, inflater) } protected open fun onSwitchPreferenceChanged(isChecked: Boolean) { } private fun updatePreferenceScreen() { val screen = preferenceScreen val sharedPreferences = preferenceManager.sharedPreferences if (screen == null || sharedPreferences == null) return screen.isEnabled = sharedPreferences.getBoolean(switchPreferenceKey, switchPreferenceDefault) } }
gpl-3.0
49fd67ca11e6c27235a7fb70e2262aff
38.983471
101
0.712839
5.280568
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/analytics/NotificationPreferencesFunnel.kt
1
2189
package org.wikipedia.analytics import android.os.Build import androidx.core.app.NotificationManagerCompat import org.json.JSONObject import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.json.JsonUtil import org.wikipedia.notifications.NotificationCategory import org.wikipedia.notifications.NotificationFilterActivity import org.wikipedia.settings.Prefs class NotificationPreferencesFunnel(app: WikipediaApp) : Funnel(app, SCHEMA_NAME, REV_ID) { override fun preprocessSessionToken(eventData: JSONObject) {} fun done() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationManagerCompat = NotificationManagerCompat.from(app) val toggleMap = NotificationCategory.MAP.valueIterator().asSequence().associate { val importance = notificationManagerCompat.getNotificationChannel(it.id)?.importance // TODO: figure out the "Show notifications" status it.id to (importance != NotificationManagerCompat.IMPORTANCE_NONE && importance != null && notificationManagerCompat.areNotificationsEnabled()) } log( "type_toggles", JsonUtil.encodeToString(toggleMap), "background_fetch", app.resources.getInteger(R.integer.notification_poll_interval_minutes) ) } } fun logNotificationFilterPrefs() { val excludedWikiCodes = Prefs.notificationExcludedWikiCodes val excludedTypeCodes = Prefs.notificationExcludedTypeCodes val fullFiltersList = NotificationFilterActivity.allWikisList() + NotificationFilterActivity.allTypesIdList() val toggleMap = fullFiltersList.associateWith { !excludedWikiCodes.contains(it) && !excludedTypeCodes.contains(it) } log("type_toggles", JsonUtil.encodeToString(toggleMap)) } fun logSearchClick() { log("type_toggles", "search_clicked") } fun logFilterClick() { log("type_toggles", "filter_clicked") } companion object { private const val SCHEMA_NAME = "MobileWikiAppNotificationPreferences" private const val REV_ID = 22083261 } }
apache-2.0
1b78707856510b47862488dc01b544b8
39.537037
124
0.706715
4.93018
false
false
false
false
stripe/stripe-android
example/src/main/java/com/stripe/example/activity/CreateCardPaymentMethodActivity.kt
1
5418
package com.stripe.example.activity import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.stripe.android.model.PaymentMethod import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.example.databinding.CreateCardPaymentMethodActivityBinding import com.stripe.example.databinding.PaymentMethodItemBinding class CreateCardPaymentMethodActivity : AppCompatActivity() { private val viewBinding: CreateCardPaymentMethodActivityBinding by lazy { CreateCardPaymentMethodActivityBinding.inflate(layoutInflater) } private val viewModel: PaymentMethodViewModel by viewModels() private val adapter: PaymentMethodsAdapter = PaymentMethodsAdapter() private val snackbarController: SnackbarController by lazy { SnackbarController(viewBinding.coordinator) } private val keyboardController: KeyboardController by lazy { KeyboardController(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) viewBinding.paymentMethods.setHasFixedSize(false) viewBinding.paymentMethods.layoutManager = LinearLayoutManager(this) viewBinding.paymentMethods.adapter = adapter viewBinding.cardFormView.setCardValidCallback { isValid, invalidFields -> viewBinding.createButton.isEnabled = isValid Log.d( CARD_VALID_CALLBACK_TAG, "Card information is " + (if (isValid) " valid" else " invalid") ) if (!isValid) { Log.d(CARD_VALID_CALLBACK_TAG, " Invalid fields are $invalidFields") } } viewBinding.createButton.setOnClickListener { keyboardController.hide() viewBinding.cardFormView.cardParams?.let { createPaymentMethod(PaymentMethodCreateParams.createCard(it)) } } viewBinding.toggleCardFormView.setOnClickListener { viewBinding.cardFormView.isEnabled = !viewBinding.cardFormView.isEnabled showSnackbar( if (viewBinding.cardFormView.isEnabled) { "CardFormView Enabled" } else { "CardFormView Disabled" } ) } } private fun createPaymentMethod(params: PaymentMethodCreateParams) { onCreatePaymentMethodStart() viewModel.createPaymentMethod(params).observe(this) { result -> onCreatePaymentMethodCompleted() result.fold( onSuccess = ::onCreatedPaymentMethod, onFailure = { showSnackbar(it.message.orEmpty()) } ) } } private fun showSnackbar(message: String) { snackbarController.show(message) } private fun onCreatePaymentMethodStart() { viewBinding.progressBar.visibility = View.VISIBLE viewBinding.createButton.isEnabled = false } private fun onCreatePaymentMethodCompleted() { viewBinding.progressBar.visibility = View.INVISIBLE viewBinding.createButton.isEnabled = true } private fun onCreatedPaymentMethod(paymentMethod: PaymentMethod?) { if (paymentMethod != null) { adapter.paymentMethods.add(0, paymentMethod) adapter.notifyItemInserted(0) } else { showSnackbar("Created null PaymentMethod") } } private class PaymentMethodsAdapter : RecyclerView.Adapter<PaymentMethodsAdapter.PaymentMethodViewHolder>() { val paymentMethods: MutableList<PaymentMethod> = mutableListOf() init { setHasStableIds(true) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PaymentMethodViewHolder { return PaymentMethodViewHolder( PaymentMethodItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemCount(): Int { return paymentMethods.size } override fun onBindViewHolder(holder: PaymentMethodViewHolder, position: Int) { holder.setPaymentMethod(paymentMethods[position]) } override fun getItemId(position: Int): Long { return requireNotNull(paymentMethods[position].id).hashCode().toLong() } class PaymentMethodViewHolder internal constructor( private val viewBinding: PaymentMethodItemBinding ) : RecyclerView.ViewHolder(viewBinding.root) { internal fun setPaymentMethod(paymentMethod: PaymentMethod) { val card = paymentMethod.card viewBinding.paymentMethodId.text = paymentMethod.id viewBinding.brand.text = card?.brand?.displayName.orEmpty() viewBinding.last4.text = card?.last4.orEmpty() } } } private companion object { private const val CARD_VALID_CALLBACK_TAG = "CardValidCallback" } }
mit
64a5fd30645d5657826ffd2a6e2749cf
34.644737
100
0.658915
5.973539
false
false
false
false
andimage/PCBridge
src/test/com/projectcitybuild/stubs/PlayerConfigMock.kt
1
378
package com.projectcitybuild import com.projectcitybuild.entities.PlayerConfig import java.time.LocalDateTime import java.util.UUID fun PlayerConfigMock(uuid: UUID? = null): PlayerConfig { return PlayerConfig( id = 1, uuid = uuid ?: UUID.randomUUID(), isMuted = false, isAllowingTPs = true, firstSeen = LocalDateTime.now(), ) }
mit
6398e0230dd697ef3729f9e3dad3e9b8
24.2
56
0.677249
4.153846
false
true
false
false
eggeral/3d-playground
src/main/kotlin/glmatrix/GlMatrix.kt
1
1806
package glmatrix import kotlin.js.Math open class GlMatrix { companion object { /** * Common utilities * @module GlMatrix */ // Configuration Constants val EPSILON = 0.000001 val RANDOM = Math.random() private val degree = Math.PI / 180 /** * Convert Degree To Radian * * @param {Double} angleInDegree Angle in Degrees */ fun toRadian(angleInDegree: Double): Double { return angleInDegree * degree } /** * Convert Degree To Radian * * @param {Float} angleInDegree Angle in Degrees */ fun toRadian(angleInDegree: Float): Double { return angleInDegree * degree } fun perspectiveProjectionMatrix(fieldOfViewInRadians: Float, aspectRatio: Float, near: Float, far: Float): Array<Float> { val f = (1.0 / Math.tan(fieldOfViewInRadians / 2.0)).toFloat() val rangeInv = 1 / (near - far) return arrayOf( f / aspectRatio, 0.0f, 0.0f, 0.0f, 0.0f, f, 0.0f, 0.0f, 0.0f, 0.0f, (near + far) * rangeInv, -1.0f, 0.0f, 0.0f, near * far * rangeInv * 2, 0.0f ) } fun orthographicProjectionMatrix(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float): Array<Float> { return arrayOf( 2.0f / (right - left), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (top - bottom), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (near - far), 0.0f, (left + right) / (left - right), (bottom + top) / (bottom - top), (near + far) / (near - far), 1.0f ) } } }
apache-2.0
faa0d1c1849d58ee7ed1070f34d7d97c
31.25
135
0.492802
3.754678
false
false
false
false
evanjpw/rotlin
src/main/kotlin/us/cornus/rotlin/path/Dijkstra.kt
1
2037
package us.cornus.rotlin.path /** * Created by ejw on 5/30/17. */ import us.cornus.rotlin.shift import us.cornus.rotlin.push data class DJItem(val x : Int, val y : Int, val prev : DJItem?) /** * @class Simplified Dijkstra's algorithm: all edges have a value of 1 * @augments ROT.Path * @see ROT.Path */ class Dijkstra(toX : Int, toY : Int, options : PathOptions, passableCallback: PathCallback) : Path(toX, toY, options, passableCallback) { constructor(toX : Int, toY : Int, topology: Int = 8, passableCallback: PathCallback) : this(toX, toY, PathOptions(topology), passableCallback) constructor(toX: Int, toY : Int, passableCallback: PathCallback, options: PathOptions) : this(toX, toY, options, passableCallback) private val computed = HashMap<String, DJItem>() private val todo = ArrayList<DJItem>() init { add(toX, toY, null) } /** * Compute a path from a given point * @see Path#compute */ override fun compute(fromX : Int, fromY : Int, callback : PathCallback) { val key = "$fromX,$fromY" if (key !in computed) { _compute(fromX, fromY) } if (key !in computed) { return } var item = computed[key] while (item != null) { callback(item.x, item.y) item = item.prev } } /** * Compute a non-cached value */ private fun _compute(fromX : Int, fromY : Int) { while (todo.size != 0) { val item = todo.shift()!! if (item.x == fromX && item.y == fromY) { return } val neighbors = this._getNeighbors(item.x, item.y) for ((x, y) in neighbors) { val id = "$x,$y" if (id in computed) { continue } /* already done */ add(x, y, item) } } } private fun add(x : Int, y : Int, prev : DJItem?) { val obj = DJItem( x = x, y = y, prev = prev ) computed["$x,$y"] = obj todo.push(obj) } }
bsd-3-clause
1c3f69582bd91a4e64f20c9aff52db25
27.305556
146
0.555228
3.710383
false
false
false
false
satamas/fortran-plugin
src/test/kotlin/org/jetbrains/fortran/lang/parsing/FortranBaseParsingTestCase.kt
1
1774
package org.jetbrains.fortran.lang.parsing import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.IFileElementType import com.intellij.testFramework.ParsingTestCase import com.intellij.util.PathUtil import org.jetbrains.fortran.FortranFixedFormLanguage import org.jetbrains.fortran.FortranLanguage import org.jetbrains.fortran.lang.parser.FortranFixedFormParserDefinition import org.jetbrains.fortran.lang.parser.FortranParserDefinition import org.jetbrains.fortran.lang.stubs.FortranFileStub abstract class FortranBaseParsingTestCase : ParsingTestCase( ".", "f", FortranParserDefinition(), FortranFixedFormParserDefinition() ) { override fun getTestDataPath() = "src/test/resources/psi" override fun includeRanges() = true fun doPreprocessorParsingTest(filePath: String) { doBaseTest(filePath, FortranFileStub.Type) } @Throws(Exception::class) fun doParsingTest(filePath: String) { if (filePath.endsWith(".f") || filePath.endsWith(".for")) { doBaseTest(filePath, IFileElementType(FortranFixedFormLanguage)) } else { doBaseTest(filePath, IFileElementType(FortranLanguage)) } } @Throws(Exception::class) private fun doBaseTest(filePath: String, fileType: IElementType) { myLanguage = fileType.language myFileExt = FileUtilRt.getExtension(PathUtil.getFileName(filePath)) myFile = createPsiFile(FileUtil.getNameWithoutExtension(PathUtil.getFileName(filePath)), loadFile(filePath)) doCheckResult(myFullDataPath, filePath.replace("\\.(for|f90|f95|f03|f08|f)".toRegex(), ".txt"), toParseTreeText(myFile, false, false).trim()) } }
apache-2.0
62a1b99dd398eb3fe95a5fdf3ac89298
41.238095
149
0.757046
4.412935
false
true
false
false
TakWolf/Android-HeaderAndFooterRecyclerView
app/src/main/java/com/takwolf/android/demo/hfrecyclerview/ui/activity/StaggeredHorizontalActivity.kt
1
1847
package com.takwolf.android.demo.hfrecyclerview.ui.activity import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.takwolf.android.demo.hfrecyclerview.R import com.takwolf.android.demo.hfrecyclerview.databinding.ActivityRecyclerViewBinding import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotoDeleteListener import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotosSwapListener import com.takwolf.android.demo.hfrecyclerview.ui.adapter.StaggeredHorizontalAdapter import com.takwolf.android.demo.hfrecyclerview.vm.SingleListViewModel import com.takwolf.android.demo.hfrecyclerview.vm.holder.setupView class StaggeredHorizontalActivity : AppCompatActivity() { private val viewModel: SingleListViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityRecyclerViewBinding.inflate(layoutInflater) binding.toolbar.setTitle(R.string.staggered_horizontal) binding.toolbar.setNavigationOnClickListener { finish() } binding.recyclerView.layoutManager = StaggeredGridLayoutManager(3, RecyclerView.HORIZONTAL) viewModel.extraHolder.setupHorizontal(layoutInflater, binding.recyclerView, binding.hfDashboard) val adapter = StaggeredHorizontalAdapter(layoutInflater).apply { onPhotosSwapListener = OnPhotosSwapListener(viewModel.photosHolder) onPhotoDeleteListener = OnPhotoDeleteListener(viewModel.photosHolder) } binding.recyclerView.adapter = adapter viewModel.photosHolder.setupView(this, adapter) setContentView(binding.root) } }
apache-2.0
194c0a4e8cf5adcb9364d50f0495dcc5
46.358974
104
0.801299
5.046448
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/HatchingPotion.kt
2
512
package com.habitrpg.android.habitica.models.inventory import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class HatchingPotion : RealmObject(), Item { @PrimaryKey override var key: String = "" override var text: String = "" override var event: ItemEvent? = null var notes: String? = null override var value: Int = 0 var limited: Boolean? = null var premium: Boolean? = null override val type: String get() = "hatchingPotions" }
gpl-3.0
09734fadf57c26bdd788d1386911fd3a
28.117647
54
0.669922
4.376068
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/KotlinScriptEditor.kt
1
3958
/******************************************************************************* * 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 org.jetbrains.kotlin.ui.editors import org.eclipse.core.runtime.jobs.Job import org.eclipse.jdt.core.IJavaProject import org.eclipse.jdt.core.JavaCore import org.eclipse.jface.text.IDocument import org.eclipse.swt.widgets.Composite import org.eclipse.ui.PlatformUI import org.jetbrains.kotlin.core.builder.KotlinPsiManager import org.jetbrains.kotlin.core.model.KotlinScriptEnvironment import org.jetbrains.kotlin.core.model.getEnvironment import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.script.KotlinScriptExternalDependencies import org.jetbrains.kotlin.ui.editors.annotations.KotlinLineAnnotationsReconciler import org.jetbrains.kotlin.script.ScriptDependenciesProvider import kotlin.script.experimental.dependencies.ScriptDependencies class KotlinScriptEditor : KotlinCommonEditor() { override val parsedFile: KtFile? get() { val file = eclipseFile ?: return null return KotlinPsiManager.getKotlinFileIfExist(file, document.get()) } override val javaProject: IJavaProject? by lazy { eclipseFile?.let { JavaCore.create(it.getProject()) } } override val document: IDocument get() = getDocumentProvider().getDocument(getEditorInput()) override fun createPartControl(parent: Composite) { super.createPartControl(parent) val file = eclipseFile ?: return val environment = getEnvironment(file) as KotlinScriptEnvironment environment.initializeScriptDefinitions { scriptDefinitions, classpath -> if (file.isAccessible && isOpen()) { reconcile { KotlinScriptEnvironment.replaceEnvironment(file, scriptDefinitions, classpath, null) } } } } override val isScript: Boolean get() = true override fun dispose() { val file = eclipseFile if (file != null && file.exists()) { val family = KotlinScriptEnvironment.constructFamilyForInitialization(file); Job.getJobManager().cancel(family); } super.dispose() eclipseFile?.let { KotlinScriptEnvironment.removeKotlinEnvironment(it) KotlinPsiManager.removeFile(it) } } internal fun reconcile(runBeforeReconciliation: () -> Unit = {}) { kotlinReconcilingStrategy.reconcile(runBeforeReconciliation) } } fun getScriptDependencies(editor: KotlinScriptEditor): ScriptDependencies? { val eclipseFile = editor.eclipseFile ?: return null val project = getEnvironment(eclipseFile).project val definition = ScriptDependenciesProvider.getInstance(project) val ktFile = editor.parsedFile ?: return null return definition.getScriptDependencies(ktFile) } fun KotlinCommonEditor.isOpen(): Boolean { for (window in PlatformUI.getWorkbench().getWorkbenchWindows()) { for (page in window.getPages()) { for (editorReference in page.getEditorReferences()) { if (editorReference.getEditor(false) == this) { return true } } } } return false }
apache-2.0
83b47f31d4fe39810ab8b2a8d1584e7a
35.657407
101
0.665488
5.087404
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/lang/core/resolve/reference/ModuleNameQualifierReference.kt
1
3230
package org.elm.lang.core.resolve.reference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.elm.lang.core.psi.ElmNamedElement import org.elm.lang.core.psi.ElmPsiFactory import org.elm.lang.core.psi.ElmQID import org.elm.lang.core.psi.elements.ElmUpperCaseQID import org.elm.lang.core.psi.elements.ElmValueQID import org.elm.lang.core.psi.offsetIn import org.elm.lang.core.resolve.ElmReferenceElement import org.elm.lang.core.resolve.scope.GlobalScope import org.elm.lang.core.resolve.scope.ModuleScope import org.elm.lang.core.stubs.index.ElmModulesIndex /** * A module-name (or alias) reference which qualifies a name from the value or type namespaces. * * e.g. `Data.User` in the expression `Data.User.name defaultUser` * * e.g. the `DU` alias in the expression `DU.name` in the program: * ``` * import Data.User as DU * f x = DU.name x * ``` * * @param elem the Psi element which owns the reference * @param elementQID the QID (qualified ID) element within `elem` */ class ModuleNameQualifierReference<T : ElmReferenceElement>( elem: T, private val elementQID: ElmQID, // IMPORTANT: do not use in stub-based codepaths; denormalize instead! qualifierPrefix: String // denormalized from [elementQID] to support Stubs ) : ElmReferenceCached<T>(elem), ElmReference { private val refText: String = qualifierPrefix override fun resolveInner(): ElmNamedElement? { val clientFile = element.elmFile val importDecls = ModuleScope.getImportDecls(clientFile) // First, check to see if it resolves to an aliased import for (decl in importDecls) { val asClause = decl.asClause if (asClause?.name == refText) return asClause } // Otherwise, try to resolve the import directly val targetModuleName = GlobalScope.defaultAliases[refText] ?: refText val targetDecl = ElmModulesIndex.get(targetModuleName, clientFile) ?: return null // Ensure that it's in scope return when { targetModuleName in GlobalScope.defaultImports -> targetDecl importDecls.any { it.moduleQID.text == refText } -> targetDecl else -> null } } override fun getVariants(): Array<ElmNamedElement> { // Code-completion of Elm module names is not done via the PsiReference 'variant' system. // Instead, see `ElmCompletionProvider` return emptyArray() } override fun calculateDefaultRangeInElement(): TextRange { val startOffset = elementQID.offsetIn(element) return TextRange(startOffset, startOffset + refText.length) } override fun handleElementRename(newElementName: String): PsiElement { val factory = ElmPsiFactory(element.project) val nameParts = elementQID.text.split(".") val newName = newElementName + "." + nameParts.last() val newId = when (elementQID) { is ElmUpperCaseQID -> factory.createUpperCaseQID(newName) is ElmValueQID -> factory.createValueQID(newName) else -> error("unexpected QID type") } elementQID.replace(newId) return element } }
mit
30828722c5b0b4f99c8f8f3607d37319
37.452381
110
0.691641
4.318182
false
false
false
false
google/android-auto-companion-android
communication/tests/unit/src/com/google/android/libraries/car/notifications/NotificationUtilsTest.kt
1
7143
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.notifications import android.service.notification.StatusBarNotification import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat.MessagingStyle import androidx.core.app.Person import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import java.time.Instant import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class NotificationUtilsTest { private val defaultKey = "key" @Test fun passesCarMsgRequirements_returnsTrueWhenValid() { val sbn = createSBN() val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isTrue() } @Test fun passesCarMsgRequirements_noReplyAction() { val sbn = createSBN(hasReplyAction = false) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isFalse() } @Test fun passesCarMsgRequirements_noMarkAsReadAction() { val sbn = createSBN(hasMarkAsRead = false) val passesStrictCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesStrictCarMsgRequirements).isFalse() val passesRelaxedCarMsgRequirements = sbn.notification.passesRelaxedCarMsgRequirements assertThat(passesRelaxedCarMsgRequirements).isTrue() } @Test fun passesCarMsgRequirements_usingInvisibleActions() { val sbn = createSBN(useInvisibleActions = true) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isTrue() } @Test fun passesCarMsgRequirements_showsUI() { val sbn = createSBN(showsUI = true) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isFalse() } @Test fun passesCarMsgRequirements_showsUI_InvisibleActions() { val sbn = createSBN(showsUI = true, useInvisibleActions = true) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isFalse() } @Test fun passesCarMsgRequirements_noMessagingStyle() { val sbn = createSBN(hasMessagingStyle = false) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isFalse() } @Test fun replyAction_returnsAppropriateAction() { val sbn = createSBN() val replyAction = sbn.notification.replyAction assertThat(replyAction).isNotNull() assertThat(replyAction?.semanticAction) .isEqualTo(NotificationCompat.Action.SEMANTIC_ACTION_REPLY) } @Test fun replyAction_returnsAppropriateActio_whenInvisible() { val sbn = createSBN(useInvisibleActions = true) val replyAction = sbn.notification.replyAction assertThat(replyAction).isNotNull() assertThat(replyAction?.semanticAction) .isEqualTo(NotificationCompat.Action.SEMANTIC_ACTION_REPLY) } @Test fun replyAction_noActionFound() { val sbn = createSBN(hasReplyAction = false) val replyAction = sbn.notification.replyAction assertThat(replyAction).isNull() } @Test fun replyAction_wrongReplySemanticAction() { val sbn = createSBN(hasWrongReplySemanticAction = true) val replyAction = sbn.notification.replyAction assertThat(replyAction).isNull() } @Test fun markAsReadAction_returnsAppropriateAction() { val sbn = createSBN(hasMarkAsRead = true) val action = sbn.notification.markAsReadAction assertThat(action).isNotNull() assertThat(action?.semanticAction) .isEqualTo(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ) } @Test fun markAsReadAction_returnsAppropriateAction_whenInvisible() { val sbn = createSBN(hasMarkAsRead = true, useInvisibleActions = true) val action = sbn.notification.markAsReadAction assertThat(action).isNotNull() assertThat(action?.semanticAction) .isEqualTo(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ) } @Test fun markAsReadAction_noMarkAsReadFound() { val sbn = createSBN(hasMarkAsRead = false) val action = sbn.notification.markAsReadAction assertThat(action).isNull() } @Test fun showsUI_returnsTrueAsAppropriate() { val sbn = createSBN(showsUI = true) val showsUI = sbn.notification.showsUI assertThat(showsUI).isTrue() } @Test fun showsUI_returnsFalseAsAppropriate() { val sbn = createSBN(showsUI = false) val showsUI = sbn.notification.showsUI assertThat(showsUI).isFalse() } @Test fun messagingStyle_returnsStyleWhenFound() { val sbn = createSBN(hasMessagingStyle = true) val style = sbn.notification.messagingStyle assertThat(style).isNotNull() assertThat(sbn.notification.messagingStyle?.user?.name).isNotNull() } @Test fun lastMessage_getsAppropriateMessage() { val style = MessagingStyle(Person.Builder().setName("user").build()) val firstMessage = MessagingStyle.Message( "Text Message One", Instant.now().toEpochMilli() + 100, Person.Builder().setName("senderOne").build() ) val lastMessage = MessagingStyle.Message( "Text Message Two", Instant.now().toEpochMilli() + 200, Person.Builder().setName("senderTwo").build() ) style.addMessage(lastMessage) style.addMessage(firstMessage) assertThat(style.lastMessage).isEqualTo(lastMessage) } /** * Default functionality is a valid message [StatusBarNotification]. To make invalid, you may * customize the input. */ private fun createSBN( hasMessagingStyle: Boolean = true, isOldMessage: Boolean = false, hasReplyAction: Boolean = true, hasWrongReplySemanticAction: Boolean = false, hasMarkAsRead: Boolean = true, useInvisibleActions: Boolean = false, showsUI: Boolean = false, key: String = defaultKey, connectionTime: Instant = Instant.now(), postSpecificMessage: MessagingStyle.Message? = null ): StatusBarNotification { return MessageNotificationMocks.createSBN( hasMessagingStyle = hasMessagingStyle, isOldMessage = isOldMessage, hasReplyAction = hasReplyAction, hasWrongReplySemanticAction = hasWrongReplySemanticAction, hasMarkAsRead = hasMarkAsRead, useInvisibleActions = useInvisibleActions, key = key, showsUI = showsUI, connectionTime = connectionTime, postSpecificMessage = postSpecificMessage ) } }
apache-2.0
3b84d3dd9263c08809edfd6ad49be0ef
33.014286
95
0.749125
5.127782
false
true
false
false
google-developer-training/basic-android-kotlin-compose-training-woof
app/src/main/java/com/example/woof/MainActivity.kt
1
8731
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.woof import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.woof.data.Dog import com.example.woof.data.dogs import com.example.woof.ui.theme.WoofTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { WoofTheme { WoofApp() } } } } /** * Composable that displays an app bar and a list of dogs. */ @Composable fun WoofApp() { Scaffold( topBar = { WoofTopAppBar() } ) { LazyColumn(modifier = Modifier.background(MaterialTheme.colors.background)) { items(dogs) { DogItem(dog = it) } } } } /** * Composable that displays a list item containing a dog icon and their information. * * @param dog contains the data that populates the list item * @param modifier modifiers to set to this composable */ @Composable fun DogItem(dog: Dog, modifier: Modifier = Modifier) { var expanded by remember { mutableStateOf(false) } Card( elevation = 4.dp, modifier = modifier.padding(8.dp) ) { Column( modifier = Modifier .animateContentSize( animationSpec = spring( dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow ) ) ) { Row( modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { DogIcon(dog.imageResourceId) DogInformation(dog.name, dog.age) Spacer(Modifier.weight(1f)) DogItemButton( expanded = expanded, onClick = { expanded = !expanded }, ) } if (expanded) { DogHobby(dog.hobbies) } } } } /** * Composable that displays a button that is clickable and displays an expand more or an expand less * icon. * * @param expanded represents whether the expand more or expand less icon is visible * @param onClick is the action that happens when the button is clicked * @param modifier modifiers to set to this composable */ @Composable private fun DogItemButton( expanded: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier ) { IconButton(onClick = onClick) { Icon( imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, tint = MaterialTheme.colors.secondary, contentDescription = stringResource(R.string.expand_button_content_description), ) } } /** * Composable that displays a Top Bar with an icon and text. * * @param modifier modifiers to set to this composable */ @Composable fun WoofTopAppBar(modifier: Modifier = Modifier) { Row( modifier = modifier .fillMaxWidth() .background(color = MaterialTheme.colors.primary), verticalAlignment = Alignment.CenterVertically ) { Image( modifier = modifier .size(64.dp) .padding(8.dp), painter = painterResource(R.drawable.ic_woof_logo), /* * Content Description is not needed here - image is decorative, and setting a null * content description allows accessibility services to skip this element during * navigation. */ contentDescription = null ) Text( text = stringResource(R.string.app_name), style = MaterialTheme.typography.h1 ) } } /** * Composable that displays a photo of a dog. * * @param dogIcon is the resource ID for the image of the dog * @param modifier modifiers to set to this composable */ @Composable fun DogIcon(@DrawableRes dogIcon: Int, modifier: Modifier = Modifier) { Image( modifier = modifier .size(64.dp) .padding(8.dp) .clip(RoundedCornerShape(50)), contentScale = ContentScale.Crop, painter = painterResource(dogIcon), /* * Content Description is not needed here - image is decorative, and setting a null content * description allows accessibility services to skip this element during navigation. */ contentDescription = null ) } /** * Composable that displays a dog's name and age. * * @param dogName is the resource ID for the string of the dog's name * @param dogAge is the Int that represents the dog's age * @param modifier modifiers to set to this composable */ @Composable fun DogInformation(@StringRes dogName: Int, dogAge: Int, modifier: Modifier = Modifier) { Column { Text( text = stringResource(dogName), style = MaterialTheme.typography.h2, modifier = modifier.padding(top = 8.dp) ) Text( text = stringResource(R.string.years_old, dogAge), style = MaterialTheme.typography.body1 ) } } /** * Composable that displays a dog's hobbies. * * @param dogHobby is the resource ID for the text string of the hobby to display * @param modifier modifiers to set to this composable */ @Composable fun DogHobby(@StringRes dogHobby: Int, modifier: Modifier = Modifier) { Column( modifier = modifier.padding( start = 16.dp, top = 8.dp, bottom = 16.dp, end = 16.dp ) ) { Text( text = stringResource(R.string.about), style = MaterialTheme.typography.h3 ) Text( text = stringResource(dogHobby), style = MaterialTheme.typography.body1 ) } } /** * Composable that displays what the UI of the app looks like in light theme in the design tab. */ @Preview @Composable fun WoofPreview() { WoofTheme(darkTheme = false) { WoofApp() } } /** * Composable that displays what the UI of the app looks like in dark theme in the design tab. */ @Preview @Composable fun WoofDarkThemePreview() { WoofTheme(darkTheme = true) { WoofApp() } }
apache-2.0
5d5ed127658782bdf33397208916deb0
30.071174
100
0.659604
4.552138
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/worker/WorkerManagerHelper.kt
1
1526
package at.ac.tuwien.caa.docscan.worker import android.content.Context import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.WorkQuery import java.util.* /** * @return a list of some worker jobs. * * The params are set to return jobs for all tags, but only for work.info states that are != SUCCEEDED. */ fun getCurrentWorkerJobStates( context: Context, tags: List<String> = listOf( UploadWorker.UPLOAD_TAG, ExportWorker.EXPORT_TAG, DocumentSanitizeWorker.TAG ), states: List<WorkInfo.State> = WorkInfo.State.values() .filter { state -> state != WorkInfo.State.SUCCEEDED }, ): List<DocScanWorkInfo> { val docScanWorkInfos = mutableListOf<DocScanWorkInfo>() val workInfosFuture = WorkManager.getInstance(context) .getWorkInfos(WorkQuery.Builder.fromTags(tags).addStates(states).build()) // TODO: Call can throw val workInfos = workInfosFuture.get() workInfos.forEach { // we assume that a worker request was always associated with just one tag. val firstTag = it.tags.firstOrNull() if (firstTag != null) { docScanWorkInfos.add(DocScanWorkInfo(firstTag, it.id, it)) } } return docScanWorkInfos.sortedBy { docScanWorkInfo -> docScanWorkInfo.tag } } data class DocScanWorkInfo(val tag: String, val jobId: UUID, val workInfo: WorkInfo) { override fun toString(): String { return "DocScanWorkInfo{tag=${tag}, jobId=${jobId}, workInfo=$workInfo}}" } }
lgpl-3.0
e2e2ef6b70793334293d7491126f1003
33.681818
103
0.695282
4.091153
false
false
false
false
konrad-jamrozik/utilities
src/main/kotlin/com/konradjamrozik/Resource.kt
1
2859
// Author: Konrad Jamrozik, github.com/konrad-jamrozik package com.konradjamrozik import java.io.File import java.io.IOException import java.net.JarURLConnection import java.net.URL import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardCopyOption class Resource @JvmOverloads constructor(val name: String, val allowAmbiguity: Boolean = false) { val urls: List<URL> = { val urls = ClassLoader.getSystemResources(name).toList() if (urls.isEmpty()) throw IOException("No resource URLs found for path \"$name\"") if (!allowAmbiguity && urls.size > 1) throw IOException("More than one resource URL found for path $name. " + "The found URLs:\n${urls.joinToString(separator = "\n")}") urls }() val text: String by lazy { url.text } val url: URL by lazy { check(!allowAmbiguity, { "check failed: !allowAmbiguity" }) urls.single() } val path: Path by lazy { check(url.protocol == "file", { "cannot get path on a resource whose protocol is not 'file'. " + "The protocol is instead '${urls.single().protocol}'" }) Paths.get(urls.single().toURI()) } val file: File by lazy { check(!allowAmbiguity, { "check failed: !allowAmbiguity" }) File(url.toURI()) } private fun copyBesideContainer(url: URL): Path { val jarUrlConnection = url.openConnection() as JarURLConnection val jarFile = File(jarUrlConnection.jarFileURL.toURI()) // Example jarFile: C:\my\local\repos\github\utilities\build\resources\test\toplevel.jar val jarDir = jarFile.parent // Example jarDir: C:\my\local\repos\github\utilities\build\resources\test val jarEntry = jarUrlConnection.jarEntry.toString() // Example jarEntry: nested.jar val targetPath = Paths.get(jarDir, jarEntry) // Example targetPath: C:\my\local\repos\github\utilities\build\resources\test\nested.jar Files.copy(url.openStream(), targetPath) return targetPath } fun withExtractedPath(block: Path.() -> Unit) { if (url.protocol == "file") Paths.get(url.toURI()).block() else { val extractedPath = copyBesideContainer(url) extractedPath.block() check (extractedPath.isRegularFile, { ("Failure: extracted path $extractedPath has been deleted while being processed in the 'withExtractedPath' block.") }) Files.delete(extractedPath) } } fun extractTo(targetDir: Path): Path { val targetFile = if (url.protocol == "file") { targetDir.resolve(name) } else { val jarUrlConnection = url.openConnection() as JarURLConnection targetDir.resolve(jarUrlConnection.jarEntry.toString()) } targetFile.mkdirs() Files.copy(url.openStream(), targetFile, StandardCopyOption.REPLACE_EXISTING) return targetFile } }
mit
3b9cade5e2f830cfea0b0b6aeae04358
28.484536
128
0.683806
4.066856
false
false
false
false
pbauerochse/youtrack-worklog-viewer
application/src/main/java/de/pbauerochse/worklogviewer/view/IssueReportRow.kt
1
884
package de.pbauerochse.worklogviewer.view import de.pbauerochse.worklogviewer.timereport.Issue import de.pbauerochse.worklogviewer.timereport.IssueWithWorkItems import de.pbauerochse.worklogviewer.timereport.view.ReportRow import java.time.LocalDate /** * A row containing the work items for a certain [Issue] */ data class IssueReportRow(val issueWithWorkItems: IssueWithWorkItems) : ReportRow { override val isGrouping: Boolean = false override val isIssue: Boolean = true override val isSummary: Boolean = false override val label: String = issueWithWorkItems.issue.fullTitle override val children: List<ReportRow> = emptyList() override val totalDurationInMinutes: Long = issueWithWorkItems.totalTimeInMinutes override fun getDurationInMinutes(date: LocalDate): Long = issueWithWorkItems.getWorkItemsForDate(date).sumOf { it.durationInMinutes } }
mit
fa4d0d802cb015bd00bbe76245ba5e9d
41.142857
138
0.803167
4.778378
false
false
false
false
firebase/snippets-android
database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/OfflineActivity.kt
1
7117
package com.google.firebase.referencecode.database.kotlin import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.google.firebase.database.ChildEventListener import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.ServerValue import com.google.firebase.database.ValueEventListener import com.google.firebase.database.ktx.database import com.google.firebase.database.ktx.getValue import com.google.firebase.ktx.Firebase class OfflineActivity : AppCompatActivity() { private fun enablePersistence() { // [START rtdb_enable_persistence] Firebase.database.setPersistenceEnabled(true) // [END rtdb_enable_persistence] } private fun keepSynced() { // [START rtdb_keep_synced] val scoresRef = Firebase.database.getReference("scores") scoresRef.keepSynced(true) // [END rtdb_keep_synced] // [START rtdb_undo_keep_synced] scoresRef.keepSynced(false) // [END rtdb_undo_keep_synced] } private fun queryRecentScores() { // [START rtdb_query_recent_scores] val scoresRef = Firebase.database.getReference("scores") scoresRef.orderByValue().limitToLast(4).addChildEventListener(object : ChildEventListener { override fun onChildAdded(snapshot: DataSnapshot, previousChild: String?) { Log.d(TAG, "The ${snapshot.key} dinosaur's score is ${snapshot.value}") } // [START_EXCLUDE] override fun onChildRemoved(dataSnapshot: DataSnapshot) = Unit override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) = Unit override fun onCancelled(databaseError: DatabaseError) = Unit override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) = Unit // [END_EXCLUDE] }) // [END rtdb_query_recent_scores] // [START rtdb_query_recent_scores_overlap] scoresRef.orderByValue().limitToLast(2).addChildEventListener(object : ChildEventListener { override fun onChildAdded(snapshot: DataSnapshot, previousChild: String?) { Log.d(TAG, "The ${snapshot.key} dinosaur's score is ${snapshot.value}") } // [START_EXCLUDE] override fun onChildRemoved(dataSnapshot: DataSnapshot) = Unit override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) = Unit override fun onCancelled(databaseError: DatabaseError) = Unit override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) = Unit // [END_EXCLUDE] }) // [END rtdb_query_recent_scores_overlap] } private fun onDisconnect() { // [START rtdb_on_disconnect_set] val presenceRef = Firebase.database.getReference("disconnectmessage") // Write a string when this client loses connection presenceRef.onDisconnect().setValue("I disconnected!") // [END rtdb_on_disconnect_set] // [START rtdb_on_disconnect_remove] presenceRef.onDisconnect().removeValue { error, reference -> error?.let { Log.d(TAG, "could not establish onDisconnect event: ${error.message}") } } // [END rtdb_on_disconnect_remove] // [START rtdb_on_disconnect_cancel] val onDisconnectRef = presenceRef.onDisconnect() onDisconnectRef.setValue("I disconnected") // ... // some time later when we change our minds // ... onDisconnectRef.cancel() // [END rtdb_on_disconnect_cancel] } private fun getConnectionState() { // [START rtdb_listen_connected] val connectedRef = Firebase.database.getReference(".info/connected") connectedRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val connected = snapshot.getValue(Boolean::class.java) ?: false if (connected) { Log.d(TAG, "connected") } else { Log.d(TAG, "not connected") } } override fun onCancelled(error: DatabaseError) { Log.w(TAG, "Listener was cancelled") } }) // [END rtdb_listen_connected] } private fun disconnectionTimestamp() { // [START rtdb_on_disconnect_timestamp] val userLastOnlineRef = Firebase.database.getReference("users/joe/lastOnline") userLastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP) // [END rtdb_on_disconnect_timestamp] } private fun getServerTimeOffset() { // [START rtdb_server_time_offset] val offsetRef = Firebase.database.getReference(".info/serverTimeOffset") offsetRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val offset = snapshot.getValue(Double::class.java) ?: 0.0 val estimatedServerTimeMs = System.currentTimeMillis() + offset } override fun onCancelled(error: DatabaseError) { Log.w(TAG, "Listener was cancelled") } }) // [END rtdb_server_time_offset] } private fun fullConnectionExample() { // [START rtdb_full_connection_example] // Since I can connect from multiple devices, we store each connection instance separately // any time that connectionsRef's value is null (i.e. has no children) I am offline val database = Firebase.database val myConnectionsRef = database.getReference("users/joe/connections") // Stores the timestamp of my last disconnect (the last time I was seen online) val lastOnlineRef = database.getReference("/users/joe/lastOnline") val connectedRef = database.getReference(".info/connected") connectedRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val connected = snapshot.getValue<Boolean>() ?: false if (connected) { val con = myConnectionsRef.push() // When this device disconnects, remove it con.onDisconnect().removeValue() // When I disconnect, update the last time I was seen online lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP) // Add this device to my connections list // this value could contain info about the device or a timestamp too con.setValue(java.lang.Boolean.TRUE) } } override fun onCancelled(error: DatabaseError) { Log.w(TAG, "Listener was cancelled at .info/connected") } }) // [END rtdb_full_connection_example] } companion object { private val TAG = "OfflineActivity" } }
apache-2.0
73a2bb1c632217436e1f811b6d4892a6
38.759777
99
0.628636
4.980406
false
false
false
false
trife/Field-Book
app/src/main/java/com/fieldbook/tracker/utilities/GeodeticUtils.kt
1
13575
package com.fieldbook.tracker.utilities import android.location.Location import com.fieldbook.tracker.database.models.ObservationUnitModel import com.fieldbook.tracker.traits.GNSSTraitLayout import com.google.gson.Gson import java.io.FileWriter import java.io.IOException import java.lang.NumberFormatException import kotlin.math.* class GeodeticUtils { companion object { /** * GeoNav log is a user preference within Settings/Behavior/GeoNav * When enabled, a log file is created each time GeoNav begins. * The filename contains parameters for the GeoNav function: * "log_interval_address_theta_systemTime.csv" * Where interval is the update interval for the algorithm, 1, 5, or 10 * Address is the mac address of the external device (: replaced with _, also can be Internal_GPS) * Theta is the user preference angle threshold 22.5, 45, 67.5, or 90 * System time is the device's time in nano seconds. * * Whenever a line is added to the log file it is flushed to the file. * Newlines should be manually added using writeGeoNavLog(log, "\n") * * File headers are the following: * UTC, primary, secondary, start latitude, start longitude, end latitude, end longitude, * azimuth, teslas, bearing, distance, thetaCheck, closest * UTC: time given by the GPS, refers to the time the start location was received * primary/secondary: the primary/secondary ids of the current iteration * start: the lat/lng coordinates of the rover * end: the lat/lng coordinates of the target * azimuth: the direction the user is facing in degrees from 0-360 like a compass * teslas: the amount of noise calculated from the device's sensors * bearing: the angle between the start and end coordinates * distance: the distance between the start and end coordinates * thetaCheck: true if end lies within the theta threshold of the start's azimuth * closest: true if this is the closest point * e.g: In the below example 1,1 is the first closest, but is updated by 1,2 * therefore, 1,2 is the closest point. 1,5 is within the theta threshold, * but it is further away than 1,2. * 191438,1,1,...,true,true * 191438,1,2,...,true,true * 191438,1,5,...,true,false * * The file is populated by (1) device coordinate updates * and (2) for each iteration of the impact zone algorithm. * * (1) Device coordinate lines look like: * 191437.8,null,null,39.19216,-096.62184,null,null,null,null,null,null,null,null * ... where only the start coordinates and UTC are available * * (2) IZ lines look like: * 191438,1,1,39.19216,-96.62184,39.19222656,-96.62168695,326.4154145186235,56.7287763993025,null,15.124376606431571,false,false * note: the bearing can be null if the compass setting is disabled */ fun writeGeoNavLog(log: FileWriter?, line: String) { log?.let { geonav -> try { geonav.append(line) geonav.flush() } catch (io: IOException) { io.printStackTrace() } } } /** * Finds the closest location within a list of locations to the user. The location * must also be within the field of view of the user. Shown in the diagram below, * the user 'u' creates a cone (roughly) in front defined by their azimuth (from the compass). * The cone's angle from the user is defined in the preferences. * * * \ | * \ x | * \_______| * u * * @param start: the user's location * @param coordinates: the coordinate list to search from * @param theta: the field of view angle * @param isCompass: whether the compass setting is enabled and if theta threshold should be used in algorithm * @return a object representing the returned location and it's distance **/ fun impactZoneSearch(log: FileWriter?, start: Location, coordinates: Array<ObservationUnitModel>, azimuth: Double, theta: Double, teslas: Double, isCompass: Boolean = true): Pair<ObservationUnitModel?, Double> { //greedy algorithm to find closest point, first point is set to inf var closestDistance = Double.MAX_VALUE var closestPoint: ObservationUnitModel? = null coordinates.forEach { coordinate -> val location = parseGeoCoordinate(coordinate.geo_coordinates) if (location != null) { writeGeoNavLog(log, "${start.time},${coordinate.primary_id},${coordinate.secondary_id},${start.latitude},${start.longitude},${location.latitude},${location.longitude},$azimuth,$teslas") if (isCompass) { val bearing = checkThetaThreshold(start, location, azimuth, theta) val distance: Double = distanceHaversine(start, location) if (bearing.first) { if (closestDistance > distance) { writeGeoNavLog(log, ",${bearing.second},$distance,true,true") closestDistance = distance closestPoint = coordinate } else { writeGeoNavLog(log, ",${bearing.second},$distance,true,false") } } else { writeGeoNavLog(log, ",${bearing.second},$distance,false,false") } } else { val distance: Double = distanceHaversine(start, location) if (closestDistance > distance) { writeGeoNavLog(log, ",null,$distance,null,true") closestDistance = distance closestPoint = coordinate } else { writeGeoNavLog(log, ",null,$distance,null,false") } } //write newline to log file after each iteration writeGeoNavLog(log, "\n") } } return closestPoint to closestDistance } /** * Geocoordinates in FB can be stored as GeoJson or semi colon delimited strings. * This function parses the string and creates a Location object. * If the parsing fails then null is returned. */ fun parseGeoCoordinate(latLng: String?): Location? { val coords = (if (latLng == null || latLng.isBlank()) "" else latLng) val location = Location("search") //first try parsing as geojson, then try semi colon delimited var nonJson = false var failed = false try { val geoJson = Gson().fromJson(coords, GNSSTraitLayout.GeoJSON::class.java) location.latitude = geoJson.geometry.coordinates[0].toDouble() location.longitude = geoJson.geometry.coordinates[1].toDouble() } catch (e: Exception) { //could be a NPE, number format exception, index out of bounds or json syntax exception, failed = true nonJson = true } if (nonJson) { //check semi colon delimited values can be parsed to doubles val latLngTokens = coords.split(";") if (latLngTokens.size == 2) { try { location.latitude = latLngTokens[0].toDouble() location.longitude = latLngTokens[1].toDouble() failed = false } catch (e: NumberFormatException) { failed = true } } } return if (failed) null else location } /** * Checks whether an object lies within the user's field of view. * @param start: the user's location * @param end: the object's location * @param azimuth: defined by the compass, it's where the user is pointing * @param thetaThresh: a preference-defined double value that defines the field of view for the detection * @return a pair where first is if the bearing passes the threshold, second is the bearing */ private fun checkThetaThreshold(start: Location, end: Location, azimuth: Double, thetaThresh: Double): Pair<Boolean, Double> { //find the direction from user to target. val angle = angleFromCoordinate(start.latitude, start.longitude, end.latitude, end.longitude) //azimuth and angle are between 0-360 //if azimuth points towards end, then correctedAngle is close to 0 and should be between the theta thresh val correctedAngle = azimuth - angle //test if the direction found above is within a threshold from our user's azimuth return (correctedAngle in -thetaThresh..thetaThresh) to angle } /* uses the Haversine method to calculate distance between two GPS coordinates */ fun distanceHaversine(a: Location, b: Location): Double { val lata = a.latitude val lnga = a.longitude val latb = b.latitude val lngb = b.longitude val R = 6371.0 //radius of the Earth 6.371 million meters val latDst = Math.toRadians(latb - lata) val lngDst = Math.toRadians(lngb - lnga) val A = (sin(latDst / 2) * sin(latDst / 2) + (cos(Math.toRadians(lata)) * cos(Math.toRadians(latb)) * sin(lngDst / 2) * sin(lngDst / 2))) val c = 2 * atan2(sqrt(A), sqrt(1 - A)) //double height = el1 - el2; //dst = Math.pow(dst, 2); //return Math.sqrt(dst); return R * c * 1000.0 } fun geodesicDestination(start: Location, bearing: Double, distance: Double): Location { val latRads = Math.toRadians(start.latitude) val lngRads = Math.toRadians(start.longitude) //(Degrees * Math.PI) / 180.0; //final double bearing = azimuth;//location.getBearing(); //created weighted vector with bearing...? val R = 6371.0 //radius of the Earth val angDst = distance / R // d/R distance to point B over Earth's radius val lat2 = asin( sin(latRads) * cos(angDst) + cos(latRads) * sin(angDst) * cos(bearing) ) val lng2 = lngRads + atan2( sin(bearing) * sin(angDst) * cos(latRads), cos(angDst) - sin(latRads) * sin(lat2) ) val l = Location("end point") l.latitude = Math.toDegrees(lat2) l.longitude = Math.toDegrees(lng2) return l } //https://www.movable-type.co.uk/scripts/latlong.html private fun angleFromCoordinate( lat1: Double, long1: Double, lat2: Double, long2: Double ): Double { //get difference between longitudes val deltaLong = Math.toRadians(long2-long1) //convert latitudes to radians before trig functions val lat1Rads = Math.toRadians(lat1) val lat2Rads = Math.toRadians(lat2) //convert to x/y coordinates val y = sin(deltaLong)*cos(lat2Rads) val x = cos(lat1Rads)*sin(lat2Rads)-sin(lat1Rads)*cos(lat2Rads)*cos(deltaLong) //return degrees return (Math.toDegrees(atan2(y, x))+360) % 360 } /** * Truncates the coordinate string based on the fix value. * https://gis.stackexchange.com/questions/8650/measuring-accuracy-of-latitude-and-longitude * basically: normal gps ~4decimal places, differential 5, rtk 8 */ fun truncateFixQuality(x: String, fix: String): String = try { val tokens = x.split(".") val head = tokens[0] val tail = tokens[1] "$head." + when (fix) { "RTK", "manual input mode" -> if (tail.length > 8) tail.substring(0, 8) else tail "DGPS", "Float RTK" -> if (tail.length > 5) tail.substring(0, 5) else tail "internal" -> if (tail.length > 4) tail.substring(0, 4) else tail else -> if (tail.length > 3) tail.substring(0, 3) else tail } } catch (e: Exception) { e.printStackTrace() x } /** * Smooth two float arrays using a low pass filter. */ fun lowPassFilter(input: FloatArray, output: FloatArray?): FloatArray = output?.mapIndexed { index, fl -> fl + 0.5f * (input[index] - fl) }?.toFloatArray() ?: input } }
gpl-2.0
0282cb8be63e87d24f333b65b59277f3
39.768769
205
0.553959
4.660144
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/controls/UndoButtonFragment.kt
1
5569
package de.westnordost.streetcomplete.controls import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.fragment.app.Fragment import de.westnordost.osmfeatures.FeatureDictionary import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuest import de.westnordost.streetcomplete.data.quest.QuestController import de.westnordost.streetcomplete.data.quest.UndoableOsmQuestsCountListener import de.westnordost.streetcomplete.data.quest.UndoableOsmQuestsSource import de.westnordost.streetcomplete.data.upload.UploadProgressListener import de.westnordost.streetcomplete.data.upload.UploadProgressSource import de.westnordost.streetcomplete.ktx.popIn import de.westnordost.streetcomplete.ktx.popOut import de.westnordost.streetcomplete.quests.getHtmlQuestTitle import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import java.util.concurrent.FutureTask import javax.inject.Inject /** Fragment that shows (and hides) the undo button, based on whether there is anything to undo */ class UndoButtonFragment : Fragment(R.layout.fragment_undo_button), CoroutineScope by CoroutineScope(Dispatchers.Main) { @Inject internal lateinit var undoableOsmQuestsSource: UndoableOsmQuestsSource @Inject internal lateinit var uploadProgressSource: UploadProgressSource @Inject internal lateinit var questController: QuestController @Inject internal lateinit var featureDictionaryFutureTask: FutureTask<FeatureDictionary> private val undoButton get() = view as ImageButton /* undo button is not shown when there is nothing to undo */ private val undoableOsmQuestsCountListener = object : UndoableOsmQuestsCountListener { override fun onUndoableOsmQuestsCountIncreased() { launch(Dispatchers.Main) { if (!undoButton.isVisible && undoableOsmQuestsSource.count > 0) { undoButton.popIn() } } } override fun onUndoableOsmQuestsCountDecreased() { launch(Dispatchers.Main) { if (undoButton.isVisible && undoableOsmQuestsSource.count == 0) { undoButton.popOut().withEndAction { undoButton.visibility = View.INVISIBLE } } } } } /* Don't allow undoing while uploading. Should prevent race conditions. (Undoing quest while * also uploading it at the same time) */ private val uploadProgressListener = object : UploadProgressListener { override fun onStarted() { launch(Dispatchers.Main) { updateUndoButtonEnablement(false) }} override fun onFinished() { launch(Dispatchers.Main) { updateUndoButtonEnablement(true) }} } /* --------------------------------------- Lifecycle ---------------------------------------- */ init { Injector.applicationComponent.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) undoButton.setOnClickListener { undoButton.isEnabled = false val quest = undoableOsmQuestsSource.getLastUndoable() if (quest != null) confirmUndo(quest) } } override fun onStart() { super.onStart() updateUndoButtonVisibility() updateUndoButtonEnablement(true) undoableOsmQuestsSource.addListener(undoableOsmQuestsCountListener) uploadProgressSource.addUploadProgressListener(uploadProgressListener) } override fun onStop() { super.onStop() undoableOsmQuestsSource.removeListener(undoableOsmQuestsCountListener) uploadProgressSource.removeUploadProgressListener(uploadProgressListener) } override fun onDestroy() { super.onDestroy() coroutineContext.cancel() } /* ------------------------------------------------------------------------------------------ */ private fun confirmUndo(quest: OsmQuest) { val element = questController.getOsmElement(quest) ?: return val ctx = context ?: return val inner = LayoutInflater.from(ctx).inflate(R.layout.dialog_undo, null, false) val icon = inner.findViewById<ImageView>(R.id.icon) icon.setImageResource(quest.type.icon) val text = inner.findViewById<TextView>(R.id.text) text.text = resources.getHtmlQuestTitle(quest.type, element, featureDictionaryFutureTask) AlertDialog.Builder(ctx) .setTitle(R.string.undo_confirm_title) .setView(inner) .setPositiveButton(R.string.undo_confirm_positive) { _, _ -> questController.undo(quest) updateUndoButtonEnablement(true) } .setNegativeButton(R.string.undo_confirm_negative) { _, _ -> updateUndoButtonEnablement(true) } .setOnCancelListener { updateUndoButtonEnablement(true) } .show() } private fun updateUndoButtonVisibility() { view?.isGone = undoableOsmQuestsSource.count <= 0 } private fun updateUndoButtonEnablement(enable: Boolean) { undoButton.isEnabled = enable && !uploadProgressSource.isUploadInProgress } }
gpl-3.0
71a55c4131c6058d2baaabe39dde24f1
39.948529
107
0.701742
5.380676
false
false
false
false
Heiner1/AndroidAPS
database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsTemporaryTargetTransaction.kt
1
3392
package info.nightscout.androidaps.database.transactions import info.nightscout.androidaps.database.entities.TemporaryTarget import info.nightscout.androidaps.database.interfaces.end import kotlin.math.abs /** * Sync the TemporaryTarget from NS */ class SyncNsTemporaryTargetTransaction(private val temporaryTarget: TemporaryTarget) : Transaction<SyncNsTemporaryTargetTransaction.TransactionResult>() { override fun run(): TransactionResult { val result = TransactionResult() if (temporaryTarget.duration != 0L) { // not ending event val current: TemporaryTarget? = temporaryTarget.interfaceIDs.nightscoutId?.let { database.temporaryTargetDao.findByNSId(it) } if (current != null) { // nsId exists, allow only invalidation if (current.isValid && !temporaryTarget.isValid) { current.isValid = false database.temporaryTargetDao.updateExistingEntry(current) result.invalidated.add(current) } if (current.duration != temporaryTarget.duration) { current.duration = temporaryTarget.duration database.temporaryTargetDao.updateExistingEntry(current) result.updatedDuration.add(current) } return result } // not known nsId val running = database.temporaryTargetDao.getTemporaryTargetActiveAt(temporaryTarget.timestamp).blockingGet() if (running != null && abs(running.timestamp - temporaryTarget.timestamp) < 1000 && running.interfaceIDs.nightscoutId == null) { // allow missing milliseconds // the same record, update nsId only running.interfaceIDs.nightscoutId = temporaryTarget.interfaceIDs.nightscoutId database.temporaryTargetDao.updateExistingEntry(running) result.updatedNsId.add(running) } else if (running != null) { // another running record. end current and insert new running.end = temporaryTarget.timestamp database.temporaryTargetDao.updateExistingEntry(running) database.temporaryTargetDao.insertNewEntry(temporaryTarget) result.ended.add(running) result.inserted.add(temporaryTarget) } else { database.temporaryTargetDao.insertNewEntry(temporaryTarget) result.inserted.add(temporaryTarget) } return result } else { // ending event val running = database.temporaryTargetDao.getTemporaryTargetActiveAt(temporaryTarget.timestamp).blockingGet() if (running != null) { running.end = temporaryTarget.timestamp database.temporaryTargetDao.updateExistingEntry(running) result.ended.add(running) } } return result } class TransactionResult { val updatedNsId = mutableListOf<TemporaryTarget>() val updatedDuration = mutableListOf<TemporaryTarget>() val inserted = mutableListOf<TemporaryTarget>() val invalidated = mutableListOf<TemporaryTarget>() val ended = mutableListOf<TemporaryTarget>() } }
agpl-3.0
8d3d0be97393745c67c240a501163a70
42.5
170
0.629127
6.089767
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt
1
3926
package info.nightscout.androidaps.dialogs import android.os.Bundle import android.os.SystemClock import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.core.R import info.nightscout.androidaps.core.databinding.DialogBolusprogressBinding import info.nightscout.androidaps.events.EventNtpStatus import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject class NtpProgressDialog : DaggerDialogFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() private var state: String? = null private var percent = 0 private var _binding: DialogBolusprogressBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { isCancelable = false state = savedInstanceState?.getString("state", null) percent = savedInstanceState?.getInt("percent", 0) ?: 0 _binding = DialogBolusprogressBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val defaultMessage = rh.gs(R.string.timedetection) dialog?.setTitle(rh.gs(R.string.objectives)) binding.stop.setOnClickListener { dismiss() } binding.status.text = state ?: defaultMessage binding.progressbar.max = 100 binding.progressbar.progress = percent binding.stop.text = rh.gs(R.string.close) binding.title.text = rh.gs(R.string.please_wait) } override fun onResume() { super.onResume() aapsLogger.debug(LTag.UI, "onResume") if (percent == 100) { dismiss() return } else dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) disposable += rxBus .toObservable(EventNtpStatus::class.java) .observeOn(aapsSchedulers.main) .subscribe({ event: EventNtpStatus -> if (_binding != null) { aapsLogger.debug(LTag.UI, "Status: " + event.status + " Percent: " + event.percent) binding.status.text = event.status binding.progressbar.progress = event.percent if (event.percent == 100) { SystemClock.sleep(100) dismiss() } state = event.status percent = event.percent } }, fabricPrivacy::logException) } override fun onPause() { aapsLogger.debug(LTag.UI, "onPause") super.onPause() disposable.clear() } override fun onDestroyView() { super.onDestroyView() disposable.clear() _binding = null } override fun onSaveInstanceState(outState: Bundle) { outState.putString("state", state) outState.putInt("percent", percent) super.onSaveInstanceState(outState) } }
agpl-3.0
86572d44ddf9abc472b33cf94f08ff9b
35.361111
111
0.669638
4.957071
false
false
false
false
world-federation-of-advertisers/virtual-people-core-serving
src/test/kotlin/org/wfanet/virtualpeople/core/model/MultiplicityImplTest.kt
1
12163
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.virtualpeople.core.model import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.virtualpeople.common.labelerEvent import org.wfanet.virtualpeople.common.multiplicity private const val EVENT_COUNT = 10000 @RunWith(JUnit4::class) class MultiplicityImplTest { @Test fun `multiplicity ref not set should throw`() { val config = multiplicity { maxValue = 1.2 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set multiplicity_ref")) } @Test fun `invalid multiplicity field name should throw`() { val config = multiplicity { expectedMultiplicityField = "bad field name" maxValue = 1.2 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("The field name is invalid")) } @Test fun `invalid multiplicity field type should throw`() { val config = multiplicity { expectedMultiplicityField = "corrected_demo" maxValue = 1.2 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Unsupported field type")) } @Test fun `person index field not set should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 capAtMax = true randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set person_index_field")) } @Test fun `invalid person index field name should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 capAtMax = true personIndexField = "bad field name" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("The field name is invalid")) } @Test fun `invalid person index field type should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 capAtMax = true personIndexField = "expected_multiplicity" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Invalid type for person_index_field")) } @Test fun `max value not set should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set max_value")) } @Test fun `cap at max not set should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set cap_at_max")) } @Test fun `random seed not set should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 capAtMax = true personIndexField = "multiplicity_person_index" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set random_seed")) } @Test fun `explicit multiplicity and cap at max true`() { val config = multiplicity { expectedMultiplicity = 2.5 maxValue = 1.3 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) var personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(1, 2) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 1.3 * EVENT_COUNT = 13000 */ assertEquals(12947, personTotal) } @Test fun `explicit multiplicity and cap at max false`() { val config = multiplicity { expectedMultiplicity = 2.5 maxValue = 1.3 capAtMax = false personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("exceeds the specified max value")) } } @Test fun `explicit multiplicity is negative should throw`() { val config = multiplicity { expectedMultiplicity = -1.2 maxValue = 1.3 capAtMax = false personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("multiplicity must >= 0")) } } @Test fun `multiplicity field and cap at max true`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.3 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) /** multiplicity field is not set, throws error. */ (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("The multiplicity field is not set")) } /** multiplicity > max_value, cap at max_value. */ var personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = 2.0 } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(1, 2) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 1.3 * EVENT_COUNT = 13000 */ assertEquals(12947, personTotal) /** multiplicity < max_value */ personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = 1.2 } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(1, 2) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 1.2 * EVENT_COUNT = 12000 */ assertEquals(11949, personTotal) } @Test fun `multiplicity field and cap at max false`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.3 capAtMax = false personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) /** multiplicity field is not set, throws error. */ (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("The multiplicity field is not set")) } /** multiplicity > max_value, return error. */ (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = 2.0 } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("exceeds the specified max value")) } /** multiplicity < max_value */ var personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = 1.2 } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(1, 2) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 1.2 * EVENT_COUNT = 12000 */ assertEquals(11949, personTotal) } @Test fun `multiplicity field is negative should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.3 capAtMax = false personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) /** return error if multiplicity < 0. */ (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = -1.2 } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("multiplicity must >= 0")) } } @Test fun `multiplicity less than one`() { val config = multiplicity { expectedMultiplicity = 0.3 maxValue = 1.3 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) var personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(0, 1) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 0.3 * EVENT_COUNT = 3000 */ assertEquals(2947, personTotal) } }
apache-2.0
100db7af4dbc5994e0f42b2b968ab402
33.261972
99
0.682069
4.880819
false
true
false
false
exponentjs/exponent
android/expoview/src/main/java/host/exp/exponent/kernel/services/ErrorRecoveryManager.kt
2
2747
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.kernel.services import host.exp.exponent.di.NativeModuleDepsProvider import host.exp.exponent.kernel.ExperienceKey import host.exp.exponent.storage.ExponentSharedPreferences import org.json.JSONException import org.json.JSONObject import java.util.* import javax.inject.Inject private const val FIVE_MINUTES_MS = (5 * 60 * 1000).toLong() private const val AUTO_RELOAD_BUFFER_BASE_MS = (5 * 1000).toLong() class ErrorRecoveryManager(private val experienceKey: ExperienceKey?) { private var timeLastLoaded = 0L private var didError = false @Inject lateinit var exponentSharedPreferences: ExponentSharedPreferences fun markExperienceLoaded() { timeLastLoaded = System.currentTimeMillis() timeAnyExperienceLoaded = timeLastLoaded markErrored(false) } @JvmOverloads fun markErrored(didError: Boolean = true) { this.didError = didError if (experienceKey != null) { val metadata = exponentSharedPreferences.getExperienceMetadata(experienceKey) ?: JSONObject() try { metadata.put(ExponentSharedPreferences.EXPERIENCE_METADATA_LOADING_ERROR, didError) exponentSharedPreferences.updateExperienceMetadata(experienceKey, metadata) } catch (e: JSONException) { e.printStackTrace() } } } fun shouldReloadOnError(): Boolean { val diff = System.currentTimeMillis() - timeLastLoaded val reloadBuffer = reloadBuffer() return diff >= reloadBuffer } private fun reloadBuffer(): Long { var interval = Math.min( FIVE_MINUTES_MS, ( AUTO_RELOAD_BUFFER_BASE_MS * Math.pow( 1.5, reloadBufferDepth.toDouble() ) ).toLong() ) val timeSinceLastExperienceLoaded = System.currentTimeMillis() - timeAnyExperienceLoaded if (timeSinceLastExperienceLoaded > interval * 2) { reloadBufferDepth = 0 interval = AUTO_RELOAD_BUFFER_BASE_MS } return interval } companion object { private val experienceScopeKeyToManager: MutableMap<String, ErrorRecoveryManager> = HashMap() private var timeAnyExperienceLoaded: Long = 0 // This goes up when there are a bunch of errors in succession private var reloadBufferDepth: Long = 0 @JvmStatic fun getInstance(experienceKey: ExperienceKey): ErrorRecoveryManager { if (!experienceScopeKeyToManager.containsKey(experienceKey.scopeKey)) { experienceScopeKeyToManager[experienceKey.scopeKey] = ErrorRecoveryManager(experienceKey) } return experienceScopeKeyToManager[experienceKey.scopeKey]!! } } init { NativeModuleDepsProvider.instance.inject(ErrorRecoveryManager::class.java, this) } }
bsd-3-clause
5a31bb226bd30d406e1143d12f9605a3
31.702381
99
0.732071
4.879218
false
false
false
false
realm/realm-java
realm/realm-annotations-processor/src/main/java/io/realm/processor/Utils.kt
1
30143
/* * Copyright 2019 Realm 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. */ // Most of com.sun.tools.javac content has been marked internal with JDK 9 @file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE") package io.realm.processor import com.sun.tools.javac.code.Attribute import com.sun.tools.javac.code.Scope import com.sun.tools.javac.code.Symbol import com.sun.tools.javac.code.Type import com.sun.tools.javac.util.Pair import io.realm.annotations.RealmNamingPolicy import io.realm.processor.nameconverter.* import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.* import javax.lang.model.type.DeclaredType import javax.lang.model.type.ReferenceType import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.lang.model.util.Types import javax.tools.Diagnostic /** * Utility methods working with the Realm processor. */ object Utils { // API for retrieving symbols differs between JDK 8 and 9, so retrieve symbol information by // reflection private val classSymbolMembersMethod = Symbol.ClassSymbol::class.java.getMethod("members") private val scopeElementsMethod = try { // JDK 8 Scope::class.java.getMethod("getElements") } catch (e: NoSuchMethodException) { // JDK 9+ Scope::class.java.getMethod("getSymbols") } private lateinit var typeUtils: Types private lateinit var messager: Messager private lateinit var realmInteger: TypeMirror private lateinit var realmAny: TypeMirror private lateinit var realmList: DeclaredType private lateinit var realmResults: DeclaredType private lateinit var markerInterface: DeclaredType private lateinit var realmModel: TypeMirror private lateinit var realmDictionary: DeclaredType private lateinit var realmSet: DeclaredType fun initialize(env: ProcessingEnvironment) { val elementUtils = env.elementUtils typeUtils = env.typeUtils messager = env.messager realmInteger = elementUtils.getTypeElement("io.realm.MutableRealmInteger").asType() realmAny = elementUtils.getTypeElement("io.realm.RealmAny").asType() realmList = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmList"), typeUtils.getWildcardType(null, null)) realmResults = typeUtils.getDeclaredType(env.elementUtils.getTypeElement("io.realm.RealmResults"), typeUtils.getWildcardType(null, null)) realmModel = elementUtils.getTypeElement("io.realm.RealmModel").asType() markerInterface = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmModel")) realmDictionary = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmDictionary"), typeUtils.getWildcardType(null, null)) realmSet = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmSet"), typeUtils.getWildcardType(null, null)) } /** * @return true if the given element is the default public no arg constructor for a class. */ fun isDefaultConstructor(constructor: Element): Boolean { return if (constructor.modifiers.contains(Modifier.PUBLIC)) { (constructor as ExecutableElement).parameters.isEmpty() } else false } fun getProxyClassSimpleName(field: VariableElement): SimpleClassName { return if (typeUtils.isAssignable(field.asType(), realmList)) { getProxyClassName(getGenericTypeQualifiedName(field)!!) } else { getProxyClassName(getFieldTypeQualifiedName(field)) } } fun getDictionaryGenericProxyClassSimpleName(field: VariableElement): SimpleClassName { return if (typeUtils.isAssignable(field.asType(), realmDictionary)) { getProxyClassName(getGenericTypeQualifiedName(field)!!) } else { getProxyClassName(getFieldTypeQualifiedName(field)) } } fun getSetGenericProxyClassSimpleName(field: VariableElement): SimpleClassName { return if (typeUtils.isAssignable(field.asType(), realmSet)) { getProxyClassName(getGenericTypeQualifiedName(field)!!) } else { getProxyClassName(getFieldTypeQualifiedName(field)) } } fun getModelClassQualifiedName(field: VariableElement): QualifiedClassName { return if (typeUtils.isAssignable(field.asType(), realmList)) { getGenericTypeQualifiedName(field)!! } else { getFieldTypeQualifiedName(field) } } fun getDictionaryGenericModelClassQualifiedName(field: VariableElement): QualifiedClassName { return if (typeUtils.isAssignable(field.asType(), realmDictionary)) { getGenericTypeQualifiedName(field)!! } else { getFieldTypeQualifiedName(field) } } fun getSetGenericModelClassQualifiedName(field: VariableElement): QualifiedClassName { return if (typeUtils.isAssignable(field.asType(), realmSet)) { getGenericTypeQualifiedName(field)!! } else { getFieldTypeQualifiedName(field) } } /** * @return the proxy class name for a given clazz */ fun getProxyClassName(className: QualifiedClassName): SimpleClassName { return SimpleClassName(className.toString().replace(".", "_") + Constants.PROXY_SUFFIX) } /** * @return `true` if a field is of type "java.lang.String", `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isString(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return getFieldTypeQualifiedName(field).toString() == "java.lang.String" } /** * @return `true` if a field is of type "org.bson.types.ObjectId", `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isObjectId(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return getFieldTypeQualifiedName(field).toString() == "org.bson.types.ObjectId" } /** * @return `true` if a field is of type "java.util.UUID", `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isUUID(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return getFieldTypeQualifiedName(field).toString() == "java.util.UUID" } /** * @return `true` if a field is a primitive type, `false` otherwise. * @throws IllegalArgumentException if the typeString is `null`. */ fun isPrimitiveType(typeString: String): Boolean { return typeString == "byte" || typeString == "short" || typeString == "int" || typeString == "long" || typeString == "float" || typeString == "double" || typeString == "boolean" || typeString == "char" } fun isPrimitiveType(type: QualifiedClassName): Boolean { return isPrimitiveType(type.toString()) } /** * @return `true` if a field is a boxed type, `false` otherwise. * @throws IllegalArgumentException if the typeString is `null`. */ fun isBoxedType(typeString: String?): Boolean { if (typeString == null) { throw IllegalArgumentException("Argument 'typeString' cannot be null.") } return typeString == Byte::class.javaObjectType.name || typeString == Short::class.javaObjectType.name || typeString == Int::class.javaObjectType.name || typeString == Long::class.javaObjectType.name || typeString == Float::class.javaObjectType.name || typeString == Double::class.javaObjectType.name || typeString == Boolean::class.javaObjectType.name } /** * @return `true` if a field is a type of primitive types, `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isPrimitiveType(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return field.asType().kind.isPrimitive } /** * @return `true` if a field is of type "byte[]", `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isByteArray(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return getFieldTypeQualifiedName(field).toString() == "byte[]" } /** * @return `true` if a given field type string is "java.lang.String", `false` otherwise. * @throws IllegalArgumentException if the fieldType is `null`. */ fun isString(fieldType: String?): Boolean { if (fieldType == null) { throw IllegalArgumentException("Argument 'fieldType' cannot be null.") } return String::class.java.name == fieldType } /** * @return `true` if a given type implement `RealmModel`, `false` otherwise. */ fun isImplementingMarkerInterface(classElement: Element): Boolean { return typeUtils.isAssignable(classElement.asType(), markerInterface) } /** * @return `true` if a given field type is `MutableRealmInteger`, `false` otherwise. */ fun isMutableRealmInteger(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmInteger) } /** * @return `true` if a given field type is `RealmAny`, `false` otherwise. */ fun isRealmAny(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmAny) } /** * @return `true` if a given field type is `RealmList`, `false` otherwise. */ fun isRealmList(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmList) } /** * @return `true` if a given field type is `RealmDictionary`, `false` otherwise. */ fun isRealmDictionary(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmDictionary) } /** * @return `true` if a given field type is `RealmDictionary` and its element type is value type, * `false` otherwise. */ fun isRealmValueDictionary(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field) ?: return false return !isRealmModel(elementTypeMirror) && !isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmDictionary<RealmModel>`, `false` otherwise. */ fun isRealmModelDictionary(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field) ?: return false return isRealmModel(elementTypeMirror) } /** * @return `true` if a given field type is `RealmDictionary` and its element type is `RealmAny`, * `false` otherwise. */ fun isRealmAnyDictionary(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field) ?: return false return isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmSet`, `false` otherwise. */ fun isRealmSet(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmSet) } /** * @return `true` if a given field type is `RealmSet<RealmModel>`, `false` otherwise. */ fun isRealmModelSet(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmSetElementTypeMirror(field) ?: return false return isRealmModel(elementTypeMirror) } /** * @return `true` if a given field type is `RealmSet` and its element type is value type, * `false` otherwise. */ fun isRealmValueSet(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmSetElementTypeMirror(field) ?: return false return !isRealmModel(elementTypeMirror) && !isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmSet<RealmAny>`, `false` otherwise. */ fun isRealmAnySet(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmSetElementTypeMirror(field) ?: return false return isRealmAny(elementTypeMirror) } /** * @param field [VariableElement] of a value list field. * @return element type of the list field. */ fun getValueListFieldType(field: VariableElement): Constants.RealmFieldType { val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field) return Constants.LIST_ELEMENT_TYPE_TO_REALM_TYPES[elementTypeMirror!!.toString()] ?: throw IllegalArgumentException("Invalid type mirror '$elementTypeMirror' for field '$field'") } /** * @param field [VariableElement] of a value dictionary field. * @return element type of the dictionary field. */ fun getValueDictionaryFieldType(field: VariableElement): Constants.RealmFieldType { val elementTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field) return Constants.DICTIONARY_ELEMENT_TYPE_TO_REALM_TYPES[elementTypeMirror!!.toString()] ?: throw IllegalArgumentException("Invalid type mirror '$elementTypeMirror' for field '$field'") } /** * @param field [VariableElement] of a value set field. * @return element type of the set field. */ fun getValueSetFieldType(field: VariableElement): Constants.RealmFieldType { val elementTypeMirror = TypeMirrors.getRealmSetElementTypeMirror(field) return Constants.SET_ELEMENT_TYPE_TO_REALM_TYPES[elementTypeMirror!!.toString()] ?: throw IllegalArgumentException("Invalid type mirror '$elementTypeMirror' for field '$field'") } /** * @return `true` if a given field type is `RealmList` and its element type is `RealmObject`, * `false` otherwise. */ fun isRealmModelList(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field) ?: return false return isRealmModel(elementTypeMirror) } /** * @return `true` if a given field type is `RealmList` and its element type is `RealmAny`, * `false` otherwise. */ fun isRealmAnyList(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field) ?: return false return isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmList` and its element type is value type, * `false` otherwise. */ fun isRealmValueList(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field) ?: return false return !isRealmModel(elementTypeMirror) && !isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmModel`, `false` otherwise. */ fun isRealmModel(field: Element): Boolean { return isRealmModel(field.asType()) } /** * @return `true` if a given type is `RealmModel`, `false` otherwise. */ fun isRealmModel(type: TypeMirror?): Boolean { // This will return the wrong result if a model class doesn't exist at all, but // the compiler will catch that eventually. return typeUtils.isAssignable(type, realmModel) // // Not sure what is happening here, but typeUtils.isAssignable("Foo", realmModel) // // returns true even if Foo doesn't exist. No idea why this is happening. // // For now punt on the problem and check the direct supertype which should be either // // RealmObject or RealmModel. // // Original implementation: `` // // // // Theory: It looks like if `type` has the internal TypeTag.ERROR (internal API) it // // automatically translate to being assignable to everything. Possible some Java Specification // // rule taking effect. In our case, however we can do better since all Realm classes // // must be in the same compilation unit, so we should be able to look the type up. // for (TypeMirror typeMirror : typeUtils.directSupertypes(type)) { // String supertype = typeMirror.toString(); // if (supertype.equals("io.realm.RealmObject") || supertype.equals("io.realm.RealmModel")) { // return true; // } // } // return false; } /** * @return `true` if a given type is `RealmAny`, `false` otherwise. */ fun isRealmAny(type: TypeMirror?) = typeUtils.isAssignable(type, realmAny) fun isRealmResults(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmResults) } // get the fully-qualified type name for the generic type of a RealmResults fun getRealmResultsType(field: VariableElement): QualifiedClassName? { if (!isRealmResults(field)) { return null } val type = getGenericTypeForContainer(field) ?: return null return QualifiedClassName(type.toString()) } // get the fully-qualified type name for the generic type of a RealmList fun getRealmListType(field: VariableElement): QualifiedClassName? { if (!isRealmList(field)) { return null } val type = getGenericTypeForContainer(field) ?: return null return QualifiedClassName(type.toString()) } fun getDictionaryType(field: VariableElement): QualifiedClassName? { if (!isRealmDictionary(field)) { return null } val type = getGenericTypeForContainer(field) ?: return null return QualifiedClassName(type.toString()) } fun getSetType(field: VariableElement): QualifiedClassName? { if (!isRealmSet(field)) { return null } val type = getGenericTypeForContainer(field) ?: return null return QualifiedClassName(type.toString()) } // Note that, because subclassing subclasses of RealmObject is forbidden, // there is no need to deal with constructs like: <code>RealmResults&lt;? extends Foos&lt;</code>. fun getGenericTypeForContainer(field: VariableElement): ReferenceType? { var fieldType = field.asType() var kind = fieldType.kind if (kind != TypeKind.DECLARED) { return null } val args = (fieldType as DeclaredType).typeArguments if (args.size <= 0) { return null } fieldType = args[0] kind = fieldType.kind // We also support RealmList<byte[]> return if (kind != TypeKind.DECLARED && kind != TypeKind.ARRAY) { null } else fieldType as ReferenceType } /** * @return the qualified type name for a field. */ fun getFieldTypeQualifiedName(field: VariableElement): QualifiedClassName { return QualifiedClassName(field.asType().toString()) } /** * @return the generic type for Lists of the form `List<type>` */ fun getGenericTypeQualifiedName(field: VariableElement): QualifiedClassName? { val fieldType = field.asType() val typeArguments = (fieldType as DeclaredType).typeArguments return if (typeArguments.isEmpty()) null else QualifiedClassName(typeArguments[0].toString()) } /** * @return the generic type for Dictionaries of the form `RealmDictionary<type>` * Note: it applies to same types as RealmList. */ fun getDictionaryValueTypeQualifiedName(field: VariableElement): QualifiedClassName? { return getGenericTypeQualifiedName(field) } /** * @return the generic type for Sets of the form `RealmSet<type>` * Note: it applies to same types as RealmList. */ fun getSetValueTypeQualifiedName(field: VariableElement): QualifiedClassName? { return getGenericTypeQualifiedName(field) } /** * Return generic type mirror if any. */ fun getGenericType(field: VariableElement): TypeMirror? { val fieldType = field.asType() val typeArguments = (fieldType as DeclaredType).typeArguments return if (typeArguments.isEmpty()) null else typeArguments[0] } /** * Strips the package name from a fully qualified class name. */ fun stripPackage(fullyQualifiedClassName: String): String { val parts = fullyQualifiedClassName.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() return if (parts.isNotEmpty()) { parts[parts.size - 1] } else { fullyQualifiedClassName } } fun error(message: String?, element: Element) { var e = element if (element is RealmFieldElement) { // Element is being cast to Symbol internally which breaks any implementors of the // Element interface. This is a hack to work around that. Bad bad Oracle e = element.fieldReference } messager.printMessage(Diagnostic.Kind.ERROR, message, e) } fun error(message: String?) { messager.printMessage(Diagnostic.Kind.ERROR, message) } fun note(message: String?, element: Element) { var e = element if (element is RealmFieldElement) { // Element is being cast to Symbol internally which breaks any implementors of the // Element interface. This is a hack to work around that. Bad bad Oracle e = element.fieldReference } messager.printMessage(Diagnostic.Kind.NOTE, message, e) } fun note(message: String?) { messager.printMessage(Diagnostic.Kind.NOTE, message) } fun getSuperClass(classType: TypeElement): Element { return typeUtils.asElement(classType.superclass) } /** * Returns the interface name for proxy class interfaces */ fun getProxyInterfaceName(qualifiedClassName: QualifiedClassName): SimpleClassName { return SimpleClassName(qualifiedClassName.toString().replace(".", "_") + Constants.INTERFACE_SUFFIX) } fun getNameFormatter(policy: RealmNamingPolicy?): NameConverter { if (policy == null) { return IdentityConverter() } when (policy) { RealmNamingPolicy.NO_POLICY -> return IdentityConverter() RealmNamingPolicy.IDENTITY -> return IdentityConverter() RealmNamingPolicy.LOWER_CASE_WITH_UNDERSCORES -> return LowerCaseWithSeparatorConverter('_') RealmNamingPolicy.CAMEL_CASE -> return CamelCaseConverter() RealmNamingPolicy.PASCAL_CASE -> return PascalCaseConverter() else -> throw IllegalArgumentException("Unknown policy: $policy") } } /** * Tries to find the internal class name for a referenced type. In model classes this can * happen with either direct object references or using `RealmList` or `RealmResults`. * * * This name is required by schema builders that operate on internal names and not the public ones. * * * Finding the internal name is easy if the referenced type is included in the current round * of annotation processing. In that case the internal name was also calculated in the same round * * * If the referenced type was already compiled, e.g being included from library, then we need * to get the name from the proxy class. Fortunately ProGuard should not have obfuscated any * class files at this point, meaning we can look it up dynamically. * * * If a name is looked up using the class loader, it also means that developers need to * combine a library and app module of model classes at runtime in the RealmConfiguration, but * this should be a valid use case. * * @param className type to lookup the internal name for. * @param classCollection collection of classes found in the current round of annotation processing. * @throws IllegalArgumentException If the internal name could not be looked up * @return the statement that evalutes to the internal class name. This will either be a string * constant or a reference to a static field in another class. In both cases, the return result * should not be put in quotes. */ fun getReferencedTypeInternalClassNameStatement(className: QualifiedClassName?, classCollection: ClassCollection): String { // Attempt to lookup internal name in current round if (classCollection.containsQualifiedClass(className)) { val metadata = classCollection.getClassFromQualifiedName(className!!) return "\"" + metadata.internalClassName + "\"" } // If we cannot find the name in the current processor round, we have to defer resolving the // name to runtime. The reason being that the annotation processor can only access the // compile type class path using Elements and Types which do not allow us to read // field values. // // Doing it this way unfortunately means that if the class is not on the apps classpath // a rather obscure class-not-found exception will be thrown when starting the app, but since // this is probably a very niche use case that is acceptable for now. // // TODO: We could probably create an internal annotation like `@InternalName("__Permission")` // which should make it possible for the annotation processor to read the value from the // proxy class, even for files in other jar files. return "io.realm.${getProxyClassName(className!!)}.ClassNameHelper.INTERNAL_CLASS_NAME" } /** * Returns a simple reference to the ColumnInfo class inside this model class, i.e. the package * name is not prefixed. */ fun getSimpleColumnInfoClassName(className: QualifiedClassName): String { val simpleModelClassName = className.getSimpleName() return "${getProxyClassName(className)}.${simpleModelClassName}ColumnInfo" } // Returns whether a type of a Realm field is embedded or not. // For types which are part of this processing round we can look it up immediately from // the metadata in the `classCollection`. For types defined in other modules we will // have to use the slower approach of inspecting the `embedded` property of the // RealmClass annotation using the compiler tool api. fun isFieldTypeEmbedded(type: TypeMirror, classCollection: ClassCollection) : Boolean { val fieldType = QualifiedClassName(type) val fieldTypeMetaData: ClassMetaData? = classCollection.getClassFromQualifiedNameOrNull(fieldType) return fieldTypeMetaData?.embedded ?: type.isEmbedded() } private fun TypeMirror.isEmbedded() : Boolean { var isEmbedded = false if (this is Type.ClassType) { val declarationAttributes: com.sun.tools.javac.util.List<Attribute.Compound>? = tsym.metadata?.declarationAttributes if (declarationAttributes != null) { loop@for (attribute: Attribute.Compound in declarationAttributes) { if (attribute.type.tsym.qualifiedName.toString() == "io.realm.annotations.RealmClass") { for (pair: Pair<Symbol.MethodSymbol, Attribute> in attribute.values) { if (pair.fst.name.toString() == "embedded") { isEmbedded = pair.snd.value as Boolean break@loop } } } } } } return isEmbedded } // Returns whether a type has primary key field // For types which are part of this processing round we can look it up immediately from // the metadata in the `classCollection`. For types defined in other modules we will // have to use the slower approach of inspecting the variable member `embedded` property of the // RealmClass annotation using the compiler tool api. fun fieldTypeHasPrimaryKey(type: TypeMirror, classCollection: ClassCollection): Boolean { val fieldType = QualifiedClassName(type) val fieldTypeMetaData: ClassMetaData? = classCollection.getClassFromQualifiedNameOrNull(fieldType) return fieldTypeMetaData?.hasPrimaryKey() ?: type.hasPrimaryKey() } private fun TypeMirror.hasPrimaryKey(): Boolean { if (this is Type.ClassType) { val scope = classSymbolMembersMethod.invoke(tsym) val elements: Iterable<Symbol> = scopeElementsMethod.invoke(scope) as Iterable<Symbol> val symbols = elements.filter { it is Symbol.VarSymbol } return symbols.any { it.declarationAttributes.any { attribute -> attribute.type.tsym.qualifiedName.toString() == "io.realm.annotations.PrimaryKey" } } } return false } }
apache-2.0
49426753086851bf8c6689aeedb0c66f
41.45493
147
0.666755
5.088285
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/attention/attentionmechanism/AttentionMechanismLayerParameters.kt
1
1984
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.attention.attentionmechanism import com.kotlinnlp.simplednn.core.arrays.ParamsArray import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer import com.kotlinnlp.simplednn.core.layers.LayerParameters /** * The parameters of the layer of type AttentionLayer. * * @property inputSize the size of each element of the input sequence * @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot) * @param sparseInput whether the weights connected to the input are sparse or not */ class AttentionMechanismLayerParameters( inputSize: Int, weightsInitializer: Initializer? = GlorotInitializer(), private val sparseInput: Boolean = false ) : LayerParameters( inputSize = inputSize, outputSize = -1, // depends on the number of element in the input sequence weightsInitializer = weightsInitializer, biasesInitializer = null ) { companion object { /** * Private val used to serialize the class (needed by Serializable) */ @Suppress("unused") private const val serialVersionUID: Long = 1L } /** * The context vector trainable parameter. */ val contextVector = ParamsArray(inputSize) /** * The list of weights parameters. */ override val weightsList: List<ParamsArray> = listOf(this.contextVector) /** * The list of biases parameters. */ override val biasesList: List<ParamsArray> = listOf() /** * Initialize all parameters values. */ init { this.initialize() } }
mpl-2.0
43d13515be9f74706f224113f2aa30cb
30.492063
92
0.714214
4.624709
false
false
false
false
wordpress-mobile/WordPress-Android
libs/image-editor/src/main/kotlin/org/wordpress/android/imageeditor/crop/CropFragment.kt
1
6943
package org.wordpress.android.imageeditor.crop import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.yalantis.ucrop.UCropFragment import com.yalantis.ucrop.UCropFragment.UCropResult import com.yalantis.ucrop.UCropFragmentCallback import org.wordpress.android.imageeditor.EditImageViewModel import org.wordpress.android.imageeditor.ImageEditor import org.wordpress.android.imageeditor.R import org.wordpress.android.imageeditor.crop.CropViewModel.CropResult import org.wordpress.android.imageeditor.crop.CropViewModel.ImageCropAndSaveState.ImageCropAndSaveFailedState import org.wordpress.android.imageeditor.crop.CropViewModel.ImageCropAndSaveState.ImageCropAndSaveStartState import org.wordpress.android.imageeditor.crop.CropViewModel.ImageCropAndSaveState.ImageCropAndSaveSuccessState import org.wordpress.android.imageeditor.crop.CropViewModel.UiState.UiLoadedState import org.wordpress.android.imageeditor.crop.CropViewModel.UiState.UiStartLoadingWithBundleState import org.wordpress.android.imageeditor.preview.PreviewImageFragment.Companion.ARG_EDIT_IMAGE_DATA import org.wordpress.android.imageeditor.utils.ToastUtils import org.wordpress.android.imageeditor.utils.ToastUtils.Duration /** * Container fragment for displaying third party crop fragment and done menu item. */ class CropFragment : Fragment(), UCropFragmentCallback { private lateinit var viewModel: CropViewModel private var doneMenu: MenuItem? = null private val navArgs: CropFragmentArgs by navArgs() companion object { private val TAG = CropFragment::class.java.simpleName const val CROP_RESULT = "crop_result" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.crop_image_fragment, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initializeViewModels() } private fun initializeViewModels() { viewModel = ViewModelProvider(this).get(CropViewModel::class.java) setupObservers() viewModel.start( navArgs.inputFilePath, navArgs.outputFileExtension, navArgs.shouldReturnToPreviewScreen, requireContext().cacheDir, ImageEditor.instance ) } private fun setupObservers() { viewModel.uiState.observe(viewLifecycleOwner, Observer { uiState -> when (uiState) { is UiStartLoadingWithBundleState -> { showThirdPartyCropFragmentWithBundle(uiState.bundle) } is UiLoadedState -> { // Do nothing } } doneMenu?.isVisible = uiState.doneMenuVisible }) viewModel.cropAndSaveImageStateEvent.observe(viewLifecycleOwner, Observer { stateEvent -> stateEvent?.getContentIfNotHandled()?.let { state -> when (state) { is ImageCropAndSaveStartState -> { val thirdPartyCropFragment = childFragmentManager .findFragmentByTag(UCropFragment.TAG) as? UCropFragment if (thirdPartyCropFragment != null && thirdPartyCropFragment.isAdded) { thirdPartyCropFragment.cropAndSaveImage() } else { Log.e(TAG, "Cannot crop and save image as thirdPartyCropFragment is null or not added!") } } is ImageCropAndSaveFailedState -> { showCropError(state.errorResId) } is ImageCropAndSaveSuccessState -> { // Do nothing } } } }) viewModel.navigateBackWithCropResult.observe(viewLifecycleOwner, Observer { cropResult -> navigateBackWithCropResult(cropResult) }) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.menu_crop_fragment, menu) doneMenu = menu.findItem(R.id.menu_done) } override fun onOptionsItemSelected(item: MenuItem): Boolean = if (item.itemId == R.id.menu_done) { viewModel.onDoneMenuClicked() true } else if (item.itemId == android.R.id.home) { if (navArgs.shouldReturnToPreviewScreen) { findNavController().popBackStack() true } else { super.onOptionsItemSelected(item) } } else { super.onOptionsItemSelected(item) } private fun showThirdPartyCropFragmentWithBundle(bundle: Bundle) { var thirdPartyCropFragment = childFragmentManager .findFragmentByTag(UCropFragment.TAG) as? UCropFragment if (thirdPartyCropFragment == null || !thirdPartyCropFragment.isAdded) { thirdPartyCropFragment = UCropFragment.newInstance(bundle) childFragmentManager.beginTransaction() .replace(R.id.fragment_container, thirdPartyCropFragment, UCropFragment.TAG) .disallowAddToBackStack() .commit() } } override fun loadingProgress(loading: Boolean) { viewModel.onLoadingProgress(loading) } override fun onCropFinish(result: UCropResult?) { result?.let { viewModel.onCropFinish(it.mResultCode, it.mResultData) } } private fun showCropError(errorResId: Int) { ToastUtils.showToast(context, getString(errorResId), Duration.LONG) } private fun navigateBackWithCropResult(cropResult: CropResult) { if (navArgs.shouldReturnToPreviewScreen) { val navController = findNavController() ViewModelProvider(requireActivity()).get(EditImageViewModel::class.java).setCropResult(cropResult) navController.popBackStack() } else { val resultData = viewModel.getOutputData(cropResult) activity?.let { it.setResult( cropResult.resultCode, Intent().apply { putParcelableArrayListExtra(ARG_EDIT_IMAGE_DATA, resultData) }) it.finish() } } } }
gpl-2.0
ae299127adc244baa45183282233cfb4
38.674286
116
0.675068
5.545527
false
false
false
false