repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/query/WebSymbolsQueryExecutor.kt
1
2716
// 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.webSymbols.query import com.intellij.model.Pointer import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.util.text.StringUtil import com.intellij.webSymbols.* import com.intellij.webSymbols.completion.WebSymbolCodeCompletionItem import com.intellij.webSymbols.context.WebSymbolsContext import com.intellij.webSymbols.context.WebSymbolsContext.Companion.KIND_FRAMEWORK /* * INAPPLICABLE_JVM_NAME -> https://youtrack.jetbrains.com/issue/KT-31420 * DEPRECATION -> @JvmDefault **/ @Suppress("INAPPLICABLE_JVM_NAME", "DEPRECATION") interface WebSymbolsQueryExecutor : ModificationTracker { val context: WebSymbolsContext val framework: FrameworkId? get() = context[KIND_FRAMEWORK] @get:JvmName("allowResolve") val allowResolve: Boolean val namesProvider: WebSymbolNamesProvider val resultsCustomizer: WebSymbolsQueryResultsCustomizer fun createPointer(): Pointer<WebSymbolsQueryExecutor> fun runNameMatchQuery(path: String, virtualSymbols: Boolean = true, abstractSymbols: Boolean = false, strictScope: Boolean = false, scope: List<WebSymbolsScope> = emptyList()): List<WebSymbol> = runNameMatchQuery(StringUtil.split(path, "/", true, true), virtualSymbols, abstractSymbols, strictScope, scope) fun runNameMatchQuery(path: List<String>, virtualSymbols: Boolean = true, abstractSymbols: Boolean = false, strictScope: Boolean = false, scope: List<WebSymbolsScope> = emptyList()): List<WebSymbol> fun runCodeCompletionQuery(path: String, /** Position to complete at in the last segment of the path **/ position: Int, virtualSymbols: Boolean = true, scope: List<WebSymbolsScope> = emptyList()): List<WebSymbolCodeCompletionItem> = runCodeCompletionQuery(StringUtil.split(path, "/", true, true), position, virtualSymbols, scope) fun runCodeCompletionQuery(path: List<String>, /** Position to complete at in the last segment of the path **/ position: Int, virtualSymbols: Boolean = true, scope: List<WebSymbolsScope> = emptyList()): List<WebSymbolCodeCompletionItem> fun withNameConversionRules(rules: List<WebSymbolNameConversionRules>): WebSymbolsQueryExecutor }
apache-2.0
0731b5da8de0b243ecb38cc42aabca48
44.283333
120
0.662371
5.32549
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/text/TextColorStyleButton.kt
2
1156
package org.thoughtcrime.securesms.mediasend.v2.text import android.content.Context import android.util.AttributeSet import androidx.appcompat.widget.AppCompatImageView import org.thoughtcrime.securesms.util.next typealias OnTextColorStyleChanged = (TextColorStyle) -> Unit /** * Allows the user to cycle between text and background styling for a text post */ class TextColorStyleButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : AppCompatImageView(context, attrs) { private var textColorStyle: TextColorStyle = TextColorStyle.NO_BACKGROUND var onTextColorStyleChanged: OnTextColorStyleChanged? = null init { setImageResource(textColorStyle.icon) super.setOnClickListener { setTextColorStyle(textColorStyle.next()) } } override fun setOnClickListener(l: OnClickListener?) { throw UnsupportedOperationException() } fun setTextColorStyle(textColorStyle: TextColorStyle) { if (textColorStyle != this.textColorStyle) { this.textColorStyle = textColorStyle setImageResource(textColorStyle.icon) onTextColorStyleChanged?.invoke(textColorStyle) } } }
gpl-3.0
1b4c99269fd40852fe7a57d9f760a821
27.9
79
0.775087
4.699187
false
false
false
false
Qase/KotlinLogger
kotlinlog/src/main/kotlin/quanti/com/kotlinlog/file/SendLogDialogFragment.kt
1
6369
package quanti.com.kotlinlog.file import android.app.AlertDialog import android.app.Dialog import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.fragment.app.DialogFragment import java.io.File import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking import quanti.com.kotlinlog.R import quanti.com.kotlinlog.utils.copyLogsTOSDCard import quanti.com.kotlinlog.utils.getFormattedFileNameDayNow import quanti.com.kotlinlog.utils.getUriForFile import quanti.com.kotlinlog.utils.getZipOfLogs import quanti.com.kotlinlog.utils.hasFileWritePermission /** * Created by Trnka Vladislav on 20.06.2017. * * Dialog that shows user options to save or send logs */ class SendLogDialogFragment : DialogFragment() { companion object { const val MESSAGE = "send_message" const val TITLE = "send_title" const val EMAIL_BUTTON_TEXT = "email_button" const val FILE_BUTTON_TEXT = "file_button" const val SEND_EMAIL_ADDRESSES = "send_address" const val EXTRA_FILES = "extra_files" const val DIALOG_THEME = "dialog_theme" @JvmOverloads @JvmStatic fun newInstance( sendEmailAddress: String, message: String = "Would you like to send logs by email or save them to SD card?", title: String = "Send logs", emailButtonText: String = "Email", fileButtonText: String = "Save", extraFiles: List<File> = arrayListOf(), dialogTheme: Int? = null ) = newInstance( arrayOf(sendEmailAddress), message, title, emailButtonText, fileButtonText, extraFiles, dialogTheme ) @JvmOverloads @JvmStatic fun newInstance( sendEmailAddress: Array<String>, message: String = "Would you like to send logs by email or save them to SD card?", title: String = "Send logs", emailButtonText: String = "Email", fileButtonText: String = "Save", extraFiles: List<File> = arrayListOf(), dialogTheme: Int? = null ): SendLogDialogFragment { val myFragment = SendLogDialogFragment() val args = Bundle() args.putString(MESSAGE, message) args.putString(TITLE, title) args.putString(EMAIL_BUTTON_TEXT, emailButtonText) args.putString(FILE_BUTTON_TEXT, fileButtonText) args.putStringArray(SEND_EMAIL_ADDRESSES, sendEmailAddress) args.putSerializable(EXTRA_FILES, ArrayList(extraFiles)) if (dialogTheme != null) { args.putInt(DIALOG_THEME, dialogTheme) } myFragment.arguments = args return myFragment } } private var zipFile: Deferred<File>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) zipFile = CoroutineScope(Dispatchers.IO).async { val extraFiles = requireArguments().getSerializable(EXTRA_FILES) as ArrayList<File> getZipOfLogs(requireActivity().applicationContext, 4, extraFiles) } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val hasFilePermission = requireActivity().applicationContext.hasFileWritePermission() return AlertDialog .Builder(requireContext(), requireArguments().getInt(DIALOG_THEME)) .apply { setMessage(requireArguments().getString(MESSAGE)) setTitle(requireArguments().getString(TITLE)) setPositiveButton( requireArguments().getString(EMAIL_BUTTON_TEXT), this@SendLogDialogFragment::positiveButtonClick ) if (hasFilePermission) { setNeutralButton( requireArguments().getString(FILE_BUTTON_TEXT), this@SendLogDialogFragment::neutralButtonClick ) } }.create() } /** * On positive button click * Create zip of all logs and open email client to send */ @Suppress("UNUSED_PARAMETER") private fun positiveButtonClick(dialog: DialogInterface, which: Int) = runBlocking { val appContext = [email protected]().applicationContext val addresses = requireArguments().getStringArray(SEND_EMAIL_ADDRESSES) val subject = getString(R.string.logs_email_subject) + " " + getFormattedFileNameDayNow() val bodyText = getString(R.string.logs_email_text) val zipFileUri = zipFile?.await()?.getUriForFile(appContext) val intent = Intent(Intent.ACTION_SEND).apply { type = "message/rfc822" // email flags = Intent.FLAG_GRANT_READ_URI_PERMISSION putExtra(Intent.EXTRA_EMAIL, addresses) putExtra(Intent.EXTRA_SUBJECT, subject) putExtra(Intent.EXTRA_TEXT, bodyText) putExtra(Intent.EXTRA_STREAM, zipFileUri) } try { startActivity(Intent.createChooser(intent, "Send mail...")) } catch (ex: android.content.ActivityNotFoundException) { Toast.makeText( appContext, getString(R.string.logs_email_no_client_installed), Toast.LENGTH_LONG ).show() } } /** * On neutral button click * Copy ZIP of all logs to sd card */ @Suppress("UNUSED_PARAMETER") private fun neutralButtonClick(dialog: DialogInterface, which: Int) = runBlocking { val appContext = [email protected]().applicationContext val file = zipFile?.await()?.copyLogsTOSDCard(requireContext()) Toast.makeText( appContext, "File successfully copied" + "\n" + file?.absolutePath, Toast.LENGTH_LONG ).show() } }
mit
d980423c927f3558833da8876f8b0e6b
35.603448
95
0.615638
5.083001
false
false
false
false
google/android-fhir
datacapture/src/test/java/com/google/android/fhir/datacapture/views/QuestionnaireItemDateTimePickerViewHolderFactoryTest.kt
1
11745
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture.views import android.widget.FrameLayout import android.widget.TextView import com.google.android.fhir.datacapture.R import com.google.android.fhir.datacapture.validation.Invalid import com.google.android.fhir.datacapture.validation.NotValidated import com.google.android.material.textfield.TextInputLayout import com.google.common.truth.Truth.assertThat import java.util.Date import java.util.Locale import org.hl7.fhir.r4.model.DateTimeType import org.hl7.fhir.r4.model.Questionnaire import org.hl7.fhir.r4.model.QuestionnaireResponse import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment @RunWith(RobolectricTestRunner::class) class QuestionnaireItemDateTimePickerViewHolderFactoryTest { private val parent = FrameLayout( RuntimeEnvironment.getApplication().apply { setTheme(R.style.Theme_Material3_DayNight) } ) private val viewHolder = QuestionnaireItemDateTimePickerViewHolderFactory.create(parent) @Before fun setUp() { Locale.setDefault(Locale.US) org.robolectric.shadows.ShadowSettings.set24HourTimeFormat(false) } @Test fun shouldSetQuestionHeader() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.itemView.findViewById<TextView>(R.id.question).text.toString()) .isEqualTo("Question?") } @Test fun shouldSetEmptyDateTimeInput() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.dateInputView.text.toString()).isEqualTo("") assertThat(viewHolder.timeInputView.text.toString()).isEqualTo("") } @Test fun shouldSetDateTimeInput() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent() .addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent() .setValue(DateTimeType(Date(2020 - 1900, 1, 5, 1, 30, 0))) ), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.dateInputView.text.toString()).isEqualTo("2/5/20") assertThat(viewHolder.timeInputView.text.toString()).isEqualTo("1:30 AM") } @Test fun `parse date text input in US locale`() { var answers: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null val itemViewItem = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent() .addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent() .setValue(DateTimeType(Date(2020 - 1900, 1, 5, 1, 30, 0))) ), validationResult = NotValidated, answersChangedCallback = { _, _, result -> answers = result }, ) viewHolder.bind(itemViewItem) viewHolder.dateInputView.text = "11/19/2020" val answer = answers!!.single().value as DateTimeType assertThat(answer.day).isEqualTo(19) assertThat(answer.month).isEqualTo(10) assertThat(answer.year).isEqualTo(2020) } @Test fun `parse date text input in Japan locale`() { Locale.setDefault(Locale.JAPAN) var answers: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null val itemViewItem = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent() .addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent() .setValue(DateTimeType(Date(2020 - 1900, 1, 5, 1, 30, 0))) ), validationResult = NotValidated, answersChangedCallback = { _, _, result -> answers = result }, ) viewHolder.bind(itemViewItem) viewHolder.dateInputView.text = "2020/11/19" val answer = answers!!.single().value as DateTimeType assertThat(answer.day).isEqualTo(19) assertThat(answer.month).isEqualTo(10) assertThat(answer.year).isEqualTo(2020) } @Test fun `if date input is invalid then clear the answer`() { var answers: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null val itemViewItem = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent() .addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent() .setValue(DateTimeType(Date(2020 - 1900, 1, 5, 1, 30, 0))) ), validationResult = NotValidated, answersChangedCallback = { _, _, result -> answers = result }, ) viewHolder.bind(itemViewItem) viewHolder.dateInputView.text = "2020/11/" assertThat(answers!!).isEmpty() } @Test fun `if date input is invalid then do not enable time text input layout`() { val itemViewItem = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) viewHolder.bind(itemViewItem) viewHolder.dateInputView.text = "11/19/" assertThat(viewHolder.itemView.findViewById<TextInputLayout>(R.id.time_input_layout).isEnabled) .isFalse() } @Test fun `if date input is valid then enable time text input layout`() { val itemViewItem = QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) viewHolder.bind(itemViewItem) viewHolder.dateInputView.text = "11/19/2020" assertThat(viewHolder.itemView.findViewById<TextInputLayout>(R.id.time_input_layout).isEnabled) .isTrue() } @Test fun displayValidationResult_error_shouldShowErrorMessage() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { required = true }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = Invalid(listOf("Missing answer for required field.")), answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.itemView.findViewById<TextInputLayout>(R.id.date_input_layout).error) .isEqualTo("Missing answer for required field.") } @Test fun displayValidationResult_noError_shouldShowNoErrorMessage() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { addExtension().apply { url = "http://hl7.org/fhir/StructureDefinition/minValue" setValue((DateTimeType(Date(2020 - 1900, 1, 5, 1, 30, 0)))) } addExtension().apply { url = "http://hl7.org/fhir/StructureDefinition/maxValue" setValue((DateTimeType(Date(2025 - 1900, 1, 5, 1, 30, 0)))) } }, QuestionnaireResponse.QuestionnaireResponseItemComponent() .addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply { value = (DateTimeType(Date(2023 - 1900, 1, 5, 1, 30, 0))) } ), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.itemView.findViewById<TextInputLayout>(R.id.date_input_layout).error) .isNull() assertThat(viewHolder.itemView.findViewById<TextInputLayout>(R.id.time_input_layout).error) .isNull() } @Test fun bind_readOnly_shouldDisableView() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { readOnly = true }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.dateInputView.isEnabled).isFalse() assertThat(viewHolder.timeInputView.isEnabled).isFalse() } @Test fun `bind multiple times with separate QuestionnaireItemViewItem should show proper date and time`() { viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent() .addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent() .setValue(DateTimeType(Date(2020 - 1900, 1, 5, 1, 30, 0))) ), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.dateInputView.text.toString()).isEqualTo("2/5/20") assertThat(viewHolder.timeInputView.text.toString()).isEqualTo("1:30 AM") viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent() .addAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent() .setValue(DateTimeType(Date(2021 - 1900, 1, 5, 2, 30, 0))) ), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.dateInputView.text.toString()).isEqualTo("2/5/21") assertThat(viewHolder.timeInputView.text.toString()).isEqualTo("2:30 AM") viewHolder.bind( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent().apply { text = "Question?" }, QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = NotValidated, answersChangedCallback = { _, _, _ -> }, ) ) assertThat(viewHolder.dateInputView.text.toString()).isEmpty() assertThat(viewHolder.timeInputView.text.toString()).isEmpty() } private val QuestionnaireItemViewHolder.dateInputView: TextView get() { return itemView.findViewById(R.id.date_input_edit_text) } private val QuestionnaireItemViewHolder.timeInputView: TextView get() { return itemView.findViewById(R.id.time_input_edit_text) } }
apache-2.0
59a2d37584886ed477b96d64c2395115
35.588785
104
0.692635
5.131062
false
false
false
false
iSoron/uhabits
uhabits-core/src/jvmTest/java/org/isoron/uhabits/core/ui/screens/habits/show/ShowHabitMenuPresenterTest.kt
1
2335
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.core.ui.screens.habits.show import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import org.apache.commons.io.FileUtils import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.isoron.uhabits.core.BaseUnitTest import org.isoron.uhabits.core.models.Habit import org.junit.Test import java.nio.file.Files class ShowHabitMenuPresenterTest : BaseUnitTest() { private lateinit var system: ShowHabitMenuPresenter.System private lateinit var screen: ShowHabitMenuPresenter.Screen private lateinit var habit: Habit private lateinit var menu: ShowHabitMenuPresenter @Throws(Exception::class) override fun setUp() { super.setUp() system = mock() screen = mock() habit = fixtures.createShortHabit() menu = ShowHabitMenuPresenter( commandRunner, habit, habitList, screen, system, taskRunner ) } @Test fun testOnEditHabit() { menu.onEditHabit() verify(screen).showEditHabitScreen(habit) } @Test @Throws(Exception::class) fun testOnExport() { val outputDir = Files.createTempDirectory("CSV").toFile() whenever(system.getCSVOutputDir()).thenReturn(outputDir) menu.onExportCSV() assertThat(FileUtils.listFiles(outputDir, null, false).size, equalTo(1)) FileUtils.deleteDirectory(outputDir) } }
gpl-3.0
c1260ddb212801624cc60249eb473f58
32.826087
80
0.710797
4.428843
false
true
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/enrollment/internal/EnrollmentImportHandlerShould.kt
1
7056
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.enrollment.internal import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.* import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction import org.hisp.dhis.android.core.common.State import org.hisp.dhis.android.core.common.internal.DataStatePropagator import org.hisp.dhis.android.core.enrollment.Enrollment import org.hisp.dhis.android.core.event.internal.EventImportHandler import org.hisp.dhis.android.core.imports.ImportStatus import org.hisp.dhis.android.core.imports.internal.* import org.hisp.dhis.android.core.tracker.importer.internal.JobReportEnrollmentHandler import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.ArgumentMatchers.anyList @RunWith(JUnit4::class) class EnrollmentImportHandlerShould { private val enrollmentStore: EnrollmentStore = mock() private val eventImportHandler: EventImportHandler = mock() private val importEvent: EventImportSummaries = mock() private val eventSummary: EventImportSummary = mock() private val importSummary: EnrollmentImportSummary = mock() private val trackerImportConflictStore: TrackerImportConflictStore = mock() private val trackerImportConflictParser: TrackerImportConflictParser = mock() private val jobReportEnrollmentHandler: JobReportEnrollmentHandler = mock() private val dataStatePropagator: DataStatePropagator = mock() private val enrollment: Enrollment = mock() private val missingEnrollment: Enrollment = mock() private val enrollmentUid = "enrollment_uid" private val teiState = State.SYNCED private lateinit var enrollments: List<Enrollment> // object to test private lateinit var enrollmentImportHandler: EnrollmentImportHandler @Before @Throws(Exception::class) fun setUp() { enrollmentImportHandler = EnrollmentImportHandler( enrollmentStore, eventImportHandler, trackerImportConflictStore, trackerImportConflictParser, jobReportEnrollmentHandler, dataStatePropagator ) whenever(enrollment.trackedEntityInstance()).thenReturn("tei_uid") whenever(enrollment.uid()).thenReturn(enrollmentUid) whenever(enrollmentStore.setSyncStateOrDelete(enrollmentUid, State.SYNCED)).thenReturn(HandleAction.Update) enrollments = listOf(enrollment) } @Test fun invoke_set_state_when_enrollment_import_summary_is_success_with_reference() { whenever(importSummary.status()).thenReturn(ImportStatus.SUCCESS) whenever(importSummary.reference()).thenReturn(enrollmentUid) enrollmentImportHandler.handleEnrollmentImportSummary(listOf(importSummary), enrollments, teiState) verify(enrollmentStore, times(1)).setSyncStateOrDelete(enrollmentUid, State.SYNCED) } @Test fun invoke_set_state_when_enrollment_import_summary_is_error_with_reference() { whenever(importSummary.status()).thenReturn(ImportStatus.ERROR) whenever(importSummary.reference()).thenReturn(enrollmentUid) enrollmentImportHandler.handleEnrollmentImportSummary(listOf(importSummary), enrollments, teiState) verify(enrollmentStore, times(1)).setSyncStateOrDelete(enrollmentUid, State.ERROR) } @Test fun invoke_set_state_and_handle_event_import_summaries_when_enrollment_is_success_and_event_is_imported() { whenever(importSummary.status()).thenReturn(ImportStatus.SUCCESS) whenever(importSummary.reference()).thenReturn(enrollmentUid) whenever(importSummary.events()).thenReturn(importEvent) val eventSummaries: List<EventImportSummary> = listOf(eventSummary) whenever(importEvent.importSummaries()).thenReturn(eventSummaries) enrollmentImportHandler.handleEnrollmentImportSummary(listOf(importSummary), enrollments, teiState) verify(enrollmentStore, times(1)).setSyncStateOrDelete(enrollmentUid, State.SYNCED) verify(eventImportHandler, times(1)).handleEventImportSummaries(eq(eventSummaries), anyList()) } @Test fun mark_as_to_update_enrollments_not_present_in_the_response() { whenever(importSummary.status()).thenReturn(ImportStatus.SUCCESS) whenever(importSummary.reference()).thenReturn(enrollmentUid) val enrollments = listOf(enrollment, missingEnrollment) whenever(missingEnrollment.uid()).thenReturn("missing_enrollment_uid") enrollmentImportHandler.handleEnrollmentImportSummary(listOf(importSummary), enrollments, teiState) verify(enrollmentStore, times(1)).setSyncStateOrDelete(enrollmentUid, State.SYNCED) verify(enrollmentStore, times(1)).setSyncStateOrDelete("missing_enrollment_uid", State.TO_UPDATE) } @Test fun return_enrollments_not_present_in_the_response() { whenever(importSummary.status()).thenReturn(ImportStatus.SUCCESS) whenever(importSummary.reference()).thenReturn(enrollmentUid) val enrollments = listOf(enrollment, missingEnrollment) whenever(missingEnrollment.uid()).thenReturn("missing_enrollment_uid") val response = enrollmentImportHandler.handleEnrollmentImportSummary( listOf(importSummary), enrollments, teiState ) assertThat(response.enrollments.ignored.size).isEqualTo(1) assertThat(response.enrollments.ignored.first().uid()).isEqualTo("missing_enrollment_uid") } }
bsd-3-clause
ee32ea283749ebb348a8c2f4e65a64c5
44.230769
115
0.765023
4.639053
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/analytics/aggregated/internal/AnalyticsOrganisationUnitHelperShould.kt
1
3729
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.analytics.aggregated.internal import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore import org.hisp.dhis.android.core.arch.db.stores.internal.LinkStore import org.hisp.dhis.android.core.common.RelativeOrganisationUnit import org.hisp.dhis.android.core.organisationunit.OrganisationUnit import org.hisp.dhis.android.core.organisationunit.OrganisationUnitLevel import org.hisp.dhis.android.core.organisationunit.OrganisationUnitOrganisationUnitGroupLink import org.hisp.dhis.android.core.user.internal.UserOrganisationUnitLinkStore import org.junit.Test class AnalyticsOrganisationUnitHelperShould { private val userOrganisationUnitStore: UserOrganisationUnitLinkStore = mock() private val organisationUnitStore: IdentifiableObjectStore<OrganisationUnit> = mock() private val organisationUnitLevelStore: IdentifiableObjectStore<OrganisationUnitLevel> = mock() private val organisationUnitOrganisationUnitGroupLinkStore: LinkStore<OrganisationUnitOrganisationUnitGroupLink> = mock() private val helper = AnalyticsOrganisationUnitHelper( userOrganisationUnitStore, organisationUnitStore, organisationUnitLevelStore, organisationUnitOrganisationUnitGroupLinkStore ) @Test fun `Should get relative organisation unit uids`() { val unorderedList = listOf("3", "2", "1") val orderedList = listOf("1", "2", "3") whenever( userOrganisationUnitStore .queryAssignedOrganisationUnitUidsByScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE) ) doReturn unorderedList whenever( organisationUnitStore.selectUidsWhere(any(), any()) ) doReturn orderedList val relativeUids = helper.getRelativeOrganisationUnitUids(RelativeOrganisationUnit.USER_ORGUNIT) assertThat(relativeUids).isEqualTo(orderedList) } }
bsd-3-clause
89556d14a75a4326add2c868c8f502cd
46.807692
118
0.778761
4.849155
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/onboarding/InitialOnboardingFragment.kt
1
4977
package org.wikipedia.onboarding import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.activity.FragmentUtil import org.wikipedia.analytics.LoginFunnel import org.wikipedia.login.LoginActivity import org.wikipedia.model.EnumCode import org.wikipedia.model.EnumCodeMap import org.wikipedia.settings.Prefs import org.wikipedia.settings.languages.WikipediaLanguagesActivity import org.wikipedia.util.FeedbackUtil import org.wikipedia.util.UriUtil class InitialOnboardingFragment : OnboardingFragment(), OnboardingPageView.Callback { private var onboardingPageView: OnboardingPageView? = null override fun getAdapter(): FragmentStateAdapter { return OnboardingPagerAdapter(this) } override val doneButtonText = R.string.onboarding_get_started override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == Constants.ACTIVITY_REQUEST_LOGIN && resultCode == LoginActivity.RESULT_LOGIN_SUCCESS) { FeedbackUtil.showMessage(this, R.string.login_success_toast) advancePage() } else { super.onActivityResult(requestCode, resultCode, data) } } override fun onSwitchChange(view: OnboardingPageView, checked: Boolean) { if (OnboardingPage.of(view.tag as Int) == OnboardingPage.PAGE_USAGE_DATA) { Prefs.setEventLoggingEnabled(checked) } } override fun onLinkClick(view: OnboardingPageView, url: String) { when (url) { "#login" -> startActivityForResult(LoginActivity .newIntent(requireContext(), LoginFunnel.SOURCE_ONBOARDING), Constants.ACTIVITY_REQUEST_LOGIN) "#privacy" -> FeedbackUtil.showPrivacyPolicy(requireContext()) "#about" -> FeedbackUtil.showAboutWikipedia(requireContext()) "#offline" -> FeedbackUtil.showOfflineReadingAndData(requireContext()) else -> UriUtil.handleExternalLink(requireActivity(), Uri.parse(url)) } } override fun onListActionButtonClicked(view: OnboardingPageView) { onboardingPageView = view requireContext().startActivity(WikipediaLanguagesActivity.newIntent(requireContext(), Constants.InvokeSource.ONBOARDING_DIALOG)) } override fun onResume() { super.onResume() onboardingPageView?.refreshLanguageList() } private class OnboardingPagerAdapter constructor(fragment: Fragment) : FragmentStateAdapter(fragment) { override fun createFragment(position: Int): Fragment { return ItemFragment.newInstance(position) } override fun getItemCount(): Int { return OnboardingPage.size() } } class ItemFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { super.onCreateView(inflater, container, savedInstanceState) val position = requireArguments().getInt("position", 0) val view = inflater.inflate(OnboardingPage.of(position).layout, container, false) as OnboardingPageView if (OnboardingPage.PAGE_USAGE_DATA.code() == position) { view.setSwitchChecked(Prefs.isEventLoggingEnabled()) } view.tag = position view.callback = callback return view } private val callback get() = FragmentUtil.getCallback(this, OnboardingPageView.Callback::class.java) companion object { fun newInstance(position: Int): ItemFragment { return ItemFragment().apply { arguments = bundleOf("position" to position) } } } } @Suppress("unused") internal enum class OnboardingPage(@LayoutRes val layout: Int) : EnumCode { PAGE_WELCOME(R.layout.inflate_initial_onboarding_page_zero), PAGE_EXPLORE(R.layout.inflate_initial_onboarding_page_one), PAGE_READING_LISTS(R.layout.inflate_initial_onboarding_page_two), PAGE_USAGE_DATA(R.layout.inflate_initial_onboarding_page_three); override fun code(): Int { return ordinal } companion object { private val MAP = EnumCodeMap(OnboardingPage::class.java) fun of(code: Int): OnboardingPage { return MAP[code] } fun size(): Int { return MAP.size() } } } companion object { fun newInstance(): InitialOnboardingFragment { return InitialOnboardingFragment() } } }
apache-2.0
33c3f01c9b661a7ae75c0c0770f0c93f
36.421053
136
0.677115
5.057927
false
false
false
false
dahlstrom-g/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/CommitProgressPanel.kt
1
11128
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.commit import com.intellij.icons.AllIcons import com.intellij.ide.nls.NlsMessages.formatNarrowAndList import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.TooltipDescriptionProvider import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.application.AppUIExecutor.onUiThread import com.intellij.openapi.application.impl.coroutineDispatchingContext import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase import com.intellij.openapi.progress.util.ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsBundle.messagePointer import com.intellij.openapi.vcs.changes.InclusionListener import com.intellij.openapi.wm.ex.ProgressIndicatorEx import com.intellij.openapi.wm.ex.StatusBarEx import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.ui.AnimatedIcon import com.intellij.ui.EditorTextComponent import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.components.panels.VerticalLayout import com.intellij.util.progress.DelegatingProgressIndicatorEx import com.intellij.util.ui.HtmlPanel import com.intellij.util.ui.JBUI.Borders.empty import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.UIUtil.getErrorForeground import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.jetbrains.annotations.Nls import java.awt.Dimension import java.awt.Font import javax.swing.BoxLayout import javax.swing.JComponent import javax.swing.event.HyperlinkEvent import kotlin.properties.Delegates.observable import kotlin.properties.ReadWriteProperty private fun JBLabel.setError(@NlsContexts.Label errorText: String) { text = errorText icon = AllIcons.General.Error foreground = getErrorForeground() isVisible = true } private fun JBLabel.setWarning(@NlsContexts.Label warningText: String) { text = warningText icon = AllIcons.General.Warning foreground = null isVisible = true } open class CommitProgressPanel : NonOpaquePanel(VerticalLayout(4)), CommitProgressUi, InclusionListener, DocumentListener, Disposable { private val scope = CoroutineScope(SupervisorJob() + onUiThread().coroutineDispatchingContext()) .also { Disposer.register(this) { it.cancel() } } private val taskInfo = CommitChecksTaskInfo() private val progressFlow = MutableStateFlow<CommitChecksProgressIndicator?>(null) private var progress: CommitChecksProgressIndicator? by progressFlow::value private val failuresPanel = FailuresPanel() private val label = JBLabel().apply { isVisible = false } override var isEmptyMessage by stateFlag() override var isEmptyChanges by stateFlag() override var isDumbMode by stateFlag() protected fun stateFlag(): ReadWriteProperty<Any?, Boolean> { return observable(false) { _, oldValue, newValue -> if (oldValue == newValue) return@observable update() } } fun setup(commitWorkflowUi: CommitWorkflowUi, commitMessage: EditorTextComponent) { add(label) add(failuresPanel) Disposer.register(commitWorkflowUi, this) commitMessage.addDocumentListener(this) commitWorkflowUi.addInclusionListener(this, this) setupProgressVisibilityDelay() setupProgressSpinnerTooltip() } @Suppress("EXPERIMENTAL_API_USAGE") private fun setupProgressVisibilityDelay() { progressFlow .debounce(DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS.toLong()) .onEach { indicator -> if (indicator?.isRunning == true && failuresPanel.isEmpty()) indicator.component.isVisible = true } .launchIn(scope + CoroutineName("Commit checks indicator visibility")) } private fun setupProgressSpinnerTooltip() { val tooltip = CommitChecksProgressIndicatorTooltip({ progress }, { failuresPanel.width }) tooltip.installOn(failuresPanel.iconLabel, this) } override fun dispose() = Unit override fun startProgress(isOnlyRunCommitChecks: Boolean): ProgressIndicatorEx { check(progress == null) { "Commit checks indicator already created" } val indicator = InlineCommitChecksProgressIndicator(isOnlyRunCommitChecks) Disposer.register(this, indicator) indicator.component.isVisible = false indicator.addStateDelegate(object : AbstractProgressIndicatorExBase() { override fun start() = progressStarted(indicator) override fun stop() = progressStopped(indicator) }) progress = indicator return IndeterminateIndicator(indicator) } private fun progressStarted(indicator: InlineCommitChecksProgressIndicator) { logger<CommitProgressPanel>().assertTrue(progress == indicator) add(indicator.component) addToStatusBar(indicator.statusBarDelegate) failuresPanel.clearFailures() revalidate() } private fun progressStopped(indicator: InlineCommitChecksProgressIndicator) { logger<CommitProgressPanel>().assertTrue(progress == indicator) progress = null remove(indicator.component) removeFromStatusBar(indicator.statusBarDelegate) Disposer.dispose(indicator) failuresPanel.endProgress() revalidate() } private fun addToStatusBar(progress: ProgressIndicatorEx) { val frame = WindowManagerEx.getInstanceEx().findFrameFor(null) ?: return val statusBar = frame.statusBar as? StatusBarEx ?: return statusBar.addProgress(progress, taskInfo) } private fun removeFromStatusBar(progress: ProgressIndicatorEx) { // `finish` tracks list of finished `TaskInfo`-s - so we pass new instance to remove from status bar progress.finish(taskInfo) } override fun addCommitCheckFailure(failure: CommitCheckFailure) { progress?.component?.isVisible = false failuresPanel.addFailure(failure) } override fun clearCommitCheckFailures() = failuresPanel.clearFailures() override fun getCommitCheckFailures(): List<CommitCheckFailure> { return failuresPanel.getFailures() } override fun documentChanged(event: DocumentEvent) = clearError() override fun inclusionChanged() = clearError() protected fun update() { val error = buildErrorText() when { error != null -> label.setError(error) isDumbMode -> label.setWarning(message("label.commit.checks.not.available.during.indexing")) else -> label.isVisible = false } } protected open fun clearError() { isEmptyMessage = false isEmptyChanges = false } @NlsContexts.Label protected open fun buildErrorText(): String? = when { isEmptyChanges && isEmptyMessage -> message("error.no.changes.no.commit.message") isEmptyChanges -> message("error.no.changes.to.commit") isEmptyMessage -> message("error.no.commit.message") else -> null } } class CommitCheckFailure(@Nls val text: String, val detailsViewer: (() -> Unit)?) private class FailuresPanel : JBPanel<FailuresPanel>() { private var nextFailureId = 0 private val failures = mutableMapOf<Int, CommitCheckFailure>() val iconLabel = JBLabel() private val description = FailuresDescriptionPanel() init { layout = BoxLayout(this, BoxLayout.X_AXIS) add(iconLabel) add(description.apply { border = empty(4, 4, 0, 0) }) add(createCommitChecksToolbar(this).component) isOpaque = false isVisible = false } fun isEmpty(): Boolean = failures.isEmpty() fun clearFailures() { isVisible = false iconLabel.icon = null failures.clear() update() } fun addFailure(failure: CommitCheckFailure) { isVisible = true iconLabel.icon = AnimatedIcon.Default() failures[nextFailureId++] = failure update() } fun endProgress() { isVisible = failures.isNotEmpty() if (isVisible) iconLabel.icon = AllIcons.General.Warning } fun getFailures() = failures.values.toList() private fun update() { description.failures = failures description.update() } } private class FailuresDescriptionPanel : HtmlPanel() { private val isInitialized = true // workaround as `getBody()` is called from super constructor var failures: Map<Int, CommitCheckFailure> = emptyMap() // For `BoxLayout` to layout "commit checks toolbar" right after failures description override fun getMaximumSize(): Dimension { val size = super.getMaximumSize() if (isMaximumSizeSet) return size return Dimension(size).apply { width = preferredSize.width } } override fun getBodyFont(): Font = StartupUiUtil.getLabelFont() override fun getBody(): String = if (isInitialized) buildDescription().toString() else "" override fun hyperlinkUpdate(e: HyperlinkEvent) = showDetails(e) private fun buildDescription(): HtmlChunk { if (failures.isEmpty()) return HtmlChunk.empty() val failureLinks = formatNarrowAndList(failures.map { if (it.value.detailsViewer != null) { HtmlChunk.link(it.key.toString(), it.value.text) } else { HtmlChunk.text(it.value.text) } }) return HtmlChunk.raw(message("label.commit.checks.failed", failureLinks)) } private fun showDetails(event: HyperlinkEvent) { if (event.eventType != HyperlinkEvent.EventType.ACTIVATED) return val failure = failures[event.description.toInt()] ?: return failure.detailsViewer!!.invoke() } } private fun createCommitChecksToolbar(target: JComponent): ActionToolbar = ActionManager.getInstance().createActionToolbar( "ChangesView.CommitChecksToolbar", DefaultActionGroup(RerunCommitChecksAction()), true ).apply { setTargetComponent(target) (this as? ActionToolbarImpl)?.setForceMinimumSize(true) // for `BoxLayout` setReservePlaceAutoPopupIcon(false) layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY component.isOpaque = false component.border = null } private class RerunCommitChecksAction : EmptyAction.MyDelegatingAction(ActionManager.getInstance().getAction("Vcs.RunCommitChecks")), TooltipDescriptionProvider { init { templatePresentation.apply { setText(Presentation.NULL_STRING) setDescription(messagePointer("tooltip.rerun.commit.checks")) icon = AllIcons.General.InlineRefresh hoveredIcon = AllIcons.General.InlineRefreshHover } } } private class IndeterminateIndicator(indicator: ProgressIndicatorEx) : DelegatingProgressIndicatorEx(indicator) { override fun setIndeterminate(indeterminate: Boolean) = Unit override fun setFraction(fraction: Double) = Unit }
apache-2.0
8dfeb41dd4fd83197cdd722b4dc4e5d7
33.24
135
0.761862
4.623182
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/mock/MockLocation.kt
3
3187
// 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.debugger.test.mock import com.sun.jdi.* class MockLocation( private val codeIndex: Int, private val lineNumber: Int, private val sourceName: String, private val sourcePath: String?, private val outputLineNumber: Int, private val method: Method, private val declaringType: ReferenceType? = null, ) : Location { internal var kotlinDebugLineNumber: Int = -1 internal var kotlinDebugSourceName: String? = null internal var kotlinDebugSourcePath: String? = null constructor(declaringType: ReferenceType, sourceName: String, lineNumber: Int) : this( codeIndex = -1, lineNumber = lineNumber, sourceName = sourceName, sourcePath = null, outputLineNumber = -1, declaringType = declaringType, method = MockMethod("", declaringType.virtualMachine()) ) fun withCodeIndex(codeIndex: Int) = MockLocation( codeIndex, lineNumber, sourceName, sourcePath, outputLineNumber, method, declaringType ).also { it.kotlinDebugLineNumber = kotlinDebugLineNumber it.kotlinDebugSourceName = kotlinDebugSourceName it.kotlinDebugSourcePath = kotlinDebugSourcePath } override fun toString(): String = "$sourceName:$lineNumber@$codeIndex" override fun codeIndex() = codeIndex.toLong() override fun lineNumber() = lineNumber override fun sourceName() = sourceName override fun declaringType() = declaringType!! override fun method() = method // LocationImpl also checks that the underlying methods are the same. override fun compareTo(other: Location): Int { val diff = codeIndex() - other.codeIndex() return if (diff < 0) -1 else if (diff > 0) 1 else 0 } override fun lineNumber(stratum: String): Int = when (stratum) { "Java" -> outputLineNumber "Kotlin" -> lineNumber "KotlinDebug" -> kotlinDebugLineNumber else -> error("Unknown stratum: $stratum") } override fun sourceName(stratum: String): String = when (stratum) { "Java" -> throw AbsentInformationException() "Kotlin" -> sourceName "KotlinDebug" -> kotlinDebugSourceName ?: throw AbsentInformationException() else -> error("Unknown stratum: $stratum") } override fun virtualMachine(): VirtualMachine = method.virtualMachine() override fun sourcePath(): String = sourcePath ?: throw AbsentInformationException() override fun sourcePath(stratum: String): String = when (stratum) { // JDI would actually compute a path based on the sourceName and the package of the enclosing reference type, // but that's not useful for Kotlin anyway. "Java" -> throw AbsentInformationException() "Kotlin" -> sourcePath ?: throw AbsentInformationException() "KotlinDebug" -> kotlinDebugSourcePath ?: throw AbsentInformationException() else -> error("Unknown stratum: $stratum") } }
apache-2.0
c53eec60bb6a7b00810723fe3787584e
36.940476
158
0.679008
5.011006
false
false
false
false
dahlstrom-g/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/intentions/MarkdownRemoveColumnIntention.kt
4
1640
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables.intentions import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.removeColumn import org.intellij.plugins.markdown.editor.tables.TableUtils import org.intellij.plugins.markdown.settings.MarkdownSettings internal class MarkdownRemoveColumnIntention: PsiElementBaseIntentionAction() { override fun getFamilyName() = text override fun getText(): String { return MarkdownBundle.message("markdown.remove.column.intention.text") } override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean { if (!MarkdownSettings.getInstance(project).isEnhancedEditingEnabled) { return false } val cell = TableUtils.findCell(element) return cell != null && cell.parentTable != null && editor != null } override fun invoke(project: Project, editor: Editor?, element: PsiElement) { val cell = TableUtils.findCell(element) val table = cell?.parentTable if (cell == null || table == null || editor == null) { return } val columnIndex = cell.columnIndex executeCommand(table.project) { table.removeColumn(columnIndex) } } }
apache-2.0
54199a45a34680b21ca7425e3b26aa37
40
158
0.768902
4.505495
false
false
false
false
elpassion/el-space-android
el-space-app/src/main/java/pl/elpassion/elspace/hub/report/list/service/ReportDayServiceImpl.kt
1
3632
package pl.elpassion.elspace.hub.report.list.service import pl.elpassion.elspace.common.extensions.* import pl.elpassion.elspace.hub.report.DailyReport import pl.elpassion.elspace.hub.report.HourlyReport import pl.elpassion.elspace.hub.report.Report import pl.elpassion.elspace.hub.report.list.* import io.reactivex.Observable import java.util.* class ReportDayServiceImpl(private val reportListService: ReportList.Service) : ReportDayService { override fun createDays(dateChangeObservable: Observable<YearMonth>): Observable<List<Day>> = dateChangeObservable .flatMap { yearMonth -> reportListService.getReports(yearMonth).map { yearMonth to it } } .map { (yearMonth, reportList) -> createDaysWithReports(yearMonth, reportList) } private fun createDaysWithReports(yearMonth: YearMonth, reportList: List<Report>) = (1..yearMonth.month.daysInMonth).map { dayNumber -> val calendarForDay = getCalendarForDay(yearMonth, dayNumber) val reports = reportList.filter(isFromSelectedDay(yearMonth, dayNumber)) createDayWithReports(calendarForDay, dayNumber, reports, yearMonth) } private fun createDayWithReports(calendarForDay: Calendar, dayNumber: Int, reports: List<Report>, yearMonth: YearMonth): Day { val hasPassed = calendarForDay.isNotAfter(getCurrentTimeCalendar()) val date = getDateString(yearMonth.year, yearMonth.month.index + 1, dayNumber) val dayName = "$dayNumber ${calendarForDay.dayName()}" val uuid = createDayUUid(yearMonth.year, yearMonth.month.index, dayNumber) return when { reports.isEmpty() -> createDayWithoutReports(uuid, calendarForDay, hasPassed, date, dayName) reports.all { it is HourlyReport } -> createDayWithHourlyReports(uuid, reports, hasPassed, date, dayName) reports.all { it is DailyReport } && reports.size == 1 -> createDayWithDailyReports(uuid, reports, hasPassed, date, dayName) else -> throw IllegalArgumentException() } } private fun createDayWithDailyReports(uuid: Long, reports: List<Report>, hasPassed: Boolean, date: String, dayName: String): DayWithDailyReport { return DayWithDailyReport(uuid = uuid, report = reports.filterIsInstance<DailyReport>().first(), hasPassed = hasPassed, name = dayName, date = date) } private fun createDayWithHourlyReports(uuid: Long, reports: List<Report>, hasPassed: Boolean, date: String, dayName: String): DayWithHourlyReports { return DayWithHourlyReports(uuid = uuid, reports = reports.filterIsInstance<HourlyReport>(), hasPassed = hasPassed, name = dayName, date = date) } private fun createDayWithoutReports(uuid: Long, calendarForDay: Calendar, hasPassed: Boolean, date: String, dayName: String): DayWithoutReports { return DayWithoutReports(uuid = uuid, name = dayName, hasPassed = hasPassed, date = date, isWeekend = calendarForDay.isWeekendDay()) } private fun isFromSelectedDay(yearMonth: YearMonth, day: Int): (Report) -> Boolean = { report -> report.year == yearMonth.year && report.month == yearMonth.month.index + 1 && report.day == day } private fun getCalendarForDay(yearMonth: YearMonth, dayNumber: Int) = getTimeFrom(year = yearMonth.year, month = yearMonth.month.index, day = dayNumber) }
gpl-3.0
2cc5930f2c07d32218d32054f25f37e0
50.9
156
0.672357
4.489493
false
false
false
false
elpassion/el-space-android
el-debate/src/androidTest/java/pl/elpassion/elspace/debate/details/DebateDetailsApiInteractor.kt
1
1755
package pl.elpassion.elspace.debate.details import com.nhaarman.mockito_kotlin.* import io.reactivex.subjects.CompletableSubject import io.reactivex.subjects.SingleSubject open class DebateDetailsApiInteractor : DebateDetailsViewInteractor() { private val debateDetailsSubject = SingleSubject.create<DebateData>() private val sendVoteSubject = CompletableSubject.create() private val apiMock by lazy { mock<DebateDetails.Api>().apply { whenever(getDebateDetails(any())).thenReturn(debateDetailsSubject) whenever(vote(any(), any())).thenReturn(sendVoteSubject) } } val votingApi: VotingApiInteractor = VotingApiInteractor() val debateApi: DebateApiInteractor = DebateApiInteractor() fun inject() { DebateDetails.ApiProvider.override = { apiMock } } inner class DebateApiInteractor { fun assertCalled(tokenMatcher: () -> String = { any() }) { verify(apiMock, times(1)).getDebateDetails(tokenMatcher()) } fun success(debateData: DebateData) { debateDetailsSubject.onSuccess(debateData) } fun error(runtimeException: Exception) { debateDetailsSubject.onError(runtimeException) } fun resetInvocations() { clearInvocations(apiMock) } } inner class VotingApiInteractor { fun error(httpException: Exception) { sendVoteSubject.onError(httpException) } fun assertCalled(tokenMatcher: () -> String = { any() }, answerMatcher: () -> Answer = { any() }) { verify(apiMock).vote(tokenMatcher(), answerMatcher()) } fun success() { sendVoteSubject.onComplete() } } }
gpl-3.0
db09342a20c53e2e31cd1432088c7970
29.275862
107
0.651282
4.630607
false
false
false
false
TechzoneMC/SonarPet
core/src/main/kotlin/net/techcable/sonarpet/nms/entity/generators/GeneratedMethod.kt
1
4683
package net.techcable.sonarpet.nms.entity.generators import net.techcable.sonarpet.utils.asmType import net.techcable.sonarpet.utils.bytecode.MethodGenerator import net.techcable.sonarpet.utils.isWrapperType import net.techcable.sonarpet.utils.primitiveWrapperType import net.techcable.sonarpet.utils.toImmutableList import org.objectweb.asm.Handle import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type import org.objectweb.asm.Type.* import java.lang.invoke.MethodHandle import java.util.function.Consumer import kotlin.reflect.KClass class GeneratedMethod( val name: String, val returnType: Type = VOID_TYPE, parameterTypes: List<Type> = listOf(), val access: Int = ACC_PUBLIC, val invokeCheckSanity: Boolean = true, // Almost everyone should invoke checkSanity val generator: MethodGenerator.(GenerationState) -> Unit ) { val parameterTypes = parameterTypes.toImmutableList() // Paranoid fun generate(state: GenerationState) { state.generator.generateMethod( Consumer { methodGenerator -> if (invokeCheckSanity) with(state) { methodGenerator.generateCheckSanity() } generator(methodGenerator, state) }, access, name, returnType, *parameterTypes.toTypedArray() ) } constructor( name: String, returnType: KClass<*>? = null, // null -> void parameterTypes: List<KClass<*>> = listOf(), access: Int = ACC_PUBLIC, generator: MethodGenerator.(GenerationState) -> Unit ) : this( name = name, returnType = returnType?.asmType ?: VOID_TYPE, parameterTypes = parameterTypes.map(KClass<*>::asmType), access = access, generator = generator ) companion object { fun createGetter( fieldName: String, fieldType: Type, returnType: Type = fieldType, methodName: String = "get${fieldName.firstToUpper()}", access: Int = ACC_PUBLIC ): GeneratedMethod { return GeneratedMethod( name = methodName, returnType = returnType, access = access ) { state -> loadThis() getField(state.currentType, fieldName, fieldType) } } fun noOp( methodName: String, returnType: Type = VOID_TYPE, access: Int = ACC_PUBLIC, parameterTypes: List<Type> = listOf(), invokeCheckSanity: Boolean = true ): GeneratedMethod { return GeneratedMethod( name = methodName, returnType = returnType, parameterTypes = parameterTypes, access = access, invokeCheckSanity = invokeCheckSanity, generator = {} ) } fun returnConstant( methodName: String, constant: Any, access: Int = ACC_PUBLIC, parameterTypes: List<Type> = listOf() ): GeneratedMethod { val constantType: Type = when (constant) { is Boolean -> BOOLEAN_TYPE is Number -> { require(constant.javaClass.isWrapperType) { "Constant number isn't a primitive wrapper type: $constant" } constant.javaClass.primitiveWrapperType.asmType } is Class<*> -> Class::class.asmType is Type -> if (constant.sort == METHOD) MethodHandle::class.asmType else Class::class.asmType is Handle -> MethodHandle::class.asmType else -> throw IllegalArgumentException("Invalid constant: $constant") } return GeneratedMethod( name = methodName, returnType = constantType, access = access, parameterTypes = parameterTypes ) { when (constant) { // Booleans are represented on the stack as ints -_- is Boolean -> visitInsn(if (constant) ICONST_1 else ICONST_0) is Class<*> -> visitLdcInsn(constant.asmType) else -> visitLdcInsn(constant) } } } } } // Utils private fun String.firstToUpper() = this[0].toUpperCase() + substring(1)
gpl-3.0
659cca4634fb564dc60f778d9cd3c4cf
37.385246
125
0.546445
5.439024
false
false
false
false
cxpqwvtj/himawari
web/src/main/kotlin/app/himawari/service/report/ReportService.kt
1
4238
package app.himawari.service.report import app.himawari.dto.json.VacationType import app.himawari.dto.report.TimecardRow import app.himawari.exbhv.TimecardDayBhv import app.himawari.model.AppDate import app.himawari.model.AppProperty import app.himawari.model.report.ReportTemplateProvider import org.apache.poi.ss.usermodel.Workbook import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.time.LocalDate import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.time.temporal.TemporalAdjusters /** * 帳票生成サービスです。 * Created by fukuda on 2017/02/24. */ @Service class ReportService( private val appDate: AppDate, private val appProperty: AppProperty, private val reportTemplateProvider: ReportTemplateProvider, private val timecardDayBhv: TimecardDayBhv ) { private val logger = LoggerFactory.getLogger(this.javaClass) fun createXlsx(yearMonth: LocalDate, userId: String): Workbook { val workbook = reportTemplateProvider.reportTemplateManager.excelTemplate() val sheet = workbook.getSheet(appProperty.timecard.excel.outputSheetName) ?: workbook.createSheet(appProperty.timecard.excel.outputSheetName) val list = timecardDayBhv.selectList { cb -> cb.setupSelect_DailyStartEndAsCurrentValue() cb.query().setBizDate_FromTo(yearMonth, yearMonth, { option -> option.compareAsMonth() }) cb.query().queryMember().setMemberAccountId_Equal(userId) cb.query().addOrderBy_BizDate_Asc() } val firstDayOfMonth = yearMonth.with(TemporalAdjusters.firstDayOfMonth()) val lastDayOfMonth = yearMonth.with(TemporalAdjusters.lastDayOfMonth()) val rows = (0..ChronoUnit.DAYS.between(firstDayOfMonth, lastDayOfMonth)).map { dayIndex -> val bizDate = appDate.toDate(firstDayOfMonth.plusDays(dayIndex).atStartOfDay()) val timecardDay = list.singleOrNull { it.bizDate.compareTo(firstDayOfMonth.plusDays(dayIndex)) == 0 } if (timecardDay?.dailyStartEndAsCurrentValue?.isPresent ?: false) { val day = timecardDay!!.dailyStartEndAsCurrentValue.get() TimecardRow(bizDate, day.startDatetime?.format(DateTimeFormatter.ofPattern("HH:mm")) ?: "", day.endDatetime?.format(DateTimeFormatter.ofPattern("HH:mm")) ?: "", if (day.vacationTypeCode == null) "" else VacationType.valueOf(day.vacationTypeCode).description, day.note ?: "") } else { TimecardRow(bizDate, "", "", "", "") } } rows.mapIndexed { i, timecardRow -> val row = sheet.getRow(appProperty.timecard.excel.beginRowNum + i) ?: sheet.createRow(appProperty.timecard.excel.beginRowNum + i) val bizDateCell = row.getCell(appProperty.timecard.excel.bizDateColumnIndex) ?: row.createCell(appProperty.timecard.excel.bizDateColumnIndex) bizDateCell.setCellValue(timecardRow.bizDate) val bizDateStyle = workbook.creationHelper.createDataFormat().getFormat("yyyy/MM/dd") val bizDateCellStyle = workbook.createCellStyle() bizDateCellStyle.dataFormat = bizDateStyle bizDateCell.cellStyle = bizDateCellStyle (row.getCell(appProperty.timecard.excel.startDatetimeColumnIndex) ?: row.createCell(appProperty.timecard.excel.startDatetimeColumnIndex)).setCellValue(timecardRow.startDatetime) (row.getCell(appProperty.timecard.excel.endDatetimeColumnIndex) ?: row.createCell(appProperty.timecard.excel.endDatetimeColumnIndex)).setCellValue(timecardRow.endDatetime) (row.getCell(appProperty.timecard.excel.vacationTypeColumnIndex) ?: row.createCell(appProperty.timecard.excel.vacationTypeColumnIndex)).setCellValue(timecardRow.vacationType) (row.getCell(appProperty.timecard.excel.noteColumnIndex) ?: row.createCell(appProperty.timecard.excel.noteColumnIndex)).setCellValue(timecardRow.note) } appProperty.timecard.excel.autoSizeColumnIndexes.map { sheet.autoSizeColumn(it) } return workbook } }
mit
4dd9e4d32a824ab137e8a7d56e39f302
55.986486
189
0.714184
4.038314
false
false
false
false
cbeust/klaxon
klaxon/src/test/kotlin/com/beust/klaxon/Issue220Test.kt
1
1377
package com.beust.klaxon import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.testng.annotations.Test import java.time.LocalDate @Test class Issue220Test { private val dateTime = object : Converter { override fun canConvert(cls: Class<*>) = cls == LocalDate::class.java override fun fromJson(jv: JsonValue): LocalDate = LocalDate.parse(jv.string) override fun toJson(value: Any): String = "\"$value\"" } // numberOfEyes contains a String instead of an Int private val referenceFailingTestFixture = """ { "lastName": "Doe", "firstName": "Jane", "dateOfBirth": "1990-11-23", "numberOfEyes": "2" } """.trimIndent() data class Person( val lastName: String, val firstName: String, val dateOfBirth: LocalDate, val numberOfEyes: Int ) fun displayMeaningfulErrorMessage() { val klaxon = Klaxon().apply { converter(dateTime) } try { val janeDoe = klaxon.parse<Person>(referenceFailingTestFixture) assertThat(janeDoe!!.numberOfEyes).isGreaterThan(0) fail("Should have failed to parse that JSON") } catch(e: KlaxonException) { assertThat(e.message).contains("Parameter numberOfEyes") } } }
apache-2.0
9933002dd94dc04faf3233bed6445847
28.319149
84
0.625999
4.456311
false
true
false
false
auricgoldfinger/Memento-Namedays
android_mobile/src/main/java/com/alexstyl/specialdates/person/AndroidPersonView.kt
3
5112
package com.alexstyl.specialdates.person import android.content.res.Resources import android.graphics.Bitmap import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.graphics.drawable.TransitionDrawable import android.support.annotation.ColorRes import android.support.annotation.DrawableRes import android.support.design.widget.AppBarLayout import android.support.design.widget.TabLayout import android.support.v4.content.res.ResourcesCompat import android.view.View import android.widget.ImageView import android.widget.TextView import com.alexstyl.android.Version import com.alexstyl.specialdates.R import com.alexstyl.specialdates.images.ImageLoadedConsumer import com.alexstyl.specialdates.images.ImageLoader import com.alexstyl.specialdates.theming.Themer import com.nostra13.universalimageloader.core.assist.LoadedFrom import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer import com.nostra13.universalimageloader.core.imageaware.ImageViewAware class AndroidPersonView(private val personNameView: TextView, private val ageAndSignView: TextView, private val imageLoader: ImageLoader, private val avatarView: ImageView, private val adapter: ContactItemsAdapter, private val tabLayout: TabLayout, private val appBarLayout: AppBarLayout, private val toolbarGradient: ImageView, private val resources: Resources, private val onOffsetChangedListener: AppBarLayout.OnOffsetChangedListener, private val themer: Themer) : PersonView { override fun displayPersonInfo(viewModel: PersonInfoViewModel) { personNameView.text = viewModel.displayName ageAndSignView.text = viewModel.ageAndStarSignlabel ageAndSignView.visibility = viewModel.AgeAndStarSignVisibility imageLoader.load(viewModel.image) .withSize(avatarView.width, avatarView.height) .into(object : ImageLoadedConsumer { override fun onImageLoaded(loadedImage: Bitmap) { if (Version.hasLollipop()) { appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener) } FadeInBitmapDisplayer(ANIMATION_DURATION).display(loadedImage, ImageViewAware(avatarView), LoadedFrom.DISC_CACHE) val layers = arrayOfNulls<Drawable>(2) layers[0] = resources.getColorDrawable(android.R.color.transparent) layers[1] = resources.getDrawableCompat(R.drawable.black_to_transparent_gradient_facing_down) val transitionDrawable = TransitionDrawable(layers) toolbarGradient.setImageDrawable(transitionDrawable) transitionDrawable.startTransition(ANIMATION_DURATION) toolbarGradient.visibility = View.VISIBLE } override fun onLoadingFailed() { val layers = arrayOfNulls<Drawable>(2) layers[0] = resources.getColorDrawable(android.R.color.transparent) layers[1] = resources.getDrawableCompat(R.drawable.ic_person_96dp) val transitionDrawable = TransitionDrawable(layers) avatarView.setImageDrawable(transitionDrawable) transitionDrawable.startTransition(ANIMATION_DURATION) toolbarGradient.visibility = View.GONE } }) } override fun displayAvailableActions(viewModel: PersonAvailableActionsViewModel) { adapter.displayEvents(viewModel) updateTabIfNeeded(0, R.drawable.ic_gift) updateTabIfNeeded(1, R.drawable.ic_call) updateTabIfNeeded(2, R.drawable.ic_message) if (tabLayout.tabCount <= 1) { tabLayout.visibility = View.GONE } else { tabLayout.visibility = View.VISIBLE } } override fun showPersonAsVisible() { throw UnsupportedOperationException("Visibility is not currently available") } override fun showPersonAsHidden() { throw UnsupportedOperationException("Visibility is not currently available") } private fun updateTabIfNeeded(index: Int, @DrawableRes iconResId: Int) { if (tabLayout.getTabAt(index) != null) { tabLayout.getTabAt(index)!!.icon = themer.getTintedDrawable(iconResId, personNameView.context) } } companion object { private const val ANIMATION_DURATION = 400 } } private fun Resources.getDrawableCompat(@DrawableRes drawableResId: Int): Drawable? = ResourcesCompat.getDrawable(this, drawableResId, null) private fun Resources.getColorDrawable(@ColorRes colorRes: Int): Drawable? = ColorDrawable(ResourcesCompat.getColor(this, colorRes, null))
mit
d3f587af1a394550106ae1d674dc1eeb
44.642857
137
0.671362
5.426752
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/mcp/gradle/McpDataService.kt
1
1814
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.gradle import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.mcp.McpModuleType import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.Key import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project class McpDataService : AbstractProjectDataService<McpModelData, Module>() { override fun getTargetDataKey(): Key<McpModelData> = McpModelData.KEY override fun importData( toImport: Collection<DataNode<McpModelData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { if (projectData == null || toImport.isEmpty()) { return } for (node in toImport) { val data = node.data val module = modelsProvider.findIdeModule(data.module) ?: continue val mcpModule = MinecraftFacet.getInstance(module, McpModuleType) if (mcpModule != null) { // Update the local settings and recompute the SRG map mcpModule.updateSettings(data.settings) continue } val children = MinecraftFacet.getChildInstances(module) for (child in children) { child.getModuleOfType(McpModuleType)?.updateSettings(data.settings) } } } }
mit
0da9a912233f93fbdc556643d0e3b627
32.592593
92
0.696251
4.997245
false
false
false
false
marcplouhinec/trust-service-reputation
src/main/kotlin/fr/marcsworld/scheduled/DocumentCheckingTasks.kt
1
3926
package fr.marcsworld.scheduled import fr.marcsworld.enums.DocumentType import fr.marcsworld.model.dto.DocumentUrlAndType import fr.marcsworld.model.entity.DocumentCheckingResult import fr.marcsworld.service.DocumentService import fr.marcsworld.utils.ResourceDownloader import org.slf4j.LoggerFactory import org.springframework.core.io.UrlResource import org.springframework.core.task.TaskExecutor import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import org.xml.sax.InputSource import org.xml.sax.helpers.XMLReaderFactory import java.util.* /** * Tasks for checking documents and updating the database. * * @author Marc Plouhinec */ @Component open class DocumentCheckingTasks( val documentService: DocumentService, val documentCheckingTaskExecutor: TaskExecutor ) { companion object { val LOGGER = LoggerFactory.getLogger(DocumentCheckingTasks::class.java)!! } /** * Find all documents that need to be checked and create one task for each of them. */ @Scheduled(fixedRateString = "\${scheduledTask.documentChecking.fixedRateInMillis}", initialDelayString = "\${scheduledTask.documentChecking.initialDelayInMillis}") fun scheduleDocumentCheckingTasks() { LOGGER.info("Check documents.") val documentUrlAndTypes = documentService.findAllStillProvidedDocumentUrlAndTypes() for (documentUrlAndType in documentUrlAndTypes) { documentCheckingTaskExecutor.execute(DocumentCheckingTask(documentUrlAndType)) } } /** * Download and check the given document. */ inner class DocumentCheckingTask( val documentUrlAndType: DocumentUrlAndType ) : Runnable { override fun run() { LOGGER.debug("Check the document: {}", documentUrlAndType.url) val currentDate = Date() // Try to download the document val timeBeforeDownloading = System.currentTimeMillis() val documentData: ByteArray? = try { ResourceDownloader.downloadResource(UrlResource(documentUrlAndType.url)) } catch (e: Exception) { LOGGER.warn("Unable to download the document {}: {} - {}", documentUrlAndType.url, e.javaClass, e.message) null } val timeAfterDownloading = System.currentTimeMillis() // Validate the document if applicable val isDocumentValid = if (documentData is ByteArray) { if (documentUrlAndType.type == DocumentType.TS_STATUS_LIST_XML) { // Check that the XML document is well-formed try { documentData.inputStream().use { val xmlReader = XMLReaderFactory.createXMLReader() xmlReader.parse(InputSource(it)) } true } catch (e: Exception) { false } } else { true } } else { false } // Store the result in the database val result = DocumentCheckingResult( url = documentUrlAndType.url, date = currentDate, isAvailable = documentData is ByteArray, isValid = isDocumentValid, sizeInBytes = (documentData as? ByteArray)?.size ?: 0, downloadDurationInMillis = if (documentData is ByteArray) timeAfterDownloading - timeBeforeDownloading else 0) documentService.saveDocumentCheckingResult(result) } } }
mit
3ee2a5ac23b5c5a1a90d92b524721ac7
38.666667
168
0.600611
5.529577
false
false
false
false
googlearchive/android-NavigationDrawer
kotlinApp/Application/src/main/java/com/example/android/navigationdrawer/PlanetFragment.kt
3
1901
/* * Copyright (C) 2018 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.android.navigationdrawer import android.app.Fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import java.util.Locale /** * Fragment that appears in the "content_frame" and shows a planet. */ class PlanetFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val planetNumber = arguments.getInt(ARG_PLANET_NUMBER) val planet = resources.getStringArray(R.array.planets_array)[planetNumber] val imageId = resources.getIdentifier(planet.toLowerCase(Locale.getDefault()), "drawable", activity.packageName) activity.title = planet return inflater.inflate(R.layout.fragment_planet, container, false).apply { findViewById<ImageView>(R.id.image).setImageResource(imageId) } } companion object { private val ARG_PLANET_NUMBER = "planet_number" fun newInstance(position: Int) = PlanetFragment().apply { arguments = Bundle().apply { putInt(ARG_PLANET_NUMBER, position) } } } }
apache-2.0
e13bf1afeae6ef064d7474fff0795bfc
31.793103
86
0.690689
4.441589
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/primitiveEntities.kt
2
6007
// 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.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import com.intellij.workspaceModel.storage.MutableEntityStorage interface BooleanEntity : WorkspaceEntity { val data: Boolean //region generated code @GeneratedCodeApiVersion(1) interface Builder : BooleanEntity, ModifiableWorkspaceEntity<BooleanEntity>, ObjBuilder<BooleanEntity> { override var entitySource: EntitySource override var data: Boolean } companion object : Type<BooleanEntity, Builder>() { operator fun invoke(data: Boolean, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): BooleanEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: BooleanEntity, modification: BooleanEntity.Builder.() -> Unit) = modifyEntity( BooleanEntity.Builder::class.java, entity, modification) //endregion interface IntEntity : WorkspaceEntity { val data: Int //region generated code @GeneratedCodeApiVersion(1) interface Builder : IntEntity, ModifiableWorkspaceEntity<IntEntity>, ObjBuilder<IntEntity> { override var entitySource: EntitySource override var data: Int } companion object : Type<IntEntity, Builder>() { operator fun invoke(data: Int, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): IntEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: IntEntity, modification: IntEntity.Builder.() -> Unit) = modifyEntity( IntEntity.Builder::class.java, entity, modification) //endregion interface StringEntity : WorkspaceEntity { val data: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : StringEntity, ModifiableWorkspaceEntity<StringEntity>, ObjBuilder<StringEntity> { override var entitySource: EntitySource override var data: String } companion object : Type<StringEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): StringEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: StringEntity, modification: StringEntity.Builder.() -> Unit) = modifyEntity( StringEntity.Builder::class.java, entity, modification) //endregion interface ListEntity : WorkspaceEntity { val data: List<String> //region generated code @GeneratedCodeApiVersion(1) interface Builder : ListEntity, ModifiableWorkspaceEntity<ListEntity>, ObjBuilder<ListEntity> { override var entitySource: EntitySource override var data: MutableList<String> } companion object : Type<ListEntity, Builder>() { operator fun invoke(data: List<String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ListEntity { val builder = builder() builder.data = data.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ListEntity, modification: ListEntity.Builder.() -> Unit) = modifyEntity( ListEntity.Builder::class.java, entity, modification) //endregion interface OptionalIntEntity : WorkspaceEntity { val data: Int? //region generated code @GeneratedCodeApiVersion(1) interface Builder : OptionalIntEntity, ModifiableWorkspaceEntity<OptionalIntEntity>, ObjBuilder<OptionalIntEntity> { override var entitySource: EntitySource override var data: Int? } companion object : Type<OptionalIntEntity, Builder>() { operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OptionalIntEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OptionalIntEntity, modification: OptionalIntEntity.Builder.() -> Unit) = modifyEntity( OptionalIntEntity.Builder::class.java, entity, modification) //endregion interface OptionalStringEntity : WorkspaceEntity { val data: String? //region generated code @GeneratedCodeApiVersion(1) interface Builder : OptionalStringEntity, ModifiableWorkspaceEntity<OptionalStringEntity>, ObjBuilder<OptionalStringEntity> { override var entitySource: EntitySource override var data: String? } companion object : Type<OptionalStringEntity, Builder>() { operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OptionalStringEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OptionalStringEntity, modification: OptionalStringEntity.Builder.() -> Unit) = modifyEntity( OptionalStringEntity.Builder::class.java, entity, modification) //endregion // Not supported at the moment /* interface OptionalListIntEntity : WorkspaceEntity { val data: List<Int>? } */
apache-2.0
22428f4d5a17ed47c5fe1d183005e33d
30.952128
138
0.747794
4.935908
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/openapi/roots/impl/FilesScanExecutor.kt
2
8731
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.roots.impl import com.intellij.concurrency.SensitiveProgressWrapper import com.intellij.model.ModelBranchImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.ProgressIndicatorUtils import com.intellij.openapi.progress.util.ProgressWrapper import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileFilter import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.impl.VirtualFileEnumeration import com.intellij.util.ExceptionUtil import com.intellij.util.Processor import com.intellij.util.TimeoutUtil import com.intellij.util.containers.ConcurrentBitSet import com.intellij.util.containers.ContainerUtil import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.FileBasedIndexEx import com.intellij.util.indexing.IdFilter import com.intellij.util.indexing.UnindexedFilesUpdater import com.intellij.util.indexing.roots.IndexableFilesIterator import com.intellij.util.indexing.roots.kind.IndexableSetOrigin import com.intellij.util.indexing.roots.kind.LibraryOrigin import com.intellij.util.indexing.roots.kind.SdkOrigin import com.intellij.util.indexing.roots.kind.SyntheticLibraryOrigin import kotlinx.coroutines.* import kotlinx.coroutines.future.asCompletableFuture import java.util.concurrent.ConcurrentLinkedDeque import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference internal object FilesScanExecutor { private val LOG = Logger.getInstance(FilesScanExecutor::class.java) private val THREAD_COUNT = UnindexedFilesUpdater.getNumberOfScanningThreads().coerceAtLeast(1) @OptIn(ExperimentalCoroutinesApi::class) private val dispatcher = Dispatchers.IO.limitedParallelism(THREAD_COUNT) @JvmStatic fun runOnAllThreads(runnable: Runnable) { val progress = ProgressIndicatorProvider.getGlobalProgressIndicator() val results = ArrayList<Job>() val coroutineScope = ApplicationManager.getApplication().coroutineScope ProgressIndicatorUtils.awaitWithCheckCanceled( coroutineScope.launch(dispatcher) { coroutineScope { for (i in 0 until THREAD_COUNT) { results.add(launch { ProgressManager.getInstance().runProcess(runnable, ProgressWrapper.wrap(progress)) }) } } }.asCompletableFuture() ) } @JvmStatic fun <T> processOnAllThreadsInReadActionWithRetries(deque: ConcurrentLinkedDeque<T>, consumer: (T) -> Boolean): Boolean { return doProcessOnAllThreadsInReadAction(deque, consumer, true) } @JvmStatic fun <T> processOnAllThreadsInReadActionNoRetries(deque: ConcurrentLinkedDeque<T>, consumer: (T) -> Boolean): Boolean { return doProcessOnAllThreadsInReadAction(deque, consumer, false) } private fun <T> doProcessOnAllThreadsInReadAction(deque: ConcurrentLinkedDeque<T>, consumer: (T) -> Boolean, retryCanceled: Boolean): Boolean { val application = ApplicationManager.getApplication() as ApplicationEx return processOnAllThreads(deque) { o -> if (application.isReadAccessAllowed) { return@processOnAllThreads consumer(o) } var result = true val indicator = ProgressIndicatorProvider.getGlobalProgressIndicator() if (!ProgressIndicatorUtils.runInReadActionWithWriteActionPriority( { result = consumer(o) }, indicator?.let { SensitiveProgressWrapper(it) } )) { throw if (retryCanceled) ProcessCanceledException() else StopWorker() } result } } private fun <T> processOnAllThreads(deque: ConcurrentLinkedDeque<T>, processor: (T) -> Boolean): Boolean { ProgressManager.checkCanceled() if (deque.isEmpty()) { return true } val runnersCount = AtomicInteger() val idleCount = AtomicInteger() val error = AtomicReference<Throwable?>() val stopped = AtomicBoolean() val exited = AtomicBoolean() runOnAllThreads { runnersCount.incrementAndGet() var idle = false while (!stopped.get()) { ProgressManager.checkCanceled() if (deque.peek() == null) { if (!idle) { idle = true idleCount.incrementAndGet() } } else if (idle) { idle = false idleCount.decrementAndGet() } if (idle) { if (idleCount.get() == runnersCount.get() && deque.isEmpty()) break TimeoutUtil.sleep(1L) continue } val item = deque.poll() ?: continue try { if (!processor(item)) { stopped.set(true) } if (exited.get() && !stopped.get()) { throw AssertionError("early exit") } } catch (ex: StopWorker) { deque.addFirst(item) runnersCount.decrementAndGet() return@runOnAllThreads } catch (ex: ProcessCanceledException) { deque.addFirst(item) } catch (ex: Throwable) { error.compareAndSet(null, ex) } } exited.set(true) if (!deque.isEmpty() && !stopped.get()) { throw AssertionError("early exit") } } ExceptionUtil.rethrowAllAsUnchecked(error.get()) return !stopped.get() } private fun isLibOrigin(origin: IndexableSetOrigin): Boolean { return origin is LibraryOrigin || origin is SyntheticLibraryOrigin || origin is SdkOrigin } @JvmStatic fun processFilesInScope(includingBinary: Boolean, scope: GlobalSearchScope, idFilter: IdFilter?, processor: Processor<in VirtualFile?>): Boolean { ApplicationManager.getApplication().assertReadAccessAllowed() val project = scope.project ?: return true val fileIndex = ProjectRootManager.getInstance(project).fileIndex val searchInLibs = scope.isSearchInLibraries val deque = ConcurrentLinkedDeque<Any>() ModelBranchImpl.processModifiedFilesInScope(scope) { e: VirtualFile -> deque.add(e) } if (scope is VirtualFileEnumeration) { ContainerUtil.addAll<VirtualFile>(deque, FileBasedIndexEx.toFileIterable((scope as VirtualFileEnumeration).asArray())) } else { deque.addAll((FileBasedIndex.getInstance() as FileBasedIndexEx).getIndexableFilesProviders(project)) } val skippedCount = AtomicInteger() val processedCount = AtomicInteger() val visitedFiles = ConcurrentBitSet.create() val fileFilter = VirtualFileFilter { file: VirtualFile -> val fileId = FileBasedIndex.getFileId(file) if (visitedFiles.set(fileId)) return@VirtualFileFilter false val result = (idFilter == null || idFilter.containsFileId(fileId)) && !fileIndex.isExcluded(file) && scope.contains(file) && (includingBinary || file.isDirectory || !file.fileType.isBinary) if (!result) skippedCount.incrementAndGet() result } val consumer = l@ { obj: Any -> ProgressManager.checkCanceled() when (obj) { is IndexableFilesIterator -> { val origin = obj.origin if (!searchInLibs && isLibOrigin(origin)) return@l true obj.iterateFiles(project, { file: VirtualFile -> if (file.isDirectory) return@iterateFiles true deque.add(file) true }, fileFilter) } is VirtualFile -> { processedCount.incrementAndGet() if (!obj.isValid) { return@l true } return@l processor.process(obj) } else -> { throw AssertionError("unknown item: $obj") } } true } val start = System.nanoTime() val result = processOnAllThreadsInReadActionNoRetries(deque, consumer) if (LOG.isDebugEnabled) { LOG.debug("${processedCount.get()} files processed (${skippedCount.get()} skipped) in ${TimeoutUtil.getDurationMillis(start)} ms") } return result } } private class StopWorker : ProcessCanceledException()
apache-2.0
b76f9461848727580a82998c4648fd48
37.637168
136
0.685145
4.807819
false
false
false
false
square/okhttp
okhttp/src/jvmMain/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt
2
16371
/* * Copyright (C) 2012 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 okhttp3.internal.http1 import java.io.EOFException import java.io.IOException import java.net.ProtocolException import java.util.concurrent.TimeUnit.MILLISECONDS import okhttp3.Headers import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.internal.EMPTY_HEADERS import okhttp3.internal.checkOffsetAndCount import okhttp3.internal.discard import okhttp3.internal.headersContentLength import okhttp3.internal.http.ExchangeCodec import okhttp3.internal.http.RequestLine import okhttp3.internal.http.StatusLine import okhttp3.internal.http.promisesBody import okhttp3.internal.http.receiveHeaders import okhttp3.internal.http.HTTP_CONTINUE import okhttp3.internal.http.HTTP_EARLY_HINTS import okhttp3.internal.skipAll import okio.Buffer import okio.BufferedSink import okio.BufferedSource import okio.ForwardingTimeout import okio.Sink import okio.Source import okio.Timeout /** * A socket connection that can be used to send HTTP/1.1 messages. This class strictly enforces the * following lifecycle: * * 1. [Send request headers][writeRequest]. * 2. Open a sink to write the request body. Either [known][newKnownLengthSink] or * [chunked][newChunkedSink]. * 3. Write to and then close that sink. * 4. [Read response headers][readResponseHeaders]. * 5. Open a source to read the response body. Either [fixed-length][newFixedLengthSource], * [chunked][newChunkedSource] or [unknown][newUnknownLengthSource]. * 6. Read from and close that source. * * Exchanges that do not have a request body may skip creating and closing the request body. * Exchanges that do not have a response body can call * [newFixedLengthSource(0)][newFixedLengthSource] and may skip reading and closing that source. */ class Http1ExchangeCodec( /** The client that configures this stream. May be null for HTTPS proxy tunnels. */ private val client: OkHttpClient?, override val carrier: ExchangeCodec.Carrier, private val source: BufferedSource, private val sink: BufferedSink ) : ExchangeCodec { private var state = STATE_IDLE private val headersReader = HeadersReader(source) private val Response.isChunked: Boolean get() = "chunked".equals(header("Transfer-Encoding"), ignoreCase = true) private val Request.isChunked: Boolean get() = "chunked".equals(header("Transfer-Encoding"), ignoreCase = true) /** * Received trailers. Null unless the response body uses chunked transfer-encoding and includes * trailers. Undefined until the end of the response body. */ private var trailers: Headers? = null /** Returns true if this connection is closed. */ val isClosed: Boolean get() = state == STATE_CLOSED override fun createRequestBody(request: Request, contentLength: Long): Sink { return when { request.body?.isDuplex() == true -> throw ProtocolException( "Duplex connections are not supported for HTTP/1") request.isChunked -> newChunkedSink() // Stream a request body of unknown length. contentLength != -1L -> newKnownLengthSink() // Stream a request body of a known length. else -> // Stream a request body of a known length. throw IllegalStateException( "Cannot stream a request body without chunked encoding or a known content length!") } } override fun cancel() { carrier.cancel() } /** * Prepares the HTTP headers and sends them to the server. * * For streaming requests with a body, headers must be prepared **before** the output stream has * been written to. Otherwise the body would need to be buffered! * * For non-streaming requests with a body, headers must be prepared **after** the output stream * has been written to and closed. This ensures that the `Content-Length` header field receives * the proper value. */ override fun writeRequestHeaders(request: Request) { val requestLine = RequestLine.get(request, carrier.route.proxy.type()) writeRequest(request.headers, requestLine) } override fun reportedContentLength(response: Response): Long { return when { !response.promisesBody() -> 0L response.isChunked -> -1L else -> response.headersContentLength() } } override fun openResponseBodySource(response: Response): Source { return when { !response.promisesBody() -> newFixedLengthSource(0) response.isChunked -> newChunkedSource(response.request.url) else -> { val contentLength = response.headersContentLength() if (contentLength != -1L) { newFixedLengthSource(contentLength) } else { newUnknownLengthSource() } } } } override fun trailers(): Headers { check(state == STATE_CLOSED) { "too early; can't read the trailers yet" } return trailers ?: EMPTY_HEADERS } override fun flushRequest() { sink.flush() } override fun finishRequest() { sink.flush() } /** Returns bytes of a request header for sending on an HTTP transport. */ fun writeRequest(headers: Headers, requestLine: String) { check(state == STATE_IDLE) { "state: $state" } sink.writeUtf8(requestLine).writeUtf8("\r\n") for (i in 0 until headers.size) { sink.writeUtf8(headers.name(i)) .writeUtf8(": ") .writeUtf8(headers.value(i)) .writeUtf8("\r\n") } sink.writeUtf8("\r\n") state = STATE_OPEN_REQUEST_BODY } override fun readResponseHeaders(expectContinue: Boolean): Response.Builder? { check(state == STATE_OPEN_REQUEST_BODY || state == STATE_WRITING_REQUEST_BODY || state == STATE_READ_RESPONSE_HEADERS) { "state: $state" } try { val statusLine = StatusLine.parse(headersReader.readLine()) val responseBuilder = Response.Builder() .protocol(statusLine.protocol) .code(statusLine.code) .message(statusLine.message) .headers(headersReader.readHeaders()) .trailers { error("trailers not available") } return when { expectContinue && statusLine.code == HTTP_CONTINUE -> { null } statusLine.code == HTTP_CONTINUE -> { state = STATE_READ_RESPONSE_HEADERS responseBuilder } statusLine.code == HTTP_EARLY_HINTS -> { // Early Hints will mean a second header are coming. state = STATE_READ_RESPONSE_HEADERS responseBuilder } else -> { state = STATE_OPEN_RESPONSE_BODY responseBuilder } } } catch (e: EOFException) { // Provide more context if the server ends the stream before sending a response. val address = carrier.route.address.url.redact() throw IOException("unexpected end of stream on $address", e) } } private fun newChunkedSink(): Sink { check(state == STATE_OPEN_REQUEST_BODY) { "state: $state" } state = STATE_WRITING_REQUEST_BODY return ChunkedSink() } private fun newKnownLengthSink(): Sink { check(state == STATE_OPEN_REQUEST_BODY) { "state: $state" } state = STATE_WRITING_REQUEST_BODY return KnownLengthSink() } private fun newFixedLengthSource(length: Long): Source { check(state == STATE_OPEN_RESPONSE_BODY) { "state: $state" } state = STATE_READING_RESPONSE_BODY return FixedLengthSource(length) } private fun newChunkedSource(url: HttpUrl): Source { check(state == STATE_OPEN_RESPONSE_BODY) { "state: $state" } state = STATE_READING_RESPONSE_BODY return ChunkedSource(url) } private fun newUnknownLengthSource(): Source { check(state == STATE_OPEN_RESPONSE_BODY) { "state: $state" } state = STATE_READING_RESPONSE_BODY carrier.noNewExchanges() return UnknownLengthSource() } /** * Sets the delegate of `timeout` to [Timeout.NONE] and resets its underlying timeout * to the default configuration. Use this to avoid unexpected sharing of timeouts between pooled * connections. */ private fun detachTimeout(timeout: ForwardingTimeout) { val oldDelegate = timeout.delegate timeout.setDelegate(Timeout.NONE) oldDelegate.clearDeadline() oldDelegate.clearTimeout() } /** * The response body from a CONNECT should be empty, but if it is not then we should consume it * before proceeding. */ fun skipConnectBody(response: Response) { val contentLength = response.headersContentLength() if (contentLength == -1L) return val body = newFixedLengthSource(contentLength) body.skipAll(Int.MAX_VALUE, MILLISECONDS) body.close() } /** An HTTP request body. */ private inner class KnownLengthSink : Sink { private val timeout = ForwardingTimeout(sink.timeout()) private var closed: Boolean = false override fun timeout(): Timeout = timeout override fun write(source: Buffer, byteCount: Long) { check(!closed) { "closed" } checkOffsetAndCount(source.size, 0, byteCount) sink.write(source, byteCount) } override fun flush() { if (closed) return // Don't throw; this stream might have been closed on the caller's behalf. sink.flush() } override fun close() { if (closed) return closed = true detachTimeout(timeout) state = STATE_READ_RESPONSE_HEADERS } } /** * An HTTP body with alternating chunk sizes and chunk bodies. It is the caller's responsibility * to buffer chunks; typically by using a buffered sink with this sink. */ private inner class ChunkedSink : Sink { private val timeout = ForwardingTimeout(sink.timeout()) private var closed: Boolean = false override fun timeout(): Timeout = timeout override fun write(source: Buffer, byteCount: Long) { check(!closed) { "closed" } if (byteCount == 0L) return sink.writeHexadecimalUnsignedLong(byteCount) sink.writeUtf8("\r\n") sink.write(source, byteCount) sink.writeUtf8("\r\n") } @Synchronized override fun flush() { if (closed) return // Don't throw; this stream might have been closed on the caller's behalf. sink.flush() } @Synchronized override fun close() { if (closed) return closed = true sink.writeUtf8("0\r\n\r\n") detachTimeout(timeout) state = STATE_READ_RESPONSE_HEADERS } } private abstract inner class AbstractSource : Source { protected val timeout = ForwardingTimeout(source.timeout()) protected var closed: Boolean = false override fun timeout(): Timeout = timeout override fun read(sink: Buffer, byteCount: Long): Long { return try { source.read(sink, byteCount) } catch (e: IOException) { carrier.noNewExchanges() responseBodyComplete() throw e } } /** * Closes the cache entry and makes the socket available for reuse. This should be invoked when * the end of the body has been reached. */ fun responseBodyComplete() { if (state == STATE_CLOSED) return if (state != STATE_READING_RESPONSE_BODY) throw IllegalStateException("state: $state") detachTimeout(timeout) state = STATE_CLOSED } } /** An HTTP body with a fixed length specified in advance. */ private inner class FixedLengthSource(private var bytesRemaining: Long) : AbstractSource() { init { if (bytesRemaining == 0L) { responseBodyComplete() } } override fun read(sink: Buffer, byteCount: Long): Long { require(byteCount >= 0L) { "byteCount < 0: $byteCount" } check(!closed) { "closed" } if (bytesRemaining == 0L) return -1 val read = super.read(sink, minOf(bytesRemaining, byteCount)) if (read == -1L) { carrier.noNewExchanges() // The server didn't supply the promised content length. val e = ProtocolException("unexpected end of stream") responseBodyComplete() throw e } bytesRemaining -= read if (bytesRemaining == 0L) { responseBodyComplete() } return read } override fun close() { if (closed) return if (bytesRemaining != 0L && !discard(ExchangeCodec.DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)) { carrier.noNewExchanges() // Unread bytes remain on the stream. responseBodyComplete() } closed = true } } /** An HTTP body with alternating chunk sizes and chunk bodies. */ private inner class ChunkedSource(private val url: HttpUrl) : AbstractSource() { private var bytesRemainingInChunk = NO_CHUNK_YET private var hasMoreChunks = true override fun read(sink: Buffer, byteCount: Long): Long { require(byteCount >= 0L) { "byteCount < 0: $byteCount" } check(!closed) { "closed" } if (!hasMoreChunks) return -1 if (bytesRemainingInChunk == 0L || bytesRemainingInChunk == NO_CHUNK_YET) { readChunkSize() if (!hasMoreChunks) return -1 } val read = super.read(sink, minOf(byteCount, bytesRemainingInChunk)) if (read == -1L) { carrier.noNewExchanges() // The server didn't supply the promised chunk length. val e = ProtocolException("unexpected end of stream") responseBodyComplete() throw e } bytesRemainingInChunk -= read return read } private fun readChunkSize() { // Read the suffix of the previous chunk. if (bytesRemainingInChunk != NO_CHUNK_YET) { source.readUtf8LineStrict() } try { bytesRemainingInChunk = source.readHexadecimalUnsignedLong() val extensions = source.readUtf8LineStrict().trim() if (bytesRemainingInChunk < 0L || extensions.isNotEmpty() && !extensions.startsWith(";")) { throw ProtocolException("expected chunk size and optional extensions" + " but was \"$bytesRemainingInChunk$extensions\"") } } catch (e: NumberFormatException) { throw ProtocolException(e.message) } if (bytesRemainingInChunk == 0L) { hasMoreChunks = false trailers = headersReader.readHeaders() client!!.cookieJar.receiveHeaders(url, trailers!!) responseBodyComplete() } } override fun close() { if (closed) return if (hasMoreChunks && !discard(ExchangeCodec.DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)) { carrier.noNewExchanges() // Unread bytes remain on the stream. responseBodyComplete() } closed = true } } /** An HTTP message body terminated by the end of the underlying stream. */ private inner class UnknownLengthSource : AbstractSource() { private var inputExhausted: Boolean = false override fun read(sink: Buffer, byteCount: Long): Long { require(byteCount >= 0L) { "byteCount < 0: $byteCount" } check(!closed) { "closed" } if (inputExhausted) return -1 val read = super.read(sink, byteCount) if (read == -1L) { inputExhausted = true responseBodyComplete() return -1 } return read } override fun close() { if (closed) return if (!inputExhausted) { responseBodyComplete() } closed = true } } companion object { private const val NO_CHUNK_YET = -1L private const val STATE_IDLE = 0 // Idle connections are ready to write request headers. private const val STATE_OPEN_REQUEST_BODY = 1 private const val STATE_WRITING_REQUEST_BODY = 2 private const val STATE_READ_RESPONSE_HEADERS = 3 private const val STATE_OPEN_RESPONSE_BODY = 4 private const val STATE_READING_RESPONSE_BODY = 5 private const val STATE_CLOSED = 6 } }
apache-2.0
313b93cd8ceb8dd1dd0c4434f5439e78
31.54672
99
0.670332
4.344745
false
false
false
false
square/okhttp
okhttp/src/jvmTest/java/okhttp3/RecordingExecutor.kt
2
2164
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.util.concurrent.AbstractExecutorService import java.util.concurrent.RejectedExecutionException import java.util.concurrent.TimeUnit import okhttp3.internal.connection.RealCall import okhttp3.internal.finishedAccessor import org.assertj.core.api.Assertions.assertThat internal class RecordingExecutor( private val dispatcherTest: DispatcherTest ) : AbstractExecutorService() { private var shutdown: Boolean = false private val calls = mutableListOf<RealCall.AsyncCall>() override fun execute(command: Runnable) { if (shutdown) throw RejectedExecutionException() calls.add(command as RealCall.AsyncCall) } fun assertJobs(vararg expectedUrls: String) { val actualUrls = calls.map { it.request.url.toString() } assertThat(actualUrls).containsExactly(*expectedUrls) } fun finishJob(url: String) { val i = calls.iterator() while (i.hasNext()) { val call = i.next() if (call.request.url.toString() == url) { i.remove() dispatcherTest.dispatcher.finishedAccessor(call) return } } throw AssertionError("No such job: $url") } override fun shutdown() { shutdown = true } override fun shutdownNow(): List<Runnable> { throw UnsupportedOperationException() } override fun isShutdown(): Boolean { return shutdown } override fun isTerminated(): Boolean { throw UnsupportedOperationException() } override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean { throw UnsupportedOperationException() } }
apache-2.0
33bffe8107a9bde3283a0dcf55f35ed2
28.643836
75
0.727357
4.371717
false
false
false
false
vvv1559/intellij-community
python/tools/src/com/jetbrains/python/tools/BuildStubsForSdk.kt
1
2740
package com.jetbrains.python.tools import com.intellij.openapi.application.PathManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileFilter import com.jetbrains.python.PythonFileType import com.jetbrains.python.PythonModuleTypeBase import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyFileElementType import com.jetbrains.python.psi.impl.stubs.PyPrebuiltStubsProvider.PREBUILT_INDEXES_PATH_PROPERTY import com.jetbrains.python.psi.impl.stubs.PyPrebuiltStubsProvider.SDK_STUBS_STORAGE_NAME import org.jetbrains.index.stubs.LanguageLevelAwareStubsGenerator import org.jetbrains.index.stubs.ProjectSdkStubsGenerator import org.jetbrains.index.stubs.mergeStubs import org.junit.Assert import java.io.File /** * @author traff */ val stubsFileName = SDK_STUBS_STORAGE_NAME val MERGE_STUBS_FROM_PATHS = "MERGE_STUBS_FROM_PATHS" fun getBaseDirValue(): String? { val path: String? = System.getProperty(PREBUILT_INDEXES_PATH_PROPERTY) if (path == null) { Assert.fail("$PREBUILT_INDEXES_PATH_PROPERTY variable is not defined") } else if (File(path).exists()) { return path } else { Assert.fail("Directory $path doesn't exist") } return null } val stubsVersion = PyFileElementType.INSTANCE.stubVersion.toString() fun main(args: Array<String>) { val baseDir = getBaseDirValue() if (System.getenv().containsKey(MERGE_STUBS_FROM_PATHS)) { mergeStubs(System.getenv(MERGE_STUBS_FROM_PATHS).split(File.pathSeparatorChar), "$baseDir", stubsFileName, "${PathManager.getHomePath()}/python/testData/empty", stubsVersion) } else { PyProjectSdkStubsGenerator().buildStubs(baseDir!!) } } class PyProjectSdkStubsGenerator : ProjectSdkStubsGenerator() { override val moduleTypeId: String get() = PythonModuleTypeBase.PYTHON_MODULE override fun createSdkProducer(sdkPath: String) = createPythonSdkProducer(sdkPath) override fun createStubsGenerator() = PyStubsGenerator(stubsVersion) override val root: String? get() = System.getenv(PYCHARM_PYTHONS) } class PyStubsGenerator(stubsVersion: String) : LanguageLevelAwareStubsGenerator<LanguageLevel>(stubsVersion) { override fun defaultLanguageLevel(): LanguageLevel = LanguageLevel.getDefault() override fun languageLevelIterator() = LanguageLevel.SUPPORTED_LEVELS.iterator() override fun applyLanguageLevel(level: LanguageLevel) { LanguageLevel.FORCE_LANGUAGE_LEVEL = level } override val fileFilter: VirtualFileFilter get() = VirtualFileFilter { file: VirtualFile -> if (file.isDirectory && file.name == "parts") throw NoSuchElementException() else file.fileType == PythonFileType.INSTANCE } }
apache-2.0
fc21dd7a09285dca5246d75bc593a733
28.148936
110
0.768248
4.208909
false
false
false
false
dmcg/konsent
src/main/java/com/oneeyedmen/konsent/FeatureRule.kt
1
1760
package com.oneeyedmen.konsent import com.oneeyedmen.konsent.okeydoke.TranscriptFeatureRecorder import com.oneeyedmen.okeydoke.Name import com.oneeyedmen.okeydoke.junit.ApprovalsRule import org.junit.rules.TestWatcher import org.junit.runner.Description class FeatureRule(private val approvalsRule: ApprovalsRule) : TestWatcher() { lateinit var recorder: FeatureRecorder override fun starting(description: Description) { approvalsRule.starting(description) recorder = TranscriptFeatureRecorder(approvalsRule.transcript()) recorder.featureStart(featureNameFrom(description), *preambleFor(description.testClass)) injectRecorder(description.testClass, null, recorder) } private fun preambleFor(testClass: Class<*>): Array<String> { val preamble = testClass.getAnnotation(Preamble::class.java) return if (preamble != null) listOf(preamble.p1, preamble.p2, preamble.p3).filter { it.isNotBlank() }.toTypedArray() else emptyArray() } override fun succeeded(description: Description) { approvalsRule.succeeded(description) } } internal fun <T> injectRecorder(clazz: Class<T>, target: T?, recorder: FeatureRecorder) { clazz.fields.filter { it.type == FeatureRecorder::class.java }.forEach { it.set(target, recorder) } } private val spaceOutCamelCase = Regex("(\\p{Ll})(\\p{Lu})") private fun String.`space Out Camel Case`() = this.replace(spaceOutCamelCase, "$1 $2") private fun featureNameFrom(description: Description) = nameFromClassAnnotation(description) ?: description.testClass.simpleName.`space Out Camel Case`() private fun nameFromClassAnnotation(description: Description): String? = description.testClass?.getAnnotation(Name::class.java)?.value
apache-2.0
ee43bd8efe971f64bee60d7c2c3a9fa1
40.928571
124
0.752273
4.064665
false
true
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/course_list/ui/activity/CourseListQueryActivity.kt
1
1499
package org.stepik.android.view.course_list.ui.activity import android.content.Context import android.content.Intent import android.os.Parcelable import android.view.MenuItem import androidx.fragment.app.Fragment import org.stepic.droid.base.SingleFragmentActivity import org.stepik.android.domain.course_list.model.CourseListQuery import org.stepik.android.view.course_list.ui.fragment.CourseListQueryFragment class CourseListQueryActivity : SingleFragmentActivity() { companion object { private const val EXTRA_COURSE_LIST_TITLE = "course_list_title" private const val EXTRA_COURSE_LIST_QUERY = "course_list_query" fun createIntent(context: Context, courseListTitle: String, courseListQuery: CourseListQuery): Intent = Intent(context, CourseListQueryActivity::class.java) .putExtra(EXTRA_COURSE_LIST_TITLE, courseListTitle) .putExtra(EXTRA_COURSE_LIST_QUERY, courseListQuery as Parcelable) } override fun createFragment(): Fragment = CourseListQueryFragment.newInstance( courseListTitle = requireNotNull(intent.getStringExtra(EXTRA_COURSE_LIST_TITLE)), courseListQuery = requireNotNull(intent.getParcelableExtra(EXTRA_COURSE_LIST_QUERY)) ) override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } }
apache-2.0
dc1ce80c62308e0b3d960bfd03e55b0f
40.666667
111
0.730487
4.773885
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRToolWindowFactory.kt
1
2984
// 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 import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.EmptyAction import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.impl.content.ToolWindowContentUi import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.pullrequest.action.GHPRSelectPullRequestForFileAction import org.jetbrains.plugins.github.pullrequest.action.GHPRSwitchRemoteAction import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContextRepository import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRToolWindowTabController import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRToolWindowTabControllerImpl import org.jetbrains.plugins.github.util.GHProjectRepositoriesManager import javax.swing.JPanel class GHPRToolWindowFactory : ToolWindowFactory, DumbAware { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) = with(toolWindow as ToolWindowEx) { setTitleActions(listOf(GHPRSelectPullRequestForFileAction(), EmptyAction.registerWithShortcutSet("Github.Create.Pull.Request", CommonShortcuts.getNew(), component))) setAdditionalGearActions(DefaultActionGroup(GHPRSwitchRemoteAction())) component.putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true") with(contentManager) { addContent(factory.createContent(JPanel(null), null, false).apply { isCloseable = false setDisposer(Disposer.newDisposable("GHPR tab disposable")) }.also { val authManager = GithubAuthenticationManager.getInstance() val repositoryManager = project.service<GHProjectRepositoriesManager>() val dataContextRepository = GHPRDataContextRepository.getInstance(project) val projectString = GithubPullRequestsProjectUISettings.getInstance(project) it.putUserData(GHPRToolWindowTabController.KEY, GHPRToolWindowTabControllerImpl(project, authManager, repositoryManager, dataContextRepository, projectString, it)) }) } } override fun shouldBeAvailable(project: Project): Boolean = invokeAndWaitIfNeeded { project.service<GHPRToolWindowController>().isAvailable() } companion object { const val ID = "Pull Requests" } }
apache-2.0
25c573f142617e2bf8c96f1f2af39c44
53.272727
140
0.812332
5.135972
false
false
false
false
allotria/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/types/SharedVariableInferenceCache.kt
3
6567
// 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.groovy.lang.psi.dataFlow.types import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction import org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ResolvedVariableDescriptor import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.getControlFlowOwner import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.isNestedFlowProcessingAllowed import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic import java.util.concurrent.atomic.AtomicReferenceArray /** * A variable is considered `shared` if it satisfies the following conditions: * 1) It is under @CompileStatic. * 2) It is local variable. * 3) It has multiple assignments. * 4) There exists an inner closure/lambda where this variable is used. * * Type of shared variable is a LUB of all its initializer types. * * Static compiler in Groovy performs two phases of type checking: * First pass: type of every variable determined according to the rules of flow typing. * Second pass: type of every shared variable is recalculated using flow typing results. */ class SharedVariableInferenceCache(val scope: GrControlFlowOwner) { val sharedVariableDescriptors: Set<VariableDescriptor> private val writeInstructions: List<Pair<ReadWriteVariableInstruction, GrControlFlowOwner>> init { val mergedInnerFlows: List<Pair<ReadWriteVariableInstruction, GrControlFlowOwner>> = mergeInnerFlows(scope) .mapNotNull { (instruction, owner) -> (instruction as? ReadWriteVariableInstruction)?.takeIf { instruction.isWrite }?.run { instruction to owner } } sharedVariableDescriptors = doGetSharedVariables(mergedInnerFlows.map(Pair<ReadWriteVariableInstruction, GrControlFlowOwner>::first)) writeInstructions = mergedInnerFlows.filter { pair -> pair.first.descriptor in sharedVariableDescriptors } } private val finalTypes: AtomicReferenceArray<PsiType?> = AtomicReferenceArray(sharedVariableDescriptors.size) fun getSharedVariableType(descriptor: VariableDescriptor): PsiType? { if (!isNestedFlowProcessingAllowed()) { return null } if (descriptor !in sharedVariableDescriptors) { return null } val indexInFinalTypes: Int = sharedVariableDescriptors.indexOf(descriptor) val finalType = finalTypes.get(indexInFinalTypes) if (finalType == null) { runSharedVariableInferencePhase() return finalTypes.get(indexInFinalTypes) } else { return finalType } } /** * Sequentially tries to compute all intermediate types for every shared variable. * The result type of a shared variable is considered to be a LUB of all its intermediate types. * * This method is not supposed to be reentrant. * If DFA would have to query the type of shared variable, then DFA will be self-invoked with a nested context. * Such behavior is consistent with @CompileStatic approach: all variables inside DFA should see the type that was achieved via flow typing. * @see DFAFlowInfo.dependentOnSharedVariables */ private fun runSharedVariableInferencePhase() { val flowTypes: Array<PsiType?> = Array(writeInstructions.size) { null } for (index: Int in writeInstructions.indices) { val (instruction: ReadWriteVariableInstruction, scope : GrControlFlowOwner) = writeInstructions[index] val inferenceCache = TypeInferenceHelper.getInferenceCache(scope) val inferredType: PsiType? = inferenceCache.getInferredType(instruction.descriptor, instruction, false) ?: PsiType.NULL flowTypes[index] = inferredType } for (variable: VariableDescriptor in sharedVariableDescriptors) { val indexInFinalTypes: Int = sharedVariableDescriptors.indexOf(variable) val inferredTypesForVariable: List<PsiType?> = writeInstructions .mapIndexedNotNull { index, pair -> flowTypes[index]?.takeIf { pair.first.descriptor == variable } } val finalType: PsiType = TypesUtil.getLeastUpperBoundNullable(inferredTypesForVariable, scope.manager) ?: PsiType.NULL if (!finalTypes.compareAndSet(indexInFinalTypes, null, finalType)) { val actualFinalType = finalTypes.get(indexInFinalTypes) assert(finalType == actualFinalType) { "Incompatible types detected during final type computation for shared variable: found $actualFinalType while inferred $finalType" } } } } @Suppress("UnnecessaryVariable") private fun doGetSharedVariables(mergedInnerFlows: List<ReadWriteVariableInstruction>): Set<VariableDescriptor> { if (!isCompileStatic(scope)) { return emptySet() } val flow = scope.controlFlow val foreignDescriptors: List<ResolvedVariableDescriptor> = flow .mapNotNull { (it?.element as? GrFunctionalExpression)?.getControlFlowOwner() } .flatMap { ControlFlowUtils.getForeignVariableDescriptors(it) } val sharedVariables: Set<VariableDescriptor> = flow .asSequence() .filterIsInstance<ReadWriteVariableInstruction>() .mapNotNull { instruction -> instruction.descriptor.takeIf { it in foreignDescriptors } as? ResolvedVariableDescriptor } // fields have their own inference rules .filter { it.variable !is GrField } // do not bother to process variable if it was assigned only once .filter { descriptor -> mergedInnerFlows.count { it.descriptor == descriptor } >= 2 } .toSet() return sharedVariables } companion object { private fun mergeInnerFlows(owner: GrControlFlowOwner): List<Pair<Instruction, GrControlFlowOwner>> { return owner.controlFlow.flatMap { val element = it.element if (it !is ReadWriteVariableInstruction && element is GrControlFlowOwner) { mergeInnerFlows(element) } else { listOf<Pair<Instruction, GrControlFlowOwner>>(it to owner) } } } } }
apache-2.0
03488b8fe71f99b33af974929b84ddf1
47.651852
142
0.756967
4.640989
false
false
false
false
RichoDemus/chronicler
server/persistence/google-cloud-storage/src/main/kotlin/com/richodemus/chronicler/persistence/gcs/GoogleCloudStoragePersistence.kt
1
4096
package com.richodemus.chronicler.persistence.gcs import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import com.google.cloud.storage.BlobId import com.google.cloud.storage.BlobInfo import com.google.cloud.storage.StorageOptions import com.richodemus.chronicler.server.core.Event import com.richodemus.chronicler.server.core.EventPersister import org.slf4j.LoggerFactory import java.util.concurrent.CompletableFuture import java.util.concurrent.Executors import java.util.concurrent.atomic.LongAdder import java.util.function.Supplier import javax.inject.Singleton @Singleton class GoogleCloudStoragePersistence : EventPersister { private val logger = LoggerFactory.getLogger(javaClass) private val project = System.getProperty("chronicler.gcs.project") ?: throw IllegalArgumentException("Missing property GCS_PROJECT/chronicler.gcs.project") private val bucket = System.getProperty("chronicler.gcs.bucket") ?: throw IllegalArgumentException("Missing property GCS_BUCKET/chronicler.gcs.bucket") private val directory = "events/v1/" private val mapper = ObjectMapper().apply { registerModule(KotlinModule()) } private val service = StorageOptions.newBuilder() .setProjectId(project) .build() .service override fun getNumberOfEvents(): Int { return service.list(bucket) .iterateAll().count() } override fun readEvents(): Iterator<Event> { val executor = Executors.newCachedThreadPool() var run = true val eventsStarted = LongAdder() val eventsDownloaded = LongAdder() try { logger.info("Preparing to download events from Google Cloud Storage...") Thread(Runnable { while (run) { if(eventsStarted.sum() > 0 || eventsDownloaded.sum() > 0) logger.info("Event downloads started: ${eventsStarted.sum()}, Events downloaded: ${eventsDownloaded.sum()}") Thread.sleep(1_000L) } }).start() return service.list(bucket) .iterateAll() .filter { it.blobId.name.startsWith(directory) } .map { eventsStarted.increment() CompletableFuture.supplyAsync(Supplier { it.getContent() .let { String(it) } .toDto() .toEvent() }, executor) } .map { eventsDownloaded.increment() it.get() } .sortedBy { it.page } .iterator() } finally { run = false executor.shutdown() } } override fun persist(event: Event) { service.create(BlobInfo.newBuilder(BlobId.of(bucket, "$directory${event.page.toString()}")).build(), event.toDto().toJSONString().toByteArray()) } private data class EventDTO @JsonCreator constructor(@JsonProperty("id") val id: String, @JsonProperty("type") val type: String, @JsonProperty("page") val page: Long, @JsonProperty("data") val data: String) private fun Event.toDto(): EventDTO { val page = this.page ?: throw IllegalStateException("Can't save event without page") return EventDTO(this.id, this.type, page, this.data) } private fun GoogleCloudStoragePersistence.EventDTO.toEvent() = com.richodemus.chronicler.server.core.Event(this.id, this.type, this.page, this.data) private fun GoogleCloudStoragePersistence.EventDTO.toJSONString() = mapper.writeValueAsString(this) private fun String.toDto() = mapper.readValue(this, EventDTO::class.java) }
gpl-3.0
7d4c7c22909ce8f0dad2d458ec0712a5
39.96
159
0.617188
4.970874
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/IncomingChangesIndicator.kt
1
3904
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.committed import com.intellij.icons.AllIcons import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.IconLoader.getDisabledIcon import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED_IN_PLUGIN import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsListener import com.intellij.openapi.vcs.changes.committed.CommittedChangesCache.COMMITTED_TOPIC import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.INCOMING import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList import com.intellij.openapi.wm.StatusBar import com.intellij.openapi.wm.StatusBarWidget import com.intellij.openapi.wm.StatusBarWidget.WidgetPresentation import com.intellij.openapi.wm.StatusBarWidgetProvider import com.intellij.openapi.wm.ToolWindowManager import com.intellij.util.Consumer import java.awt.event.MouseEvent import javax.swing.Icon import kotlin.properties.Delegates.observable private val LOG = logger<IncomingChangesIndicator>() class IncomingChangesIndicatorProvider : StatusBarWidgetProvider { override fun getWidget(project: Project): StatusBarWidget = IncomingChangesIndicator(project) } private class IncomingChangesIndicator(private val project: Project) : StatusBarWidget, StatusBarWidget.IconPresentation { private var statusBar: StatusBar? = null private var isIncomingChangesAvailable = false private var incomingChangesCount: Int by observable(0) { _, _, newValue -> LOG.debug("Refreshing indicator: $newValue changes") statusBar?.updateWidget(ID()) } override fun ID(): String = "IncomingChanges" override fun getPresentation(): WidgetPresentation = this override fun getIcon(): Icon? { if (!isIncomingChangesAvailable) return null // hide widget return if (incomingChangesCount > 0) AllIcons.Ide.IncomingChangesOn else getDisabledIcon(AllIcons.Ide.IncomingChangesOn) } override fun getTooltipText(): String? { if (!isIncomingChangesAvailable) return null return if (incomingChangesCount > 0) message("incoming.changes.indicator.tooltip", incomingChangesCount) else "No incoming changelists available" } override fun getClickConsumer(): Consumer<MouseEvent> = Consumer { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) toolWindow?.show { ChangesViewContentManager.getInstance(project).selectContent(INCOMING) } } override fun install(statusBar: StatusBar) { this.statusBar = statusBar project.messageBus.connect(this).apply { subscribe(COMMITTED_TOPIC, object : CommittedChangesListener { override fun incomingChangesUpdated(receivedChanges: List<CommittedChangeList>?) = refresh() override fun changesCleared() = refresh() }) subscribe(VCS_CONFIGURATION_CHANGED, VcsListener { refresh() }) subscribe(VCS_CONFIGURATION_CHANGED_IN_PLUGIN, VcsListener { refresh() }) } } override fun dispose() { statusBar = null } private fun refresh() = runInEdt { if (project.isDisposed || statusBar == null) return@runInEdt isIncomingChangesAvailable = IncomingChangesViewProvider.VisibilityPredicate().`fun`(project) incomingChangesCount = if (isIncomingChangesAvailable) getCachedIncomingChangesCount() else 0 } private fun getCachedIncomingChangesCount() = CommittedChangesCache.getInstance(project).cachedIncomingChanges?.size ?: 0 }
apache-2.0
977009a5ffedfb0cb165c282043ca442
41.912088
140
0.793801
4.737864
false
false
false
false
leafclick/intellij-community
platform/credential-store/src/macOsKeychainLibrary.kt
1
10359
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.credentialStore import com.intellij.openapi.util.SystemInfo import com.intellij.util.ArrayUtilRt import com.intellij.util.text.nullize import com.sun.jna.* import com.sun.jna.ptr.IntByReference import com.sun.jna.ptr.PointerByReference import gnu.trove.TIntObjectHashMap val isMacOsCredentialStoreSupported: Boolean get() = SystemInfo.isMacIntel64 && SystemInfo.isMacOSLeopard private const val errSecSuccess = 0 private const val errSecItemNotFound = -25300 private const val errSecInvalidRecord = -67701 // or if Deny clicked on access dialog private const val errUserNameNotCorrect = -25293 // https://developer.apple.com/documentation/security/1542001-security_framework_result_codes/errsecusercanceled?language=objc private const val errSecUserCanceled = -128 private const val kSecFormatUnknown = 0 private const val kSecAccountItemAttr = (('a'.toInt() shl 8 or 'c'.toInt()) shl 8 or 'c'.toInt()) shl 8 or 't'.toInt() internal class KeyChainCredentialStore : CredentialStore { companion object { private val library = Native.load("Security", MacOsKeychainLibrary::class.java) private fun findGenericPassword(serviceName: ByteArray, accountName: String?): Credentials? { val accountNameBytes = accountName?.toByteArray() val passwordSize = IntArray(1) val passwordRef = PointerByReference() val itemRef = PointerByReference() val errorCode = checkForError("find", library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes?.size ?: 0, accountNameBytes, passwordSize, passwordRef, itemRef)) if (errorCode == errSecUserCanceled) { return ACCESS_TO_KEY_CHAIN_DENIED } if (errorCode == errUserNameNotCorrect) { return CANNOT_UNLOCK_KEYCHAIN } val pointer = passwordRef.value ?: return null val password = OneTimeString(pointer.getByteArray(0, passwordSize.get(0))) library.SecKeychainItemFreeContent(null, pointer) var effectiveAccountName = accountName if (effectiveAccountName == null) { val attributes = PointerByReference() checkForError("SecKeychainItemCopyAttributesAndData", library.SecKeychainItemCopyAttributesAndData(itemRef.value!!, SecKeychainAttributeInfo(kSecAccountItemAttr), null, attributes, null, null)) val attributeList = SecKeychainAttributeList(attributes.value) try { attributeList.read() effectiveAccountName = readAttributes(attributeList).get(kSecAccountItemAttr) } finally { library.SecKeychainItemFreeAttributesAndData(attributeList, null) } } return Credentials(effectiveAccountName, password) } private fun checkForError(message: String, code: Int): Int { if (code == errSecSuccess || code == errSecItemNotFound) { return code } val translated = library.SecCopyErrorMessageString(code, null) val builder = StringBuilder(message).append(": ") if (translated == null) { builder.append(code) } else { val buf = CharArray(library.CFStringGetLength(translated).toInt()) for (i in 0 until buf.size) { buf[i] = library.CFStringGetCharacterAtIndex(translated, i.toLong()) } library.CFRelease(translated) builder.append(buf).append(" (").append(code).append(')') } if (code == errUserNameNotCorrect || code == errSecUserCanceled || code == -25299 /* The specified item already exists in the keychain */) { LOG.warn(builder.toString()) } else { LOG.error(builder.toString()) } return code } } override fun get(attributes: CredentialAttributes): Credentials? { return findGenericPassword(attributes.serviceName.toByteArray(), attributes.userName.nullize()) } override fun set(attributes: CredentialAttributes, credentials: Credentials?) { val serviceName = attributes.serviceName.toByteArray() if (credentials.isEmpty()) { val itemRef = PointerByReference() val userName = attributes.userName.nullize()?.toByteArray() val code = library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, null, null, itemRef) if (code == errSecItemNotFound || code == errSecInvalidRecord) { return } checkForError("find (for delete)", code) itemRef.value?.let { checkForError("delete", library.SecKeychainItemDelete(it)) library.CFRelease(it) } return } val userName = (attributes.userName.nullize() ?: credentials!!.userName)?.toByteArray() val searchUserName = if (attributes.serviceName == SERVICE_NAME_PREFIX) userName else null val itemRef = PointerByReference() val library = library checkForError("find (for save)", library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, searchUserName?.size ?: 0, searchUserName, null, null, itemRef)) val password = if (attributes.isPasswordMemoryOnly || credentials!!.password == null) null else credentials.password!!.toByteArray(false) val pointer = itemRef.value if (pointer == null) { checkForError("save (new)", library.SecKeychainAddGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, password?.size ?: 0, password)) } else { val attribute = SecKeychainAttribute() attribute.tag = kSecAccountItemAttr attribute.length = userName?.size ?: 0 if (userName != null && userName.isNotEmpty()) { val userNamePointer = Memory(userName.size.toLong()) userNamePointer.write(0, userName, 0, userName.size) attribute.data = userNamePointer } val attributeList = SecKeychainAttributeList() attributeList.count = 1 attribute.write() attributeList.attr = attribute.pointer checkForError("save (update)", library.SecKeychainItemModifyContent(pointer, attributeList, password?.size ?: 0, password ?: ArrayUtilRt.EMPTY_BYTE_ARRAY)) library.CFRelease(pointer) } password?.fill(0) } } // https://developer.apple.com/library/mac/documentation/Security/Reference/keychainservices/index.html // It is very, very important to use CFRelease/SecKeychainItemFreeContent You must do it, otherwise you can get "An invalid record was encountered." @Suppress("FunctionName") private interface MacOsKeychainLibrary : Library { fun SecKeychainAddGenericPassword(keychain: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray?, passwordLength: Int, passwordData: ByteArray?, itemRef: Pointer? = null): Int fun SecKeychainItemModifyContent(itemRef: Pointer, /*SecKeychainAttributeList**/ attrList: Any?, length: Int, data: ByteArray?): Int fun SecKeychainFindGenericPassword(keychainOrArray: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray?, passwordLength: IntArray?, passwordData: PointerByReference?, itemRef: PointerByReference?): Int fun SecKeychainItemCopyAttributesAndData(itemRef: Pointer, info: SecKeychainAttributeInfo, itemClass: IntByReference?, attrList: PointerByReference, length: IntByReference?, outData: PointerByReference?): Int fun SecKeychainItemFreeAttributesAndData(attrList: SecKeychainAttributeList, data: Pointer?): Int fun SecKeychainItemDelete(itemRef: Pointer): Int fun /*CFString*/ SecCopyErrorMessageString(status: Int, reserved: Pointer?): Pointer? // http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html fun /*CFIndex*/ CFStringGetLength(/*CFStringRef*/ theString: Pointer): Long fun /*UniChar*/ CFStringGetCharacterAtIndex(/*CFStringRef*/ theString: Pointer, /*CFIndex*/ idx: Long): Char fun CFRelease(/*CFTypeRef*/ cf: Pointer) fun SecKeychainItemFreeContent(/*SecKeychainAttributeList*/attrList: Pointer?, data: Pointer?) } // must be not private @Structure.FieldOrder("count", "tag", "format") internal class SecKeychainAttributeInfo : Structure() { @JvmField var count: Int = 0 @JvmField var tag: Pointer? = null @JvmField var format: Pointer? = null } @Suppress("FunctionName") private fun SecKeychainAttributeInfo(vararg ids: Int): SecKeychainAttributeInfo { val info = SecKeychainAttributeInfo() val length = ids.size info.count = length val size = length shl 2 val tag = Memory((size shl 1).toLong()) val format = tag.share(size.toLong(), size.toLong()) info.tag = tag info.format = format var offset = 0 for (id in ids) { tag.setInt(offset.toLong(), id) format.setInt(offset.toLong(), kSecFormatUnknown) offset += 4 } return info } // must be not private @Structure.FieldOrder("count", "attr") internal class SecKeychainAttributeList : Structure { @JvmField var count = 0 @JvmField var attr: Pointer? = null constructor(p: Pointer) : super(p) constructor() : super() } // must be not private @Structure.FieldOrder("tag", "length", "data") internal class SecKeychainAttribute : Structure, Structure.ByReference { @JvmField var tag = 0 @JvmField var length = 0 @JvmField var data: Pointer? = null internal constructor(p: Pointer) : super(p) internal constructor() : super() } private fun readAttributes(list: SecKeychainAttributeList): TIntObjectHashMap<String> { val map = TIntObjectHashMap<String>() val attrList = SecKeychainAttribute(list.attr!!) attrList.read() @Suppress("UNCHECKED_CAST") for (attr in attrList.toArray(list.count) as Array<SecKeychainAttribute>) { val data = attr.data ?: continue map.put(attr.tag, String(data.getByteArray(0, attr.length))) } return map }
apache-2.0
2bc5ddf12e23ca5094cab1ee69397bcf
41.113821
230
0.692827
4.47473
false
false
false
false
zdary/intellij-community
platform/statistics/devkit/src/com/intellij/internal/statistic/toolwindow/StatisticsEventLogConsole.kt
3
2900
// 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 com.intellij.internal.statistic.toolwindow import com.intellij.diagnostic.logging.LogConsoleBase import com.intellij.diagnostic.logging.LogFilterModel import com.intellij.internal.statistic.actions.OpenEventsSchemeFileAction.Companion.getEventsSchemeFile import com.intellij.json.JsonLanguage import com.intellij.json.psi.JsonArray import com.intellij.json.psi.JsonObject import com.intellij.json.psi.JsonProperty import com.intellij.json.psi.JsonStringLiteral import com.intellij.json.psi.impl.JsonRecursiveElementVisitor import com.intellij.openapi.application.ReadAction import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindowManager import com.intellij.psi.PsiManager import com.intellij.refactoring.suggested.startOffset internal class StatisticsEventLogConsole(private val project: Project, model: LogFilterModel, recorderId: String) : LogConsoleBase(project, null, eventLogToolWindowsId, false, model) { init { val schemeFile = LocalFileSystem.getInstance().findFileByNioFile(getEventsSchemeFile(recorderId)) if (schemeFile != null) { val groupIdToLine = ReadAction.compute<HashMap<String, Int>, Throwable> { computeLineNumbers(schemeFile) } if (groupIdToLine != null && groupIdToLine.isNotEmpty()) { console?.addMessageFilter(StatisticsEventLogFilter(schemeFile, groupIdToLine)) } } } private fun computeLineNumbers(schemeFile: VirtualFile): HashMap<String, Int>? { val groupIdToLine = HashMap<String, Int>() val document = FileDocumentManager.getInstance().getDocument(schemeFile) ?: return null val psiFile = PsiManager.getInstance(project).findFile(schemeFile) ?: return null if (psiFile.language == JsonLanguage.INSTANCE) { psiFile.accept(object : JsonRecursiveElementVisitor() { override fun visitProperty(property: JsonProperty) { if (property.name != "groups") return val groups = property.value as? JsonArray ?: return for (groupElement in groups.valueList) { val groupObject = groupElement as JsonObject val idProperty = groupObject.findProperty("id") ?: continue val id = (idProperty.value as? JsonStringLiteral)?.value ?: continue groupIdToLine[id] = document.getLineNumber(idProperty.startOffset) } } }) } return groupIdToLine } override fun isActive(): Boolean { return ToolWindowManager.getInstance(project).getToolWindow(eventLogToolWindowsId)?.isVisible ?: false } fun addLogLine(line: String) { super.addMessage(line) } }
apache-2.0
1d84019f9247309ab18e42241cbb687e
43.630769
140
0.757586
4.59588
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/capabilities/inventory/SidedItemHandlerConfig.kt
1
4381
package net.ndrei.teslacorelib.capabilities.inventory import com.google.common.collect.Lists import net.minecraft.item.EnumDyeColor import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagInt import net.minecraft.nbt.NBTTagList import net.minecraft.util.EnumFacing import net.minecraftforge.common.util.Constants import net.minecraftforge.common.util.INBTSerializable import net.ndrei.teslacorelib.inventory.BoundingRectangle import net.ndrei.teslacorelib.inventory.ColoredItemHandlerInfo /** * Created by CF on 2017-06-28. */ open class SidedItemHandlerConfig : ISidedItemHandlerConfig, INBTSerializable<NBTTagList> { private val facesConfig = hashMapOf<EnumDyeColor, MutableList<EnumFacing>>() private var information = mutableListOf<ColoredItemHandlerInfo>() override fun isSideSet(color: EnumDyeColor, side: EnumFacing): Boolean { if (this.facesConfig.containsKey(color)) { val list = this.facesConfig[color] if ((list != null) && list.contains(side)) { return true } } return false } fun toggleSide(color: EnumDyeColor, side: EnumFacing): Boolean { if (this.facesConfig.containsKey(color)) { val list = this.facesConfig[color] if (list != null && list.contains(side)) { list.remove(side) } else if (list != null) { list.add(side) } else /*if (list == null)*/ { this.setSidesForColor(color, Lists.newArrayList(side)) } } else { this.setSidesForColor(color, Lists.newArrayList(side)) } this.updated() return this.isSideSet(color, side) } override val coloredInfo: List<ColoredItemHandlerInfo> get() = this.information .toList() .filter { !it.highlight.isEmpty } .sortedBy { it.index } override fun addColoredInfo(name: String, color: EnumDyeColor, highlight: BoundingRectangle) { this.addColoredInfo(name, color, highlight, (this.information.map { it.index }.max() ?: 0) + 10) } override fun addColoredInfo(name: String, color: EnumDyeColor, highlight: BoundingRectangle, index: Int) { this.addColoredInfo(ColoredItemHandlerInfo(name, color, highlight, index)) } override fun addColoredInfo(info: ColoredItemHandlerInfo) { this.information.add(info) } override fun getSidesForColor(color: EnumDyeColor) = if (this.facesConfig.containsKey(color)) { this.facesConfig[color] ?: listOf() } else { listOf<EnumFacing>() } override fun setSidesForColor(color: EnumDyeColor, sides: List<EnumFacing>) { this.facesConfig.put(color, sides.toMutableList()) this.updated() } override fun serializeNBT(): NBTTagList { val list = NBTTagList() val keys = this.facesConfig.keys.toTypedArray() for (k in keys.indices) { val nbt = NBTTagCompound() nbt.setInteger("color", keys[k].metadata) val sides = NBTTagList() for (facing in this.facesConfig[keys[k]]!!) { sides.appendTag(NBTTagInt(facing.index)) } nbt.setTag("sides", sides) list.appendTag(nbt) } return list } override fun deserializeNBT(nbt: NBTTagList) { this.facesConfig.clear() for (i in 0 until nbt.tagCount()) { val item = nbt.getCompoundTagAt(i) val color = EnumDyeColor.byMetadata(item.getInteger("color")) val sides = Lists.newArrayList<EnumFacing>() val list = item.getTagList("sides", Constants.NBT.TAG_INT) (0 until list.tagCount()) .mapTo(sides) { EnumFacing.byIndex(list.getIntAt(it)) } this.facesConfig.put(color, sides) } this.updated() } protected open fun updated() {} override fun removeColoredInfo(color: EnumDyeColor) { this.information.removeIf { i -> i.color == color } this.facesConfig.remove(color) this.updated() } fun setColorIndex(color: EnumDyeColor, index: Int) { this.information.forEach { if (it.color == color) { it.index = index } } } }
mit
6eafe118e20410053c2f615c5811371a
32.96124
110
0.61995
4.385385
false
true
false
false
JuliusKunze/kotlin-native
runtime/src/main/kotlin/kotlin/internal/progressionUtil.kt
2
3113
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlin.internal // a mod b (in arithmetical sense) private fun mod(a: Int, b: Int): Int { val mod = a % b return if (mod >= 0) mod else mod + b } private fun mod(a: Long, b: Long): Long { val mod = a % b return if (mod >= 0) mod else mod + b } // (a - b) mod c private fun differenceModulo(a: Int, b: Int, c: Int): Int { return mod(mod(a, c) - mod(b, c), c) } private fun differenceModulo(a: Long, b: Long, c: Long): Long { return mod(mod(a, c) - mod(b, c), c) } /** * Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range * from [start] to [end] in case of a positive [step], or from [end] to [start] in case of a negative * [step]. * * No validation on passed parameters is performed. The given parameters should satisfy the condition: either * `step > 0` and `start >= end`, or `step < 0` and`start >= end`. * @param start first element of the progression * @param end ending bound for the progression * @param step increment, or difference of successive elements in the progression * @return the final element of the progression * @suppress */ internal fun getProgressionLastElement(start: Int, end: Int, step: Int): Int { if (step > 0) { return end - differenceModulo(end, start, step) } else if (step < 0) { return end + differenceModulo(start, end, -step) } else { throw kotlin.IllegalArgumentException("Step is zero.") } } /** * Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range * from [start] to [end] in case of a positive [step], or from [end] to [start] in case of a negative * [step]. * * No validation on passed parameters is performed. The given parameters should satisfy the condition: either * `step > 0` and `start >= end`, or `step < 0` and`start >= end`. * @param start first element of the progression * @param end ending bound for the progression * @param step increment, or difference of successive elements in the progression * @return the final element of the progression * @suppress */ internal fun getProgressionLastElement(start: Long, end: Long, step: Long): Long { if (step > 0) { return end - differenceModulo(end, start, step) } else if (step < 0) { return end + differenceModulo(start, end, -step) } else { throw kotlin.IllegalArgumentException("Step is zero.") } }
apache-2.0
14d45dce5b7078f5f3d6c0258b4c7d48
34.781609
131
0.678766
3.705952
false
false
false
false
FirebaseExtended/mlkit-material-android
app/src/main/java/com/google/firebase/ml/md/kotlin/objectdetection/ObjectDotGraphic.kt
1
2005
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.ml.md.kotlin.objectdetection import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Paint.Style import android.graphics.PointF import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay.Graphic import com.google.firebase.ml.md.R /** A dot to indicate a detected object used by multiple objects detection mode. */ internal class ObjectDotGraphic( overlay: GraphicOverlay, detectedObject: DetectedObject, private val animator: ObjectDotAnimator ) : Graphic(overlay) { private val paint: Paint private val center: PointF private val dotRadius: Int private val dotAlpha: Int init { val box = detectedObject.boundingBox center = PointF( overlay.translateX((box.left + box.right) / 2f), overlay.translateY((box.top + box.bottom) / 2f) ) paint = Paint().apply { style = Style.FILL color = Color.WHITE } dotRadius = context.resources.getDimensionPixelOffset(R.dimen.object_dot_radius) dotAlpha = paint.alpha } override fun draw(canvas: Canvas) { paint.alpha = (dotAlpha * animator.alphaScale).toInt() canvas.drawCircle(center.x, center.y, dotRadius * animator.radiusScale, paint) } }
apache-2.0
7b343ab8e015d52c10f578b58567f6d4
32.416667
88
0.707232
4.221053
false
false
false
false
Flank/flank
test_runner/src/test/kotlin/ftl/environment/android/AndroidModelDescriptionTest.kt
1
3504
package ftl.environment.android import ftl.api.DeviceModel import ftl.presentation.cli.firebase.test.android.models.describe.prepareDescription import org.junit.Assert.assertEquals import org.junit.Test class AndroidModelDescriptionTest { @Test fun `should return model with tag if any tag exists`() { val models = listOf( DeviceModel.Android( id = "walleye", codename = "walleye", brand = "Google", form = "PHYSICAL", formFactor = "PHONE", manufacturer = "Google", name = "Pixel 2", screenDensity = 420, screenX = 1080, screenY = 1920, supportedAbis = listOf("arm64-v8a", "armeabi-v7a", "armeabi"), supportedVersionIds = listOf("26", "27", "28"), thumbnailUrl = "https://lh3.googleusercontent.com/j4urvb3lXTaFGZI6IzHmAjum2HQVID1OHPhDB7dOzRvXb2WscSX2RFwEEFFSYhajqRO5Yu0e6FYQ", tags = listOf("default"), lowFpsVideoRecording = true ) ) val modelDescription = models.find { it.id == "walleye" }?.prepareDescription() val expected = """ brand: Google codename: walleye form: PHYSICAL formFactor: PHONE id: walleye manufacturer: Google name: Pixel 2 screenDensity: 420 screenX: 1080 screenY: 1920 supportedAbis: - arm64-v8a - armeabi-v7a - armeabi supportedVersionIds: - 26 - 27 - 28 tags: - default thumbnailUrl: https://lh3.googleusercontent.com/j4urvb3lXTaFGZI6IzHmAjum2HQVID1OHPhDB7dOzRvXb2WscSX2RFwEEFFSYhajqRO5Yu0e6FYQ """.trimIndent() assertEquals(expected, modelDescription) } @Test fun `should return model without tag if no tags`() { val models = listOf( DeviceModel.Android( id = "walleye", codename = "walleye", brand = "Google", form = "PHYSICAL", formFactor = "PHONE", manufacturer = "Google", name = "Pixel 2", screenDensity = 420, screenX = 1080, screenY = 1920, supportedAbis = listOf("arm64-v8a", "armeabi-v7a", "armeabi"), supportedVersionIds = listOf("26", "27", "28"), thumbnailUrl = "https://lh3.googleusercontent.com/j4urvb3lXTaFGZI6IzHmAjum2HQVID1OHPhDB7dOzRvXb2WscSX2RFwEEFFSYhajqRO5Yu0e6FYQ", tags = emptyList(), lowFpsVideoRecording = true ) ) val modelDescription = models.find { it.id == "walleye" }?.prepareDescription() val expected = """ brand: Google codename: walleye form: PHYSICAL formFactor: PHONE id: walleye manufacturer: Google name: Pixel 2 screenDensity: 420 screenX: 1080 screenY: 1920 supportedAbis: - arm64-v8a - armeabi-v7a - armeabi supportedVersionIds: - 26 - 27 - 28 thumbnailUrl: https://lh3.googleusercontent.com/j4urvb3lXTaFGZI6IzHmAjum2HQVID1OHPhDB7dOzRvXb2WscSX2RFwEEFFSYhajqRO5Yu0e6FYQ """.trimIndent() assertEquals(expected, modelDescription) } }
apache-2.0
5a726d427f643c80b260af316be707ac
32.056604
132
0.55137
3.963801
false
false
false
false
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/projectFilter/ProjectIndexableFilesFilterHolder.kt
6
5877
// 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 com.intellij.util.indexing.projectFilter import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ReadAction import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.ProgressIndicatorUtils import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.roots.ContentIterator import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileWithId import com.intellij.util.containers.ConcurrentFactoryMap import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.FileBasedIndexImpl import com.intellij.util.indexing.IdFilter import com.intellij.util.indexing.UnindexedFilesUpdater import java.util.concurrent.Callable import java.util.concurrent.ConcurrentMap internal enum class FileAddStatus { ADDED, PRESENT, SKIPPED } internal sealed class ProjectIndexableFilesFilterHolder { abstract fun getProjectIndexableFiles(project: Project): IdFilter? abstract fun addFileId(fileId: Int, projects: () -> Set<Project>): FileAddStatus abstract fun addFileId(fileId: Int, project: Project): FileAddStatus abstract fun entireProjectUpdateStarted(project: Project) abstract fun entireProjectUpdateFinished(project: Project) abstract fun removeFile(fileId: Int) abstract fun findProjectForFile(fileId: Int): Project? abstract fun runHealthCheck() } internal class IncrementalProjectIndexableFilesFilterHolder : ProjectIndexableFilesFilterHolder() { private val myProjectFilters: ConcurrentMap<Project, IncrementalProjectIndexableFilesFilter> = ConcurrentFactoryMap.createMap { IncrementalProjectIndexableFilesFilter() } init { ApplicationManager.getApplication().messageBus.connect().subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosed(project: Project) { myProjectFilters.remove(project) } }) } override fun getProjectIndexableFiles(project: Project): IdFilter? { if (!UnindexedFilesUpdater.isProjectContentFullyScanned(project) || UnindexedFilesUpdater.isIndexUpdateInProgress(project)) { return null } return myProjectFilters[project] } override fun entireProjectUpdateStarted(project: Project) { assert(UnindexedFilesUpdater.isIndexUpdateInProgress(project)) myProjectFilters[project]?.memoizeAndResetFileIds() } override fun entireProjectUpdateFinished(project: Project) { assert(UnindexedFilesUpdater.isIndexUpdateInProgress(project)) myProjectFilters[project]?.resetPreviousFileIds() } override fun addFileId(fileId: Int, projects: () -> Set<Project>): FileAddStatus { val matchedProjects by lazy(LazyThreadSafetyMode.NONE) { projects() } val statuses = myProjectFilters.map { (p, filter) -> filter.ensureFileIdPresent(fileId) { matchedProjects.contains(p) } } if (statuses.all { it == FileAddStatus.SKIPPED }) return FileAddStatus.SKIPPED if (statuses.any { it == FileAddStatus.ADDED }) return FileAddStatus.ADDED return FileAddStatus.PRESENT } override fun addFileId(fileId: Int, project: Project): FileAddStatus { return myProjectFilters.get(project)!!.ensureFileIdPresent(fileId) { true } } override fun removeFile(fileId: Int) { for (filter in myProjectFilters.values) { filter.removeFileId(fileId) } } override fun findProjectForFile(fileId: Int): Project? { for ((project, filter) in myProjectFilters) { if (filter.containsFileId(fileId)) { return project } } return null } override fun runHealthCheck() { try { for ((project, filter) in myProjectFilters) { var errors: List<HealthCheckError>? = null ProgressIndicatorUtils.runInReadActionWithWriteActionPriority { if (DumbService.isDumb(project)) return@runInReadActionWithWriteActionPriority errors = runHealthCheck(project, filter) } if (errors.isNullOrEmpty()) continue for (error in errors!!) { error.fix(filter) } val message = StringUtil.first(errors!!.map { ReadAction.nonBlocking(Callable { it.presentableText }) }.joinToString(", "), 300, true) FileBasedIndexImpl.LOG.error("Project indexable filter health check errors: $message") } } catch (_: ProcessCanceledException) { } catch (e: Exception) { FileBasedIndexImpl.LOG.error(e) } } private fun runHealthCheck(project: Project, filter: IncrementalProjectIndexableFilesFilter): List<HealthCheckError> { val errors = mutableListOf<HealthCheckError>() val index = FileBasedIndex.getInstance() as FileBasedIndexImpl index.iterateIndexableFiles(ContentIterator { if (it is VirtualFileWithId) { val fileId = it.id if (!filter.containsFileId(fileId)) { filter.ensureFileIdPresent(fileId) { true } } } true }, project, ProgressManager.getInstance().progressIndicator) return errors } private class HealthCheckError(private val project: Project, private val virtualFile: VirtualFile) { val presentableText: String get() = "file ${virtualFile.path} not found in ${project.name}" fun fix(filter: IncrementalProjectIndexableFilesFilter) { filter.ensureFileIdPresent((virtualFile as VirtualFileWithId).id) { true } } } }
apache-2.0
d05e66fa4218c0b0995ed9e091d32191
35.06135
172
0.742386
4.751011
false
false
false
false
mdaniel/intellij-community
python/src/com/jetbrains/python/ui/remotePathEditor/ManualPathEntryDialog.kt
1
2789
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.python.ui.remotePathEditor import com.intellij.execution.Platform import com.intellij.execution.target.BrowsableTargetEnvironmentType import com.intellij.execution.target.TargetEnvironmentConfiguration import com.intellij.execution.target.getTargetType import com.intellij.execution.target.textFieldWithBrowseTargetButton import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.io.OSAgnosticPathUtil import com.intellij.ui.layout.* import com.jetbrains.python.PyBundle import java.util.function.Supplier import javax.swing.JComponent /** * The dialog that allows to specify the path to a file or directory manually. * * Performs validation that the path that is being added is an absolute path on * the specified [platform]. */ class ManualPathEntryDialog(private val project: Project?, private val platform: Platform = Platform.UNIX, targetConfig: TargetEnvironmentConfiguration? = null) : DialogWrapper(project) { private val targetConfigAndType: Pair<TargetEnvironmentConfiguration, BrowsableTargetEnvironmentType>? = (targetConfig?.getTargetType() as? BrowsableTargetEnvironmentType)?.let { Pair(targetConfig, it) } var path: String = "" private set init { title = PyBundle.message("enter.path.dialog.title") init() } override fun createCenterPanel(): JComponent { val label = PyBundle.message("path.label") return panel { row(label = label) { val textFieldComponent = if (targetConfigAndType == null) textField(prop = ::path) else textFieldWithBrowseTargetButton(this, targetConfigAndType.second, Supplier { targetConfigAndType.first }, project!!, label, this@ManualPathEntryDialog::path.toBinding(), false) textFieldComponent.withValidationOnApply { textField -> val text = textField.text when { text.isBlank() -> error(PyBundle.message("path.must.not.be.empty.error.message")) !isAbsolutePath(text, platform) -> error(PyBundle.message("path.must.be.absolute.error.message")) text.endsWith(" ") -> warning(PyBundle.message("path.ends.with.whitespace.warning.message")) else -> null } }.focused() } } } companion object { fun isAbsolutePath(path: String, platform: Platform): Boolean = when (platform) { Platform.UNIX -> path.startsWith("/") Platform.WINDOWS -> isAbsoluteWindowsPath(path) } private fun isAbsoluteWindowsPath(path: String): Boolean = OSAgnosticPathUtil.isAbsoluteDosPath(path) } }
apache-2.0
a6a5ca518da2914000e1f06efef70e37
41.272727
186
0.721406
4.542345
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/InvertIfConditionIntention.kt
1
11902
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.core.unblockDocument import org.jetbrains.kotlin.idea.inspections.ReplaceNegatedIsEmptyWithIsNotEmptyInspection.Companion.invertSelectorFunction import org.jetbrains.kotlin.idea.refactoring.getLineNumber import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.util.psi.patternMatching.matches import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull class InvertIfConditionIntention : SelfTargetingIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("invert.if.condition") ) { override fun isApplicableTo(element: KtIfExpression, caretOffset: Int): Boolean { if (!element.ifKeyword.textRange.containsOffset(caretOffset)) return false return element.condition != null && element.then != null } override fun applyTo(element: KtIfExpression, editor: Editor?) { val rBrace = parentBlockRBrace(element) val commentSavingRange = if (rBrace != null) PsiChildRange(element, rBrace) else PsiChildRange.singleElement(element) val commentSaver = CommentSaver(commentSavingRange) if (rBrace != null) element.nextEolCommentOnSameLine()?.delete() val condition = element.condition!! val newCondition = (condition as? KtQualifiedExpression)?.invertSelectorFunction() ?: condition.negate() val newIf = handleSpecialCases(element, newCondition) ?: handleStandardCase(element, newCondition) val commentRestoreRange = if (rBrace != null) PsiChildRange(newIf, rBrace) else PsiChildRange(newIf, parentBlockRBrace(newIf) ?: newIf) commentSaver.restore(commentRestoreRange) val newIfCondition = newIf.condition (newIfCondition as? KtPrefixExpression)?.let { //use De Morgan's law only for negated condition to not make it more complex if (it.operationReference.getReferencedNameElementType() == KtTokens.EXCL) { val binaryExpr = (it.baseExpression as? KtParenthesizedExpression)?.expression as? KtBinaryExpression if (binaryExpr != null) { ConvertBinaryExpressionWithDemorgansLawIntention.convertIfPossible(binaryExpr) } } } editor?.apply { unblockDocument() moveCaret(newIf.textOffset) } } private fun handleStandardCase(ifExpression: KtIfExpression, newCondition: KtExpression): KtIfExpression { val psiFactory = KtPsiFactory(ifExpression) val thenBranch = ifExpression.then!! val elseBranch = ifExpression.`else` ?: psiFactory.createEmptyBody() val newThen = if (elseBranch is KtIfExpression) psiFactory.createSingleStatementBlock(elseBranch) else elseBranch val newElse = if (thenBranch is KtBlockExpression && thenBranch.statements.isEmpty()) null else thenBranch val conditionLineNumber = ifExpression.condition?.getLineNumber(false) val thenBranchLineNumber = thenBranch.getLineNumber(false) val elseKeywordLineNumber = ifExpression.elseKeyword?.getLineNumber() val afterCondition = if (newThen !is KtBlockExpression && elseKeywordLineNumber != elseBranch.getLineNumber(false)) "\n" else "" val beforeElse = if (newThen !is KtBlockExpression && conditionLineNumber != elseKeywordLineNumber) "\n" else " " val afterElse = if (newElse !is KtBlockExpression && conditionLineNumber != thenBranchLineNumber) "\n" else " " val newIf = if (newElse == null) { psiFactory.createExpressionByPattern("if ($0)$afterCondition$1", newCondition, newThen) } else { psiFactory.createExpressionByPattern("if ($0)$afterCondition$1${beforeElse}else$afterElse$2", newCondition, newThen, newElse) } as KtIfExpression return ifExpression.replaced(newIf) } private fun handleSpecialCases(ifExpression: KtIfExpression, newCondition: KtExpression): KtIfExpression? { val elseBranch = ifExpression.`else` if (elseBranch != null) return null val factory = KtPsiFactory(ifExpression) val thenBranch = ifExpression.then!! val lastThenStatement = thenBranch.lastBlockStatementOrThis() if (lastThenStatement.isExitStatement()) { val block = ifExpression.parent as? KtBlockExpression if (block != null) { val rBrace = block.rBrace val afterIfInBlock = ifExpression.siblings(withItself = false).takeWhile { it != rBrace }.toList() val lastStatementInBlock = afterIfInBlock.lastIsInstanceOrNull<KtExpression>() if (lastStatementInBlock != null) { val exitStatementAfterIf = if (lastStatementInBlock.isExitStatement()) lastStatementInBlock else exitStatementExecutedAfter(lastStatementInBlock) if (exitStatementAfterIf != null) { val first = afterIfInBlock.first() val last = afterIfInBlock.last() // build new then branch from statements after if (we will add exit statement if necessary later) //TODO: no block if single? val newThenRange = if (isEmptyReturn(lastThenStatement) && isEmptyReturn(lastStatementInBlock)) { PsiChildRange(first, lastStatementInBlock.prevSibling).trimWhiteSpaces() } else { PsiChildRange(first, last).trimWhiteSpaces() } val newIf = factory.createExpressionByPattern("if ($0) { $1 }", newCondition, newThenRange) as KtIfExpression // remove statements after if as they are moving under if block.deleteChildRange(first, last) if (isEmptyReturn(lastThenStatement)) { if (block.parent is KtDeclarationWithBody && block.parent !is KtFunctionLiteral) { lastThenStatement.delete() } } val updatedIf = copyThenBranchAfter(ifExpression) // check if we need to add exit statement to then branch if (exitStatementAfterIf != lastStatementInBlock) { // don't insert the exit statement, if the new if statement placement has the same exit statement executed after it val exitAfterNewIf = exitStatementExecutedAfter(updatedIf) if (exitAfterNewIf == null || !exitAfterNewIf.matches(exitStatementAfterIf)) { val newThen = newIf.then as KtBlockExpression newThen.addBefore(exitStatementAfterIf, newThen.rBrace) } } return updatedIf.replace(newIf) as KtIfExpression } } } } val exitStatement = exitStatementExecutedAfter(ifExpression) ?: return null val updatedIf = copyThenBranchAfter(ifExpression) val newIf = factory.createExpressionByPattern("if ($0) $1", newCondition, exitStatement) return updatedIf.replace(newIf) as KtIfExpression } private fun isEmptyReturn(statement: KtExpression) = statement is KtReturnExpression && statement.returnedExpression == null && statement.labeledExpression == null private fun copyThenBranchAfter(ifExpression: KtIfExpression): KtIfExpression { val factory = KtPsiFactory(ifExpression) val thenBranch = ifExpression.then ?: return ifExpression val parent = ifExpression.parent if (parent !is KtBlockExpression) { assert(parent is KtContainerNode) val block = factory.createEmptyBody() block.addAfter(ifExpression, block.lBrace) val newBlock = ifExpression.replaced(block) val newIf = newBlock.statements.single() as KtIfExpression return copyThenBranchAfter(newIf) } if (thenBranch is KtBlockExpression) { (thenBranch.statements.lastOrNull() as? KtContinueExpression)?.delete() val range = thenBranch.contentRange() if (!range.isEmpty) { parent.addRangeAfter(range.first, range.last, ifExpression) parent.addAfter(factory.createNewLine(), ifExpression) } } else if (thenBranch !is KtContinueExpression) { parent.addAfter(thenBranch, ifExpression) parent.addAfter(factory.createNewLine(), ifExpression) } return ifExpression } private fun exitStatementExecutedAfter(expression: KtExpression): KtExpression? { val parent = expression.parent if (parent is KtBlockExpression) { val lastStatement = parent.statements.last() return if (expression == lastStatement) { exitStatementExecutedAfter(parent) } else if (lastStatement.isExitStatement() && expression.siblings(withItself = false).firstIsInstance<KtExpression>() == lastStatement ) { lastStatement } else { null } } when (parent) { is KtNamedFunction -> { if (parent.bodyExpression == expression) { if (!parent.hasBlockBody()) return null val returnType = parent.resolveToDescriptorIfAny()?.returnType if (returnType == null || !returnType.isUnit()) return null return KtPsiFactory(expression).createExpression("return") } } is KtContainerNode -> when (val pparent = parent.parent) { is KtLoopExpression -> { if (expression == pparent.body) { return KtPsiFactory(expression).createExpression("continue") } } is KtIfExpression -> { if (expression == pparent.then || expression == pparent.`else`) { return exitStatementExecutedAfter(pparent) } } } } return null } private fun parentBlockRBrace(element: KtIfExpression): PsiElement? = (element.parent as? KtBlockExpression)?.rBrace private fun KtIfExpression.nextEolCommentOnSameLine(): PsiElement? = getLineNumber(false).let { lastLineNumber -> siblings(withItself = false) .takeWhile { it.getLineNumber() == lastLineNumber } .firstOrNull { it is PsiComment && it.node.elementType == KtTokens.EOL_COMMENT } } }
apache-2.0
51a154efea629e4ff2677e93ea317a9d
46.608
158
0.636364
5.572097
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHPRList.kt
1
6282
// 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 org.jetbrains.plugins.github.pullrequest.ui import com.intellij.ide.CopyProvider import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.ide.CopyPasteManager import com.intellij.ui.ListUtil import com.intellij.ui.ScrollingUtil import com.intellij.ui.components.JBList import com.intellij.util.text.DateFormatUtil import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.ListUiUtil import com.intellij.util.ui.UIUtil import icons.GithubIcons import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestState import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider import org.jetbrains.plugins.github.util.GithubUIUtil import java.awt.Component import java.awt.datatransfer.StringSelection import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* internal class GHPRList(private val copyPasteManager: CopyPasteManager, avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory, model: ListModel<GHPullRequestShort>) : JBList<GHPullRequestShort>(model), CopyProvider, DataProvider, Disposable { private val avatarIconsProvider = avatarIconsProviderFactory.create(GithubUIUtil.avatarSize, this) init { selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION addMouseListener(RightClickSelectionListener()) val renderer = PullRequestsListCellRenderer() cellRenderer = renderer UIUtil.putClientProperty(this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(renderer)) ScrollingUtil.installActions(this) } override fun getToolTipText(event: MouseEvent): String? { val childComponent = ListUtil.getDeepestRendererChildComponentAt(this, event.point) if (childComponent !is JComponent) return null return childComponent.toolTipText } override fun performCopy(dataContext: DataContext) { if (selectedIndex < 0) return val selection = model.getElementAt(selectedIndex) copyPasteManager.setContents(StringSelection("#${selection.number} ${selection.title}")) } override fun isCopyEnabled(dataContext: DataContext) = !isSelectionEmpty override fun isCopyVisible(dataContext: DataContext) = false override fun getData(dataId: String): Any? = when { PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this GHPRActionKeys.SELECTED_PULL_REQUEST.`is`(dataId) -> selectedValue else -> null } override fun dispose() {} private inner class PullRequestsListCellRenderer : ListCellRenderer<GHPullRequestShort>, JPanel() { private val stateIcon = JLabel() private val title = JLabel() private val info = JLabel() private val labels = JPanel().apply { layout = BoxLayout(this, BoxLayout.X_AXIS) } private val assignees = JPanel().apply { layout = BoxLayout(this, BoxLayout.X_AXIS) } init { border = JBUI.Borders.empty(5, 8) layout = MigLayout(LC().gridGap("0", "0") .insets("0", "0", "0", "0") .fillX()) val gapAfter = "${JBUI.scale(5)}px" add(stateIcon, CC() .gapAfter(gapAfter)) add(title, CC() .minWidth("pref/2px") .gapAfter(gapAfter)) add(labels, CC() .growX() .pushX() .minWidth("0px") .gapAfter(gapAfter)) add(assignees, CC() .spanY(2) .wrap()) add(info, CC() .minWidth("0px") .skip(1) .spanX(2)) } override fun getListCellRendererComponent(list: JList<out GHPullRequestShort>, value: GHPullRequestShort, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { UIUtil.setBackgroundRecursively(this, ListUiUtil.WithTallRow.background(list, isSelected, list.hasFocus())) val primaryTextColor = ListUiUtil.WithTallRow.foreground(isSelected, list.hasFocus()) val secondaryTextColor = ListUiUtil.WithTallRow.secondaryForeground(list, isSelected) stateIcon.apply { icon = when (value.state) { GHPullRequestState.CLOSED -> GithubIcons.PullRequestClosed GHPullRequestState.MERGED -> GithubIcons.PullRequestMerged GHPullRequestState.OPEN -> GithubIcons.PullRequestOpen } toolTipText = value.state.toString().toLowerCase().capitalize() } title.apply { text = value.title foreground = primaryTextColor } info.apply { text = "#${value.number} ${value.author?.login} on ${DateFormatUtil.formatDate(value.createdAt)}" foreground = secondaryTextColor } labels.apply { removeAll() for (label in value.labels) { add(GithubUIUtil.createIssueLabelLabel(label)) add(Box.createRigidArea(JBDimension(4, 0))) } } assignees.apply { removeAll() for (assignee in value.assignees) { if (componentCount != 0) { add(Box.createRigidArea(JBDimension(UIUtil.DEFAULT_HGAP, 0))) } add(JLabel().apply { icon = avatarIconsProvider.getIcon(assignee.avatarUrl) toolTipText = assignee.login }) } } return this } } private inner class RightClickSelectionListener : MouseAdapter() { override fun mousePressed(e: MouseEvent) { if (SwingUtilities.isRightMouseButton(e)) { val row = locationToIndex(e.point) if (row != -1) selectionModel.setSelectionInterval(row, row) } } } }
apache-2.0
91aead985e1cd64919b4e00553db6e5c
35.74269
140
0.682904
4.832308
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticOverloadsRenamer.kt
1
4045
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.refactoring.rename.naming.AutomaticRenamer import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory import com.intellij.usageView.UsageInfo import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.util.expectedDescriptor import org.jetbrains.kotlin.idea.util.getAllAccessibleFunctions import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.UserDataProperty import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.source.getPsi class AutomaticOverloadsRenamer(function: KtNamedFunction, newName: String) : AutomaticRenamer() { companion object { @get:TestOnly @set:TestOnly var PsiElement.elementFilter: ((PsiElement) -> Boolean)? by UserDataProperty(Key.create("ELEMENT_FILTER")) } init { val filter = function.elementFilter function.getOverloads().mapNotNullTo(myElements) { val candidate = it.source.getPsi() as? KtNamedFunction ?: return@mapNotNullTo null if (filter != null && !filter(candidate)) return@mapNotNullTo null if (candidate != function) candidate else null } suggestAllNames(function.name, newName) } override fun getDialogTitle() = KotlinBundle.message("text.rename.overloads.title") override fun getDialogDescription() = KotlinBundle.message("text.rename.overloads.to") override fun entityName() = KotlinBundle.message("text.overload") override fun isSelectedByDefault(): Boolean = true } private fun KtNamedFunction.getOverloads(): Collection<FunctionDescriptor> { val name = nameAsName ?: return emptyList() val resolutionFacade = getResolutionFacade() val descriptor = this.unsafeResolveToDescriptor() as FunctionDescriptor val context = resolutionFacade.analyze(this, BodyResolveMode.FULL) val scope = getResolutionScope(context, resolutionFacade) val extensionReceiverClass = descriptor.extensionReceiverParameter?.type?.constructor?.declarationDescriptor as? ClassDescriptor if (descriptor.isActual && descriptor.expectedDescriptor() != null) return emptyList() val result = LinkedHashSet<FunctionDescriptor>() result += scope.getAllAccessibleFunctions(name) if (extensionReceiverClass != null) { result += extensionReceiverClass.unsubstitutedMemberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE) } return result } class AutomaticOverloadsRenamerFactory : AutomaticRenamerFactory { override fun isApplicable(element: PsiElement): Boolean { if (element !is KtNamedFunction) return false if (element.isLocal) return false return element.getOverloads().size > 1 } override fun getOptionName() = JavaRefactoringBundle.message("rename.overloads") override fun isEnabled() = KotlinRefactoringSettings.instance.renameOverloads override fun setEnabled(enabled: Boolean) { KotlinRefactoringSettings.instance.renameOverloads = enabled } override fun createRenamer(element: PsiElement, newName: String, usages: Collection<UsageInfo>) = AutomaticOverloadsRenamer(element as KtNamedFunction, newName) }
apache-2.0
6eba61c9bb24624b83e86a09e570b78d
46.046512
158
0.781953
5.043641
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/runtime/collections/array4.kt
4
1607
/* * Copyright 2010-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 runtime.collections.array4 import kotlin.test.* @Test fun runTest() { assertFailsWith<IllegalArgumentException> { val a = Array(-2) { "nope" } println(a) } assertFailsWith<IllegalArgumentException> { val a = ByteArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = UByteArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = ShortArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = UShortArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = IntArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = UIntArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = LongArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = ULongArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = FloatArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = DoubleArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = BooleanArray(-2) println(a) } assertFailsWith<IllegalArgumentException> { val a = CharArray(-2) println(a) } println("OK") }
apache-2.0
8dd2fc516b78052acd96c3eec81e5342
24.125
101
0.610454
4.578348
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/popup/list/NonActionsPopupInlineSupport.kt
1
1827
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.popup.list import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import java.awt.Point import java.awt.event.InputEvent import javax.swing.JComponent import javax.swing.JList class NonActionsPopupInlineSupport(private val myListPopup: ListPopupImpl) : PopupInlineActionsSupport { override fun calcExtraButtonsCount(element: Any?): Int = if (hasMoreButton(element)) 1 else 0 override fun calcButtonIndex(element: Any?, point: Point): Int? { if (element == null || !hasMoreButton(element)) return null return calcButtonIndex(myListPopup.list, 1, point) } override fun runInlineAction(element: Any?, index: Int, event: InputEvent?): Boolean { if (index == 0 && hasMoreButton(element)) myListPopup.showNextStepPopup(myListPopup.listStep.onChosen(element, false), element) return false } override fun getExtraButtons(list: JList<*>, value: Any?, isSelected: Boolean): List<JComponent> = if (hasMoreButton(value) && isSelected) listOf(createExtraButton (AllIcons.Actions.More, getActiveButtonIndex(list) == 0)) else emptyList() override fun getActiveExtraButtonToolTipText(list: JList<*>, value: Any?): String? = if (hasMoreButton(value) && getActiveButtonIndex(list) == 0) IdeBundle.message("inline.actions.more.actions.text") else null override fun getActiveButtonIndex(list: JList<*>): Int? = (list as? ListPopupImpl.ListWithInlineButtons)?.selectedButtonIndex private fun hasMoreButton(element: Any?) = myListPopup.listStep.hasSubstep(element) && !myListPopup.isShowSubmenuOnHover && myListPopup.listStep.isFinal(element) }
apache-2.0
1a7a418bce46ac49cc206cf9ff69c9ac
48.405405
131
0.729611
4.329384
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/CollapsibleRowImpl.kt
1
3384
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.dsl.builder.impl import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.UiSwitcher import com.intellij.openapi.util.NlsContexts import com.intellij.ui.Expandable import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.gridLayout.Gaps import org.jetbrains.annotations.ApiStatus import java.awt.Font import javax.swing.border.EmptyBorder @ApiStatus.Internal internal class CollapsibleRowImpl(dialogPanelConfig: DialogPanelConfig, panelContext: PanelContext, parent: PanelImpl, @NlsContexts.BorderTitle title: String, init: Panel.() -> Unit) : RowImpl(dialogPanelConfig, panelContext, parent, RowLayout.INDEPENDENT), CollapsibleRow { private val collapsibleTitledSeparator = CollapsibleTitledSeparatorImpl(title) override var expanded by collapsibleTitledSeparator::expanded override fun setTitle(title: String) { collapsibleTitledSeparator.text = title } override fun setTitleFont(font: Font) { collapsibleTitledSeparator.titleFont = font } override fun addExpandedListener(action: (Boolean) -> Unit) { collapsibleTitledSeparator.expandedProperty.afterChange { action(it) } } init { collapsibleTitledSeparator.setLabelFocusable(true) (collapsibleTitledSeparator.label.border as? EmptyBorder)?.borderInsets?.let { collapsibleTitledSeparator.putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps(top = it.top, left = it.left, bottom = it.bottom)) } collapsibleTitledSeparator.label.putClientProperty(Expandable::class.java, object : Expandable { override fun expand() { expanded = true } override fun collapse() { expanded = false } override fun isExpanded(): Boolean { return expanded } }) val action = DumbAwareAction.create { expanded = !expanded } action.registerCustomShortcutSet(ActionUtil.getShortcutSet("CollapsiblePanel-toggle"), collapsibleTitledSeparator.label) val collapsibleTitledSeparator = this.collapsibleTitledSeparator lateinit var expandablePanel: Panel panel { row { cell(collapsibleTitledSeparator).align(AlignX.FILL) } row { expandablePanel = panel(init).align(AlignY.FILL) }.resizableRow() collapsibleTitledSeparator.onAction { expandablePanel.visible(it) } }.align(AlignY.FILL) applyUiSwitcher(expandablePanel as PanelImpl, CollapsibleRowUiSwitcher(this)) } private fun applyUiSwitcher(panel: PanelImpl, uiSwitcher: UiSwitcher) { for (row in panel.rows) { for (cell in row.cells) { when (cell) { is CellImpl<*> -> UiSwitcher.append(cell.viewComponent, uiSwitcher) is PanelImpl -> applyUiSwitcher(cell, uiSwitcher) else -> {} } } } } private class CollapsibleRowUiSwitcher(private val collapsibleRow: CollapsibleRowImpl) : UiSwitcher { override fun show(): Boolean { collapsibleRow.expanded = true return true } } }
apache-2.0
b1c82ae4e7e49c09e28bc0ce4cb94938
33.530612
124
0.69208
4.961877
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/KotlinInlayParameterHintsProvider.kt
7
3626
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.hints import com.intellij.codeInsight.hints.HintInfo import com.intellij.codeInsight.hints.InlayInfo import com.intellij.codeInsight.hints.InlayParameterHintsProvider import com.intellij.lang.Language import com.intellij.lang.java.JavaLanguage import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallElement import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe class KotlinInlayParameterHintsProvider : InlayParameterHintsProvider { override fun getDefaultBlackList(): Set<String> = setOf( "*listOf", "*setOf", "*arrayOf", "*ListOf", "*SetOf", "*ArrayOf", "*assert*(*)", "*mapOf", "*MapOf", "kotlin.require*(*)", "kotlin.check*(*)", "*contains*(value)", "*containsKey(key)", "kotlin.lazyOf(value)", "*SequenceBuilder.resume(value)", "*SequenceBuilder.yield(value)", /* Gradle DSL especially annoying hints */ "org.gradle.api.Project.hasProperty(propertyName)", "org.gradle.api.Project.findProperty(propertyName)", "org.gradle.api.Project.file(path)", "org.gradle.api.Project.uri(path)", "jvmArgs(arguments)", "org.gradle.kotlin.dsl.DependencyHandlerScope.*(notation)", "org.gradle.kotlin.dsl.*(dependencyNotation)", "org.gradle.kotlin.dsl.kotlin(module)", "org.gradle.kotlin.dsl.kotlin(module,version)", "org.gradle.kotlin.dsl.project(path,configuration)" ) override fun getHintInfo(element: PsiElement): HintInfo? { if (!(HintType.PARAMETER_HINT.isApplicable(element))) return null val parent: PsiElement = (element as? KtValueArgumentList)?.parent ?: return null return (parent as? KtCallElement)?.let { getMethodInfo(it) } } override fun getParameterHints(element: PsiElement): List<InlayInfo> { return if (HintType.PARAMETER_HINT.isApplicable(element)) HintType.PARAMETER_HINT.provideHints(element) else emptyList() } override fun getBlackListDependencyLanguage(): Language = JavaLanguage.INSTANCE override fun getInlayPresentation(inlayText: String): String = inlayText private fun getMethodInfo(elem: KtCallElement): HintInfo.MethodInfo? { val resolvedCall = elem.resolveToCall() val resolvedCallee = resolvedCall?.candidateDescriptor if (resolvedCallee is FunctionDescriptor) { val paramNames = resolvedCallee.valueParameters.asSequence().map { it.name }.filter { !it.isSpecial }.map(Name::asString).toList() val fqName = if (resolvedCallee is ConstructorDescriptor) resolvedCallee.containingDeclaration.fqNameSafe.asString() else (resolvedCallee.fqNameOrNull()?.asString() ?: return null) return HintInfo.MethodInfo(fqName, paramNames) } return null } } fun PsiElement.isNameReferenceInCall() = this is KtNameReferenceExpression && parent is KtCallExpression
apache-2.0
d53461cd030fd2e52820309bd79aec1b
46.723684
129
0.711804
4.847594
false
false
false
false
loxal/FreeEthereum
free-ethereum-core/src/main/java/org/ethereum/config/blockchain/DaoHFConfig.kt
1
16889
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.ethereum.config.blockchain import com.fasterxml.jackson.databind.ObjectMapper import org.ethereum.config.BlockchainConfig import org.ethereum.core.Block import org.ethereum.core.Repository import org.spongycastle.util.encoders.Hex import java.io.IOException import java.math.BigInteger import java.util.* class DaoHFConfig : AbstractDaoConfig { private val daoAccounts = ArrayList<ByteArray>() private val withdrawAccount = Hex.decode("bf4ed7b27f1d666546e30d74d50d173d20bca754") init { supportFork = true } constructor() { initDaoConfig(HomesteadConfig(), AbstractDaoConfig.ETH_FORK_BLOCK_NUMBER) } constructor(parent: BlockchainConfig, forkBlockNumber: Long) { initDaoConfig(parent, forkBlockNumber) } override fun initDaoConfig(parent: BlockchainConfig, forkBlockNumber: Long) { super.initDaoConfig(parent, forkBlockNumber) try { val objectMapper = ObjectMapper() val daoAccts = objectMapper.readValue(accountsJson.replace('\'', '"'), Array<DaoAcct>::class.java) for (daoAcct in daoAccts) { daoAccounts.add(Hex.decode(daoAcct.address!!.substring(2))) daoAccounts.add(Hex.decode(daoAcct.extraBalanceAccount!!.substring(2))) } } catch (e: IOException) { throw RuntimeException(e) } } /** * Goal is to transfer balance from set of accounts to single refund one. * Accounts may not exists in tests. However refund account should be created anyway. */ override fun hardForkTransfers(block: Block, repo: Repository) { if (block.number == forkBlockNumber) { repo.addBalance(withdrawAccount, BigInteger.ZERO) for (account in daoAccounts) { if (repo.isExist(account)) { val balance = repo.getBalance(account) repo.addBalance(account, balance.negate()) repo.addBalance(withdrawAccount, balance) } } } } override fun toString(): String { return super.toString() + "(forkBlock:" + forkBlockNumber + ")" } private class DaoAcct { var address: String? = null var extraBalanceAccount: String? = null } companion object { private val accountsJson = "" + "[ " + " { " + " 'address':'0xd4fe7bc31cedb7bfb8a345f31e668033056b2728'," + " 'extraBalanceAccount':'0xb3fb0e5aba0e20e5c49d252dfd30e102b171a425'" + " }," + " { " + " 'address':'0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f'," + " 'extraBalanceAccount':'0xecd135fa4f61a655311e86238c92adcd779555d2'" + " }," + " { " + " 'address':'0x1975bd06d486162d5dc297798dfc41edd5d160a7'," + " 'extraBalanceAccount':'0xa3acf3a1e16b1d7c315e23510fdd7847b48234f6'" + " }," + " { " + " 'address':'0x319f70bab6845585f412ec7724b744fec6095c85'," + " 'extraBalanceAccount':'0x06706dd3f2c9abf0a21ddcc6941d9b86f0596936'" + " }," + " { " + " 'address':'0x5c8536898fbb74fc7445814902fd08422eac56d0'," + " 'extraBalanceAccount':'0x6966ab0d485353095148a2155858910e0965b6f9'" + " }," + " { " + " 'address':'0x779543a0491a837ca36ce8c635d6154e3c4911a6'," + " 'extraBalanceAccount':'0x2a5ed960395e2a49b1c758cef4aa15213cfd874c'" + " }," + " { " + " 'address':'0x5c6e67ccd5849c0d29219c4f95f1a7a93b3f5dc5'," + " 'extraBalanceAccount':'0x9c50426be05db97f5d64fc54bf89eff947f0a321'" + " }," + " { " + " 'address':'0x200450f06520bdd6c527622a273333384d870efb'," + " 'extraBalanceAccount':'0xbe8539bfe837b67d1282b2b1d61c3f723966f049'" + " }," + " { " + " 'address':'0x6b0c4d41ba9ab8d8cfb5d379c69a612f2ced8ecb'," + " 'extraBalanceAccount':'0xf1385fb24aad0cd7432824085e42aff90886fef5'" + " }," + " { " + " 'address':'0xd1ac8b1ef1b69ff51d1d401a476e7e612414f091'," + " 'extraBalanceAccount':'0x8163e7fb499e90f8544ea62bbf80d21cd26d9efd'" + " }," + " { " + " 'address':'0x51e0ddd9998364a2eb38588679f0d2c42653e4a6'," + " 'extraBalanceAccount':'0x627a0a960c079c21c34f7612d5d230e01b4ad4c7'" + " }," + " { " + " 'address':'0xf0b1aa0eb660754448a7937c022e30aa692fe0c5'," + " 'extraBalanceAccount':'0x24c4d950dfd4dd1902bbed3508144a54542bba94'" + " }," + " { " + " 'address':'0x9f27daea7aca0aa0446220b98d028715e3bc803d'," + " 'extraBalanceAccount':'0xa5dc5acd6a7968a4554d89d65e59b7fd3bff0f90'" + " }," + " { " + " 'address':'0xd9aef3a1e38a39c16b31d1ace71bca8ef58d315b'," + " 'extraBalanceAccount':'0x63ed5a272de2f6d968408b4acb9024f4cc208ebf'" + " }," + " { " + " 'address':'0x6f6704e5a10332af6672e50b3d9754dc460dfa4d'," + " 'extraBalanceAccount':'0x77ca7b50b6cd7e2f3fa008e24ab793fd56cb15f6'" + " }," + " { " + " 'address':'0x492ea3bb0f3315521c31f273e565b868fc090f17'," + " 'extraBalanceAccount':'0x0ff30d6de14a8224aa97b78aea5388d1c51c1f00'" + " }," + " { " + " 'address':'0x9ea779f907f0b315b364b0cfc39a0fde5b02a416'," + " 'extraBalanceAccount':'0xceaeb481747ca6c540a000c1f3641f8cef161fa7'" + " }," + " { " + " 'address':'0xcc34673c6c40e791051898567a1222daf90be287'," + " 'extraBalanceAccount':'0x579a80d909f346fbfb1189493f521d7f48d52238'" + " }," + " { " + " 'address':'0xe308bd1ac5fda103967359b2712dd89deffb7973'," + " 'extraBalanceAccount':'0x4cb31628079fb14e4bc3cd5e30c2f7489b00960c'" + " }," + " { " + " 'address':'0xac1ecab32727358dba8962a0f3b261731aad9723'," + " 'extraBalanceAccount':'0x4fd6ace747f06ece9c49699c7cabc62d02211f75'" + " }," + " { " + " 'address':'0x440c59b325d2997a134c2c7c60a8c61611212bad'," + " 'extraBalanceAccount':'0x4486a3d68fac6967006d7a517b889fd3f98c102b'" + " }," + " { " + " 'address':'0x9c15b54878ba618f494b38f0ae7443db6af648ba'," + " 'extraBalanceAccount':'0x27b137a85656544b1ccb5a0f2e561a5703c6a68f'" + " }," + " { " + " 'address':'0x21c7fdb9ed8d291d79ffd82eb2c4356ec0d81241'," + " 'extraBalanceAccount':'0x23b75c2f6791eef49c69684db4c6c1f93bf49a50'" + " }," + " { " + " 'address':'0x1ca6abd14d30affe533b24d7a21bff4c2d5e1f3b'," + " 'extraBalanceAccount':'0xb9637156d330c0d605a791f1c31ba5890582fe1c'" + " }," + " { " + " 'address':'0x6131c42fa982e56929107413a9d526fd99405560'," + " 'extraBalanceAccount':'0x1591fc0f688c81fbeb17f5426a162a7024d430c2'" + " }," + " { " + " 'address':'0x542a9515200d14b68e934e9830d91645a980dd7a'," + " 'extraBalanceAccount':'0xc4bbd073882dd2add2424cf47d35213405b01324'" + " }," + " { " + " 'address':'0x782495b7b3355efb2833d56ecb34dc22ad7dfcc4'," + " 'extraBalanceAccount':'0x58b95c9a9d5d26825e70a82b6adb139d3fd829eb'" + " }," + " { " + " 'address':'0x3ba4d81db016dc2890c81f3acec2454bff5aada5'," + " 'extraBalanceAccount':'0xb52042c8ca3f8aa246fa79c3feaa3d959347c0ab'" + " }," + " { " + " 'address':'0xe4ae1efdfc53b73893af49113d8694a057b9c0d1'," + " 'extraBalanceAccount':'0x3c02a7bc0391e86d91b7d144e61c2c01a25a79c5'" + " }," + " { " + " 'address':'0x0737a6b837f97f46ebade41b9bc3e1c509c85c53'," + " 'extraBalanceAccount':'0x97f43a37f595ab5dd318fb46e7a155eae057317a'" + " }," + " { " + " 'address':'0x52c5317c848ba20c7504cb2c8052abd1fde29d03'," + " 'extraBalanceAccount':'0x4863226780fe7c0356454236d3b1c8792785748d'" + " }," + " { " + " 'address':'0x5d2b2e6fcbe3b11d26b525e085ff818dae332479'," + " 'extraBalanceAccount':'0x5f9f3392e9f62f63b8eac0beb55541fc8627f42c'" + " }," + " { " + " 'address':'0x057b56736d32b86616a10f619859c6cd6f59092a'," + " 'extraBalanceAccount':'0x9aa008f65de0b923a2a4f02012ad034a5e2e2192'" + " }," + " { " + " 'address':'0x304a554a310c7e546dfe434669c62820b7d83490'," + " 'extraBalanceAccount':'0x914d1b8b43e92723e64fd0a06f5bdb8dd9b10c79'" + " }," + " { " + " 'address':'0x4deb0033bb26bc534b197e61d19e0733e5679784'," + " 'extraBalanceAccount':'0x07f5c1e1bc2c93e0402f23341973a0e043f7bf8a'" + " }," + " { " + " 'address':'0x35a051a0010aba705c9008d7a7eff6fb88f6ea7b'," + " 'extraBalanceAccount':'0x4fa802324e929786dbda3b8820dc7834e9134a2a'" + " }," + " { " + " 'address':'0x9da397b9e80755301a3b32173283a91c0ef6c87e'," + " 'extraBalanceAccount':'0x8d9edb3054ce5c5774a420ac37ebae0ac02343c6'" + " }," + " { " + " 'address':'0x0101f3be8ebb4bbd39a2e3b9a3639d4259832fd9'," + " 'extraBalanceAccount':'0x5dc28b15dffed94048d73806ce4b7a4612a1d48f'" + " }," + " { " + " 'address':'0xbcf899e6c7d9d5a215ab1e3444c86806fa854c76'," + " 'extraBalanceAccount':'0x12e626b0eebfe86a56d633b9864e389b45dcb260'" + " }," + " { " + " 'address':'0xa2f1ccba9395d7fcb155bba8bc92db9bafaeade7'," + " 'extraBalanceAccount':'0xec8e57756626fdc07c63ad2eafbd28d08e7b0ca5'" + " }," + " { " + " 'address':'0xd164b088bd9108b60d0ca3751da4bceb207b0782'," + " 'extraBalanceAccount':'0x6231b6d0d5e77fe001c2a460bd9584fee60d409b'" + " }," + " { " + " 'address':'0x1cba23d343a983e9b5cfd19496b9a9701ada385f'," + " 'extraBalanceAccount':'0xa82f360a8d3455c5c41366975bde739c37bfeb8a'" + " }," + " { " + " 'address':'0x9fcd2deaff372a39cc679d5c5e4de7bafb0b1339'," + " 'extraBalanceAccount':'0x005f5cee7a43331d5a3d3eec71305925a62f34b6'" + " }," + " { " + " 'address':'0x0e0da70933f4c7849fc0d203f5d1d43b9ae4532d'," + " 'extraBalanceAccount':'0xd131637d5275fd1a68a3200f4ad25c71a2a9522e'" + " }," + " { " + " 'address':'0xbc07118b9ac290e4622f5e77a0853539789effbe'," + " 'extraBalanceAccount':'0x47e7aa56d6bdf3f36be34619660de61275420af8'" + " }," + " { " + " 'address':'0xacd87e28b0c9d1254e868b81cba4cc20d9a32225'," + " 'extraBalanceAccount':'0xadf80daec7ba8dcf15392f1ac611fff65d94f880'" + " }," + " { " + " 'address':'0x5524c55fb03cf21f549444ccbecb664d0acad706'," + " 'extraBalanceAccount':'0x40b803a9abce16f50f36a77ba41180eb90023925'" + " }," + " { " + " 'address':'0xfe24cdd8648121a43a7c86d289be4dd2951ed49f'," + " 'extraBalanceAccount':'0x17802f43a0137c506ba92291391a8a8f207f487d'" + " }," + " { " + " 'address':'0x253488078a4edf4d6f42f113d1e62836a942cf1a'," + " 'extraBalanceAccount':'0x86af3e9626fce1957c82e88cbf04ddf3a2ed7915'" + " }," + " { " + " 'address':'0xb136707642a4ea12fb4bae820f03d2562ebff487'," + " 'extraBalanceAccount':'0xdbe9b615a3ae8709af8b93336ce9b477e4ac0940'" + " }," + " { " + " 'address':'0xf14c14075d6c4ed84b86798af0956deef67365b5'," + " 'extraBalanceAccount':'0xca544e5c4687d109611d0f8f928b53a25af72448'" + " }," + " { " + " 'address':'0xaeeb8ff27288bdabc0fa5ebb731b6f409507516c'," + " 'extraBalanceAccount':'0xcbb9d3703e651b0d496cdefb8b92c25aeb2171f7'" + " }," + " { " + " 'address':'0x6d87578288b6cb5549d5076a207456a1f6a63dc0'," + " 'extraBalanceAccount':'0xb2c6f0dfbb716ac562e2d85d6cb2f8d5ee87603e'" + " }," + " { " + " 'address':'0xaccc230e8a6e5be9160b8cdf2864dd2a001c28b6'," + " 'extraBalanceAccount':'0x2b3455ec7fedf16e646268bf88846bd7a2319bb2'" + " }," + " { " + " 'address':'0x4613f3bca5c44ea06337a9e439fbc6d42e501d0a'," + " 'extraBalanceAccount':'0xd343b217de44030afaa275f54d31a9317c7f441e'" + " }," + " { " + " 'address':'0x84ef4b2357079cd7a7c69fd7a37cd0609a679106'," + " 'extraBalanceAccount':'0xda2fef9e4a3230988ff17df2165440f37e8b1708'" + " }," + " { " + " 'address':'0xf4c64518ea10f995918a454158c6b61407ea345c'," + " 'extraBalanceAccount':'0x7602b46df5390e432ef1c307d4f2c9ff6d65cc97'" + " }," + " { " + " 'address':'0xbb9bc244d798123fde783fcc1c72d3bb8c189413'," + " 'extraBalanceAccount':'0x807640a13483f8ac783c557fcdf27be11ea4ac7a'" + " }" + "]" } }
mit
fd8a79e3a2c78758ef002b6690dd71ef
49.717718
110
0.523832
3.022369
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/codeVision/DaemonBoundCodeVisionProvider.kt
2
2675
// 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.codeInsight.hints.codeVision import com.intellij.codeInsight.codeVision.CodeVisionAnchorKind import com.intellij.codeInsight.codeVision.CodeVisionEntry import com.intellij.codeInsight.codeVision.CodeVisionPlaceholderCollector import com.intellij.codeInsight.codeVision.CodeVisionRelativeOrdering import com.intellij.codeInsight.codeVision.ui.model.CodeVisionPredefinedActionEntry import com.intellij.openapi.editor.Editor import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls /** * Almost the same thing as [com.intellij.codeInsight.codeVision.CodeVisionProvider], but run in the [com.intellij.codeInsight.daemon.DaemonCodeAnalyzer] * and that's why it has built-in support of interruption. */ interface DaemonBoundCodeVisionProvider { companion object { const val EP_NAME: String = "com.intellij.codeInsight.daemonBoundCodeVisionProvider" val extensionPoint: ExtensionPointName<DaemonBoundCodeVisionProvider> = ExtensionPointName.create(EP_NAME) } fun preparePreview(editor: Editor, file: PsiFile) { } /** * Computes code lens data in read action in background for a given editor. */ @Deprecated("Use overload with file") fun computeForEditor(editor: Editor): List<Pair<TextRange, CodeVisionEntry>> = emptyList() /** * Computes code lens data in read action in background for a given editor. */ @Suppress("DEPRECATION") fun computeForEditor(editor: Editor, file: PsiFile): List<Pair<TextRange, CodeVisionEntry>> = emptyList() fun handleClick(editor: Editor, textRange: TextRange, entry: CodeVisionEntry){ if (entry is CodeVisionPredefinedActionEntry) entry.onClick(editor) } /** * Calls on background BEFORE editor opening * Returns ranges where placeholders should be when editor opens */ @Deprecated("use getPlaceholderCollector") fun collectPlaceholders(editor: Editor): List<TextRange> = emptyList() fun getPlaceholderCollector(editor: Editor, psiFile: PsiFile?): CodeVisionPlaceholderCollector? = null /** * Name in settings. */ @get:Nls val name: String val relativeOrderings: List<CodeVisionRelativeOrdering> val defaultAnchor: CodeVisionAnchorKind /** * Unique identifier (among all instances of [DaemonBoundCodeVisionProvider] and [com.intellij.codeInsight.codeVision.CodeVisionProvider]) */ @get:NonNls val id: String val groupId: String get() = id }
apache-2.0
a09198dbf9fd5264011ca2f8d22cedc9
35.657534
153
0.781682
4.636049
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/RemovePropertyReceiverAfter.kt
13
371
open class A { open var p: Int = 1 } class AA : A() { override var p: Int = 1 } class B : J() { override var p: Int = 1 } fun test() { with(A()) { val t = p p = 3 } with(AA()) { val t = p p = 3 } with(J()) { val t = p p = 3 } with(B()) { val t = p p = 3 } }
apache-2.0
86243f566a71ef8a0e4e3ba437da0a00
10.272727
27
0.336927
2.944444
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/compiler-plugins/allopen/maven/src/org/jetbrains/kotlin/idea/compilerPlugin/allopen/maven/AllOpenMavenProjectImportHandler.kt
1
1919
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.compilerPlugin.allopen.maven import org.jetbrains.kotlin.allopen.AllOpenCommandLineProcessor import org.jetbrains.kotlin.idea.maven.compilerPlugin.annotationBased.AbstractMavenImportHandler import org.jetbrains.kotlin.idea.compilerPlugin.AnnotationBasedCompilerPluginSetup.PluginOption import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts class AllOpenMavenProjectImportHandler : AbstractMavenImportHandler() { private companion object { val ANNOTATION_PARAMETER_PREFIX = "all-open:${AllOpenCommandLineProcessor.ANNOTATION_OPTION.optionName}=" } override val compilerPluginId = AllOpenCommandLineProcessor.PLUGIN_ID override val pluginName = "allopen" override val mavenPluginArtifactName = "kotlin-maven-allopen" override val pluginJarFileFromIdea = KotlinArtifacts.instance.allopenCompilerPlugin override fun getOptions(enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String>): List<PluginOption>? { if ("all-open" !in enabledCompilerPlugins && "spring" !in enabledCompilerPlugins) { return null } val annotations = mutableListOf<String>() for ((presetName, presetAnnotations) in AllOpenCommandLineProcessor.SUPPORTED_PRESETS) { if (presetName in enabledCompilerPlugins) { annotations.addAll(presetAnnotations) } } annotations.addAll(compilerPluginOptions.mapNotNull { text -> if (!text.startsWith(ANNOTATION_PARAMETER_PREFIX)) return@mapNotNull null text.substring(ANNOTATION_PARAMETER_PREFIX.length) }) return annotations.map { PluginOption(AllOpenCommandLineProcessor.ANNOTATION_OPTION.optionName, it) } } }
apache-2.0
ca4961d22814f05e22ad3742597a27f7
46.975
158
0.755602
5.144772
false
false
false
false
vicpinm/KPresenterAdapter
sample/src/test/java/com.vicpin.sample.testjvm/ViewHolderLifecycleTests.kt
1
3757
package com.vicpin.sample.testjvm import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.test.core.app.launchActivity import androidx.test.ext.junit.runners.AndroidJUnit4 import com.nhaarman.mockitokotlin2.* import com.vicpin.kpresenteradapter.PresenterAdapter import com.vicpin.sample.R import com.vicpin.sample.di.Injector import com.vicpin.sample.model.Country import com.vicpin.sample.model.IRepository import com.vicpin.sample.view.presenter.CountryPresenter import com.vicpin.sample.view.activity.ManualBindingActivity import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ViewHolderLifecycleTests { private val TEST_PAGE_SIZE = 10 private var testRepository = TestRepository(TEST_PAGE_SIZE) private lateinit var countryPresenter: CountryPresenter @Before fun setUp() { //We will use a spied injector, in order to return a specific presenter instance when requested Injector.set(spy(Injector.get())) Injector.get().setCountryRepository(testRepository) //We sill use a spied country presenter to verify lifecycle method invocations countryPresenter = spy(CountryPresenter()) whenever(Injector.get().getCountryPresenter()).thenReturn(countryPresenter) } @Test fun when_thereIsNoData_then_headerShowsNoItems() { //Given some items val itemsSize = 5 initRepositoryWihtCountries(itemsSize) //When: activity starts launchActivity<ManualBindingActivity>().onActivity { //Then: oncreate and onattached methods are called one time per item verify(countryPresenter, times(itemsSize)).onCreate() verify(countryPresenter, times(itemsSize)).onAttach() } } @Test fun when_scroll_then_onDetachedAndOnDestroyIsCalled() { //Given a large amount of items val itemsSize = 50 initRepositoryWihtCountries(itemsSize) //When: activity starts launchActivity<ManualBindingActivity>().onActivity { //Calculate visible amount of items when activity starts val recycler = it.findViewById<RecyclerView>(R.id.recycler) val lastPosition = (recycler.layoutManager as LinearLayoutManager).findLastVisibleItemPosition() val totalVisibleItems = lastPosition - (recycler.adapter as PresenterAdapter<Country>).getHeadersCount() + 1 //Then: verify that onCreate and onAttached is called for each item verify(countryPresenter, times(totalVisibleItems)).onCreate() verify(countryPresenter, times(totalVisibleItems)).onAttach() //After: scroll to second group of visible items onViewId(R.id.recycler).scrollTo(totalVisibleItems * 2) //Then: verify that onCreate and onAttached is called for each item again verify(countryPresenter, times(totalVisibleItems * 2)).onCreate() verify(countryPresenter, times(totalVisibleItems * 2)).onAttach() //Verify that onDetached is called for no visible items verify(countryPresenter, times(totalVisibleItems)).onDetach() //Verify that onDestroy is called at leas once (we cannot assure how many times is going to be called) verify(countryPresenter, atLeastOnce()).onDestroy() } } fun initRepositoryWihtCountries(size: Int) { testRepository.items = List(size) { Country("Country $it", R.mipmap.ic_launcher) } } } class TestRepository(pageSize: Int): IRepository<Country> { override val PAGE_SIZE = pageSize override var items = listOf<Country>() }
apache-2.0
f614b758ec3a8e93678097a0289ab66c
38.557895
120
0.713069
4.761724
false
true
false
false
timrijckaert/LottieSwipeRefreshLayout
lib/src/main/kotlin/be/rijckaert/tim/lib/LottiePullToRefreshLayout.kt
1
1613
package be.rijckaert.tim.lib import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import com.airbnb.lottie.LottieAnimationView import com.airbnb.lottie.LottieDrawable class LottiePullToRefreshLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : SimplePullToRefreshLayout(context, attrs, defStyle) { private var animationFile: Int = -1 private val lottieAnimationView by lazy { LottieAnimationView(context).apply { if (animationFile == -1) { throw IllegalStateException("Could not resolve an animation for your pull to refresh layout") } setAnimation(animationFile) repeatCount = LottieDrawable.INFINITE layoutParams = LayoutParams(ViewGroup.LayoutParams(MATCH_PARENT, triggerOffSetTop)).apply { type = ViewType.TOP_VIEW } } } init { context.theme.obtainStyledAttributes(attrs, R.styleable.LottiePullToRefreshLayout, defStyle, 0).let { style -> animationFile = style.getResourceId(R.styleable.LottiePullToRefreshLayout_pull_to_refresh_lottieFile, -1) addView(lottieAnimationView) style.recycle() } onProgressListener { lottieAnimationView.progress = it } onTriggerListener { lottieAnimationView.resumeAnimation() } } override fun stopRefreshing() { super.stopRefreshing() lottieAnimationView.pauseAnimation() } }
mit
a4912a1b852bdcde8a24a340af334468
34.065217
130
0.690639
5.056426
false
false
false
false
deltadak/plep
src/main/kotlin/nl/deltadak/plep/ui/gridpane/GridPaneInitializer.kt
1
3662
package nl.deltadak.plep.ui.gridpane import javafx.scene.control.ProgressIndicator import javafx.scene.control.TreeItem import javafx.scene.control.TreeView import javafx.scene.layout.AnchorPane import javafx.scene.layout.GridPane import nl.deltadak.plep.HomeworkTask import nl.deltadak.plep.commands.UndoFacility import nl.deltadak.plep.database.ContentProvider import nl.deltadak.plep.database.settingsdefaults.SettingsDefaults import nl.deltadak.plep.database.tables.Settings import nl.deltadak.plep.keylisteners.TaskDeletionInitialiser import nl.deltadak.plep.ui.taskcell.TaskCell import nl.deltadak.plep.ui.treeview.getTreeViewHeight import nl.deltadak.plep.ui.treeview.getTreeViewWidth import java.time.LocalDate import kotlin.reflect.KMutableProperty /** * Initializes the whole UI of the GridPane. */ class GridPaneInitializer( /** Facility which provides deletion. */ private val undoFacility: UndoFacility, /** User feedback. */ val progressIndicator: ProgressIndicator) { /** * Sets up TreeViews for each day, including the editing of items and more. * * @param gridPane The GridPane to setup. * @param numberOfDaysProperty The total number of days to setup the gridpane with. Pass reference instead of value, with ::numberOfDays. * @param focusDateProperty This date is the central date in the sense it is shown as the second day, which is by default today. Pass reference instead of value, with ::focusDate. */ fun setup(gridPane: GridPane, numberOfDaysProperty: KMutableProperty<Int>, focusDateProperty: KMutableProperty<LocalDate>, toolBarHeight: Double) { val numberOfDays = numberOfDaysProperty.getter.call() val focusDate = focusDateProperty.getter.call() // Anchor the main GridPane to the bottom of the Toolbar. AnchorPane.setTopAnchor(gridPane, toolBarHeight) //toolBar.prefHeight // First clear the GridPane, especially of the day text. gridPane.children.clear() // Find out whether the number of columns should be calculated automatically or is user overridden. val isAutoColumns: Boolean = Settings.get(SettingsDefaults.MAX_COLUMNS_AUTO).toBoolean() val nrColumns = if (isAutoColumns) { Math.ceil(Math.sqrt(numberOfDays.toDouble())).toInt() } else { Settings.get(SettingsDefaults.MAX_COLUMNS).toInt() } // For every day, add a list for that day. for (index in 0 until numberOfDays) { // The day to add, starting from the day before the focusDate. val date = focusDate.plusDays(index.toLong() - 1 ) // Initialize the TreeView. val rootItem = TreeItem<HomeworkTask>(HomeworkTask()) rootItem.isExpanded = true val tree = TreeView<HomeworkTask>(rootItem) tree.isEditable = true tree.setCellFactory { TaskCell(tree, date).apply { setup(progressIndicator, gridPane, focusDate) } } tree.isShowRoot = false // Add the tree with title to the GridPane. TreeContainer(tree, date).addTreeToGridPane(gridPane, index, nrColumns) // Request the content to be set. ContentProvider().setForOneDay(tree, date, progressIndicator) // Setup deletion of tasks. TaskDeletionInitialiser(progressIndicator, undoFacility).addDeleteKeyListener(tree, localDate = date) tree.prefWidth = getTreeViewWidth(nrColumns).toDouble() tree.prefHeight = getTreeViewHeight(nrColumns, numberOfDays).toDouble() } } }
mit
ba73ab18252c56953f970c1cae760efd
39.7
183
0.702622
4.641318
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/pattern/url/PatternUrlActivity.kt
1
24384
/* * Copyright (C) 2017-2021 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.pattern.url import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ResolveInfo import android.net.Uri import android.os.Bundle import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.* import androidx.fragment.app.DialogFragment import jp.hazuki.yuzubrowser.adblock.filter.fastmatch.FastMatcherFactory import jp.hazuki.yuzubrowser.core.utility.extensions.hideIme import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.databinding.PatternAddWebsettingBinding import jp.hazuki.yuzubrowser.legacy.pattern.PatternAction import jp.hazuki.yuzubrowser.legacy.pattern.PatternActivity import jp.hazuki.yuzubrowser.legacy.pattern.action.OpenOthersPatternAction import jp.hazuki.yuzubrowser.legacy.pattern.action.WebSettingPatternAction import jp.hazuki.yuzubrowser.legacy.useragent.UserAgentListActivity import jp.hazuki.yuzubrowser.legacy.utils.WebUtils import java.util.* import java.util.regex.PatternSyntaxException class PatternUrlActivity : PatternActivity<PatternUrlChecker>() { private lateinit var urlEditText: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.setDisplayHomeAsUpEnabled(true) val headerView = layoutInflater.inflate(R.layout.pattern_list_url, null) urlEditText = headerView.findViewById(R.id.urlEditText) addHeaderView(headerView) if (intent != null) { urlEditText.setText(intent.getStringExtra(Intent.EXTRA_TEXT)) } setPatternManager(PatternUrlManager(applicationContext)) } private fun makeHeaderView(checker: PatternUrlChecker?): View { val headerView = layoutInflater.inflate(R.layout.pattern_list_url, null) val editText: EditText = headerView.findViewById(R.id.urlEditText) val url: CharSequence if (checker == null) { url = urlEditText.text urlEditText.text = null } else { url = checker.patternUrl ?: "" } editText.setText(url) return headerView } override fun getWebSettingDialog(checker: PatternUrlChecker?): androidx.fragment.app.DialogFragment { return SettingWebDialog.getInstance(getPosition(checker), checker) } override fun getOpenOtherDialog(checker: PatternUrlChecker?): androidx.fragment.app.DialogFragment { return OpenOtherDialog.newInstance(getPosition(checker), checker, urlEditText.text.toString()) } override fun settingBlockAction(checker: PatternUrlChecker?, header_view: View?) { super.settingBlockAction(checker, makeHeaderView(checker)) } override fun makeActionChecker(pattern_action: PatternAction, header_view: View): PatternUrlChecker? { val patternUrl = (header_view.findViewById<View>(R.id.urlEditText) as EditText).text.toString() try { val checker = PatternUrlChecker(pattern_action, FastMatcherFactory(), patternUrl) urlEditText.setText("") return checker } catch (e: PatternSyntaxException) { ErrorReport.printAndWriteLog(e) Toast.makeText(applicationContext, R.string.pattern_syntax_error, Toast.LENGTH_SHORT).show() } return null } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } class SettingWebDialog : DialogFragment() { private lateinit var header: View private lateinit var layout: SettingWebDialogView override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val arguments = arguments ?: throw IllegalArgumentException() val checker = arguments.getSerializable(CHECKER) as? PatternUrlChecker val binding = PatternAddWebsettingBinding.inflate(requireActivity().layoutInflater) if (activity is PatternUrlActivity) { header = (activity as PatternUrlActivity).makeHeaderView(checker) binding.headerFrame.addView(header) } layout = SettingWebDialogView(binding).apply { init(checker) } val alertDialog = AlertDialog.Builder(activity) .setTitle(R.string.pattern_change_websettings) .setView(binding.root) .setPositiveButton(android.R.string.ok, null) .setNegativeButton(android.R.string.cancel, null) .create() alertDialog.setOnShowListener { alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener { val action = layout.getAction() if (activity is PatternUrlActivity) { val newChecker = (activity as PatternUrlActivity).makeActionChecker(action, header) if (newChecker != null) { val id = arguments.getInt(ID) (activity as PatternUrlActivity).add(id, newChecker) dismiss() } } } } return alertDialog } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { layout.handleResult(requestCode, resultCode, data) } companion object { private const val ID = "id" private const val CHECKER = "checker" private const val REQUEST_USER_AGENT = 1 fun getInstance(id: Int, checker: PatternUrlChecker?): androidx.fragment.app.DialogFragment { val fragment = SettingWebDialog() val bundle = Bundle() bundle.putInt(ID, id) bundle.putSerializable(CHECKER, checker) fragment.arguments = bundle return fragment } } private inner class SettingWebDialogView(val binding: PatternAddWebsettingBinding) { fun init(checker: PatternUrlChecker?) { setData(checker) setListeners() } fun getAction(): WebSettingPatternAction { binding.apply { var ua: String? = null if (uaCheckBox.isChecked) { ua = uaEditText.text.toString() } var js = WebSettingPatternAction.UNDEFINED if (jsCheckBox.isChecked) { js = if (jsSwitch.isChecked) { WebSettingPatternAction.ENABLE } else { WebSettingPatternAction.DISABLE } } var navLock = WebSettingPatternAction.UNDEFINED if (navLockCheckBox.isChecked) { navLock = if (navLockSwitch.isChecked) { WebSettingPatternAction.ENABLE } else { WebSettingPatternAction.DISABLE } } var image = WebSettingPatternAction.UNDEFINED if (loadImageCheckBox.isChecked) { image = if (loadImageSwitch.isChecked) { WebSettingPatternAction.ENABLE } else { WebSettingPatternAction.DISABLE } } var cookie = WebSettingPatternAction.UNDEFINED if (cookieCheckBox.isChecked) { cookie = if (cookieSwitch.isChecked) { WebSettingPatternAction.ENABLE } else { WebSettingPatternAction.DISABLE } } var thirdCookie = WebSettingPatternAction.UNDEFINED if (thirdCookieCheckBox.isChecked) { thirdCookie = if (thirdCookieSwitch.isChecked) { WebSettingPatternAction.ENABLE } else { WebSettingPatternAction.DISABLE } } var renderingMode = WebSettingPatternAction.UNDEFINED_RENDERING if (renderingModeCheckBox.isChecked) { renderingMode = renderingModeSpinner.selectedItemPosition } var webTheme = WebSettingPatternAction.UNDEFINED_RENDERING if (webThemeCheckBox.isChecked) { webTheme = webThemeSpinner.selectedItemPosition } return WebSettingPatternAction( ua, js, navLock, image, cookie, thirdCookie, renderingMode, webTheme, ) } } private fun setData(checker: PatternUrlChecker?) = binding.apply { if (checker == null) { uaEditText.isEnabled = false uaButton.isEnabled = false jsSwitch.isEnabled = false navLockSwitch.isEnabled = false loadImageSwitch.isEnabled = false cookieSwitch.isEnabled = false thirdCookieSwitch.isEnabled = false renderingModeSpinner.isEnabled = false webThemeSpinner.isEnabled = false } else { val action = checker.action as WebSettingPatternAction val ua = action.userAgentString uaCheckBox.isChecked = ua != null if (ua != null) { uaEditText.setText(ua) } else { uaEditText.isEnabled = false uaButton.isEnabled = false } when (action.javaScriptSetting) { WebSettingPatternAction.UNDEFINED -> { jsCheckBox.isChecked = false jsSwitch.isChecked = false jsSwitch.isEnabled = false } WebSettingPatternAction.ENABLE -> { jsCheckBox.isChecked = true jsSwitch.isChecked = true } WebSettingPatternAction.DISABLE -> { jsCheckBox.isChecked = true jsSwitch.isChecked = false } } when (action.navLock) { WebSettingPatternAction.UNDEFINED -> { navLockCheckBox.isChecked = false navLockSwitch.isChecked = false navLockSwitch.isEnabled = false } WebSettingPatternAction.ENABLE -> { navLockCheckBox.isChecked = true navLockSwitch.isChecked = true } WebSettingPatternAction.DISABLE -> { navLockCheckBox.isChecked = true navLockSwitch.isChecked = false } } when (action.loadImage) { WebSettingPatternAction.UNDEFINED -> { loadImageCheckBox.isChecked = false loadImageSwitch.isChecked = false loadImageSwitch.isEnabled = false } WebSettingPatternAction.ENABLE -> { loadImageCheckBox.isChecked = true loadImageSwitch.isChecked = true } WebSettingPatternAction.DISABLE -> { loadImageCheckBox.isChecked = true loadImageSwitch.isChecked = false } } when (action.cookie) { WebSettingPatternAction.UNDEFINED -> { cookieCheckBox.isChecked = false cookieSwitch.isChecked = false cookieSwitch.isEnabled = false } WebSettingPatternAction.ENABLE -> { cookieCheckBox.isChecked = true cookieSwitch.isChecked = true } WebSettingPatternAction.DISABLE -> { cookieCheckBox.isChecked = true cookieSwitch.isChecked = false } } when (action.thirdCookie) { WebSettingPatternAction.UNDEFINED -> { thirdCookieCheckBox.isChecked = false thirdCookieSwitch.isChecked = false thirdCookieSwitch.isEnabled = false } WebSettingPatternAction.ENABLE -> { thirdCookieCheckBox.isChecked = true thirdCookieSwitch.isChecked = true } WebSettingPatternAction.DISABLE -> { thirdCookieCheckBox.isChecked = true thirdCookieSwitch.isChecked = false } } if (action.renderingMode < 0) { renderingModeCheckBox.isChecked = false renderingModeSpinner.isEnabled = false renderingModeSpinner.setSelection(0) } else { renderingModeCheckBox.isChecked = true renderingModeSpinner.isEnabled = true renderingModeSpinner.setSelection(action.renderingMode) } if (action.webTheme < 0) { webThemeCheckBox.isChecked = false webThemeSpinner.isEnabled = false webThemeSpinner.setSelection(0) } else { webThemeCheckBox.isChecked = true webThemeSpinner.isEnabled = true webThemeSpinner.setSelection(action.webTheme) } } } fun handleResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_USER_AGENT && resultCode == RESULT_OK) { binding.uaEditText.setText(data?.getStringExtra(Intent.EXTRA_TEXT)) } } private fun setListeners() = binding.apply { uaCheckBox.setOnCheckedChangeListener { _, b -> uaEditText.isEnabled = b uaButton.isEnabled = b } uaButton.setOnClickListener { val intent = Intent(activity, UserAgentListActivity::class.java) intent.putExtra(Intent.EXTRA_TEXT, uaEditText.text.toString()) startActivityForResult(intent, REQUEST_USER_AGENT) } jsCheckBox.setOnCheckedChangeListener { _, b -> jsSwitch.isEnabled = b } navLockCheckBox.setOnCheckedChangeListener { _, b -> navLockSwitch.isEnabled = b } loadImageCheckBox.setOnCheckedChangeListener { _, b -> loadImageSwitch.isEnabled = b } cookieCheckBox.setOnCheckedChangeListener { _, b -> cookieSwitch.isEnabled = b } thirdCookieCheckBox.setOnCheckedChangeListener { _, b -> thirdCookieSwitch.isEnabled = b } renderingModeCheckBox.setOnCheckedChangeListener { _, b -> renderingModeSpinner.isEnabled = b } webThemeCheckBox.setOnFocusChangeListener { _, b -> webThemeSpinner.isEnabled = b } } } } class OpenOtherDialog : DialogFragment() { private var patternActivity: PatternUrlActivity? = null private lateinit var intent: Intent override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val activity = activity ?: throw IllegalStateException() val arguments = arguments ?: throw IllegalArgumentException() var url = arguments.getString(URL) val checker = arguments.getSerializable(CHECKER) as? PatternUrlChecker val headerView = View.inflate(activity, R.layout.pattern_list_url, null) val urlEditText = headerView.findViewById<EditText>(R.id.urlEditText) if (checker != null) { url = checker.patternUrl } if (url == null) { url = "" } urlEditText.setText(url) val view = View.inflate(activity, R.layout.pattern_add_open, null) as ViewGroup view.addView(headerView, 0) val listView = view.findViewById<ListView>(R.id.listView) val pm = activity.packageManager val intentUrl = url.replace("*", "") intent = Intent(Intent.ACTION_VIEW, Uri.parse(if (WebUtils.maybeContainsUrlScheme(intentUrl)) intentUrl else "http://$intentUrl")) val openAppList = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL) Collections.sort(openAppList, ResolveInfo.DisplayNameComparator(pm)) val arrayAdapter = object : ArrayAdapter<ResolveInfo>(activity, 0, openAppList) { private val app_icon_size = resources.getDimension(android.R.dimen.app_icon_size).toInt() override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var v = convertView if (v == null) { v = View.inflate(activity, R.layout.image_text_list_item, null) val imageView = v!!.findViewById<ImageView>(R.id.imageView) val params = imageView.layoutParams params.height = app_icon_size params.width = app_icon_size imageView.layoutParams = params } val imageView = v.findViewById<ImageView>(R.id.imageView) val textView = v.findViewById<TextView>(R.id.textView) if (position == 0) { imageView.setImageDrawable(null) textView.text = getString(R.string.pattern_open_app_list) } else { val item = getItem(position) imageView.setImageDrawable(item!!.loadIcon(pm)) textView.text = item.loadLabel(pm) } return v } override fun getItem(position: Int): ResolveInfo? { return super.getItem(position - 1) } override fun getCount(): Int { return super.getCount() + 1 } } listView.adapter = arrayAdapter val builder = AlertDialog.Builder(activity) .setTitle(R.string.pattern_open_others) .setView(view) .setNegativeButton(android.R.string.cancel, null) if (checker != null) builder.setPositiveButton(android.R.string.ok) { _, _ -> val newChecker = patternActivity!!.makeActionChecker(checker.action, headerView) if (newChecker != null) { patternActivity!!.add(arguments.getInt(ID), newChecker) } } listView.setOnItemClickListener { _, _, position, _ -> val pattern = if (position == 0) { OpenOthersPatternAction(OpenOthersPatternAction.TYPE_APP_LIST) } else { val item = openAppList[position - 1] intent.setClassName(item.activityInfo.packageName, item.activityInfo.name) OpenOthersPatternAction(intent) } val newChecker = patternActivity!!.makeActionChecker(pattern, headerView) if (newChecker != null) { patternActivity!!.add(arguments.getInt(ID), newChecker) dismiss() } } listView.setOnItemLongClickListener { _, _, position, _ -> if (position == 0) { val newPattern = OpenOthersPatternAction(OpenOthersPatternAction.TYPE_APP_CHOOSER) val newChecker = patternActivity!!.makeActionChecker(newPattern, headerView) if (newChecker != null) { patternActivity!!.add(arguments.getInt(ID), newChecker) dismiss() } } true } urlEditText.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { activity.hideIme(urlEditText) val url1 = urlEditText.text.toString() intent = Intent(Intent.ACTION_VIEW, Uri.parse(if (WebUtils.maybeContainsUrlScheme(url1)) url1 else "http://$url1")) val newOpenAppList = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL) Collections.sort(newOpenAppList, ResolveInfo.DisplayNameComparator(pm)) arrayAdapter.clear() arrayAdapter.addAll(newOpenAppList) arrayAdapter.notifyDataSetChanged() return@setOnEditorActionListener true } false } return builder.create() } override fun onAttach(context: Context) { super.onAttach(context) patternActivity = activity as PatternUrlActivity } override fun onDetach() { super.onDetach() patternActivity = null } companion object { private const val ID = "id" private const val CHECKER = "checker" private const val URL = "url" fun newInstance(id: Int, checker: PatternUrlChecker?, url: String): OpenOtherDialog { val dialog = OpenOtherDialog() val bundle = Bundle() bundle.putInt(ID, id) bundle.putSerializable(CHECKER, checker) bundle.putString(URL, url) dialog.arguments = bundle return dialog } } } }
apache-2.0
0e71a7d09a03301dc1c0ebbcfc9f23a8
41.406957
135
0.536499
5.825131
false
false
false
false
kvnxiao/meirei
meirei-core/src/test/kotlin/com/github/kvnxiao/discord/meirei/jda/tests/annotated/AnnotatedCommand.kt
1
1722
/* * Copyright (C) 2017-2018 Ze Hao Xiao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.kvnxiao.discord.meirei.jda.tests.annotated import com.github.kvnxiao.discord.meirei.annotations.Command import com.github.kvnxiao.discord.meirei.annotations.CommandGroup import com.github.kvnxiao.discord.meirei.annotations.RegistryAware @CommandGroup("test.annotated.grouped") class AnnotatedCommand { @Command( id = "parent", aliases = ["parent"], prefix = "/" ) fun parent() = Unit @Command( id = "child", parentId = "parent", aliases = ["child"] ) fun child() = Unit @Command( id = "third", parentId = "child", aliases = ["third"] ) fun third() = Unit @Command( id = "fourth", parentId = "third", aliases = ["fourth"] ) @RegistryAware fun fourth() = Unit @Command( id = "beta", parentId = "child", aliases = ["beta"] ) fun beta() = Unit @Command( id = "charlie", parentId = "beta", aliases = ["charlie"] ) @RegistryAware fun charlie() = Unit }
apache-2.0
15ad63961eb0b5ebdc50942b8b5ca04b
24.323529
77
0.611498
4.023364
false
false
false
false
serorigundam/numeri3
app/src/main/kotlin/net/ketc/numeri/presentation/view/activity/ui/CreateDisplayGroupActivityUI.kt
1
1706
package net.ketc.numeri.presentation.view.activity.ui import android.support.v7.widget.Toolbar import android.text.InputType import android.widget.EditText import android.widget.LinearLayout import net.ketc.numeri.R import net.ketc.numeri.presentation.view.activity.CreateDisplayGroupActivity import org.jetbrains.anko.* import org.jetbrains.anko.appcompat.v7.toolbar import org.jetbrains.anko.design.appBarLayout import org.jetbrains.anko.design.textInputLayout class CreateDisplayGroupActivityUI : ICreateDisplayGroupActivityUI { override lateinit var groupNameEdit: EditText private set override lateinit var toolbar: Toolbar private set override fun createView(ui: AnkoContext<CreateDisplayGroupActivity>) = with(ui) { linearLayout { orientation = LinearLayout.VERTICAL lparams(matchParent, matchParent) appBarLayout { id = R.id.app_bar toolbar = toolbar { id = R.id.toolbar }.lparams(matchParent, wrapContent) }.lparams(matchParent, wrapContent) textInputLayout { groupNameEdit = editText { id = R.id.column_group_name_edit lines = 1 inputType = InputType.TYPE_CLASS_TEXT hint = context.getString(R.string.hint_input_column_group_name) } }.lparams(matchParent, wrapContent) { margin = dimen(R.dimen.margin_medium) } } } } interface ICreateDisplayGroupActivityUI : AnkoComponent<CreateDisplayGroupActivity> { val groupNameEdit: EditText val toolbar: Toolbar }
mit
9f6e03dcbc0fa0db40b1f7040838517a
33.14
85
0.658265
4.888252
false
false
false
false
serorigundam/numeri3
app/src/main/kotlin/net/ketc/numeri/presentation/view/component/ui/TweetViewUI.kt
1
7106
package net.ketc.numeri.presentation.view.component.ui import android.content.Context import android.text.TextUtils import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import net.ketc.numeri.R import net.ketc.numeri.util.android.endOf import net.ketc.numeri.util.android.startOf import net.ketc.numeri.util.toImmutableList import org.jetbrains.anko.* class TweetViewUI(override val ctx: Context) : ITweetViewUI { override lateinit var iconImage: ImageView private set override lateinit var subInfoIcon: ImageView private set override lateinit var subInfoText: TextView private set override lateinit var screenNameText: TextView private set override lateinit var userNameText: TextView private set override lateinit var createdAtText: TextView private set override lateinit var text: TextView private set override val thumbnails: List<Pair<FrameLayout, ImageView>> get() = mThumbnails.toImmutableList() private val mThumbnails = ArrayList<Pair<FrameLayout, ImageView>>() override lateinit var sourceText: TextView private set override lateinit var overlayRelative: RelativeLayout private set override fun createView(): View = ctx.frameLayout { lparams(matchParent, wrapContent) relativeLayout { overlayRelative = this id = R.id.overlay_relative lparams(matchParent, wrapContent) { padding = dimen(R.dimen.margin_small) } frameLayout { backgroundColor = ctx.getColor(R.color.image_background_transparency) id = R.id.icon_image imageView { iconImage = this backgroundColor = ctx.getColor(R.color.transparent) } }.lparams(dimen(R.dimen.image_icon), dimen(R.dimen.image_icon)) { alignParentLeft() below(R.id.sub_info_text) marginEnd = dimen(R.dimen.margin_small) } imageView { subInfoIcon = this id = R.id.sub_info_icon }.lparams(dip(16), dip(16)) { alignEnd(R.id.icon_image) bottomMargin = dimen(R.dimen.margin_text_small) } textView { subInfoText = this id = R.id.sub_info_text lines = 1 ellipsize = TextUtils.TruncateAt.END visibility = View.GONE }.lparams(matchParent, wrapContent) { endOf(R.id.icon_image) startOf(R.id.twitter_bird_image) bottomMargin = dimen(R.dimen.margin_text_small) } imageView { id = R.id.twitter_bird_image setImageDrawable(ctx.getDrawable(R.drawable.ic_twitter_circle_white)) }.lparams(dip(16), dip(16)) { alignParentTop() alignParentEnd() bottomMargin = dimen(R.dimen.margin_text_small) } textView { userNameText = this id = R.id.user_name_text lines = 1 ellipsize = TextUtils.TruncateAt.END }.lparams(wrapContent, wrapContent) { below(R.id.sub_info_text) endOf(R.id.icon_image) startOf(R.id.created_at_text) marginEnd = dimen(R.dimen.margin_text_small) } textView { screenNameText = this id = R.id.screen_name_text lines = 1 ellipsize = TextUtils.TruncateAt.END }.lparams(wrapContent, wrapContent) { bottomOf(R.id.user_name_text) endOf(R.id.icon_image) startOf(R.id.created_at_text) marginEnd = dimen(R.dimen.margin_text_small) } textView { createdAtText = this id = R.id.created_at_text lines = 1 }.lparams(wrapContent, wrapContent) { bottomOf(R.id.twitter_bird_image) alignParentEnd() } textView { [email protected] = this id = R.id.text }.lparams(wrapContent, wrapContent) { below(R.id.icon_image) endOf(R.id.icon_image) } thumbnails() textView { id = R.id.via_text text = context.getString(R.string.via) }.lparams(wrapContent, wrapContent) { endOf(R.id.icon_image) below(R.id.thumbnails_relative) topMargin = dimen(R.dimen.margin_text_small) marginEnd = dimen(R.dimen.margin_text_small) } textView { sourceText = this id = R.id.source_text }.lparams(wrapContent, wrapContent) { below(R.id.thumbnails_relative) endOf(R.id.via_text) topMargin = dimen(R.dimen.margin_text_small) } } } private fun _RelativeLayout.thumbnails() { fun _RelativeLayout.thumb(id: Int, init: RelativeLayout.LayoutParams.() -> Unit = {}) { val background = frameLayout { backgroundColor = ctx.getColor(R.color.image_background_transparency) }.lparams(dimen(R.dimen.image_icon), dimen(R.dimen.image_icon), init) val thumb = imageView { this.id = id backgroundColor = ctx.getColor(R.color.transparent) }.lparams(dimen(R.dimen.image_icon), dimen(R.dimen.image_icon), init) mThumbnails.add(background to thumb) } relativeLayout { id = R.id.thumbnails_relative lparams(matchParent, matchParent) { endOf(R.id.icon_image) topMargin = dimen(R.dimen.margin_small) below(R.id.text) } thumb(R.id.thumb_image1) thumb(R.id.thumb_image2) { endOf(R.id.thumb_image1) marginStart = dimen(R.dimen.margin_small) } thumb(R.id.thumb_image3) { endOf(R.id.thumb_image2) marginStart = dimen(R.dimen.margin_small) } thumb(R.id.thumb_image4) { endOf(R.id.thumb_image3) marginStart = dimen(R.dimen.margin_small) } } } } interface ITweetViewUI : UI { val iconImage: ImageView val subInfoIcon: ImageView val subInfoText: TextView val screenNameText: TextView val userNameText: TextView val createdAtText: TextView val text: TextView val thumbnails: List<Pair<FrameLayout, ImageView>> val sourceText: TextView val overlayRelative: RelativeLayout }
mit
745d641ea86a3c8647a61032ec1b7315
32.055814
95
0.552491
4.626302
false
false
false
false
square/sqldelight
drivers/native-driver/src/mingwMain/kotlin/com/squareup/sqldelight/drivers/native/util/NativeCache.kt
1
725
package com.squareup.sqldelight.drivers.native.util import co.touchlab.stately.collections.SharedHashMap import co.touchlab.stately.collections.frozenHashMap internal actual fun <T : Any> nativeCache(): NativeCache<T> = NativeCacheImpl() private class NativeCacheImpl<T : Any> : NativeCache<T> { private val dictionary = frozenHashMap<String, T?>() as SharedHashMap<String, T?> override fun put(key: String, value: T?): T? = dictionary.put(key, value) override fun getOrCreate(key: String, block: () -> T): T = dictionary.getOrPut(key, block)!! override fun remove(key: String): T? = dictionary.remove(key) override fun cleanUp(block: (T) -> Unit) { dictionary.values.filterNotNull().forEach(block) } }
apache-2.0
9bab3aa07de802d29c7b8b5f3c62b341
39.277778
94
0.735172
3.643216
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/adapters/RingtoneAdapter.kt
1
6115
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Authors: Rayan Osseiran <[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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.adapters import android.graphics.drawable.Drawable import android.media.MediaPlayer import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.target.DrawableImageViewTarget import cx.ring.R import cx.ring.adapters.RingtoneAdapter.RingtoneViewHolder import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.PublishSubject import io.reactivex.rxjava3.subjects.Subject import net.jami.model.Ringtone import java.io.IOException class RingtoneAdapter(private val ringtoneList: List<Ringtone>) : RecyclerView.Adapter<RingtoneViewHolder>() { private var currentlySelectedPosition = 1 // default item private val mp = MediaPlayer() private val ringtoneSubject: Subject<Ringtone> = PublishSubject.create() class RingtoneViewHolder(view: View) : RecyclerView.ViewHolder(view) { val name: TextView = view.findViewById(R.id.item_ringtone_name) val isSelected: ImageView = view.findViewById(R.id.item_ringtone_selected) val isPlaying: ImageView = view.findViewById(R.id.item_ringtone_playing) val ringtoneIcon: ImageView = view.findViewById(R.id.item_ringtone_icon) init { Glide.with(view.context) .load(R.raw.baseline_graphic_eq_black_24dp) .placeholder(R.drawable.baseline_graphic_eq_24) .into(DrawableImageViewTarget(isPlaying)) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RingtoneViewHolder { val viewHolder = RingtoneViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_ringtone, parent, false)) configureRingtoneView(viewHolder) return viewHolder } override fun onBindViewHolder(holder: RingtoneViewHolder, position: Int) { val ringtone = ringtoneList[position] holder.name.text = ringtone.name holder.ringtoneIcon.setImageDrawable(ringtone.ringtoneIcon as Drawable) holder.isSelected.visibility = if (ringtone.isSelected) View.VISIBLE else View.INVISIBLE holder.isPlaying.visibility = if (ringtone.isPlaying) View.VISIBLE else View.INVISIBLE } override fun getItemCount(): Int { return ringtoneList.size } private fun configureRingtoneView(viewHolder: RingtoneViewHolder) { viewHolder.itemView.setOnClickListener { if (currentlySelectedPosition == viewHolder.adapterPosition && mp.isPlaying) { stopPreview() return@setOnClickListener } else { resetState() } currentlySelectedPosition = viewHolder.adapterPosition val ringtone = ringtoneList[currentlySelectedPosition] try { mp.setDataSource(ringtone.ringtonePath) mp.prepare() mp.start() ringtone.isPlaying = true } catch (e: IOException) { stopPreview() Log.e(TAG, "Error previewing ringtone", e) } catch (e: IllegalStateException) { stopPreview() Log.e(TAG, "Error previewing ringtone", e) } catch (e: NullPointerException) { stopPreview() Log.e(TAG, "Error previewing ringtone", e) } finally { ringtoneSubject.onNext(ringtone) ringtone.isSelected = true notifyItemChanged(currentlySelectedPosition) } mp.setOnCompletionListener { stopPreview() } } } /** * Stops the preview from playing and disables the playing animation */ private fun stopPreview() { if (mp.isPlaying) mp.stop() mp.reset() ringtoneList[currentlySelectedPosition].isPlaying = false notifyItemChanged(currentlySelectedPosition) } fun releaseMediaPlayer() { mp.release() } /** * Deselects the current item and stops the preview */ fun resetState() { ringtoneList[currentlySelectedPosition].isSelected = false stopPreview() } /** * Sets the ringtone from the user settings * @param path the ringtone path * @param enabled true if the user did not select silent */ fun selectDefaultItem(path: String, enabled: Boolean) { if (!enabled) { currentlySelectedPosition = 0 } else { // ignore first element because it represents silent and has a null path (checked for before) for (ringtoneIndex in 1 until ringtoneList.size) { if (ringtoneList[ringtoneIndex].ringtonePath == path) { currentlySelectedPosition = ringtoneIndex } } } ringtoneList[currentlySelectedPosition].isSelected = true notifyItemChanged(currentlySelectedPosition) } fun getRingtone(): Observable<Ringtone> { return ringtoneSubject } companion object { private val TAG = RingtoneAdapter::class.simpleName!! } }
gpl-3.0
eefb244e1db049367ce454315a7b1b61
37.225
127
0.669828
4.826361
false
false
false
false
almapp/uc-access-android
app/src/main/java/com/almapp/ucaccess/lib/models/WebPage.kt
1
320
package com.almapp.ucaccess.lib.models /** * Created by patriciolopez on 19-01-16. */ data class WebPage( val id: String? = null, val name: String = "", val description: String = "", val URL: String? = null, val imageURL: String? = null, var selected: Boolean = true )
gpl-3.0
c162a40021698aef29e99b58abf09d2b
23.615385
40
0.58125
3.478261
false
false
false
false
grote/Liberario
app/src/main/java/de/grobox/transportr/utils/OnboardingBuilder.kt
1
2127
/* * Transportr * * Copyright (c) 2013 - 2018 Torsten Grote * * 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.grobox.transportr.utils import android.app.Activity import androidx.core.content.ContextCompat import android.util.TypedValue import de.grobox.transportr.R import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt import uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.CirclePromptBackground import uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.RectanglePromptBackground import uk.co.samuelwall.materialtaptargetprompt.extras.focals.CirclePromptFocal import uk.co.samuelwall.materialtaptargetprompt.extras.focals.RectanglePromptFocal class OnboardingBuilder(activity: Activity) : MaterialTapTargetPrompt.Builder(activity) { init { backgroundColour = ContextCompat.getColor(activity, R.color.primary) promptBackground = RectanglePromptBackground() promptFocal = RectanglePromptFocal() setFocalPadding(R.dimen.buttonSize) val typedValue = TypedValue() activity.theme.resolveAttribute(android.R.attr.windowBackground, typedValue, true) focalColour = typedValue.data } } class IconOnboardingBuilder(activity: Activity) : MaterialTapTargetPrompt.Builder(activity) { init { backgroundColour = ContextCompat.getColor(activity, R.color.primary) promptBackground = CirclePromptBackground() promptFocal = CirclePromptFocal() } }
gpl-3.0
3e34e917aa5bee9889b99310bd3981f7
37
93
0.760696
4.237052
false
false
false
false
firebase/quickstart-android
auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/BaseActivity.kt
2
861
package com.google.firebase.quickstart.auth.kotlin import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity open class BaseActivity : AppCompatActivity() { private var progressBar: ProgressBar? = null fun setProgressBar(bar: ProgressBar) { progressBar = bar } fun showProgressBar() { progressBar?.visibility = View.VISIBLE } fun hideProgressBar() { progressBar?.visibility = View.INVISIBLE } fun hideKeyboard(view: View) { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } public override fun onStop() { super.onStop() hideProgressBar() } }
apache-2.0
98485355c8d469d09a0acb6a3ed8c452
24.323529
86
0.711963
4.976879
false
false
false
false
Stargamers/FastHub
app/src/main/java/com/fastaccess/ui/modules/repos/wiki/WikiActivity.kt
4
6465
package com.fastaccess.ui.modules.repos.wiki import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.widget.DrawerLayout import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ProgressBar import butterknife.BindView import com.evernote.android.state.State import com.fastaccess.R import com.fastaccess.data.dao.NameParser import com.fastaccess.data.dao.wiki.WikiContentModel import com.fastaccess.helper.ActivityHelper import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Bundler import com.fastaccess.provider.scheme.LinkParserHelper import com.fastaccess.ui.base.BaseActivity import com.fastaccess.ui.modules.repos.RepoPagerActivity import com.fastaccess.ui.widgets.StateLayout import com.prettifier.pretty.PrettifyWebView /** * Created by Kosh on 13 Jun 2017, 8:35 PM */ class WikiActivity : BaseActivity<WikiMvp.View, WikiPresenter>(), WikiMvp.View { @BindView(R.id.wikiSidebar) lateinit var navMenu: NavigationView @BindView(R.id.drawer) lateinit var drawerLayout: DrawerLayout @BindView(R.id.progress) lateinit var progressbar: ProgressBar @BindView(R.id.stateLayout) lateinit var stateLayout: StateLayout @BindView(R.id.webView) lateinit var webView: PrettifyWebView @State var wiki = WikiContentModel(null, null, arrayListOf()) @State var selectedTitle: String = "Home" override fun layout(): Int = R.layout.wiki_activity_layout override fun isTransparent(): Boolean = true override fun providePresenter(): WikiPresenter = WikiPresenter() override fun onLoadContent(wiki: WikiContentModel) { hideProgress() this.wiki = wiki if (wiki.sidebar.isNotEmpty()) { loadMenu() } if (wiki.content != null) { val baseUrl = Uri.Builder().scheme(LinkParserHelper.PROTOCOL_HTTPS) .authority(LinkParserHelper.HOST_DEFAULT) .appendPath(presenter.login) .appendPath(presenter.repoId) .appendPath("wiki") .build() .toString() webView.setWikiContent(wiki.content, baseUrl) } } override fun onSetPage(page: String) { selectedTitle = page } private fun loadMenu() { navMenu.menu.clear() wiki.sidebar.onEach { navMenu.menu.add(R.id.languageGroup, it.title?.hashCode()!!, Menu.NONE, it.title) .setCheckable(true) .isChecked = it.title.toLowerCase() == selectedTitle.toLowerCase() } } override fun canBack(): Boolean = true override fun isSecured(): Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { onLoadContent(wiki) } else { presenter.onActivityCreated(intent) } navMenu.setNavigationItemSelectedListener { onSidebarClicked(it) return@setNavigationItemSelectedListener true } toolbar?.subtitle = presenter.login + "/" + presenter.repoId setTaskName("${presenter.login}/${presenter.repoId} - Wiki - $selectedTitle") } private fun onSidebarClicked(item: MenuItem) { this.selectedTitle = item.title.toString() setTaskName("${presenter.login}/${presenter.repoId} - Wiki - $selectedTitle") closeDrawerLayout() wiki.sidebar.first { it.title?.toLowerCase() == item.title.toString().toLowerCase() } .let { presenter.onSidebarClicked(it) } } private fun closeDrawerLayout() { drawerLayout.closeDrawer(Gravity.END) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.trending_menu, menu) menu?.findItem(R.id.menu)?.setIcon(R.drawable.ic_menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.menu -> { drawerLayout.openDrawer(Gravity.END) return true } R.id.share -> { ActivityHelper.shareUrl(this, "${LinkParserHelper.PROTOCOL_HTTPS}://${LinkParserHelper.HOST_DEFAULT}/" + "${presenter.login}/${presenter.repoId}/wiki/$selectedTitle") return true } android.R.id.home -> { if (!presenter.login.isNullOrEmpty() && !presenter.repoId.isNullOrEmpty()) { val nameParse = NameParser("") nameParse.name = presenter.repoId!! nameParse.username = presenter.login!! nameParse.isEnterprise = isEnterprise RepoPagerActivity.startRepoPager(this, nameParse) } finish() return true } else -> return super.onOptionsItemSelected(item) } } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } override fun showMessage(titleRes: String, msgRes: String) { hideProgress() super.showMessage(titleRes, msgRes) } override fun showErrorMessage(msgRes: String) { hideProgress() super.showErrorMessage(msgRes) } override fun showProgress(resId: Int) { progressbar.visibility = View.VISIBLE stateLayout.showProgress() } override fun hideProgress() { progressbar.visibility = View.GONE stateLayout.hideProgress() } companion object { fun getWiki(context: Context, repoId: String?, username: String?): Intent { return getWiki(context, repoId, username, null) } fun getWiki(context: Context, repoId: String?, username: String?, page: String?): Intent { val intent = Intent(context, WikiActivity::class.java) intent.putExtras(Bundler.start() .put(BundleConstant.ID, repoId) .put(BundleConstant.EXTRA, username) .put(BundleConstant.EXTRA_TWO, page) .end()) return intent } } }
gpl-3.0
dd7d8e3b1c3615920d1f03be43468807
34.333333
120
0.636195
4.771218
false
false
false
false
NLPIE/BioMedICUS
biomedicus-core/src/test/kotlin/edu/umn/biomedicus/time/DetectTemporalPhrasesTest.kt
1
4325
/* * Copyright (c) 2018 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.time import edu.umn.biomedicus.common.types.syntax.PartOfSpeech import edu.umn.biomedicus.framework.LabelAliases import edu.umn.biomedicus.framework.SearchExprFactory import edu.umn.biomedicus.measures.Number import edu.umn.biomedicus.measures.Quantifier import edu.umn.biomedicus.measures.TimeUnit import edu.umn.biomedicus.numbers.NumberType import edu.umn.biomedicus.sentences.Sentence import edu.umn.biomedicus.tagging.PosTag import edu.umn.biomedicus.tokenization.ParseToken import edu.umn.nlpengine.StandardArtifact import edu.umn.nlpengine.addTo import edu.umn.nlpengine.labelIndex import kotlin.test.Test import kotlin.test.assertEquals class DetectTemporalPhrasesTest { private val labelAliases = LabelAliases().apply { addAlias("Sentence", Sentence::class.java) addAlias("ParseToken", ParseToken::class.java) addAlias("PosTag", PosTag::class.java) addAlias("Quantifier", Quantifier::class.java) addAlias("TimeUnit", TimeUnit::class.java) addAlias("DayOfWeek", DayOfWeek::class.java) addAlias("TextDate", TextDate::class.java) addAlias("TextTime", TextTime::class.java) addAlias("TimeOfDayWord", TimeOfDayWord::class.java) addAlias("SeasonWord", SeasonWord::class.java) addAlias("YearRange", YearRange::class.java) addAlias("Number", Number::class.java) } private val searchExprFactory = SearchExprFactory(labelAliases) private val pattern = TemporalPhrasePattern(searchExprFactory) private val detector = DetectTemporalPhrases(pattern) @Test fun testSinceTheAgeOf() { val document = StandardArtifact("1") .addDocument("doc", "since the age of 33") Sentence(0, 19).addTo(document) ParseToken(0, 5, "since", true).addTo(document) ParseToken(6, 9, "the", true).addTo(document) ParseToken(10, 13, "age", true).addTo(document) ParseToken(14, 16, "of", true).addTo(document) ParseToken(17, 19, "33", false).addTo(document) PosTag(0, 5, PartOfSpeech.IN).addTo(document) Number(17, 19, "33", "1", NumberType.CARDINAL) .addTo(document) detector.run(document) val temporals = document.labelIndex<TemporalPhrase>().asList() assertEquals(temporals.size, 1) assertEquals(temporals[0].startIndex, 0) assertEquals(temporals[0].endIndex, 19) } @Test fun testATimeUnit() { val document = StandardArtifact("1").addDocument("doc", "a week") document.labeler(Sentence::class.java).add(Sentence(0, 6)) ParseToken(0, 1, "a", true).addTo(document) ParseToken(2, 6, "week", false).addTo(document) TimeUnit(2, 6).addTo(document) detector.run(document) val temporals = document.labelIndex(TemporalPhrase::class.java).asList() assertEquals(temporals.size, 1) assertEquals(temporals[0].startIndex, 0) assertEquals(temporals[0].endIndex, 6) } @Test fun testNumberYearsAgo() { val document = StandardArtifact("1").addDocument("doc", "30 years ago") Sentence(0, 12).addTo(document) ParseToken(0, 2, "30", true).addTo(document) ParseToken(3, 8, "years", true).addTo(document) ParseToken(9, 12, "ago", true).addTo(document) Quantifier(0, 2, true).addTo(document) TimeUnit(3, 8).addTo(document) detector.run(document) val temporals = document.labelIndex<TemporalPhrase>().asList() assertEquals(temporals.size, 1) assertEquals(temporals[0].startIndex, 0) assertEquals(temporals[0].endIndex, 12) } }
apache-2.0
30a2e48e3cfd740c2470c89d21915d96
34.45082
80
0.68763
3.924682
false
true
false
false
ipanardian/tictactoe
app/src/main/java/com/ipanardian/tictactoe/TicTacToeActivity.kt
1
3794
/** * Tic Tac Toe * (c) 2017 Ipan Ardian * Android Tic Tac Toe games written in Kotlin with Anko DSL layout and support i18n * * https://github.com/ipanardian/tictactoe * GPL-3.0 License */ package com.ipanardian.tictactoe import android.graphics.Color import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.text.SpannableString import android.text.method.LinkMovementMethod import android.text.util.Linkify import android.view.Menu import android.view.MenuItem import android.widget.Button import android.widget.TextView import org.jetbrains.anko.* import org.jetbrains.anko.appcompat.v7.Appcompat import kotlin.properties.Delegates class TicTacToeActivity : AppCompatActivity() { var squares = mutableMapOf<Int, String>() var xIsNext = true var winner: String by Delegates.notNull() val totalCell = 9 companion object { const val X = "X" const val O = "O" } private val lines: Array<IntArray> = arrayOf( intArrayOf(0,1,2), intArrayOf(3,4,5), intArrayOf(6,7,8), intArrayOf(0,3,6), intArrayOf(1,4,7), intArrayOf(2,5,8), intArrayOf(0,4,8), intArrayOf(2,4,6) ) private lateinit var ui: TicTacToeActivityUI override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ui = TicTacToeActivityUI() ui.setContentView(this) winner = "" } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate( R.menu.main_menu, menu ) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item != null) when (item.itemId) { R.id.menuAbout -> aboutDialog() } return super.onOptionsItemSelected(item) } fun playGame(cellID: Int, btnSelected: Button) { if (!winner.isNullOrEmpty()) { toast(R.string.game_over) return } when { xIsNext -> { squares[cellID] = X btnSelected.setBackgroundColor(Color.GREEN) } else -> { squares[cellID] = O btnSelected.setBackgroundColor(Color.BLUE) } } btnSelected.text = squares[cellID] btnSelected.isEnabled = false xIsNext = !xIsNext checkWinner { winner -> winner?.let { this.winner = it } } ui.updateGuideText() } private inline fun checkWinner(result: (winner: String?) -> Unit) { if (squares.isNotEmpty()) for (line in lines) { val (a, b, c) = line if (squares[a] != null && squares[a] == squares[b] && squares[a] === squares[c]) { result(squares[a]) } } } fun newGame() { squares = mutableMapOf() xIsNext = true winner = "" with(ui) { tvNextPlayer.text = resources.getString(R.string.next_player, X) tvNextPlayer.setTextColor(Color.GRAY) resetButton() } } private fun aboutDialog() { var aboutContent = SpannableString(resources.getString(R.string.about_content)) Linkify.addLinks(aboutContent, Linkify.WEB_URLS) val alert = alert(Appcompat) { title = resources.getString(R.string.about) message = aboutContent yesButton { dialog -> dialog.dismiss() } }.build() alert.show() var textView = alert.find<TextView>(android.R.id.message) textView.movementMethod = LinkMovementMethod.getInstance() } }
gpl-3.0
f175daabe35708a37ff3244a9f336784
26.1
94
0.58777
4.253363
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/util/CharSequences.kt
1
730
package cn.yiiguxing.plugin.translate.util /** * 根据指定的[正则表达式][regex]将字符序列分块,分为匹配和未匹配目标正则表达式的块。 */ fun CharSequence.chunked(regex: Regex, transform: (MatchResult) -> CharSequence): List<CharSequence> { val chunked = mutableListOf<CharSequence>() var cursor = 0 for (matchResult in regex.findAll(this)) { val start = matchResult.range.first if (start != 0) { chunked += substring(cursor, matchResult.range.first) } chunked += transform(matchResult) cursor = matchResult.range.last + 1 } if (cursor < length) { chunked += substring(cursor, length) } return chunked }
mit
0d56522c5f1eeb06b27404a4169c7965
25.36
102
0.641337
3.963855
false
false
false
false
MichaelRocks/lightsaber
processor/src/main/java/io/michaelrocks/lightsaber/processor/commons/CompositeAnnotationVisitor.kt
1
1591
/* * Copyright 2019 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.lightsaber.processor.commons import org.objectweb.asm.AnnotationVisitor import org.objectweb.asm.Opcodes import java.util.ArrayList class CompositeAnnotationVisitor : AnnotationVisitor(Opcodes.ASM5), CompositeVisitor<AnnotationVisitor> { override val visitors = ArrayList<AnnotationVisitor>() override fun addVisitor(visitor: AnnotationVisitor) { visitors.add(visitor) } override fun visit(name: String?, value: Any) = forEachVisitor { visit(name, value) } override fun visitEnum(name: String?, desc: String, value: String) = forEachVisitor { visitEnum(name, desc, value) } override fun visitAnnotation(name: String?, desc: String): AnnotationVisitor? = addVisitorsTo(CompositeAnnotationVisitor()) { visitAnnotation(name, desc) } override fun visitArray(name: String?): AnnotationVisitor? = addVisitorsTo(CompositeAnnotationVisitor()) { visitArray(name) } override fun visitEnd() = forEachVisitor { visitEnd() } }
apache-2.0
66944102e5f6c77cccd1a3bf5299964a
35.159091
105
0.754243
4.3
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/ui/main/tune/buildprop/PropAdapter.kt
1
11077
package com.androidvip.hebf.ui.main.tune.buildprop import android.app.Activity import android.content.DialogInterface import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import com.androidvip.hebf.R import com.androidvip.hebf.applyAnim import com.androidvip.hebf.utils.* import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import java.util.* class PropAdapter(private val propList: MutableList<Pair<String, String>>, private val activity: Activity) : RecyclerView.Adapter<PropAdapter.ViewHolder>() { private val fab: FloatingActionButton? = activity.findViewById(R.id.buildPropFab) private val propPresets = arrayOf( "Disable logcat", "Enable navigation bar*", "Enable lockscreen rotation", "Enable homescreen rotation*", "Toggle adb notification*", "Toggle multitouch", "Max number of touches", "Disable anonymous data send", "Proximity sensor delay", "Unlock tethering*", "Increase JPG quality", "Enable ADB over TCP" ) inner class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { var key: TextView = v.findViewById(R.id.build_prop_key) var value: TextView = v.findViewById(R.id.build_prop_value) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.list_item_prop, parent, false) return ViewHolder(v) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val (key, value) = propList[position] holder.key.text = key holder.value.text = value fab?.setOnLongClickListener { MaterialAlertDialogBuilder(activity) .setTitle(R.string.add) .setItems(propPresets) { _, which -> when (which) { 0 -> showAddPropDialog("logcat.live", "enable") 1 -> showAddPropDialog("qemu.hw.mainkeys", "1") 2 -> showAddPropDialog("lockscreen.rot_override", "true") 3 -> showAddPropDialog("log.tag.launcher_force_rotate", "VERBOSE") 4 -> showAddPropDialog("persist.adb.notify", "1") 5 -> showAddPropDialog("ro.product.multi_touch_enabled", "true") 6 -> showAddPropDialog("ro.product.max_num_touch", "8") 7 -> showAddPropDialog("ro.config.nocheckin", "1") 8 -> showAddPropDialog("mot.proximity.delay", "150") 9 -> showAddPropDialog("net.tethering.noprovisioning", "true") 10 -> showAddPropDialog("ro.media.enc.jpeg.quality", "100") 11 -> showAddPropDialog("service.adb.tcp.port", "5555") 12 -> showAddPropDialog("ro.opa.eligible_device", "true") } } .show() true } fab?.setOnClickListener { showAddPropDialog("", "") } holder.itemView.setOnClickListener { val menuOptions = arrayListOf( SheetOption(activity.getString(R.string.edit), "edit", R.drawable.ic_file), SheetOption(activity.getString(R.string.delete), "delete", R.drawable.ic_delete) ) val contextSheet = ContextBottomSheet.newInstance(key, menuOptions) contextSheet.onOptionClickListener = object : ContextBottomSheet.OnOptionClickListener { override fun onOptionClick(tag: String) { contextSheet.dismiss() when (tag) { "edit" -> { if (key.contains("ro.build.version.sdk")) { Toast.makeText(activity, activity.getString(R.string.unsafe_operation), Toast.LENGTH_LONG).show() } else { val propDialog = PropDialog(activity.getString(R.string.edit), key, value) propDialog.setOkListener(DialogInterface.OnClickListener { _, _ -> val newProp = propDialog.newKey to propDialog.newValue RootUtils.executeAsync("sed 's|$key=$value|${newProp.first}=${newProp.second}|g' -i /system/build.prop") Logger.logInfo("Changed $key value to ${newProp.second}", activity) propList[position] = newProp notifyItemChanged(position) Snackbar.make(fab!!, R.string.done, Snackbar.LENGTH_LONG).show() val userPrefs = UserPrefs(activity) val achievementsSet = userPrefs.getStringSet(K.PREF.ACHIEVEMENT_SET, HashSet()) if (!achievementsSet.contains("prop")) { Utils.addAchievement(activity.applicationContext, "prop") Toast.makeText(activity, activity.getString(R.string.achievement_unlocked, activity.getString(R.string.achievement_prop)), Toast.LENGTH_LONG).show() } }) propDialog.show() } } "delete" -> { if (key.contains("ro.build.version.sdk")) { Toast.makeText(activity, activity.getString(R.string.unsafe_operation), Toast.LENGTH_LONG).show() } else { MaterialAlertDialogBuilder(activity) .setTitle(activity.getString(R.string.warning)) .setMessage(activity.getString(R.string.confirmation_message)) .setNegativeButton(android.R.string.cancel) { _, _ -> } .setPositiveButton(R.string.remove) { _, _ -> RootUtils.executeAsync("sed 's|$key=$value|#$key=$value|g' -i /system/build.prop") Logger.logInfo("Removed (commented) $key from build.prop", activity) Snackbar.make(fab!!, R.string.done, Snackbar.LENGTH_LONG).show() propList.removeAt(position) notifyItemRemoved(position) notifyItemRangeChanged(position, itemCount) }.applyAnim().also { it.show() } } } } } } contextSheet.show((activity as AppCompatActivity).supportFragmentManager, "sheet") } } override fun getItemCount(): Int { return propList.size } // Custom instance of PropDialog for adding a prop only private fun showAddPropDialog(defaultKey: String, defaultValue: String) { val propDialog = PropDialog(activity.getString(R.string.add), defaultKey, defaultValue) propDialog.setOkListener(DialogInterface.OnClickListener { _, _ -> val newProp = propDialog.newKey to propDialog.newValue if (newProp.first.isEmpty()) { Utils.showEmptyInputFieldSnackbar(fab) } else { RootUtils.executeAsync("chmod +w /system/build.prop && echo ${newProp.first}=${newProp.second} >> /system/build.prop") Logger.logInfo("Added ${newProp.first} to build.prop", activity) propList.add(newProp) notifyItemInserted(propList.size + 1) Snackbar.make(fab!!, R.string.done, Snackbar.LENGTH_LONG).show() val userPrefs = UserPrefs(activity) val achievementsSet = userPrefs.getStringSet(K.PREF.ACHIEVEMENT_SET, HashSet()) if (!achievementsSet.contains("prop")) { Utils.addAchievement(activity.applicationContext, "prop") Toast.makeText(activity, activity.getString(R.string.achievement_unlocked, activity.getString(R.string.achievement_prop)), Toast.LENGTH_LONG).show() } } }) propDialog.show() } /** * Class used to show a dialog allowing user to edit or add a system property. */ private inner class PropDialog (title: String, key: String, value: String) { private val editKey: EditText private val editValue: EditText private val builder: MaterialAlertDialogBuilder = MaterialAlertDialogBuilder(activity) private var okListener: DialogInterface.OnClickListener? = null internal val newKey: String get() = editKey.text.toString().trim() internal val newValue: String get() = editValue.text.toString().trim() init { // The base view used in this dialog, contains 2 EditTexts, one for the key, other for the value val dialogView = activity.layoutInflater.inflate(R.layout.dialog_build_prop_edit, null) builder.setTitle(title) builder.setView(dialogView) editKey = dialogView.findViewById(R.id.edit_prop_key) editValue = dialogView.findViewById(R.id.edit_prop_value) // Fill up text fields with prop information editKey.setText(key) editValue.setText(value) builder.setNegativeButton(android.R.string.cancel) { _, _ -> } } /** * Do not forget to call this method, it comes away from the constructor so the dev * can have a chance to finish instantiating the dialog and (then) be able to use * [.getNewKey] and [.getNewValue] in the OK button listener. * * @param okListener the listener that indicates what to do when the user presses the positive button */ fun setOkListener(okListener: DialogInterface.OnClickListener) { this.okListener = okListener } fun show() { checkNotNull(okListener) { "Cannot show a PropDialog if no positive button callback is set for it" } builder.setPositiveButton(R.string.done, okListener) builder.show() } } }
apache-2.0
bf4af976c57f16eb8d4622767a4a3a34
48.67713
188
0.558635
5.118762
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hil/inspection/HILOperationTypesMismatchInspection.kt
1
6959
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hil.inspection import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.psi.PsiElementVisitor import org.intellij.plugins.hcl.terraform.config.TerraformFileType import org.intellij.plugins.hcl.terraform.config.model.Type import org.intellij.plugins.hcl.terraform.config.model.Types import org.intellij.plugins.hil.GoUtil import org.intellij.plugins.hil.HILElementTypes import org.intellij.plugins.hil.HILElementTypes.IL_BINARY_EQUALITY_EXPRESSION import org.intellij.plugins.hil.HILTypes.ILBinaryBooleanOnlyOperations import org.intellij.plugins.hil.HILTypes.ILBinaryNumericOnlyOperations import org.intellij.plugins.hil.psi.* import org.intellij.plugins.hil.psi.impl.getHCLHost class HILOperationTypesMismatchInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { val file = InjectedLanguageManager.getInstance(holder.project).getTopLevelFile(holder.file) val ft = file.fileType if (ft != TerraformFileType) { return super.buildVisitor(holder, isOnTheFly) } return MyEV(holder) } inner class MyEV(val holder: ProblemsHolder) : ILElementVisitor() { override fun visitILBinaryExpression(operation: ILBinaryExpression) { ProgressIndicatorProvider.checkCanceled() operation.getHCLHost() ?: return val left = operation.lOperand val right = operation.rOperand ?: return val leftType = getType(left) val rightType = getType(right) val elementType = operation.node.elementType if (elementType in ILBinaryNumericOnlyOperations) { if (leftType != null && leftType != Types.Number && leftType != Types.Any) { holder.registerProblem(left, "Expected to be number, actual type is ${leftType.name}", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } if (rightType != null && rightType != Types.Number && rightType != Types.Any) { holder.registerProblem(right, "Expected to be number, actual type is ${rightType.name}", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } return } else if (elementType == IL_BINARY_EQUALITY_EXPRESSION) { return // could compare anything with implicit 'toString' conversion. TODO: Add warning? } else if (elementType in ILBinaryBooleanOnlyOperations) { if (leftType != null && leftType != Types.Boolean && leftType != Types.Any) { holder.registerProblem(left, "Expected to be boolean, actual type is ${leftType.name}", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } if (rightType != null && rightType != Types.Boolean && rightType != Types.Any) { holder.registerProblem(right, "Expected to be boolean, actual type is ${rightType.name}", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } return } else { return } } override fun visitILUnaryExpression(operation: ILUnaryExpression) { ProgressIndicatorProvider.checkCanceled() operation.getHCLHost() ?: return val operand = operation.operand ?: return val sign = operation.operationSign // Return if we cannot determine operands type val type = getType(operand) ?: return if (sign == HILElementTypes.OP_PLUS || sign == HILElementTypes.OP_MINUS) { if (type != Types.Number && type != Types.Any) { holder.registerProblem(operand, "Expected to be number, actual type is ${type.name}", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } return } else if (sign == HILElementTypes.OP_NOT) { if (type != Types.Boolean && type != Types.Any) { holder.registerProblem(operand, "Expected to be boolean, actual type is ${type.name}", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } return } else { return } } override fun visitILConditionalExpression(operation: ILConditionalExpression) { ProgressIndicatorProvider.checkCanceled() operation.getHCLHost() ?: return // First check condition val condition = operation.condition val type = getType(condition) if (type == Types.Boolean) { // Ok } else if (type == Types.String) { // Semi ok if (condition is ILLiteralExpression && condition.doubleQuotedString != null) { if (!GoUtil.isBoolean(condition.unquotedText!!)) { holder.registerProblem(condition, "Condition should be boolean or string with boolean value", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } } } else if (type != Types.Any) { holder.registerProblem(condition, "Condition should be boolean or string with boolean value", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } ProgressIndicatorProvider.checkCanceled() // Then branches val left = operation.then ?: return val right = operation.`else` ?: return // See TypeCachedValueProvider.doGetType(ILConditionalExpression) for details val l = getType(left) val r = getType(right) ProgressIndicatorProvider.checkCanceled() // There's some weird logic in HIL eval_test.go: // > // false expression is type-converted to match true expression // > // true expression is type-converted to match false expression if the true expression is string if (l == r) // Ok else if (l == null) // Ok else if (r == null) // Ok else if (l == Types.Any || r == Types.Any) // Ok else if (l == Types.String) // Ok // Would be casted //TODO Check actual value else if (r == Types.String) // Ok // Would be casted //TODO Check actual value else if (l != r) { holder.registerProblem(operation, "Both branches expected to have same type. 'then' is ${l.name}, 'else' is ${r.name}", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } // TODO: Report if some branch has type Array or Map, they're forbidden for now } } companion object { private fun getType(e: ILExpression): Type? { return TypeCachedValueProvider.getType(e) } } }
apache-2.0
f5f1f96b8e22430a92a49422c6a32ccd
42.229814
174
0.69852
4.495478
false
false
false
false
esafirm/android-image-picker
imagepicker/src/main/java/com/esafirm/imagepicker/helper/state/LiveDataObservableState.kt
1
1257
package com.esafirm.imagepicker.helper.state import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer class LiveDataObservableState<T>( value: T, private val usePostValue: Boolean = false ) : ObservableState<T> { private val backingField: MutableLiveData<T> = MutableLiveData(value) /** * This is only use only when [usePostValue] is true */ private var valueHolder: T = value override fun set(value: T) { if (usePostValue) { valueHolder = value backingField.postValue(value) } else { backingField.value = value } } override fun get(): T = if (usePostValue) { valueHolder } else { backingField.value!! } override fun observe(owner: LifecycleOwner, observer: (T) -> Unit) { backingField.reObserve(owner, { observer.invoke(it) }) } override fun observeForever(observer: (T) -> Unit) { backingField.observeForever(observer) } private fun <T> LiveData<T>.reObserve(owner: LifecycleOwner, observer: Observer<T>) { removeObserver(observer) observe(owner, observer) } }
mit
808691092e9d2e64ed1ac233e3894dd5
25.765957
89
0.651551
4.410526
false
false
false
false
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/service/receivers/devices/remote/RemoteControlProxy.kt
1
1855
package com.lasthopesoftware.bluewater.client.playback.service.receivers.devices.remote import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.playback.service.broadcasters.PlaylistEvents import com.lasthopesoftware.bluewater.client.playback.service.broadcasters.TrackPositionBroadcaster import java.util.* class RemoteControlProxy(private val remoteBroadcaster: IRemoteBroadcaster) : BroadcastReceiver() { private val mappedEvents: MutableMap<String, (Intent) -> Unit> fun registerForIntents(): Set<String> { return mappedEvents.keys } override fun onReceive(context: Context, intent: Intent) { val action = intent.action ?: return val eventHandler = mappedEvents[action] eventHandler?.invoke(intent) } private fun onPlaylistChange(intent: Intent) { val fileKey = intent.getIntExtra(PlaylistEvents.PlaybackFileParameters.fileKey, -1) if (fileKey > 0) remoteBroadcaster.updateNowPlaying(ServiceFile(fileKey)) } private fun onTrackPositionUpdate(intent: Intent) { val trackPosition = intent.getLongExtra(TrackPositionBroadcaster.TrackPositionChangedParameters.filePosition, -1) if (trackPosition >= 0) remoteBroadcaster.updateTrackPosition(trackPosition) } init { mappedEvents = HashMap(5) mappedEvents[PlaylistEvents.onPlaylistTrackChange] = { intent -> onPlaylistChange(intent) } mappedEvents[PlaylistEvents.onPlaylistPause] = { remoteBroadcaster.setPaused() } mappedEvents[PlaylistEvents.onPlaylistStart] = { remoteBroadcaster.setPlaying() } mappedEvents[PlaylistEvents.onPlaylistStop] = { remoteBroadcaster.setStopped() } mappedEvents[TrackPositionBroadcaster.trackPositionUpdate] = { intent -> onTrackPositionUpdate(intent) } } }
lgpl-3.0
b41c916c9c0b29c4b98d0ae005734d2e
44.243902
115
0.814555
4.168539
false
false
false
false
spark/photon-tinker-android
app/src/main/java/io/particle/android/sdk/tinker/TinkerPrefs.kt
1
1296
package io.particle.android.sdk.tinker import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences private const val BUCKET_NAME = "tinkerPrefsBucket" private const val KEY_IS_VISITED = "isVisited" private const val KEY_API_BASE_URI = "KEY_API_BASE_URI" internal class TinkerPrefs private constructor(context: Context) { companion object { @SuppressLint("StaticFieldLeak") // we use app context, so it doesn't matter private var instance: TinkerPrefs? = null fun getInstance(ctx: Context): TinkerPrefs { var inst = instance if (inst == null) { inst = TinkerPrefs(ctx) instance = inst } return inst } } private val app: Context = context.applicationContext private val prefs: SharedPreferences = app.getSharedPreferences(BUCKET_NAME, Context.MODE_PRIVATE) val isFirstVisit: Boolean get() = !prefs.getBoolean(KEY_IS_VISITED, false) // val apiBaseUri: String? // get() = _getApiBaseUri() fun setVisited(isVisited: Boolean) { prefs.edit().putBoolean(KEY_IS_VISITED, isVisited).apply() } // private fun _getApiBaseUri(): String? { // return // } }
apache-2.0
f8b8df1758ef015dba67ea2187abfb05
26
85
0.649691
4.167203
false
false
false
false
stephanenicolas/toothpick
ktp/src/main/kotlin/toothpick/ktp/binding/BindingExtension.kt
1
6354
/* * Copyright 2019 Stephane Nicolas * Copyright 2019 Daniel Molinero Reguera * * 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 toothpick.ktp.binding import javax.inject.Provider import kotlin.reflect.KClass import toothpick.config.Binding import toothpick.config.Module /** * DSL method to define bindings. A typical example is * <pre> * module { * bind(Foo::class)... * bind(bar::class)... * ... * } * </pre> * @param bindings a list of bindings statements. * @return a module containing all the bindings {@code bindings}. */ fun module(bindings: Module.() -> Unit): Module = Module().apply { bindings() } /** * DSL method to start a binding statement. * @param key the {@link KClass} used as a key for this binding. * @return a binding statement for this key, that can be further customized. * @see module(Module.() -> Unit) */ fun <T : Any> Module.bind(key: KClass<T>): CanBeNamed<T> = CanBeNamed(bind(key.java)) /** * DSL method to start a binding statement, using reified types for a more Kotlin friendly syntax. * @param T the {@link KClass} used as a key for this binding. * @return a binding statement for this key, that can be further customized. * @see toothpick.config.Module.bind(Class) */ inline fun <reified T : Any> Module.bind(): CanBeNamed<T> = CanBeNamed(bind(T::class.java)) open class CanBeBound<T : Any>(open val delegate: Binding<T>.CanBeBound) { /** * DSL method to make a binding Singleton. * @return a binding statement for this key, with the implementation class {@code implClass} * that can be further customized. */ fun singleton(): Binding<T>.CanBeReleasable = delegate.singleton() /** * DSL method to associate an implementation class to a binding. * @param implClass the {@link KClass} used as an implementation class for this binding. * @return a binding statement for this key, with the implementation class {@code implClass} * that can be further customized. */ fun toClass(implClass: KClass<out T>): Binding<T>.CanBeSingleton = delegate.to(implClass.java) /** * DSL method to associate an implementation class to a binding, more Kotlin friendly. * @return a binding statement for this key, with the implementation class {@code T} * that can be further customized. * @see Binding.CanBeBound.toClass(KClass<T>) */ inline fun <reified P : T> toClass(): Binding<T>.CanBeSingleton = delegate.to(P::class.java) /** * DSL method to associate an instance to a binding, more Kotlin friendly. * @param instance to be used * @return a binding statement for this key, with the instance provided by the lambda * that can be further customized. */ fun toInstance(instance: T) = delegate.toInstance(instance) /** * DSL method to associate an instance to a binding, more Kotlin friendly. * @param instanceProvider a lambda that creates the instance * @return a binding statement for this key, with the instance provided by the lambda * that can be further customized. */ fun toInstance(instanceProvider: () -> T) = delegate.toInstance(instanceProvider()) /** * DSL method to associate an provider to a binding, more Kotlin friendly. * @param providerClass the {@link KClass} used as a provider class for this binding. * @return a binding statement for this key, with the provider class * that can be further customized. */ fun toProvider(providerClass: KClass<out Provider<out T>>): Binding<T>.CanProvideSingletonOrSingleton = delegate.toProvider(providerClass.java) // https://youtrack.jetbrains.com/issue/KT-17061 // inline fun <T, reified P : Provider<out T>> Binding<T>.CanBeBound.toProvider(): Binding<T>.CanProvideSingletonOrSingleton = toProvider(P::class.java) /** * DSL method to associate an provider impl to a binding, more Kotlin friendly. * @param providerInstance the provider instance to be used for this binding. * @return a binding statement for this key, with the provider class * that can be further customized. */ fun toProviderInstance(providerInstance: Provider<out T>): Binding<T>.CanProvideSingleton = delegate.toProviderInstance(providerInstance) /** * DSL method to associate an provider impl to a binding, more Kotlin friendly. * @param providerInstanceProvider a lambda used as a provider for this binding. * @return a binding statement for this key, with the provider class * that can be further customized. */ fun toProviderInstance(providerInstanceProvider: () -> T): Binding<T>.CanProvideSingleton = delegate.toProviderInstance(providerInstanceProvider) } class CanBeNamed<T : Any>(override val delegate: Binding<T>.CanBeNamed) : CanBeBound<T>(delegate) { /** * DSL method to give a name (String) to a binding. * @param name the {@link String} used as a name for this binding. * @return a binding statement for this key, with the name {@code name} * that can be further customized. */ fun withName(name: String): CanBeBound<T> = CanBeBound(delegate.withName(name)) /** * DSL method to give a name (annotation class) to a binding. * @param annotationClassWithQualifierAnnotation the {@link KClass} used as a name for this binding. * @return a binding statement for this key, with the name {@code annotationClassWithQualifierAnnotation} * that can be further customized. */ fun withName(annotationClassWithQualifierAnnotation: KClass<out Annotation>): CanBeBound<T> = CanBeBound(delegate.withName(annotationClassWithQualifierAnnotation.java)) // https://youtrack.jetbrains.com/issue/KT-17061 // inline fun <T, reified A : Annotation> Binding<T>.CanBeNamed.withName() = withName(A::class.java) }
apache-2.0
8ce3706d43b4b6824802ac81401a9512
44.06383
172
0.709789
4.17477
false
false
false
false
spark/photon-tinker-android
app/src/main/java/io/particle/android/sdk/ui/InspectorActivity.kt
1
9994
package io.particle.android.sdk.ui import android.content.Context import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Parcelable import android.view.Menu import android.view.MenuItem import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.RadioButton import android.widget.TextView import android.widget.Toast import androidx.lifecycle.Observer import androidx.viewpager.widget.ViewPager import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.tabs.TabLayout import io.particle.android.sdk.cloud.BroadcastContract import io.particle.android.sdk.cloud.ParticleCloudSDK import io.particle.android.sdk.cloud.ParticleDevice import io.particle.android.sdk.cloud.ParticleEventVisibility import io.particle.android.sdk.cloud.exceptions.ParticleCloudException import io.particle.android.sdk.cloud.models.DeviceStateChange import io.particle.android.sdk.utils.Async import io.particle.android.sdk.utils.ui.Ui import io.particle.commonui.DeviceInfoBottomSheetController import io.particle.mesh.common.android.livedata.BroadcastReceiverLD import io.particle.mesh.setup.flow.Scopes import io.particle.mesh.setup.utils.ToastGravity import io.particle.mesh.setup.utils.safeToast import io.particle.mesh.ui.controlpanel.ControlPanelActivity import io.particle.sdk.app.R import mu.KotlinLogging import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe private const val EXTRA_DEVICE = "EXTRA_DEVICE" /** An activity representing the Inspector screen for a Device */ class InspectorActivity : BaseActivity() { companion object { fun buildIntent(ctx: Context, device: ParticleDevice): Intent { return Intent(ctx, InspectorActivity::class.java) .putExtra(EXTRA_DEVICE, device) } } private val log = KotlinLogging.logger {} private val syncStatus = object : Runnable { override fun run() { invalidateOptionsMenu() handler.postDelayed(this, 1000 * 60L) } } private lateinit var devicesUpdatedBroadcast: BroadcastReceiverLD<Int> lateinit var device: ParticleDevice private val cloud = ParticleCloudSDK.getCloud() private val handler = Handler() private lateinit var deviceInfoController: DeviceInfoBottomSheetController private val scopes = Scopes() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null || intent.getParcelableExtra<Parcelable>(EXTRA_DEVICE) == null) { finish() return } device = intent.getParcelableExtra(EXTRA_DEVICE)!! setContentView(R.layout.activity_inspector) // Show the Up button in the action bar. supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(true) updateDetails() setupInspectorPages() handler.postDelayed(syncStatus, 1000 * 60L) deviceInfoController = DeviceInfoBottomSheetController( this, scopes, findViewById(R.id.device_info_bottom_sheet), device ) deviceInfoController.initializeBottomSheet() var initialValue = 0 devicesUpdatedBroadcast = BroadcastReceiverLD( this, BroadcastContract.BROADCAST_DEVICES_UPDATED, { ++initialValue }, true ) devicesUpdatedBroadcast.observe(this, Observer { updateDetails() }) } private fun updateDetails() { title = device.name // FIXME: and update the device indicator that we have to add to the device info slider // FIXME: and update the Tinker fragment state } public override fun onResume() { super.onResume() EventBus.getDefault().register(this) scopes.onWorker { val owned = try { cloud.userOwnsDevice(device.id) } catch (ex: Exception) { // this seems odd to return true here, but there are a load of different errors // which can be thrown if, e.g.: this Android device has no internet access at // the moment. That shouldn't cause us to bail here true } if (!owned) { scopes.onMain { safeToast("Device is not owned by this user", gravity = ToastGravity.CENTER) finish() } } try { device.refresh() device.subscribeToSystemEvents() } catch (ex: ParticleCloudException) { // minor issue if we don't update online/offline states } } } public override fun onPause() { EventBus.getDefault().unregister(this) scopes.onWorker { try { device.unsubscribeFromSystemEvents() } catch (ex: ParticleCloudException) { // ignore } } // action_signal_device.isChecked = false super.onPause() } override fun onDestroy() { super.onDestroy() scopes.cancelChildren() } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { android.R.id.home -> finish() R.id.action_event_publish -> presentPublishDialog() R.id.action_launchcontrol_panel -> { startActivity(ControlPanelActivity.buildIntent(this, device)) } else -> { return false } } return true } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.inspector, menu) return true } override fun onBackPressed() { if (deviceInfoController.sheetBehaviorState == BottomSheetBehavior.STATE_EXPANDED) { deviceInfoController.sheetBehaviorState = BottomSheetBehavior.STATE_COLLAPSED } else { super.onBackPressed() } } @Subscribe fun onEvent(device: ParticleDevice) { //update device and UI //TODO update more fields this.device = device runOnUiThread { title = device.name deviceInfoController.updateDeviceDetails() } } @Subscribe fun onEvent(deviceStateChange: DeviceStateChange) { //reload menu to display online/offline invalidateOptionsMenu() runOnUiThread { deviceInfoController.updateDeviceDetails() } } private fun setupInspectorPages() { val viewPager = findViewById<ViewPager>(R.id.viewPager) viewPager.adapter = InspectorPager(supportFragmentManager, device) viewPager.offscreenPageLimit = 3 val tabLayout = findViewById<TabLayout>(R.id.tabLayout) tabLayout.setupWithViewPager(viewPager) //hiding keyboard on tab changed viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { } override fun onPageSelected(position: Int) {} override fun onPageScrollStateChanged(state: Int) { val view = currentFocus val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if (view != null && imm != null) { imm.hideSoftInputFromWindow(view.windowToken, 0) } } }) } private fun presentPublishDialog() { val publishDialogView = View.inflate(this, R.layout.publish_event, null) MaterialDialog.Builder(this) .customView(publishDialogView, false) .positiveText(R.string.publish_positive_action) .onPositive { _, _ -> val nameView = Ui.findView<TextView>(publishDialogView, R.id.eventName) val valueView = Ui.findView<TextView>(publishDialogView, R.id.eventValue) val privateEventRadio: RadioButton = Ui.findView(publishDialogView, R.id.privateEvent) val name = nameView.text.toString() val value = valueView.text.toString() val eventVisibility = if (privateEventRadio.isChecked) ParticleEventVisibility.PRIVATE else ParticleEventVisibility.PUBLIC publishEvent(name, value, eventVisibility) } .negativeText(R.string.cancel) .cancelable(true) .cancelListener { it.dismiss() } .show() } private fun publishEvent(name: String, value: String, eventVisibility: Int) { try { Async.executeAsync(device, object : Async.ApiProcedure<ParticleDevice>() { @Throws(ParticleCloudException::class) override fun callApi(particleDevice: ParticleDevice): Void? { particleDevice.cloud.publishEvent(name, value, eventVisibility, 600) return null } override fun onFailure(exception: ParticleCloudException) { Toast.makeText( this@InspectorActivity, "Failed to publish '" + name + "' event", Toast.LENGTH_SHORT ).show() } }) } catch (e: ParticleCloudException) { Toast.makeText( this, "Failed to publish '" + name + "' event", Toast.LENGTH_SHORT ).show() } } }
apache-2.0
f1738904ac18a45b8de814a4f0776a97
32.993197
96
0.624875
5.191688
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/animations/animationcomposition/StoryFooterComponent.kt
1
8015
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.samples.litho.kotlin.animations.animationcomposition import android.graphics.Color import com.facebook.litho.Column import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Row import com.facebook.litho.Style import com.facebook.litho.Transition import com.facebook.litho.animation.AnimatedProperties import com.facebook.litho.animation.DimensionValue import com.facebook.litho.core.height import com.facebook.litho.core.margin import com.facebook.litho.core.padding import com.facebook.litho.core.width import com.facebook.litho.core.widthPercent import com.facebook.litho.dp import com.facebook.litho.flexbox.flex import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.sp import com.facebook.litho.transition.transitionKey import com.facebook.litho.transition.useTransition import com.facebook.litho.useState import com.facebook.litho.view.backgroundColor import com.facebook.litho.view.onClick import com.facebook.litho.view.testKey import com.facebook.yoga.YogaAlign import com.facebook.yoga.YogaJustify class StoryFooterComponent : KComponent() { override fun ComponentScope.render(): Component? { val commentText = useState { false } useTransition( Transition.parallel( Transition.create(Transition.TransitionKeyType.GLOBAL, "comment_editText") .animate(AnimatedProperties.ALPHA) .appearFrom(0f) .disappearTo(0f) .animate(AnimatedProperties.X) .appearFrom(DimensionValue.widthPercentageOffset(-50f)) .disappearTo(DimensionValue.widthPercentageOffset(-50f)), Transition.create(Transition.TransitionKeyType.GLOBAL, "cont_comment") .animate(AnimatedProperties.ALPHA) .appearFrom(0f) .disappearTo(0f), Transition.create(Transition.TransitionKeyType.GLOBAL, "icon_like", "icon_share") .animate(AnimatedProperties.X), Transition.create(Transition.TransitionKeyType.GLOBAL, "text_like", "text_share") .animate(AnimatedProperties.ALPHA) .appearFrom(0f) .disappearTo(0f) .animate(AnimatedProperties.X) .appearFrom(DimensionValue.widthPercentageOffset(50f)) .disappearTo(DimensionValue.widthPercentageOffset(50f)))) if (!commentText.value) { return Row(style = Style.backgroundColor(Color.WHITE).height(56f.dp)) { child( Row( alignItems = YogaAlign.CENTER, justifyContent = YogaJustify.CENTER, style = Style.widthPercent(33.3f) .onClick { commentText.update(!commentText.value) } .testKey("like_button") .transitionKey(context, "icon_like", Transition.TransitionKeyType.GLOBAL)) { child( Column( style = Style.height(24f.dp) .width(24f.dp) .backgroundColor(Color.RED) .transitionKey( context, "icon_like", Transition.TransitionKeyType.GLOBAL))) child( Text( textSize = 16f.sp, text = "Like", style = Style.transitionKey( context, "text_like", Transition.TransitionKeyType.GLOBAL) .margin(left = 8f.dp))) }) child( Row( alignItems = YogaAlign.CENTER, justifyContent = YogaJustify.CENTER, style = Style.transitionKey( context, "cont_comment", Transition.TransitionKeyType.GLOBAL) .widthPercent(33.3f)) { child( Column(style = Style.height(24f.dp).width(24f.dp).backgroundColor(Color.RED))) child( Text(textSize = 16f.sp, text = "Comment", style = Style.margin(left = 8f.dp))) }) child( Row( alignItems = YogaAlign.CENTER, justifyContent = YogaJustify.CENTER, style = Style.widthPercent(33.3f)) { child( Column( style = Style.transitionKey( context, "icon_share", Transition.TransitionKeyType.GLOBAL) .height(24f.dp) .width(24f.dp) .backgroundColor(Color.RED))) child( Text( textSize = 16f.sp, text = "Share", style = Style.transitionKey( context, "text_share", Transition.TransitionKeyType.GLOBAL) .margin(left = 8f.dp))) }) } } else { return Row(style = Style.backgroundColor(Color.WHITE).height(56f.dp)) { child( Row( alignItems = YogaAlign.CENTER, justifyContent = YogaJustify.CENTER, style = Style.onClick { commentText.update(!commentText.value) } .padding(horizontal = 16f.dp) .testKey("like_button")) { child( Column( style = Style.transitionKey( context, "icon_like", Transition.TransitionKeyType.GLOBAL) .height(24f.dp) .width(24f.dp) .backgroundColor(Color.RED))) }) child( Column( style = Style.flex(grow = 1f) .transitionKey( context, "comment_editText", Transition.TransitionKeyType.GLOBAL)) { child(Text(text = "Input here", textSize = 16f.sp)) }) child( Row( alignItems = YogaAlign.CENTER, style = Style.transitionKey(context, "cont_share", Transition.TransitionKeyType.GLOBAL) .onClick { commentText.update(!commentText.value) } .padding(all = 16f.dp) .backgroundColor(0xFF0000FF.toInt())) { child( Column( style = Style.transitionKey( context, "icon_share", Transition.TransitionKeyType.GLOBAL) .height(24f.dp) .width(24f.dp) .backgroundColor(Color.RED))) }) } } } }
apache-2.0
c46102fab6b72aeb192ab72fc6a605d8
42.559783
100
0.520649
5.105096
false
false
false
false
ze-pequeno/okhttp
okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt
2
3384
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.sse.internal import java.io.IOException import okhttp3.Call import okhttp3.Callback import okhttp3.EventListener import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody import okhttp3.internal.connection.RealCall import okhttp3.internal.stripBody import okhttp3.sse.EventSource import okhttp3.sse.EventSourceListener internal class RealEventSource( private val request: Request, private val listener: EventSourceListener ) : EventSource, ServerSentEventReader.Callback, Callback { private var call: RealCall? = null @Volatile private var canceled = false fun connect(client: OkHttpClient) { val client = client.newBuilder() .eventListener(EventListener.NONE) .build() val realCall = client.newCall(request) as RealCall call = realCall realCall.enqueue(this) } override fun onResponse(call: Call, response: Response) { processResponse(response) } fun processResponse(response: Response) { response.use { if (!response.isSuccessful) { listener.onFailure(this, null, response) return } val body = response.body if (!body.isEventStream()) { listener.onFailure(this, IllegalStateException("Invalid content-type: ${body.contentType()}"), response) return } // This is a long-lived response. Cancel full-call timeouts. call?.timeoutEarlyExit() // Replace the body with a stripped one so the callbacks can't see real data. val response = response.stripBody() val reader = ServerSentEventReader(body.source(), this) try { if (!canceled) { listener.onOpen(this, response) while (!canceled && reader.processNextEvent()) { } } } catch (e: Exception) { val exception = when { canceled -> IOException("canceled", e) else -> e } listener.onFailure(this, exception, response) return } if (canceled) { listener.onFailure(this, IOException("canceled"), response) } else { listener.onClosed(this) } } } private fun ResponseBody.isEventStream(): Boolean { val contentType = contentType() ?: return false return contentType.type == "text" && contentType.subtype == "event-stream" } override fun onFailure(call: Call, e: IOException) { listener.onFailure(this, e, null) } override fun request(): Request = request override fun cancel() { canceled = true call?.cancel() } override fun onEvent(id: String?, type: String?, data: String) { listener.onEvent(this, id, type, data) } override fun onRetryChange(timeMs: Long) { // Ignored. We do not auto-retry. } }
apache-2.0
f7f746c074463be8763b1403b50165ec
27.677966
91
0.676714
4.316327
false
false
false
false
exviva/stew
app/src/main/kotlin/net/stew/stew/ui/PostsFragment.kt
1
1964
package net.stew.stew.ui import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import net.stew.stew.databinding.FragmentPostsBinding import net.stew.stew.model.PostCollection import net.stew.stew.model.SubdomainPostCollection class PostsFragment : Fragment() { companion object { fun newInstance(collection: PostCollection) = PostsFragment().apply { arguments = Bundle().apply { putInt("index", collection.ordinal()) putString("subdomain", collection.subdomain) } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = FragmentPostsBinding.inflate(inflater, container, false).apply { postsView.apply { val collection = requireArguments().run { val index = getInt("index") if (index >= 0) PostCollection.Predefined[index] else SubdomainPostCollection(getString("subdomain")!!) } val adapter = PostsAdapter(activity as MainActivity, collection).apply { load() } val layoutManager = LinearLayoutManager(context) this.adapter = adapter this.layoutManager = layoutManager addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition() post { adapter.maybeLoadMore(lastVisibleItemPosition) } } }) } }.root }
gpl-2.0
290889c7a2934dd4c4b081514d1ffcde
40.808511
109
0.612525
5.862687
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/ui/launcher/ListFactory.kt
1
3708
package info.papdt.express.helper.ui.launcher import android.appwidget.AppWidgetManager import android.content.Context import android.content.Intent import android.graphics.drawable.ColorDrawable import androidx.core.content.ContextCompat import android.text.style.ForegroundColorSpan import android.widget.RemoteViews import android.widget.RemoteViewsService import info.papdt.express.helper.R import info.papdt.express.helper.dao.PackageDatabase import info.papdt.express.helper.model.Kuaidi100Package import info.papdt.express.helper.support.ScreenUtils import info.papdt.express.helper.support.Spanny class ListFactory(private val mContext: Context, intent: Intent) : RemoteViewsService.RemoteViewsFactory { private val mAppWidgetId: Int = intent.getIntExtra( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID ) private val mDatabase: PackageDatabase = PackageDatabase.getInstance(mContext.applicationContext) private val DP_16_TO_PX: Float = ScreenUtils.dpToPx(mContext, 8f) private val statusTitleColor: Int = ContextCompat.getColor(mContext, R.color.package_list_status_title_color) private val statusSubtextColor: Int = ContextCompat.getColor(mContext, R.color.package_list_status_subtext_color) private val STATUS_STRING_ARRAY: Array<String> = mContext.resources.getStringArray(R.array.item_status_description) private val STATUS_ERROR: String = mContext.getString(R.string.item_text_cannot_get_package_status) override fun onCreate() { } override fun onDataSetChanged() { } override fun onDestroy() { } private fun getDeliveringData(): List<Kuaidi100Package> { return mDatabase.data.filter { it.getState() == Kuaidi100Package.STATUS_ON_THE_WAY || it.getState() == Kuaidi100Package.STATUS_RETURNING || it.getState() == Kuaidi100Package.STATUS_NORMAL } } override fun getCount(): Int { return getDeliveringData().size } override fun getViewAt(i: Int): RemoteViews { val views = RemoteViews(mContext.packageName, R.layout.item_list_package_for_widget) val p = getDeliveringData()[i] views.setTextViewText(R.id.tv_title, p.name) if (p.data != null && p.data!!.size > 0) { val status = p.data!![0] val spanny = Spanny(STATUS_STRING_ARRAY[p.getState()], ForegroundColorSpan(statusTitleColor)) .append(" - " + status.context, ForegroundColorSpan(statusSubtextColor)) views.setTextViewText(R.id.tv_other, spanny) } else { /** Set placeholder when cannot get data */ views.setTextViewText(R.id.tv_other, STATUS_ERROR) } /** Set CircleImageView */ views.setTextViewText(R.id.tv_first_char, p.getFirstChar()) val packagePalette = p.getPaletteFromId() val b = ScreenUtils.drawableToBitmap(ColorDrawable(packagePalette["100"])) views.setImageViewBitmap(R.id.iv_logo, b) views.setTextColor(R.id.tv_first_char, packagePalette["800"]) /** Add paddingTop/Bottom to the first or last item */ if (i == 0) { views.setViewPadding(R.id.item_container, 0, DP_16_TO_PX.toInt(), 0, 0) } else if (i == count) { views.setViewPadding(R.id.item_container, 0, 0, 0, DP_16_TO_PX.toInt()) } val intent = Intent() intent.putExtra(EXTRA_PACKAGE_JSON, p.toJsonString()) intent.putExtra(EXTRA_STATE, p.getState()) views.setOnClickFillInIntent(R.id.item_container, intent) return views } override fun getLoadingView(): RemoteViews? { return null } override fun getViewTypeCount(): Int { return 1 } override fun getItemId(i: Int): Long { return i.toLong() } override fun hasStableIds(): Boolean { return true } companion object { private const val EXTRA_PACKAGE_JSON = "extra_package_json" private const val EXTRA_STATE = "extra_state" } }
gpl-3.0
9512d5c25c661735698feeb6c2924a99
30.423729
116
0.75027
3.504726
false
false
false
false
google/horologist
audio-ui/src/debug/java/com/google/android/horologist/audio/ui/DeviceChipPreview.kt
1
1738
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.audio.ui import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Headphones import androidx.compose.runtime.Composable import androidx.compose.ui.unit.dp import androidx.wear.compose.material.Icon import androidx.wear.compose.material.MaterialTheme import com.google.android.horologist.audio.ui.components.DeviceChip import com.google.android.horologist.compose.tools.WearPreview import com.google.android.horologist.compose.tools.WidthConstrainedBox @WearPreview @Composable fun DeviceChipPreview() { WidthConstrainedBox( widths = listOf(100.dp, 164.dp, 192.dp, 227.dp), comfortableHeight = 100.dp ) { DeviceChip( volumeDescription = "", deviceName = "Bluetooth Headphones", icon = { Icon( imageVector = Icons.Default.Headphones, contentDescription = "", tint = MaterialTheme.colors.onSurfaceVariant ) }, onAudioOutputClick = { } ) } }
apache-2.0
5ae86cfb9d2ca0ae921b64b73cb4638b
33.76
75
0.689873
4.433673
false
false
false
false
google/horologist
media-sample/src/main/java/com/google/android/horologist/mediasample/di/NetworkModule.kt
1
8857
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.mediasample.di import android.content.Context import android.net.ConnectivityManager import android.net.wifi.WifiManager import coil.ImageLoader import coil.decode.SvgDecoder import coil.disk.DiskCache import coil.request.CachePolicy import coil.util.DebugLogger import com.google.android.horologist.mediasample.BuildConfig import com.google.android.horologist.mediasample.data.api.UampService import com.google.android.horologist.mediasample.data.api.WearArtworkUampService import com.google.android.horologist.mediasample.ui.AppConfig import com.google.android.horologist.networks.data.DataRequestRepository import com.google.android.horologist.networks.data.InMemoryDataRequestRepository import com.google.android.horologist.networks.data.RequestType import com.google.android.horologist.networks.highbandwidth.HighBandwidthNetworkMediator import com.google.android.horologist.networks.highbandwidth.StandardHighBandwidthNetworkMediator import com.google.android.horologist.networks.logging.NetworkStatusLogger import com.google.android.horologist.networks.okhttp.NetworkAwareCallFactory import com.google.android.horologist.networks.okhttp.NetworkSelectingCallFactory import com.google.android.horologist.networks.okhttp.impl.NetworkLoggingEventListenerFactory import com.google.android.horologist.networks.request.NetworkRequester import com.google.android.horologist.networks.request.NetworkRequesterImpl import com.google.android.horologist.networks.rules.NetworkingRulesEngine import com.google.android.horologist.networks.status.NetworkRepository import com.google.android.horologist.networks.status.NetworkRepositoryImpl import com.squareup.moshi.Moshi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import okhttp3.Cache import okhttp3.Call import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.LoggingEventListener import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.io.File import javax.inject.Provider import javax.inject.Singleton import kotlin.time.Duration.Companion.seconds @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Singleton @Provides fun networkRepository( @ApplicationContext application: Context, @ForApplicationScope coroutineScope: CoroutineScope ): NetworkRepository = NetworkRepositoryImpl.fromContext( application, coroutineScope ) @Singleton @Provides fun cache( @ApplicationContext application: Context ): Cache = Cache( application.cacheDir.resolve("HttpCache"), 10_000_000 ) @Singleton @Provides fun alwaysHttpsInterceptor(): Interceptor = Interceptor { var request = it.request() if (request.url.scheme == "http") { request = request.newBuilder().url( request.url.newBuilder().scheme("https").build() ).build() } it.proceed(request) } @Singleton @Provides fun okhttpClient( cache: Cache, alwaysHttpsInterceptor: Interceptor ): OkHttpClient { return OkHttpClient.Builder().followSslRedirects(false) .addInterceptor(alwaysHttpsInterceptor) .eventListenerFactory(LoggingEventListener.Factory()).cache(cache).build() } @Provides fun networkLogger(): NetworkStatusLogger = NetworkStatusLogger.Logging @Singleton @Provides fun dataRequestRepository(): DataRequestRepository = InMemoryDataRequestRepository() @Provides fun networkingRulesEngine( networkRepository: NetworkRepository, networkLogger: NetworkStatusLogger, appConfig: AppConfig ): NetworkingRulesEngine = NetworkingRulesEngine( networkRepository = networkRepository, logger = networkLogger, networkingRules = appConfig.strictNetworking!! ) @Provides fun connectivityManager( @ApplicationContext application: Context ): ConnectivityManager = application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager @Provides fun wifiManager( @ApplicationContext application: Context ): WifiManager = application.getSystemService(Context.WIFI_SERVICE) as WifiManager @Singleton @Provides fun aggregatingHighBandwidthRequester( networkLogger: NetworkStatusLogger, networkRequester: NetworkRequester, @ForApplicationScope coroutineScope: CoroutineScope ) = StandardHighBandwidthNetworkMediator( networkLogger, networkRequester, coroutineScope, 3.seconds ) @Singleton @Provides fun highBandwidthRequester( highBandwidthNetworkMediator: StandardHighBandwidthNetworkMediator ): HighBandwidthNetworkMediator = highBandwidthNetworkMediator @Singleton @Provides fun networkRequester( connectivityManager: ConnectivityManager ): NetworkRequester = NetworkRequesterImpl( connectivityManager ) @Singleton @Provides fun networkAwareCallFactory( appConfig: AppConfig, okhttpClient: OkHttpClient, networkingRulesEngine: Provider<NetworkingRulesEngine>, highBandwidthNetworkMediator: Provider<HighBandwidthNetworkMediator>, dataRequestRepository: DataRequestRepository, networkRepository: NetworkRepository, @ForApplicationScope coroutineScope: CoroutineScope, logger: NetworkStatusLogger ): Call.Factory = if (appConfig.strictNetworking != null) { NetworkSelectingCallFactory( networkingRulesEngine.get(), highBandwidthNetworkMediator.get(), networkRepository, dataRequestRepository, okhttpClient, coroutineScope ) } else { okhttpClient.newBuilder() .eventListenerFactory( NetworkLoggingEventListenerFactory( logger, networkRepository, okhttpClient.eventListenerFactory, dataRequestRepository ) ) .build() } @Singleton @Provides fun moshi() = Moshi.Builder().build() @Singleton @Provides fun mooshiConverterFactory( moshi: Moshi ): MoshiConverterFactory = MoshiConverterFactory.create(moshi) @Singleton @Provides fun retrofit( callFactory: Call.Factory, moshiConverterFactory: MoshiConverterFactory ) = Retrofit.Builder() .addConverterFactory(moshiConverterFactory) .baseUrl(UampService.BASE_URL) .callFactory( NetworkAwareCallFactory( callFactory, RequestType.ApiRequest ) ).build() @Singleton @Provides fun uampService( retrofit: Retrofit ): UampService = WearArtworkUampService( retrofit.create(UampService::class.java) ) @Singleton @Provides fun imageLoader( @ApplicationContext application: Context, @CacheDir cacheDir: File, callFactory: Call.Factory ): ImageLoader = ImageLoader.Builder(application) .crossfade(false) .components { add(SvgDecoder.Factory()) } .respectCacheHeaders(false).diskCache { DiskCache.Builder() .directory(cacheDir.resolve("image_cache")) .build() } .memoryCachePolicy(CachePolicy.ENABLED) .diskCachePolicy(CachePolicy.ENABLED) .networkCachePolicy(CachePolicy.ENABLED) .callFactory { NetworkAwareCallFactory( callFactory, defaultRequestType = RequestType.ImageRequest ) }.apply { if (BuildConfig.DEBUG) { logger(DebugLogger()) } }.build() }
apache-2.0
9b3e679339883e967ae7d64c2601ba0b
32.296992
96
0.701027
5.31952
false
false
false
false
Ekito/koin
koin-projects/examples/androidx-compose/src/main/java/org/koin/sample/androidx/compose/data/UserRepository.kt
1
285
package org.koin.sample.androidx.compose.data class UserRepository { fun getUsers(): List<User> { return listOf( User(name = "Peter", age = 32), User(name = "John", age = 27), User(name = "Paul", age = 18) ) } }
apache-2.0
fd5c6d210b562cf4cb1fc13d191a3e61
22.833333
47
0.494737
3.958333
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/highlighter/MdSyntaxHighlighter.kt
1
20411
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.highlighter import com.intellij.lexer.Lexer import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.fileTypes.PlainTextSyntaxHighlighterFactory import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.vladsch.md.nav.parser.MdLexer import com.vladsch.md.nav.parser.MdPlainTextLexer import com.vladsch.md.nav.psi.util.MdTokenSets.* import com.vladsch.md.nav.settings.MdApplicationSettings import com.vladsch.md.nav.settings.MdRenderingProfile import com.vladsch.md.nav.settings.SyntaxHighlightingType import java.awt.Color import java.util.* import java.util.concurrent.atomic.AtomicBoolean import kotlin.collections.HashMap class MdSyntaxHighlighter constructor(val renderingProfile: MdRenderingProfile, val forSampleDoc: Boolean, val forAnnotator: Boolean) : SyntaxHighlighterBase() { constructor() : this(MdRenderingProfile.DEFAULT, false, false) override fun getHighlightingLexer(): Lexer { val noSyntax = MdApplicationSettings.instance.documentSettings.syntaxHighlighting == SyntaxHighlightingType.NONE.intValue val renderingProfile = this.renderingProfile return when { forAnnotator -> MdPlainTextLexer() forSampleDoc -> MdLexer(MdRenderingProfile.FOR_SAMPLE_DOC) noSyntax -> PlainTextSyntaxHighlighterFactory.createPlainTextLexer() else -> MdLexer(renderingProfile) } } override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> { val textAttributesKey = ATTRIBUTES[tokenType] // if (textAttributesKey == null) { // val tmp = 0 // } return SyntaxHighlighterBase.pack(textAttributesKey) } companion object { private val MERGED_ATTRIBUTES = HashMap<TextAttributesKey, List<TextAttributesKey>>() private val ATTRIBUTES: HashMap<IElementType, TextAttributesKey> by lazy { val map = HashMap<IElementType, TextAttributesKey>() val highlighterColors = MdHighlighterColors.getInstance() fillMap(map, TEXT_FOR_SYNTAX_SET, highlighterColors.TEXT_ATTR_KEY) fillMap(map, ABBREVIATION_SET, highlighterColors.ABBREVIATION_ATTR_KEY) fillMap(map, ABBREVIATION_SHORT_TEXT_SET, highlighterColors.ABBREVIATION_SHORT_TEXT_ATTR_KEY) fillMap(map, ABBREVIATION_EXPANDED_TEXT_SET, highlighterColors.ABBREVIATION_EXPANDED_TEXT_ATTR_KEY) fillMap(map, ABBREVIATED_TEXT_SET, highlighterColors.ABBREVIATED_TEXT_ATTR_KEY) fillMap(map, AUTO_LINK_SET, highlighterColors.AUTO_LINK_ATTR_KEY) fillMap(map, ANCHOR_SET, highlighterColors.ANCHOR_ATTR_KEY) fillMap(map, ANCHOR_ID_SET, highlighterColors.ANCHOR_ID_ATTR_KEY) fillMap(map, EMOJI_MARKER_SET, highlighterColors.EMOJI_MARKER_ATTR_KEY) fillMap(map, EMOJI_ID_SET, highlighterColors.EMOJI_ID_ATTR_KEY) fillMap(map, ASIDE_BLOCK_SET, highlighterColors.ASIDE_BLOCK_ATTR_KEY) fillMap(map, BLOCK_QUOTE_SET, highlighterColors.BLOCK_QUOTE_ATTR_KEY) fillMap(map, BOLD_MARKER_SET, highlighterColors.BOLD_MARKER_ATTR_KEY) fillMap(map, BOLD_SET, highlighterColors.BOLD_ATTR_KEY) fillMap(map, UNDERLINE_MARKER_SET, highlighterColors.UNDERLINE_MARKER_ATTR_KEY) fillMap(map, UNDERLINE_SET, highlighterColors.UNDERLINE_ATTR_KEY) fillMap(map, SUPERSCRIPT_MARKER_SET, highlighterColors.SUPERSCRIPT_MARKER_ATTR_KEY) fillMap(map, SUPERSCRIPT_SET, highlighterColors.SUPERSCRIPT_ATTR_KEY) fillMap(map, SUBSCRIPT_MARKER_SET, highlighterColors.SUBSCRIPT_MARKER_ATTR_KEY) fillMap(map, SUBSCRIPT_SET, highlighterColors.SUBSCRIPT_ATTR_KEY) fillMap(map, BULLET_LIST_SET, highlighterColors.BULLET_LIST_ATTR_KEY) fillMap(map, COMMENT_SET, highlighterColors.COMMENT_ATTR_KEY) fillMap(map, BLOCK_COMMENT_SET, highlighterColors.BLOCK_COMMENT_ATTR_KEY) fillMap(map, CODE_SET, highlighterColors.CODE_ATTR_KEY) fillMap(map, CODE_MARKER_SET, highlighterColors.CODE_MARKER_ATTR_KEY) fillMap(map, GITLAB_MATH_SET, highlighterColors.GITLAB_MATH_ATTR_KEY) fillMap(map, GITLAB_MATH_MARKER_SET, highlighterColors.GITLAB_MATH_MARKER_ATTR_KEY) fillMap(map, DEFINITION_MARKER_SET, highlighterColors.DEFINITION_MARKER_ATTR_KEY) fillMap(map, DEFINITION_TERM_SET, highlighterColors.DEFINITION_TERM_ATTR_KEY) fillMap(map, EXPLICIT_LINK_SET, highlighterColors.EXPLICIT_LINK_ATTR_KEY) fillMap(map, FOOTNOTE_SET, highlighterColors.FOOTNOTE_ATTR_KEY) fillMap(map, FOOTNOTE_REF_SET, highlighterColors.FOOTNOTE_REF_ATTR_KEY) fillMap(map, FOOTNOTE_ID_SET, highlighterColors.FOOTNOTE_ID_ATTR_KEY) fillMap(map, ATX_HEADER_SET, highlighterColors.ATX_HEADER_ATTR_KEY) fillMap(map, SETEXT_HEADER_SET, highlighterColors.SETEXT_HEADER_ATTR_KEY) fillMap(map, HEADER_TEXT_SET, highlighterColors.HEADER_TEXT_ATTR_KEY) fillMap(map, HEADER_ATX_MARKER_SET, highlighterColors.HEADER_ATX_MARKER_ATTR_KEY) fillMap(map, HEADER_SETEXT_MARKER_SET, highlighterColors.HEADER_SETEXT_MARKER_ATTR_KEY) fillMap(map, HRULE_SET, highlighterColors.HRULE_ATTR_KEY) fillMap(map, HTML_BLOCK_SET, highlighterColors.HTML_BLOCK_ATTR_KEY) fillMap(map, JEKYLL_FRONT_MATTER_BLOCK_SET, highlighterColors.JEKYLL_FRONT_MATTER_BLOCK_ATTR_KEY) fillMap(map, JEKYLL_FRONT_MATTER_MARKER_SET, highlighterColors.JEKYLL_FRONT_MATTER_MARKER_ATTR_KEY) fillMap(map, JEKYLL_TAG_MARKER_SET, highlighterColors.JEKYLL_TAG_MARKER_ATTR_KEY) fillMap(map, JEKYLL_TAG_NAME_SET, highlighterColors.JEKYLL_TAG_NAME_ATTR_KEY) fillMap(map, JEKYLL_TAG_PARAMETERS_SET, highlighterColors.JEKYLL_TAG_PARAMETERS_ATTR_KEY) fillMap(map, MACRO_SET, highlighterColors.MACRO_ATTR_KEY) fillMap(map, MACRO_REF_SET, highlighterColors.MACRO_REF_ATTR_KEY) fillMap(map, MACRO_ID_SET, highlighterColors.MACRO_ID_ATTR_KEY) fillMap(map, ATTRIBUTES_MARKER_SET, highlighterColors.ATTRIBUTES_MARKER_ATTR_KEY) fillMap(map, ATTRIBUTE_NAME_SET, highlighterColors.ATTRIBUTE_NAME_ATTR_KEY) fillMap(map, ATTRIBUTE_VALUE_SEP_SET, highlighterColors.ATTRIBUTE_VALUE_SEP_ATTR_KEY) fillMap(map, ATTRIBUTE_VALUE_MARKER_SET, highlighterColors.ATTRIBUTE_VALUE_MARKER_ATTR_KEY) fillMap(map, ENUM_REF_FORMAT_SET, highlighterColors.ENUM_REF_FORMAT_ATTR_KEY) fillMap(map, ENUM_REF_LINK_SET, highlighterColors.ENUM_REF_LINK_ATTR_KEY) fillMap(map, ENUM_REF_TEXT_SET, highlighterColors.ENUM_REF_TEXT_ATTR_KEY) fillMap(map, ENUM_REF_ID_SET, highlighterColors.ENUM_REF_ID_ATTR_KEY) fillMap(map, ADMONITION_MARKER_SET, highlighterColors.ADMONITION_MARKER_ATTR_KEY) fillMap(map, ADMONITION_INFO_SET, highlighterColors.ADMONITION_INFO_ATTR_KEY) fillMap(map, ADMONITION_TITLE_SET, highlighterColors.ADMONITION_TITLE_ATTR_KEY) fillMap(map, FLEXMARK_MARKER_SET, highlighterColors.FLEXMARK_MARKER_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_SECTION_SET, highlighterColors.FLEXMARK_EXAMPLE_SECTION_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_SECTION_MARKER_SET, highlighterColors.FLEXMARK_EXAMPLE_SECTION_MARKER_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_NUMBER_SET, highlighterColors.FLEXMARK_EXAMPLE_NUMBER_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_EXAMPLE_KEYWORD_SET, highlighterColors.FLEXMARK_EXAMPLE_EXAMPLE_KEYWORD_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_OPTIONS_KEYWORD_SET, highlighterColors.FLEXMARK_EXAMPLE_OPTIONS_KEYWORD_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_OPTIONS_MARKER_SET, highlighterColors.FLEXMARK_EXAMPLE_OPTIONS_MARKER_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_OPTION_SET, highlighterColors.FLEXMARK_EXAMPLE_OPTION_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_OPTION_PARAM_SET, highlighterColors.FLEXMARK_EXAMPLE_OPTION_PARAM_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_OPTION_PARAM_MARKER_SET, highlighterColors.FLEXMARK_EXAMPLE_OPTION_PARAM_MARKER_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_OPTION_BUILT_IN_SET, highlighterColors.FLEXMARK_EXAMPLE_OPTION_BUILT_IN_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_OPTION_IGNORE_SET, highlighterColors.FLEXMARK_EXAMPLE_OPTION_IGNORE_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_OPTION_FAIL_SET, highlighterColors.FLEXMARK_EXAMPLE_OPTION_FAIL_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_OPTION_DISABLED_NAME_SET, highlighterColors.FLEXMARK_EXAMPLE_OPTION_DISABLED_NAME_ATTR_KEY) fillMap(map, FLEXMARK_EXAMPLE_SEPARATOR_SET, highlighterColors.FLEXMARK_EXAMPLE_SEPARATOR_ATTR_KEY) fillMap(map, IMAGE_LINK_REF_SET, highlighterColors.IMAGE_LINK_REF_ATTR_KEY) fillMap(map, IMAGE_URL_CONTENT_SET, highlighterColors.IMAGE_URL_CONTENT_ATTR_KEY) fillMap(map, IMAGE_LINK_REF_TITLE_SET, highlighterColors.IMAGE_LINK_REF_TITLE_ATTR_KEY) fillMap(map, IMAGE_ALT_TEXT_SET, highlighterColors.IMAGE_ALT_TEXT_ATTR_KEY) fillMap(map, IMAGE_SET, highlighterColors.IMAGE_ATTR_KEY) fillMap(map, INLINE_HTML_SET, highlighterColors.INLINE_HTML_ATTR_KEY) fillMap(map, HTML_ENTITY_SET, highlighterColors.HTML_ENTITY_ATTR_KEY) fillMap(map, ITALIC_MARKER_SET, highlighterColors.ITALIC_MARKER_ATTR_KEY) fillMap(map, ITALIC_SET, highlighterColors.ITALIC_ATTR_KEY) fillMap(map, LINK_REF_SET, highlighterColors.LINK_REF_ATTR_KEY) fillMap(map, LINK_REF_TEXT_SET, highlighterColors.LINK_REF_TEXT_ATTR_KEY) fillMap(map, LINK_REF_TITLE_SET, highlighterColors.LINK_REF_TITLE_ATTR_KEY) fillMap(map, LINK_REF_ANCHOR_SET, highlighterColors.LINK_REF_ANCHOR_ATTR_KEY) fillMap(map, LINK_REF_ANCHOR_MARKER_SET, highlighterColors.LINK_REF_ANCHOR_MARKER_ATTR_KEY) fillMap(map, MAIL_LINK_SET, highlighterColors.MAIL_LINK_ATTR_KEY) fillMap(map, ORDERED_LIST_SET, highlighterColors.ORDERED_LIST_ATTR_KEY) fillMap(map, QUOTE_SET, highlighterColors.QUOTE_ATTR_KEY) fillMap(map, QUOTED_TEXT_SET, highlighterColors.QUOTED_TEXT_ATTR_KEY) fillMap(map, REFERENCE_IMAGE_SET, highlighterColors.REFERENCE_IMAGE_ATTR_KEY) fillMap(map, REFERENCE_IMAGE_REFERENCE_SET, highlighterColors.REFERENCE_IMAGE_REFERENCE_ATTR_KEY) fillMap(map, REFERENCE_IMAGE_TEXT_SET, highlighterColors.REFERENCE_IMAGE_TEXT_ATTR_KEY) fillMap(map, REFERENCE_LINK_SET, highlighterColors.REFERENCE_LINK_ATTR_KEY) fillMap(map, REFERENCE_LINK_REFERENCE_SET, highlighterColors.REFERENCE_LINK_REFERENCE_ATTR_KEY) fillMap(map, REFERENCE_LINK_TEXT_SET, highlighterColors.REFERENCE_LINK_TEXT_ATTR_KEY) fillMap(map, REFERENCE_SET, highlighterColors.REFERENCE_ATTR_KEY) fillMap(map, REFERENCE_LINK_REF_SET, highlighterColors.REFERENCE_LINK_REF_ATTR_KEY) fillMap(map, REFERENCE_TITLE_SET, highlighterColors.REFERENCE_TITLE_ATTR_KEY) fillMap(map, REFERENCE_TEXT_SET, highlighterColors.REFERENCE_TEXT_ATTR_KEY) fillMap(map, REFERENCE_ANCHOR_SET, highlighterColors.REFERENCE_ANCHOR_ATTR_KEY) fillMap(map, REFERENCE_ANCHOR_MARKER_SET, highlighterColors.REFERENCE_ANCHOR_MARKER_ATTR_KEY) fillMap(map, SMARTS_SET, highlighterColors.SMARTS_ATTR_KEY) fillMap(map, SPECIAL_TEXT_SET, highlighterColors.SPECIAL_TEXT_ATTR_KEY) fillMap(map, SPECIAL_TEXT_MARKER_SET, highlighterColors.SPECIAL_TEXT_MARKER_ATTR_KEY) fillMap(map, LINE_BREAK_SPACES_SET, highlighterColors.LINE_BREAK_SPACES_ATTR_KEY) fillMap(map, STRIKETHROUGH_MARKER_SET, highlighterColors.STRIKETHROUGH_MARKER_ATTR_KEY) fillMap(map, STRIKETHROUGH_SET, highlighterColors.STRIKETHROUGH_ATTR_KEY) fillMap(map, TABLE_CAPTION_SET, highlighterColors.TABLE_CAPTION_ATTR_KEY) fillMap(map, TABLE_CAPTION_MARKER_SET, highlighterColors.TABLE_CAPTION_MARKER_ATTR_KEY) fillMap(map, TABLE_CELL_REVEN_CEVEN_SET, highlighterColors.TABLE_CELL_REVEN_CEVEN_ATTR_KEY) fillMap(map, TABLE_CELL_REVEN_CODD_SET, highlighterColors.TABLE_CELL_REVEN_CODD_ATTR_KEY) fillMap(map, TABLE_CELL_RODD_CEVEN_SET, highlighterColors.TABLE_CELL_RODD_CEVEN_ATTR_KEY) fillMap(map, TABLE_CELL_RODD_CODD_SET, highlighterColors.TABLE_CELL_RODD_CODD_ATTR_KEY) fillMap(map, TABLE_ROW_EVEN_SET, highlighterColors.TABLE_ROW_EVEN_ATTR_KEY) fillMap(map, TABLE_ROW_ODD_SET, highlighterColors.TABLE_ROW_ODD_ATTR_KEY) fillMap(map, TABLE_HDR_CELL_REVEN_CEVEN_SET, highlighterColors.TABLE_HDR_CELL_REVEN_CEVEN_ATTR_KEY) fillMap(map, TABLE_HDR_CELL_REVEN_CODD_SET, highlighterColors.TABLE_HDR_CELL_REVEN_CODD_ATTR_KEY) fillMap(map, TABLE_HDR_CELL_RODD_CEVEN_SET, highlighterColors.TABLE_HDR_CELL_RODD_CEVEN_ATTR_KEY) fillMap(map, TABLE_HDR_CELL_RODD_CODD_SET, highlighterColors.TABLE_HDR_CELL_RODD_CODD_ATTR_KEY) fillMap(map, TABLE_HDR_ROW_EVEN_SET, highlighterColors.TABLE_HDR_ROW_EVEN_ATTR_KEY) fillMap(map, TABLE_HDR_ROW_ODD_SET, highlighterColors.TABLE_HDR_ROW_ODD_ATTR_KEY) fillMap(map, TABLE_SEP_COLUMN_ODD_SET, highlighterColors.TABLE_SEP_COLUMN_ODD_ATTR_KEY) fillMap(map, TABLE_SEP_COLUMN_EVEN_SET, highlighterColors.TABLE_SEP_COLUMN_EVEN_ATTR_KEY) fillMap(map, TABLE_SEPARATOR_ROW_SET, highlighterColors.TABLE_SEPARATOR_ATTR_KEY) fillMap(map, TABLE_SET, highlighterColors.TABLE_ATTR_KEY) fillMap(map, TEXT_SET, highlighterColors.TEXT_ATTR_KEY) fillMap(map, TOC_SET, highlighterColors.TOC_ATTR_KEY) fillMap(map, GEN_CONTENT_SET, highlighterColors.GEN_CONTENT_ATTR_KEY) fillMap(map, TOC_MARKER_SET, highlighterColors.TOC_MARKER_ATTR_KEY) fillMap(map, TOC_OPTION_SET, highlighterColors.TOC_OPTION_ATTR_KEY) fillMap(map, SIM_TOC_TITLE_SET, highlighterColors.SIM_TOC_TITLE_ATTR_KEY) fillMap(map, TASK_ITEM_MARKER_SET, highlighterColors.TASK_ITEM_MARKER_ATTR_KEY) fillMap(map, TASK_DONE_MARKER_ITEM_SET, highlighterColors.TASK_DONE_ITEM_MARKER_ATTR_KEY) fillMap(map, VERBATIM_SET, highlighterColors.VERBATIM_ATTR_KEY) fillMap(map, VERBATIM_MARKER_SET, highlighterColors.VERBATIM_MARKER_ATTR_KEY) fillMap(map, VERBATIM_CONTENT_SET, highlighterColors.VERBATIM_CONTENT_ATTR_KEY) fillMap(map, VERBATIM_LANG_SET, highlighterColors.VERBATIM_LANG_ATTR_KEY) fillMap(map, WIKI_LINK_SET, highlighterColors.WIKI_LINK_ATTR_KEY) fillMap(map, WIKI_LINK_SEPARATOR_SET, highlighterColors.WIKI_LINK_SEPARATOR_ATTR_KEY) fillMap(map, WIKI_LINK_REF_SET, highlighterColors.WIKI_LINK_REF_ATTR_KEY) fillMap(map, WIKI_LINK_REF_ANCHOR_SET, highlighterColors.WIKI_LINK_REF_ANCHOR_ATTR_KEY) fillMap(map, WIKI_LINK_REF_ANCHOR_MARKER_SET, highlighterColors.WIKI_LINK_REF_ANCHOR_MARKER_ATTR_KEY) fillMap(map, WIKI_LINK_TEXT_SET, highlighterColors.WIKI_LINK_TEXT_ATTR_KEY) map } private fun fillMap(map: HashMap<IElementType, TextAttributesKey>, keys: TokenSet, value: TextAttributesKey) { fillMap(map, value, *keys.types) } @JvmStatic fun fillMap(keys: TokenSet, value: TextAttributesKey) { fillMap(ATTRIBUTES, value, *keys.types) } private fun fillMap(map: HashMap<IElementType, TextAttributesKey>, value: TextAttributesKey, vararg types: IElementType) { for (type in types) { map[type] = value } } @JvmStatic fun getAttributes(): Map<IElementType, TextAttributesKey> { return ATTRIBUTES } @JvmStatic fun getMergedKeys(): Collection<TextAttributesKey> { return MERGED_ATTRIBUTES.keys } @JvmStatic fun addMergedKey(combinedKey: TextAttributesKey, baseKey: TextAttributesKey, overlayKey: TextAttributesKey) { val list = ArrayList<TextAttributesKey>(2) list.add(baseKey) list.add(overlayKey) MERGED_ATTRIBUTES.put(combinedKey, list) } private var inMergeAttributes = AtomicBoolean(false) @JvmStatic fun computeMergedAttributes(initEditors: Boolean) { if (!inMergeAttributes.getAndSet(true)) { try { val scheme = EditorColorsManager.getInstance().globalScheme val keys = getMergedKeys() for (key in keys) { val list = MERGED_ATTRIBUTES[key] ?: continue var combinedAttr: TextAttributes? = null for (attrKey in list) { val attr = scheme.getAttributes(attrKey) if (combinedAttr == null) { combinedAttr = attr.clone() } else { combinedAttr.foregroundColor = combineColors(combinedAttr.foregroundColor, attr.foregroundColor) combinedAttr.backgroundColor = combineColors(combinedAttr.backgroundColor, attr.backgroundColor) combinedAttr.effectType = if (combinedAttr.effectColor == null) attr.effectType else combinedAttr.effectType combinedAttr.effectColor = combineColors(combinedAttr.effectColor, attr.effectColor) combinedAttr.errorStripeColor = combineColors(combinedAttr.errorStripeColor, attr.errorStripeColor) combinedAttr.fontType = combineFontType(combinedAttr.fontType, attr.fontType) } } scheme.setAttributes(key, combinedAttr) } if (initEditors) { val manager = EditorColorsManager.getInstance() as EditorColorsManagerImpl manager.schemeChangedOrSwitched(manager.globalScheme) } } finally { inMergeAttributes.set(false) } } } private fun combineFontType(baseFontType: Int, overlayFontType: Int): Int { return baseFontType or overlayFontType } @JvmStatic fun combineColors(baseColor: Color?, overlayColor: Color?): Color? { if (overlayColor == null) return baseColor if (baseColor == null) return overlayColor val colors = baseColor.getRGBComponents(null) val overlays = overlayColor.getRGBComponents(null) val overlayAlpha = 0.5f val baseAlpha = (1.0f - overlayAlpha) val averageAlpha = 0.10f val multiplyAlpha = (1.0f - averageAlpha) val results = colors.clone() for (i in 0 .. 2) { if (colors[i] * overlays[i] < 0.25) { results[i] = 1.0f - (((1.0f - colors[i]) * baseAlpha + (1.0f - overlays[i]) * overlayAlpha) * (1.0f - averageAlpha) + (1.0f - colors[i]) * (1.0f - overlays[i]) * (1.0f - multiplyAlpha)) } else { results[i] = (colors[i] * baseAlpha + overlays[i] * overlayAlpha) * averageAlpha + colors[i] * overlays[i] * multiplyAlpha } } return Color(results[0], results[1], results[2], colors[3]) } } }
apache-2.0
7840bce7805a1aa1e2a05da0986b9a74
64.419872
205
0.683308
3.87379
false
false
false
false
TeleSoftas/android-core
telesoftas-common/src/test/kotlin/com/telesoftas/core/common/presenter/BasePresenterTest.kt
1
2848
package com.telesoftas.core.common.presenter import com.nhaarman.mockito_kotlin.mock import org.junit.Assert.* import org.junit.Before import org.junit.Test class BasePresenterTest { private lateinit var presenter: TestBasePresenter private val view = mock<Any>() @Before fun setUp() { presenter = TestBasePresenter() } @Test fun getView_defaultsToNull() { assertNull("Default view not null", presenter.testView) } @Test fun getView_takeView_returnsTakenView() { presenter.takeView(view) assertEquals("Modified the taken view", view, presenter.testView) } @Test fun getView_dropView_nullifiesView() { presenter.takeView(view) assertEquals("Modified the taken view", view, presenter.testView) presenter.dropView() assertNull("Dropped view not null", presenter.testView) } @Test fun getView_setView_returnsSetView() { presenter.testView = view assertEquals("Modified the taken view", view, presenter.testView) } @Test fun hasView_trueWhenViewTaken() { presenter.takeView(view) val actual = presenter.testHasView() assertTrue("False with taken view", actual) } @Test fun hasView_defaultToFalse() { val actual = presenter.testHasView() assertFalse("True by default", actual) } @Test fun hasView_dropView_returnsFalse() { presenter.takeView(view) val actual = presenter.testHasView() assertTrue("False with taken view", actual) presenter.dropView() val droppedActual = presenter.testHasView() assertFalse("True with dropped view", droppedActual) } @Test fun onView_takeView_invokesAction() { presenter.takeView(view) var actionCalled = false presenter.doActionOnView { actionCalled = true } assertTrue("Action never called", actionCalled) } @Test fun onView_noView_neverInvokesAction() { presenter.doActionOnView { throw IllegalStateException("Action should never be called") } } @Test fun onView_dropView_neverInvokesAction() { presenter.takeView(view) var actionCalled = false presenter.doActionOnView { actionCalled = true } assertTrue("Action never called", actionCalled) presenter.dropView() presenter.doActionOnView { throw IllegalStateException("Action should never be called") } } class TestBasePresenter : BasePresenter<Any>() { var testView: Any? get() = super.view set(value) { super.view = value } fun testHasView(): Boolean = hasView() fun doActionOnView(action: Any.() -> Unit) { onView { action() } } } }
apache-2.0
ca7ddc4956a400ae85b0c7f4e7337f9f
22.941176
97
0.634831
4.600969
false
true
false
false
dya-tel/TSU-Schedule
src/main/kotlin/ru/dyatel/tsuschedule/layout/LessonView.kt
1
4493
package ru.dyatel.tsuschedule.layout import android.content.Context import android.view.View import android.widget.TextView import org.jetbrains.anko._LinearLayout import org.jetbrains.anko.alignParentLeft import org.jetbrains.anko.alignParentRight import org.jetbrains.anko.backgroundResource import org.jetbrains.anko.find import org.jetbrains.anko.horizontalMargin import org.jetbrains.anko.leftOf import org.jetbrains.anko.matchParent import org.jetbrains.anko.relativeLayout import org.jetbrains.anko.textView import org.jetbrains.anko.verticalLayout import org.jetbrains.anko.verticalMargin import org.jetbrains.anko.view import ru.dyatel.tsuschedule.R import ru.dyatel.tsuschedule.model.GroupLesson import ru.dyatel.tsuschedule.model.Lesson import ru.dyatel.tsuschedule.model.LessonType import ru.dyatel.tsuschedule.model.TeacherLesson import ru.dyatel.tsuschedule.utilities.hideIf abstract class LessonView<in T : Lesson>(context: Context) : _LinearLayout(context) { private companion object { val timeViewId = View.generateViewId() val auditoryViewId = View.generateViewId() val disciplineViewId = View.generateViewId() } private val typeMarkerView: View private val timeView: TextView private val auditoryView: TextView private val disciplineView: TextView init { lparams(width = matchParent) { horizontalMargin = DIM_SMALL verticalMargin = DIM_MEDIUM } typeMarkerView = view().lparams(width = DIM_MEDIUM, height = matchParent) { rightMargin = DIM_CARD_PADDING } verticalLayout { lparams(width = matchParent) relativeLayout { lparams(width = matchParent) textView { id = timeViewId }.lparams { leftOf(auditoryViewId) alignParentLeft() } textView { id = auditoryViewId }.lparams { alignParentRight() } } textView { id = disciplineViewId } customize(this) } timeView = find(timeViewId) auditoryView = find(auditoryViewId) disciplineView = find(disciplineViewId) } protected abstract fun customize(container: _LinearLayout) open fun bind(lesson: T) { typeMarkerView.backgroundResource = when (lesson.type) { LessonType.PRACTICE -> R.color.practice_color LessonType.LECTURE -> R.color.lecture_color LessonType.LABORATORY -> R.color.laboratory_color LessonType.UNKNOWN -> R.color.unknown_color } val typeText = when (lesson.type) { LessonType.PRACTICE -> R.string.lesson_type_practice LessonType.LECTURE -> R.string.lesson_type_lecture LessonType.LABORATORY -> R.string.lesson_type_laboratory LessonType.UNKNOWN -> null }?.let { context.getString(it) } timeView.text = lesson.time auditoryView.apply { text = lesson.auditory hideIf { text.isEmpty() } } disciplineView.text = typeText?.let { "${lesson.discipline} ($typeText)" } ?: lesson.discipline } open fun unbind() { timeView.text = null auditoryView.text = null disciplineView.text = null } } class GroupLessonView(context: Context) : LessonView<GroupLesson>(context) { private lateinit var teacherView: TextView override fun customize(container: _LinearLayout) { container.apply { teacherView = textView() } } override fun bind(lesson: GroupLesson) { super.bind(lesson) teacherView.apply { text = lesson.teacher hideIf { text.isEmpty() } } } override fun unbind() { teacherView.text = null super.unbind() } } class TeacherLessonView(context: Context) : LessonView<TeacherLesson>(context) { private lateinit var groupView: TextView override fun customize(container: _LinearLayout) { container.apply { groupView = textView() } } override fun bind(lesson: TeacherLesson) { super.bind(lesson) groupView.apply { text = lesson.groups.joinToString(", ").takeUnless { it.isEmpty() } hideIf { text.isEmpty() } } } override fun unbind() { groupView.text = null super.unbind() } }
mit
035e1d44d5dc95a4dd1961202e30ad95
27.987097
103
0.640107
4.561421
false
false
false
false
http4k/http4k
http4k-metrics-micrometer/src/test/kotlin/org/http4k/filter/helpers.kt
1
1675
package org.http4k.filter import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.has import com.natpryce.hamkrest.present import io.micrometer.core.instrument.Counter import io.micrometer.core.instrument.Meter import io.micrometer.core.instrument.MeterRegistry import io.micrometer.core.instrument.Tag import io.micrometer.core.instrument.Timer import java.util.concurrent.TimeUnit internal fun assert(registry: MeterRegistry, vararg matcher: Matcher<MeterRegistry>) = matcher.forEach { assertThat(registry, it) } internal fun hasCounter(name: String, tags: List<Tag>, matcher: Matcher<Counter>? = null): Matcher<MeterRegistry> = has("a counter named $name with tags ${tags.map { "${it.key}=${it.value}" }}", { it.find(name).tags(tags).counter() }, present(matcher) ) internal fun hasTimer(name: String, tags: List<Tag>, matcher: Matcher<Timer>? = null): Matcher<MeterRegistry> = has("a timer named $name with tags ${tags.map { "${it.key}=${it.value}" }}", { it.find(name).tags(tags).timer() }, present(matcher) ) internal fun counterCount(value: Long) = has<Counter, Long>("count", { it.count().toLong() }, equalTo(value)) internal fun timerCount(value: Long) = has<Timer, Long>("count", { it.count() }, equalTo(value)) internal fun timerTotalTime(millis: Long) = has<Timer, Long>("total time", { it.totalTime(TimeUnit.MILLISECONDS).toLong() }, equalTo(millis)) internal fun description(value: String) = has<Meter, String>("description", { it.id.description ?: "unknown" }, equalTo(value))
apache-2.0
833c3c8f5db03cc47063c51ee7ed0312
41.948718
115
0.715224
3.755605
false
false
false
false
geckour/Egret
app/src/main/java/com/geckour/egret/view/fragment/AccountManageFragment.kt
1
4857
package com.geckour.egret.view.fragment import android.app.Activity import android.databinding.DataBindingUtil import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.geckour.egret.R import com.geckour.egret.api.MastodonClient import com.geckour.egret.api.model.Account import com.geckour.egret.databinding.FragmentManageAccountBinding import com.geckour.egret.model.AccessToken import com.geckour.egret.util.Common import com.geckour.egret.util.OrmaProvider import com.geckour.egret.view.activity.LoginActivity import com.geckour.egret.view.activity.MainActivity import com.geckour.egret.view.adapter.ManageAccountAdapter import com.geckour.egret.view.adapter.model.AccountContent import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import timber.log.Timber class AccountManageFragment: BaseFragment() { lateinit private var binding: FragmentManageAccountBinding private val adapter: ManageAccountAdapter by lazy { ManageAccountAdapter() } private val preItems: ArrayList<AccountContent> = ArrayList() companion object { val TAG: String = this::class.java.simpleName fun newInstance(): AccountManageFragment { val fragment = AccountManageFragment() return fragment } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_manage_account, container, false) return binding.root } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val helper = Common.getSwipeToDismissTouchHelperForManageAccount(adapter) helper.attachToRecyclerView(binding.recyclerView) binding.recyclerView.addItemDecoration(helper) binding.recyclerView.adapter = adapter } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) bindSavedAccounts() } override fun onResume() { super.onResume() if (activity is MainActivity) ((activity as MainActivity).findViewById(R.id.fab) as FloatingActionButton?)?.hide() } override fun onPause() { super.onPause() removeAccounts(adapter.getItems(), activity) } fun bindSavedAccounts() { adapter.clearItems() preItems.clear() Observable.fromIterable(OrmaProvider.db.selectFromAccessToken()) .map { token -> MastodonClient(Common.setAuthInfo(token) ?: throw IllegalArgumentException()).getAccount(token.accountId) .map { val domain = OrmaProvider.db.selectFromInstanceAuthInfo().idEq(token.instanceId).last().instance AccountContent(token, "@${it.acct}@$domain", it.avatarUrl) } } .subscribeOn(Schedulers.newThread()) .compose(bindToLifecycle()) .subscribe({ it.observeOn(AndroidSchedulers.mainThread()) .subscribe({ content -> adapter.addItem(content) preItems.add(content) }, Throwable::printStackTrace) }, Throwable::printStackTrace) } fun removeAccounts(items: List<AccountContent>, activity: Activity) { val shouldRemoveItems = preItems.filter { items.none { item -> it.token.id == item.token.id } } Observable.fromIterable(shouldRemoveItems) .flatMap { Single.merge<Int>( OrmaProvider.db.deleteFromInstanceAuthInfo().idEq(it.token.instanceId).executeAsSingle(), OrmaProvider.db.deleteFromAccessToken().idEq(it.token.id).executeAsSingle() ) .toObservable() } .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { Timber.d("an account deleted: $it") }, Throwable::printStackTrace, { if (items.isEmpty()) showLoginActivity(activity) }) } fun showLoginActivity(activity: Activity) { val intent = LoginActivity.getIntent(activity) activity.startActivity(intent) } }
gpl-3.0
66e248e900e77316487e6feed21403d8
37.547619
129
0.652254
5.216971
false
false
false
false
strooooke/quickfit
app/src/main/java/com/lambdasoup/quickfit/alarm/Alarms.kt
1
21352
/* * Copyright 2016-2019 Juliane Lehmann <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.lambdasoup.quickfit.alarm import android.app.AlarmManager import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.ContentValues import android.content.Context import android.content.Intent import android.database.Cursor import android.media.RingtoneManager import android.net.Uri import android.os.Build import android.os.Bundle import androidx.annotation.AnyThread import androidx.annotation.WorkerThread import androidx.core.app.AlarmManagerCompat import androidx.core.app.NotificationCompat import androidx.core.app.TaskStackBuilder import androidx.core.content.ContextCompat import androidx.core.database.getLongOrNull import androidx.preference.PreferenceManager import com.lambdasoup.quickfit.Constants.NOTIFICATION_ALARM import com.lambdasoup.quickfit.Constants.NOTIFICATION_CHANNEL_ID_ALARM import com.lambdasoup.quickfit.Constants.PENDING_INTENT_ALARM_RECEIVER import com.lambdasoup.quickfit.Constants.PENDING_INTENT_DID_IT import com.lambdasoup.quickfit.Constants.PENDING_INTENT_DISMISS_ALARM import com.lambdasoup.quickfit.Constants.PENDING_INTENT_SNOOZE import com.lambdasoup.quickfit.Constants.PENDING_INTENT_WORKOUT_LIST import com.lambdasoup.quickfit.FitActivityService import com.lambdasoup.quickfit.R import com.lambdasoup.quickfit.model.DayOfWeek import com.lambdasoup.quickfit.model.FitActivity import com.lambdasoup.quickfit.persist.QuickFitContentProvider import com.lambdasoup.quickfit.persist.QuickFitContract.ScheduleEntry import com.lambdasoup.quickfit.persist.QuickFitContract.WorkoutEntry import com.lambdasoup.quickfit.ui.WorkoutListActivity import com.lambdasoup.quickfit.util.DateTimes import timber.log.Timber import java.util.concurrent.TimeUnit /** * Actual logic for workout reminder alarm tasks. Called by different android components ([AlarmService], [AlarmReceiver], * [ResetAlarmsReceiver]) according to the needs of the Android framework. * * Responsible for database interaction as far as the reminder-related columns are concerned and for the related notifications. */ class Alarms(private val context: Context) { private val notificationManager by lazy { context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager } private val alarmManager by lazy { context.getSystemService(Context.ALARM_SERVICE) as AlarmManager } @WorkerThread fun onSnoozed(scheduleId: Long) { notificationManager.cancel(scheduleId.toString(), NOTIFICATION_ALARM) prepareNextAlert(scheduleId, ScheduleEntry.CURRENT_STATE_SNOOZED) { nowPlusSnoozeTime() } } @WorkerThread fun onDidIt(scheduleId: Long, workoutId: Long) { notificationManager.cancel(scheduleId.toString(), NOTIFICATION_ALARM) FitActivityService.enqueueInsertSession(context, workoutId) context.contentResolver.update( QuickFitContentProvider.getUriSchedulesId(scheduleId), ContentValues(1).apply { put(ScheduleEntry.COL_CURRENT_STATE, ScheduleEntry.CURRENT_STATE_ACKNOWLEDGED) }, null, null ) } @AnyThread fun notify(scheduleId: Long, workoutData: WorkoutNotificationData) { val fitActivity = FitActivity.fromKey(workoutData.activityType, context.resources) val dismissIntent = getForegroundServicePendingIntentCompat( context, PENDING_INTENT_DISMISS_ALARM, AlarmService.getOnNotificationDismissedIntent(context, scheduleId), PendingIntent.FLAG_UPDATE_CURRENT ) val showWorkoutPendingIntent = TaskStackBuilder.create(context) .addNextIntentWithParentStack( Intent(context, WorkoutListActivity::class.java) // for intent disambiguation // and for WorkoutListActivity to show correct workout .setData(QuickFitContentProvider.getUriWorkoutsId(workoutData.workoutId)) // dismiss intent not fired by autocancel .putExtra(WorkoutListActivity.EXTRA_NOTIFICATIONS_CANCEL_INTENT, dismissIntent) ) .getPendingIntent(PENDING_INTENT_WORKOUT_LIST, PendingIntent.FLAG_UPDATE_CURRENT) val didItIntent = getForegroundServicePendingIntentCompat( context, PENDING_INTENT_DID_IT, AlarmService.getDidItIntent(context, workoutData.workoutId, scheduleId), PendingIntent.FLAG_UPDATE_CURRENT ) val snoozeIntent = getForegroundServicePendingIntentCompat( context, PENDING_INTENT_SNOOZE, AlarmService.getSnoozeIntent(context, scheduleId), PendingIntent.FLAG_UPDATE_CURRENT ) val notificationBuilder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID_ALARM) .setContentTitle(context.getString(R.string.notification_alarm_title_single, fitActivity.displayName)) .setContentText(context.getString( R.string.notification_alarm_content_single, context.resources.getQuantityString( R.plurals.duration_mins_format, workoutData.durationMinutes, workoutData.durationMinutes ), workoutData.label.orEmpty() )) .setContentIntent(showWorkoutPendingIntent) .addAction( R.drawable.ic_done_white_24dp, context.getString(R.string.notification_action_did_it), didItIntent ) .addAction( R.drawable.ic_alarm_white_24dp, context.getString(R.string.notification_action_remind_me_later), snoozeIntent ) .setDeleteIntent(dismissIntent) // Only effect is on content-click. cancelIntent is not fired, despite the name. Actions need to cancel the notification // themselves. .setAutoCancel(true) // Notification might be re-displayed after device time corrections. No point in re-alerting the user. // If the user does not dismiss the notification for a week, they won't get noisily alerted about the _next_ occurence. // This is acceptable to me. .setOnlyAlertOnce(true) .setPriority(NotificationCompat.PRIORITY_HIGH) .setSmallIcon(R.drawable.ic_stat_quickfit_icon) .setColor(ContextCompat.getColor(context, R.color.colorPrimary)) .setCategory(NotificationCompat.CATEGORY_ALARM) // Starting with O, those properties are set on the notification channel if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { val preferences = PreferenceManager.getDefaultSharedPreferences(context) val ringtoneUriStr = preferences.getString(context.getString(R.string.pref_key_notification_ringtone), null) notificationBuilder.setSound( when { ringtoneUriStr == null -> RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION) ringtoneUriStr.isNotEmpty() -> Uri.parse(ringtoneUriStr) else -> null } ) val ledOn = preferences.getBoolean(context.getString(R.string.pref_key_notification_led), true) val vibrationOn = preferences.getBoolean(context.getString(R.string.pref_key_notification_vibrate), true) notificationBuilder.setDefaults( (if (ledOn) Notification.DEFAULT_LIGHTS else 0) or if (vibrationOn) Notification.DEFAULT_VIBRATE else 0 ) } // Deliberately not using groups, for the time being, because we'd have to create a summary notification, so we would need to // know about all currently displaying workout schedule notifications. // On API levels >= 24, we could do this by querying the NotificationManager for all those, and construct an inbox-style // summary from the snippets. But on exactly those API levels, the system already does this for us, as long as we do *not* // specify a group. // On API levels < 24, we cannot query the NotificationManager for this information. We could query our own database - and on those // API levels, we can reliably do I/O work on an AlarmManager broadcast, in principle - but this would mean maintaining a separate // implementation for those API levels. Might happen at a later date - or we might raise minSdk to 24 instead. // While it is not nice of us to potentially generate loads of notifications for the same id on those API levels (and was advised // against in the documentation earlier), we can live with this for the time being. notificationManager.notify(scheduleId.toString(), NOTIFICATION_ALARM, notificationBuilder.build()) } @WorkerThread fun onScheduleChanged(scheduleId: Long) { Timber.d("onScheduleChanged: $scheduleId") notificationManager.cancel(scheduleId.toString(), NOTIFICATION_ALARM) prepareNextAlert(scheduleId, ScheduleEntry.CURRENT_STATE_ACKNOWLEDGED, this::nextOccurence) } @WorkerThread fun onScheduleDeleted(scheduleId: Long) { Timber.d("onScheduleDeleted: $scheduleId") notificationManager.cancel(scheduleId.toString(), NOTIFICATION_ALARM) alarmManager.cancel(buildAlarmReceiverPendingIntent(scheduleId, null)) } @WorkerThread fun onNotificationShown(scheduleId: Long) { prepareNextAlert(scheduleId, ScheduleEntry.CURRENT_STATE_DISPLAYING, this::nextOccurence) } @WorkerThread fun onNotificationDismissed(scheduleId: Long) { context.contentResolver.update( QuickFitContentProvider.getUriSchedulesId(scheduleId), ContentValues(1).apply { put(ScheduleEntry.COL_CURRENT_STATE, ScheduleEntry.CURRENT_STATE_ACKNOWLEDGED) }, null, null ) } @WorkerThread fun resetAlarms() { val now = System.currentTimeMillis() Timber.d("resetAlarms, now=$now") context.contentResolver.query( QuickFitContentProvider.getUriWorkoutsList(), arrayOf( WorkoutEntry.SCHEDULE_ID, WorkoutEntry.WORKOUT_ID, WorkoutEntry.ACTIVITY_TYPE, WorkoutEntry.LABEL, WorkoutEntry.DURATION_MINUTES, WorkoutEntry.DAY_OF_WEEK, WorkoutEntry.HOUR, WorkoutEntry.MINUTE, WorkoutEntry.NEXT_ALARM_MILLIS, WorkoutEntry.CURRENT_STATE ), "${ScheduleEntry.TABLE_NAME}.${ScheduleEntry.COL_ID} IS NOT NULL", null, null ).use { cursor -> if (cursor == null) { return@resetAlarms } while (cursor.moveToNext()) { val scheduleId = cursor.getLong(cursor.getColumnIndexOrThrow(WorkoutEntry.SCHEDULE_ID)) val nextAlarmMillis = cursor.getLongOrNull(cursor.getColumnIndexOrThrow(WorkoutEntry.NEXT_ALARM_MILLIS)) val currentState = cursor.getString(cursor.getColumnIndexOrThrow(WorkoutEntry.CURRENT_STATE)) val workoutNotificationData = WorkoutNotificationData.fromRow(cursor) if (nextAlarmMillis == null) { Timber.d("not yet scheduled: $scheduleId $workoutNotificationData") // system had no chance yet to compute next alert time, so let's do that now. prepareNextAlert(scheduleId, ScheduleEntry.CURRENT_STATE_ACKNOWLEDGED, this::nextOccurence) } else if (nextAlarmMillis <= now || currentState == ScheduleEntry.CURRENT_STATE_DISPLAYING) { Timber.d("already past or was displaying: $scheduleId $workoutNotificationData") notify(scheduleId, workoutNotificationData) prepareNextAlert(scheduleId, ScheduleEntry.CURRENT_STATE_DISPLAYING, this::nextOccurence) } else { Timber.d("re-enqueue: $scheduleId $workoutNotificationData") enqueueWithAlarmManager(scheduleId, nextAlarmMillis, workoutNotificationData) } } } } private fun nowPlusSnoozeTime(): Long { val durationMinutes = PreferenceManager.getDefaultSharedPreferences(context).getString( context.getString(R.string.pref_key_snooze_duration_mins), "60" )!!.toLong() // Why not an Int pref? Because of the string array resource. There are no Int array resources. return System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(durationMinutes) } private fun nextOccurence(schedule: Schedule) = DateTimes.getNextOccurrence(System.currentTimeMillis(), schedule.dayOfWeek, schedule.hour, schedule.minute) @WorkerThread private fun prepareNextAlert(scheduleId: Long, newCurrentState: String, getNextAlarmMillis: (Schedule) -> Long) { Timber.d("prepareNextAlert: $scheduleId") val (schedule, workoutData) = context.contentResolver.query( QuickFitContentProvider.getUriWorkoutsList(), arrayOf( WorkoutEntry.SCHEDULE_ID, WorkoutEntry.WORKOUT_ID, WorkoutEntry.ACTIVITY_TYPE, WorkoutEntry.LABEL, WorkoutEntry.DURATION_MINUTES, WorkoutEntry.DAY_OF_WEEK, WorkoutEntry.HOUR, WorkoutEntry.MINUTE ), "${ScheduleEntry.TABLE_NAME}.${ScheduleEntry.COL_ID}=?", arrayOf(scheduleId.toString()), null ).use { cursor -> if (cursor?.moveToNext() == true) { Pair( Schedule.fromRow(cursor), WorkoutNotificationData.fromRow(cursor) ) } else { Timber.w("Schedule $scheduleId does not exist, aborting prepareNextAlert") return@prepareNextAlert } } val nextAlarmMillis = getNextAlarmMillis(schedule) enqueueWithAlarmManager(scheduleId, nextAlarmMillis, workoutData) context.contentResolver.update( QuickFitContentProvider.getUriSchedulesId(scheduleId), ContentValues(2).apply { put(ScheduleEntry.COL_NEXT_ALARM_MILLIS, nextAlarmMillis) put(ScheduleEntry.COL_CURRENT_STATE, newCurrentState) }, null, null ) } private fun enqueueWithAlarmManager(scheduleId: Long, nextAlarmMillis: Long, workoutData: WorkoutNotificationData) { val alarmReceiverPendingIntent = buildAlarmReceiverPendingIntent(scheduleId, workoutData) Timber.d("enqueuing $scheduleId $workoutData at $nextAlarmMillis") AlarmManagerCompat.setExactAndAllowWhileIdle( alarmManager, AlarmManager.RTC_WAKEUP, nextAlarmMillis, alarmReceiverPendingIntent ) } private fun buildAlarmReceiverPendingIntent(scheduleId: Long, workoutData: WorkoutNotificationData?) = PendingIntent.getBroadcast( context, PENDING_INTENT_ALARM_RECEIVER, // disambiguation is via Intent data AlarmReceiver.getNotifyIntent(context, scheduleId, workoutData), PendingIntent.FLAG_UPDATE_CURRENT ) } @Suppress("SameParameterValue") private fun getForegroundServicePendingIntentCompat(context: Context, requestCode: Int, intent: Intent, flags: Int) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { PendingIntent.getForegroundService(context, requestCode, intent, flags) } else { PendingIntent.getService(context, requestCode, intent, flags) } private data class Schedule constructor( val id: Long, val dayOfWeek: DayOfWeek, val hour: Int, val minute: Int ) { companion object { internal fun fromRow(cursor: Cursor): Schedule { val dayOfWeek = DayOfWeek.valueOf(cursor.getString(cursor.getColumnIndexOrThrow(WorkoutEntry.DAY_OF_WEEK))) val hour = cursor.getInt(cursor.getColumnIndexOrThrow(WorkoutEntry.HOUR)) val minute = cursor.getInt(cursor.getColumnIndexOrThrow(WorkoutEntry.MINUTE)) val id = cursor.getLong(cursor.getColumnIndexOrThrow(WorkoutEntry.SCHEDULE_ID)) return Schedule(id, dayOfWeek, hour, minute) } } } data class WorkoutNotificationData constructor( val workoutId: Long, val activityType: String, val label: String?, val durationMinutes: Int ) { /* * Passing custom Parcelables through other processes (e.g. as a PendingIntent extra) fails in general - see * https://commonsware.com/blog/2016/07/22/be-careful-where-you-use-custom-parcelables.html * * In particular, when used as an extra in a PendingIntent for AlarmManager, this never works. * * Tried using the workaround suggested in * https://stackoverflow.com/questions/18000093/how-to-marshall-and-unmarshall-a-parcelable-to-a-byte-array-with-help-of-parcel/18000094#18000094 * and gave that avenue up again, because I don't see a way of making properly generic `Bundle.putSafeExtra` and * `<T : Parcelable> Bundle.getSafeParcelableExtra` extension methods - the latter fails, due to the fantastic * design of the CREATOR object which is not part of the Parcelable interface (and cannot be, due to the Java type system). * So there's no way of obtaining it from the (reified) type parameter, so we'd have to pass it in at each use. * * And then we notice that when using @Parcelize for auto-generated Parcelable implementation, this CREATOR object * does not exist (at least not enough for the IDE to see it at compile time). * * So if we have to hand-generate the serialization anyway, going through Bundle is the more readable approach. */ fun asBundle(): Bundle = Bundle(4).apply { putLong(KEY_WORKOUT_ID, workoutId) putString(KEY_ACTIVITY_TYPE, activityType) putString(KEY_LABEL, label) putInt(KEY_DURATION_MINUTES, durationMinutes) } companion object { private const val KEY_WORKOUT_ID = "com.lambdasoup.quickfit.alarm.WorkoutNotificationData.KEY_WORKOUT_ID" private const val KEY_ACTIVITY_TYPE = "com.lambdasoup.quickfit.alarm.WorkoutNotificationData.KEY_ACTIVITY_TYPE" private const val KEY_LABEL = "com.lambdasoup.quickfit.alarm.WorkoutNotificationData.KEY_LABEL" private const val KEY_DURATION_MINUTES = "com.lambdasoup.quickfit.alarm.WorkoutNotificationData.KEY_DURATION_MINUTES" internal fun fromBundle(bundle: Bundle): WorkoutNotificationData = with(bundle) { WorkoutNotificationData( getLong(KEY_WORKOUT_ID), getString(KEY_ACTIVITY_TYPE)!!, getString(KEY_LABEL), getInt(KEY_DURATION_MINUTES) ) } internal fun fromRow(cursor: Cursor): WorkoutNotificationData { val workoutId = cursor.getLong(cursor.getColumnIndexOrThrow(WorkoutEntry.WORKOUT_ID)) val activityType = cursor.getString(cursor.getColumnIndexOrThrow(WorkoutEntry.ACTIVITY_TYPE)) val label = cursor.getColumnIndexOrThrow(WorkoutEntry.LABEL).let { if (!cursor.isNull(it)) cursor.getString(it) else "" } val durationMinutes = cursor.getInt(cursor.getColumnIndexOrThrow(WorkoutEntry.DURATION_MINUTES)) return WorkoutNotificationData(workoutId, activityType, label, durationMinutes) } } }
apache-2.0
7cb3124661c5a8bd5dcd1d616b615ad5
47.527273
149
0.654365
5.161228
false
false
false
false
msebire/intellij-community
platform/credential-store/src/kdbx/KeePassDatabase.kt
1
9426
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.credentialStore.kdbx import com.intellij.credentialStore.OneTimeString import com.intellij.credentialStore.createSecureRandom import com.intellij.credentialStore.generateBytes import com.intellij.openapi.util.JDOMUtil import com.intellij.util.getOrCreate import com.intellij.util.io.toByteArray import org.bouncycastle.crypto.SkippingStreamCipher import org.bouncycastle.crypto.engines.ChaCha7539Engine import org.bouncycastle.crypto.params.KeyParameter import org.bouncycastle.crypto.params.ParametersWithIV import org.jdom.Element import java.io.OutputStream import java.nio.ByteBuffer import java.nio.CharBuffer import java.security.SecureRandom import java.time.LocalDateTime import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.util.* internal object KdbxDbElementNames { const val group = "Group" const val entry = "Entry" const val root = "Root" const val name = "Name" } internal val LOCATION_CHANGED = arrayOf("Times", "LocationChanged") internal val USAGE_COUNT_ELEMENT_NAME = arrayOf("Times", "UsageCount") internal val EXPIRES_ELEMENT_NAME = arrayOf("Times", "Expires") internal val ICON_ELEMENT_NAME = arrayOf("IconID") internal val UUID_ELEMENT_NAME = arrayOf("UUID") internal val LAST_MODIFICATION_TIME_ELEMENT_NAME = arrayOf("Times", "LastModificationTime") internal val CREATION_TIME_ELEMENT_NAME = arrayOf("Times", "CreationTime") internal val LAST_ACCESS_TIME_ELEMENT_NAME = arrayOf("Times", "LastAccessTime") internal val EXPIRY_TIME_ELEMENT_NAME = arrayOf("Times", "ExpiryTime") internal var dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") private fun createRandomlyInitializedChaCha7539Engine(secureRandom: SecureRandom): SkippingStreamCipher { val engine = ChaCha7539Engine() initCipherRandomly(secureRandom, engine) return engine } private fun initCipherRandomly(secureRandom: SecureRandom, engine: SkippingStreamCipher) { val keyParameter = KeyParameter(secureRandom.generateBytes(32)) engine.init(true, ParametersWithIV(keyParameter, secureRandom.generateBytes(12))) } // we should on each save change protectedStreamKey for security reasons (as KeeWeb also does) // so, this requirement (is it really required?) can force us to re-encrypt all passwords on save internal class KeePassDatabase(private val rootElement: Element = createEmptyDatabase()) { private var secureStringCipher = lazy { createRandomlyInitializedChaCha7539Engine(createSecureRandom()) } @Volatile var isDirty: Boolean = false internal set val rootGroup: KdbxGroup init { val rootElement = rootElement.getOrCreate(KdbxDbElementNames.root) val groupElement = rootElement.getChild(KdbxDbElementNames.group) if (groupElement == null) { rootGroup = createGroup(this, null) rootGroup.name = KdbxDbElementNames.root rootElement.addContent(rootGroup.element) } else { rootGroup = KdbxGroup(groupElement, this, null) } } internal fun protectValue(value: CharSequence) = StringProtectedByStreamCipher(value, secureStringCipher.value) @Synchronized fun save(credentials: KeePassCredentials, outputStream: OutputStream, secureRandom: SecureRandom) { val kdbxHeader = KdbxHeader(secureRandom) kdbxHeader.writeKdbxHeader(outputStream) val metaElement = rootElement.getOrCreate("Meta") metaElement.getOrCreate("HeaderHash").text = Base64.getEncoder().encodeToString(kdbxHeader.headerHash) metaElement.getOrCreate("MemoryProtection").getOrCreate("ProtectPassword").text = "True" kdbxHeader.createEncryptedStream(credentials.key, outputStream).writer().use { ProtectedXmlWriter(createSalsa20StreamCipher(kdbxHeader.protectedStreamKey)).printElement(it, rootElement, 0) } // should we init secureStringCipher if now we have secureRandom? // on first glance yes, because creating SkippingStreamCipher is very fast and not memory hungry, and creating SecureRandom is a cost operation, // but no - no need to init because if save called, it means that database is dirty for some reasons already... // but yes - because maybe database is dirty due to change some unprotected value (url, user name). if (secureStringCipher.isInitialized()) { initCipherRandomly(secureRandom, secureStringCipher.value) } else { secureStringCipher = lazyOf(createRandomlyInitializedChaCha7539Engine(secureRandom)) } isDirty = false } fun createEntry(title: String): KdbxEntry { val element = Element(KdbxDbElementNames.entry) ensureElements(element, mandatoryEntryElements) val result = KdbxEntry(element, this, null) result.title = title return result } } private val mandatoryEntryElements: Map<Array<String>, ValueCreator> = linkedMapOf( UUID_ELEMENT_NAME to UuidValueCreator(), ICON_ELEMENT_NAME to ConstantValueCreator("0"), CREATION_TIME_ELEMENT_NAME to DateValueCreator(), LAST_MODIFICATION_TIME_ELEMENT_NAME to DateValueCreator(), LAST_ACCESS_TIME_ELEMENT_NAME to DateValueCreator(), EXPIRY_TIME_ELEMENT_NAME to DateValueCreator(), EXPIRES_ELEMENT_NAME to ConstantValueCreator("False"), USAGE_COUNT_ELEMENT_NAME to ConstantValueCreator("0"), LOCATION_CHANGED to DateValueCreator() ) internal fun ensureElements(element: Element, childElements: Map<Array<String>, ValueCreator>) { for ((elementPath, value) in childElements) { val result = findElement(element, elementPath) if (result == null) { var currentElement = element for (elementName in elementPath) { currentElement = currentElement.getOrCreate(elementName) } currentElement.text = value.value } } } private fun findElement(element: Element, elementPath: Array<String>): Element? { var result = element for (elementName in elementPath) { result = result.getChild(elementName) ?: return null } return result } internal fun formattedNow() = LocalDateTime.now(ZoneOffset.UTC).format(dateFormatter) internal interface ValueCreator { val value: String } internal class ConstantValueCreator(override val value: String) : ValueCreator internal class DateValueCreator : ValueCreator { override val value: String get() = formattedNow() } internal class UuidValueCreator : ValueCreator { override val value: String get() = base64FromUuid(UUID.randomUUID()) } private fun base64FromUuid(uuid: UUID): String { val b = ByteBuffer.wrap(ByteArray(16)) b.putLong(uuid.mostSignificantBits) b.putLong(uuid.leastSignificantBits) return Base64.getEncoder().encodeToString(b.array()) } private fun createEmptyDatabase(): Element { val creationDate = formattedNow() @Suppress("SpellCheckingInspection") return JDOMUtil.load("""<KeePassFile> <Meta> <Generator>IJ</Generator> <HeaderHash></HeaderHash> <DatabaseName>New Database</DatabaseName> <DatabaseNameChanged>${creationDate}</DatabaseNameChanged> <DatabaseDescription>Empty Database</DatabaseDescription> <DatabaseDescriptionChanged>${creationDate}</DatabaseDescriptionChanged> <DefaultUserName/> <DefaultUserNameChanged>${creationDate}</DefaultUserNameChanged> <MaintenanceHistoryDays>365</MaintenanceHistoryDays> <Color/> <MasterKeyChanged>${creationDate}</MasterKeyChanged> <MasterKeyChangeRec>-1</MasterKeyChangeRec> <MasterKeyChangeForce>-1</MasterKeyChangeForce> <MemoryProtection> <ProtectTitle>False</ProtectTitle> <ProtectUserName>False</ProtectUserName> <ProtectPassword>True</ProtectPassword> <ProtectURL>False</ProtectURL> <ProtectNotes>False</ProtectNotes> </MemoryProtection> <CustomIcons/> <RecycleBinEnabled>True</RecycleBinEnabled> <RecycleBinUUID>AAAAAAAAAAAAAAAAAAAAAA==</RecycleBinUUID> <RecycleBinChanged>${creationDate}</RecycleBinChanged> <EntryTemplatesGroup>AAAAAAAAAAAAAAAAAAAAAA==</EntryTemplatesGroup> <EntryTemplatesGroupChanged>${creationDate}</EntryTemplatesGroupChanged> <LastSelectedGroup>AAAAAAAAAAAAAAAAAAAAAA==</LastSelectedGroup> <LastTopVisibleGroup>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleGroup> <HistoryMaxItems>10</HistoryMaxItems> <HistoryMaxSize>6291456</HistoryMaxSize> <Binaries/> <CustomData/> </Meta> </KeePassFile>""") } internal class StringProtectedByStreamCipher(value: ByteArray, private val cipher: SkippingStreamCipher) : SecureString { private val position: Long private val data: ByteArray constructor(value: CharSequence, cipher: SkippingStreamCipher) : this(Charsets.UTF_8.encode(CharBuffer.wrap(value)).toByteArray(), cipher) init { var position = 0L data = ByteArray(value.size) synchronized(cipher) { position = cipher.position cipher.processBytes(value, 0, value.size, data, 0) } this.position = position } override fun get(clearable: Boolean) = OneTimeString(getAsByteArray(), clearable = clearable) fun getAsByteArray(): ByteArray { val value = ByteArray(data.size) synchronized(cipher) { cipher.seekTo(position) cipher.processBytes(data, 0, data.size, value, 0) } return value } }
apache-2.0
d1d204041021a4fe19208b29b36bf365
37.165992
148
0.751538
4.353811
false
false
false
false
xingyuli/swordess-jsondb
src/main/kotlin/org/swordess/persistence/json/JsonDB.kt
2
2722
/* * The MIT License (MIT) * * Copyright (c) 2016 Vic Lau * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.swordess.persistence.json import org.swordess.persistence.DB import java.util.ArrayList import kotlin.reflect.KClass class JsonDB : DB { // private val logger = LoggerFactory.getLogger(javaClass) // MUST be initialized by client code lateinit var database: Database override fun <T : Any> save(obj: T): T { val table: JsonTable<T> = database[obj.javaClass.kotlin] table.add(obj) database.persist(table) return obj } override fun <T : Any> findOne(entityType: KClass<T>, id: Long): T? { val metadata = database.getMetadata(entityType) val table = database[entityType] return table.firstOrNull { id == metadata.idMetadata.getter(it) } } override fun <T : Any> findAll(entityType: KClass<T>): List<T> = ArrayList<T>().apply { addAll(database[entityType]) } override fun update(entity: Any) { val metadata = database.getMetadata(entity.javaClass.kotlin) val id = metadata.idMetadata.getter(entity) val table = database[entity.javaClass.kotlin] table.firstOrNull { id == metadata.idMetadata.getter(it) }?.let { table.replace(it, entity) database.persist(table) } } override fun <T : Any> remove(entityType: KClass<T>, id: Long) { val metadata = database.getMetadata(entityType) val table = database[entityType] table.firstOrNull { id == metadata.idMetadata.getter(it) }?.let { table.remove(it) database.persist(table) } } }
mit
69c86a24fa938c938582958148f76595
33.897436
81
0.68626
4.259781
false
false
false
false
damien5314/HoldTheNarwhal
app/src/main/java/com/ddiehl/android/htn/view/FragmentExt.kt
1
1681
package com.ddiehl.android.htn.view import android.content.Context import androidx.fragment.app.Fragment /** * Checks the type of the fragment's host [Context] or parent [Fragment]. If one of those is an instance * of type [T], it is returned. * * Throws an [IllegalStateException] if the neither the host [Context] nor parent [Fragment] match the expected type. */ inline fun <reified T> Fragment.getDelegate(): T { val context = context if (context != null && context is T) { return context } val parentFragment = parentFragment if (parentFragment != null && parentFragment is T) { return parentFragment } throw IllegalStateException("Either host Context or parent Fragment must implement ${T::class.java.simpleName}") } /** * Checks the type of the fragment's host [Context] or parent [Fragment]. If one of those is an instance * of type [T], it is returned. * * Throws an [IllegalStateException] if the neither the host [Context] nor parent [Fragment] match the expected type. * * Same as [getDelegate] but doesn't use a reified type for Java compatibility. */ fun <T> Fragment.getDelegate(clazz: Class<T>): T { val context = context @Suppress("UNCHECKED_CAST") // We're actually checking it if (context != null && clazz.isInstance(context)) { return context as T } val parentFragment = parentFragment @Suppress("UNCHECKED_CAST") // We're actually checking it if (parentFragment != null && clazz.isInstance(parentFragment)) { return parentFragment as T } throw IllegalStateException("Either host Context or parent Fragment must implement ${clazz.simpleName}") }
apache-2.0
7041bc8a7a0808de2291c149a09e8e99
34.020833
117
0.700773
4.423684
false
false
false
false
akvo/akvo-flow-mobile
app/src/main/java/org/akvo/flow/presentation/form/OldFormMapper.kt
1
6509
/* * Copyright (C) 2021 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Akvo Flow is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.presentation.form import org.akvo.flow.domain.QuestionGroup import org.akvo.flow.domain.QuestionResponse import org.akvo.flow.domain.Survey import org.akvo.flow.domain.entity.DomainForm import org.akvo.flow.domain.entity.DomainQuestionGroup import org.akvo.flow.domain.entity.DomainResponse import org.akvo.flow.domain.entity.question.DomainAltText import org.akvo.flow.domain.entity.question.DomainDependency import org.akvo.flow.domain.entity.question.DomainLevel import org.akvo.flow.domain.entity.question.DomainOption import org.akvo.flow.domain.entity.question.DomainQuestion import org.akvo.flow.domain.entity.question.DomainQuestionHelp import org.akvo.flow.utils.entity.AltText import org.akvo.flow.utils.entity.Dependency import org.akvo.flow.utils.entity.Level import org.akvo.flow.utils.entity.Option import org.akvo.flow.utils.entity.Question import org.akvo.flow.utils.entity.QuestionHelp import org.akvo.flow.utils.entity.SurveyGroup import java.util.ArrayList import java.util.HashMap import javax.inject.Inject class OldFormMapper @Inject constructor() { fun mapForm(surveyGroup: SurveyGroup, domainForm: DomainForm): Survey { val form = Survey() form.surveyGroup = surveyGroup form.name = domainForm.name form.id = domainForm.formId form.questionGroups = mapGroups(domainForm.groups) form.version = domainForm.version.toDouble() form.type = domainForm.type form.location = domainForm.location form.fileName = domainForm.filename form.isHelpDownloaded = domainForm.cascadeDownloaded form.language = domainForm.language return form } private fun mapGroups(groups: List<DomainQuestionGroup>): MutableList<QuestionGroup> { val mappedGroups = mutableListOf<QuestionGroup>() for ((i, group) in groups.withIndex()) { val element = QuestionGroup() element.order = i element.heading = group.heading element.isRepeatable = group.isRepeatable element.questions.addAll(mapQuestions(group.questions)) mappedGroups.add(element) } return mappedGroups } private fun mapQuestions(domainQuestions: MutableList<DomainQuestion>): ArrayList<Question> { val questions = arrayListOf<Question>() for (question in domainQuestions) { questions.add(Question( question.questionId, question.isMandatory, question.text, question.order, question.isAllowOther, mapHelps(question.questionHelp), question.type, mapOptions(question.options), question.isAllowMultiple, question.isLocked, mapAltText(question.languageTranslationMap), mapDependencies(question.dependencies), question.isLocaleName, question.isLocaleLocation, question.isDoubleEntry, question.isAllowPoints, question.isAllowLine, question.isAllowPolygon, question.caddisflyRes, question.cascadeResource, mapLevels(question.levels) )) } return questions } private fun mapLevels(domainLevels: MutableList<DomainLevel>): MutableList<Level> { val levels = mutableListOf<Level>() for (level in domainLevels) { levels.add(Level(level.text, mapAltText(level.altTextMap))) } return levels } private fun mapDependencies(domainDependencies: MutableList<DomainDependency>): MutableList<Dependency> { val dependencies = mutableListOf<Dependency>() for (dependency in domainDependencies) { dependencies.add(Dependency(dependency.question, dependency.answer)) } return dependencies } private fun mapOptions(domainOptions: MutableList<DomainOption>?): MutableList<Option> { val options = mutableListOf<Option>() if (domainOptions != null) { for (option in domainOptions) { options.add(Option(option.text, option.code, option.isOther, mapAltText(option.altTextMap))) } } return options } private fun mapHelps(questionHelp: MutableList<DomainQuestionHelp>): MutableList<QuestionHelp> { val domainHelps = mutableListOf<QuestionHelp>() for (help in questionHelp) { domainHelps.add(QuestionHelp(mapAltText(help.altTextMap), help.text)) } return domainHelps } private fun mapAltText(domainAltText: HashMap<String?, DomainAltText>): HashMap<String?, AltText> { val textMap = HashMap<String?, AltText>() for (language in domainAltText.keys) { val altText = domainAltText[language] if (altText != null) { textMap[language] = AltText(altText.languageCode, altText.type, altText.text) } } return textMap } fun mapResponses( responses: List<DomainResponse>, formInstanceId: Long?, ): HashMap<String, QuestionResponse> { val questionResponses: HashMap<String, QuestionResponse> = HashMap() for (response in responses) { val questionResponse = QuestionResponse(response.value, response.answerType, response.id, formInstanceId, response.questionId, response.isIncludeFlag, response.iteration) questionResponses[questionResponse.responseMapKey()] = questionResponse } return questionResponses } }
gpl-3.0
7d1673d3b427ce8bed3e56b6a1c79900
38.210843
109
0.666615
4.580577
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/notequests/NoteQuestsHiddenDao.kt
1
1645
package de.westnordost.streetcomplete.data.osmnotes.notequests import de.westnordost.streetcomplete.data.CursorPosition import de.westnordost.streetcomplete.data.Database import de.westnordost.streetcomplete.data.osmnotes.notequests.NoteQuestsHiddenTable.Columns.NOTE_ID import de.westnordost.streetcomplete.data.osmnotes.notequests.NoteQuestsHiddenTable.Columns.TIMESTAMP import de.westnordost.streetcomplete.data.osmnotes.notequests.NoteQuestsHiddenTable.NAME import java.lang.System.currentTimeMillis import javax.inject.Inject /** Persists which note ids should be hidden (because the user selected so) in the note quest */ class NoteQuestsHiddenDao @Inject constructor(private val db: Database) { fun add(noteId: Long) { db.insert(NAME, listOf( NOTE_ID to noteId, TIMESTAMP to currentTimeMillis() )) } fun contains(noteId: Long): Boolean = getTimestamp(noteId) != null fun getTimestamp(noteId: Long): Long? = db.queryOne(NAME, where = "$NOTE_ID = $noteId") { it.getLong(TIMESTAMP) } fun delete(noteId: Long): Boolean = db.delete(NAME, where = "$NOTE_ID = $noteId") == 1 fun getNewerThan(timestamp: Long): List<NoteIdWithTimestamp> = db.query(NAME, where = "$TIMESTAMP > $timestamp") { it.toNoteIdWithTimestamp() } fun getAllIds(): List<Long> = db.query(NAME) { it.getLong(NOTE_ID) } fun deleteAll(): Int = db.delete(NAME) } private fun CursorPosition.toNoteIdWithTimestamp() = NoteIdWithTimestamp(getLong(NOTE_ID), getLong(TIMESTAMP)) data class NoteIdWithTimestamp(val noteId: Long, val timestamp: Long)
gpl-3.0
11aed26989ae661c35bbf8e3831c453a
37.255814
101
0.72766
4.031863
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/activity/ViewAllDappsActivity.kt
1
5281
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.view.activity import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import com.toshi.R import com.toshi.extensions.addHorizontalLineDivider import com.toshi.extensions.getPxSize import com.toshi.extensions.startActivity import com.toshi.extensions.toArrayList import com.toshi.extensions.toast import com.toshi.model.network.dapp.Dapp import com.toshi.view.adapter.AllDappsAdapter import com.toshi.viewModel.LoadingState import com.toshi.viewModel.PagingState import com.toshi.viewModel.ViewAllDappsViewModel import com.toshi.viewModel.ViewModelFactory.ViewAllDappsViewModelFactory import kotlinx.android.synthetic.main.activity_settings_advanced.networkStatusView import kotlinx.android.synthetic.main.activity_view_dapps.closeButton import kotlinx.android.synthetic.main.activity_view_dapps.dapps import kotlinx.android.synthetic.main.activity_view_dapps.toolbarTitle class ViewAllDappsActivity : AppCompatActivity() { companion object { const val CATEGORY = 1 const val ALL = 2 const val VIEW_TYPE = "viewType" const val CATEGORY_ID = "categoryId" private const val PREFETCH_NUMBER = 5 } private lateinit var viewModel: ViewAllDappsViewModel private lateinit var allDappsAdapter: AllDappsAdapter private lateinit var dappsLayoutManager: LinearLayoutManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_view_dapps) init() } private fun init() { initViewModel() initNetworkView() initClickListeners() initAdapter() initScrollListener() initObservers() } private fun initViewModel() { viewModel = ViewModelProviders.of( this, ViewAllDappsViewModelFactory(intent) ).get(ViewAllDappsViewModel::class.java) } private fun initNetworkView() { networkStatusView.setNetworkVisibility(viewModel.getNetworks()) } private fun initClickListeners() { closeButton.setOnClickListener { finish() } } private fun initAdapter() { allDappsAdapter = AllDappsAdapter().apply { onItemClickedListener = { startViewDappActivity(it) } } dappsLayoutManager = LinearLayoutManager(this) dapps.apply { adapter = allDappsAdapter layoutManager = dappsLayoutManager addHorizontalLineDivider(leftPadding = getPxSize(R.dimen.avatar_size_medium) + getPxSize(R.dimen.margin_primary) + getPxSize(R.dimen.margin_primary)) } } private fun startViewDappActivity(dapp: Dapp) { val categories = viewModel.dappCategories startActivity<ViewDappActivity> { putExtra(ViewDappActivity.DAPP_CATEGORIES, categories.toArrayList()) Dapp.buildIntent(this, dapp) } } private fun initScrollListener() { dapps.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) handleScroll() } }) } private fun handleScroll() { val isLoading = viewModel.loadingState == LoadingState.LOADING val hasReachedEnd = viewModel.pagingState == PagingState.REACHED_END if (isLoading || hasReachedEnd) return val shouldFetch = (getVisibleItemCount() + PREFETCH_NUMBER + getFirstVisibleItemPosition()) >= getTotalItemCount() && getFirstVisibleItemPosition() > 0 if (shouldFetch) viewModel.gethMoreDapps() } private fun getVisibleItemCount() = dappsLayoutManager.childCount private fun getTotalItemCount() = dappsLayoutManager.itemCount private fun getFirstVisibleItemPosition() = dappsLayoutManager.findFirstVisibleItemPosition() private fun initObservers() { viewModel.dapps.observe(this, Observer { if (it != null) allDappsAdapter.setDapps(it) }) viewModel.dappsError.observe(this, Observer { if (it != null) toast(it) }) viewModel.categoryName.observe(this, Observer { if (it != null) toolbarTitle.text = it }) } }
gpl-3.0
db0cba27a15ed6d6efaaac83de441e18
35.680556
122
0.697595
4.592174
false
false
false
false
AkshayPathak/New-Horizons
app/src/main/java/com/thunder/horizons/repository/checklist/RealmChecklistModel.kt
1
5457
package com.thunder.horizons.repository.checklist import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.LinearLayout import android.widget.TextView import com.mikepenz.fastadapter.IItem import com.squareup.moshi.Json import com.thunder.horizons.R import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.Ignore import io.realm.annotations.PrimaryKey import kotlinx.android.synthetic.main.checklist_item.view.* import java.util.* open class RealmChecklistModel( @PrimaryKey @field:Json(name = "aircraftId") open var aircraftId: Long = 0, @field:Json(name = "checklist") open var checklist: RealmList<RealmProcedureModel> = RealmList(), open var isComplete: Boolean = false, @Ignore open var dataType: Int = -1 ) : RealmObject() { companion object { val DATA_TYPE_NETWORK: Int = 1 val DATA_TYPE_CACHE: Int = 0 } } open class RealmProcedureModel( @PrimaryKey var procedureId: Long = 0, @field:Json(name = "procedureName") open var name: String = "", @field:Json(name = "procedureItems") open var items: RealmList<RealmChecklistItemModel> = RealmList(), open var isComplete: Boolean = false ) : RealmObject() open class RealmChecklistItemModel( @PrimaryKey open var itemId: Long = 0, @field:Json(name = "item") open var item: String = "", @field:Json(name = "action") open var action: String = "", open var isChecked: Boolean = false ) : RealmObject(), IItem<RealmChecklistItemModel, RealmChecklistItemModel.ViewHolder> { override fun getType(): Int { return R.id.checklist_id } override fun getViewHolder(parent: ViewGroup): ViewHolder { return getViewHolder(LayoutInflater.from(parent.context).inflate(layoutRes, parent, false)) } fun getViewHolder(v: View): RealmChecklistItemModel.ViewHolder { return RealmChecklistItemModel.ViewHolder(v) } override fun getLayoutRes(): Int { return R.layout.checklist_item } override fun bindView(holder: ViewHolder, payloads: MutableList<Any>) { holder.checkbox.isChecked = isChecked holder.itemName.text = item holder.itemAction.text = action } override fun unbindView(holder: ViewHolder) { holder.itemName.text = null holder.itemAction.text = null } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val parent: LinearLayout = itemView.linear_checklist_parent val checkbox: CheckBox = itemView.checkbox_is_completed val itemName: TextView = itemView.textview_item val itemAction: TextView = itemView.textview_action } override fun getIdentifier(): Long { return itemId } override fun getTag(): Any { return "" } override fun isEnabled(): Boolean { return true } override fun withSetSelected(selected: Boolean): RealmChecklistItemModel { // Not supported return this } override fun withSelectable(selectable: Boolean): RealmChecklistItemModel { // Not supported return this } override fun isSelectable(): Boolean { // Not supported return false } override fun generateView(ctx: Context): View { val viewHolder: RealmChecklistItemModel.ViewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(layoutRes, null, false)) bindView(viewHolder, Collections.emptyList()) return viewHolder.itemView } override fun generateView(ctx: Context, parent: ViewGroup): View { val viewHolder: RealmChecklistItemModel.ViewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(layoutRes, parent, false)) bindView(viewHolder, Collections.emptyList()) return viewHolder.itemView } override fun attachToWindow(holder: RealmChecklistItemModel.ViewHolder?) {} override fun detachFromWindow(holder: RealmChecklistItemModel.ViewHolder?) {} override fun failedToRecycle(holder: RealmChecklistItemModel.ViewHolder): Boolean { return false } override fun equals(id: Int): Boolean { return this.itemId.toInt() == id } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as RealmChecklistItemModel if (itemId != other.itemId) return false if (item != other.item) return false if (action != other.action) return false if (isChecked != other.isChecked) return false return true } override fun hashCode(): Int { var result = itemId.hashCode() result = 31 * result + item.hashCode() result = 31 * result + action.hashCode() result = 31 * result + isChecked.hashCode() return result } override fun withIdentifier(identifier: Long): RealmChecklistItemModel { this.itemId = itemId return this } override fun withEnabled(enabled: Boolean): RealmChecklistItemModel { // Not supported return this } override fun withTag(tag: Any?): RealmChecklistItemModel { return this } override fun isSelected(): Boolean { return false } }
gpl-3.0
75a3386db29e2b20c318a154c6f9be72
30.918129
134
0.679677
4.696213
false
false
false
false
jonninja/node.kt
src/main/kotlin/node/express/middleware/JsonBodyParser.kt
1
3310
package node.express.middleware import node.express.Response import node.express.Request import io.netty.util.CharsetUtil import com.fasterxml.jackson.databind.ObjectMapper import kotlin.dom.attribute import com.fasterxml.jackson.databind.JsonNode import node.express.Body import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.databind.node.ArrayNode import java.util.ArrayList import java.util.HashSet import node.express.RouteHandler private val json = ObjectMapper(); /** * Parses the body of a request as a JSON object */ public fun jsonBodyParser(): RouteHandler.() -> Unit { return { if (req.body == null) { try { var content = req.request.content()!!; if (content.isReadable()) { val jsonString = content.toString(CharsetUtil.UTF_8); val node = json.readTree(jsonString)!!; req.attributes.put("body", JsonBody(node)); } } catch(t: Throwable) { } } next(); } } private class JsonBody(n: JsonNode): Body { var node = n; val objectNode: ObjectNode get() { return node as ObjectNode } override fun get(key: String): Any? { var value = (node as? ObjectNode)?.get(key); return when { value == null -> null value.isIntegralNumber() -> value.asInt() value.isTextual() -> value.asText() value.isBoolean() -> value.asBoolean() else -> value } } override fun asInt(key: String): Int? { return (node as? ObjectNode)?.get(key)?.asInt(); } override fun asString(key: String): String? { return (node as? ObjectNode)?.get(key)?.asText(); } override fun asInt(index: Int): Int? { return (node as? ArrayNode)?.get(index)?.asInt(); } override fun asString(index: Int): String? { return (node as? ArrayNode)?.get(index)?.asText(); } override fun asNative(): Any { return node; } override fun asDouble(key: String): Double? { return (node as? ObjectNode)?.get(key)?.asDouble(); } public override fun size(): Int { return objectNode.size() } public override fun isEmpty(): Boolean { return objectNode.size() == 0 } public override fun containsKey(key: Any?): Boolean { return objectNode.findValue(key as String?) != null } public override fun containsValue(value: Any?): Boolean { throw UnsupportedOperationException() } public override fun get(key: Any?): Any? { return objectNode.get(key as String?)?.textValue() } public override fun keySet(): Set<String> { return objectNode.fieldNames().asSequence().mapTo(HashSet<String>(), {it}) } public override fun values(): Collection<Any?> { return objectNode.fields()!!.asSequence().mapTo(ArrayList<Any?>(), {it}) } public override fun entrySet(): Set<Map.Entry<String, Any?>> { return objectNode.fields()!!.asSequence().mapTo(HashSet<Map.Entry<String, Any?>>(), { object : Map.Entry<String, Any?> { public override fun getKey(): String { return it.getKey() } public override fun getValue(): Any { return it.getValue() } public override fun hashCode(): Int { return it.hashCode() } public override fun equals(other: Any?): Boolean { return it.equals(other) } } }) } }
mit
c9b5a59110b180c01e051e6ab74f5d9b
28.828829
89
0.643807
4.111801
false
false
false
false
pokk/mvp-magazine
app/src/main/kotlin/taiwan/no1/app/mvp/models/cast/CastImagesModel.kt
1
913
package taiwan.no1.app.mvp.models.cast import android.os.Parcel import android.os.Parcelable import taiwan.no1.app.mvp.models.ImageProfileModel /** * * @author Jieyi * @since 1/1/17 */ data class CastImagesModel(val profiles: List<ImageProfileModel>? = null): Parcelable { //region Parcelable companion object { @JvmField val CREATOR: Parcelable.Creator<CastImagesModel> = object: Parcelable.Creator<CastImagesModel> { override fun createFromParcel(source: Parcel): CastImagesModel = CastImagesModel(source) override fun newArray(size: Int): Array<CastImagesModel?> = arrayOfNulls(size) } } constructor(source: Parcel): this(source.createTypedArrayList(ImageProfileModel.CREATOR)) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeTypedList(profiles) } //endregion }
apache-2.0
6bc1ac0875dc93533b65b2007ec35cd0
29.433333
114
0.711939
4.188073
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/lang/commands/LatexArrowCommand.kt
1
8426
package nl.hannahsten.texifyidea.lang.commands import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.AMSSYMB import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.LATEXSYMB import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.STMARYRD /** * @author Hannah Schellekens */ enum class LatexArrowCommand( override val command: String, override vararg val arguments: Argument = emptyArray(), override val dependency: LatexPackage = LatexPackage.DEFAULT, override val display: String? = null, override val isMathMode: Boolean = true, val collapse: Boolean = false ) : LatexCommand { NOT_RIGHT_ARROW("nrightarrow", dependency = AMSSYMB, display = "↛", collapse = true), LEFT_ARROW("leftarrow", display = "←", collapse = true), LEFT_DOUBLE_ARROW("Leftarrow", display = "⇐", collapse = true), RIGHT_ARROW("rightarrow", display = "→", collapse = true), RIGHT_DOUBLE_ARROW("Rightarrow", display = "⇒", collapse = true), LEFT_AND_RIGHT_ARROW("leftrightarrow", display = "↔", collapse = true), LEFT_AND_RIGHT_DOUBLE_ARROW("Leftrightarrow", display = "⇔", collapse = true), LONG_LEFT_ARROW("longleftarrow", display = "⟵", collapse = true), LONG_LEFT_DOUBLE_ARROW("Longleftarrow", display = "⟸", collapse = true), LONG_RIGHT_ARROW("longrightarrow", display = "⟶", collapse = true), L_ONGRIGHTARROW("Longrightarrow", display = "⟹", collapse = true), LONG_LEFT_AND_RIGHT_ARROW("longleftrightarrow", display = "⟷", collapse = true), LONG_LEFT_AND_RIGHT_DOUBLE_ARROW("Longleftrightarrow", display = "⟺", collapse = true), UP_ARROW("uparrow", display = "↑", collapse = true), UP_DOUBLE_ARROW("Uparrow", display = "⇑", collapse = true), DOWN_ARROW("downarrow", display = "↓", collapse = true), DOWN_DOUBLE_ARROW("Downarrow", display = "⇓", collapse = true), UP_AND_DOWN_ARROW("updownarrow", display = "↕", collapse = true), UP_AND_DOWN_DOUBLE_ARROW("Updownarrow", display = "⇕", collapse = true), MAPS_TO("mapsto", display = "↦", collapse = true), LEFT_ARROW_WITH_HOOK("hookleftarrow", display = "↩", collapse = true), LEFT_HARPOON_UP("leftharpoonup", display = "↼", collapse = true), LEFT_HARPOON_DOWN("leftharpoondown", display = "↽", collapse = true), RIGHT_AND_LEFT_HARPOONS("rightleftharpoons", display = "⇌", collapse = true), LONG_MAPS_TO("longmapsto", display = "⟼", collapse = true), RIGHT_ARROW_WITH_HOOK("hookrightarrow", display = "↪", collapse = true), RIGHT_HARPOON_UP("rightharpoonup", display = "⇀", collapse = true), RIGHT_HARPOON_DOWN("rightharpoondown", display = "⇁", collapse = true), LEADSTO("leadsto", dependency = LATEXSYMB, display = "⤳", collapse = true), NORTH_EAST_ARROW("nearrow", display = "↗", collapse = true), SOUTH_EAST_ARROW("searrow", display = "↘", collapse = true), SOUTH_WEST_ARROW("swarrow", display = "↙", collapse = true), NORTH_WEST_ARROW("nwarrow", display = "↖", collapse = true), DASHED_RIGHT_ARROW("dashrightarrow", dependency = AMSSYMB, display = "⤍", collapse = true), LEFT_AND_RIGHT_ARROW_PAIR("leftrightarrows", dependency = AMSSYMB, display = "⇆", collapse = true), LEFT_ARROW_WITH_TAIL("leftarrowtail", dependency = AMSSYMB, display = "↢", collapse = true), ANTI_CLOCKWISE_SEMICIRCLE_ARROW_TOP("curvearrowleft", dependency = AMSSYMB, display = "↶", collapse = true), UP_ARROW_PAIR("upuparrows", dependency = AMSSYMB, display = "⇈", collapse = true), MULTIMAP("multimap", dependency = AMSSYMB, display = "⊸", collapse = true), RIGHT_AND_LEFT_ARROW_PAIR("rightleftarrows", dependency = AMSSYMB, display = "⇄", collapse = true), TWO_HEADED_RIGHT_ARROW("twoheadrightarrow", dependency = AMSSYMB, display = "↠", collapse = true), UP_ARROW_WITH_RIGHT_TIP("Rsh", dependency = AMSSYMB, display = "↱", collapse = true), DOWN_HARPOON_RIGHT("downharpoonright", dependency = AMSSYMB, display = "⇂", collapse = true), DASHED_LEFT_ARROW("dashleftarrow", dependency = AMSSYMB, display = "⇠", collapse = true), LEFT_TRIPLE_ARROW("Lleftarrow", dependency = AMSSYMB, display = "⇚", collapse = true), LEFT_ARROW_WITH_LOOP("looparrowleft", dependency = AMSSYMB, display = "↫", collapse = true), ANTI_CLOCKWISE_CIRCLE_ARROW("circlearrowleft", dependency = AMSSYMB, display = "↺", collapse = true), UP_HARPOON_LEFT("upharpoonleft", dependency = AMSSYMB, display = "↿", collapse = true), LEFT_AND_RIGHT_WAVE_ARROW("leftrightsquigarrow", dependency = AMSSYMB, display = "↭", collapse = true), RIGHT_ARROW_PAIR("rightrightarrows", dependency = AMSSYMB, display = "⇉", collapse = true), RIGHT_ARROW_WITH_TAIL("rightarrowtail", dependency = AMSSYMB, display = "↣", collapse = true), CLOCKWISE_SEMICIRCLE_ARROW_TOP("curvearrowright", dependency = AMSSYMB, display = "↷", collapse = true), DOWN_ARROW_PAIR("downdownarrows", dependency = AMSSYMB, display = "⇊", collapse = true), RIGHT_WAVE_ARROW("rightsquigarrow", dependency = AMSSYMB, display = "⇝", collapse = true), LEFT_ARROW_PAIR("leftleftarrows", dependency = AMSSYMB, display = "⇇", collapse = true), TWO_HEADED_LEFT_ARROW("twoheadleftarrow", dependency = AMSSYMB, display = "↞", collapse = true), LEFT_AND_RIGHT_HARPOONS("leftrightharpoons", dependency = AMSSYMB, display = "↰", collapse = true), UP_ARROW_WITH_LEFT_TIP("Lsh", dependency = AMSSYMB, display = "↰", collapse = true), DOWN_HARPOON_LEFT("downharpoonleft", dependency = AMSSYMB, display = "⇃", collapse = true), RIGHT_ARROW_WITH_LOOP("looparrowright", dependency = AMSSYMB, display = "↬", collapse = true), CLOCKWISE_CIRCLE_ARROW("circlearrowright", dependency = AMSSYMB, display = "↻", collapse = true), UP_HARPOON_RIGHT("upharpoonright", dependency = AMSSYMB, display = "↾", collapse = true), NOT_LEFT_ARROW("nleftarrow", dependency = AMSSYMB, display = "↚", collapse = true), NOT_LEFT_DOUBLE_ARROW("nLeftarrow", dependency = AMSSYMB, display = "⇍", collapse = true), NOT_RIGHT_DOUBLE_ARROW("nRightarrow", dependency = AMSSYMB, display = "⇏", collapse = true), NOT_LEFT_AND_RIGHT_ARROW("nleftrightarrow", dependency = AMSSYMB, display = "↮", collapse = true), NOT_LEFT_AND_RIGHT_DOUBLE_ARROW("nLeftrightarrow", dependency = AMSSYMB, display = "⇎", collapse = true), LONG_MAPS_FROM_DOUBLE_ARROW("Longmapsfrom", dependency = STMARYRD, display = "⟽", collapse = true), LONG_MAPS_TO_DOUBLE_ARROW("Longmapsto", dependency = STMARYRD, display = "⟾", collapse = true), MAPS_FROM_DOUBLE_ARROW("Mapsfrom", dependency = STMARYRD, display = "⤆", collapse = true), MAPS_TO_DOUBLE_ARROW("Mapsto", dependency = STMARYRD, display = "⤇", collapse = true), LEFT_OPEN_HEADED_ARROW("leftarrowtriangle", dependency = STMARYRD, display = "⇽", collapse = true), RIGHT_OPEN_HEADED_ARROW("rightarrowtriangle", dependency = STMARYRD, display = "⇾", collapse = true), LEFT_AND_RIGHT_ARROW_EQUALS("leftrightarroweq", dependency = STMARYRD), LEFT_AND_RIGHT_OPEN_HEADED_ARROW("leftrightarrowtriangle", dependency = STMARYRD, display = "⇿", collapse = true), LIGHTNING("lightning", dependency = STMARYRD, display = "☇", collapse = true), LONG_MAPS_FROM("longmapsfrom", dependency = STMARYRD, display = "⟻", collapse = true), MAPS_FROM("mapsfrom", dependency = STMARYRD, display = "↤", collapse = true), NORTH_NORTH_EAST_ARROW("nnearrow", dependency = STMARYRD, display = "↗", collapse = true), NORTH_NORTH_WEST_ARROW("nnwarrow", dependency = STMARYRD, display = "↖", collapse = true), SOUNT_SOUTH_EAST_ARROW("ssearrow", dependency = STMARYRD, display = "↘", collapse = true), SOUTH_SOUTH_WEST_ARROW("sswarrow", dependency = STMARYRD, display = "↙", collapse = true), SHORT_LEFT_ARROW("shortleftarrow", dependency = STMARYRD, display = "←", collapse = true), SHORT_UP_ARROW("shortuparrow", dependency = STMARYRD, display = "↑", collapse = true), SHORT_RIGHT_ARROW("shortrightarrow", dependency = STMARYRD, display = "→", collapse = true), SHORT_DOWN_ARROW("shortdownarrow", dependency = STMARYRD, display = "↓", collapse = true), ; override val identifier: String get() = name }
mit
4bb369d660c3d0df0d192786cc7d0704
74.063636
118
0.678173
3.560155
false
false
false
false
smuzani/Umbrella
app/src/main/java/com/syedmuzani/umbrella/utils/MyDatabaseOpenHelper.kt
1
1171
package com.syedmuzani.umbrella.utils import android.content.Context import android.database.sqlite.SQLiteDatabase import org.jetbrains.anko.db.* /** * Created by muz on 2019-02-15. */ class MyDatabaseOpenHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "MyDatabase", null, 1) { companion object { private var instance: MyDatabaseOpenHelper? = null const val TODO_TABLE = "Todo" const val COL_NAME = "name" const val COL_ID = "_id" @Synchronized fun getInstance(ctx: Context): MyDatabaseOpenHelper { if (instance == null) { instance = MyDatabaseOpenHelper(ctx.applicationContext) } return instance!! } } override fun onCreate(db: SQLiteDatabase) { // Here you create tables db.createTable(TODO_TABLE, true, COL_ID to TEXT + PRIMARY_KEY + UNIQUE, COL_NAME to TEXT) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { // do nothing } } val Context.database: MyDatabaseOpenHelper get() = MyDatabaseOpenHelper.getInstance(applicationContext)
artistic-2.0
6590f25f85d1794ff961a14a0894a655
26.904762
96
0.639624
4.469466
false
false
false
false
doylew/safesearch
src/main/kotlin/edu/unh/cs/ai/IO.kt
1
2862
package edu.unh.cs.ai import java.util.* /** * input and output functions * Created by doylew on 1/9/17. */ fun readGridWorldDomain(input: Scanner): State<GridWorldState> { val width = input.nextInt() val height = input.nextInt() var row = 0 var col = 0 var agentX = 0 var agentY = 0 var goalX = 0 var goalY = 0 val obstacles = ArrayList<Pair>() input.nextLine() while (input.hasNextLine()) { val nextLine = input.nextLine() nextLine.forEach { if (it == '@') { agentX = col agentY = row } else if (it == '*') { goalX = col goalY = row } else if (it == '#') { val newObstacle = Pair(col, row) obstacles.add(newObstacle) } else { if (it != '_') { throw InputMismatchException("corrupted input file") } } ++col } ++row col = 0 } return GridWorldState(Dimensions(width, height), Pair(agentX, agentY), Pair(goalX, goalY), obstacles) } fun readVehicleDomain(input: Scanner): State<VehicleState> { val width = input.nextInt() val height = input.nextInt() var row = 0 var col = 0 var agentX = 0 var agentY = 0 var goalX = 0 var goalY = 0 val obstacles = HashMap<Pair, Obstacle>() val bunkers = ArrayList<Pair>() input.nextLine() while (input.hasNextLine()) { val nextLine = input.nextLine() nextLine.forEach { if (it == '@') { agentX = col agentY = row } else if (it == '*') { goalX = col goalY = row } else if (it == '#') { val dx = if (random.nextBoolean()) random.nextInt(1) + 1 else 0 val dy = if (random.nextBoolean()) random.nextInt(1) + 1 else 0 val newObstacle = Obstacle(col, row, dx, dy) obstacles[Pair(col, row)] = newObstacle } else if (it == '$') { val newBunker = Pair(col, row) bunkers.add(newBunker) } else { if (it != '_') { throw InputMismatchException("corrupted input file") } } ++col } ++row col = 0 } return VehicleState(Dimensions(width, height), Pair(agentX, agentY), Pair(goalX, goalY), obstacles, bunkers) } fun initializeDummyVehicle(): State<VehicleState> { return VehicleState(Dimensions(-1, -1), Pair(-1, -1), Pair(-1, -1), HashMap<Pair, Obstacle>(), ArrayList<Pair>()) } fun initializeDummyGridWorld(): State<GridWorldState> { return GridWorldState(Dimensions(-1, -1), Pair(-1, -1), Pair(-1, -1), ArrayList<Pair>()) }
mit
b53a5c0ed696f33f3486e97c73dc79c3
29.136842
117
0.507338
4.065341
false
false
false
false
Mauin/detekt
detekt-cli/src/test/kotlin/io/gitlab/arturbosch/detekt/cli/ConfigAssert.kt
1
2641
package io.gitlab.arturbosch.detekt.cli import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.YamlConfig import org.assertj.core.api.Assertions import org.assertj.core.api.Assertions.assertThat import org.reflections.Reflections import java.lang.reflect.Field import java.lang.reflect.Modifier class ConfigAssert( private val config: Config, private val name: String, private val packageName: String) { fun assert() { val ymlDeclarations = getYmlRuleConfig().properties.filter { it.key != "active" } assertThat(ymlDeclarations).isNotEmpty val ruleClasses = getRuleClasses() assertThat(ruleClasses).isNotEmpty assertThat(ruleClasses).hasSize(ymlDeclarations.size) checkRules(ruleClasses, ymlDeclarations) } private fun checkRules(ruleClasses: List<Class<out Rule>>, ymlDeclarations: Map<String, Any>) { for (ruleClass in ruleClasses) { val ymlDeclaration = ymlDeclarations.filter { it.key == ruleClass.simpleName } if (ymlDeclaration.keys.size != 1) { Assertions.fail<String>("${ruleClass.simpleName} rule is not correctly defined in $CONFIG_FILE") } @Suppress("UNCHECKED_CAST") val options = ymlDeclaration.iterator().next().value as HashMap<String, *> checkOptions(options, ruleClass) } } private fun checkOptions(ymlOptions: HashMap<String, *>, ruleClass: Class<out Rule>) { val configFields = ruleClass.declaredFields.filter { isPublicStaticFinal(it) && it.name != "Companion" } var filter = ymlOptions.filterKeys { it != "active" } if (filter.containsKey(THRESHOLD)) { assertThat(ruleClass.superclass.simpleName).isEqualTo(THRESHOLD_RULE) filter = filter.filterKeys { it != THRESHOLD } } for (ymlOption in filter) { val configField = configFields.singleOrNull { ymlOption.key == it.get(null) } if (configField == null) { Assertions.fail<String>("${ymlOption.key} option for ${ruleClass.simpleName} rule is not correctly " + "defined") } } } private fun getYmlRuleConfig() = config.subConfig(name) as? YamlConfig ?: throw IllegalStateException("yaml config expected but got ${config.javaClass}") private fun getRuleClasses(): List<Class<out Rule>> { return Reflections(packageName) .getSubTypesOf(Rule::class.java) .filter { !Modifier.isAbstract(it.modifiers) } } private fun isPublicStaticFinal(it: Field): Boolean { val modifiers = it.modifiers return Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers) && Modifier.isFinal(modifiers) } } private const val THRESHOLD_RULE = "ThresholdRule" private const val THRESHOLD = "threshold"
apache-2.0
b980fee30da0e8e5f2c8e8336d323434
35.680556
106
0.746687
3.704067
false
true
false
false