repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
icanit/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerReader.kt
1
7882
package eu.kanade.tachiyomi.ui.reader.viewer.pager import android.view.GestureDetector import android.view.MotionEvent import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.ui.reader.viewer.base.BaseReader import eu.kanade.tachiyomi.ui.reader.viewer.pager.horizontal.LeftToRightReader import eu.kanade.tachiyomi.ui.reader.viewer.pager.horizontal.RightToLeftReader import rx.subscriptions.CompositeSubscription /** * Implementation of a reader based on a ViewPager. */ abstract class PagerReader : BaseReader() { companion object { /** * Zoom automatic alignment. */ const val ALIGN_AUTO = 1 /** * Align to left. */ const val ALIGN_LEFT = 2 /** * Align to right. */ const val ALIGN_RIGHT = 3 /** * Align to right. */ const val ALIGN_CENTER = 4 /** * Left side region of the screen. Used for touch events. */ const val LEFT_REGION = 0.33f /** * Right side region of the screen. Used for touch events. */ const val RIGHT_REGION = 0.66f } /** * Generic interface of a ViewPager. */ lateinit var pager: Pager private set /** * Adapter of the pager. */ lateinit var adapter: PagerReaderAdapter private set /** * Gesture detector for touch events. */ val gestureDetector by lazy { createGestureDetector() } /** * Subscriptions for reader settings. */ var subscriptions: CompositeSubscription? = null private set /** * Whether transitions are enabled or not. */ var transitions: Boolean = false private set /** * Scale type (fit width, fit screen, etc). */ var scaleType = 1 private set /** * Zoom type (start position). */ var zoomType = 1 private set /** * Initializes the pager. * * @param pager the pager to initialize. */ protected fun initializePager(pager: Pager) { adapter = PagerReaderAdapter(childFragmentManager) this.pager = pager.apply { setLayoutParams(ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)) setOffscreenPageLimit(1) setId(R.id.view_pager) setOnChapterBoundariesOutListener(object : OnChapterBoundariesOutListener { override fun onFirstPageOutEvent() { readerActivity.requestPreviousChapter() } override fun onLastPageOutEvent() { readerActivity.requestNextChapter() } }) setOnPageChangeListener { onPageChanged(it) } } pager.adapter = adapter subscriptions = CompositeSubscription().apply { val preferences = readerActivity.preferences add(preferences.imageDecoder() .asObservable() .doOnNext { setDecoderClass(it) } .skip(1) .distinctUntilChanged() .subscribe { refreshAdapter() }) add(preferences.zoomStart() .asObservable() .doOnNext { setZoomStart(it) } .skip(1) .distinctUntilChanged() .subscribe { refreshAdapter() }) add(preferences.imageScaleType() .asObservable() .doOnNext { scaleType = it } .skip(1) .distinctUntilChanged() .subscribe { refreshAdapter() }) add(preferences.enableTransitions() .asObservable() .subscribe { transitions = it }) } setPagesOnAdapter() } override fun onDestroyView() { pager.clearOnPageChangeListeners() subscriptions?.unsubscribe() super.onDestroyView() } /** * Creates the gesture detector for the pager. * * @return a gesture detector. */ protected fun createGestureDetector(): GestureDetector { return GestureDetector(activity, object : GestureDetector.SimpleOnGestureListener() { override fun onSingleTapConfirmed(e: MotionEvent): Boolean { val positionX = e.x if (positionX < pager.width * LEFT_REGION) { if (tappingEnabled) onLeftSideTap() } else if (positionX > pager.width * RIGHT_REGION) { if (tappingEnabled) onRightSideTap() } else { readerActivity.onCenterSingleTap() } return true } }) } /** * Called when a new chapter is set in [BaseReader]. * * @param chapter the chapter set. * @param currentPage the initial page to display. */ override fun onChapterSet(chapter: Chapter, currentPage: Page) { this.currentPage = getPageIndex(currentPage) // we might have a new page object // Make sure the view is already initialized. if (view != null) { setPagesOnAdapter() } } /** * Called when a chapter is appended in [BaseReader]. * * @param chapter the chapter appended. */ override fun onChapterAppended(chapter: Chapter) { // Make sure the view is already initialized. if (view != null) { adapter.pages = pages } } /** * Sets the pages on the adapter. */ protected fun setPagesOnAdapter() { if (pages.isNotEmpty()) { adapter.pages = pages setActivePage(currentPage) updatePageNumber() } } /** * Sets the active page. * * @param pageNumber the index of the page from [pages]. */ override fun setActivePage(pageNumber: Int) { pager.setCurrentItem(pageNumber, false) } /** * Refresh the adapter. */ private fun refreshAdapter() { pager.adapter = adapter pager.setCurrentItem(currentPage, false) } /** * Called when the left side of the screen was clicked. */ protected open fun onLeftSideTap() { moveToPrevious() } /** * Called when the right side of the screen was clicked. */ protected open fun onRightSideTap() { moveToNext() } /** * Moves to the next page or requests the next chapter if it's the last one. */ override fun moveToNext() { if (pager.currentItem != pager.adapter.count - 1) { pager.setCurrentItem(pager.currentItem + 1, transitions) } else { readerActivity.requestNextChapter() } } /** * Moves to the previous page or requests the previous chapter if it's the first one. */ override fun moveToPrevious() { if (pager.currentItem != 0) { pager.setCurrentItem(pager.currentItem - 1, transitions) } else { readerActivity.requestPreviousChapter() } } /** * Sets the zoom start position. * * @param zoomStart the value stored in preferences. */ private fun setZoomStart(zoomStart: Int) { if (zoomStart == ALIGN_AUTO) { if (this is LeftToRightReader) setZoomStart(ALIGN_LEFT) else if (this is RightToLeftReader) setZoomStart(ALIGN_RIGHT) else setZoomStart(ALIGN_CENTER) } else { zoomType = zoomStart } } }
apache-2.0
50e5cac221040b7c566edee690d85876
26.463415
93
0.563436
4.998098
false
false
false
false
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/network/GetMsgWorker.kt
1
4341
package im.fdx.v2ex.network import android.app.* import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.work.Worker import androidx.work.WorkerParameters import com.elvishew.xlog.XLog import im.fdx.v2ex.R import im.fdx.v2ex.ui.NotificationActivity import im.fdx.v2ex.utils.Keys import okhttp3.Call import okhttp3.Callback import okhttp3.Response import java.io.IOException import java.util.regex.Pattern class GetMsgWorker(val context: Context, workerParameters: WorkerParameters) : Worker(context, workerParameters) { override fun doWork(): Result { getUnread(context) return Result.success() } private fun getUnread(context: Context) { vCall(NetManager.URL_FOLLOWING).start(object : Callback { override fun onFailure(call: Call, e: IOException) { NetManager.dealError(context, -1) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val code = response.code if (code != 200) { NetManager.dealError(context, code) return } val html = response.body!!.string() // <a href="/notifications" class="fade">0 条未读提醒</a> val p = Pattern.compile("(?<=<a href=\"/notifications\".{0,20}>)\\d+") val matcher = p.matcher(html) if (matcher.find()) { val num = Integer.parseInt(matcher.group()) XLog.d("num:$num") if (num != 0) { val intent = Intent(Keys.ACTION_GET_NOTIFICATION) intent.putExtra(Keys.KEY_UNREAD_COUNT, num) LocalBroadcastManager.getInstance(context).sendBroadcast(intent) putNotification(context, num) } } else { XLog.e("not find num of unread message") } } }) } private fun putNotification(context: Context, number: Int) { val resultIntent = Intent(context, NotificationActivity::class.java) resultIntent.putExtra(Keys.KEY_UNREAD_COUNT, number) val stackBuilder = TaskStackBuilder.create(context) stackBuilder.addNextIntentWithParentStack(resultIntent) val resultPendingIntent = stackBuilder .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) val color = ContextCompat.getColor(context, R.color.primary) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel("channel_id", "未读消息", NotificationManager.IMPORTANCE_DEFAULT) val notificationManager = context.getSystemService( Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } val mBuilder = NotificationCompat.Builder(context, "channel_id") mBuilder // .setSubText("subtext") .setContentTitle(context.getString(R.string.you_have_notifications, number)) // .setContentText("") .setTicker(context.getString(R.string.you_have_notifications)) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_notification_icon) // .setLargeIcon(R.drawable.logo2x) .setLights(color, 2000, 1000) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setDefaults(Notification.DEFAULT_SOUND) .setAutoCancel(true) .setOnlyAlertOnce(true) .setColor(color) .setContentIntent(resultPendingIntent) val mNotificationCompat = mBuilder.build() val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager mNotificationManager.notify(Keys.notifyID, mNotificationCompat) } }
apache-2.0
cbd6c654159559459ce0a1254b725880
40.180952
114
0.615313
4.986159
false
false
false
false
LordAkkarin/Beacon
ui/src/main/kotlin/tv/dotstart/beacon/ui/component/PreferencePageView.kt
1
3963
/* * Copyright 2020 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tv.dotstart.beacon.ui.component import javafx.beans.DefaultProperty import javafx.beans.binding.Bindings import javafx.beans.property.ObjectProperty import javafx.beans.property.ReadOnlyObjectProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.fxml.Initializable import javafx.scene.Node import javafx.scene.control.ListCell import javafx.scene.control.ListView import javafx.scene.layout.HBox import javafx.scene.layout.Priority import javafx.scene.layout.VBox import tv.dotstart.beacon.ui.delegate.property import java.net.URL import java.util.* /** * Provides an alternative version of the tab view which displays all available options within a * standard list view. * * This component is primarily aimed at preference related window implementations. * * @author [Johannes Donath](mailto:[email protected]) * @date 09/12/2020 */ @DefaultProperty("pages") class PreferencePageView : HBox(), Initializable { private val preferenceListView = ListView<PreferencePage>() private val contentPane = VBox() private val _pageProperty: ObjectProperty<PreferencePage> = SimpleObjectProperty() /** * Defines a listing of pages present within this component. */ val pages: ObservableList<PreferencePage> = FXCollections.observableArrayList() /** * Identifies the page which is currently displayed within the preference view. */ val pageProperty: ReadOnlyObjectProperty<PreferencePage> get() = this._pageProperty /** * @see pageProperty */ val page by property(_pageProperty) init { this.styleClass.add("preference-page-view") this.children.setAll(this.preferenceListView, this.contentPane) this.preferenceListView.styleClass.add("preference-page-list") this.preferenceListView.setCellFactory { PageCell() } Bindings.bindContent(this.preferenceListView.items, this.pages) this.contentPane.styleClass.add("preference-page-content") HBox.setHgrow(this.contentPane, Priority.ALWAYS) this._pageProperty.addListener { _, _, page -> this.contentPane.children.clear() page?.let { this.contentPane.children.setAll(it) } } val selectionBinding = Bindings.select<PreferencePage>( this.preferenceListView, "selectionModel", "selectedItem") this._pageProperty.bind(selectionBinding) this.pages.addListener(ListChangeListener { change -> while (change.next()) { val currentSelection = this.page if (currentSelection == null || currentSelection in change.removed) { this.children .takeIf(ObservableList<Node>::isNotEmpty) ?.let { this.preferenceListView.selectionModel.select(0) } } } }) } override fun initialize(location: URL?, resources: ResourceBundle?) { } private class PageCell : ListCell<PreferencePage>() { override fun updateItem(item: PreferencePage?, empty: Boolean) { super.updateItem(item, empty) this.textProperty().unbind() if (!empty && item != null) { this.textProperty().bind(item.titleProperty) } else { this.text = null } } } }
apache-2.0
c3aca8f5694a0d5dc14ee2925cab087e
31.483607
96
0.73404
4.442825
false
false
false
false
loziuu/vehicle-management
ivms/src/main/kotlin/pl/loziuu/ivms/identity/user/domain/User.kt
1
677
package pl.loziuu.ivms.identity.user.domain import javax.persistence.* @Entity @Table(name = "users") class User(@Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long = 0, @Enumerated(EnumType.STRING) var role: Role = Role.MANAGER, @Column(unique = true) val login: String = "", var password: String = "", var enabled: Boolean = false) { fun activate() { enabled = true; } fun deactivate() { enabled = false } fun changePassword(password: String) { this.password = password; } fun changeRole(role: Role) { this.role = role } }
gpl-3.0
72016220d356618e1b4b8e4ae145975a
21.6
84
0.576071
4.153374
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/parking_lanes/ParkingLanesParser.kt
2
2620
package de.westnordost.streetcomplete.quests.parking_lanes import de.westnordost.streetcomplete.quests.parking_lanes.ParkingLanePosition.* data class LeftAndRightParkingLane(val left: ParkingLane?, val right: ParkingLane?) fun createParkingLaneSides(tags: Map<String, String>): LeftAndRightParkingLane? { val expandedTags = expandRelevantSidesTags(tags) // then get the values for left and right val left = createParkingLaneForSide(expandedTags, "left") val right = createParkingLaneForSide(expandedTags, "right") if (left == null && right == null) return null return LeftAndRightParkingLane(left, right) } private fun createParkingLaneForSide(tags: Map<String, String>, side: String?): ParkingLane? { val sideVal = if (side != null) ":$side" else "" val parkingLaneValue = tags["parking:lane$sideVal"] val parkingLanePositionValue = tags["parking:lane$sideVal:$parkingLaneValue"] val parkingLanePosition = parkingLanePositionValue?.toParkingLanePosition() return when (parkingLaneValue) { "parallel" -> ParallelParkingLane(parkingLanePosition) "diagonal" -> DiagonalParkingLane(parkingLanePosition) "perpendicular" -> PerpendicularParkingLane(parkingLanePosition) "marked" -> MarkedParkingLane "no_parking" -> NoParking "no_stopping" -> NoStopping "fire_lane" -> FireLane "no" -> NoParkingLane null -> null else -> UnknownParkingLane } } private fun String.toParkingLanePosition() = when(this) { "on_street" -> ON_STREET "half_on_kerb" -> HALF_ON_KERB "on_kerb" -> ON_KERB "shoulder" -> SHOULDER "painted_area_only" -> PAINTED_AREA_ONLY "lay_by" -> LAY_BY else -> UNKNOWN } private fun expandRelevantSidesTags(tags: Map<String, String>): Map<String, String> { val result = tags.toMutableMap() expandSidesTag("parking:lane", "", result) expandSidesTag("parking:lane", "parallel", result) expandSidesTag("parking:lane", "diagonal", result) expandSidesTag("parking:lane", "perpendicular", result) return result } /** Expand my_tag:both and my_tag into my_tag:left and my_tag:right etc */ private fun expandSidesTag(keyPrefix: String, keyPostfix: String, tags: MutableMap<String, String>) { val pre = keyPrefix val post = if (keyPostfix.isEmpty()) "" else ":$keyPostfix" val value = tags["$pre:both$post"] ?: tags["$pre$post"] if (value != null) { if (!tags.containsKey("$pre:left$post")) tags["$pre:left$post"] = value if (!tags.containsKey("$pre:right$post")) tags["$pre:right$post"] = value } }
gpl-3.0
6f91865516d67e31420cef67a3f03567
38.712121
101
0.691985
3.881481
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/persistence/entity/AddonOptionEntity.kt
2
743
package org.wordpress.android.fluxc.persistence.entity import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.ForeignKey.CASCADE import androidx.room.PrimaryKey import org.wordpress.android.fluxc.persistence.entity.AddonEntity.LocalPriceType @Entity( foreignKeys = [ForeignKey( entity = AddonEntity::class, parentColumns = ["addonLocalId"], childColumns = ["addonLocalId"], onDelete = CASCADE )] ) data class AddonOptionEntity( @PrimaryKey(autoGenerate = true) val addonOptionLocalId: Long = 0, val addonLocalId: Long, val priceType: LocalPriceType, val label: String?, val price: String?, val image: String? )
gpl-2.0
e48ebbce560d25354558754169cd63b1
29.958333
80
0.690444
4.39645
false
false
false
false
devulex/eventorage
frontend/src/com/devulex/eventorage/react/components/pages/SettingsPageComponent.kt
1
5952
package com.devulex.eventorage.react.components.pages import com.devulex.eventorage.locale.Messages import com.devulex.eventorage.model.* import com.devulex.eventorage.react.RProps import com.devulex.eventorage.react.RState import com.devulex.eventorage.react.ReactComponentSpec import com.devulex.eventorage.react.dom.ReactDOMBuilder import com.devulex.eventorage.react.dom.ReactDOMComponent import com.devulex.eventorage.rpc.getSettings import com.devulex.eventorage.rpc.updateSetting import kotlinx.coroutines.experimental.async import kotlinx.html.* import kotlinx.html.js.onChangeFunction import kotlinx.html.js.onClickFunction import com.devulex.eventorage.common.toggleChecked class SettingsPageComponent : ReactDOMComponent<SettingsPageComponent.SettingHandlerProps, SettingsPageComponent.SettingsState>() { companion object : ReactComponentSpec<SettingsPageComponent, SettingsPageComponent.SettingHandlerProps, SettingsPageComponent.SettingsState> init { state = SettingsPageComponent.SettingsState() } override fun ReactDOMBuilder.render() { div(classes = "page") { div(classes = "content") { div(classes = "settings-field") { div(classes = "text") { +(+Messages.YOU_CAN_CHANGE_CLUSTER_SETTINGS) span(classes = "code") { +"application.conf" } } } div(classes = "settings-field") { div(classes = "label") { +(+Messages.CLUSTER_NAME) } div(classes = "value text mono") { +props.staticSettings.elasticsearchClusterName } } div(classes = "settings-field") { div(classes = "label") { +(+Messages.CLUSTER_NODES) } div(classes = "value text mono") { +props.staticSettings.elasticsearchClusterNodes } } div(classes = "settings-field") { div(classes = "label") { +(+Messages.LANGUAGE) } div(classes = "value") { select(classes = "select") { attributes["value"] = +props.dynamicSettings.language option { value = +Language.EN +"English" } option { value = +Language.RU +"Russian" } onChangeFunction = { e -> val value = e.target!!.asDynamic().value.toString() setState { props.dynamicSettings.language = Language.parse(value) props.changeLangHandler(Language.parse(value)) } doUpdateSetting(+SettingProperty.LANGUAGE, value) } } } } div(classes = "settings-field") { div(classes = "label") { +(+Messages.DATE_FORMAT) } div(classes = "value") { select(classes = "select mono") { attributes["value"] = +props.dynamicSettings.dateFormat option { value = +DateFormatter.YYYY_MM_DD +(+DateFormatter.YYYY_MM_DD) } option { value = +DateFormatter.DD_MM_YYYY +(+DateFormatter.DD_MM_YYYY) } onChangeFunction = { e -> val value = e.target!!.asDynamic().value.toString() setState { props.dynamicSettings.dateFormat = DateFormatter.parse(value) } doUpdateSetting(+SettingProperty.DATE_FORMAT, value) } } } } div(classes = "settings-field") { div(classes = "checkbox") { if (props.dynamicSettings.autoCheckUpdates) { attributes["data-checked"] = "" } +(+Messages.AUTOMATICALLY_CHECK_FOR_UPDATES_TO_EVENTORAGE) onClickFunction = { it.toggleChecked() setState { props.dynamicSettings.autoCheckUpdates = !props.dynamicSettings.autoCheckUpdates } doUpdateSetting(+SettingProperty.AUTO_CHECK_UPDATES, props.dynamicSettings.autoCheckUpdates.toString()) } span {} span {} } } } } } class SettingsState : RState class SettingHandlerProps(var staticSettings: StaticEventorageSettings, var dynamicSettings: DynamicEventorageSettings) : RProps() { var changeLangHandler: (Language) -> Unit = {} } /** * Not used */ private fun doGetSettings() { async { getSettings() }.catch { err -> console.error("Failed to get settings: " + err.message) } } private fun doUpdateSetting(name: String, value: String) { async { updateSetting(name, value) }.catch { err -> console.error("Failed to update setting: " + err.message) } } }
mit
569e3ad302fbf67cc886b73fc1ae72f4
42.445255
144
0.474294
5.684814
false
false
false
false
PKRoma/github-android
app/src/main/java/com/github/pockethub/android/ui/issue/IssueDashboardPagerFragment.kt
5
2699
/* * Copyright (c) 2015 PocketHub * * 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.pockethub.android.ui.issue import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP import android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import com.github.pockethub.android.R import com.github.pockethub.android.ui.MainActivity import com.github.pockethub.android.ui.helpers.PagerHandler import com.github.pockethub.android.ui.base.BaseFragment import kotlinx.android.synthetic.main.pager_with_tabs.* import kotlinx.android.synthetic.main.pager_with_tabs.view.* /** * Dashboard activity for issues */ class IssueDashboardPagerFragment : BaseFragment() { private var pagerHandler: PagerHandler<IssueDashboardPagerAdapter>? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.pager_with_tabs, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setHasOptionsMenu(true) view.toolbar.visibility = View.GONE configurePager() } private fun configurePager() { val adapter = IssueDashboardPagerAdapter(this) pagerHandler = PagerHandler(this, vp_pages, adapter) lifecycle.addObserver(pagerHandler!!) pagerHandler!!.tabs = sliding_tabs_layout } override fun onDestroy() { super.onDestroy() lifecycle.removeObserver(pagerHandler!!) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { val intent = Intent(activity, MainActivity::class.java) intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP) startActivity(intent) true } else -> super.onOptionsItemSelected(item) } } }
apache-2.0
3a2a5ccd1ebf845f22acf35a2dbd5b0e
33.602564
84
0.710634
4.468543
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/lang/commands/LatexNewDefinitionCommand.kt
1
1846
package nl.hannahsten.texifyidea.lang.commands import nl.hannahsten.texifyidea.lang.LatexPackage /** * @author Hannah Schellekens */ enum class LatexNewDefinitionCommand( 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 = false, val collapse: Boolean = false ) : LatexCommand { CATCODE("catcode"), NEWCOMMAND("newcommand", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)), NEWCOMMAND_STAR("newcommand*", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)), NEWIF("newif", "cmd".asRequired()), PROVIDECOMMAND("providecommand", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)), PROVIDECOMMAND_STAR("providecommand*", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)), RENEWCOMMAND("renewcommand", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)), RENEWCOMMAND_STAR("renewcommand*", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)), NEWENVIRONMENT("newenvironment", "name".asRequired(), "args".asOptional(), "default".asOptional(), "begdef".asRequired(Argument.Type.TEXT), "enddef".asRequired(Argument.Type.TEXT)), RENEWENVIRONMENT("renewenvironment", "name".asRequired(), "args".asOptional(), "default".asOptional(), "begdef".asRequired(Argument.Type.TEXT), "enddef".asRequired(Argument.Type.TEXT)), ; override val identifier: String get() = name }
mit
ebeac505f1858cedc5f7ca416e036bd4
58.580645
189
0.704767
4.195455
false
false
false
false
ntlv/BasicLauncher2
app/src/main/java/se/ntlv/basiclauncher/appgrid/AppIconClickHandler.kt
1
2246
package se.ntlv.basiclauncher.appgrid import android.app.Activity import android.content.pm.PackageManager import android.util.Log import android.view.View import android.view.animation.AlphaAnimation import android.view.animation.Animation import org.jetbrains.anko.onClick import org.jetbrains.anko.onLongClick import rx.Observable import rx.schedulers.Schedulers import se.ntlv.basiclauncher.* import se.ntlv.basiclauncher.database.AppDetail import se.ntlv.basiclauncher.database.AppDetailRepository class AppIconClickHandler { constructor(pm: PackageManager, activity: Activity, repo: AppDetailRepository) { packageManager = pm base = activity mRepo = repo } private val packageManager: PackageManager private val mRepo: AppDetailRepository private val base: Activity private val TAG = tag() private fun onClick(view: View, appDetail: AppDetail): Boolean { if (appDetail.isPlaceholder()) return false Log.d(TAG, "Onclick $appDetail") val anim = AlphaAnimation(1f, 0.2f) anim.duration = 250 anim.repeatMode = Animation.REVERSE anim.repeatCount = 1 val animListener = listenForAnimationEvent(anim, targetEvents = AnimationEvent.END) val starter = Observable.just(appDetail.packageName) .subscribeOn(Schedulers.computation()) .map { packageManager.getLaunchIntentForPackage(it) } Observable.zip(animListener, starter, pickSecond()) .observeOn(Schedulers.computation()) .take(1) .subscribe { base.startActivityWithClipReveal(it, view) } view.startAnimation(anim) return true } private fun onLongClick(origin: View, appDetail: AppDetail): Boolean { if (appDetail.isPlaceholder()) return false Log.d(TAG, "OnLongClick $appDetail") val shadow = View.DragShadowBuilder(origin) val payload = appDetail.asClipData() return origin.startDrag(payload, shadow, null, 0) } fun bind(origin: View, meta: AppDetail) { origin.onClick { onClick(origin, meta) } origin.onLongClick { onLongClick(origin, meta) } } }
mit
21238691fa092128982722bbae63e538
30.194444
91
0.682992
4.621399
false
false
false
false
lindar-open/acolyte
src/main/kotlin/lindar/acolyte/util/ListsAcolyte.kt
1
4962
package lindar.acolyte.util import java.util.Optional class ListsAcolyte { companion object { @JvmStatic fun <T> listOf(vararg elements: T): List<T> { return kotlin.collections.listOf(*elements) } @JvmStatic fun <T> arrayListOf(vararg elements: T): MutableList<T> { return kotlin.collections.mutableListOf(*elements) } @JvmStatic fun containsIgnoreCase(list: List<String?>?, item: String?): Boolean { return list.orEmpty().any { str -> str.equals(item, ignoreCase = true) } } @JvmStatic fun containsAnyIgnoreCase(list: List<String?>?, vararg items: String?): Boolean { return list.orEmpty().any { str -> items.any { it.equals(str, ignoreCase = true) } } } @JvmStatic fun containsAllIgnoreCase(list: List<String?>?, vararg items: String?): Boolean { return items.all{str -> list.orEmpty().any{it.equals(str, ignoreCase = true)}} } @JvmStatic fun containsAnyIgnoreCase(list: List<String?>?, items: List<String?>?): Boolean { return items != null && list.orEmpty().any { str -> items.any { it.equals(str, ignoreCase = true) } } } @JvmStatic fun containsAllIgnoreCase(list: List<String?>?, items: List<String?>?): Boolean { return items != null && items.all{str -> list.orEmpty().any{it.equals(str, ignoreCase = true)}} } @JvmStatic fun eachContainsIgnoreCase(list: List<String?>?, item: String?): Boolean { return item != null && list.orEmpty().filterNotNull().any { str -> str.contains(item, ignoreCase = true) } } /** * Checks if list is null or empty */ @JvmStatic fun <T> isEmpty(list: List<T>?): Boolean { return list == null || list.isEmpty() } /** * Checks that list is not null and not empty */ @JvmStatic fun <T> isNotEmpty(list: List<T>?): Boolean { return list != null && !list.isEmpty() } /** * If provided list is null returns a new ArrayList */ @JvmStatic fun <T> defaultIfNull(list: MutableList<T>?): MutableList<T> { return list ?: ArrayList<T>() } @JvmStatic fun <T> defaultIfNull(list: MutableList<T>?, defaultVal: MutableList<T>): MutableList<T> { return list ?: defaultVal } @JvmStatic fun <T> defaultIfEmpty(list: MutableList<T>?, defaultVal: MutableList<T>): MutableList<T> { return if (list == null || list.isEmpty()) defaultVal else list } @JvmStatic fun <T> hasOnlyOneItem(list: List<T?>?): Boolean { return list?.size == 1 } @JvmStatic fun <T> hasMoreThanOneItem(list: List<T?>?): Boolean { return list != null && list.size > 1 } @JvmStatic fun <T> emptyOrHasAtMostOneItem(list: List<T?>?): Boolean { return list == null || list.size <= 1 } @JvmStatic fun <T> hasOnlyOneNonNullItem(list: List<T?>?): Boolean { // we use sequence cause it has lazy evaluation return list != null && list.asSequence().filter { it != null }.count() == 1 } @JvmStatic fun <T> hasMoreThanOneNonNullItem(list: List<T?>?): Boolean { // we use sequence cause it has lazy evaluation return list != null && list.asSequence().filter { it != null }.count() > 1 } @JvmStatic fun <T> hasAtLeastOneNonNullItem(list: List<T?>?): Boolean { // we use sequence cause it has lazy evaluation return list != null && list.asSequence().filter { it != null }.count() > 0 } @JvmStatic fun <T> emptyOrHasAtMostOneNonNullItem(list: List<T?>?): Boolean { // we use sequence cause it has lazy evaluation return list == null || list.asSequence().filter { it != null }.count() <= 1 } @JvmStatic fun <T> getFirstItemIfExists(list: List<T?>?): Optional<T> { return Optional.ofNullable(list?.firstOrNull()) } @JvmStatic fun <T> getFirstNonNullItemIfExists(list: List<T?>?): Optional<T> { return Optional.ofNullable(list?.find { it != null }) } @JvmStatic fun <T> getLastItemIfExists(list: List<T?>?): Optional<T> { return Optional.ofNullable(list?.lastOrNull()) } @JvmStatic fun <T> getLastNonNullItemIfExists(list: List<T?>?): Optional<T> { return Optional.ofNullable(list?.findLast { it != null }) } @JvmStatic fun <T, U> mapTo(initialList: List<T?>?, mapper: (T?) -> U): List<U> { return initialList?.filter {it != null}?.map(mapper) ?: ArrayList() } @JvmStatic fun <T, U> mapToIncludeNull(initialList: List<T?>?, mapper: (T?) -> U?): List<U?> { return initialList?.map(mapper) ?: ArrayList() } } }
apache-2.0
161c7ea8952df31be768954dc15d065b
38.388889
118
0.574164
4.318538
false
false
false
false
tomhenne/Jerusalem
src/main/java/de/esymetric/jerusalem/main/Jerusalem.kt
1
14911
package de.esymetric.jerusalem.main import de.esymetric.jerusalem.osmDataRepresentation.OSMDataReader import de.esymetric.jerusalem.osmDataRepresentation.osm2ownMaps.PartitionedOsmNodeID2OwnIDMap import de.esymetric.jerusalem.ownDataRepresentation.geoData.Position import de.esymetric.jerusalem.ownDataRepresentation.geoData.importExport.KML import de.esymetric.jerusalem.rebuilding.Rebuilder import de.esymetric.jerusalem.routing.Router import de.esymetric.jerusalem.routing.RoutingType import de.esymetric.jerusalem.routing.algorithms.TomsAStarStarRouting import de.esymetric.jerusalem.routing.heuristics.TomsRoutingHeuristics import de.esymetric.jerusalem.tools.CrossroadsFinder import de.esymetric.jerusalem.utils.Utils import org.apache.tools.bzip2.CBZip2InputStream import java.io.* import java.util.* object Jerusalem { @JvmStatic fun main(args: Array<String>) { println("JERUSALEM 1.0 Java Enabled Routing Using Speedy Algorithms for Largely Extended Maps (jerusalem.gps-sport.net) based on OSM (OpenStreetMap.org)") if (args.isEmpty()) { printUsage() return } val command = args[0] val maxExecutionTimeS = 120 val dataDirectoryPath = (System.getProperty("user.dir") + File.separatorChar + "jerusalemData") var tempDirectoryPath = dataDirectoryPath File(dataDirectoryPath).mkdir() if ("clean" == command) { // remove temp files from osm 2 own id map if (args.size < 2) { printUsage() return } tempDirectoryPath = (args[1] + File.separatorChar + "jerusalemTempData") File(tempDirectoryPath).mkdirs() val poniom = PartitionedOsmNodeID2OwnIDMap( tempDirectoryPath, true ) poniom.deleteLatLonTempFiles() poniom.close() return } if ("rebuildIndex" == command) { if (args.size < 2) { printUsage() return } tempDirectoryPath = (args[1] + File.separatorChar + "jerusalemTempData") val rebuilder = Rebuilder( dataDirectoryPath, tempDirectoryPath, TomsRoutingHeuristics(), true, false, true ) rebuilder.makeQuadtreeIndex() // do NOT close Rebuilder rebuilder.close(); return } if ("rebuildTransitions" == command) { if (args.size < 2) { printUsage() return } tempDirectoryPath = (args[1] + File.separatorChar + "jerusalemTempData") val rebuilder = Rebuilder( dataDirectoryPath, tempDirectoryPath, TomsRoutingHeuristics(), true, false, false ) rebuilder.buildTransitions(true) // do NOT close Rebuilder rebuilder.close(); return } if ("rebuild" == command || "rebuildWays" == command) { val rebuildOnlyWays = "rebuildWays" == command if (args.size < 3) { printUsage() return } var filePath: String? = args[1] if ("-" != filePath) { println("Rebuilding $filePath") } else { println("Rebuilding from stdin") filePath = null } tempDirectoryPath = (args[2] + File.separatorChar + "jerusalemTempData") File(tempDirectoryPath).mkdirs() val startTime = Date() println("start date $startTime") try { val rebuilder = Rebuilder( dataDirectoryPath, tempDirectoryPath, TomsRoutingHeuristics(), rebuildOnlyWays, rebuildOnlyWays, false ) if (filePath != null) { val fis: InputStream = FileInputStream(filePath) fis.read() fis.read() val bzis = CBZip2InputStream(fis) val osmdr = OSMDataReader( bzis, rebuilder, rebuildOnlyWays ) osmdr.read(startTime) bzis.close() fis.close() } else { val osmdr = OSMDataReader( System.`in`, rebuilder, rebuildOnlyWays ) osmdr.read(startTime) } rebuilder.finishProcessingAndClose() } catch (e: IOException) { e.printStackTrace() } println("finish date " + Date()) println( "required time " + Utils.formatTimeStopWatch( Date().time - startTime.time ) ) return } // routing if ("route" == command || "routeVerbose" == command || "routeWithTransitions" == command) { if (args.size < 6) { printUsage() return } val router = Router( dataDirectoryPath, TomsAStarStarRouting(), TomsRoutingHeuristics(), maxExecutionTimeS ) Router.debugMode = "routeVerbose" == command val outputTransitions = "routeWithTransitions" == command val routingType = args[1] val lat1 = args[2].toDouble() val lng1 = args[3].toDouble() val lat2 = args[4].toDouble() val lng2 = args[5].toDouble() val route = router.findRoute( routingType, lat1, lng1, lat2, lng2 ) router.close() if (route != null) { for (n in route) { val sb = StringBuilder() sb.append(n.lat).append(',').append(n.lng) if (outputTransitions) { sb.append(',').append(n.numberOfTransitionsIfTransitionsAreLoaded) } println(sb.toString()) } if (args.size > 6) { val filename = args[6] val kml = KML() val trackPts = Vector<Position>() for (n in route) { val p = Position() p.latitude = n.lat p.longitude = n.lng trackPts.add(p) } kml.trackPositions = trackPts kml.save( dataDirectoryPath + File.separatorChar + filename + "-" + routingType + ".kml" ) } } return } // find crossroads if ("findCrossroads" == command) { if (args.size < 2) { printUsage() return } val routingType = args[1] val isr = InputStreamReader(System.`in`) val lnr = LineNumberReader(isr) val positions: MutableList<Position> = ArrayList() while (true) { var line: String? = null try { line = lnr.readLine() } catch (e: IOException) { e.printStackTrace() } if (line == null || "eof" == line) break val lp = line.split(",").toTypedArray() if (lp.size < 3) { continue } val p = Position() p.latitude = lp[0].toDouble() p.longitude = lp[1].toDouble() p.altitude = lp[2].toDouble() positions.add(p) } val cf = CrossroadsFinder(dataDirectoryPath) cf.loadNumberOfCrossroads(positions, RoutingType.valueOf(routingType)) for (p in positions) { val sb = StringBuilder() sb.append(p.latitude).append(',').append(p.longitude).append(',').append(p.altitude).append(',') .append(p.nrOfTransitions.toInt()) println(sb.toString()) } return } // find crossroads test if ("findCrossroadsTest" == command) { if (args.size < 2) { printUsage() return } val routingType = args[1] val positions: MutableList<Position> = ArrayList() var pt = Position() pt.latitude = 48.116915489240476 pt.longitude = 11.48764371871948 pt.altitude = 600.0 positions.add(pt) pt = Position() pt.latitude = 48.15 pt.longitude = 11.55 pt.altitude = 660.0 positions.add(pt) val cf = CrossroadsFinder(dataDirectoryPath) cf.loadNumberOfCrossroads(positions, RoutingType.valueOf(routingType)) for (p in positions) { val sb = StringBuilder() sb.append(p.latitude).append(',').append(p.longitude).append(',').append(p.altitude).append(',') .append(p.nrOfTransitions.toInt()) println(sb.toString()) } return } // test routing if ("routingTest" == command) { val startTime = Date() println("routing test start date $startTime") val router = Router( dataDirectoryPath, TomsAStarStarRouting(), TomsRoutingHeuristics(), maxExecutionTimeS ) Router.debugMode = true testRoute( router, 48.116915489240476, 11.48764371871948, 48.219297, 11.372824, "hadern-a8", dataDirectoryPath ) testRoute( router, 48.116915489240476, 11.48764371871948, 48.29973956844243, 10.97055673599243, "hadern-kissing", dataDirectoryPath ) testRoute( router, 48.125166, 11.451445, 48.12402, 11.515946, "a96", dataDirectoryPath ) testRoute( router, 48.125166, 11.451445, 48.103516, 11.501441, "a96_Fuerstenrieder", dataDirectoryPath ) testRoute( router, 48.09677, 11.323729, 48.393707, 11.841116, "autobahn", dataDirectoryPath ) testRoute( router, 48.107891, 11.461865, 48.099986, 11.511051, "durch-waldfriedhof", dataDirectoryPath ) testRoute( router, 48.107608, 11.461648, 48.108656, 11.477371, "grosshadern-fussweg", dataDirectoryPath ) testRoute( router, 48.275653, 11.786957, 48.106514, 11.449685, "muenchen-quer", dataDirectoryPath ) testRoute( router, 48.073606, 11.38175, 48.065548, 11.327763, "gauting-unterbrunn", dataDirectoryPath ) testRoute( router, 48.073606, 11.38175, 48.152888, 11.346259, "gauting-puchheim", dataDirectoryPath ) testRoute( router, 48.073606, 11.38175, 48.365138, 11.583881, "gauting-moosanger", dataDirectoryPath ) testRoute( router, 47.986073, 11.326733, 48.230162, 11.717434, "starnberg-ismaning", dataDirectoryPath ) router.close() println("finish date " + Date()) println( "required time " + Utils.formatTimeStopWatch( Date().time - startTime.time ) ) } } private fun printUsage() { println("java -jar Jerusalem.jar route foot|bike|racingBike|mountainBike|car|carShortest <latitude1> <longitude1> <latitude2> <longitude2> [<output-file-base-name>]") println("java -jar Jerusalem.jar rebuild <source-filepath>|- <temp-filepath>") println("java -jar Jerusalem.jar rebuildIndex <temp-filepath>") println("java -jar Jerusalem.jar rebuildTransitions <temp-filepath>") println("java -jar Jerusalem.jar clean <temp-filepath>") println("java -jar Jerusalem.jar routingTest") println("java -jar Jerusalem.jar findCrossroads foot|bike|racingBike|mountainBike|car|carShortest") println("java -jar Jerusalem.jar findCrossroadsTest foot|bike|racingBike|mountainBike|car|carShortest") } private fun testRoute( router: Router, lat1: Double, lng1: Double, lat2: Double, lng2: Double, name: String, dataDirectoryPath: String ) { for (rt in RoutingType.values()) testRoute( router, rt.name, lat1, lng1, lat2, lng2, name, dataDirectoryPath ) } fun testRoute( router: Router, routingType: String, lat1: Double, lng1: Double, lat2: Double, lng2: Double, name: String, dataDirectoryPath: String ) { println("---------------------------------------------") println("Computing Route $name ($routingType)") println("---------------------------------------------") val route = router .findRoute(routingType, lat1, lng1, lat2, lng2) if (route == null) { println( "ERROR: no route found for " + name + " (" + routingType + ")" ) return } println() val kml = KML() val trackPts = Vector<Position>() for (n in route) { val p = Position() p.latitude = n.lat p.longitude = n.lng trackPts.add(p) } kml.trackPositions = trackPts kml.save( dataDirectoryPath + File.separatorChar + name + "-" + routingType + ".kml" ) } }
apache-2.0
9de8a1ce55910adad3aea84bdaa9c5aa
36.735065
174
0.48253
4.874469
false
true
false
false
cloose/luftbild4p3d
src/main/kotlin/org/luftbild4p3d/osm/Way.kt
1
430
package org.luftbild4p3d.osm import javax.xml.bind.annotation.XmlAttribute import javax.xml.bind.annotation.XmlElement class Way(@XmlAttribute val id: Long = 0) { @XmlElement(name = "nd") val nodeReference: MutableCollection<NodeReference> = mutableListOf() @XmlElement(name = "tag") val tag: MutableCollection<Tag> = mutableListOf() fun closed() = nodeReference.first().ref == nodeReference.last().ref }
gpl-3.0
4fd11d877271a0a96e0c29d7e2731e06
27.733333
73
0.730233
3.839286
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/ApplicationAction.kt
1
5397
/* ParaTask Copyright (C) 2017 Nick Robinson> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.gui import javafx.event.EventHandler import javafx.scene.control.* import javafx.scene.image.Image import javafx.scene.image.ImageView import javafx.scene.input.KeyCode import javafx.scene.input.KeyCodeCombination import javafx.scene.input.KeyCombination import javafx.scene.input.KeyEvent import uk.co.nickthecoder.paratask.ParaTask import kotlin.reflect.KMutableProperty0 /** */ open class ApplicationAction( val name: String, keyCode: KeyCode?, shift: Boolean? = false, control: Boolean? = false, alt: Boolean? = false, meta: Boolean? = false, shortcut: Boolean? = false, val tooltip: String? = null, val label: String? = null ) { private val defaultKeyCodeCombination: KeyCodeCombination? = keyCode?.let { createKeyCodeCombination(keyCode, shift, control, alt, meta, shortcut) } var keyCodeCombination = defaultKeyCodeCombination open val image: Image? = ParaTask.imageResource("buttons/$name.png") fun revert() { keyCodeCombination = defaultKeyCodeCombination } fun isChanged(): Boolean = keyCodeCombination != defaultKeyCodeCombination fun shortcutString(): String = if (keyCodeCombination?.code == null) "" else keyCodeCombination.toString() fun match(event: KeyEvent): Boolean { return keyCodeCombination?.match(event) == true } fun createTooltip(): Tooltip? { if (tooltip == null && keyCodeCombination == null) { return null } val result = StringBuilder() tooltip?.let { result.append(it) } if (tooltip != null && keyCodeCombination != null) { result.append(" (") } keyCodeCombination?.let { result.append(it.displayText) } if (tooltip != null && keyCodeCombination != null) { result.append(")") } return Tooltip(result.toString()) } fun shortcutLabel() = keyCodeCombination?.displayText fun createMenuItem(shortcuts: ShortcutHelper? = null, action: () -> Unit): MenuItem { shortcuts?.add(this, action) val menuItem = MenuItem(label) menuItem.onAction = EventHandler { action() } image?.let { menuItem.graphic = ImageView(it) } menuItem.accelerator = keyCodeCombination return menuItem } fun createCheckMenuItem(shortcuts: ShortcutHelper? = null, property: KMutableProperty0<Boolean>, action: () -> Unit): CheckMenuItem { val menuItem = CheckMenuItem(label) menuItem.isSelected = property.getter.call() val updateAction = { menuItem.isSelected != menuItem.isSelected property.setter.call(menuItem.isSelected) action() } shortcuts?.add(this, updateAction) menuItem.accelerator = keyCodeCombination menuItem.onAction = EventHandler { updateAction() } return menuItem } fun createButton(shortcuts: ShortcutHelper? = null, action: () -> Unit): Button { shortcuts?.add(this, action) val button = Button() updateButton(button, action) return button } fun createToggleButton(shortcuts: ShortcutHelper? = null, action: () -> Unit): ToggleButton { val button = ToggleButton() shortcuts?.add(this, { button.isSelected = !button.isSelected action() }) updateButton(button, action) return button } private fun updateButton(button: ButtonBase, action: () -> Unit) { if (image == null) { button.text = label ?: name } else { button.graphic = ImageView(image) } if (label != null) { button.text = label } button.onAction = EventHandler { action() } button.tooltip = createTooltip() } companion object { fun modifier(down: Boolean?) = if (down == null) { KeyCombination.ModifierValue.ANY } else if (down) { KeyCombination.ModifierValue.DOWN } else { KeyCombination.ModifierValue.UP } fun createKeyCodeCombination( keyCode: KeyCode, shift: Boolean? = false, control: Boolean? = false, alt: Boolean? = false, meta: Boolean? = false, shortcut: Boolean? = false): KeyCodeCombination { return KeyCodeCombination( keyCode, modifier(shift), modifier(control), modifier(alt), modifier(meta), modifier(shortcut)) } } }
gpl-3.0
4e4c97a70dff9611d5bb38b223a639bc
30.747059
137
0.62368
4.879747
false
false
false
false
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/support/SettingsRepositoryExtensions.kt
1
2530
package net.nemerosa.ontrack.model.support import kotlin.reflect.KProperty0 import kotlin.reflect.KProperty1 /** * Type safe access to settings. */ inline fun <reified T> SettingsRepository.getString(property: KProperty1<T, String?>, defaultValue: String): String = getString(T::class.java, property.name, defaultValue) /** * Type safe access to settings. */ inline fun <reified T> SettingsRepository.getInt(property: KProperty1<T, Int?>, defaultValue: Int): Int = getInt(T::class.java, property.name, defaultValue) /** * Type safe access to settings. */ inline fun <reified T> SettingsRepository.getLong(property: KProperty1<T, Long?>, defaultValue: Long): Long = getLong(T::class.java, property.name, defaultValue) /** * Type safe access to settings. */ inline fun <reified T> SettingsRepository.getBoolean( property: KProperty1<T, Boolean?>, defaultValue: Boolean, ): Boolean = getBoolean(T::class.java, property.name, defaultValue) /** * Type safe access to settings. */ inline fun <reified T, reified E : Enum<E>> SettingsRepository.getEnum( property: KProperty1<T, E?>, defaultValue: E, ): E = getString(T::class.java, property.name, "") .takeIf { it.isNotBlank() } ?.let { enumValueOf<E>(it) } ?: defaultValue /** * Type safe access to settings. */ inline fun <reified T> SettingsRepository.getPassword( property: KProperty1<T, String?>, defaultValue: String, noinline decryptService: (String?) -> String?, ): String = getPassword(T::class.java, property.name, defaultValue, decryptService) /** * Type safe setter of settings */ inline fun <reified T> SettingsRepository.setString(property: KProperty0<String?>) { setString(T::class.java, property.name, property.get()) } /** * Type safe setter of settings */ inline fun <reified T> SettingsRepository.setBoolean(property: KProperty0<Boolean>) { setBoolean(T::class.java, property.name, property.get()) } /** * Type safe setter of settings */ inline fun <reified T> SettingsRepository.setInt(property: KProperty0<Int>) { setInt(T::class.java, property.name, property.get()) } /** * Type safe setter of settings */ inline fun <reified T> SettingsRepository.setLong(property: KProperty0<Long>) { setLong(T::class.java, property.name, property.get()) } /** * Type safe setter of settings */ inline fun <reified T, E : Enum<E>> SettingsRepository.setEnum(property: KProperty0<E>) { setString(T::class.java, property.name, property.get().toString()) }
mit
f31bc02248e83b4388e91befba7836ae
28.08046
117
0.704743
3.787425
false
false
false
false
yh-kim/gachi-android
Gachi/app/src/main/kotlin/com/pickth/gachi/view/chat/ChatDetailPresenter.kt
1
2862
/* * Copyright 2017 Yonghoon Kim * * 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.pickth.gachi.view.chat import android.util.Log import com.pickth.commons.mvp.BaseView import com.pickth.gachi.net.service.GachiService import com.pickth.gachi.view.chat.adapter.ChatDetailAdapterContract import com.pickth.gachi.view.chat.adapter.ChatMessage import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.text.SimpleDateFormat import java.util.* class ChatDetailPresenter: ChatDetailContract.Presenter { private lateinit var mView: ChatDetailContract.View private lateinit var mAdapterView: ChatDetailAdapterContract.View private lateinit var mAdapterModel: ChatDetailAdapterContract.Model private lateinit var mParticipantAdapter: ParticipantAdapter override fun attachView(view: BaseView<*>) { mView = view as ChatDetailContract.View } override fun setChatDetailAdapterView(view: ChatDetailAdapterContract.View) { mAdapterView = view } override fun setChatDetailAdapterModel(model: ChatDetailAdapterContract.Model) { mAdapterModel = model } override fun setParticipantAdapter(adapter: ParticipantAdapter) { mParticipantAdapter = adapter } override fun getItemCount(): Int = mAdapterModel.getItemCount() override fun sendMessage(msg: String) { val date = SimpleDateFormat("hh : mm a").format(Date(System.currentTimeMillis())).toString() mAdapterModel.addItem(ChatMessage(msg, date ,0)) // test input mAdapterModel.addItem(ChatMessage("test", date ,1)) mView.scrollToPosition(getItemCount()) } override fun getGachiInfo() { GachiService().getGachiInfo(mView.getLid()) .enqueue(object: Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>) { Log.d("Gachi__ChatPresenter", "getGachiInfo onResponse, code: ${response.code()}") if(response.code() != 200) return mView.bindGachiInfo(response.body()?.string()!!) } override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) { } }) } }
apache-2.0
6ae8356eac8c8452b8fcd2860d76486c
34.7875
106
0.698113
4.684124
false
false
false
false
Pixelhash/SignColors
src/main/kotlin/de/codehat/signcolors/daos/SignLocationDao.kt
1
2137
package de.codehat.signcolors.daos import com.j256.ormlite.jdbc.JdbcConnectionSource import de.codehat.signcolors.SignColors import de.codehat.signcolors.dao.Dao import de.codehat.signcolors.database.model.SignLocation import org.bukkit.Location import org.bukkit.block.Block class SignLocationDao(connectionSource: JdbcConnectionSource): Dao<SignLocation, Void>(connectionSource, SignLocation::class.java) { fun exists(block: Block): Boolean { return exists(block.location) } fun exists(location: Location): Boolean { with(location) { return exists(this.world.name, this.blockX, this.blockY, this.blockZ) } } fun exists(world: String, x: Int, y: Int, z: Int): Boolean { val queryBuilder = dao.queryBuilder() val where = queryBuilder.where() with(where) { eq("world", world) and() eq("x", x) and() eq("y", y) and() eq("z", z) } return dao.query(queryBuilder.prepare()).size >= 1 } fun create(block: Block) { create(block.location) } fun create(location: Location) { with(location) { create(this.world.name, this.blockX, this.blockY, this.blockZ) } } fun create(world: String, x: Int, y: Int, z: Int) { SignLocation(world, x, y, z).apply { dao.create(this) } } fun delete(block: Block) { delete(block.location) } fun delete(location: Location) { with(location) { delete(this.world.name, this.blockX, this.blockY, this.blockZ) } } fun delete(world: String, x: Int, y: Int, z: Int) { if (exists(world, x, y, z)) { val deleteBuilder = dao.deleteBuilder() val where = deleteBuilder.where() with(where) { eq("world", world) and() eq("x", x) and() eq("y", y) and() eq("z", z) } deleteBuilder.delete() } } }
gpl-3.0
1916f505e4f935ca11335e20deffc75d
24.440476
81
0.542349
3.899635
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/gallery/ImageInfo.kt
1
1402
package org.wikipedia.gallery import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable class ImageInfo { var source = "" var captions = emptyMap<String, String>() @SerialName("short_name") private val shortName: String? = null @SerialName("descriptionshorturl") private val descriptionShortUrl: String? = null private val derivatives = emptyList<Derivative>() // Fields specific to video files: private val codecs: List<String>? = null private val name: String? = null @SerialName("descriptionurl") val commonsUrl = "" @SerialName("thumburl") val thumbUrl = "" @SerialName("thumbwidth") val thumbWidth = 0 @SerialName("thumbheight") val thumbHeight = 0 @SerialName("url") val originalUrl = "" val mime = "*/*" @SerialName("extmetadata") val metadata: ExtMetadata? = null val user = "" val timestamp = "" val size = 0 val width = 0 val height = 0 val bestDerivative get() = derivatives.lastOrNull() // TODO: make this smarter. @Serializable class Derivative { val src = "" private val type: String? = null private val title: String? = null private val shorttitle: String? = null private val width = 0 private val height = 0 private val bandwidth: Long = 0 } }
apache-2.0
522b3e5ac0673ed8ba1e0754f5ef9d67
21.612903
55
0.63766
4.508039
false
false
false
false
Xenoage/Zong
utils-kotlin/src/com/xenoage/utils/math/Math.kt
1
5483
package com.xenoage.utils.math import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin import kotlin.math.sqrt /** PI in float precision. */ val pi = PI.toFloat() /** Returns max, if this > max, min, if this < min, else this. */ fun Int.clamp(min: Int, max: Int): Int = when { this < min -> min this > max -> max else -> this } /** * Returns this, if this < min, else this. */ fun Int.clampMin(min: Int): Int = when { this < min -> min else -> this } /** Returns max, if this > max, min, if this < min, else this. */ fun Int.clampMax(max: Int): Int = when { this > max -> max else -> this } /** * Returns min, if x < min, else x. */ fun clampMin(x: Float, min: Float): Float { return if (x < min) min else x } /** * Returns max, if x > max, min, if x < min, else x. */ fun clamp(x: Double, min: Double, max: Double): Double { return if (x < min) min else if (x > max) max else x } /** * Returns min, if x < min, else x. */ fun clampMin(x: Double, min: Double): Double { return if (x < min) min else x } /** * Returns the greatest common divisor of the given numbers. */ fun gcd(n1: Int, n2: Int): Int { return if (n2 == 0) n1 else gcd(n2, n1 % n2) } /** * Returns the least common multiple of the given numbers. */ fun lcm(n1: Int, n2: Int): Int { var ret = gcd(n1, n2) ret = n1 * n2 / ret return ret } /** * Like the % operator, but also returns positive results for negative numbers. * E.g. -3 mod 4 = 1. */ fun mod(n: Int, mod: Int): Int { return (n % mod + mod) % mod } /** * Returns the lowest result of n modulo mod, where the result is still * greater or equal than min. Also negative values are allowed, and n may be * smaller than min. */ fun modMin(n: Int, mod: Int, min: Int): Int { var n = n if (mod < 1) throw IllegalArgumentException("mod must be > 0") while (n < min) n += mod while (n - mod >= min) n -= mod return n } /** * Rotates the given point by the given angle in degrees in counter * clockwise order around the origin and returnes the rotated point. */ fun rotate(p: Point2f, angle: Float): Point2f { if (angle == 0f) return p val rot = angle * PI / 180 val cos = cos(rot) val sin = sin(rot) val x = (p.x * +cos + p.y * +sin).toFloat() val y = (p.x * -sin + p.y * +cos).toFloat() return Point2f(x, y) } /** * Returns the position of the given cubic Bézier curve at the given t value * between 0 and 1. The Bézier curve is defined by the start and end point * (named p1 and p2) and two control points (named c1 and c2). */ fun bezier(p1: Point2f, p2: Point2f, c1: Point2f, c2: Point2f, t: Float) = Point2f((-p1.x + 3 * c1.x - 3 * c2.x + p2.x) * t * t * t + (3 * p1.x - 6 * c1.x + 3 * c2.x) * t * t + (-3 * p1.x + 3 * c1.x) * t + p1.x, (-p1.y + 3 * c1.y - 3 * c2.y + p2.y) * t * t * t + (3 * p1.y - 6 * c1.y + 3 * c2.y) * t * t + (-3 * p1.y + 3 * c1.y) * t + p1.y) /** * Linear interpolation between p1 and p2, at position t between t1 and t2, * where t1 is the coordinate of p1 and t2 is the coordinate of p2. */ fun interpolateLinear(p1: Float, p2: Float, t1: Float, t2: Float, t: Float): Float { return p1 + (p2 - p1) * (t - t1) / (t2 - t1) } /** * Linear interpolation between p1 and p2, at position t between t1 and t2, * where t1 is the coordinate of p1 and t2 is the coordinate of p2. */ fun interpolateLinear(points: LinearInterpolationPoints, t: Float): Float { return interpolateLinear(points.p1, points.p2, points.t1, points.t2, t) } class LinearInterpolationPoints(val p1: Float, val p2: Float, val t1: Float, val t2: Float) fun lowestPrimeNumber(number: Int): Int { var i = 2 while (i <= sqrt(number.toDouble())) { if (number % i == 0) return i i++ } return number } /** * Computes and returns a rotated rectangle, that encloses the given two * points with the given width. * This is shown here: * * <pre> * [0]---___ * / ---___ * p1 ---[1] _ _ * / / / * [3]---___ p2 / width * ---___ / / * ---[2] _/_ </pre> * * * The result is returned as four Point2f values as shown on the above * sketch. */ fun computeRectangleFromTo(p1: Point2f, p2: Point2f, width: Float): Array<Point2f> { // compute the line from p1 to p2 val p1Top2 = p2.sub(p1) // compute the line from p1 to [0] val p1To0 = Point2f(p1Top2.y, -p1Top2.x).normalize().scale(width / 2) // compute return values return arrayOf<Point2f>(p1.add(p1To0), p2.add(p1To0), p2.sub(p1To0), p1.sub(p1To0)) } /** * Returns -1 if the given value is negative, 1 if the given value is * positive, 0 otherwise. */ fun sign(v: Float) = if (v < 0) -1f else if (v > 0) 1f else 0f /** * Returns the minimum element of the given [Comparable]s. * If any element is null or if no element is given, null is returned. * If more then one element qualifies, the first one is returned. */ fun <T : Comparable<T>> minOrNull(vararg ts: T?): T? { var ret: T? = null for (t in ts) if (t == null) return null else if (ret == null || t < ret) ret = t return ret } /** * For 2 ^ x = number, returns x. For example. 2 ^ x = 8 returns 3. * When there is no integer solution, the next smaller integer is returned, * for example 2 ^ x = 5 returns 2. */ fun log2(number: Long): Int { if (number < 1) throw IllegalArgumentException("log2(x) = n for n < 1 not possible") var n: Long = 1 var ret = 0 while (n <= number) { n *= 2 ret++ } return ret - 1 }
agpl-3.0
a82b8771b6fca34230ee2331339c18be
22.934498
119
0.607188
2.661972
false
false
false
false
sksamuel/scrimage
scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/X11ColorlistGenerator.kt
1
532
package com.sksamuel.scrimage.core import java.nio.file.Files import java.nio.file.Paths fun main() { val file = "/etc/X11/rgb.txt" Files.newInputStream(Paths.get(file)).bufferedReader().readLines().map { line -> val tokens = line.replace("\\s{2,}".toRegex(), " ").trim().split(' ') val red = tokens[0] val green = tokens[1] val blue = tokens[2] val name = tokens.drop(3).joinToString(" ").trim() if (!name.contains(" ")) println("val $name = Color($red, $green, $blue)") } }
apache-2.0
20cd7f36d4163ba8250b95f749c5f931
30.294118
83
0.601504
3.388535
false
false
false
false
mvarnagiris/expensius
billing/src/main/kotlin/com/mvcoding/billing/Security.kt
1
2746
/* * Copyright (C) 2016 Mantas Varnagiris. * * 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. */ package com.mvcoding.billing import android.util.Base64 import android.util.Log import java.security.* import java.security.spec.InvalidKeySpecException import java.security.spec.X509EncodedKeySpec object Security { private val TAG = "Billing/Security" private val KEY_FACTORY_ALGORITHM = "RSA" private val SIGNATURE_ALGORITHM = "SHA1withRSA" fun verifyPurchase(base64PublicKey: String, signedData: String, signature: String): Boolean { if (base64PublicKey.isEmpty() || signedData.isEmpty() || signature.isEmpty()) return false val key = generatePublicKey(base64PublicKey) return verify(key, signedData, signature) } private fun generatePublicKey(base64PublicKey: String): PublicKey { return try { val decodedKey = Base64.decode(base64PublicKey, Base64.DEFAULT) val keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM) keyFactory.generatePublic(X509EncodedKeySpec(decodedKey)) } catch (e: NoSuchAlgorithmException) { throw RuntimeException(e); } catch (e: InvalidKeySpecException) { throw IllegalArgumentException(e) } } private fun verify(publicKey: PublicKey, signedData: String, signature: String): Boolean { val signatureBytes: ByteArray try { signatureBytes = Base64.decode(signature, Base64.DEFAULT) } catch (e: IllegalArgumentException) { Log.e(TAG, "Base64 decoding failed.") return false } try { val sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey) sig.update(signedData.toByteArray()) if (!sig.verify(signatureBytes)) { Log.e(TAG, "Signature verification failed.") return false } return true } catch (e: NoSuchAlgorithmException) { Log.e(TAG, "NoSuchAlgorithmException.") } catch (e: InvalidKeyException) { Log.e(TAG, "Invalid key specification.") } catch (e: SignatureException) { Log.e(TAG, "Signature exception.") } return false } }
gpl-3.0
adedd86ecbda507591172067b09fb4f1
36.121622
98
0.662782
4.71012
false
false
false
false
TeamWizardry/LibrarianLib
modules/albedo/src/main/kotlin/com/teamwizardry/librarianlib/albedo/shader/uniform/DoubleMatrices.kt
1
18961
package com.teamwizardry.librarianlib.albedo.shader.uniform import com.teamwizardry.librarianlib.core.bridge.IMatrix3f import com.teamwizardry.librarianlib.core.bridge.IMatrix4f import com.teamwizardry.librarianlib.core.util.mixinCast import com.teamwizardry.librarianlib.math.Matrix3d import com.teamwizardry.librarianlib.math.Matrix4d import net.minecraft.util.math.Matrix3f import net.minecraft.util.math.Matrix4f import org.lwjgl.opengl.GL40 /** * All the matrix uniform APIs represent the matrix in *row* major order. Internally they're transformed to column major * order, but this doesn't matter to you. * * The only time the major order matters is when you're asked to turn a flat array like `[a, b, c, d, e, f, g, h, i]` * into a matrix. The matrix itself *doesn't rotate.* The only difference is the order you string the values together * when you make them into a flat array. With that out of the way, here's what that looks like for a 3x3 matrix. * Keep in mind that these letters have nothing to do with the math, the only significance is the order they're stored * in memory. * * ``` * "Row major" * ⎡ a b c ⎤ * ⎢ d e f ⎥ * ⎣ g h i ⎦ * * "Column major" * ⎡ a d g ⎤ * ⎢ b e h ⎥ * ⎣ c f i ⎦ * ``` */ public sealed class DoubleMatrixUniform(name: String, glConstant: Int, public val columns: Int, public val rows: Int) : Uniform(name, glConstant) { protected var values: DoubleArray = DoubleArray(columns * rows) protected operator fun get(row: Int, column: Int): Double { return values[column * rows + row] } protected operator fun set(row: Int, column: Int, value: Double) { values[column * rows + row] = value } } public sealed class DoubleMatrixArrayUniform( name: String, glConstant: Int, length: Int, public val columns: Int, public val rows: Int ) : ArrayUniform(name, glConstant, length) { private val stride = columns * rows protected val values: DoubleArray = DoubleArray(length * stride) protected operator fun get(index: Int, row: Int, column: Int): Double { return values[index * stride + column * rows + row] } protected operator fun set(index: Int, row: Int, column: Int, value: Double) { values[index * stride + column * rows + row] = value } } public class DoubleMat2x2Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT2, columns = 2, rows = 2) { /** * ``` * ⎡ m00 m01 ⎤ * ⎣ m10 m11 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m10: Double, m11: Double, ) { this[0, 0] = m00; this[0, 1] = m01 this[1, 0] = m10; this[1, 1] = m11 } override fun push() { GL40.glUniformMatrix2dv(location, true, values) } } public class DoubleMat2x2ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT2, length, columns = 2, rows = 2) { /** * ``` * ⎡ m00 m01 ⎤ * ⎣ m10 m11 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m10: Double, m11: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01 this[index, 1, 0] = m10; this[index, 1, 1] = m11 } override fun push() { GL40.glUniformMatrix2dv(location, true, values) } } public class DoubleMat3x3Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT3, columns = 3, rows = 3) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎣ m20 m21 m22 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, m20: Double, m21: Double, m22: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12 this[2, 0] = m20; this[2, 1] = m21; this[2, 2] = m22 } public fun set(matrix: Matrix3d) { this.set( matrix.m00, matrix.m01, matrix.m02, matrix.m10, matrix.m11, matrix.m12, matrix.m20, matrix.m21, matrix.m22, ) } public fun set(matrix: Matrix3f) { val imatrix = mixinCast<IMatrix3f>(matrix) this.set( imatrix.m00.toDouble(), imatrix.m01.toDouble(), imatrix.m02.toDouble(), imatrix.m10.toDouble(), imatrix.m11.toDouble(), imatrix.m12.toDouble(), imatrix.m20.toDouble(), imatrix.m21.toDouble(), imatrix.m22.toDouble(), ) } override fun push() { GL40.glUniformMatrix3dv(location, true, values) } } public class DoubleMat3x3ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT3, length, columns = 3, rows = 3) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎣ m20 m21 m22 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, m20: Double, m21: Double, m22: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12 this[index, 2, 0] = m20; this[index, 2, 1] = m21; this[index, 2, 2] = m22 } public fun set(index: Int, matrix: Matrix3d) { this.set( index, matrix.m00, matrix.m01, matrix.m02, matrix.m10, matrix.m11, matrix.m12, matrix.m20, matrix.m21, matrix.m22, ) } public fun set(index: Int, matrix: Matrix3f) { @Suppress("CAST_NEVER_SUCCEEDS") val imatrix = matrix as IMatrix3f this.set( index, imatrix.m00.toDouble(), imatrix.m01.toDouble(), imatrix.m02.toDouble(), imatrix.m10.toDouble(), imatrix.m11.toDouble(), imatrix.m12.toDouble(), imatrix.m20.toDouble(), imatrix.m21.toDouble(), imatrix.m22.toDouble(), ) } override fun push() { GL40.glUniformMatrix3dv(location, true, values) } } public class DoubleMat4x4Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT4, columns = 4, rows = 4) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎢ m10 m11 m12 m13 ⎥ * ⎢ m20 m21 m22 m23 ⎥ * ⎣ m30 m31 m32 m33 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, m20: Double, m21: Double, m22: Double, m23: Double, m30: Double, m31: Double, m32: Double, m33: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02; this[0, 3] = m03 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12; this[1, 3] = m13 this[2, 0] = m20; this[2, 1] = m21; this[2, 2] = m22; this[2, 3] = m23 this[3, 0] = m30; this[3, 1] = m31; this[3, 2] = m32; this[3, 3] = m33 } public fun set(matrix: Matrix4d) { this.set( matrix.m00, matrix.m01, matrix.m02, matrix.m03, matrix.m10, matrix.m11, matrix.m12, matrix.m13, matrix.m20, matrix.m21, matrix.m22, matrix.m23, matrix.m30, matrix.m31, matrix.m32, matrix.m33, ) } public fun set(matrix: Matrix4f) { @Suppress("CAST_NEVER_SUCCEEDS") val imatrix = matrix as IMatrix4f this.set( imatrix.m00.toDouble(), imatrix.m01.toDouble(), imatrix.m02.toDouble(), imatrix.m03.toDouble(), imatrix.m10.toDouble(), imatrix.m11.toDouble(), imatrix.m12.toDouble(), imatrix.m13.toDouble(), imatrix.m20.toDouble(), imatrix.m21.toDouble(), imatrix.m22.toDouble(), imatrix.m23.toDouble(), imatrix.m30.toDouble(), imatrix.m31.toDouble(), imatrix.m32.toDouble(), imatrix.m33.toDouble(), ) } override fun push() { GL40.glUniformMatrix4dv(location, true, values) } } public class DoubleMat4x4ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT4, length, columns = 4, rows = 4) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎢ m10 m11 m12 m13 ⎥ * ⎢ m20 m21 m22 m23 ⎥ * ⎣ m30 m31 m32 m33 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, m20: Double, m21: Double, m22: Double, m23: Double, m30: Double, m31: Double, m32: Double, m33: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02; this[index, 0, 3] = m03 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12; this[index, 1, 3] = m13 this[index, 2, 0] = m20; this[index, 2, 1] = m21; this[index, 2, 2] = m22; this[index, 2, 3] = m23 this[index, 3, 0] = m30; this[index, 3, 1] = m31; this[index, 3, 2] = m32; this[index, 3, 3] = m33 } public fun set(index: Int, matrix: Matrix4d) { this.set( index, matrix.m00, matrix.m01, matrix.m02, matrix.m03, matrix.m10, matrix.m11, matrix.m12, matrix.m13, matrix.m20, matrix.m21, matrix.m22, matrix.m23, matrix.m30, matrix.m31, matrix.m32, matrix.m33, ) } public fun set(index: Int, matrix: Matrix4f) { val imatrix = mixinCast<IMatrix4f>(matrix) this.set( index, imatrix.m00.toDouble(), imatrix.m01.toDouble(), imatrix.m02.toDouble(), imatrix.m03.toDouble(), imatrix.m10.toDouble(), imatrix.m11.toDouble(), imatrix.m12.toDouble(), imatrix.m13.toDouble(), imatrix.m20.toDouble(), imatrix.m21.toDouble(), imatrix.m22.toDouble(), imatrix.m23.toDouble(), imatrix.m30.toDouble(), imatrix.m31.toDouble(), imatrix.m32.toDouble(), imatrix.m33.toDouble(), ) } override fun push() { GL40.glUniformMatrix4dv(location, true, values) } } public class DoubleMat2x3Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT2x3, columns = 2, rows = 3) { /** * ``` * ⎡ m00 m01 ⎤ * ⎢ m10 m11 ⎥ * ⎣ m20 m21 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m10: Double, m11: Double, m20: Double, m21: Double, ) { this[0, 0] = m00; this[0, 1] = m01 this[1, 0] = m10; this[1, 1] = m11 this[2, 0] = m20; this[2, 1] = m21 } override fun push() { GL40.glUniformMatrix2x3dv(location, true, values) } } public class DoubleMat2x3ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT2x3, length, columns = 2, rows = 3) { /** * ``` * ⎡ m00 m01 ⎤ * ⎢ m10 m11 ⎥ * ⎣ m20 m21 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m10: Double, m11: Double, m20: Double, m21: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01 this[index, 1, 0] = m10; this[index, 1, 1] = m11 this[index, 2, 0] = m20; this[index, 2, 1] = m21 } override fun push() { GL40.glUniformMatrix2x3dv(location, true, values) } } public class DoubleMat2x4Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT2x4, columns = 2, rows = 4) { /** * ``` * ⎡ m00 m01 ⎤ * ⎢ m10 m11 ⎥ * ⎢ m20 m21 ⎥ * ⎣ m30 m31 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m10: Double, m11: Double, m20: Double, m21: Double, m30: Double, m31: Double, ) { this[0, 0] = m00; this[0, 1] = m01 this[1, 0] = m10; this[1, 1] = m11 this[2, 0] = m20; this[2, 1] = m21 this[3, 0] = m30; this[3, 1] = m31 } override fun push() { GL40.glUniformMatrix2x4dv(location, true, values) } } public class DoubleMat2x4ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT2x4, length, columns = 2, rows = 4) { /** * ``` * ⎡ m00 m01 ⎤ * ⎢ m10 m11 ⎥ * ⎢ m20 m21 ⎥ * ⎣ m30 m31 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m10: Double, m11: Double, m20: Double, m21: Double, m30: Double, m31: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01 this[index, 1, 0] = m10; this[index, 1, 1] = m11 this[index, 2, 0] = m20; this[index, 2, 1] = m21 this[index, 3, 0] = m30; this[index, 3, 1] = m31 } override fun push() { GL40.glUniformMatrix2x4dv(location, true, values) } } public class DoubleMat3x2Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT3x2, columns = 3, rows = 2) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎣ m10 m11 m12 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02; this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12; } override fun push() { GL40.glUniformMatrix3x2dv(location, true, values) } } public class DoubleMat3x2ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT3x2, length, columns = 3, rows = 2) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎣ m30 m31 m32 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12 } override fun push() { GL40.glUniformMatrix3x2dv(location, true, values) } } public class DoubleMat3x4Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT3x4, columns = 3, rows = 4) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎢ m20 m21 m22 ⎥ * ⎣ m30 m31 m32 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, m20: Double, m21: Double, m22: Double, m30: Double, m31: Double, m32: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12 this[2, 0] = m20; this[2, 1] = m21; this[2, 2] = m22 this[3, 0] = m30; this[3, 1] = m31; this[3, 2] = m32 } override fun push() { GL40.glUniformMatrix3x4dv(location, true, values) } } public class DoubleMat3x4ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT3x4, length, columns = 3, rows = 4) { /** * ``` * ⎡ m00 m01 m02 ⎤ * ⎢ m10 m11 m12 ⎥ * ⎢ m20 m21 m22 ⎥ * ⎣ m30 m31 m32 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m10: Double, m11: Double, m12: Double, m20: Double, m21: Double, m22: Double, m30: Double, m31: Double, m32: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12 this[index, 2, 0] = m20; this[index, 2, 1] = m21; this[index, 2, 2] = m22 this[index, 3, 0] = m30; this[index, 3, 1] = m31; this[index, 3, 2] = m32 } override fun push() { GL40.glUniformMatrix3x4dv(location, true, values) } } public class DoubleMat4x2Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT4x2, columns = 4, rows = 2) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎣ m10 m11 m12 m13 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02; this[0, 3] = m03 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12; this[1, 3] = m13 } override fun push() { GL40.glUniformMatrix4x2dv(location, true, values) } } public class DoubleMat4x2ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT4x2, length, columns = 4, rows = 2) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎣ m10 m11 m12 m13 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02; this[index, 0, 3] = m03 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12; this[index, 1, 3] = m13 } override fun push() { GL40.glUniformMatrix4x2dv(location, true, values) } } public class DoubleMat4x3Uniform(name: String) : DoubleMatrixUniform(name, GL40.GL_FLOAT_MAT4x3, columns = 4, rows = 3) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎢ m10 m11 m12 m13 ⎥ * ⎣ m20 m21 m22 m23 ⎦ * ``` */ public fun set( m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, m20: Double, m21: Double, m22: Double, m23: Double, ) { this[0, 0] = m00; this[0, 1] = m01; this[0, 2] = m02; this[0, 3] = m03 this[1, 0] = m10; this[1, 1] = m11; this[1, 2] = m12; this[1, 3] = m13 this[2, 0] = m20; this[2, 1] = m21; this[2, 2] = m22; this[2, 3] = m23 } override fun push() { GL40.glUniformMatrix4x3dv(location, true, values) } } public class DoubleMat4x3ArrayUniform(name: String, length: Int) : DoubleMatrixArrayUniform(name, GL40.GL_FLOAT_MAT4x3, length, columns = 4, rows = 3) { /** * ``` * ⎡ m00 m01 m02 m03 ⎤ * ⎢ m10 m11 m12 m13 ⎥ * ⎣ m20 m21 m22 m23 ⎦ * ``` */ public fun set( index: Int, m00: Double, m01: Double, m02: Double, m03: Double, m10: Double, m11: Double, m12: Double, m13: Double, m20: Double, m21: Double, m22: Double, m23: Double, ) { this[index, 0, 0] = m00; this[index, 0, 1] = m01; this[index, 0, 2] = m02; this[index, 0, 3] = m03 this[index, 1, 0] = m10; this[index, 1, 1] = m11; this[index, 1, 2] = m12; this[index, 1, 3] = m13 this[index, 2, 0] = m20; this[index, 2, 1] = m21; this[index, 2, 2] = m22; this[index, 2, 3] = m23 } override fun push() { GL40.glUniformMatrix4x3dv(location, true, values) } }
lgpl-3.0
7625dd30b9ac529452a5b08796c8228c
31.215146
152
0.558423
2.800269
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/project/model/impl/UserDisabledFeaturesHolder.kt
3
3103
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.model.impl import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.util.io.systemIndependentPath import org.jdom.Element import org.rust.cargo.project.model.cargoProjects import org.rust.stdext.mapNotNullToSet import java.nio.file.Path import java.nio.file.Paths /** * A service needed to store [UserDisabledFeatures] separately from [CargoProjectsServiceImpl]. * Needed to make it possible to store them in different XML files ([Storage]s) */ @State(name = "CargoProjectFeatures", storages = [ Storage(StoragePathMacros.WORKSPACE_FILE, roamingType = RoamingType.DISABLED) ]) @Service class UserDisabledFeaturesHolder(private val project: Project) : PersistentStateComponent<Element> { private var loadedUserDisabledFeatures: Map<Path, UserDisabledFeatures> = emptyMap() fun takeLoadedUserDisabledFeatures(): Map<Path, UserDisabledFeatures> { val result = loadedUserDisabledFeatures loadedUserDisabledFeatures = emptyMap() return result } override fun getState(): Element { val state = Element("state") for (cargoProject in project.cargoProjects.allProjects) { val pkgToFeatures = cargoProject.userDisabledFeatures if (!pkgToFeatures.isEmpty()) { val cargoProjectElement = Element("cargoProject") cargoProjectElement.setAttribute("file", cargoProject.manifest.systemIndependentPath) for ((pkg, features) in pkgToFeatures.pkgRootToDisabledFeatures) { if (features.isNotEmpty()) { val packageElement = Element("package") packageElement.setAttribute("file", pkg.systemIndependentPath) for (feature in features) { val featureElement = Element("feature") featureElement.setAttribute("name", feature) packageElement.addContent(featureElement) } cargoProjectElement.addContent(packageElement) } } state.addContent(cargoProjectElement) } } return state } override fun loadState(state: Element) { val cargoProjects = state.getChildren("cargoProject") loadedUserDisabledFeatures = cargoProjects.associate { cargoProject -> val projectFile = cargoProject.getAttributeValue("file").orEmpty() val features = UserDisabledFeatures.of(cargoProject.getChildren("package").associate { pkg -> val packageFile = pkg.getAttributeValue("file").orEmpty() val features = pkg.getChildren("feature").mapNotNullToSet { it.getAttributeValue("name") } Paths.get(packageFile) to features }) Paths.get(projectFile) to features } } }
mit
ffe4970c2f5b8d912d95d7b3128a3f02
40.932432
105
0.646149
5.434326
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/window/AwtWindow.desktop.kt
3
4838
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.window import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.node.Ref import androidx.compose.ui.util.UpdateEffect import androidx.compose.ui.util.makeDisplayable import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.swing.Swing import java.awt.Window /** * Compose [Window] obtained from [create]. The [create] block will be called * exactly once to obtain the [Window] to be composed, and it is also guaranteed to be invoked on * the UI thread (Event Dispatch Thread). * * Once [AwtWindow] leaves the composition, [dispose] will be called to free resources that * obtained by the [Window]. * * The [update] block can be run multiple times (on the UI thread as well) due to recomposition, * and it is the right place to set [Window] properties depending on state. * When state changes, the block will be reexecuted to set the new properties. * Note the block will also be ran once right after the [create] block completes. * * [AwtWindow] is needed for creating window's / dialog's that still can't be created with * the default Compose functions [androidx.compose.ui.window.Window] or * [androidx.compose.ui.window.Dialog]. * * @param visible Is [Window] visible to user. * Note that if we set `false` - native resources will not be released. They will be released * only when [Window] will leave the composition. * @param create The block creating the [Window] to be composed. * @param dispose The block to dispose [Window] and free native resources. Usually it is simple * `Window::dispose` * @param update The callback to be invoked after the layout is inflated. */ @OptIn(DelicateCoroutinesApi::class) @Suppress("unused") @Composable fun <T : Window> AwtWindow( visible: Boolean = true, create: () -> T, dispose: (T) -> Unit, update: (T) -> Unit = {} ) { val currentVisible by rememberUpdatedState(visible) val windowRef = remember { Ref<T>() } fun window() = windowRef.value!! DisposableEffect(Unit) { windowRef.value = create() onDispose { dispose(window()) } } UpdateEffect { val window = window() update(window) if (!window.isDisplayable) { window.makeDisplayable() } } val showJob = Ref<Job?>() SideEffect { // Why we dispatch showing in the next AWT tick: // // 1. // window.isVisible = true can be a blocking operation. // So we have to schedule it when we will be outside of Compose render frame. // // This happens in the when we create a modal dialog. // When we call `window.isVisible = true`, internally will be created a new AWT event loop, // which will handle all the future Swing events while dialog is visible. // // We can't use LaunchedEffect or rememberCoroutineScope, because they have a dispatcher // which is controlled by the Compose rendering loop (ComposeScene.dispatcher) and we // will block coroutine. // // 2. // We achieve the correct order when we open nested // window at the same time when we open the parent window. If we would show the window // immediately we will have this sequence in case of nested Window's: // // 1. window1.setContent // 2. window2.setContent // 3. window2.isVisible = true // 4. window1.isVisible = true // // So we will have a wrong active window (window1). showJob.value?.cancel() showJob.value = GlobalScope.launch(Dispatchers.Swing) { window().isVisible = currentVisible } } DisposableEffect(Unit) { onDispose { showJob.value?.cancel() window().isVisible = false } } }
apache-2.0
a19e7b2580f608887cf61224de7c5610
35.938931
99
0.687888
4.382246
false
false
false
false
taigua/exercism
kotlin/pig-latin/src/main/kotlin/PigLatin.kt
1
651
/** * Created by Corwin on 2017/2/1. */ object PigLatin { private val rVowel = Regex("^([aeiou]|xr|yt)(.*)$") private val rConsonant = Regex("^([^aeiou]*qu|y|[^aeiou]+)(.*)$") fun translate(input: String) = input.trim().split(Regex("\\s+")).map { translateWord(it) }.joinToString(" ") private fun translateWord(input: String) : String { val mv = rVowel.matchEntire(input) val mc = rConsonant.matchEntire(input) return when { mv != null -> mv.groupValues[1] + mv.groupValues[2] + "ay" mc != null -> mc.groupValues[2] + mc.groupValues[1] + "ay" else -> "" } } }
mit
ac9d78a26a662a3bb5d4a06b54bafbab
33.315789
112
0.556068
3.304569
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/structure/ElmBreadcrumbsProvider.kt
1
2062
package org.elm.ide.structure import com.intellij.lang.Language import com.intellij.psi.PsiElement import com.intellij.ui.breadcrumbs.BreadcrumbsProvider import org.elm.lang.core.ElmLanguage import org.elm.lang.core.psi.ElmPsiElement import org.elm.lang.core.psi.elements.* class ElmBreadcrumbsProvider : BreadcrumbsProvider { override fun getLanguages(): Array<Language> = LANGUAGES override fun acceptElement(element: PsiElement): Boolean { return element is ElmPsiElement && breadcrumbName(element) != null } override fun getElementInfo(element: PsiElement): String { return breadcrumbName(element as ElmPsiElement)!! } companion object { private val LANGUAGES: Array<Language> = arrayOf(ElmLanguage) fun breadcrumbName(e: ElmPsiElement): String? { return when (e) { is ElmLetInExpr -> "let … in" is ElmIfElseExpr -> "if ${e.expressionList.firstOrNull()?.text.truncate()} then" is ElmTypeAliasDeclaration -> e.name is ElmTypeDeclaration -> e.name is ElmTypeAnnotation -> "${e.referenceName} :" is ElmValueDeclaration -> when (val assignee = e.assignee) { is ElmFunctionDeclarationLeft -> assignee.name else -> assignee?.text?.truncate() } is ElmAnonymousFunctionExpr -> e.patternList.joinToString(" ", prefix = "\\") { it.text }.truncate() + " ->" is ElmFieldType -> e.name is ElmUnionVariant -> e.name is ElmCaseOfExpr -> "case ${e.expression?.text.truncate()} of" is ElmCaseOfBranch -> "${e.pattern.text.truncate()} ->" is ElmRecordExpr -> e.baseRecordIdentifier?.let { "{${it.text} | …}" } else -> null } } private fun String?.truncate(len: Int = 20) = when { this == null -> "…" length > len -> take(len) + "…" else -> this } } }
mit
3a73bcf5ceff969702c16040998b2739
37.754717
124
0.591042
4.595078
false
false
false
false
darkpaw/boss_roobot
src/org/darkpaw/ld33/Audio.kt
1
755
package org.darkpaw.ld33 import jquery.jq import org.w3c.dom.HTMLElement import org.w3c.dom.HTMLAudioElement import java.util.* import kotlin.browser.window import org.w3c.xhr.XMLHttpRequest class Audio(val world : GameWorld) { val sounds = HashMap<String, HTMLAudioElement>() init { } fun loadSample(name : String, path: String): HTMLAudioElement { val sound = window.document.createElement("audio") as HTMLAudioElement sound.src = path sound.loop = false sounds.set(name, sound) return sound } fun play(name : String){ val sound = sounds.get(name) as HTMLAudioElement //sound.pause() //sound.play() println("audio is muted - ${name}") } }
agpl-3.0
c21e932ce5268f4d8c18be61c295d3c7
18.358974
78
0.647682
3.756219
false
false
false
false
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt
1
3284
package com.baeldung.kotlin import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse class StructuralJumpUnitTest { @Test fun givenLoop_whenBreak_thenComplete() { var value = "" for (i in "hello_world") { if (i == '_') break value += i.toString() } assertEquals("hello", value) } @Test fun givenLoop_whenBreakWithLabel_thenComplete() { var value = "" outer_loop@ for (i in 'a'..'d') { for (j in 1..3) { value += "" + i + j if (i == 'b' && j == 1) break@outer_loop } } assertEquals("a1a2a3b1", value) } @Test fun givenLoop_whenContinue_thenComplete() { var result = "" for (i in "hello_world") { if (i == '_') continue result += i } assertEquals("helloworld", result) } @Test fun givenLoop_whenContinueWithLabel_thenComplete() { var result = "" outer_loop@ for (i in 'a'..'c') { for (j in 1..3) { if (i == 'b') continue@outer_loop result += "" + i + j } } assertEquals("a1a2a3c1c2c3", result) } @Test fun givenLambda_whenReturn_thenComplete() { var result = returnInLambda(); assertEquals("hello", result) } private fun returnInLambda(): String { var result = "" "hello_world".forEach { // non-local return directly to the caller if (it == '_') return result result += it.toString() } //this line won't be reached return result; } @Test fun givenLambda_whenReturnWithExplicitLabel_thenComplete() { var result = "" "hello_world".forEach lit@{ if (it == '_') { // local return to the caller of the lambda, i.e. the forEach loop return@lit } result += it.toString() } assertEquals("helloworld", result) } @Test fun givenLambda_whenReturnWithImplicitLabel_thenComplete() { var result = "" "hello_world".forEach { if (it == '_') { // local return to the caller of the lambda, i.e. the forEach loop return@forEach } result += it.toString() } assertEquals("helloworld", result) } @Test fun givenAnonymousFunction_return_thenComplete() { var result = "" "hello_world".forEach(fun(element) { // local return to the caller of the anonymous fun, i.e. the forEach loop if (element == '_') return result += element.toString() }) assertEquals("helloworld", result) } @Test fun givenAnonymousFunction_returnToLabel_thenComplete() { var result = "" run loop@{ "hello_world".forEach { // non-local return from the lambda passed to run if (it == '_') return@loop result += it.toString() } } assertEquals("hello", result) } }
gpl-3.0
5ad9b23ee2f551787344256ddeb73fe8
26.140496
85
0.492692
4.461957
false
true
false
false
google-developer-training/basic-android-kotlin-compose-training-lunch-tray
app/src/main/java/com/example/lunchtray/ui/EntreeMenuScreen.kt
1
1616
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.lunchtray.datasource.DataSource import com.example.lunchtray.model.MenuItem import com.example.lunchtray.model.MenuItem.EntreeItem @Composable fun EntreeMenuScreen( options: List<EntreeItem>, onCancelButtonClicked: () -> Unit, onNextButtonClicked: () -> Unit, onSelectionChanged: (EntreeItem) -> Unit, modifier: Modifier = Modifier ) { BaseMenuScreen( options = options, onCancelButtonClicked = onCancelButtonClicked, onNextButtonClicked = onNextButtonClicked, onSelectionChanged = onSelectionChanged as (MenuItem) -> Unit ) } @Preview @Composable fun EntreeMenuPreview(){ EntreeMenuScreen( options = DataSource.entreeMenuItems, onCancelButtonClicked = {}, onNextButtonClicked = {}, onSelectionChanged = {} ) }
apache-2.0
54a265508e9a6b4e1f02568288dd2a2f
31.32
75
0.732673
4.367568
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/forge/creator/ForgeProjectCreator.kt
1
11580
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.creator import com.demonwav.mcdev.creator.BaseProjectCreator import com.demonwav.mcdev.creator.BasicJavaClassStep import com.demonwav.mcdev.creator.CreatorStep import com.demonwav.mcdev.creator.LicenseStep import com.demonwav.mcdev.creator.buildsystem.BuildSystem import com.demonwav.mcdev.creator.buildsystem.gradle.BasicGradleFinalizerStep import com.demonwav.mcdev.creator.buildsystem.gradle.GradleBuildSystem import com.demonwav.mcdev.creator.buildsystem.gradle.GradleFiles import com.demonwav.mcdev.creator.buildsystem.gradle.GradleGitignoreStep import com.demonwav.mcdev.creator.buildsystem.gradle.GradleWrapperStep import com.demonwav.mcdev.creator.buildsystem.gradle.SimpleGradleSetupStep import com.demonwav.mcdev.platform.forge.util.ForgeConstants import com.demonwav.mcdev.platform.forge.util.ForgePackAdditionalData import com.demonwav.mcdev.platform.forge.util.ForgePackDescriptor import com.demonwav.mcdev.util.MinecraftVersions import com.demonwav.mcdev.util.SemanticVersion import com.demonwav.mcdev.util.runGradleTaskAndWait import com.demonwav.mcdev.util.runWriteTask import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption.CREATE import java.nio.file.StandardOpenOption.TRUNCATE_EXISTING import java.nio.file.StandardOpenOption.WRITE import java.util.Locale class Fg2ProjectCreator( private val rootDirectory: Path, private val rootModule: Module, private val buildSystem: GradleBuildSystem, private val config: ForgeProjectConfig, private val mcVersion: SemanticVersion ) : BaseProjectCreator(rootModule, buildSystem) { private fun setupMainClassStep(): BasicJavaClassStep { return createJavaClassStep(config.mainClass) { packageName, className -> Fg2Template.applyMainClass(project, buildSystem, config, packageName, className) } } override fun getSteps(): Iterable<CreatorStep> { val buildText = Fg2Template.applyBuildGradle(project, buildSystem, mcVersion) val propText = Fg2Template.applyGradleProp(project, config) val settingsText = Fg2Template.applySettingsGradle(project, buildSystem.artifactId) val files = GradleFiles(buildText, propText, settingsText) return listOf( SimpleGradleSetupStep( project, rootDirectory, buildSystem, files ), setupMainClassStep(), GradleWrapperStep(project, rootDirectory, buildSystem), McmodInfoStep(project, buildSystem, config), SetupDecompWorkspaceStep(project, rootDirectory), GradleGitignoreStep(project, rootDirectory), BasicGradleFinalizerStep(rootModule, rootDirectory, buildSystem), ForgeRunConfigsStep(buildSystem, rootDirectory, config, CreatedModuleType.SINGLE) ) } companion object { val FG_WRAPPER_VERSION = SemanticVersion.release(4, 10, 3) } } open class Fg3ProjectCreator( protected val rootDirectory: Path, protected val rootModule: Module, protected val buildSystem: GradleBuildSystem, protected val config: ForgeProjectConfig ) : BaseProjectCreator(rootModule, buildSystem) { private fun setupMainClassStep(): BasicJavaClassStep { return createJavaClassStep(config.mainClass) { packageName, className -> if (config.mcVersion >= MinecraftVersions.MC1_19) { Fg3Template.apply1_19MainClass(project, buildSystem, config, packageName, className) } else if (config.mcVersion >= MinecraftVersions.MC1_18) { Fg3Template.apply1_18MainClass(project, buildSystem, config, packageName, className) } else if (config.mcVersion >= MinecraftVersions.MC1_17) { Fg3Template.apply1_17MainClass(project, buildSystem, config, packageName, className) } else { Fg3Template.applyMainClass(project, buildSystem, config, packageName, className) } } } protected fun transformModName(modName: String?): String { modName ?: return "examplemod" return modName.lowercase(Locale.ENGLISH).replace(" ", "") } protected fun createGradleFiles(hasData: Boolean): GradleFiles<String> { val modName = transformModName(config.pluginName) val buildText = Fg3Template.applyBuildGradle(project, buildSystem, config, modName, hasData) val propText = Fg3Template.applyGradleProp(project) val settingsText = Fg3Template.applySettingsGradle(project, buildSystem.artifactId) return GradleFiles(buildText, propText, settingsText) } override fun getSteps(): Iterable<CreatorStep> { val files = createGradleFiles(hasData = true) val steps = mutableListOf( SimpleGradleSetupStep( project, rootDirectory, buildSystem, files ), setupMainClassStep(), GradleWrapperStep(project, rootDirectory, buildSystem), Fg3ProjectFilesStep(project, buildSystem, config), Fg3CompileJavaStep(project, rootDirectory), GradleGitignoreStep(project, rootDirectory), LicenseStep(project, rootDirectory, config.license, config.authors.joinToString(", ")), BasicGradleFinalizerStep(rootModule, rootDirectory, buildSystem), ForgeRunConfigsStep(buildSystem, rootDirectory, config, CreatedModuleType.SINGLE) ) if (config.mixins) { steps += MixinConfigStep(project, buildSystem) } return steps } companion object { val FG5_WRAPPER_VERSION = SemanticVersion.release(7, 4, 2) } } class Fg3Mc112ProjectCreator( rootDirectory: Path, rootModule: Module, buildSystem: GradleBuildSystem, config: ForgeProjectConfig ) : Fg3ProjectCreator(rootDirectory, rootModule, buildSystem, config) { private fun setupMainClassStep(): BasicJavaClassStep { return createJavaClassStep(config.mainClass) { packageName, className -> Fg2Template.applyMainClass(project, buildSystem, config, packageName, className) } } override fun getSteps(): Iterable<CreatorStep> { val files = createGradleFiles(hasData = false) return listOf( SimpleGradleSetupStep( project, rootDirectory, buildSystem, files ), setupMainClassStep(), GradleWrapperStep(project, rootDirectory, buildSystem), McmodInfoStep(project, buildSystem, config), Fg3CompileJavaStep(project, rootDirectory), GradleGitignoreStep(project, rootDirectory), BasicGradleFinalizerStep(rootModule, rootDirectory, buildSystem), ForgeRunConfigsStep(buildSystem, rootDirectory, config, CreatedModuleType.SINGLE) ) } } class SetupDecompWorkspaceStep( private val project: Project, private val rootDirectory: Path ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { indicator.text = "Setting up project" indicator.text2 = "Running Gradle task: 'setupDecompWorkspace'" runGradleTaskAndWait(project, rootDirectory) { settings -> settings.taskNames = listOf("setupDecompWorkspace") settings.vmOptions = "-Xmx2G" } indicator.text2 = null } } class McmodInfoStep( private val project: Project, private val buildSystem: BuildSystem, private val config: ForgeProjectConfig ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { val text = Fg2Template.applyMcmodInfo(project, buildSystem, config) val dir = buildSystem.dirsOrError.resourceDirectory runWriteTask { CreatorStep.writeTextToFile(project, dir, ForgeConstants.MCMOD_INFO, text) } } } class Fg3ProjectFilesStep( private val project: Project, private val buildSystem: BuildSystem, private val config: ForgeProjectConfig ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { val modsTomlText = Fg3Template.applyModsToml(project, buildSystem, config) val packDescriptor = ForgePackDescriptor.forMcVersion(config.mcVersion) ?: ForgePackDescriptor.FORMAT_3 val additionalData = ForgePackAdditionalData.forMcVersion(config.mcVersion) val packMcmetaText = Fg3Template.applyPackMcmeta(project, buildSystem.artifactId, packDescriptor, additionalData) val dir = buildSystem.dirsOrError.resourceDirectory runWriteTask { CreatorStep.writeTextToFile(project, dir, ForgeConstants.PACK_MCMETA, packMcmetaText) val meta = dir.resolve("META-INF") Files.createDirectories(meta) CreatorStep.writeTextToFile(project, meta, ForgeConstants.MODS_TOML, modsTomlText) } } } class Fg3CompileJavaStep( private val project: Project, private val rootDirectory: Path ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { indicator.text = "Setting up classpath" indicator.text2 = "Running Gradle task: 'compileJava'" runGradleTaskAndWait(project, rootDirectory) { settings -> settings.taskNames = listOf("compileJava") } indicator.text2 = null } } class MixinConfigStep( private val project: Project, private val buildSystem: BuildSystem ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { val text = Fg3Template.applyMixinConfigTemplate(project, buildSystem) val dir = buildSystem.dirsOrError.resourceDirectory runWriteTask { CreatorStep.writeTextToFile(project, dir, "${buildSystem.artifactId}.mixins.json", text) } } } enum class CreatedModuleType { SINGLE, MULTI } class ForgeRunConfigsStep( private val buildSystem: BuildSystem, private val rootDirectory: Path, private val config: ForgeProjectConfig, private val createdModuleType: CreatedModuleType ) : CreatorStep { override fun runStep(indicator: ProgressIndicator) { val gradleDir = rootDirectory.resolve(".gradle") Files.createDirectories(gradleDir) val hello = gradleDir.resolve(HELLO) val task = if (createdModuleType == CreatedModuleType.MULTI) { ":${buildSystem.artifactId}:genIntellijRuns" } else { "genIntellijRuns" } // We don't use `rootModule.name` here because Gradle will change the name of the module to match // what was set as the artifactId once it imports the project val moduleName = if (createdModuleType == CreatedModuleType.MULTI) { "${buildSystem.parentOrError.artifactId}.${buildSystem.artifactId}" } else { buildSystem.artifactId } val fileContents = moduleName + "\n" + config.mcVersion + "\n" + config.forgeVersion + "\n" + task Files.write(hello, fileContents.toByteArray(Charsets.UTF_8), CREATE, TRUNCATE_EXISTING, WRITE) } companion object { const val HELLO = ".hello_from_mcdev" } }
mit
275311dc3bf0a01e7d1f92cd21d03ca9
37.092105
111
0.697409
4.769357
false
true
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/net/social/ActorEndpoints.kt
1
5864
/* * Copyright (C) 2018 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.net.social import android.content.ContentValues import android.database.Cursor import android.net.Uri import org.andstatus.app.context.MyContext import org.andstatus.app.data.DbUtils import org.andstatus.app.data.MyProvider import org.andstatus.app.data.MyQuery import org.andstatus.app.database.table.ActorEndpointTable import org.andstatus.app.os.AsyncUtil import org.andstatus.app.util.UriUtils import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import java.util.function.Function class ActorEndpoints private constructor(private val myContext: MyContext, private val actorId: Long) { enum class State { EMPTY, ADDING, LAZYLOAD, LOADED } private val initialized: AtomicBoolean = AtomicBoolean() private val state: AtomicReference<State> = AtomicReference(if (actorId == 0L) State.EMPTY else State.LAZYLOAD) @Volatile private var map: Map<ActorEndpointType, List<Uri>> = emptyMap() fun add(type: ActorEndpointType, value: String?): ActorEndpoints { return add(type, UriUtils.fromString(value)) } fun add(type: ActorEndpointType, uri: Uri): ActorEndpoints { if (initialize().state.get() == State.ADDING) { map = add(map.toMutableMap(), type, uri) } return this } fun findFirst(type: ActorEndpointType?): Optional<Uri> { return if (type == ActorEndpointType.EMPTY) Optional.empty() else initialize().map.getOrDefault(type, emptyList()).stream().findFirst() } fun initialize(): ActorEndpoints { while (state.get() == State.EMPTY) { if (initialized.compareAndSet(false, true)) { map = ConcurrentHashMap() state.set(State.ADDING) } } while (state.get() == State.LAZYLOAD && myContext.isReady && AsyncUtil.nonUiThread) { if (initialized.compareAndSet(false, true)) { return load() } } return this } override fun toString(): String { return map.toString() } private fun load(): ActorEndpoints { val map: MutableMap<ActorEndpointType, List<Uri>> = ConcurrentHashMap() val sql = "SELECT " + ActorEndpointTable.ENDPOINT_TYPE + "," + ActorEndpointTable.ENDPOINT_INDEX + "," + ActorEndpointTable.ENDPOINT_URI + " FROM " + ActorEndpointTable.TABLE_NAME + " WHERE " + ActorEndpointTable.ACTOR_ID + "=" + actorId + " ORDER BY " + ActorEndpointTable.ENDPOINT_TYPE + "," + ActorEndpointTable.ENDPOINT_INDEX MyQuery.foldLeft(myContext, sql, map, { m: MutableMap<ActorEndpointType, List<Uri>> -> Function { cursor: Cursor -> add(m, ActorEndpointType.fromId(DbUtils.getLong(cursor, ActorEndpointTable.ENDPOINT_TYPE)), UriUtils.fromString(DbUtils.getString(cursor, ActorEndpointTable.ENDPOINT_URI))) } }) this.map = map state.set(State.LOADED) return this } fun save(actorId: Long) { if (actorId == 0L || !state.compareAndSet(State.ADDING, State.LOADED)) return val old = from(myContext, actorId).initialize() if (this == old) return MyProvider.delete(myContext, ActorEndpointTable.TABLE_NAME, ActorEndpointTable.ACTOR_ID, actorId) map.forEach { (key: ActorEndpointType, list: List<Uri>) -> for ((index, uri) in list.withIndex()) { val contentValues = ContentValues() contentValues.put(ActorEndpointTable.ACTOR_ID, actorId) contentValues.put(ActorEndpointTable.ENDPOINT_TYPE, key.id) contentValues.put(ActorEndpointTable.ENDPOINT_INDEX, index) contentValues.put(ActorEndpointTable.ENDPOINT_URI, uri.toString()) MyProvider.insert(myContext, ActorEndpointTable.TABLE_NAME, contentValues) } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val endpoints = other as ActorEndpoints return map == endpoints.map } override fun hashCode(): Int { return Objects.hash(map) } companion object { fun from(myContext: MyContext, actorId: Long): ActorEndpoints { return ActorEndpoints(myContext, actorId) } private fun add(map: MutableMap<ActorEndpointType, List<Uri>>, type: ActorEndpointType, uri: Uri): MutableMap<ActorEndpointType, List<Uri>> { if (UriUtils.isEmpty(uri) || type == ActorEndpointType.EMPTY) return map val urisOld = map[type] if (urisOld == null) { map[type] = listOf(uri) } else { val uris: MutableList<Uri> = ArrayList(urisOld) if (!uris.contains(uri)) { uris.add(uri) map[type] = uris } } return map } } }
apache-2.0
ffd6dbbaead71d251a55b88449361121
38.355705
115
0.633527
4.472921
false
false
false
false
ajordens/lalas
jvm/sleepybaby-api-core/src/main/kotlin/org/jordens/sleepybaby/Model.kt
2
2254
/* * Copyright 2017 Adam Jordens * * 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.jordens.sleepybaby data class Feeding(val date: String, val time: String, val nursingDurationMinutes: Int, val milkType: String, val milkVolumeMilliliters: Int, val bodyTemperature: Double?, val diaperTypes: Collection<String>, val notes: String, val milkVolumeAverageMilliliters: Int? = null) // this is a hack data class FeedingSummaryByDay(val date: String, val numberOfFeedings: Int, val milkVolumeTotalMilliliters: Int, val diaperCount: Int, val nursingDurationMinutes: Int) { val milkVolumeAverageMilliliters = Math.round(milkVolumeTotalMilliliters / numberOfFeedings.toFloat()) // ounces are rounded to one decimal val milkVolumeAverageOunces = Math.round(milkVolumeAverageMilliliters / 29.5735 * 10) / 10.0 val milkVolumeTotalOunces = Math.round(milkVolumeTotalMilliliters / 29.5735 * 10) / 10.0 } data class FeedingSummaryByTime(val feeding: Int, val feedings: MutableList<Feeding>, val summaries: MutableMap<String, Summary>, var current: Boolean = false) data class Summary(val milkVolumeAverageMilliliters: Int, val timesOfDay: Collection<String>) data class Diaper(val date: String, val time: String, val diaperType: String) data class DiaperSummaryByDay(val date: String, val diaperCount: Int)
apache-2.0
c3c767ba0b838e11005b4e5727f32fad
40.740741
104
0.631322
4.342967
false
false
false
false
esofthead/mycollab
mycollab-config/src/main/java/com/mycollab/configuration/EnDecryptHelper.kt
3
3017
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.configuration import com.mycollab.core.MyCollabException import org.jasypt.exceptions.EncryptionOperationNotPossibleException import org.jasypt.util.password.StrongPasswordEncryptor import org.jasypt.util.text.BasicTextEncryptor import java.io.UnsupportedEncodingException import java.net.URLDecoder import java.net.URLEncoder /** * Utility class to make encrypt and decrypt text * * @author MyCollab Ltd. * @since 1.0 */ object EnDecryptHelper { private val strongEncryptor = StrongPasswordEncryptor() private var basicTextEncryptor = BasicTextEncryptor() init { basicTextEncryptor.setPassword(SiteConfiguration.getEnDecryptPassword()) } /** * Encrypt password * * @param password * @return */ @JvmStatic fun encryptSaltPassword(password: String): String = strongEncryptor.encryptPassword(password) @JvmStatic fun encryptText(text: String): String = basicTextEncryptor.encrypt(text) @JvmStatic fun encryptTextWithEncodeFriendly(text: String): String = try { URLEncoder.encode(basicTextEncryptor.encrypt(text), "ASCII") } catch (e: UnsupportedEncodingException) { throw MyCollabException(e) } @JvmStatic fun decryptText(text: String): String = try { basicTextEncryptor.decrypt(text) } catch (e: EncryptionOperationNotPossibleException) { throw MyCollabException("Can not decrypt the text--$text---") } @JvmStatic fun decryptTextWithEncodeFriendly(text: String): String = try { basicTextEncryptor.decrypt(URLDecoder.decode(text, "ASCII")) } catch (e: Exception) { throw MyCollabException("Can not decrypt the text--$text---", e) } /** * Check password `inputPassword` match with * `expectedPassword` in case `inputPassword` encrypt * or not * * @param inputPassword * @param expectedPassword * @param isPasswordEncrypt flag to denote `inputPassword` is encrypted or not * @return */ @JvmStatic fun checkPassword(inputPassword: String, expectedPassword: String, isPasswordEncrypt: Boolean): Boolean = when { isPasswordEncrypt -> inputPassword == expectedPassword else -> strongEncryptor.checkPassword(inputPassword, expectedPassword) } }
agpl-3.0
ff0d817a34ac7623592e274d6fc96214
32.511111
116
0.719164
4.535338
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/madara/darkyurealm/src/DarkYueRealm.kt
1
1980
package eu.kanade.tachiyomi.extension.pt.darkyurealm import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.multisrc.madara.Madara import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.SManga import okhttp3.OkHttpClient import okhttp3.Request import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit class DarkYueRealm : Madara( "DarkYue Realm", "https://darkyuerealm.site/web", "pt-BR", SimpleDateFormat("dd 'de' MMMMM, yyyy", Locale("pt", "BR")) ) { // Override the id because the name was wrong. override val id: Long = 593455310609863709 override val client: OkHttpClient = super.client.newBuilder() .addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS)) .build() override fun mangaDetailsRequest(manga: SManga): Request { return GET(baseUrl + manga.url.removePrefix("/web"), headers) } override fun chapterListRequest(manga: SManga): Request { return GET(baseUrl + manga.url.removePrefix("/web"), headers) } // [...document.querySelectorAll('input[name="genre[]"]')] // .map(x => `Genre("${document.querySelector('label[for=' + x.id + ']').innerHTML.trim()}", "${x.value}")`) // .join(',\n') override fun getGenreList(): List<Genre> = listOf( Genre("Ação", "acao"), Genre("Aventura", "aventura"), Genre("Comédia", "comedia"), Genre("Drama", "drama"), Genre("Ecchi", "ecchi"), Genre("Escolar", "escolar"), Genre("Fantasia", "fantasia"), Genre("Harém", "harem"), Genre("Isekai", "isekai"), Genre("Romance", "romance"), Genre("School Life", "school-life"), Genre("Seinen", "seinen"), Genre("Shounen", "shounen"), Genre("Slice of Life", "slice-of-life"), Genre("Sobrenatural", "sobrenatural"), Genre("Vida Escolar", "vida-escolar") ) }
apache-2.0
7913556fcf4bf64fa1926e619f826e3a
34.285714
114
0.6417
3.742424
false
false
false
false
mitallast/netty-queue
src/main/java/org/mitallast/queue/transport/TransportController.kt
1
1193
package org.mitallast.queue.transport import com.google.inject.Inject import io.vavr.collection.HashMap import io.vavr.collection.Map import org.mitallast.queue.common.codec.Message import org.mitallast.queue.common.logging.LoggingService @Suppress("UNCHECKED_CAST") class TransportController @Inject constructor(logging: LoggingService) { private val logger = logging.logger() @Volatile private var handlerMap: Map<Class<*>, (Message) -> Unit> = HashMap.empty() @Synchronized fun <T : Message> registerMessageHandler( requestClass: Class<T>, handler: (T) -> Unit ) { handlerMap = handlerMap.put(requestClass, handler as ((Message) -> Unit)) } @Synchronized fun <T : Message> registerMessagesHandler( requestClass: Class<T>, handler: (Message) -> Unit ) { handlerMap = handlerMap.put(requestClass, handler) } fun <T : Message> dispatch(message: T) { val handler = handlerMap.getOrElse(message.javaClass, null) if (handler != null) { handler.invoke(message) } else { logger.error("handler not found for {}", message.javaClass) } } }
mit
248e8b2517bd28277fe642e17a34b34f
29.589744
81
0.66052
4.128028
false
false
false
false
luanalbineli/popularmovies
app/src/main/java/com/themovielist/home/HomeFragment.kt
1
5023
package com.themovielist.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.themovielist.R import com.themovielist.base.BaseFragment import com.themovielist.base.BasePresenter import com.themovielist.enums.RequestStatusDescriptor import com.themovielist.event.FavoriteMovieEvent import com.themovielist.home.fulllist.HomeFullMovieListActivity import com.themovielist.home.partiallist.HomeMovieListFragment import com.themovielist.injector.components.ApplicationComponent import com.themovielist.injector.components.DaggerFragmentComponent import com.themovielist.model.MovieModel import com.themovielist.model.view.HomeViewModel import com.themovielist.util.setDisplay import kotlinx.android.synthetic.main.home_fragment.* import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import timber.log.Timber import javax.inject.Inject class HomeFragment : BaseFragment<HomeContract.View>(), HomeContract.View { override val presenterImplementation: BasePresenter<HomeContract.View> get() = mPresenter override val viewImplementation: HomeContract.View get() = this @Inject lateinit var mPresenter: HomePresenter private lateinit var mPopularMovieListFragment: HomeMovieListFragment private lateinit var mTopRatedMovieListFragment: HomeMovieListFragment override fun onInjectDependencies(applicationComponent: ApplicationComponent) { DaggerFragmentComponent.builder() .applicationComponent(applicationComponent) .build() .inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) EventBus.getDefault().register(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.home_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity.setTitle(R.string.home) mPopularMovieListFragment = addFragmentIfNotExists(childFragmentManager, R.id.flHomePopularMovieContainer, POPULAR_MOVIE_LIST_TAG) { HomeMovieListFragment.getInstance() } mTopRatedMovieListFragment = addFragmentIfNotExists(childFragmentManager, R.id.flHomeTopRatedMovieContainer, RATING_MOVIE_LIST_TAG) { HomeMovieListFragment.getInstance() } rsvHomeMovieRequestStatus.setTryAgainClickListener { mPresenter.tryToLoadMoviesAgain() } tvHomeSeeMovieCast.setOnClickListener { mPresenter.seeAllPopularMovieList() } tvHomeSeeMovieListByRating.setOnClickListener { mPresenter.sellAllRatingMovieList() } val homeViewModel = savedInstanceState?.getParcelable(HOME_VIEW_MODEL_BUNDLE_KEY) ?: HomeViewModel() mPresenter.start(homeViewModel) } override fun showTopRatedMovies(topRatedList: List<MovieModel>) { mTopRatedMovieListFragment.addMovies(topRatedList) } override fun showErrorLoadingMovies(error: Throwable) { Timber.i(error, "An error occurred while tried to fecth the movies from HOME") rsvHomeMovieRequestStatus.setRequestStatus(RequestStatusDescriptor.ERROR, true) } override fun showLoadingIndicator() { rsvHomeMovieRequestStatus.setRequestStatus(RequestStatusDescriptor.LOADING, true) } override fun hideLoadingIndicatorAndShowMovies() { rsvHomeMovieRequestStatus.setRequestStatus(RequestStatusDescriptor.HIDDEN) rsvHomeMovieRequestStatus.setDisplay(false) flHomeMovieContainer.setDisplay(true) } override fun showPopularMovies(popularList: List<MovieModel>) { mPopularMovieListFragment.addMovies(popularList) } override fun seeAllMoviesSortedBy(homeMovieSort: Int) { val intent = HomeFullMovieListActivity.getIntent(activity, homeMovieSort) startActivity(intent) } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.putParcelable(HOME_VIEW_MODEL_BUNDLE_KEY, mPresenter.viewModel) } override fun onStop() { super.onStop() mPresenter.onStop() EventBus.getDefault().unregister(this) } @Subscribe(threadMode = ThreadMode.MAIN) fun onFavoriteMovieEvent(favoriteMovieEvent: FavoriteMovieEvent) { mPresenter.onFavoriteMovieEvent(favoriteMovieEvent.movie, favoriteMovieEvent.favorite) } companion object { private const val POPULAR_MOVIE_LIST_TAG = "popular_movie_list_fragment" private const val RATING_MOVIE_LIST_TAG = "rating_movie_list_fragment" private const val HOME_VIEW_MODEL_BUNDLE_KEY = "home_view_model_bundle_key" fun getInstance(): HomeFragment { return HomeFragment() } } }
apache-2.0
ff979c498b33e5072d0ff33d4092e480
37.343511
141
0.75652
4.968348
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/cache/user/structure/DbStructureUser.kt
2
1986
package org.stepik.android.cache.user.structure import androidx.sqlite.db.SupportSQLiteDatabase object DbStructureUser { const val TABLE_NAME = "users" object Columns { const val ID = "id" const val PROFILE = "profile" const val FIRST_NAME = "first_name" const val LAST_NAME = "last_name" const val FULL_NAME = "full_name" const val SHORT_BIO = "short_bio" const val DETAILS = "details" const val AVATAR = "avatar" const val COVER = "cover" const val IS_PRIVATE = "is_private" const val IS_GUEST = "is_guest" const val IS_ORGANIZATION = "is_organization" const val SOCIAL_PROFILES = "social_profiles" const val KNOWLEDGE = "knowledge" const val KNOWLEDGE_RANK = "knowledge_rank" const val REPUTATION = "reputation" const val REPUTATION_RANK = "reputation_rank" const val CREATED_COURSES_COUNT = "created_courses_count" const val FOLLOWERS_COUNT = "followers_count" const val ISSUED_CERTIFICATES_COUNT = "issued_certificates_count" const val JOIN_DATE = "join_date" } fun createTable(db: SupportSQLiteDatabase) { db.execSQL(""" CREATE TABLE IF NOT EXISTS $TABLE_NAME ( ${DbStructureUser.Columns.ID} LONG PRIMARY KEY, ${DbStructureUser.Columns.PROFILE} LONG, ${DbStructureUser.Columns.FIRST_NAME} TEXT, ${DbStructureUser.Columns.LAST_NAME} TEXT, ${DbStructureUser.Columns.FULL_NAME} TEXT, ${DbStructureUser.Columns.SHORT_BIO} TEXT, ${DbStructureUser.Columns.DETAILS} TEXT, ${DbStructureUser.Columns.AVATAR} TEXT, ${DbStructureUser.Columns.IS_PRIVATE} INTEGER, ${DbStructureUser.Columns.IS_ORGANIZATION} INTEGER, ${DbStructureUser.Columns.JOIN_DATE} LONG ) """.trimIndent()) } }
apache-2.0
5b2e3418fbc4e0ff8c6b9270bca7bf33
37.211538
73
0.609768
4.317391
false
false
false
false
spkingr/50-android-kotlin-projects-in-100-days
ProjectSimpleViewGroup/app/src/main/java/me/liuqingwen/android/projectsimpleviewgroup/SimpleViewGroup.kt
1
16251
package me.liuqingwen.android.projectsimpleviewgroup import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context import android.graphics.Rect import android.os.Build import android.util.AttributeSet import android.view.* import android.widget.Scroller import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.error import org.jetbrains.anko.info import org.jetbrains.anko.px2dip import kotlin.math.absoluteValue import kotlin.math.roundToInt /** * Created by Qingwen on 2018-1-25, project: ProjectSimpleViewGroup. * * @Author: Qingwen * @DateTime: 2018-1-25 * @Package: me.liuqingwen.android.projectsimpleviewgroup in project: ProjectSimpleViewGroup * * Notice: If you are using this class or file, check it and do some modification. */ fun View.rect2dipString(rect: Rect) = "Rect[left:${px2dip(rect.left)}, top:${px2dip(rect.top)}, right:${px2dip(rect.right)}, bottom:${px2dip(rect.bottom)} ]" class SimpleViewGroup:ViewGroup, AnkoLogger { constructor(context: Context):super(context) constructor(context: Context, attrs:AttributeSet):this(context, attrs, 0) constructor(context: Context, attrs:AttributeSet, defStyleAttr:Int):super(context, attrs, defStyleAttr) { this.setUp(attrs, defStyleAttr, 0) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs:AttributeSet, defStyleAttr:Int, defStyleRes:Int):super(context, attrs, defStyleAttr, defStyleRes) { this.setUp(attrs, defStyleAttr, defStyleRes) } private var pointerX = 0.0f private var pageCount = 0 private var pageSize = 0 private var pageHeight = 0 //For constrains in Y, if not set the y of the children(big size) will not be correctly positioned private val childRect by lazy(LazyThreadSafetyMode.NONE) { Rect() } private val containerRect by lazy(LazyThreadSafetyMode.NONE) { Rect() } private val scroller by lazy(LazyThreadSafetyMode.NONE) { Scroller(this.context)} private fun setUp(attrs:AttributeSet, defStyleAttr:Int, defStyleRes:Int) { /*val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SimpleViewGroup, defStyleAttr, defStyleRes) typedArray.recycle()*/ } override fun performClick(): Boolean { super.performClick() return true } override fun performLongClick(): Boolean { super.performLongClick() return true } override fun computeScroll() { super.computeScroll() if (this.scroller.computeScrollOffset()) { this.scrollTo(this.scroller.currX, 0) postInvalidate() } } private var interceptEventY = 0.0f private var interceptEventX = 0.0f override fun onInterceptTouchEvent(event: MotionEvent?): Boolean { if (event?.action == MotionEvent.ACTION_DOWN && event.edgeFlags != 0) { return false } //------------------------------------------------------------------------------------------ info("""--------------------------------------->onInterceptTouchEvent |Event: (x:${event?.x}, y:${event?.y}) |Type: (${event?.action}) """.trimMargin()) var isIntercepted = false when(event?.action) { MotionEvent.ACTION_DOWN -> { this.interceptEventX = event.x this.interceptEventY = event.y isIntercepted = ! this.scroller.isFinished } MotionEvent.ACTION_MOVE -> { if ((event.x - this.interceptEventX).absoluteValue >= ViewConfiguration.get(this.context).scaledTouchSlop.toFloat()) { isIntercepted = true //Important! Event loops: [InterceptEventDown->InterceptEventMove->TouchEventMove->TouchEventDown!!!] //So must update the x and y for touch event! //If here no updates, then you will jump when try to drag a button or other clickable ones to scroll! this.pointerX = event.x } } /*MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { error("----------------this only happens when event is intercepted--------------->onInterceptTouchEvent(Cancel? = ${event.action == MotionEvent.ACTION_CANCEL})") this.checkPerformClicks(event) } //event is intercepted!*/ else -> this.error("Not correctly handled yet!") } return isIntercepted } private fun checkPerformClicks(event: MotionEvent) { val touchSlop = ViewConfiguration.get(this.context).scaledTouchSlop.toFloat() val clickable = this.isClickable or this.isLongClickable if (event.action == MotionEvent.ACTION_UP && clickable && (event.x - this.interceptEventX).absoluteValue < touchSlop && (event.y - this.interceptEventY).absoluteValue < touchSlop) { if (this.isFocusable && this.isFocusableInTouchMode && ! this.isFocused) { this.requestFocus() } val longTouchSlop = ViewConfiguration.getLongPressTimeout() if (event.eventTime - event.downTime >= longTouchSlop && this.isLongClickable) { this.performLongClick() } else { this.performClick() } } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent?): Boolean { //------------------------------------------------------------------------------------------ info("""--------------------------------------->onTouchEvent |Event: (x:${event?.x}, y:${event?.y}) |Type: (${event?.action}) """.trimMargin()) when(event?.action) { MotionEvent.ACTION_DOWN -> { error("-----------------this only happens when no children consume event------------->onTouchEvent") this.pointerX = event.x if (! this.scroller.isFinished) { this.scroller.abortAnimation() } return true //True for accepting touch events } MotionEvent.ACTION_MOVE -> { this.scrollBy((this.pointerX - event.x).roundToInt(), 0) this.pointerX = event.x } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { val delta = this.pointerX - event.x + this.scrollX when { delta < 0 -> this.scroller.startScroll(this.scrollX, this.scrollY, - this.scrollX, 0) delta > (this.pageCount - 1) * this.pageSize -> this.scroller.startScroll(this.scrollX, this.scrollY, (this.pageCount - 1) * this.pageSize - this.scrollX, 0) else -> { val isNext = delta.roundToInt() % this.pageSize >= this.pageSize / 2 val pageNumber = delta.roundToInt() / this.pageSize + if (isNext) 1 else 0 this.scroller.startScroll(this.scrollX, this.scrollY, pageNumber * this.pageSize - this.scrollX, 0) } } this.invalidate() //------------------------------------------------------------------------------------------ info("""---------------------------------------> |Group: [Padding: ($paddingLeft, $paddingTop, $paddingRight, $paddingBottom)] |Page:[PageCount: $pageCount, PageSize: $pageSize] |Scroll:[ScrollXY: ($scrollX, $scrollY)] """.trimMargin()) this.checkPerformClicks(event) } else -> { this.error("Not correctly handled yet!") } } return super.onTouchEvent(event) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { //Max width and height is used only for AT_MOST(WRAP_CONTENT) layout parameters var maxWidth = 0 var maxHeight = 0 for(index in 0 until this.childCount) { val child = this.getChildAt(index) if (child.visibility == View.GONE) { continue } super.measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0) //Must add the margins to the child space rect val layoutParams = child.layoutParams as MarginLayoutParams val childWidth = child.measuredWidth + layoutParams.leftMargin + layoutParams.rightMargin val childHeight = child.measuredHeight + layoutParams.topMargin + layoutParams.bottomMargin if (childHeight > maxHeight) { maxHeight = childHeight } if (childWidth > maxWidth) { maxWidth = childWidth } //------------------------------------------------------------------------------------------ info("""--------------------------------------->onMeasure |Child[$index]: [Margin: (${px2dip(layoutParams.leftMargin)}, ${px2dip(layoutParams.topMargin)}, ${px2dip(layoutParams.rightMargin)}, ${px2dip(layoutParams.bottomMargin)})] |Child[$index]: [Padding: (${px2dip(child.paddingLeft)}, ${px2dip(child.paddingTop)}, ${px2dip(child.paddingRight)}, ${px2dip(child.paddingBottom)})] |Child[$index]: [Width&Height: (${px2dip(child.width)} = ${px2dip(child.measuredWidth)}, ${px2dip(child.height)} = ${px2dip(child.measuredHeight)})] |Child[$index]: [Position: (${rect2dipString(childRect)})] """.trimMargin()) } maxWidth += this.paddingLeft + this.paddingRight maxHeight += this.paddingTop + this.paddingBottom //Check the mode of the ViewGroup size measurement val widthMode = MeasureSpec.getMode(widthMeasureSpec) val heightMode = MeasureSpec.getMode(widthMeasureSpec) var widthMeasured = MeasureSpec.getSize(widthMeasureSpec) var heightMeasured = MeasureSpec.getSize(widthMeasureSpec) //------------------------------------------------------------------------------------------ info("""--------------------------------------->onMeasure Result-> |MaxWidth: ${px2dip(maxWidth)}, MaxHeight: ${px2dip(maxHeight)} |MeasuredWidth: ${px2dip(widthMeasured)}, MeasuredHeight: ${px2dip(heightMeasured)} |WidthMode=$widthMode, HeightMode=$heightMode """.trimMargin()) if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) { widthMeasured = maxOf(maxWidth, widthMeasured, super.getSuggestedMinimumWidth()) heightMeasured = maxOf(maxHeight, heightMeasured, super.getSuggestedMinimumHeight()) } else if (widthMode == MeasureSpec.AT_MOST) { widthMeasured = maxOf(maxWidth, widthMeasured, super.getSuggestedMinimumWidth()) } else if (heightMode == MeasureSpec.AT_MOST) { heightMeasured = maxOf(maxHeight, heightMeasured, super.getSuggestedMinimumHeight()) } //Here the widthMeasured is the max one and is the page size(width) this.pageSize = widthMeasured this.pageHeight = heightMeasured widthMeasured = View.resolveSizeAndState(widthMeasured, widthMeasureSpec, 0) heightMeasured = View.resolveSizeAndState(heightMeasured, heightMeasureSpec, 0) super.setMeasuredDimension(widthMeasured, heightMeasured) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { with(this.containerRect) { this.left = [email protected] this.top = [email protected] this.right = right - left - [email protected] this.bottom = bottom - top - [email protected] //------------------------------------------------------------------------------------------ info("--------------------------------------->Height:${px2dip(this.bottom)}-${px2dip(this.top)}=${px2dip(this.bottom - this.top)},Padding[$paddingLeft,$paddingTop,$paddingRight,$paddingBottom]") } this.pageCount = 0 for (index in 0 until this.childCount) { val child = this.getChildAt(index) if (child.visibility == View.GONE) { continue } val layoutParams = child.layoutParams as LayoutParams val gravity = layoutParams.gravity val childWidth = minOf(child.measuredWidth + layoutParams.leftMargin + layoutParams.rightMargin, this.pageSize) //Cannot overflow the page width! val childHeight = minOf(child.measuredHeight + layoutParams.topMargin + layoutParams.bottomMargin, this.pageHeight) Gravity.apply(gravity, childWidth, childHeight, this.containerRect, this.childRect) val l = this.childRect.left + layoutParams.leftMargin + this.pageCount * this.pageSize val t = this.childRect.top + layoutParams.topMargin val r = this.childRect.right - layoutParams.rightMargin + this.pageCount * this.pageSize val b = this.childRect.bottom - layoutParams.bottomMargin child.layout(l, t, r, b) //------------------------------------------------------------------------------------------ info("""--------------------------------------->OnLayout |Child[$index]: [Gravity: $gravity = ${gravity.toString(16)}] |Child[$index]: [Margin: (${px2dip(layoutParams.leftMargin)}, ${px2dip(layoutParams.topMargin)}, ${px2dip(layoutParams.rightMargin)}, ${px2dip(layoutParams.bottomMargin)})] |Child[$index]: [Padding: (${px2dip(child.paddingLeft)}, ${px2dip(child.paddingTop)}, ${px2dip(child.paddingRight)}, ${px2dip(child.paddingBottom)})] |Child[$index]: [Width: (${px2dip(child.width)} = ${px2dip(child.measuredWidth)}, ${px2dip(child.height)} = ${px2dip(child.measuredHeight)})] |Child[$index]: [Position: (${rect2dipString(childRect)})] """.trimMargin()) this.pageCount ++ } } //Add custom layout parameters for all children override fun generateDefaultLayoutParams() = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) override fun generateLayoutParams(attrs: AttributeSet?) = LayoutParams(this.context, attrs) override fun generateLayoutParams(p: ViewGroup.LayoutParams?) = LayoutParams(p) override fun checkLayoutParams(p: ViewGroup.LayoutParams?) = p is LayoutParams //The custom class name can be the same with ViewGroup.LayoutParams inner class LayoutParams:MarginLayoutParams { var gravity = -1 constructor(context: Context, attrs: AttributeSet?):super(context, attrs) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SimpleViewGroup_Layout) this.gravity = typedArray.getInt(R.styleable.SimpleViewGroup_Layout_android_layout_gravity, -1) typedArray.recycle() } constructor(width: Int, height: Int):super(width, height) constructor(source: MarginLayoutParams):super(source) constructor(source: ViewGroup.LayoutParams?):super(source) constructor(source: LayoutParams):super(source) { this.gravity = source.gravity } constructor(width: Int, height: Int, gravity: Int):super(width, height) { this.gravity = gravity } } }
mit
0a021fc338a22142e4d4623a227171bd
45.567335
206
0.569503
5.132975
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/widget/MaterialSpinnerView.kt
1
5831
package eu.kanade.tachiyomi.widget import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.LayoutInflater import android.view.MenuItem import android.widget.FrameLayout import androidx.annotation.ArrayRes import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.view.menu.MenuBuilder import androidx.appcompat.widget.PopupMenu import androidx.core.content.withStyledAttributes import androidx.core.view.forEach import androidx.core.view.get import androidx.core.view.size import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.core.preference.Preference import eu.kanade.tachiyomi.databinding.PrefSpinnerBinding import eu.kanade.tachiyomi.util.system.getResourceColor class MaterialSpinnerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) { private var entries = emptyList<String>() private var selectedPosition = 0 private var popup: PopupMenu? = null var onItemSelectedListener: ((Int) -> Unit)? = null set(value) { field = value if (value != null) { popup = makeSettingsPopup() setOnTouchListener(popup?.dragToOpenListener) setOnClickListener { popup?.show() } } } private val emptyIcon by lazy { AppCompatResources.getDrawable(context, R.drawable.ic_blank_24dp) } private val checkmarkIcon by lazy { AppCompatResources.getDrawable(context, R.drawable.ic_check_24dp)?.mutate()?.apply { setTint(context.getResourceColor(android.R.attr.textColorPrimary)) } } private val binding = PrefSpinnerBinding.inflate(LayoutInflater.from(context), this, false) init { addView(binding.root) context.withStyledAttributes(set = attrs, attrs = R.styleable.MaterialSpinnerView) { val title = getString(R.styleable.MaterialSpinnerView_title).orEmpty() binding.title.text = title val viewEntries = ( getTextArray(R.styleable.MaterialSpinnerView_android_entries) ?: emptyArray() ).map { it.toString() } entries = viewEntries binding.details.text = viewEntries.firstOrNull().orEmpty() } } fun setSelection(selection: Int) { if (selectedPosition < (popup?.menu?.size ?: 0)) { popup?.menu?.getItem(selectedPosition)?.let { it.icon = emptyIcon } } selectedPosition = selection popup?.menu?.getItem(selectedPosition)?.let { it.icon = checkmarkIcon } binding.details.text = entries.getOrNull(selection).orEmpty() } fun bindToPreference(pref: Preference<Int>, offset: Int = 0, block: ((Int) -> Unit)? = null) { setSelection(pref.get() - offset) popup = makeSettingsPopup(pref, offset, block) setOnTouchListener(popup?.dragToOpenListener) setOnClickListener { popup?.show() } } inline fun <reified T : Enum<T>> bindToPreference(pref: Preference<T>) { val enumConstants = T::class.java.enumConstants enumConstants?.indexOf(pref.get())?.let { setSelection(it) } val popup = makeSettingsPopup(pref) setOnTouchListener(popup.dragToOpenListener) setOnClickListener { popup.show() } } fun bindToIntPreference(pref: Preference<Int>, @ArrayRes intValuesResource: Int, block: ((Int) -> Unit)? = null) { val intValues = resources.getStringArray(intValuesResource).map { it.toIntOrNull() } setSelection(intValues.indexOf(pref.get())) popup = makeSettingsPopup(pref, intValues, block) setOnTouchListener(popup?.dragToOpenListener) setOnClickListener { popup?.show() } } inline fun <reified T : Enum<T>> makeSettingsPopup(preference: Preference<T>): PopupMenu { return createPopupMenu { pos -> onItemSelectedListener?.invoke(pos) val enumConstants = T::class.java.enumConstants enumConstants?.get(pos)?.let { enumValue -> preference.set(enumValue) } } } private fun makeSettingsPopup(preference: Preference<Int>, intValues: List<Int?>, block: ((Int) -> Unit)? = null): PopupMenu { return createPopupMenu { pos -> preference.set(intValues[pos] ?: 0) block?.invoke(pos) } } private fun makeSettingsPopup(preference: Preference<Int>, offset: Int = 0, block: ((Int) -> Unit)? = null): PopupMenu { return createPopupMenu { pos -> preference.set(pos + offset) block?.invoke(pos) } } private fun makeSettingsPopup(): PopupMenu { return createPopupMenu { pos -> onItemSelectedListener?.invoke(pos) } } private fun menuClicked(menuItem: MenuItem): Int { val pos = menuItem.itemId setSelection(pos) return pos } @SuppressLint("RestrictedApi") fun createPopupMenu(onItemClick: (Int) -> Unit): PopupMenu { val popup = PopupMenu(context, this, Gravity.END, R.attr.actionOverflowMenuStyle, 0) entries.forEachIndexed { index, entry -> popup.menu.add(0, index, 0, entry) } (popup.menu as? MenuBuilder)?.setOptionalIconsVisible(true) popup.menu.forEach { it.icon = emptyIcon } popup.menu[selectedPosition].icon = checkmarkIcon popup.setOnMenuItemClickListener { menuItem -> val pos = menuClicked(menuItem) onItemClick(pos) true } return popup } }
apache-2.0
392191f6195d180898670137b234b7a3
33.916168
130
0.639856
4.706215
false
false
false
false
square/wire
wire-library/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt
1
3715
/* * Copyright 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 com.squareup.wire import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types import com.squareup.wire.internal.EnumJsonFormatter import com.squareup.wire.internal.createRuntimeMessageAdapter import java.lang.reflect.Type /** * A [JsonAdapter.Factory] that allows Wire messages to be serialized and deserialized using the * Moshi Json library. * * ``` * Moshi moshi = new Moshi.Builder() * .add(new WireJsonAdapterFactory()) * .build(); * ``` * * The resulting [Moshi] instance will be able to serialize and deserialize Wire [Message] types, * including extensions. It ignores unknown field values. The JSON encoding is intended to be * compatible with the [protobuf-java-format](https://code.google.com/p/protobuf-java-format/) * library. * * In Proto3, if a field is set to its default (or identity) value, it will be omitted in the * JSON-encoded data. Set [writeIdentityValues] to true if you want Wire to always write values, * including default ones. */ class WireJsonAdapterFactory @JvmOverloads constructor( private val typeUrlToAdapter: Map<String, ProtoAdapter<*>> = mapOf(), private val writeIdentityValues: Boolean = false, ) : JsonAdapter.Factory { /** * Returns a new WireJsonAdapterFactory that can encode the messages for [adapters] if they're * used with [AnyMessage]. */ fun plus(adapters: List<ProtoAdapter<*>>): WireJsonAdapterFactory { val newMap = typeUrlToAdapter.toMutableMap() for (adapter in adapters) { val key = adapter.typeUrl ?: throw IllegalArgumentException( "recompile ${adapter.type} to use it with WireJsonAdapterFactory" ) newMap[key] = adapter } return WireJsonAdapterFactory(newMap, writeIdentityValues) } /** * Returns a new WireJsonAdapterFactory that can encode the messages for [adapter] if they're * used with [AnyMessage]. */ fun plus(adapter: ProtoAdapter<*>): WireJsonAdapterFactory { return plus(listOf(adapter)) } override fun create( type: Type, annotations: Set<Annotation>, moshi: Moshi ): JsonAdapter<*>? { val rawType = Types.getRawType(type) return when { annotations.isNotEmpty() -> null rawType == AnyMessage::class.java -> AnyMessageJsonAdapter(moshi, typeUrlToAdapter) Message::class.java.isAssignableFrom(rawType) -> { val messageAdapter = createRuntimeMessageAdapter<Nothing, Nothing>(type as Class<Nothing>, writeIdentityValues) val jsonAdapters = MoshiJsonIntegration.jsonAdapters(messageAdapter, moshi) val redactedFieldsAdapter = moshi.adapter<List<String>>( Types.newParameterizedType(List::class.java, String::class.java) ) MessageJsonAdapter(messageAdapter, jsonAdapters, redactedFieldsAdapter).nullSafe() } WireEnum::class.java.isAssignableFrom(rawType) -> { val enumAdapter = RuntimeEnumAdapter.create(type as Class<Nothing>) val enumJsonFormatter = EnumJsonFormatter(enumAdapter) EnumJsonAdapter(enumJsonFormatter).nullSafe() } else -> null } } }
apache-2.0
9e532ab1289c79a4b7161a738ecc8ca9
37.298969
119
0.722746
4.44378
false
false
false
false
PolymerLabs/arcs
java/arcs/core/crdt/CrdtSingleton.kt
1
7662
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.crdt import arcs.core.common.Referencable import arcs.core.common.ReferenceId import arcs.core.crdt.CrdtSet.Operation.Add import arcs.core.crdt.CrdtSet.Operation.Remove import arcs.core.crdt.CrdtSingleton.Data import arcs.core.data.util.ReferencablePrimitive /** A [CrdtModel] capable of managing a mutable reference. */ class CrdtSingleton<T : Referencable>( initialVersion: VersionMap = VersionMap(), initialData: T? = null, singletonToCopy: CrdtSingleton<T>? = null ) : CrdtModel<Data<T>, CrdtSingleton.IOperation<T>, T?> { override val versionMap: VersionMap get() = set._data.versionMap.copy() private var set: CrdtSet<T> override val data: Data<T> get() { val setData = set._data return DataImpl(setData.versionMap, setData.values) } override val consumerView: T? // Get any value, or null if no value is present. get() = set.consumerView.minByOrNull { it.id } init { CrdtException.require(initialData == null || singletonToCopy == null) { "Cannot instantiate CrdtSingleton by supplying both initialData AND singletonToCopy" } set = when { initialData != null -> CrdtSet( CrdtSet.DataImpl( initialVersion, mutableMapOf(initialData.id to CrdtSet.DataValue(initialVersion, initialData)) ) ) singletonToCopy != null -> singletonToCopy.set.copy() else -> CrdtSet(CrdtSet.DataImpl(initialVersion)) } } /** * Simple constructor to build a [CrdtSingleton] from an initial value and starting at a given * [VersionMap]. */ constructor(versionMap: VersionMap, data: T?) : this( initialVersion = versionMap, initialData = data ) override fun merge(other: Data<T>): MergeChanges<Data<T>, IOperation<T>> { if (data == other) { return MergeChanges(CrdtChange.Operations(), CrdtChange.Operations()) } val result = set.merge(other.asCrdtSetData()) // Always return CrdtChange.Data change record for the local update, since we cannot perform // an op-based change. val modelChange: CrdtChange<Data<T>, IOperation<T>> = CrdtChange.Data(data) // If the other changes were empty, we should actually just return empty changes, rather // than the model.. val otherChange: CrdtChange<Data<T>, IOperation<T>> = if (result.otherChange.isEmpty()) { CrdtChange.Operations() } else { CrdtChange.Data(data) } return MergeChanges(modelChange, otherChange) } override fun applyOperation(op: IOperation<T>): Boolean = op.applyTo(set) /** Makes a deep copy of this [CrdtSingleton]. */ /* internal */ fun copy(): CrdtSingleton<T> = CrdtSingleton(singletonToCopy = this) override fun toString(): String = "CrdtSingleton(data=${set.data})" override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (this::class != other::class) return false other as CrdtSingleton<*> if (set != other.set) return false return true } override fun hashCode(): Int = set.hashCode() /** Abstract representation of the data stored by a [CrdtSingleton]. */ interface Data<T : Referencable> : CrdtData { val values: MutableMap<ReferenceId, CrdtSet.DataValue<T>> /** Constructs a deep copy of this [Data]. */ fun copy(): Data<T> /** * Converts this instance into an equivalent instance of [CrdtSet.Data]. * * CrdtSingleton is implemented via a backing CrdtSet, and their [Data] types are trivially * convertible from one to the other. */ fun asCrdtSetData(): CrdtSet.Data<T> } /** Concrete representation of the data stored by a [CrdtSingleton]. */ data class DataImpl<T : Referencable>( override var versionMap: VersionMap = VersionMap(), override val values: MutableMap<ReferenceId, CrdtSet.DataValue<T>> = mutableMapOf() ) : Data<T> { override fun asCrdtSetData() = CrdtSet.DataImpl(versionMap, values) override fun copy() = DataImpl( versionMap = VersionMap(versionMap), values = HashMap(values) ) override fun toString(): String = "CrdtSingleton.Data(versionMap=$versionMap, values=${values.toStringRepr()})" private fun <T : Referencable> Map<ReferenceId, CrdtSet.DataValue<T>>.toStringRepr() = entries.joinToString(prefix = "{", postfix = "}") { (id, value) -> "${ReferencablePrimitive.unwrap(id) ?: id}=$value" } } /** General representation of an operation which can be applied to a [CrdtSingleton]. */ interface IOperation<T : Referencable> : CrdtOperation { val actor: Actor /** Mutates [data] based on the implementation of the [Operation]. */ fun applyTo(set: CrdtSet<T>): Boolean } sealed class Operation<T : Referencable>( override val actor: Actor, override val versionMap: VersionMap ) : IOperation<T> { /** An [Operation] to update the value stored by the [CrdtSingleton]. */ open class Update<T : Referencable>( override val actor: Actor, override val versionMap: VersionMap, val value: T ) : Operation<T>(actor, versionMap) { override fun applyTo(set: CrdtSet<T>): Boolean { // If the update does not increment actors clock we reject it. if (set.versionMap[actor] >= versionMap[actor]) return false // Remove does not require an increment, but the caller of this method will have // incremented its version, so we hack a version with t-1 for this actor. val removeVersionMap = VersionMap(versionMap) removeVersionMap[actor]-- // Clear all the values inserted before this update. Clear<T>(actor, removeVersionMap).applyTo(set) // After removal of all existing values, we simply need to add the new value. return set.applyOperation(Add(actor, versionMap, value)) } override fun equals(other: Any?): Boolean = other is Update<*> && other.versionMap == versionMap && other.actor == actor && other.value == value override fun hashCode(): Int = toString().hashCode() override fun toString(): String = "CrdtSingleton.Operation.Update($versionMap, $actor, $value)" } /** An [Operation] to clear the value stored by the [CrdtSingleton]. */ open class Clear<T : Referencable>( override val actor: Actor, override val versionMap: VersionMap ) : Operation<T>(actor, versionMap) { override fun applyTo(set: CrdtSet<T>): Boolean { // Clear all existing values if our versionMap allows it. val removeOps = set.data.values.map { (id, _) -> Remove<T>(actor, versionMap, id) } // Clear succeeds if all values are removed. return removeOps.map { set.applyOperation(it) }.all { it } } override fun equals(other: Any?): Boolean = other is Clear<*> && other.versionMap == versionMap && other.actor == actor override fun hashCode(): Int = toString().hashCode() override fun toString(): String = "CrdtSingleton.Operation.Clear($versionMap, $actor)" } } companion object { /** Creates a [CrdtSingleton] from pre-existing data. */ fun <T : Referencable> createWithData( data: Data<T> ) = CrdtSingleton<T>().apply { set = CrdtSet(data.asCrdtSetData()) } } }
bsd-3-clause
3f48bb0db458f084994e3e849e1708cf
33.827273
96
0.666797
4.383295
false
false
false
false
Maccimo/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/ExampleWorkspaceModelEventsHandler.kt
4
10071
// 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.ide.impl import com.intellij.openapi.Disposable import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.legacyBridge.module.isModuleUnloaded import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.bridgeEntities.api.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl /** * This class is not handling events about global libraries and SDK changes. Such events should * be processed via [com.intellij.openapi.roots.ModuleRootListener] */ class ExampleWorkspaceModelEventsHandler(private val project: Project): Disposable { init { val messageBusConnection = project.messageBus.connect(this) WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(messageBusConnection, object : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { // Example of handling VirtualFileUrl change at entities with update cache based on the changed urls handleLibraryChanged(event) handleContentRootChanged(event) handleSourceRootChanged(event) // If cache invalidation depends on specific properties e.g. [org.jetbrains.jps.model.java.JavaResourceRootProperties.getRelativeOutputPath] // changes from [JavaResourceRootEntity] should be handled handleJavaSourceRootChanged(event) handleJavaResourceRootChanged(event) handleCustomSourceRootPropertiesChanged(event) handleModuleChanged(event) handleJavaModuleSettingsChanged(event) handleLibraryPropertiesChanged(event) handleModuleGroupPathChanged(event) handleModuleCustomImlDataChanged(event) } }) } private fun handleLibraryChanged(event: VersionedStorageChange) { event.getChanges(LibraryEntity::class.java).forEach { change -> val (entity, _) = getEntityAndStorage(event, change) if (!libraryIsDependency(entity, project)) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf(), listOf({ roots.map { it.url }}, { excludedRoots })) updateCache(addedUrls.urls, removedUrls.urls) } } /** * If your cache invalidation depends on [com.intellij.openapi.roots.impl.libraries.LibraryEx.getKind] or * [com.intellij.openapi.roots.impl.libraries.LibraryEx.getProperties] you should handle changes from [LibraryPropertiesEntity] */ private fun handleLibraryPropertiesChanged(event: VersionedStorageChange) { event.getChanges(LibraryPropertiesEntity::class.java).forEach { change -> val (entity, _) = getEntityAndStorage(event, change) if (!libraryIsDependency(entity.library, project)) return@forEach updateCache() } } private fun handleContentRootChanged(event: VersionedStorageChange) { event.getChanges(ContentRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf({url}), listOf({ excludedUrls })) updateCache(addedUrls.urls, removedUrls.urls) } } private fun handleSourceRootChanged(event: VersionedStorageChange) { event.getChanges(SourceRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ contentRoot.module }) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf({url})) updateCache(addedUrls.urls, removedUrls.urls) } } private fun handleJavaModuleSettingsChanged(event: VersionedStorageChange) { event.getChanges(JavaModuleSettingsEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf({compilerOutput}, {compilerOutputForTests})) updateCache(addedUrls.urls, removedUrls.urls) } } private fun handleModuleChanged(event: VersionedStorageChange) { event.getChanges(ModuleEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ this }) return@forEach updateCache() } } private fun handleModuleGroupPathChanged(event: VersionedStorageChange) { event.getChanges(ModuleGroupPathEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach updateCache() } } private fun handleModuleCustomImlDataChanged(event: VersionedStorageChange) { event.getChanges(ModuleCustomImlDataEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach updateCache() } } private fun handleJavaSourceRootChanged(event: VersionedStorageChange) { event.getChanges(JavaSourceRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ sourceRoot.contentRoot.module }) return@forEach updateCache() } } /** * If cache invalidation depends on specific properties e.g. [org.jetbrains.jps.model.java.JavaResourceRootProperties.getRelativeOutputPath] * changes from [JavaResourceRootEntity] should be handled */ private fun handleJavaResourceRootChanged(event: VersionedStorageChange) { event.getChanges(JavaResourceRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change) { sourceRoot.contentRoot.module }) return@forEach updateCache() } } private fun handleCustomSourceRootPropertiesChanged(event: VersionedStorageChange) { event.getChanges(CustomSourceRootPropertiesEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change) { sourceRoot.contentRoot.module }) return@forEach updateCache() } } private fun <T: WorkspaceEntity> getEntityAndStorage(event: VersionedStorageChange, change: EntityChange<T>): Pair<T, EntityStorage> { return when (change) { is EntityChange.Added -> change.entity to event.storageAfter is EntityChange.Removed -> change.entity to event.storageBefore is EntityChange.Replaced -> change.newEntity to event.storageAfter } } private fun <T: WorkspaceEntity> isInUnloadedModule(event: VersionedStorageChange, change: EntityChange<T>, moduleAssessor: T.() -> ModuleEntity): Boolean { val (entity, storage) = getEntityAndStorage(event, change) return entity.moduleAssessor().isModuleUnloaded(storage) } /** * Example of method for calculation changed VirtualFileUrls at entities */ private fun <T: WorkspaceEntity> calculateChangedUrls(change: EntityChange<T>, vfuAssessors: List<T.() -> VirtualFileUrl?>, vfuListAssessors: List<T.() -> List<VirtualFileUrl>> = emptyList()): Pair<Added, Removed> { val addedVirtualFileUrls = mutableSetOf<VirtualFileUrl>() val removedVirtualFileUrls = mutableSetOf<VirtualFileUrl>() vfuAssessors.forEach { fieldAssessor -> when (change) { is EntityChange.Added -> fieldAssessor.invoke(change.entity)?.also { addedVirtualFileUrls.add(it) } is EntityChange.Removed -> fieldAssessor.invoke(change.entity)?.also { removedVirtualFileUrls.add(it) } is EntityChange.Replaced -> { val newVirtualFileUrl = fieldAssessor.invoke(change.newEntity) val oldVirtualFileUrl = fieldAssessor.invoke(change.oldEntity) if (newVirtualFileUrl != oldVirtualFileUrl) { newVirtualFileUrl?.also { addedVirtualFileUrls.add(it) } oldVirtualFileUrl?.also { removedVirtualFileUrls.add(it) } } } } } vfuListAssessors.forEach { fieldAssessor -> when (change) { is EntityChange.Added -> { val virtualFileUrls = fieldAssessor.invoke(change.entity) if (virtualFileUrls.isNotEmpty()) { addedVirtualFileUrls.addAll(virtualFileUrls) } } is EntityChange.Removed -> { val virtualFileUrls = fieldAssessor.invoke(change.entity) if (virtualFileUrls.isNotEmpty()) { removedVirtualFileUrls.addAll(virtualFileUrls) } } is EntityChange.Replaced -> { val newVirtualFileUrls = fieldAssessor.invoke(change.newEntity).toSet() val oldVirtualFileUrls = fieldAssessor.invoke(change.oldEntity).toSet() addedVirtualFileUrls.addAll(newVirtualFileUrls.subtract(oldVirtualFileUrls)) removedVirtualFileUrls.addAll(oldVirtualFileUrls.subtract(newVirtualFileUrls)) } } } return Added(addedVirtualFileUrls) to Removed(removedVirtualFileUrls) } private fun libraryIsDependency(library: LibraryEntity, project: Project): Boolean { if (library.tableId is LibraryTableId.ModuleLibraryTableId) return true val libraryName = library.name ModuleManager.getInstance(project).modules.forEach { module -> val exists = ModuleRootManager.getInstance(module).orderEntries.any { it is LibraryOrderEntry && it.libraryName == libraryName } if (exists) return true } return false } private fun updateCache() { } private fun updateCache(addedVirtualFileUrls: MutableSet<VirtualFileUrl>, removedVirtualFileUrls: MutableSet<VirtualFileUrl>) { } private data class Added(val urls: MutableSet<VirtualFileUrl>) private data class Removed(val urls: MutableSet<VirtualFileUrl>) override fun dispose() { } }
apache-2.0
3da81f3140d765f09e5ecb2c9b7cce01
44.990868
158
0.73806
5.201963
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/optimizer/ParamsOptimizerUtils.kt
1
1536
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.optimizer import com.kotlinnlp.simplednn.core.layers.models.feedforward.simple.FeedforwardLayerParameters import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory /** * */ object ParamsOptimizerUtils { /** * */ fun buildParams() = FeedforwardLayerParameters(inputSize = 4, outputSize = 2).also { it.unit.weights.values.assignValues(DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.3, 0.4, 0.2, -0.2), doubleArrayOf(0.2, -0.1, 0.1, 0.6) ))) it.unit.biases.values.assignValues(DenseNDArrayFactory.arrayOf( doubleArrayOf(0.3, -0.4) )) } /** * */ fun buildWeightsErrorsValues1() = DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.3, 0.4, 0.2, -0.2), doubleArrayOf(0.2, -0.1, 0.1, 0.6) )) /** * */ fun buildBiasesErrorsValues1() = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, -0.4)) /** * */ fun buildWeightsErrorsValues2() = DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.7, -0.8, 0.1, -0.6), doubleArrayOf(0.8, 0.6, -0.9, -0.2) )) /** * */ fun buildBiasesErrorsValues2() = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.9, 0.1)) }
mpl-2.0
78b06ccf8e2c76636348d43d76145a0c
25.482759
95
0.643229
3.531034
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/granular/usecases/OverviewUseCase.kt
1
11545
package org.wordpress.android.ui.stats.refresh.lists.sections.granular.usecases import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker import org.wordpress.android.analytics.AnalyticsTracker.Stat.STATS_OVERVIEW_ERROR import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.stats.LimitMode import org.wordpress.android.fluxc.model.stats.time.VisitsAndViewsModel import org.wordpress.android.fluxc.network.utils.StatsGranularity import org.wordpress.android.fluxc.store.StatsStore.TimeStatsType.OVERVIEW import org.wordpress.android.fluxc.store.stats.time.VisitsAndViewsStore import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem import org.wordpress.android.ui.stats.refresh.lists.sections.granular.GranularUseCaseFactory import org.wordpress.android.ui.stats.refresh.lists.sections.granular.SelectedDateProvider import org.wordpress.android.ui.stats.refresh.lists.sections.granular.usecases.OverviewUseCase.UiState import org.wordpress.android.ui.stats.refresh.lists.widget.WidgetUpdater.StatsWidgetUpdaters import org.wordpress.android.ui.stats.refresh.utils.StatsDateFormatter import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider import org.wordpress.android.ui.stats.refresh.utils.toStatsSection import org.wordpress.android.ui.stats.refresh.utils.trackGranular import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import org.wordpress.android.util.LocaleManagerWrapper import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.viewmodel.ResourceProvider import java.util.Calendar import javax.inject.Inject import javax.inject.Named import kotlin.math.ceil const val OVERVIEW_ITEMS_TO_LOAD = 15 @Suppress("LongParameterList") class OverviewUseCase constructor( private val statsGranularity: StatsGranularity, private val visitsAndViewsStore: VisitsAndViewsStore, private val selectedDateProvider: SelectedDateProvider, private val statsSiteProvider: StatsSiteProvider, private val statsDateFormatter: StatsDateFormatter, private val overviewMapper: OverviewMapper, @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val analyticsTracker: AnalyticsTrackerWrapper, private val statsWidgetUpdaters: StatsWidgetUpdaters, private val localeManagerWrapper: LocaleManagerWrapper, private val resourceProvider: ResourceProvider ) : BaseStatsUseCase<VisitsAndViewsModel, UiState>( OVERVIEW, mainDispatcher, backgroundDispatcher, UiState(), uiUpdateParams = listOf(UseCaseParam.SelectedDateParam(statsGranularity.toStatsSection())) ) { override fun buildLoadingItem(): List<BlockListItem> = listOf( ValueItem( value = "0", unit = R.string.stats_views, isFirst = true, contentDescription = resourceProvider.getString(R.string.stats_loading_card) ) ) override suspend fun loadCachedData(): VisitsAndViewsModel? { statsWidgetUpdaters.updateViewsWidget(statsSiteProvider.siteModel.siteId) statsWidgetUpdaters.updateWeekViewsWidget(statsSiteProvider.siteModel.siteId) val cachedData = visitsAndViewsStore.getVisits( statsSiteProvider.siteModel, statsGranularity, LimitMode.All ) if (cachedData != null) { logIfIncorrectData(cachedData, statsGranularity, statsSiteProvider.siteModel, false) selectedDateProvider.onDateLoadingSucceeded(statsGranularity) } return cachedData } override suspend fun fetchRemoteData(forced: Boolean): State<VisitsAndViewsModel> { val response = visitsAndViewsStore.fetchVisits( statsSiteProvider.siteModel, statsGranularity, LimitMode.Top(OVERVIEW_ITEMS_TO_LOAD), forced ) val model = response.model val error = response.error return when { error != null -> { selectedDateProvider.onDateLoadingFailed(statsGranularity) State.Error(error.message ?: error.type.name) } model != null && model.dates.isNotEmpty() -> { logIfIncorrectData(model, statsGranularity, statsSiteProvider.siteModel, true) selectedDateProvider.onDateLoadingSucceeded(statsGranularity) State.Data(model) } else -> { selectedDateProvider.onDateLoadingSucceeded(statsGranularity) State.Empty() } } } /** * Track the incorrect data shown for some users * see https://github.com/wordpress-mobile/WordPress-Android/issues/11412 */ private fun logIfIncorrectData( model: VisitsAndViewsModel, granularity: StatsGranularity, site: SiteModel, fetched: Boolean ) { model.dates.lastOrNull()?.let { lastDayData -> val yesterday = localeManagerWrapper.getCurrentCalendar() yesterday.add(Calendar.DAY_OF_YEAR, -1) val lastDayDate = statsDateFormatter.parseStatsDate(granularity, lastDayData.period) if (lastDayDate.before(yesterday.time)) { val currentCalendar = localeManagerWrapper.getCurrentCalendar() val lastItemAge = ceil((currentCalendar.timeInMillis - lastDayDate.time) / 86400000.0) analyticsTracker.track( STATS_OVERVIEW_ERROR, mapOf( "stats_last_date" to statsDateFormatter.printStatsDate(lastDayDate), "stats_current_date" to statsDateFormatter.printStatsDate(currentCalendar.time), "stats_age_in_days" to lastItemAge.toInt(), "is_jetpack_connected" to site.isJetpackConnected, "is_atomic" to site.isWPComAtomic, "action_source" to if (fetched) "remote" else "cached" ) ) } } } override fun buildUiModel( domainModel: VisitsAndViewsModel, uiState: UiState ): List<BlockListItem> { val items = mutableListOf<BlockListItem>() if (domainModel.dates.isNotEmpty()) { val dateFromProvider = selectedDateProvider.getSelectedDate(statsGranularity) val visibleBarCount = uiState.visibleBarCount ?: domainModel.dates.size val availableDates = domainModel.dates.map { statsDateFormatter.parseStatsDate( statsGranularity, it.period ) } val selectedDate = dateFromProvider ?: availableDates.last() val index = availableDates.indexOf(selectedDate) selectedDateProvider.selectDate( selectedDate, availableDates.takeLast(visibleBarCount), statsGranularity ) val selectedItem = domainModel.dates.getOrNull(index) ?: domainModel.dates.last() val previousItem = domainModel.dates.getOrNull(domainModel.dates.indexOf(selectedItem) - 1) items.add( overviewMapper.buildTitle( selectedItem, previousItem, uiState.selectedPosition, isLast = selectedItem == domainModel.dates.last(), statsGranularity = statsGranularity ) ) items.addAll( overviewMapper.buildChart( domainModel.dates, statsGranularity, this::onBarSelected, this::onBarChartDrawn, uiState.selectedPosition, selectedItem.period ) ) items.add( overviewMapper.buildColumns( selectedItem, this::onColumnSelected, uiState.selectedPosition ) ) } else { selectedDateProvider.onDateLoadingFailed(statsGranularity) AppLog.e(T.STATS, "There is no data to be shown in the overview block") } return items } private fun onBarSelected(period: String?) { analyticsTracker.trackGranular( AnalyticsTracker.Stat.STATS_OVERVIEW_BAR_CHART_TAPPED, statsGranularity ) if (period != null && period != "empty") { val selectedDate = statsDateFormatter.parseStatsDate(statsGranularity, period) selectedDateProvider.selectDate( selectedDate, statsGranularity ) } } private fun onColumnSelected(position: Int) { analyticsTracker.trackGranular( AnalyticsTracker.Stat.STATS_OVERVIEW_TYPE_TAPPED, statsGranularity ) updateUiState { it.copy(selectedPosition = position) } } private fun onBarChartDrawn(visibleBarCount: Int) { updateUiState { it.copy(visibleBarCount = visibleBarCount) } } data class UiState(val selectedPosition: Int = 0, val visibleBarCount: Int? = null) class OverviewUseCaseFactory @Inject constructor( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val statsSiteProvider: StatsSiteProvider, private val selectedDateProvider: SelectedDateProvider, private val statsDateFormatter: StatsDateFormatter, private val overviewMapper: OverviewMapper, private val visitsAndViewsStore: VisitsAndViewsStore, private val analyticsTracker: AnalyticsTrackerWrapper, private val statsWidgetUpdaters: StatsWidgetUpdaters, private val localeManagerWrapper: LocaleManagerWrapper, private val resourceProvider: ResourceProvider ) : GranularUseCaseFactory { override fun build(granularity: StatsGranularity, useCaseMode: UseCaseMode) = OverviewUseCase( granularity, visitsAndViewsStore, selectedDateProvider, statsSiteProvider, statsDateFormatter, overviewMapper, mainDispatcher, backgroundDispatcher, analyticsTracker, statsWidgetUpdaters, localeManagerWrapper, resourceProvider ) } }
gpl-2.0
f1609a97f9938390c1e587814da8e8ec
43.748062
112
0.636466
5.466383
false
false
false
false
f-list/exported
mobile/android/app/src/main/kotlin/net/f_list/fchat/Logs.kt
1
8788
package net.f_list.fchat import android.content.Context import android.util.SparseArray import android.webkit.JavascriptInterface import org.json.JSONArray import org.json.JSONStringer import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.RandomAccessFile import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.CharBuffer import java.util.* class Logs(private val ctx: Context) { data class IndexItem(val name: String, val index: MutableMap<Int, Int> = LinkedHashMap(), val offsets: MutableList<Long> = ArrayList()) private var index: MutableMap<String, IndexItem>? = null private var loadedIndex: MutableMap<String, IndexItem>? = null private lateinit var baseDir: File private var character: String? = null private val encoder = Charsets.UTF_8.newEncoder() private val decoder = Charsets.UTF_8.newDecoder() private val buffer = ByteBuffer.allocateDirect(51000).order(ByteOrder.LITTLE_ENDIAN) private fun loadIndex(character: String): MutableMap<String, IndexItem> { val files = File(ctx.filesDir, "$character/logs").listFiles({ _, name -> name.endsWith(".idx") }) val index = HashMap<String, IndexItem>(files.size) for(file in files) { FileInputStream(file).use { stream -> buffer.clear() val read = stream.channel.read(buffer) buffer.rewind() val nameLength = buffer.get().toInt() buffer.limit(nameLength + 1) val cb = CharBuffer.allocate(nameLength) decoder.reset() decoder.decode(buffer, cb, true) decoder.flush(cb) cb.flip() val indexItem = IndexItem(cb.toString()) buffer.limit(read) while(buffer.position() < buffer.limit()) { val key = buffer.short.toInt() indexItem.index[key] = indexItem.offsets.size indexItem.offsets.add(buffer.int.toLong() or (buffer.get().toLong() shl 32)) } index[file.nameWithoutExtension] = indexItem } } return index } @JavascriptInterface fun initN(character: String): String { baseDir = File(ctx.filesDir, "$character/logs") baseDir.mkdirs() this.character = character index = loadIndex(character) loadedIndex = index val json = JSONStringer().`object`() for(item in index!!) json.key(item.key).`object`().key("name").value(item.value.name).key("dates").value(JSONArray(item.value.index.keys)).endObject() return json.endObject().toString() } @JavascriptInterface fun logMessage(key: String, conversation: String, time: Int, type: Int, sender: String, text: String) { val day = time / 86400 val file = File(baseDir, key) buffer.clear() if(!index!!.containsKey(key)) { index!![key] = IndexItem(conversation) buffer.position(1) encoder.encode(CharBuffer.wrap(conversation), buffer, true) buffer.put(0, (buffer.position() - 1).toByte()) } val item = index!![key]!! if(!item.index.containsKey(day)) { buffer.putShort(day.toShort()) val size = file.length() item.index[day] = item.offsets.size item.offsets.add(size) buffer.putInt((size and 0xffffffffL).toInt()).put((size shr 32).toByte()) FileOutputStream(File(baseDir, "$key.idx"), true).use { file -> buffer.flip() file.channel.write(buffer) } } FileOutputStream(file, true).use { file -> buffer.clear() buffer.putInt(time) buffer.put(type.toByte()) buffer.position(6) encoder.encode(CharBuffer.wrap(sender), buffer, true) val senderLength = buffer.position() - 6 buffer.put(5, senderLength.toByte()) buffer.position(8 + senderLength) encoder.encode(CharBuffer.wrap(text), buffer, true) buffer.putShort(senderLength + 6, (buffer.position() - senderLength - 8).toShort()) buffer.putShort(buffer.position().toShort()) buffer.flip() file.channel.write(buffer) } } @JavascriptInterface fun getBacklogN(key: String): String { buffer.clear() val file = File(baseDir, key) if(!file.exists()) return "[]" val list = LinkedList<JSONStringer>() FileInputStream(file).use { stream -> val channel = stream.channel val lengthBuffer = ByteBuffer.allocateDirect(4).order(ByteOrder.LITTLE_ENDIAN) channel.position(channel.size()) while(channel.position() > 0 && list.size < 20) { lengthBuffer.rewind() lengthBuffer.limit(2) channel.position(channel.position() - 2) channel.read(lengthBuffer) lengthBuffer.clear() val length = lengthBuffer.int channel.position(channel.position() - length - 2) buffer.rewind() buffer.limit(length) channel.read(buffer) buffer.rewind() val stringer = JSONStringer() deserializeMessage(buffer, stringer) list.addFirst(stringer) channel.position(channel.position() - length) } } val json = StringBuilder("[") for(item in list) json.append(item).append(",") json.setLength(json.length - 1) return json.append("]").toString() } @JavascriptInterface fun getLogsN(character: String, key: String, date: Int): String { val indexItem = loadedIndex!![key] ?: return "[]" val dateKey = indexItem.index[date] ?: return "[]" val json = JSONStringer() json.array() FileInputStream(File(ctx.filesDir, "$character/logs/$key")).use { stream -> val channel = stream.channel val start = indexItem.offsets[dateKey] val end = if(dateKey >= indexItem.offsets.size - 1) channel.size() else indexItem.offsets[dateKey + 1] channel.position(start) val buffer = ByteBuffer.allocateDirect((end - start).toInt()).order(ByteOrder.LITTLE_ENDIAN) channel.read(buffer) buffer.rewind() while(buffer.position() < buffer.limit()) { deserializeMessage(buffer, json) buffer.limit(buffer.capacity()) buffer.position(buffer.position() + 2) } } return json.endArray().toString() } @JavascriptInterface fun loadIndexN(character: String): String { loadedIndex = if(character == this.character) this.index else this.loadIndex(character) val json = JSONStringer().`object`() for(item in loadedIndex!!) json.key(item.key).`object`().key("name").value(item.value.name).key("dates").value(JSONArray(item.value.index.keys)).endObject() return json.endObject().toString() } @JavascriptInterface fun getCharactersN(): String { return JSONArray(ctx.filesDir.listFiles().filter { it.isDirectory }.map { it.name }).toString() } @JavascriptInterface fun repair() { val files = baseDir.listFiles() val indexBuffer = ByteBuffer.allocateDirect(7).order(ByteOrder.LITTLE_ENDIAN) for(entry in files) { if(entry.name.endsWith(".idx")) continue RandomAccessFile("$entry.idx", "rw").use { idx -> buffer.clear() buffer.limit(1) idx.channel.read(buffer) idx.channel.truncate((buffer.get(0) + 1).toLong()) idx.channel.position(idx.channel.size()) RandomAccessFile(entry, "rw").use { file -> var lastDay = 0 val size = file.channel.size() var pos = 0L try { while(file.channel.position() < size) { buffer.clear() pos = file.channel.position() val read = file.channel.read(buffer) var success = false buffer.flip() while(buffer.remaining() > 10) { val offset = buffer.position() val day = buffer.int / 86400 buffer.get() val senderLength = buffer.get() if(buffer.remaining() < senderLength + 4) break buffer.limit(buffer.position() + senderLength) decoder.decode(buffer) buffer.limit(read) val textLength = buffer.short.toInt() if(buffer.remaining() < textLength + 2) break buffer.limit(buffer.position() + textLength) decoder.decode(buffer) buffer.limit(read) val messageSize = buffer.position() - offset if(messageSize != buffer.short.toInt()) throw Exception() if(day > lastDay) { lastDay = day indexBuffer.position(0) indexBuffer.putShort(day.toShort()) indexBuffer.putInt((pos and 0xffffffffL).toInt()).put((pos shr 32).toByte()) indexBuffer.position(0) idx.channel.write(indexBuffer) } pos += messageSize + 2 success = true } if(!success) throw Exception() file.channel.position(pos) } } catch(e: Exception) { file.channel.truncate(pos) } } } } } private fun deserializeMessage(buffer: ByteBuffer, json: JSONStringer) { val start = buffer.position() json.`object`() json.key("time") json.value(buffer.int) json.key("type") json.value(buffer.get()) json.key("sender") val senderLength = buffer.get() buffer.limit(start + 6 + senderLength) json.value(decoder.decode(buffer)) buffer.limit(buffer.capacity()) val textLength = buffer.short.toInt() and 0xffff json.key("text") buffer.limit(start + 8 + senderLength + textLength) json.value(decoder.decode(buffer)) json.endObject() } }
mit
1b3ddfd8373428b769ec5670d3a34c45
32.803846
136
0.681042
3.44898
false
false
false
false
martinhellwig/DatapassWidget
app/src/main/java/de/schooltec/datapass/ConnectionChangeReceiver.kt
1
2373
package de.schooltec.datapass import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.os.AsyncTask import de.schooltec.datapass.AppWidgetIdUtil.getAllStoredAppWidgetIds /** * Gets events, if the connectivity-status gets changed and updates all widgets, if wifi is off and mobile data on. * * @author Martin Hellwig * @author Markus Hettig */ class ConnectionChangeReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // Get connection mode val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager @Suppress("DEPRECATION") val connectionType = when { connectivityManager.activeNetworkInfo == null -> ConnectionType.NONE else -> { when (connectivityManager.activeNetworkInfo.type) { ConnectivityManager.TYPE_MOBILE -> ConnectionType.MOBILE ConnectivityManager.TYPE_WIFI -> ConnectionType.WIFI else -> return } } } // wait 3 seconds, so that phone has hopefully inet connection try { Thread.sleep(3000) } catch (ignored: InterruptedException) { } // Get all appIds val storedAppIds = getAllStoredAppWidgetIds(context) /* Only update in silent mode if switched to mobile data. Otherwise you are probably in wifi mode, ergo there is no new information about the used data and therefore grayish the progress bar. */ val updateMode = if (connectionType == ConnectionType.MOBILE) UpdateMode.SILENT else UpdateMode.ULTRA_SILENT storedAppIds.forEach { val appWidgetId = Integer.valueOf(it.substring(0, it.indexOf(","))) val carrier = it.substring(it.indexOf(",") + 1) UpdateWidgetTask( appWidgetId, context, updateMode, carrier ).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } } private enum class ConnectionType { MOBILE, WIFI, NONE } }
apache-2.0
ed1fa93cbf8ec751ef28d482d2c502f3
31.958333
115
0.613148
5.356659
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/serialonly/NolTransitData.kt
1
3626
/* * NolTransitData.kt * * Copyright 2019 Google * * 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 au.id.micolous.metrodroid.transit.serialonly import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.desfire.DesfireCard import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.CardInfo import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.transit.TransitRegion import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.NumberUtils @Parcelize data class NolTransitData (private val mSerial: Int?, private val mType: Int?): SerialOnlyTransitData() { override val reason: Reason get() = Reason.LOCKED override val extraInfo: List<ListItem>? get() = super.extraInfo.orEmpty() + listOf(ListItem(R.string.card_type, when (mType) { 0x4d5 -> Localizer.localizeString(R.string.nol_silver) 0x4d9 -> Localizer.localizeString(R.string.nol_red) else -> Localizer.localizeString(R.string.unknown_format, "${mType?.toString(16)}") })) override val serialNumber get() = formatSerial(mSerial) override val cardName get() = Localizer.localizeString(NAME) companion object { private const val APP_ID_SERIAL = 0xffffff private val NAME = R.string.card_name_nol private val CARD_INFO = CardInfo( name = NAME, locationId = R.string.location_dubai, imageId = R.drawable.nol, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareDesfire, region = TransitRegion.UAE, resourceExtraNote = R.string.card_note_card_number_only) private fun getSerial(card: DesfireCard) = card.getApplication(APP_ID_SERIAL)?.getFile(8)?.data?.getBitsFromBuffer( 61, 32) private fun formatSerial(serial: Int?) = if (serial != null) NumberUtils.formatNumber(serial.toLong(), " ", 3, 3, 4) else null val FACTORY: DesfireCardTransitFactory = object : DesfireCardTransitFactory { override fun earlyCheck(appIds: IntArray) = (0x4078 in appIds) && (APP_ID_SERIAL in appIds) override fun parseTransitData(card: DesfireCard) = NolTransitData(mSerial = getSerial(card), mType = card.getApplication(APP_ID_SERIAL)?.getFile(8) ?.data?.byteArrayToInt(0xc, 2)) override fun parseTransitIdentity(card: DesfireCard) = TransitIdentity(NAME, formatSerial(getSerial(card))) override val allCards get() = listOf(CARD_INFO) } } }
gpl-3.0
98ffc3b5a0e60be6a7f27bcb6b8077ee
40.678161
105
0.663817
4.337321
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/advanced/AdvancedPrivacySettingsViewModel.kt
2
3456
package org.thoughtcrime.securesms.components.settings.app.privacy.advanced import android.content.SharedPreferences import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobs.RefreshAttributesJob import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.util.SingleLiveEvent import org.thoughtcrime.securesms.util.TextSecurePreferences import org.thoughtcrime.securesms.util.livedata.Store class AdvancedPrivacySettingsViewModel( private val sharedPreferences: SharedPreferences, private val repository: AdvancedPrivacySettingsRepository ) : ViewModel() { private val store = Store(getState()) private val singleEvents = SingleLiveEvent<Event>() val state: LiveData<AdvancedPrivacySettingsState> = store.stateLiveData val events: LiveData<Event> = singleEvents fun disablePushMessages() { store.update { getState().copy(showProgressSpinner = true) } repository.disablePushMessages { when (it) { AdvancedPrivacySettingsRepository.DisablePushMessagesResult.SUCCESS -> { TextSecurePreferences.setPushRegistered(ApplicationDependencies.getApplication(), false) SignalStore.registrationValues().clearRegistrationComplete() } AdvancedPrivacySettingsRepository.DisablePushMessagesResult.NETWORK_ERROR -> { singleEvents.postValue(Event.DISABLE_PUSH_FAILED) } } store.update { getState().copy(showProgressSpinner = false) } } } fun setAlwaysRelayCalls(enabled: Boolean) { sharedPreferences.edit().putBoolean(TextSecurePreferences.ALWAYS_RELAY_CALLS_PREF, enabled).apply() refresh() } fun setShowStatusIconForSealedSender(enabled: Boolean) { sharedPreferences.edit().putBoolean(TextSecurePreferences.SHOW_UNIDENTIFIED_DELIVERY_INDICATORS, enabled).apply() repository.syncShowSealedSenderIconState() refresh() } fun setAllowSealedSenderFromAnyone(enabled: Boolean) { sharedPreferences.edit().putBoolean(TextSecurePreferences.UNIVERSAL_UNIDENTIFIED_ACCESS, enabled).apply() ApplicationDependencies.getJobManager().add(RefreshAttributesJob()) refresh() } fun refresh() { store.update { getState().copy(showProgressSpinner = it.showProgressSpinner) } } private fun getState() = AdvancedPrivacySettingsState( isPushEnabled = TextSecurePreferences.isPushRegistered(ApplicationDependencies.getApplication()), alwaysRelayCalls = TextSecurePreferences.isTurnOnly(ApplicationDependencies.getApplication()), showSealedSenderStatusIcon = TextSecurePreferences.isShowUnidentifiedDeliveryIndicatorsEnabled( ApplicationDependencies.getApplication() ), allowSealedSenderFromAnyone = TextSecurePreferences.isUniversalUnidentifiedAccess( ApplicationDependencies.getApplication() ), false ) enum class Event { DISABLE_PUSH_FAILED } class Factory( private val sharedPreferences: SharedPreferences, private val repository: AdvancedPrivacySettingsRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return requireNotNull( modelClass.cast( AdvancedPrivacySettingsViewModel( sharedPreferences, repository ) ) ) } } }
gpl-3.0
1352982a2b42ad946875e3c70dfae918
35.378947
117
0.769097
5.127596
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/en1545/En1545Parsed.kt
1
7011
/* * En1545Fixed.kt * * Copyright 2018 Google * * 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 au.id.micolous.metrodroid.transit.en1545 import au.id.micolous.metrodroid.multi.Parcelable import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.time.MetroTimeZone import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.util.NumberUtils import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray sealed class En1545Value : Parcelable @Parcelize class En1545ValueInt(val v: Int) : En1545Value() @Parcelize class En1545ValueString(val v: String) : En1545Value() @Parcelize class En1545Parsed(private val map: MutableMap<String, En1545Value> = mutableMapOf()) : Parcelable { operator fun plus(other: En1545Parsed) = En1545Parsed((map + other.map).toMutableMap()) fun insertInt(name: String, path: String, value: Int) { map[makeFullName(name, path)] = En1545ValueInt(value) } fun insertString(name: String, path: String, value: String) { map[makeFullName(name, path)] = En1545ValueString(value) } fun getInfo(skipSet: Set<String>): List<ListItem> = map.entries.sortedBy { it.key } .filter { (key, _) -> !skipSet.contains(getBaseName(key)) }.map { (key, l) -> when (l) { is En1545ValueInt -> ListItem(key, NumberUtils.intToHex(l.v)) is En1545ValueString -> ListItem(key, l.v) } } private fun getBaseName(name: String): String { return name.substring(name.lastIndexOf('/') + 1) } fun makeString(separator: String, skipSet: Set<String>): String { val ret = StringBuilder() for ((key, value) in map) { if (skipSet.contains(getBaseName(key))) continue ret.append(key).append(" = ") if (value is En1545ValueInt) ret.append(NumberUtils.intToHex(value.v)) if (value is En1545ValueString) ret.append("\"").append(value.v).append("\"") ret.append(separator) } return ret.toString() } override fun toString(): String { return "[" + makeString(", ", emptySet()) + "]" } fun getInt(name: String, path: String = ""): Int? { return (map[makeFullName(name, path)] as? En1545ValueInt)?.v } fun getInt(name: String, vararg ipath: Int): Int? { val path = StringBuilder() for (iel in ipath) path.append("/").append(iel.toString()) return (map[makeFullName(name, path.toString())] as? En1545ValueInt)?.v } fun getIntOrZero(name: String, path: String = "") = getInt(name, path) ?: 0 fun getString(name: String, path: String = ""): String? { return (map[makeFullName(name, path)] as? En1545ValueString)?.v } fun getTimeStamp(name: String, tz: MetroTimeZone): Timestamp? { if (contains(En1545FixedInteger.dateTimeName(name))) return En1545FixedInteger.parseTimeSec( getIntOrZero(En1545FixedInteger.dateTimeName(name)), tz) if (contains(En1545FixedInteger.dateTimeLocalName(name))) return En1545FixedInteger.parseTimeSecLocal( getIntOrZero(En1545FixedInteger.dateTimeLocalName(name)), tz) if (contains(En1545FixedInteger.timeName(name)) && contains(En1545FixedInteger.dateName(name))) return En1545FixedInteger.parseTime( getIntOrZero(En1545FixedInteger.dateName(name)), getIntOrZero(En1545FixedInteger.timeName(name)), tz) if (contains(En1545FixedInteger.timeLocalName(name)) && contains(En1545FixedInteger.dateName(name))) return En1545FixedInteger.parseTimeLocal( getIntOrZero(En1545FixedInteger.dateName(name)), getIntOrZero(En1545FixedInteger.timeLocalName(name)), tz) if (contains(En1545FixedInteger.timePacked16Name(name)) && contains(En1545FixedInteger.dateName(name))) return En1545FixedInteger.parseTimePacked16( getIntOrZero(En1545FixedInteger.dateName(name)), getIntOrZero(En1545FixedInteger.timePacked16Name(name)), tz) if (contains(En1545FixedInteger.timePacked11LocalName(name)) && contains(En1545FixedInteger.datePackedName(name))) return En1545FixedInteger.parseTimePacked11Local( getIntOrZero(En1545FixedInteger.datePackedName(name)), getIntOrZero(En1545FixedInteger.timePacked11LocalName(name)), tz) if (contains(En1545FixedInteger.dateName(name))) return En1545FixedInteger.parseDate( getIntOrZero(En1545FixedInteger.dateName(name)), tz) if (contains(En1545FixedInteger.datePackedName(name))) return En1545FixedInteger.parseDatePacked( getIntOrZero(En1545FixedInteger.datePackedName(name))) if (contains(En1545FixedInteger.dateBCDName(name))) return En1545FixedInteger.parseDateBCD( getIntOrZero(En1545FixedInteger.dateBCDName(name))) return null // TODO: any need to support time-only cases? } fun contains(name: String, path: String = ""): Boolean { return map.containsKey(makeFullName(name, path)) } fun append(data: ImmutableByteArray, off: Int, field: En1545Field): En1545Parsed { field.parseField(data, off, "", this) { obj, offset, len -> obj.getBitsFromBuffer(offset, len) } return this } fun appendLeBits(data: ImmutableByteArray, off: Int, field: En1545Field): En1545Parsed { field.parseField(data, off, "", this) { obj, offset, len -> obj.getBitsFromBufferLeBits(offset, len) } return this } fun append(data: ImmutableByteArray, field: En1545Field): En1545Parsed { return append(data, 0, field) } fun appendLeBits(data: ImmutableByteArray, field: En1545Field): En1545Parsed { return appendLeBits(data, 0, field) } companion object { private fun makeFullName(name: String, path: String?): String { return if (path == null || path.isEmpty()) name else "$path/$name" } private fun dig2(v: Int): String = when (v) { in 0..9 -> "0$v" else -> "$v" } } }
gpl-3.0
2ba44d2d05be85d740727f3c4a4d306f
40.485207
122
0.655113
4.121693
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/TransitData.kt
1
9773
/* * TransitData.kt * * Copyright 2011-2014 Eric Butler <[email protected]> * Copyright 2015-2019 Michael Farrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit import au.id.micolous.metrodroid.multi.* import au.id.micolous.metrodroid.time.Daystamp import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.ui.HeaderListItem import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.Preferences import au.id.micolous.metrodroid.util.TripObfuscator abstract class TransitData : Parcelable { /** * The (currency) balance of the card's _purse_. Most cards have only one purse. * * By default, this returns `null`, so no balance information will be displayed (and it is presumed unknown). * * If a card **only** stores season passes or a number of credited rides (instead of currency), return `null`. * * Cards with more than one purse must implement [balances] instead. * * Cards with a single purse _should_ implement this method, and [TransitData.balance] will automatically handle * the conversion. * * Note: This method is protected -- callers must use [balances], even in the case there is only one purse. * * @see balances * @return The balance of the card, or `null` if it is not known. */ protected open val balance: TransitBalance? get() = null /** * The (currency) balances of all of the card's _purses_. * * Cards with multiple "purse" balances (generally: hybrid transit cards that can act as multiple transit cards) * must implement this method, and must not implement [balance]. * * Cards with a single "purse" balance should implement [balance] instead -- the default implementation in * [TransitData] will automatically up-convert it. * * @return The purse balance(s) of the card, or `null` if it is not known. */ open val balances: List<TransitBalance>? get() { val b = balance ?: return null return listOf(b) } /** * The serial number of the card. Generally printed on the card itself, or shown on receipts from ticket vending * machines. * * If a card has more than one serial number, then show the second serial number in [info]. */ abstract val serialNumber: String? /** * Lists all trips on the card. * * If the transit card does not store trip information, or the [TransitData] implementation does not support * reading trips yet, return `null`. * * If the [TransitData] implementation supports reading trip data, but no trips have been taken on the card, return * an [emptyList]. * * Note: UI elements must use [prepareTrips] instead, which implements obfuscation. * * @return A [List] of [Trip]s, or `null` if not supported. * @see [prepareTrips] */ open val trips: List<Trip>? get() = null open val subscriptions: List<Subscription>? get() = null /** * Allows [TransitData] implementors to show extra information that doesn't fit within the standard bounds of the * interface. By default, this returns `null`, which hides the "Info" tab. * * Implementors **must** implement obfuscation through this method: * * * Check for [Preferences.hideCardNumbers] whenever you show a card number, or other mark (such as name, height, * weight, birthday or gender) that could be used to identify this card or its holder. * * * Pass dates and times ([Timestamp] and [Daystamp]) through [TripObfuscator.maybeObfuscateTS]. * * * Pass all currency amounts through [TransitCurrency.formatCurrencyString] and * [TransitCurrency.maybeObfuscateBalance]. * */ open val info: List<ListItem>? get() = null abstract val cardName: String /** * You can optionally add a link to an FAQ page for the card. This will be shown in the ... * drop down menu for cards that are supported, and on the main page for subclasses of * [au.id.micolous.metrodroid.transit.serialonly.SerialOnlyTransitData]. * * @return Uri pointing to an FAQ page, or null if no page is to be supplied. */ open val moreInfoPage: String? get() = null /** * You may optionally link to a page which allows you to view the online services for the card. * * By default, this returns `null`, which causes the menu item to be removed. * * @return Uri to card's online services page. */ open val onlineServicesPage: String? get() = null open val warning: String? get() = null /** * If a [TransitData] provider doesn't know some of the stops / stations on a user's card, * then it may raise a signal to the user to submit the unknown stations to our web service. * * @return false if all stations are known (default), true if there are unknown stations */ open val hasUnknownStations: Boolean get() = false /** * Finds the [Daystamp] of the latest [Trip] taken on the card. This value is **not** obfuscated. * * This is helpful for cards that define their [balance] validity period as "_n_ years since last use". * * @return Latest timestamp of a trip, or `null` if there are no trips or no trips with timestamps. */ fun getLastUseDaystamp(): Daystamp? { // Find the last trip taken on the card. return trips?.mapNotNull { t -> t.endTimestamp ?: t.startTimestamp }?.map { it.toDaystamp() } ?.maxBy { it.daysSinceEpoch } } /** * Declares levels of raw information to display, useful for development and debugging. */ enum class RawLevel { /** Display no extra information (default). */ NONE, /** Display only unknown fields, or fields that are not displayed in other contexts. */ UNKNOWN_ONLY, /** Display all fields, even ones that are decoded in other contexts. */ ALL; companion object { fun fromString(v: String): RawLevel? = values().find { it.toString() == v } } } /** * Prepares a list of trips for display in the UI. * * This will obfuscate trip details if the user has enabled one of the trip obfuscation [Preferences]. * * @param safe When `false` (default), the exact [trips] will be returned verbatim if no obfuscation [Preferences] * have been enabled. * * When `true`, [trips] is passed through [TripObfuscator] regardless of whether the user has enabled one * of the trip obfuscation [Preferences]. If no obfuscation flags are enabled, [TripObfuscator] will simply copy * all fields verbatim. * * This is required for Swift interop, as properties can't throw exceptions in Swift. * * @return A list of trips for display purposes. If [trips] is null, this also returns null. * * @see [trips], [TripObfuscator.obfuscateTrips] */ @NativeThrows fun prepareTrips(safe: Boolean = false): List<Trip>? = logAndSwiftWrap ("TransitData", "prepareTrips failed") lam@{ val trips = this.trips ?: return@lam null val maybeObfuscatedTrips = if (safe || Preferences.obfuscateTripDates || Preferences.obfuscateTripTimes || Preferences.obfuscateTripFares) { TripObfuscator.obfuscateTrips(trips, Preferences.obfuscateTripDates, Preferences.obfuscateTripTimes, Preferences.obfuscateTripFares) } else { trips } // Explicitly sort these events return@lam maybeObfuscatedTrips.sortedWith(Trip.Comparator()) } /** * Raw field information from the card, which is only useful for development and debugging. By default, this * returns `null`. * * This has the same semantics as [info], except obfuscation is never used on these fields. * * This is only called when [Preferences.rawLevel] is not [RawLevel.NONE]. * * @param level Level of detail requested. * @see [info] */ open fun getRawFields(level: RawLevel): List<ListItem>? = null companion object { fun mergeInfo(transitData: TransitData): List<ListItem>? { val rawLevel = Preferences.rawLevel val inf = transitData.info if (rawLevel == RawLevel.NONE) return inf val rawInf = transitData.getRawFields(rawLevel) ?: return inf return inf.orEmpty() + listOf(HeaderListItem(Localizer.localizeString(R.string.raw_header))) + rawInf } fun hasInfo(transitData: TransitData): Boolean { if (transitData.info != null) return true val rawLevel = Preferences.rawLevel if (rawLevel == RawLevel.NONE) return false return transitData.getRawFields(rawLevel) != null } } }
gpl-3.0
35eefef78b113a33b4589d2e7954b1a6
38.248996
120
0.649954
4.386445
false
false
false
false
JavaEden/Orchid-Core
OrchidCore/src/main/kotlin/com/eden/orchid/impl/compilers/clog/ClogSetupListener.kt
2
6601
package com.eden.orchid.impl.compilers.clog import com.caseyjbrooks.clog.Clog import com.caseyjbrooks.clog.ClogLogger import com.caseyjbrooks.clog.DefaultLogger import com.caseyjbrooks.clog.parseltongue.Parseltongue import com.eden.orchid.Orchid import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.compilers.TemplateFunction import com.eden.orchid.api.events.On import com.eden.orchid.api.events.OrchidEventListener import com.eden.orchid.utilities.SuppressedWarnings import java.util.Arrays import java.util.HashMap import java.util.HashSet import java.util.logging.Handler import java.util.logging.Level import java.util.logging.LogManager import java.util.logging.LogRecord import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton @Singleton @JvmSuppressWildcards @Suppress(SuppressedWarnings.UNUSED_PARAMETER) class ClogSetupListener @Inject constructor( private val contextProvider: Provider<OrchidContext>, private val templateTagsProvider: Provider<Set<TemplateFunction>> ) : OrchidEventListener { private val warningLogger = AbstractLogCollector(contextProvider, "Warnings:", Clog.Priority.WARNING) private val errorLogger = AbstractLogCollector(contextProvider, "Errors:", Clog.Priority.ERROR) private val fatalLogger = AbstractLogCollector(contextProvider, "Fatal exceptions:", Clog.Priority.FATAL) @On(Orchid.Lifecycle.InitComplete::class) fun onInitComplete(event: Orchid.Lifecycle.InitComplete) { Clog.getInstance().addLogger(Clog.KEY_W, warningLogger) Clog.getInstance().addLogger(Clog.KEY_E, errorLogger) Clog.getInstance().addLogger(Clog.KEY_WTF, fatalLogger) } @On(Orchid.Lifecycle.OnStart::class) fun onStart(event: Orchid.Lifecycle.OnStart) { val formatter = Clog.getInstance().formatter if (formatter is Parseltongue) { val incantations = templateTagsProvider.get() .map { templateTag -> ClogIncantationWrapper( contextProvider, templateTag.name, Arrays.asList(*templateTag.parameters()), templateTag.javaClass ) } formatter.addSpells(*incantations.toTypedArray()) } } @On(Orchid.Lifecycle.BuildFinish::class) fun onBuildFinish(event: Orchid.Lifecycle.BuildFinish) { printPendingMessages() } @On(Orchid.Lifecycle.DeployFinish::class) fun onBuildFinish(deployFinish: Orchid.Lifecycle.DeployFinish) { printPendingMessages() } @On(Orchid.Lifecycle.Shutdown::class) fun onShutdown(event: Orchid.Lifecycle.Shutdown) { printPendingMessages() } private fun printPendingMessages() { warningLogger.printAllMessages() errorLogger.printAllMessages() fatalLogger.printAllMessages() } companion object { @JvmStatic fun registerJavaLoggingHandler() { //reset() will remove all default handlers LogManager.getLogManager().reset() val rootLogger = LogManager.getLogManager().getLogger("") // add our custom Java Logging handler rootLogger.addHandler(ClogJavaLoggingHandler()) // ignore annoying Hibernate Validator and JSass messages Clog.getInstance().addTagToBlacklist("org.hibernate.validator.internal.util.Version") Clog.getInstance().addTagToBlacklist("io.bit3.jsass.adapter.NativeLoader") // Ignore Pebble internal logging Clog.getInstance().addTagToBlacklist("com.mitchellbosecke.pebble.lexer.LexerImpl") Clog.getInstance().addTagToBlacklist("com.mitchellbosecke.pebble.lexer.TemplateSource") Clog.getInstance().addTagToBlacklist("com.mitchellbosecke.pebble.PebbleEngine") } } } data class LogMessage(val message: String, val throwable: Throwable?) private class AbstractLogCollector( val contextProvider: Provider<OrchidContext>, val headerMessage: String, val loggerPriority: Clog.Priority ) : ClogLogger { val messages: MutableMap<String, MutableSet<LogMessage>> = HashMap() override fun priority(): Clog.Priority = loggerPriority override fun isActive(): Boolean = true override fun log(tag: String, message: String): Int { messages.getOrPut(tag) { HashSet() }.add(LogMessage(message, null)) if (!contextProvider.get().state.isWorkingState) { printAllMessages() } return 0 } override fun log(tag: String, message: String, throwable: Throwable): Int { messages.getOrPut(tag) { HashSet() }.add(LogMessage(message, null)) if (!contextProvider.get().state.isWorkingState) { printAllMessages() } return 0 } fun printAllMessages() { if (messages.size > 0) { val logger = DefaultLogger(priority()) logger.log("", headerMessage) messages.forEach { tag, logMessages -> logger.log(tag, "") logMessages.forEach { message -> if (message.throwable != null) { logger.log("", " - " + message.message, message.throwable) } else { logger.log("", " - " + message.message) } } println("") } messages.clear() println("") } } } private class ClogJavaLoggingHandler : Handler() { override fun publish(record: LogRecord) { val level = record.level val levelInt = level.intValue() val clog = Clog.tag(record.sourceClassName) if (level == Level.OFF) { // do nothing } else if (level == Level.ALL) { // always log at verbose level clog.v(record.message) } else { // log at closest Clog level if (levelInt >= Level.SEVERE.intValue()) { clog.e(record.message) } else if (levelInt >= Level.WARNING.intValue()) { clog.w(record.message) } else if (levelInt >= Level.INFO.intValue()) { clog.i(record.message) } else if (levelInt >= Level.CONFIG.intValue()) { clog.d(record.message) } else { clog.v(record.message) } } } override fun flush() {} @Throws(SecurityException::class) override fun close() { } }
mit
f06cd79b50e4c4244d71a465545d41b7
32.507614
109
0.637176
4.60642
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/provider.kt
4
2509
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror import com.sun.jdi.* import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.DefaultExecutionContext import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty interface ReferenceTypeProvider { fun getCls(): ClassType } interface MirrorProvider<T, F> { fun mirror(value: T?, context: DefaultExecutionContext): F? fun isCompatible(value: T?): Boolean } class MethodMirrorDelegate<T, F>(val name: String, private val mirrorProvider: MirrorProvider<T, F>, val signature: String? = null) : ReadOnlyProperty<ReferenceTypeProvider, MethodEvaluator.MirrorMethodEvaluator<T, F>> { override fun getValue(thisRef: ReferenceTypeProvider, property: KProperty<*>): MethodEvaluator.MirrorMethodEvaluator<T, F> { val methods = if (signature == null) thisRef.getCls().methodsByName(name) else thisRef.getCls().methodsByName(name, signature) return MethodEvaluator.MirrorMethodEvaluator(methods.singleOrNull(), mirrorProvider) } } class MethodDelegate<T>(val name: String, val signature: String? = null) : ReadOnlyProperty<ReferenceTypeProvider, MethodEvaluator<T>> { override fun getValue(thisRef: ReferenceTypeProvider, property: KProperty<*>): MethodEvaluator<T> { val methods = if (signature == null) thisRef.getCls().methodsByName(name) else thisRef.getCls().methodsByName(name, signature) return MethodEvaluator.DefaultMethodEvaluator(methods.singleOrNull()) } } class FieldMirrorDelegate<T, F>(val name: String, private val mirrorProvider: MirrorProvider<T, F>) : ReadOnlyProperty<ReferenceTypeProvider, FieldEvaluator.MirrorFieldEvaluator<T, F>> { override fun getValue(thisRef: ReferenceTypeProvider, property: KProperty<*>): FieldEvaluator.MirrorFieldEvaluator<T, F> { return FieldEvaluator.MirrorFieldEvaluator(thisRef.getCls().fieldByName(name), thisRef, mirrorProvider) } } class FieldDelegate<T>(val name: String) : ReadOnlyProperty<ReferenceTypeProvider, FieldEvaluator<T>> { override fun getValue(thisRef: ReferenceTypeProvider, property: KProperty<*>): FieldEvaluator<T> { return FieldEvaluator.DefaultFieldEvaluator(thisRef.getCls().fieldByName(name), thisRef) } }
apache-2.0
2affbded271275833875dd5aeed87bcd
53.543478
168
0.742527
4.570128
false
false
false
false
cfieber/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/StartTaskHandler.kt
1
2219
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.Task import com.netflix.spinnaker.orca.events.TaskStarted import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.StartTask import com.netflix.spinnaker.q.Queue import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.ApplicationEventPublisher import org.springframework.stereotype.Component import java.time.Clock @Component class StartTaskHandler( override val queue: Queue, override val repository: ExecutionRepository, override val contextParameterProcessor: ContextParameterProcessor, @Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher, private val clock: Clock ) : OrcaMessageHandler<StartTask>, ExpressionAware { override fun handle(message: StartTask) { message.withTask { stage, task -> task.status = RUNNING task.startTime = clock.millis() val mergedContextStage = stage.withMergedContext() repository.storeStage(mergedContextStage) queue.push(RunTask(message, task.id, task.type)) publisher.publishEvent(TaskStarted(this, mergedContextStage, task)) } } override val messageType = StartTask::class.java @Suppress("UNCHECKED_CAST") private val com.netflix.spinnaker.orca.pipeline.model.Task.type get() = Class.forName(implementingClass) as Class<out Task> }
apache-2.0
8d2707584dbeef10952f20f5b7532459
36.610169
85
0.784588
4.385375
false
false
false
false
mdanielwork/intellij-community
platform/script-debugger/protocol/protocol-reader/src/TypeWriter.kt
3
8531
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.protocolReader import org.jetbrains.jsonProtocol.JsonObjectBased import java.lang.reflect.Method import java.util.* internal const val FIELD_PREFIX = '_' internal const val NAME_VAR_NAME = "_n" private fun assignField(out: TextOutput, fieldName: String) = out.append(FIELD_PREFIX).append(fieldName).append(" = ") internal class TypeRef<T>(val typeClass: Class<T>) { var type: TypeWriter<T>? = null } internal class TypeWriter<T>(val typeClass: Class<T>, jsonSuperClass: TypeRef<*>?, private val volatileFields: List<VolatileFieldBinding>, private val methodHandlerMap: LinkedHashMap<Method, MethodHandler>, /** Loaders that should read values and save them in field array on parse time. */ private val fieldLoaders: List<FieldLoader>, private val hasLazyFields: Boolean) { /** Subtype aspects of the type or null */ val subtypeAspect = if (jsonSuperClass == null) null else ExistingSubtypeAspect(jsonSuperClass) fun writeInstantiateCode(scope: ClassScope, out: TextOutput) { writeInstantiateCode(scope, false, out) } fun writeInstantiateCode(scope: ClassScope, deferredReading: Boolean, out: TextOutput) { val className = scope.getTypeImplReference(this) if (deferredReading || subtypeAspect == null) { out.append(className) } else { subtypeAspect.writeInstantiateCode(className, out) } } fun write(fileScope: FileScope) { val out = fileScope.output val valueImplClassName = fileScope.getTypeImplShortName(this) out.append("private class ").append(valueImplClassName).append('(').append(JSON_READER_PARAMETER_DEF).comma().append("preReadName: String?") subtypeAspect?.writeSuperFieldJava(out) out.append(") : ").append(typeClass.canonicalName).openBlock() if (hasLazyFields || JsonObjectBased::class.java.isAssignableFrom(typeClass)) { out.append("private var ").append(PENDING_INPUT_READER_NAME).append(": ").append(JSON_READER_CLASS_NAME).append("? = reader.subReader()!!").newLine() } val classScope = fileScope.newClassScope() for (field in volatileFields) { field.writeFieldDeclaration(classScope, out) out.newLine() } for (loader in fieldLoaders) { if (loader.asImpl) { out.append("override") } else { out.append("private") } out.append(" var ").appendName(loader) fun addType() { out.append(": ") loader.valueReader.appendFinishedValueTypeName(out) out.append("? = null") } if (loader.valueReader is PrimitiveValueReader) { val defaultValue = loader.defaultValue ?: loader.valueReader.defaultValue if (defaultValue != null) { out.append(" = ").append(defaultValue) } else { addType() } } else { addType() } out.newLine() } if (fieldLoaders.isNotEmpty()) { out.newLine() } writeConstructorMethod(classScope, out) out.newLine() subtypeAspect?.writeParseMethod(classScope, out) for ((key, value) in methodHandlerMap.entries) { out.newLine() value.writeMethodImplementationJava(classScope, key, out) out.newLine() } writeBaseMethods(out) subtypeAspect?.writeGetSuperMethodJava(out) writeEqualsMethod(valueImplClassName, out) out.indentOut().append('}') } /** * Generates Java implementation of standard methods of JSON type class (if needed): * {@link org.jetbrains.jsonProtocol.JsonObjectBased#getDeferredReader()} */ private fun writeBaseMethods(out: TextOutput) { val method: Method try { method = typeClass.getMethod("getDeferredReader") } catch (ignored: NoSuchMethodException) { // Method not found, skip. return } out.newLine() writeMethodDeclarationJava(out, method) out.append(" = ").append(PENDING_INPUT_READER_NAME) } private fun writeEqualsMethod(valueImplClassName: String, out: TextOutput) { if (fieldLoaders.isEmpty()) { return } out.newLine().append("override fun equals(other: Any?): Boolean = ") out.append("other is ").append(valueImplClassName) // at first we should compare primitive values, then enums, then string, then objects fun fieldWeight(reader: ValueReader): Int { var w = 10 if (reader is PrimitiveValueReader) { w-- if (reader.className != "String") { w-- } } else if (reader is EnumReader) { // -1 as primitive, -1 as not a string w -= 2 } return w } for (loader in fieldLoaders.sortedWith(Comparator<FieldLoader> { f1, f2 -> fieldWeight((f1.valueReader)) - fieldWeight((f2.valueReader))})) { out.append(" && ") out.appendName(loader).append(" == ").append("other.").appendName(loader) } out.newLine() } private fun writeConstructorMethod(classScope: ClassScope, out: TextOutput) { out.append("init").block { if (fieldLoaders.isEmpty()) { out.append(READER_NAME).append(".skipValue()") } else { out.append("var ").append(NAME_VAR_NAME).append(" = preReadName") out.newLine().append("if (").append(NAME_VAR_NAME).append(" == null && reader.hasNext() && reader.beginObject().hasNext())").block { out.append(NAME_VAR_NAME).append(" = reader.nextName()") } out.newLine() writeReadFields(out, classScope) // we don't read all data if we have lazy fields, so, we should not check end of stream //if (!hasLazyFields) { out.newLine().newLine().append(READER_NAME).append(".endObject()") //} } } } private fun writeReadFields(out: TextOutput, classScope: ClassScope) { val stopIfAllFieldsWereRead = hasLazyFields val hasOnlyOneFieldLoader = fieldLoaders.size == 1 val isTracedStop = stopIfAllFieldsWereRead && !hasOnlyOneFieldLoader if (isTracedStop) { out.newLine().append("var i = 0") } out.newLine().append("loop@ while (").append(NAME_VAR_NAME).append(" != null)").block { (out + "when (" + NAME_VAR_NAME + ")").block { var isFirst = true for (fieldLoader in fieldLoaders) { if (fieldLoader.skipRead) { continue } if (!isFirst) { out.newLine() } out.append('"') if (fieldLoader.jsonName.first() == '$') { out.append('\\') } out.append(fieldLoader.jsonName).append('"').append(" -> ") if (stopIfAllFieldsWereRead && !isTracedStop) { out.openBlock() } val primitiveValueName = if (fieldLoader.valueReader is ObjectValueReader) fieldLoader.valueReader.primitiveValueName else null if (primitiveValueName != null) { out.append("if (reader.peek() == com.google.gson.stream.JsonToken.BEGIN_OBJECT)").openBlock() } out.appendName(fieldLoader).append(" = ") fieldLoader.valueReader.writeReadCode(classScope, false, out) if (primitiveValueName != null) { out.closeBlock().newLine().append("else").block { assignField(out, "${primitiveValueName}Type") out.append("reader.peek()").newLine() assignField(out, primitiveValueName) out + "reader.nextString(true)" } } if (stopIfAllFieldsWereRead && !isTracedStop) { out.newLine().append(READER_NAME).append(".skipValues()").newLine().append("break@loop").closeBlock() } if (isFirst) { isFirst = false } } out.newLine().append("else ->") if (isTracedStop) { out.block { out.append("reader.skipValue()") out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()" out.newLine() + "continue@loop" } } else { out.space().append("reader.skipValue()") } } out.newLine() + NAME_VAR_NAME + " = reader.nextNameOrNull()" if (isTracedStop) { out.newLine().newLine().append("if (i++ == ").append(fieldLoaders.size - 1).append(")").block { (out + READER_NAME + ".skipValues()").newLine() + "break" } } } } }
apache-2.0
8bd16b497abf05667371d6818ebce136
31.942085
206
0.61763
4.397423
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/ImagePreviewDialog.kt
1
6525
package org.wikipedia.views import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import androidx.core.os.bundleOf import com.google.android.material.bottomsheet.BottomSheetBehavior import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.R import org.wikipedia.commons.ImageTagsProvider import org.wikipedia.databinding.DialogImagePreviewBinding import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.descriptions.DescriptionEditActivity.Action import org.wikipedia.json.GsonMarshaller import org.wikipedia.json.GsonUnmarshaller import org.wikipedia.page.ExtendedBottomSheetDialogFragment import org.wikipedia.suggestededits.PageSummaryForEdit import org.wikipedia.util.DimenUtil import org.wikipedia.util.L10nUtil.setConditionalLayoutDirection import org.wikipedia.util.StringUtil import org.wikipedia.util.log.L class ImagePreviewDialog : ExtendedBottomSheetDialogFragment(), DialogInterface.OnDismissListener { private var _binding: DialogImagePreviewBinding? = null private val binding get() = _binding!! private lateinit var pageSummaryForEdit: PageSummaryForEdit private lateinit var action: Action private val disposables = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = DialogImagePreviewBinding.inflate(inflater, container, false) pageSummaryForEdit = GsonUnmarshaller.unmarshal(PageSummaryForEdit::class.java, requireArguments().getString(ARG_SUMMARY)) action = requireArguments().getSerializable(ARG_ACTION) as Action setConditionalLayoutDirection(binding.root, pageSummaryForEdit.lang) return binding.root } override fun onStart() { super.onStart() BottomSheetBehavior.from(requireView().parent as View).peekHeight = DimenUtil.roundedDpToPx(DimenUtil.getDimension(R.dimen.imagePreviewSheetPeekHeight)) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.progressBar.visibility = VISIBLE binding.toolbarView.setOnClickListener { dismiss() } binding.titleText.text = StringUtil.removeHTMLTags(StringUtil.removeNamespace(pageSummaryForEdit.displayTitle!!)) loadImageInfo() } override fun onDestroyView() { binding.toolbarView.setOnClickListener(null) _binding = null disposables.clear() super.onDestroyView() } private fun showError(caught: Throwable?) { binding.dialogDetailContainer.layoutTransition = null binding.dialogDetailContainer.minimumHeight = 0 binding.progressBar.visibility = GONE binding.filePageView.visibility = GONE binding.errorView.visibility = VISIBLE binding.errorView.setError(caught) } private fun loadImageInfo() { lateinit var imageTags: Map<String, List<String>> lateinit var page: MwQueryPage var isFromCommons = false var thumbnailWidth = 0 var thumbnailHeight = 0 disposables.add(ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getImageInfo(pageSummaryForEdit.title, pageSummaryForEdit.lang) .subscribeOn(Schedulers.io()) .flatMap { if (it.query()!!.pages()!![0].imageInfo() == null) { // If file page originally comes from *.wikipedia.org (i.e. movie posters), it will not have imageInfo and pageId. ServiceFactory.get(pageSummaryForEdit.pageTitle.wikiSite).getImageInfo(pageSummaryForEdit.title, pageSummaryForEdit.lang) } else { // Fetch API from commons.wikimedia.org and check whether if it is not a "shared" image. isFromCommons = !it.query()!!.pages()!![0].isImageShared Observable.just(it) } } .flatMap { response -> page = response.query()!!.pages()!![0] if (page.imageInfo() != null) { val imageInfo = page.imageInfo()!! pageSummaryForEdit.timestamp = imageInfo.timestamp pageSummaryForEdit.user = imageInfo.user pageSummaryForEdit.metadata = imageInfo.metadata thumbnailWidth = imageInfo.thumbWidth thumbnailHeight = imageInfo.thumbHeight } ImageTagsProvider.getImageTagsObservable(page.pageId(), pageSummaryForEdit.lang) } .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate { binding.filePageView.visibility = VISIBLE binding.progressBar.visibility = GONE binding.filePageView.setup( this, pageSummaryForEdit, imageTags, page, binding.dialogDetailContainer.width, thumbnailWidth, thumbnailHeight, imageFromCommons = isFromCommons, showFilename = false, showEditButton = false, action = action ) } .subscribe({ imageTags = it }, { caught -> L.e(caught) showError(caught) })) } companion object { private const val ARG_SUMMARY = "summary" private const val ARG_ACTION = "action" fun newInstance(pageSummaryForEdit: PageSummaryForEdit, action: Action): ImagePreviewDialog { val dialog = ImagePreviewDialog() dialog.arguments = bundleOf(ARG_SUMMARY to GsonMarshaller.marshal(pageSummaryForEdit), ARG_ACTION to action) return dialog } } }
apache-2.0
2d81bc46a43b8a85540dc8b9bc182f8c
44.3125
160
0.654559
5.543755
false
false
false
false
fyookball/electrum
android/app/src/main/java/org/electroncash/electroncash3/Exchange.kt
1
1563
package org.electroncash.electroncash3 import androidx.lifecycle.MediatorLiveData val EXCHANGE_CALLBACKS = setOf("on_quotes", "on_history") val libExchange by lazy { libMod("exchange_rate") } val fiatUpdate = MediatorLiveData<Unit>().apply { value = Unit } val fx by lazy { daemonModel.daemon.get("fx")!! } fun initExchange() { settings.getString("currency").observeForever { fx.callAttr("set_currency", it) } settings.getString("use_exchange").observeForever { fx.callAttr("set_exchange", it) } with (fiatUpdate) { addSource(settings.getBoolean("use_exchange_rate"), { value = Unit }) addSource(settings.getString("currency"), { value = Unit }) addSource(settings.getString("use_exchange"), { value = Unit }) } } fun formatFiatAmountAndUnit(amount: Long): String? { val amountStr = formatFiatAmount(amount) if (amountStr == null) { return null } else { return amountStr + " " + formatFiatUnit() } } fun formatSatoshisAndFiat(amount: Long): String { var result = formatSatoshisAndUnit(amount) val fiat = formatFiatAmountAndUnit(amount) if (fiat != null) { result += " ($fiat)" } return result } fun formatFiatAmount(amount: Long): String? { if (!fx.callAttr("is_enabled").toBoolean()) { return null } val amountStr = fx.callAttr("format_amount", amount).toString() return if (amountStr.isEmpty()) null else amountStr } fun formatFiatUnit(): String { return fx.callAttr("get_currency").toString() }
mit
c84a8b51a9ea39ec4f36d49750dc1204
25.508475
77
0.658989
3.878412
false
false
false
false
Heapy/kpress
kpress-engine/src/main/kotlin/io/heapy/kpress/application/AsciiDocEngine.kt
1
1734
package io.heapy.kpress.application import io.heapy.kpress.engine.extensions.logger import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.withContext import org.asciidoctor.Asciidoctor import org.asciidoctor.OptionsBuilder /** * Converts input data to html markup. * @author Ruslan Ibragimov */ class AsciiDocEngine( shutdownManager: ShutdownManager ) { init { shutdownManager.onShutdown("Asciidoctor") { if (asciidoctor.isActive || asciidoctor.isCompleted) { if (asciidoctor.isActive) LOGGER.info("Await Asciidoctor creation to stop Asciidoctor...") if (asciidoctor.isCompleted) LOGGER.info("Stopping asciidoctor...") asciidoctor.await().shutdown() LOGGER.info("Thanks Matsumoto, Asciidoctor stopped") } if (!asciidoctor.isActive && !asciidoctor.isCompleted) { LOGGER.info("Lucky, looks like you doesn't used Asciidoctor this time") } } } private val asciidoctor = GlobalScope.async(Dispatchers.IO, start = CoroutineStart.LAZY) { LOGGER.info("Creating asciidoctor... May take a while") Asciidoctor.Factory.create().also { LOGGER.info("Allons-y! Asciidoctor ${it.asciidoctorVersion()} created!") } } suspend fun convert(content: String): String = withContext(Dispatchers.IO) { val optionsBuilder = OptionsBuilder.options().inPlace(false) asciidoctor.await().convert(content, optionsBuilder) } companion object { private val LOGGER = logger<AsciiDocEngine>() } }
gpl-3.0
a7ec2a0ccf4f6d650215c2649a3c233b
33
106
0.680507
4.198547
false
false
false
false
mcdimus/mate-wp
src/main/kotlin/ee/mcdimus/matewp/service/BingPhotoOfTheDayService.kt
1
1769
package ee.mcdimus.matewp.service import ee.mcdimus.matewp.model.ImageData import org.json.simple.JSONArray import org.json.simple.JSONObject import org.json.simple.JSONValue import org.json.simple.parser.ParseException import java.net.URL /** * @author Dmitri Maksimov */ class BingPhotoOfTheDayService { companion object { private const val BING_PHOTO_OF_THE_DAY_URL = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US" private const val START_DATE = "startdate" private const val COPYRIGHT = "copyright" private const val URL_BASE = "urlbase" private const val IMAGES = "images" } fun getData(): ImageData { val url = URL(BING_PHOTO_OF_THE_DAY_URL) val conn = url.openConnection() conn.inputStream.bufferedReader().use { try { val jsonObject = JSONValue.parseWithException(it) as JSONObject validateProperties(jsonObject, listOf(IMAGES)) val images = jsonObject[IMAGES] as JSONArray if (images.isEmpty()) { throw IllegalStateException("'$IMAGES' is empty") } val image = images[0] as JSONObject validateProperties(image, listOf(START_DATE, COPYRIGHT, URL_BASE)) return ImageData( startDate = image[START_DATE] as String, copyright = image[COPYRIGHT] as String, urlBase = image[URL_BASE] as String ) } catch(e: ParseException) { throw IllegalStateException(e.message) } } } private fun validateProperties(jsonObject: JSONObject, properties: List<String>) { for (property in properties) { if (!jsonObject.contains(property)) { throw IllegalStateException("$jsonObject has no required property '$property'") } } } }
mit
4ca9869f0ccc87f0e368976204bc1dee
28.983051
121
0.673827
4.057339
false
false
false
false
spotify/heroic
heroic-elasticsearch-utils/src/main/java/com/spotify/heroic/elasticsearch/RestClientWrapper.kt
1
2898
/* * Copyright (c) 2020 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.elasticsearch import com.spotify.heroic.common.Duration import com.spotify.heroic.elasticsearch.index.IndexMapping import eu.toolchain.async.AsyncFramework import org.apache.http.HttpHost import org.elasticsearch.client.RestClient import org.elasticsearch.client.RestHighLevelClient import org.elasticsearch.client.sniff.Sniffer import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms import java.net.InetAddress import java.net.UnknownHostException import java.util.concurrent.TimeUnit private const val DEFAULT_PORT = 9200 data class RestClientWrapper @JvmOverloads constructor( val seeds: List<String> = listOf("localhost"), val sniff: Boolean = false, val sniffInterval: Duration = Duration.of(30, TimeUnit.SECONDS) ): ClientWrapper<ParsedStringTerms> { private val client = RestHighLevelClient(RestClient.builder(*parseSeeds())) private val sniffer: Sniffer? = if (sniff) { Sniffer.builder(client.lowLevelClient) .setSniffIntervalMillis(sniffInterval.toMilliseconds().toInt()) .build() } else { null } override fun start( async: AsyncFramework, index: IndexMapping, templateName: String, type: BackendType ): Connection<ParsedStringTerms> { return RestConnection(client, sniffer, async, index, templateName, type) } private fun parseSeeds(): Array<HttpHost> { return seeds .map(::parseInetSocketTransportAddress) .map {(host, port) -> HttpHost(host, port) } .toTypedArray() } private fun parseInetSocketTransportAddress(seed: String): Pair<InetAddress, Int> { try { if (seed.contains(":")) { val parts = seed.split(":") return InetAddress.getByName(parts.first()) to parts.last().toInt() } return InetAddress.getByName(seed) to DEFAULT_PORT } catch (e: UnknownHostException) { throw RuntimeException(e) } } }
apache-2.0
56fb33abad961321e31068313fd22547
34.790123
87
0.703934
4.371041
false
false
false
false
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter7/7.14.functions.kt
1
1087
package com.packt.chapter7 import kotlin.reflect.KClass import kotlin.reflect.declaredMemberExtensionFunctions import kotlin.reflect.functions import kotlin.reflect.memberFunctions import kotlin.reflect.memberProperties class Rocket() { var lat: Double = 0.0 var long: Double = 0.0 fun explode() { println("Boom") } fun setCourse(lat: Double, long: Double) { require(lat.isValid()) require(long.isValid()) this.lat = lat this.long = long } fun Double.isValid() = Math.abs(this) <= 180 } fun <T : Any> printFunctions(kclass: KClass<T>) { kclass.declaredMemberExtensionFunctions kclass.memberFunctions.forEach { println(it.name) } } fun <T : Any> printProperties(kclass: KClass<T>) { kclass.memberProperties.forEach { println(it.name) } } fun <T : Any> invokeExplodeFunction(kclass: KClass<T>) { val function = kclass.functions.find { it.name == "explode" } function?.call(Rocket()) } fun main(args: Array<String>) { printFunctions(Rocket::class) printProperties(Rocket::class) invokeExplodeFunction(Rocket::class) }
mit
e7f1be04c27ea3ed80badafbc2a09ec7
20.74
63
0.710212
3.575658
false
false
false
false
pflammertsma/cryptogram
app/src/main/java/com/pixplicity/cryptogram/models/PuzzleProgressState.kt
1
685
package com.pixplicity.cryptogram.models import com.google.gson.annotations.SerializedName import java.util.* class PuzzleProgressState { @SerializedName("current") var currentId: Int? = null private set @SerializedName("progress") private var mProgress: ArrayList<PuzzleProgress>? = null val progress: ArrayList<PuzzleProgress> get() { if (mProgress == null) { mProgress = ArrayList() } return mProgress!! } fun setCurrentId(puzzleId: Int) { currentId = puzzleId } fun addProgress(puzzleProgress: PuzzleProgress) { progress.add(puzzleProgress) } }
mit
f16af1c0fe4815d51be0ceada9f46e85
21.096774
60
0.629197
4.724138
false
false
false
false
vicboma1/GameBoyEmulatorEnvironment
src/main/kotlin/assets/table/model/TableModelImpl.kt
1
2097
package assets.table.model import assets.table.comparator.TableHeaderComparator import java.util.stream.IntStream import javax.swing.table.AbstractTableModel /** * Created by vbolinch on 02/01/2017. */ class TableModelImpl internal constructor(val columnNames : Array<Any>?, val data: Array<Array<Any>>?, var isEditable : Boolean = false ) : AbstractTableModel() { companion object { fun factoryArrayOf(size:Int, elements :Int) : Array<Array<Any>>? { return Array<Array<Any>>(size) { factoryArrayOf(elements) } } fun factoryArrayOf(elements :Int) : Array<Any> { val list = arrayListOf("") IntStream.range(0,elements-1).forEach { list.add("") } return list.toArray() } fun create(columnNames: Array<Any>?, data: Array<Array<Any>>?) = TableModelImpl(columnNames, data) fun create(columnNames: Int, size:Int, rows:Int) = TableModelImpl( factoryArrayOf(columnNames), factoryArrayOf(size,rows)) } init { } override fun getValueAt(rowIndex: Int, columnIndex: Int) : Any = data!![rowIndex][columnIndex] override fun getColumnCount(): Int = columnNames!!.size override fun getRowCount(): Int { if(data != null) return data.size; return 0 } override fun getColumnName(col: Int): String = columnNames!![col].toString() override fun getColumnClass(columnIndex: Int) : Class<*> = this.getValueAt(0, columnIndex).javaClass override fun isCellEditable(rowIndex: Int, columnIndex: Int) = isEditable override fun setValueAt(aValue: Any?, rowIndex: Int, columnIndex: Int) { data!![rowIndex][columnIndex] = aValue!! fireTableCellUpdated(rowIndex,columnIndex) } fun sortWith(cmp : TableHeaderComparator) = data?.sortWith(cmp) fun removeAll() { for (i in getRowCount() - 1 downTo 0) data!![i] = arrayOf() } fun toString(rowIndex: Int): String { return "${getValueAt(rowIndex,0)} ${getValueAt(rowIndex,1)} ${getValueAt(rowIndex,2)} ${getValueAt(rowIndex,3)} ${getValueAt(rowIndex,4)}" } }
lgpl-3.0
313b754ff6bd850b3b3e3cd7736d41a2
33.966667
162
0.668097
4.297131
false
false
false
false
phrase/Phrase-AndroidStudio
src/main/kotlin/com/phrase/intellij/PhraseBundle.kt
1
604
package com.phrase.intellij import com.intellij.AbstractBundle import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey @NonNls private const val BUNDLE = "messages.Phrase" object PhraseBundle : AbstractBundle(BUNDLE) { @Suppress("SpreadOperator") @JvmStatic fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) = getMessage(key, *params) @Suppress("SpreadOperator") @JvmStatic fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) = getLazyMessage(key, *params) }
bsd-3-clause
f66aa75caf521faa238585c7be6ab6ff
27.761905
95
0.745033
4.441176
false
false
false
false
airbnb/epoxy
epoxy-composeinterop-maverickssample/src/main/java/com/airbnb/epoxy/composeinterop/maverickssample/ComposeInteropListFragmnet.kt
1
3633
package com.airbnb.epoxy.composeinterop.maverickssample import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.text.ClickableText import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle import androidx.fragment.app.Fragment import com.airbnb.epoxy.EpoxyRecyclerView import com.airbnb.epoxy.TypedEpoxyController import com.airbnb.epoxy.composableInterop import com.airbnb.epoxy.composeinterop.maverickssample.epoxyviews.headerView import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.MavericksView import com.airbnb.mvrx.MavericksViewModel import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.withState data class CounterState( val counter: List<Int> = List(100) { it }, ) : MavericksState class HelloWorldViewModel(initialState: CounterState) : MavericksViewModel<CounterState>(initialState) { fun increase(index: Int) { withState { state -> val updatedCounterList = state.counter.mapIndexed { i, value -> if (i == index) value + 1 else value } setState { copy(counter = updatedCounterList) } } } } class ComposeInteropListFragmnet : Fragment(R.layout.fragment_my), MavericksView { private val viewModel by fragmentViewModel(HelloWorldViewModel::class) private val controller: MyEpoxyController by lazy { MyEpoxyController(viewModel) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = inflater.inflate(R.layout.fragment_my, container, false).apply { findViewById<EpoxyRecyclerView>(R.id.epoxyRecyclerView).apply { setController(controller) } } override fun invalidate() = withState(viewModel) { controller.setData(it) } } class MyEpoxyController(private val viewModel: HelloWorldViewModel) : TypedEpoxyController<CounterState>() { private fun annotatedString(str: String) = buildAnnotatedString { withStyle( style = SpanStyle(fontWeight = FontWeight.Bold) ) { append(str) } } override fun buildModels(state: CounterState) { state.counter.forEachIndexed { index, counterValue -> composableInterop("$index", counterValue) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { TextFromCompose(counterValue) { [email protected](index) } } } headerView { id(index) title("Text from normal epoxy model: $counterValue") clickListener { _ -> [email protected](index) } } } } @Composable fun TextFromCompose(counterValue: Int, onClick: () -> Unit) { ClickableText( text = annotatedString("Text from composable interop $counterValue"), onClick = { onClick() } ) } }
apache-2.0
80f1723fea74bffe5eb9b4f727434bfc
31.72973
93
0.666942
4.824701
false
false
false
false
paplorinc/intellij-community
python/src/com/jetbrains/python/inspections/PyThirdPartyInspectionExtension.kt
1
2218
// 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.jetbrains.python.inspections import com.intellij.util.containers.ContainerUtil import com.jetbrains.python.codeInsight.stdlib.PyDataclassParameters import com.jetbrains.python.codeInsight.stdlib.parseDataclassParameters import com.jetbrains.python.psi.PyElement import com.jetbrains.python.psi.PyExpression import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyUtil import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.QualifiedNameFinder import com.jetbrains.python.psi.types.PyClassType import com.jetbrains.python.psi.types.PyType import com.jetbrains.python.psi.types.TypeEvalContext class PyThirdPartyInspectionExtension : PyInspectionExtension() { override fun ignoreMethodParameters(function: PyFunction, context: TypeEvalContext): Boolean { val cls = function.containingClass if (cls != null) { // zope.interface.Interface inheritor could have any parameters val interfaceQName = "zope.interface.interface.Interface" if (cls.isSubclass(interfaceQName, context)) return true // Checking for subclassing above does not help while zope.interface.Interface is defined as target with call expression assigned val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context) for (expression in cls.superClassExpressions) { if (resolvesTo(expression, interfaceQName, resolveContext)) return true } } return false } override fun ignoreUnresolvedMember(type: PyType, name: String, context: TypeEvalContext): Boolean { return name == "__attrs_attrs__" && type is PyClassType && parseDataclassParameters(type.pyClass, context)?.type == PyDataclassParameters.Type.ATTRS } private fun resolvesTo(expression: PyExpression, qualifiedName: String, resolveContext: PyResolveContext): Boolean { return ContainerUtil.exists(PyUtil.multiResolveTopPriority(expression, resolveContext)) { it is PyElement && QualifiedNameFinder.getQualifiedName(it) == qualifiedName } } }
apache-2.0
1b867215dc83d93563cd4fe4d14b4e7c
46.212766
140
0.782236
4.790497
false
false
false
false
vladmm/intellij-community
platform/platform-impl/src/org/jetbrains/io/netty.kt
1
2737
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.io import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Conditions import io.netty.bootstrap.Bootstrap import io.netty.channel.* import io.netty.channel.oio.OioEventLoopGroup import io.netty.channel.socket.oio.OioSocketChannel import io.netty.util.concurrent.GenericFutureListener import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.ide.PooledThreadExecutor import java.net.InetSocketAddress import java.util.concurrent.TimeUnit inline fun Bootstrap.handler(crossinline task: (Channel) -> Unit): Bootstrap { handler(object : ChannelInitializer<Channel>() { override fun initChannel(channel: Channel) { task(channel) } }) return this } fun oioClientBootstrap(): Bootstrap { val bootstrap = Bootstrap().group(OioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(OioSocketChannel::class.java) bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true) return bootstrap } inline fun ChannelFuture.addListener(crossinline listener: (future: ChannelFuture) -> Unit) { addListener(object : GenericFutureListener<ChannelFuture> { override fun operationComplete(future: ChannelFuture) { listener(future) } }) } // if NIO, so, it is shared and we must not shutdown it fun EventLoop.shutdownIfOio() { if (this is OioEventLoopGroup) { @Suppress("USELESS_CAST") (this as OioEventLoopGroup).shutdownGracefully(1L, 2L, TimeUnit.NANOSECONDS) } } // Event loop will be shut downed only if OIO fun Channel.closeAndShutdownEventLoop() { val eventLoop = eventLoop() try { close().awaitUninterruptibly() } finally { eventLoop.shutdownIfOio() } } @JvmOverloads fun Bootstrap.connect(remoteAddress: InetSocketAddress, promise: AsyncPromise<*>? = null, maxAttemptCount: Int = NettyUtil.DEFAULT_CONNECT_ATTEMPT_COUNT, stopCondition: Condition<Void>? = null): Channel? { try { return NettyUtil.doConnect(this, remoteAddress, promise, maxAttemptCount, stopCondition ?: Conditions.alwaysFalse<Void>()) } catch (e: Throwable) { promise?.setError(e) return null } }
apache-2.0
4bd46b327b531e9205dbafe6f2fc22ac
32.802469
205
0.757764
4.283255
false
false
false
false
imageprocessor/cv4j
app/src/main/java/com/cv4j/app/activity/pixels/ArithmeticAndLogicOperationActivity.kt
1
3344
package com.cv4j.app.activity.pixels import android.content.Intent import android.os.Bundle import com.cv4j.app.R import com.cv4j.app.app.BaseActivity import kotlinx.android.synthetic.main.activity_arithmetic_and_logic_operator.* /** * * @FileName: * com.cv4j.app.activity.pixels.ArithmeticAndLogicOperationActivity * @author: Tony Shen * @date: 2020-05-04 22:18 * @version: V1.0 <描述当前版本功能> */ class ArithmeticAndLogicOperationActivity : BaseActivity() { var title: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_arithmetic_and_logic_operator) intent.extras?.let { title = it.getString("Title","") }?:{ title = "" }() toolbar.setOnClickListener { finish() } text1.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text1.text.toString()) i.putExtra("Type", PixelOperatorActivity.ADD) startActivity(i) } text2.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text2.text.toString()) i.putExtra("Type", PixelOperatorActivity.SUBSTRACT) startActivity(i) } text3.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text3.text.toString()) i.putExtra("Type", PixelOperatorActivity.MULTIPLE) startActivity(i) } text4.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text4.text.toString()) i.putExtra("Type", PixelOperatorActivity.DIVISION) startActivity(i) } text5.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text5.text.toString()) i.putExtra("Type", PixelOperatorActivity.BITWISE_AND) startActivity(i) } text6.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text6.text.toString()) i.putExtra("Type", PixelOperatorActivity.BITWISE_OR) startActivity(i) } text7.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text7.text.toString()) i.putExtra("Type", PixelOperatorActivity.BITWISE_NOT) startActivity(i) } text8.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text8.text.toString()) i.putExtra("Type", PixelOperatorActivity.BITWISE_XOR) startActivity(i) } text9.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text9!!.text.toString()) i.putExtra("Type", PixelOperatorActivity.ADD_WEIGHT) startActivity(i) } initData() } private fun initData() { toolbar.title = "< $title" } }
apache-2.0
9546a2def42130cb680a2cedc22c1aed
30.704762
78
0.604567
4.431425
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ArchiveDiskAction.kt
1
1345
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.objectweb.asm.Type @DependsOn(Node::class, ArchiveDisk::class) class ArchiveDiskAction : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Node>() } .and { it.instanceFields.any { it.type == type<ArchiveDisk>() } } @DependsOn(ArchiveDisk::class) class archiveDisk : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<ArchiveDisk>() } } @DependsOn(Archive::class) class archive : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<Archive>() } } class data : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == ByteArray::class.type } } class type : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == Type.INT_TYPE } } }
mit
fccd2066148f0830c64d8d23c55e6127
38.588235
89
0.727138
4.075758
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/TrailingCommaInspection.kt
2
11560
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.intention.FileModifier import com.intellij.codeInspection.* import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel import com.intellij.codeInspection.util.InspectionMessage import com.intellij.codeInspection.util.IntentionFamilyName import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.CodeStyleSettingsManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.formatter.TrailingCommaVisitor import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaContext import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaState import org.jetbrains.kotlin.idea.formatter.trailingComma.addTrailingCommaIsAllowedFor import org.jetbrains.kotlin.idea.formatter.trailingCommaAllowedInModule import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.idea.util.isComma import org.jetbrains.kotlin.idea.util.isLineBreak import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import javax.swing.JComponent import kotlin.properties.Delegates class TrailingCommaInspection( @JvmField var addCommaWarning: Boolean = false ) : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : TrailingCommaVisitor() { override val recursively: Boolean = false private var useTrailingComma by Delegates.notNull<Boolean>() override fun process(trailingCommaContext: TrailingCommaContext) { val element = trailingCommaContext.ktElement val kotlinCustomSettings = element.containingKtFile.kotlinCustomSettings useTrailingComma = kotlinCustomSettings.addTrailingCommaIsAllowedFor(element) when (trailingCommaContext.state) { TrailingCommaState.MISSING, TrailingCommaState.EXISTS -> { checkCommaPosition(element) checkLineBreaks(element) } else -> Unit } checkTrailingComma(trailingCommaContext) } private fun checkLineBreaks(commaOwner: KtElement) { val first = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) if (first?.nextLeaf(true)?.isLineBreak() == false) { first.nextSibling?.let { registerProblemForLineBreak(commaOwner, it, ProblemHighlightType.INFORMATION) } } val last = TrailingCommaHelper.elementAfterLastElement(commaOwner) if (last?.prevLeaf(true)?.isLineBreak() == false) { registerProblemForLineBreak( commaOwner, last, if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION, ) } } private fun checkCommaPosition(commaOwner: KtElement) { for (invalidComma in TrailingCommaHelper.findInvalidCommas(commaOwner)) { reportProblem( invalidComma, KotlinBundle.message("inspection.trailing.comma.comma.loses.the.advantages.in.this.position"), KotlinBundle.message("inspection.trailing.comma.fix.comma.position") ) } } private fun checkTrailingComma(trailingCommaContext: TrailingCommaContext) { val commaOwner = trailingCommaContext.ktElement val trailingCommaOrLastElement = TrailingCommaHelper.trailingCommaOrLastElement(commaOwner) ?: return when (trailingCommaContext.state) { TrailingCommaState.MISSING -> { if (!trailingCommaAllowedInModule(commaOwner)) return reportProblem( trailingCommaOrLastElement, KotlinBundle.message("inspection.trailing.comma.missing.trailing.comma"), KotlinBundle.message("inspection.trailing.comma.add.trailing.comma"), if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION, ) } TrailingCommaState.REDUNDANT -> { reportProblem( trailingCommaOrLastElement, KotlinBundle.message("inspection.trailing.comma.useless.trailing.comma"), KotlinBundle.message("inspection.trailing.comma.remove.trailing.comma"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, checkTrailingCommaSettings = false, ) } else -> Unit } } private fun reportProblem( commaOrElement: PsiElement, @InspectionMessage message: String, @IntentionFamilyName fixMessage: String, highlightType: ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING, checkTrailingCommaSettings: Boolean = true, ) { val commaOwner = commaOrElement.parent as KtElement // case for KtFunctionLiteral, where PsiWhiteSpace after KtTypeParameterList isn't included in this list val problemOwner = commonParent(commaOwner, commaOrElement) val highlightTypeWithAppliedCondition = highlightType.applyCondition(!checkTrailingCommaSettings || useTrailingComma) // INFORMATION shouldn't be reported in batch mode if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) { holder.registerProblem( problemOwner, message, highlightTypeWithAppliedCondition, commaOrElement.textRangeOfCommaOrSymbolAfter.shiftLeft(problemOwner.startOffset), createQuickFix(fixMessage, commaOwner), ) } } private fun registerProblemForLineBreak( commaOwner: KtElement, elementForTextRange: PsiElement, highlightType: ProblemHighlightType, ) { val problemElement = commonParent(commaOwner, elementForTextRange) val highlightTypeWithAppliedCondition = highlightType.applyCondition(useTrailingComma) // INFORMATION shouldn't be reported in batch mode if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) { holder.registerProblem( problemElement, KotlinBundle.message("inspection.trailing.comma.missing.line.break"), highlightTypeWithAppliedCondition, TextRange.from(elementForTextRange.startOffset, 1).shiftLeft(problemElement.startOffset), createQuickFix(KotlinBundle.message("inspection.trailing.comma.add.line.break"), commaOwner), ) } } private fun commonParent(commaOwner: PsiElement, elementForTextRange: PsiElement): PsiElement = PsiTreeUtil.findCommonParent(commaOwner, elementForTextRange) ?: throw KotlinExceptionWithAttachments("Common parent not found") .withPsiAttachment("commaOwner", commaOwner) .withAttachment("commaOwnerRange", commaOwner.textRange) .withPsiAttachment("elementForTextRange", elementForTextRange) .withAttachment("elementForTextRangeRange", elementForTextRange.textRange) .withPsiAttachment("parent", commaOwner.parent) .withAttachment("parentRange", commaOwner.parent.textRange) private fun ProblemHighlightType.applyCondition(condition: Boolean): ProblemHighlightType = when { isUnitTestMode() -> ProblemHighlightType.GENERIC_ERROR_OR_WARNING condition -> this else -> ProblemHighlightType.INFORMATION } private fun createQuickFix( @IntentionFamilyName fixMessage: String, commaOwner: KtElement, ): LocalQuickFix = ReformatTrailingCommaFix(commaOwner, fixMessage) private val PsiElement.textRangeOfCommaOrSymbolAfter: TextRange get() { val textRange = textRange if (isComma) return textRange return nextLeaf()?.leafIgnoringWhitespaceAndComments(false)?.endOffset?.takeIf { it > 0 }?.let { TextRange.create(it - 1, it).intersection(textRange) } ?: TextRange.create(textRange.endOffset - 1, textRange.endOffset) } } override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel( KotlinBundle.message("inspection.trailing.comma.report.also.a.missing.comma"), this, "addCommaWarning", ) class ReformatTrailingCommaFix(commaOwner: KtElement, @IntentionFamilyName private val fixMessage: String) : LocalQuickFix { val commaOwnerPointer = commaOwner.createSmartPointer() override fun getFamilyName(): String = fixMessage override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) { val element = commaOwnerPointer.element ?: return val range = createFormatterTextRange(element) val settings = CodeStyleSettingsManager.getInstance(project).cloneSettings(CodeStyle.getSettings(element.containingKtFile)) settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA = true settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA_ON_CALL_SITE = true CodeStyle.doWithTemporarySettings(project, settings, Runnable { CodeStyleManager.getInstance(project).reformatRange(element, range.startOffset, range.endOffset) }) } private fun createFormatterTextRange(commaOwner: KtElement): TextRange { val startElement = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) ?: commaOwner val endElement = TrailingCommaHelper.elementAfterLastElement(commaOwner) ?: commaOwner return TextRange.create(startElement.startOffset, endElement.endOffset) } override fun getFileModifierForPreview(target: PsiFile): FileModifier? { val element = commaOwnerPointer.element ?: return null return ReformatTrailingCommaFix(PsiTreeUtil.findSameElementInCopy(element, target), fixMessage) } } }
apache-2.0
147dce210400fff2e0cde974997bc81f
50.838565
158
0.682699
6.262189
false
false
false
false
boxtape/boxtape-cli
boxtape-cli/src/main/java/io/boxtape/cli/core/MavenDependencyCollector.kt
1
1741
package io.boxtape.cli.core import io.boxtape.core.LibraryArtifact import io.boxtape.cli.core.Project import org.apache.maven.cli.MavenCli import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.io.ByteArrayOutputStream import java.io.File import java.io.PrintStream import java.util.regex.Pattern @Component public class MavenDependencyCollector @Autowired constructor(val mvn: MavenCli):DependencyCollector { val ALPHA_CHARACTER = Pattern.compile("[a-zA-Z]"); val GROUP_ID = 0 val ARTIFACT_ID = 1 val VERSION = 3 override fun collect(project: Project):List<LibraryArtifact> { if (!project.hasFile("pom.xml")) { return listOf() } project.console.info("Reading your maven pom for dependencies") val outputStream = ByteArrayOutputStream() val printStream = PrintStream(outputStream) val outputFile = File.createTempFile("dependencies", ".txt") System.setProperty("maven.multiModuleProjectDirectory" , project.projectHome().canonicalPath) mvn.doMain(arrayOf("dependency:tree","-Dscope=compile", "-DoutputFile=${outputFile.getCanonicalPath()}"), project.projectHome().canonicalPath, printStream, printStream) val output = outputFile.readLines() .map { trimTreeSyntax(it) } .map { val parts = it.splitBy(":") LibraryArtifact(parts[GROUP_ID], parts[ARTIFACT_ID], parts[VERSION]) } return output } private fun trimTreeSyntax(line: String): String { val matcher = ALPHA_CHARACTER.matcher(line) return if (matcher.find()) line.substring(matcher.start()) else "" } }
apache-2.0
79f0efcdb291d7403333772f6787f3d6
35.270833
176
0.692705
4.487113
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/PortableCompilationCache.kt
1
11459
// 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.intellij.build.impl.compilation import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.NioFiles import org.jetbrains.intellij.build.CompilationContext import org.jetbrains.intellij.build.CompilationTasks import org.jetbrains.intellij.build.impl.JpsCompilationRunner import org.jetbrains.intellij.build.impl.compilation.cache.CommitsHistory import org.jetbrains.jps.incremental.storage.ProjectStamps import java.nio.file.Files import java.nio.file.Path import java.util.* class PortableCompilationCache(private val context: CompilationContext) { companion object { @JvmStatic val IS_ENABLED = ProjectStamps.PORTABLE_CACHES && IS_CONFIGURED private var isAlreadyUpdated = false } init { require(IS_ENABLED) { "JPS Caches are expected to be enabled" } } private val git = Git(context.paths.projectHome) /** * JPS data structures allowing incremental compilation for [CompilationOutput] */ private class JpsCaches(context: CompilationContext) { val skipDownload = bool(SKIP_DOWNLOAD_PROPERTY) val skipUpload = bool(SKIP_UPLOAD_PROPERTY) val dir: Path by lazy { context.compilationData.dataStorageRoot } val maybeAvailableLocally: Boolean by lazy { val files = dir.toFile().list() context.messages.info("$dir: ${files.joinToString()}") Files.isDirectory(dir) && files != null && files.isNotEmpty() } } /** * Server which stores [PortableCompilationCache] */ internal class RemoteCache(context: CompilationContext) { val url by lazy { require(URL_PROPERTY, "Remote Cache url", context) } val uploadUrl by lazy { require(UPLOAD_URL_PROPERTY, "Remote Cache upload url", context) } val authHeader by lazy { val username = System.getProperty("jps.auth.spaceUsername") val password = System.getProperty("jps.auth.spacePassword") when { password == null -> "" username == null -> "Bearer $password" else -> "Basic " + Base64.getEncoder().encodeToString("$username:$password".toByteArray()) } } } private val forceDownload = bool(FORCE_DOWNLOAD_PROPERTY) private val forceRebuild = bool(FORCE_REBUILD_PROPERTY) private val remoteCache = RemoteCache(context) private val jpsCaches by lazy { JpsCaches(context) } private val remoteGitUrl by lazy { val result = require(GIT_REPOSITORY_URL_PROPERTY, "Repository url", context) context.messages.info("Git remote url $result") result } private val downloader by lazy { val availableForHeadCommit = bool(AVAILABLE_FOR_HEAD_PROPERTY) PortableCompilationCacheDownloader(context, git, remoteCache, remoteGitUrl, availableForHeadCommit, jpsCaches.skipDownload) } private val uploader by lazy { val s3Folder = require(AWS_SYNC_FOLDER_PROPERTY, "AWS S3 sync folder", context) val commitHash = require(COMMIT_HASH_PROPERTY, "Repository commit", context) PortableCompilationCacheUploader(context, remoteCache, remoteGitUrl, commitHash, s3Folder, jpsCaches.skipUpload, forceRebuild) } /** * Download the latest available [PortableCompilationCache], * [org.jetbrains.intellij.build.CompilationTasks.resolveProjectDependencies] * and perform incremental compilation if necessary. * * When force rebuilding incremental compilation flag has to be set to false otherwise backward-refs won't be created. * During rebuild JPS checks condition [org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex.exists] || [org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.isRebuildInAllJavaModules] * and if incremental compilation is enabled JPS won't create [org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter]. * For more details see [org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.initialize] */ fun downloadCacheAndCompileProject() { synchronized(PortableCompilationCache) { if (isAlreadyUpdated) { context.messages.info("PortableCompilationCache is already updated") return } if (forceRebuild || forceDownload) { clean() } if (!forceRebuild && !isLocalCacheUsed()) { downloadCache() } CompilationTasks.create(context).resolveProjectDependencies() if (isCompilationRequired()) { context.options.incrementalCompilation = !forceRebuild context.messages.block("Compiling project") { compileProject(context) } } isAlreadyUpdated = true context.options.incrementalCompilation = true } } private fun isCompilationRequired() = forceRebuild || isLocalCacheUsed() || isRemoteCacheStale() private fun isLocalCacheUsed() = !forceRebuild && !forceDownload && jpsCaches.maybeAvailableLocally private fun isRemoteCacheStale() = !downloader.availableForHeadCommit /** * Upload local [PortableCompilationCache] to [PortableCompilationCache.RemoteCache] */ fun upload() { if (!forceRebuild && downloader.availableForHeadCommit) { context.messages.info("Nothing new to upload") } else { uploader.upload(context.messages) } val metadataFile = context.paths.artifactDir.resolve(COMPILATION_CACHE_METADATA_JSON) Files.createDirectories(metadataFile.parent) Files.writeString(metadataFile, "This is stub file required only for TeamCity artifact dependency. " + "Compiled classes will be resolved via ${remoteCache.url}") context.messages.artifactBuilt("$metadataFile") } /** * Publish already uploaded [PortableCompilationCache] to [PortableCompilationCache.RemoteCache] */ fun publish() { uploader.updateCommitHistory() } /** * Publish already uploaded [PortableCompilationCache] to [PortableCompilationCache.RemoteCache] overriding existing [CommitsHistory]. * Used in force rebuild and cleanup. */ fun overrideCommitHistory(forceRebuiltCommits: Set<String>) { uploader.updateCommitHistory(CommitsHistory(mapOf(remoteGitUrl to forceRebuiltCommits)), true) } private fun clean() { for (it in listOf(jpsCaches.dir, context.classesOutputDirectory)) { context.messages.info("Cleaning $it") NioFiles.deleteRecursively(it) } } private fun compileProject(context: CompilationContext) { // fail-fast in case of KTIJ-17296 if (SystemInfoRt.isWindows && git.lineBreaksConfig() != "input") { context.messages.error("PortableCompilationCache cannot be used with CRLF line breaks, " + "please execute `git config --global core.autocrlf input` before checkout " + "and upvote https://youtrack.jetbrains.com/issue/KTIJ-17296") } context.compilationData.statisticsReported = false val jps = JpsCompilationRunner(context) try { jps.buildAll() } catch (e: Exception) { if (!context.options.incrementalCompilation) { throw e } val successMessage: String if (forceDownload) { context.messages.warning("Incremental compilation using Remote Cache failed. Re-trying without any caches.") clean() context.options.incrementalCompilation = false successMessage = "Compilation successful after clean build retry" } else { // Portable Compilation Cache is rebuilt from scratch on CI and re-published every night to avoid possible incremental compilation issues. // If download isn't forced then locally available cache will be used which may suffer from those issues. // Hence, compilation failure. Replacing local cache with remote one may help. context.messages.warning("Incremental compilation using locally available caches failed. Re-trying using Remote Cache.") downloadCache() successMessage = "Compilation successful after retry with fresh Remote Cache" } context.compilationData.reset() jps.buildAll() context.messages.info(successMessage) println("##teamcity[buildStatus status='SUCCESS' text='$successMessage']") context.messages.reportStatisticValue("Incremental compilation failures", "1") } } private fun downloadCache() { context.messages.block("Downloading Portable Compilation Cache") { downloader.download() } } } /** * [PortableCompilationCache.JpsCaches] archive upload may be skipped if only [CompilationOutput]s are required * without any incremental compilation (for tests execution as an example) */ private const val SKIP_UPLOAD_PROPERTY = "intellij.jps.remote.cache.uploadCompilationOutputsOnly" /** * [PortableCompilationCache.JpsCaches] archive download may be skipped if only [CompilationOutput]s are required * without any incremental compilation (for tests execution as an example) */ private const val SKIP_DOWNLOAD_PROPERTY = "intellij.jps.remote.cache.downloadCompilationOutputsOnly" /** * URL for read/write operations */ private const val UPLOAD_URL_PROPERTY = "intellij.jps.remote.cache.upload.url" /** * URL for read-only operations */ private const val URL_PROPERTY = "intellij.jps.remote.cache.url" /** * If true then [PortableCompilationCache.RemoteCache] is configured to be used */ private val IS_CONFIGURED = !System.getProperty(URL_PROPERTY).isNullOrBlank() /** * IntelliJ repository git remote url */ private const val GIT_REPOSITORY_URL_PROPERTY = "intellij.remote.url" /** * If true then [PortableCompilationCache] for head commit is expected to exist and search in [CommitsHistory.JSON_FILE] is skipped. * Required for temporary branch caches which are uploaded but not published in [CommitsHistory.JSON_FILE]. */ private const val AVAILABLE_FOR_HEAD_PROPERTY = "intellij.jps.cache.availableForHeadCommit" /** * Download [PortableCompilationCache] even if there are caches available locally */ private const val FORCE_DOWNLOAD_PROPERTY = "intellij.jps.cache.download.force" /** * If true then [PortableCompilationCache] will be rebuilt from scratch */ private const val FORCE_REBUILD_PROPERTY = "intellij.jps.cache.rebuild.force" /** * Folder to store [PortableCompilationCache] for later upload to AWS S3 bucket. * Upload performed in a separate process on CI. */ private const val AWS_SYNC_FOLDER_PROPERTY = "jps.caches.aws.sync.folder" /** * Commit hash for which [PortableCompilationCache] is to be built/downloaded */ private const val COMMIT_HASH_PROPERTY = "build.vcs.number" private fun require(systemProperty: String, description: String, context: CompilationContext): String { val value = System.getProperty(systemProperty) if (value.isNullOrBlank()) { context.messages.error("$description is not defined. Please set '$systemProperty' system property.") } return value } private fun bool(systemProperty: String): Boolean { return System.getProperty(systemProperty).toBoolean() } /** * Compiled bytecode of project module, cannot be used for incremental compilation without [PortableCompilationCache.JpsCaches] */ internal class CompilationOutput( name: String, type: String, @JvmField val hash: String, // Some hash of compilation output, could be non-unique across different CompilationOutput's @JvmField val path: String, // Local path to compilation output ) { val remotePath = "$type/$name/$hash" }
apache-2.0
fc24dfeb11c0c25420f4769eaa2d4891
38.650519
204
0.732786
4.469189
false
false
false
false
apollographql/apollo-android
apollo-runtime/src/commonMain/kotlin/com/apollographql/apollo3/network/http/HttpNetworkTransport.kt
1
6587
package com.apollographql.apollo3.network.http import com.apollographql.apollo3.api.ApolloRequest import com.apollographql.apollo3.api.ApolloResponse import com.apollographql.apollo3.api.CustomScalarAdapters import com.apollographql.apollo3.api.Operation import com.apollographql.apollo3.api.http.DefaultHttpRequestComposer import com.apollographql.apollo3.api.http.HttpHeader import com.apollographql.apollo3.api.http.HttpRequest import com.apollographql.apollo3.api.http.HttpRequestComposer import com.apollographql.apollo3.api.http.HttpResponse import com.apollographql.apollo3.api.json.jsonReader import com.apollographql.apollo3.api.parseJsonResponse import com.apollographql.apollo3.exception.ApolloException import com.apollographql.apollo3.exception.ApolloHttpException import com.apollographql.apollo3.exception.ApolloParseException import com.apollographql.apollo3.internal.NonMainWorker import com.apollographql.apollo3.mpp.currentTimeMillis import com.apollographql.apollo3.network.NetworkTransport import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class HttpNetworkTransport private constructor( private val httpRequestComposer: HttpRequestComposer, val engine: HttpEngine, val interceptors: List<HttpInterceptor>, val exposeErrorBody: Boolean ) : NetworkTransport { private val worker = NonMainWorker() private val engineInterceptor = EngineInterceptor() override fun <D : Operation.Data> execute( request: ApolloRequest<D>, ): Flow<ApolloResponse<D>> { val customScalarAdapters = request.executionContext[CustomScalarAdapters]!! val httpRequest = httpRequestComposer.compose(request) return execute(request, httpRequest, customScalarAdapters) } fun <D : Operation.Data> execute( request: ApolloRequest<D>, httpRequest: HttpRequest, customScalarAdapters: CustomScalarAdapters, ): Flow<ApolloResponse<D>> { return flow { val millisStart = currentTimeMillis() val httpResponse = DefaultHttpInterceptorChain( interceptors = interceptors + engineInterceptor, index = 0 ).proceed(httpRequest) if (httpResponse.statusCode !in 200..299) { val maybeBody = if (exposeErrorBody) { httpResponse.body } else { httpResponse.body?.close() null } throw ApolloHttpException( statusCode = httpResponse.statusCode, headers = httpResponse.headers, body = maybeBody, message = "Http request failed with status code `${httpResponse.statusCode}`" ) } // do not capture request val operation = request.operation val response = worker.doWork { try { operation.parseJsonResponse( jsonReader = httpResponse.body!!.jsonReader(), customScalarAdapters = customScalarAdapters ) } catch (e: Exception) { throw wrapThrowableIfNeeded(e) } } emit( response.newBuilder() .requestUuid(request.requestUuid) .addExecutionContext( HttpInfo( millisStart = millisStart, millisEnd = currentTimeMillis(), statusCode = httpResponse.statusCode, headers = httpResponse.headers ) ) .build() ) } } inner class EngineInterceptor : HttpInterceptor { override suspend fun intercept(request: HttpRequest, chain: HttpInterceptorChain): HttpResponse { return engine.execute(request) } } override fun dispose() { interceptors.forEach { it.dispose() } engine.dispose() } /** * Creates a new Builder that shares the underlying resources * * Calling [dispose] on the original instance or the new one will terminate the [engine] for both instances */ fun newBuilder(): Builder { return Builder() .httpEngine(engine) .interceptors(interceptors) .httpRequestComposer(httpRequestComposer) } /** * A builder for [HttpNetworkTransport] */ class Builder { private var httpRequestComposer: HttpRequestComposer? = null private var serverUrl: String? = null private var engine: HttpEngine? = null private val interceptors: MutableList<HttpInterceptor> = mutableListOf() private var exposeErrorBody: Boolean = false fun httpRequestComposer(httpRequestComposer: HttpRequestComposer) = apply { this.httpRequestComposer = httpRequestComposer } fun serverUrl(serverUrl: String) = apply { this.serverUrl = serverUrl } /** * Configures whether to expose the error body in [ApolloHttpException]. * * If you're setting this to `true`, you **must** catch [ApolloHttpException] and close the body explicitly * to avoid sockets and other resources leaking. * * Default: false */ fun exposeErrorBody(exposeErrorBody: Boolean) = apply { this.exposeErrorBody = exposeErrorBody } fun httpHeaders(headers: List<HttpHeader>) = apply { interceptors.add(HeadersInterceptor(headers)) } fun httpEngine(httpEngine: HttpEngine) = apply { this.engine = httpEngine } fun interceptors(interceptors: List<HttpInterceptor>) = apply { this.interceptors.clear() this.interceptors.addAll(interceptors) } fun addInterceptor(interceptor: HttpInterceptor) = apply { this.interceptors.add(interceptor) } fun build(): HttpNetworkTransport { check (httpRequestComposer == null || serverUrl == null) { "It is an error to set both 'httpRequestComposer' and 'serverUrl'" } val composer = httpRequestComposer ?: serverUrl?.let { DefaultHttpRequestComposer(it) } ?: error("No HttpRequestComposer found. Use 'httpRequestComposer' or 'serverUrl'") return HttpNetworkTransport( httpRequestComposer = composer, engine = engine ?: DefaultHttpEngine(), interceptors = interceptors, exposeErrorBody = exposeErrorBody, ) } } companion object { private fun wrapThrowableIfNeeded(throwable: Throwable): ApolloException { return if (throwable is ApolloException) { throwable } else { // This happens for null pointer exceptions on missing fields ApolloParseException( message = "Failed to parse GraphQL http network response", cause = throwable ) } } } }
mit
0864459dace1b9ff33657773c685bea1
32.100503
111
0.682557
5.05138
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldReturnToIfIntention.kt
1
3033
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.types.typeUtil.isNothing class UnfoldReturnToIfIntention : LowPriorityAction, SelfTargetingRangeIntention<KtReturnExpression>( KtReturnExpression::class.java, KotlinBundle.lazyMessage("replace.return.with.if.expression") ) { override fun applicabilityRange(element: KtReturnExpression): TextRange? { val ifExpression = element.returnedExpression as? KtIfExpression ?: return null return TextRange(element.startOffset, ifExpression.ifKeyword.endOffset) } override fun applyTo(element: KtReturnExpression, editor: Editor?) { val ifExpression = element.returnedExpression as KtIfExpression val thenExpr = ifExpression.then!!.lastBlockStatementOrThis() val elseExpr = ifExpression.`else`!!.lastBlockStatementOrThis() val newIfExpression = ifExpression.copied() val newThenExpr = newIfExpression.then!!.lastBlockStatementOrThis() val newElseExpr = newIfExpression.`else`!!.lastBlockStatementOrThis() val psiFactory = KtPsiFactory(element.project) val context = element.analyze() val labelName = element.getLabelName() newThenExpr.replace(createReturnExpression(thenExpr, labelName, psiFactory, context)) newElseExpr.replace(createReturnExpression(elseExpr, labelName, psiFactory, context)) element.replace(newIfExpression) } companion object { fun createReturnExpression( expr: KtExpression, labelName: String?, psiFactory: KtPsiFactory, context: BindingContext ): KtExpression { val label = labelName?.let { "@$it" } ?: "" val returnText = when (expr) { is KtBreakExpression, is KtContinueExpression, is KtReturnExpression, is KtThrowExpression -> "" else -> if (expr.getResolvedCall(context)?.resultingDescriptor?.returnType?.isNothing() == true) "" else "return$label " } return psiFactory.createExpressionByPattern("$returnText$0", expr) } } }
apache-2.0
b1fd7fb5cea1a442e87f936f43552a44
47.15873
158
0.745137
5.114671
false
false
false
false
fancylou/FancyFilePicker
fancyfilepickerlibrary/src/main/java/net/muliba/fancyfilepickerlibrary/ui/fragment/FileLocalStoragePickerFragment.kt
1
6833
package net.muliba.fancyfilepickerlibrary.ui.fragment import android.os.Bundle import android.os.Environment import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.TextView import kotlinx.android.synthetic.main.breadcrumbs.* import kotlinx.android.synthetic.main.fragment_file_picker.* import net.muliba.fancyfilepickerlibrary.FilePicker import net.muliba.fancyfilepickerlibrary.R import net.muliba.fancyfilepickerlibrary.adapter.FileAdapter import net.muliba.fancyfilepickerlibrary.adapter.FileViewHolder import net.muliba.fancyfilepickerlibrary.ext.friendlyFileLength import net.muliba.fancyfilepickerlibrary.ui.FileActivity import net.muliba.fancyfilepickerlibrary.util.Utils import org.jetbrains.anko.doAsync import org.jetbrains.anko.toast import org.jetbrains.anko.uiThread import java.io.File import java.util.regex.Pattern /** * Created by fancylou on 10/23/17. */ class FileLocalStoragePickerFragment: Fragment() { var mActivity: FileActivity? = null private val rootPath: String = Environment.getExternalStorageDirectory().absolutePath private var currentPath = rootPath override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if (activity != null) { mActivity = (activity as FileActivity) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_file_picker, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler_file_picker_list.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) recycler_file_picker_list.adapter = adapter constraint_file_picker_upper_level_button.setOnClickListener { upperLevel() } refreshList(currentPath) } fun onBackPressed():Boolean { if (rootPath == currentPath) { return false }else { upperLevel() return true } } /** * 向上一级 */ private fun upperLevel() { if (rootPath == currentPath) { activity?.toast(getString(R.string.message_already_on_top)) } else { refreshList(File(currentPath).parentFile.absolutePath) } } /** * 定义adapter */ val adapter: FileAdapter by lazy { object : FileAdapter() { override fun onBind(file: File, holder: FileViewHolder) { if (file.isDirectory) { holder.setText(R.id.tv_file_picker_folder_name, file.name) val folderDesc = holder.getView<TextView>(R.id.tv_file_picker_folder_description) doAsync { val size = file.list().size.toString() uiThread { folderDesc.text = getString(R.string.item_folder_description_label).format(size) } } holder.convertView.setOnClickListener { refreshList(file.absolutePath) } } else { holder.setText(R.id.tv_file_picker_file_name, file.name) .setImageByResource(R.id.image_file_picker_file, Utils.fileIcon(file.extension)) val fileDesc = holder.getView<TextView>(R.id.tv_file_picker_file_description) doAsync { val len = file.length().friendlyFileLength() uiThread { fileDesc.text = len } } val checkbox = holder.getView<CheckBox>(R.id.checkBox_file_picker_file) if (mActivity?.chooseType == FilePicker.CHOOSE_TYPE_SINGLE){ checkbox.visibility = View.GONE }else{ checkbox.visibility = View.VISIBLE checkbox.isChecked = false if (mActivity?.mSelected?.contains(file.absolutePath) == true) { checkbox.isChecked = true } //checkbox click checkbox.setOnClickListener { val check = checkbox.isChecked mActivity?.toggleChooseFile(file.absolutePath, check) } } holder.convertView.setOnClickListener { v -> if (mActivity?.chooseType == FilePicker.CHOOSE_TYPE_SINGLE){ mActivity?.chooseFileSingle(file.absolutePath) }else{ val filePickerCheckbox = v.findViewById(R.id.checkBox_file_picker_file) as CheckBox val check = filePickerCheckbox.isChecked filePickerCheckbox.isChecked = !check mActivity?.toggleChooseFile(file.absolutePath, !check) } } } } } } /** * 刷新list */ private fun refreshList(path: String) { doAsync { val list: List<File> = File(path).listFiles{ _, fileName -> val pattern = Pattern.compile("\\..*") !pattern.matcher(fileName).matches() }.map { it }.sortedWith(Comparator<File> { o1, o2 -> if (o1.isDirectory && o2.isDirectory) { o1.name.compareTo(o2.name, true) } else if (o1.isFile && o2.isFile) { o1.name.compareTo(o2.name, true) } else { when (o1.isDirectory && o2.isFile) { true -> -1 false -> 1 } } }) uiThread { currentPath = path if (currentPath.equals(rootPath)){ breadcrumbs.visibility = View.GONE }else { breadcrumbs.visibility = View.VISIBLE } tv_file_picker_folder_path.text = currentPath if (list.isNotEmpty()) { recycler_file_picker_list.visibility = View.VISIBLE file_picker_empty.visibility = View.GONE } else { recycler_file_picker_list.visibility = View.GONE file_picker_empty.visibility = View.VISIBLE } adapter.refreshItems(list) } } } }
apache-2.0
d051917431eef5e5d90a3ce12b9d5a02
38.871345
118
0.568285
4.968659
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/course_reviews/ui/adapter/delegates/CourseReviewDataDelegate.kt
2
4872
package org.stepik.android.view.course_reviews.ui.adapter.delegates import android.graphics.BitmapFactory import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.view.View import android.view.ViewGroup import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.PopupMenu import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory import androidx.core.view.isVisible import kotlinx.android.synthetic.main.view_course_reviews_item.view.* import org.stepic.droid.R import org.stepik.android.view.glide.ui.extension.wrapWithGlide import org.stepic.droid.util.DateTimeHelper import org.stepic.droid.util.resolveColorAttribute import org.stepik.android.domain.course_reviews.model.CourseReview import org.stepik.android.domain.course_reviews.model.CourseReviewItem import org.stepik.android.model.user.User import org.stepik.android.view.base.ui.mapper.DateMapper import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class CourseReviewDataDelegate( private val onUserClicked: (User) -> Unit, private val onEditReviewClicked: (CourseReview) -> Unit, private val onRemoveReviewClicked: (CourseReview) -> Unit ) : AdapterDelegate<CourseReviewItem, DelegateViewHolder<CourseReviewItem>>() { override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseReviewItem> = ViewHolder(createView(parent, R.layout.view_course_reviews_item)) override fun isForViewType(position: Int, data: CourseReviewItem): Boolean = data is CourseReviewItem.Data inner class ViewHolder(root: View) : DelegateViewHolder<CourseReviewItem>(root) { private val reviewIcon = root.reviewIcon private val reviewIconWrapper = reviewIcon.wrapWithGlide() private val reviewDate = root.reviewDate private val reviewName = root.reviewName private val reviewRating = root.reviewRating private val reviewText = root.reviewText private val reviewMenu = root.reviewMenu private val reviewMark = root.reviewMark private val reviewIconPlaceholder = with(context.resources) { val coursePlaceholderBitmap = BitmapFactory.decodeResource(this, R.drawable.general_placeholder) val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(this, coursePlaceholderBitmap) circularBitmapDrawable.cornerRadius = getDimension(R.dimen.corner_radius) circularBitmapDrawable } init { val userClickListener = View.OnClickListener { (itemData as? CourseReviewItem.Data)?.user?.let(onUserClicked) } reviewIcon.setOnClickListener(userClickListener) reviewName.setOnClickListener(userClickListener) reviewDate.setOnClickListener(userClickListener) reviewMenu.setOnClickListener(::showReviewMenu) } override fun onBind(data: CourseReviewItem) { data as CourseReviewItem.Data reviewIconWrapper.setImagePath(data.user.avatar ?: "", AppCompatResources.getDrawable(context, R.drawable.general_placeholder)) reviewName.text = data.user.fullName reviewDate.text = DateMapper.mapToRelativeDate(context, DateTimeHelper.nowUtc(), data.courseReview.updateDate?.time ?: 0) reviewRating.progress = data.courseReview.score reviewRating.total = 5 reviewText.text = data.courseReview.text reviewMenu.isVisible = data.isCurrentUserReview reviewMark.isVisible = data.isCurrentUserReview } private fun showReviewMenu(view: View) { val courseReview = (itemData as? CourseReviewItem.Data) ?.courseReview ?: return val popupMenu = PopupMenu(context, view) popupMenu.inflate(R.menu.course_review_menu) popupMenu .menu .findItem(R.id.course_review_menu_remove) ?.let { menuItem -> val title = SpannableString(menuItem.title) title.setSpan(ForegroundColorSpan(context.resolveColorAttribute(R.attr.colorError)), 0, title.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE) menuItem.title = title } popupMenu .setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { R.id.course_review_menu_edit -> onEditReviewClicked(courseReview) R.id.course_review_menu_remove -> onRemoveReviewClicked(courseReview) } true } popupMenu.show() } } }
apache-2.0
ad9af84576462c8559ea4d8103e251cf
42.508929
157
0.69376
5.085595
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/features/stories/ui/delegate/StoriesActivityDelegate.kt
1
3159
package org.stepic.droid.features.stories.ui.delegate import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.children import androidx.viewpager.widget.ViewPager import kotlinx.android.synthetic.main.activity_stories.* import org.stepic.droid.R import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.analytic.Analytic import org.stepik.android.domain.story.model.StoryReaction import ru.nobird.app.core.model.safeCast import ru.nobird.android.stories.model.Story import ru.nobird.android.stories.ui.adapter.StoriesPagerAdapter import ru.nobird.android.stories.ui.custom.DismissableLayout import ru.nobird.android.stories.ui.custom.StoryView import ru.nobird.android.stories.ui.delegate.StoriesActivityDelegateBase import ru.nobird.android.stories.ui.delegate.StoryPartViewDelegate class StoriesActivityDelegate( activity: AppCompatActivity, private val analytic: Analytic, storyReactionListener: (storyId: Long, storyPosition: Int, storyReaction: StoryReaction) -> Unit ) : StoriesActivityDelegateBase(activity) { private val storyReactions = mutableMapOf<Long, StoryReaction>() private val storyPartDelegate = PlainTextWithButtonStoryPartDelegate(analytic, activity, storyReactions, storyReactionListener) public override val dismissableLayout: DismissableLayout = activity.content public override val storiesViewPager: ViewPager = activity.storiesPager override val arguments: Bundle = activity.intent.extras ?: Bundle.EMPTY override val storyPartDelegates: List<StoryPartViewDelegate> = listOf(storyPartDelegate, FeedbackStoryPartDelegate(analytic, activity, dismissableLayout)) override fun onComplete() { super.onComplete() val story = getCurrentStory() ?: return analytic.reportAmplitudeEvent(AmplitudeAnalytic.Stories.STORY_CLOSED, mapOf( AmplitudeAnalytic.Stories.Values.STORY_ID to story.id, AmplitudeAnalytic.Stories.Values.CLOSE_TYPE to AmplitudeAnalytic.Stories.Values.CloseTypes.AUTO )) } fun getCurrentStory(): Story? = storiesViewPager.adapter .safeCast<StoriesPagerAdapter>() ?.stories ?.getOrNull(storiesViewPager.currentItem) fun setStoryVotes(votes: Map<Long, StoryReaction>) { val diff = votes - storyReactions // only this way as reactions can't be removed storyReactions.clear() storyReactions += votes val adapter = storiesViewPager.adapter .safeCast<StoriesPagerAdapter>() ?: return diff.forEach { (storyId, _) -> val position = adapter.stories .indexOfFirst { it.id == storyId } val story = adapter.stories .getOrNull(position) val storyPartPager = storiesViewPager .findViewWithTag<StoryView>(position) ?.findViewById<ViewPager>(R.id.storyViewPager) storyPartPager?.children?.forEach { view -> storyPartDelegate.setUpReactions(story, view, position) } } } }
apache-2.0
85f9f9135650d851bfc6fc52cedcb1a4
37.072289
107
0.722697
4.779123
false
false
false
false
allotria/intellij-community
platform/elevation/client/src/com/intellij/execution/process/mediator/client/MediatedProcess.kt
2
8192
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("EXPERIMENTAL_API_USAGE") package com.intellij.execution.process.mediator.client import com.google.protobuf.ByteString import com.intellij.execution.process.SelfKiller import com.intellij.execution.process.mediator.daemon.QuotaExceededException import com.intellij.execution.process.mediator.util.ChannelInputStream import com.intellij.execution.process.mediator.util.ChannelOutputStream import com.intellij.execution.process.mediator.util.blockingGet import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.flow.* import kotlinx.coroutines.future.asCompletableFuture import java.io.* import java.lang.ref.Cleaner import java.util.concurrent.CompletableFuture import kotlin.coroutines.coroutineContext private val CLEANER = Cleaner.create() class MediatedProcess private constructor( private val handle: MediatedProcessHandle, command: List<String>, workingDir: File, environVars: Map<String, String>, inFile: File?, outFile: File?, errFile: File?, ) : Process(), SelfKiller { companion object { @Throws(IOException::class, QuotaExceededException::class, CancellationException::class) fun create(processMediatorClient: ProcessMediatorClient, processBuilder: ProcessBuilder): MediatedProcess { val workingDir = processBuilder.directory() ?: File(".").normalize() // defaults to current working directory val inFile = processBuilder.redirectInput().file() val outFile = processBuilder.redirectOutput().file() val errFile = processBuilder.redirectError().file() val handle = MediatedProcessHandle.create(processMediatorClient) return try { MediatedProcess(handle, processBuilder.command(), workingDir, processBuilder.environment(), inFile, outFile, errFile).apply { val cleanable = CLEANER.register(this, handle::releaseAsync) onExit().thenRun { cleanable.clean() } } } catch (e: Throwable) { handle.rpcScope.cancel(e as? CancellationException ?: CancellationException("Failed to create process", e)) throw e } } } private val pid = runBlocking { handle.rpc { handleId -> createProcess(handleId, command, workingDir, environVars, inFile, outFile, errFile) } } private val stdin: OutputStream = if (inFile == null) createOutputStream(0) else NullOutputStream private val stdout: InputStream = if (outFile == null) createInputStream(1) else NullInputStream private val stderr: InputStream = if (errFile == null) createInputStream(2) else NullInputStream private val termination: Deferred<Int> = handle.rpcScope.async { handle.rpc { handleId -> awaitTermination(handleId) } } override fun pid(): Long = pid override fun getOutputStream(): OutputStream = stdin override fun getInputStream(): InputStream = stdout override fun getErrorStream(): InputStream = stderr @Suppress("EXPERIMENTAL_API_USAGE") private fun createOutputStream(@Suppress("SameParameterValue") fd: Int): OutputStream { val ackFlow = MutableStateFlow<Long?>(0L) val channel = handle.rpcScope.actor<ByteString>(capacity = Channel.BUFFERED) { handle.rpc { handleId -> try { // NOTE: Must never consume the channel associated with the actor. In fact, the channel IS the actor coroutine, // and cancelling it makes the coroutine die in a horrible way leaving the remote call in a broken state. writeStream(handleId, fd, channel.receiveAsFlow()) .onCompletion { ackFlow.value = null } .fold(0L) { l, _ -> (l + 1).also { ackFlow.value = it } } } catch (e: IOException) { channel.cancel(CancellationException(e.message, e)) } } } val stream = ChannelOutputStream(channel, ackFlow) return BufferedOutputStream(stream) } @Suppress("EXPERIMENTAL_API_USAGE") private fun createInputStream(fd: Int): InputStream { val channel = handle.rpcScope.produce<ByteString>(capacity = Channel.BUFFERED) { handle.rpc { handleId -> try { readStream(handleId, fd).collect(channel::send) } catch (e: IOException) { channel.close(e) } } } val stream = ChannelInputStream(channel) return BufferedInputStream(stream) } override fun waitFor(): Int = termination.blockingGet() override fun onExit(): CompletableFuture<Process> = termination.asCompletableFuture().thenApply { this } override fun exitValue(): Int { return try { @Suppress("EXPERIMENTAL_API_USAGE") termination.getCompleted() } catch (e: IllegalStateException) { throw IllegalThreadStateException(e.message) } } override fun destroy() { destroy(false) } override fun destroyForcibly(): Process { destroy(true) return this } fun destroy(force: Boolean, destroyGroup: Boolean = false) { // In case this is called after releasing the handle (due to process termination), // it just does nothing, without throwing any error. handle.rpcScope.launch { handle.rpc { handleId -> destroyProcess(handleId, force, destroyGroup) } } } private object NullInputStream : InputStream() { override fun read(): Int = -1 override fun available(): Int = 0 } private object NullOutputStream : OutputStream() { override fun write(b: Int) = throw IOException("Stream closed") } } /** * All remote calls are performed using the provided [ProcessMediatorClient], * and the whole process lifecycle is contained within the coroutine scope of the client. * Normal remote calls (those besides process creation and release) are performed within the scope of the handle object. */ private class MediatedProcessHandle private constructor( private val client: ProcessMediatorClient, private val handleId: Long, private val lifetimeChannel: ReceiveChannel<*>, ) { companion object { fun create(client: ProcessMediatorClient): MediatedProcessHandle { val lifetimeChannel = client.openHandle().produceIn(client.coroutineScope) try { val handleId = runBlocking { lifetimeChannel.receiveOrNull() ?: throw IOException("Failed to receive handleId") } return MediatedProcessHandle(client, handleId, lifetimeChannel) } catch (e: Throwable) { lifetimeChannel.cancel(e as? CancellationException ?: CancellationException("Failed to initialize client-side handle", e)) throw e } } } private val parentScope: CoroutineScope = client.coroutineScope private val lifetimeJob = parentScope.launch { try { lifetimeChannel.receive() } catch (e: ClosedReceiveChannelException) { throw CancellationException("closed", e) } error("unreachable") } private val rpcJob: CompletableJob = SupervisorJob(lifetimeJob).apply { invokeOnCompletion { e -> lifetimeChannel.cancel(e as? CancellationException ?: CancellationException("Complete", e)) } } val rpcScope: CoroutineScope = parentScope + rpcJob suspend fun <R> rpc(block: suspend ProcessMediatorClient.(handleId: Long) -> R): R { rpcScope.ensureActive() coroutineContext.ensureActive() // Perform the call in the scope of this handle, so that it is dispatched in the same way as OpenHandle(). // This overrides the parent so that we can await for the call to complete before closing the lifetimeChannel; // at the same time we ensure the caller is still able to cancel it. val deferred = rpcScope.async { client.block(handleId) } return try { deferred.await() } catch (e: CancellationException) { deferred.cancel(e) throw e } } fun releaseAsync() { // let ongoing operations finish gracefully, // and once all of them finish don't accept new calls rpcJob.complete() } }
apache-2.0
e2ad8a78711a4298d3509f955b194774
34.772926
140
0.693726
4.643991
false
false
false
false
allotria/intellij-community
python/src/com/jetbrains/python/sdk/add/PyAddNewCondaEnvPanel.kt
3
6316
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.add import com.intellij.execution.ExecutionException import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBCheckBox import com.intellij.util.PathUtil import com.intellij.util.SystemProperties import com.intellij.util.ui.FormBuilder import com.jetbrains.python.PyBundle import com.jetbrains.python.packaging.PyCondaPackageManagerImpl import com.jetbrains.python.packaging.PyCondaPackageService import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.associateWithModule import com.jetbrains.python.sdk.basePath import com.jetbrains.python.sdk.conda.PyCondaSdkCustomizer import com.jetbrains.python.sdk.createSdkByGenerateTask import com.jetbrains.python.sdk.flavors.CondaEnvSdkFlavor import icons.PythonIcons import org.jetbrains.annotations.SystemIndependent import java.awt.BorderLayout import javax.swing.Icon import javax.swing.JComboBox import javax.swing.event.DocumentEvent /** * @author vlan */ open class PyAddNewCondaEnvPanel( private val project: Project?, private val module: Module?, private val existingSdks: List<Sdk>, newProjectPath: String? ) : PyAddNewEnvPanel() { override val envName: String = "Conda" override val panelName: String get() = PyBundle.message("python.add.sdk.panel.name.new.environment") override val icon: Icon = PythonIcons.Python.Anaconda protected val languageLevelsField: JComboBox<String> protected val condaPathField = TextFieldWithBrowseButton().apply { val path = PyCondaPackageService.getCondaExecutable(null) path?.let { text = it } addBrowseFolderListener(PyBundle.message("python.sdk.select.conda.path.title"), null, project, FileChooserDescriptorFactory.createSingleFileOrExecutableAppDescriptor()) textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { updatePathField() } }) } protected val pathField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(PyBundle.message("python.sdk.select.location.for.conda.title"), null, project, FileChooserDescriptorFactory.createSingleFolderDescriptor()) } private val makeSharedField = JBCheckBox(PyBundle.message("available.to.all.projects")) override var newProjectPath: String? = newProjectPath set(value) { field = value updatePathField() } init { layout = BorderLayout() val supportedLanguageLevels = LanguageLevel.SUPPORTED_LEVELS .asReversed() .filter { it < LanguageLevel.PYTHON310 } .map { it.toPythonVersion() } languageLevelsField = ComboBox(supportedLanguageLevels.toTypedArray()).apply { selectedItem = if (itemCount > 0) getItemAt(0) else null } if (PyCondaSdkCustomizer.instance.sharedEnvironmentsByDefault) { makeSharedField.isSelected = true } updatePathField() @Suppress("LeakingThis") layoutComponents() } protected open fun layoutComponents() { layout = BorderLayout() val formPanel = FormBuilder.createFormBuilder() .addLabeledComponent(PyBundle.message("sdk.create.venv.conda.dialog.label.location"), pathField) .addLabeledComponent(PyBundle.message("sdk.create.venv.conda.dialog.label.python.version"), languageLevelsField) .addLabeledComponent(PyBundle.message("python.sdk.conda.path"), condaPathField) .addComponent(makeSharedField) .panel add(formPanel, BorderLayout.NORTH) } override fun validateAll(): List<ValidationInfo> = listOfNotNull(CondaEnvSdkFlavor.validateCondaPath(condaPathField.text), validateEnvironmentDirectoryLocation(pathField)) override fun getOrCreateSdk(): Sdk? { val condaPath = condaPathField.text val task = object : Task.WithResult<String, ExecutionException>(project, PyBundle.message("python.sdk.creating.conda.environment.title"), false) { override fun compute(indicator: ProgressIndicator): String { indicator.isIndeterminate = true return PyCondaPackageManagerImpl.createVirtualEnv(condaPath, pathField.text, selectedLanguageLevel) } } val shared = makeSharedField.isSelected val associatedPath = if (!shared) projectBasePath else null val sdk = createSdkByGenerateTask(task, existingSdks, null, associatedPath, null) ?: return null if (!shared) { sdk.associateWithModule(module, newProjectPath) } PyCondaPackageService.onCondaEnvCreated(condaPath) return sdk } override fun addChangeListener(listener: Runnable) { val documentListener = object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { listener.run() } } pathField.textField.document.addDocumentListener(documentListener) condaPathField.textField.document.addDocumentListener(documentListener) } private fun updatePathField() { val baseDir = defaultBaseDir ?: "${SystemProperties.getUserHome()}/.conda/envs" val dirName = PathUtil.getFileName(projectBasePath ?: "untitled") pathField.text = FileUtil.toSystemDependentName("$baseDir/$dirName") } private val defaultBaseDir: String? get() { val conda = condaPathField.text val condaFile = LocalFileSystem.getInstance().findFileByPath(conda) ?: return null return condaFile.parent?.parent?.findChild("envs")?.path } private val projectBasePath: @SystemIndependent String? get() = newProjectPath ?: module?.basePath ?: project?.basePath private val selectedLanguageLevel: String get() = languageLevelsField.getItemAt(languageLevelsField.selectedIndex) }
apache-2.0
bdc93d31d3e5d5a866510bc295670df0
38.475
150
0.763458
4.678519
false
false
false
false
spring-projects/spring-framework
spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/client/ClientResponseExtensionsTests.kt
1
5122
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.function.client import io.mockk.every import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import reactor.core.publisher.Mono /** * Mock object based tests for [ClientResponse] Kotlin extensions. * * @author Sebastien Deleuze * @author Igor Manushin */ class ClientResponseExtensionsTests { private val response = mockk<ClientResponse>(relaxed = true) @Test fun `bodyToMono with reified type parameters`() { response.bodyToMono<List<Foo>>() verify { response.bodyToMono(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun `bodyToFlux with reified type parameters`() { response.bodyToFlux<List<Foo>>() verify { response.bodyToFlux(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun `bodyToFlow with reified type parameters`() { response.bodyToFlow<List<Foo>>() verify { response.bodyToFlux(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun `bodyToFlow with KClass parameter`() { response.bodyToFlow(Foo::class) verify { response.bodyToFlux(Foo::class.java) } } @Test fun `toEntity with reified type parameters`() { response.toEntity<List<Foo>>() verify { response.toEntity(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun `ResponseSpec#toEntityList with reified type parameters`() { response.toEntityList<List<Foo>>() verify { response.toEntityList(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun awaitBody() { val response = mockk<ClientResponse>() every { response.bodyToMono<String>() } returns Mono.just("foo") runBlocking { assertThat(response.awaitBody<String>()).isEqualTo("foo") } } @Test fun `awaitBody with KClass parameter`() { val response = mockk<ClientResponse>() every { response.bodyToMono(String::class.java) } returns Mono.just("foo") runBlocking { assertThat(response.awaitBody(String::class)).isEqualTo("foo") } } @Test fun awaitBodyOrNull() { val response = mockk<ClientResponse>() every { response.bodyToMono<String>() } returns Mono.empty() runBlocking { assertThat(response.awaitBodyOrNull<String>()).isNull() } } @Test fun `awaitBodyOrNullGeneric with KClass parameter`() { val response = mockk<ClientResponse>() every { response.bodyToMono(String::class.java) } returns Mono.empty() runBlocking { assertThat(response.awaitBodyOrNull(String::class)).isNull() } } @Test fun awaitEntity() { val response = mockk<ClientResponse>() val entity = ResponseEntity("foo", HttpStatus.OK) every { response.toEntity<String>() } returns Mono.just(entity) runBlocking { assertThat(response.awaitEntity<String>()).isEqualTo(entity) } } @Test fun `awaitEntity with KClass parameter`() { val response = mockk<ClientResponse>() val entity = ResponseEntity("foo", HttpStatus.OK) every { response.toEntity(String::class.java) } returns Mono.just(entity) runBlocking { assertThat(response.awaitEntity(String::class)).isEqualTo(entity) } } @Test fun awaitEntityList() { val response = mockk<ClientResponse>() val entity = ResponseEntity(listOf("foo"), HttpStatus.OK) every { response.toEntityList<String>() } returns Mono.just(entity) runBlocking { assertThat(response.awaitEntityList<String>()).isEqualTo(entity) } } @Test fun `awaitEntityList with KClass parameter`() { val response = mockk<ClientResponse>() val entity = ResponseEntity(listOf("foo"), HttpStatus.OK) every { response.toEntityList(String::class.java) } returns Mono.just(entity) runBlocking { assertThat(response.awaitEntityList(String::class)).isEqualTo(entity) } } @Test fun awaitBodilessEntity() { val response = mockk<ClientResponse>() val entity = mockk<ResponseEntity<Void>>() every { response.toBodilessEntity() } returns Mono.just(entity) runBlocking { assertThat(response.awaitBodilessEntity()).isEqualTo(entity) } } @Test fun createExceptionAndAwait() { val response = mockk<ClientResponse>() val exception = mockk<WebClientResponseException>() every { response.createException() } returns Mono.just(exception) runBlocking { assertThat(response.createExceptionAndAwait()).isEqualTo(exception) } } class Foo }
apache-2.0
61ea3b906739752de3b57a8f248b37e8
28.606936
87
0.734479
3.794074
false
true
false
false
grover-ws-1/http4k
http4k-testing-hamkrest/src/main/kotlin/org/http4k/hamkrest/response.kt
1
643
package org.http4k.hamkrest import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.has import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.cookie.Cookie import org.http4k.core.cookie.cookies fun hasStatus(expected: Status): Matcher<Response> = has(Response::status, equalTo(expected)) fun hasSetCookie(expected: Cookie): Matcher<Response> = hasSetCookie(expected.name, equalTo(expected)) fun hasSetCookie(name: String, expected: Matcher<Cookie>): Matcher<Response> = has("Cookie '$name'", { r: Response -> r.cookies().find { name == it.name }!! }, expected)
apache-2.0
ac9ea09225cc331767e9a5481e5563aa
41.866667
169
0.777605
3.532967
false
false
false
false
zdary/intellij-community
xml/xml-psi-impl/src/com/intellij/html/embedding/HtmlTokenEmbeddedContentProvider.kt
12
1520
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.html.embedding import com.intellij.lexer.BaseHtmlLexer import com.intellij.lexer.Lexer import com.intellij.openapi.util.TextRange import com.intellij.psi.tree.IElementType import java.util.function.Supplier open class HtmlTokenEmbeddedContentProvider @JvmOverloads constructor(lexer: BaseHtmlLexer, private val token: IElementType, highlightingLexerSupplier: Supplier<Lexer?>, elementTypeOverrideSupplier: Supplier<IElementType?> = Supplier { token }) : BaseHtmlEmbeddedContentProvider(lexer) { private val info = object : HtmlEmbedmentInfo { override fun getElementType(): IElementType? = elementTypeOverrideSupplier.get() override fun createHighlightingLexer(): Lexer? = highlightingLexerSupplier.get() } override fun isStartOfEmbedment(tokenType: IElementType): Boolean = tokenType == this.token override fun createEmbedmentInfo(): HtmlEmbedmentInfo? = info override fun findTheEndOfEmbedment(): Pair<Int, Int> { val baseLexer = lexer.delegate val position = baseLexer.currentPosition baseLexer.advance() val result = Pair(baseLexer.tokenStart, baseLexer.state) baseLexer.restore(position) return result } override fun handleToken(tokenType: IElementType, range: TextRange) { embedment = tokenType == this.token } }
apache-2.0
84c51005616f6c0f388d25de16d947b6
38
140
0.742105
4.606061
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/conf/Config.kt
1
6469
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.common.conf import slatekit.common.* import slatekit.common.crypto.Encryptor //import java.time.* import org.threeten.bp.* import slatekit.common.convert.Conversions import slatekit.common.ext.decrypt import slatekit.common.ext.getEnv import slatekit.common.io.Uri import java.util.* /** * Conf is a wrapper around the typesafe config with additional support for: * 1. RESOURCES Use a prefix for indicating where to load config from. - "jars://" for the resources directory in the jar. - "user://" for the user.home directory. - "file://" for an explicit path to the file - "file://" for relative path to the file from working directory Examples: - jar://env.qa.conf - user://${company.dir}/${group.dir}/${app.id}/conf/env.qa.conf - file://c:/slatekit/${company.dir}/${group.dir}/${app.id}/conf/env.qa.conf - file://./conf/env.qa.conf 2. LOADING Use a short-hand syntax for specifying the files to merge and fallback with Examples: - primary - primary, fallback1 - primary, fallback1, fallback2 3. FUNCTIONS: Use functions in the config to resolve values dynamically. You can use the resolveString method to resolve the value dynamically. Note: This uses the slatekit.common.subs component. Examples: ( props inside your .conf file ) - tag : "@{today.yyyymmdd-hhmmss}" 4. DEFAULTS: Use optional default values for getting strings, int, doubles, bools. Examples: - getStringOrElse - getIntOrElse - getBoolOrElse - getDoubleOrElse - getDateOrElse 5. MAPPING Map slatekit objects automatically from the conf settings. Built in mappers for the Examples: - "env" : Environment selection ( dev, qa, stg, prod ) etc. - "login" : slatekit.common.Credentials object - "db" : database connection strings - "api" : standardized api keys * * @param fileName * @param enc * @param props */ class Config( cls: Class<*>, uri:Uri, val config: Properties, val enc: Encryptor? = null ) : Conf(cls, uri, { raw -> enc?.decrypt(raw) ?: raw }) { /** * Get or load the config object */ override val raw: Any = config override fun get(key: String): Any? = getInternal(key) override fun containsKey(key: String): Boolean = config.containsKey(key) override fun size(): Int = config.values.size override fun getString(key: String): String = interpret(key) override fun getBool(key: String): Boolean = Conversions.toBool(getStringRaw(key)) override fun getShort(key: String): Short = Conversions.toShort(getStringRaw(key)) override fun getInt(key: String): Int = Conversions.toInt(getStringRaw(key)) override fun getLong(key: String): Long = Conversions.toLong(getStringRaw(key)) override fun getFloat(key: String): Float = Conversions.toFloat(getStringRaw(key)) override fun getDouble(key: String): Double = Conversions.toDouble(getStringRaw(key)) override fun getInstant(key: String): Instant = Conversions.toInstant(getStringRaw(key)) override fun getDateTime(key: String): DateTime = Conversions.toDateTime(getStringRaw(key)) override fun getLocalDate(key: String): LocalDate = Conversions.toLocalDate(getStringRaw(key)) override fun getLocalTime(key: String): LocalTime = Conversions.toLocalTime(getStringRaw(key)) override fun getLocalDateTime(key: String): LocalDateTime = Conversions.toLocalDateTime(getStringRaw(key)) override fun getZonedDateTime(key: String): ZonedDateTime = Conversions.toZonedDateTime(getStringRaw(key)) override fun getZonedDateTimeUtc(key: String): ZonedDateTime = Conversions.toZonedDateTimeUtc(getStringRaw(key)) /** * Loads config from the file path supplied * * @param file * @return */ override fun loadFrom(file: String?): Conf? = Confs.load(cls, file, enc) /** * Extends the config by supporting decryption via marker tags. * e.g. * db.connection = "@{decrypt('8r4AbhQyvlzSeWnKsamowA')}" * db.connection = "@{env('APP1_DB_URL')}" * * @param key : key: The name of the config key * @return */ private fun interpret(key: String): String { val raw = getStringRaw(key) val value = if(raw.startsWith("@{env")) { raw.getEnv() } else if(raw.startsWith("@{decrypt")) { raw.decrypt(encryptor) } else { raw } return value } private fun getInternal(key: String): Any? { return if (containsKey(key)) { val value = config.getProperty(key) if (value != null && value is String) { value.trim() } else { value } } else { null } } private fun getStringRaw(key: String): String = config.getProperty(key)?.trim() ?: "" companion object { operator fun invoke(cls:Class<*>):Config { val info = Props.fromPath(cls, "") return Config(cls, info.first, info.second) } fun of(cls:Class<*>, configPath: String, enc: Encryptor? = null):Config { val info = Props.fromPath(cls, configPath) val conf = Config(cls, info.first, info.second, enc) return conf } fun of(cls:Class<*>, configPath: String, configParentPath: String, enc: Encryptor?):ConfigMulti { val parentInfo = Props.fromPath(cls, configParentPath) val parentConf = Config(cls, parentInfo.first, parentInfo.second, enc) val inheritInfo = Props.fromPath(cls, configPath) val inheritConf = Config(cls, inheritInfo.first, inheritInfo.second, enc) val conf = ConfigMulti(cls, inheritConf, parentConf, inheritInfo.first, enc) return conf } fun of(cls:Class<*>, configSource: Uri, configParent: Conf, enc: Encryptor?) :ConfigMulti { val inheritProps = Props.fromUri(cls, configSource) val inheritConf = Config(cls, configSource, inheritProps, enc) val conf = ConfigMulti(cls, inheritConf, configParent, configSource, enc) return conf } } }
apache-2.0
0f57d84b00e04a5221f1a4c532a69d57
32.518135
116
0.663627
4.02301
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/defaultArguments/function/extensionFunctionManyArgs.kt
5
6972
fun Int.foo(a: Int = 1, b: Int = 2, c: Int = 3, d: Int = 4, e: Int = 5, f: Int = 6, g: Int = 7, h: Int = 8, i: Int = 9, j: Int = 10, k: Int = 11, l: Int = 12, m: Int = 13, n: Int = 14, o: Int = 15, p: Int = 16, q: Int = 17, r: Int = 18, s: Int = 19, t: Int = 20, u: Int = 21, v: Int = 22, w: Int = 23, x: Int = 24, y: Int = 25, z: Int = 26, aa: Int = 27, bb: Int = 28, cc: Int = 29, dd: Int = 30, ee: Int = 31, ff: Int = 32): String { return "$a $b $c $d $e $f $g $h $i $j $k $l $m $n $o $p $q $r $s $t $u $v $w $x $y $z $aa $bb $cc $dd $ee $ff" } fun String.bar(a: Int = 1, b: Int = 2, c: Int = 3, d: Int = 4, e: Int = 5, f: Int = 6, g: Int = 7, h: Int = 8, i: Int = 9, j: Int = 10, k: Int = 11, l: Int = 12, m: Int = 13, n: Int = 14, o: Int = 15, p: Int = 16, q: Int = 17, r: Int = 18, s: Int = 19, t: Int = 20, u: Int = 21, v: Int = 22, w: Int = 23, x: Int = 24, y: Int = 25, z: Int = 26, aa: Int = 27, bb: Int = 28, cc: Int = 29, dd: Int = 30, ee: Int = 31, ff: Int = 32, gg: Int = 33, hh: Int = 34, ii: Int = 35, jj: Int = 36, kk: Int = 37, ll: Int = 38, mm: Int = 39, nn: Int = 40): String { return "$a $b $c $d $e $f $g $h $i $j $k $l $m $n $o $p $q $r $s $t $u $v $w $x $y $z $aa $bb $cc $dd $ee $ff " + "$gg $hh $ii $jj $kk $ll $mm $nn" } fun Char.baz(a: Int = 1, b: Int = 2, c: Int = 3, d: Int = 4, e: Int = 5, f: Int = 6, g: Int = 7, h: Int = 8, i: Int = 9, j: Int = 10, k: Int = 11, l: Int = 12, m: Int = 13, n: Int = 14, o: Int = 15, p: Int = 16, q: Int = 17, r: Int = 18, s: Int = 19, t: Int = 20, u: Int = 21, v: Int = 22, w: Int = 23, x: Int = 24, y: Int = 25, z: Int = 26, aa: Int = 27, bb: Int = 28, cc: Int = 29, dd: Int = 30, ee: Int = 31, ff: Int = 32, gg: Int = 33, hh: Int = 34, ii: Int = 35, jj: Int = 36, kk: Int = 37, ll: Int = 38, mm: Int = 39, nn: Int = 40, oo: Int = 41, pp: Int = 42, qq: Int = 43, rr: Int = 44, ss: Int = 45, tt: Int = 46, uu: Int = 47, vv: Int = 48, ww: Int = 49, xx: Int = 50, yy: Int = 51, zz: Int = 52, aaa: Int = 53, bbb: Int = 54, ccc: Int = 55, ddd: Int = 56, eee: Int = 57, fff: Int = 58, ggg: Int = 59, hhh: Int = 60, iii: Int = 61, jjj: Int = 62, kkk: Int = 63, lll: Int = 64, mmm: Int = 65, nnn: Int = 66, ooo: Int = 67, ppp: Int = 68, qqq: Int = 69, rrr: Int = 70): String { return "$a $b $c $d $e $f $g $h $i $j $k $l $m $n $o $p $q $r $s $t $u $v $w $x $y $z $aa $bb $cc $dd $ee $ff $gg $hh $ii $jj $kk " + "$ll $mm $nn $oo $pp $qq $rr $ss $tt $uu $vv $ww $xx $yy $zz $aaa $bbb $ccc $ddd $eee $fff $ggg $hhh $iii $jjj $kkk $lll " + "$mmm $nnn $ooo $ppp $qqq $rrr" } fun box(): String { val test1 = 1.foo(4, e = 8, f = 15, w = 16, aa = 23, ff = 42) val test2 = 1.foo() val test3 = 1.foo(32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, q = 16, r = 15, s = 14, t = 13, u = 12, v = 11, w = 10, x = 9, y = 8, z = 7, aa = 6, bb = 5, cc = 4, dd = 3, ee = 2, ff = 1) if (test1 != "4 2 3 4 8 15 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 16 24 25 26 23 28 29 30 31 42") { return "test1 = $test1" } if (test2 != "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32") { return "test2 = $test2" } if (test3 != "32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1") { return "test3 = $test3" } val test4 = "".bar(54, 217, h = 236, l = 18, q = 3216, u = 8, aa = 22, ff = 33, jj = 44, mm = 55) val test5 = "".bar() val test6 = "".bar(40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, u = 20, v = 19, w = 18, x = 17, y = 16, z = 15, aa = 14, bb = 13, cc = 12, dd = 11, ee = 10, ff = 9, gg = 8, hh = 7, ii = 6, jj = 5, kk = 4, ll = 3, mm = 2, nn = 1) if (test4 != "54 217 3 4 5 6 7 236 9 10 11 18 13 14 15 16 3216 18 19 20 8 22 23 24 25 26 22 28 29 30 31 33 33 34 35 44 37 38 55 40") { return "test4 = $test4" } if (test5 != "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40") { return "test5 = $test5" } if (test6 != "40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1") { return "test6 = $test6" } val test7 = 'a'.baz(5, f = 3, w = 1, aa = 71, nn = 2, qq = 15, ww = 97, aaa = 261258, iii = 3, nnn = 8, rrr = 7) val test8 = 'a'.baz() val test9 = 'a'.baz(70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, jj = 35, kk = 34, ll = 33, mm = 32, nn = 31, oo = 30, pp = 29, qq = 28, rr = 27, ss = 26, tt = 25, uu = 24, vv = 23, ww = 22, xx = 21, yy = 20, zz = 19, aaa = 18, bbb = 17, ccc = 16, ddd = 15, eee = 14, fff = 13, ggg = 12, hhh = 11, iii = 10, jjj = 9, kkk = 8, lll = 7, mmm = 6, nnn = 5, ooo = 4, ppp = 3, qqq = 2, rrr = 1) if (test7 != "5 2 3 4 5 3 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1 24 25 26 71 28 29 30 31 32 33 34 35 36 37 38 39 2 41 42 15 " + "44 45 46 47 48 97 50 51 52 261258 54 55 56 57 58 59 60 3 62 63 64 65 8 67 68 69 7") { return "test7 = $test7" } if (test8 != "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 " + "43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70") { return "test8 = $test8" } if (test9 != "70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 " + "31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1") { return "test9 = $test9" } return "OK" }
apache-2.0
97a60ce37f83e229c876077d663e4f06
33.009756
143
0.40175
2.650951
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/suspendFunctionAsCoroutine/privateFunctions.kt
2
816
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* class X { var res = "" suspend fun execute() { a() b() } private suspend fun a() { res += suspendThere("O") res += suspendThere("K") } private suspend fun b() { res += suspendThere("5") res += suspendThere("6") } } suspend fun suspendThere(v: String): String = suspendCoroutineOrReturn { x -> x.resume(v) COROUTINE_SUSPENDED } fun builder(c: suspend X.() -> Unit) { c.startCoroutine(X(), EmptyContinuation) } fun box(): String { var result = "" builder { execute() result = res } if (result != "OK56") return "fail 1: $result" return "OK" }
apache-2.0
047c463f7aa9834c112107be897d3035
17.545455
77
0.57598
3.867299
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/bridges/fakeOverrideWithSeveralSuperDeclarations.kt
5
477
interface D1 { fun foo(): Any } interface D2 { fun foo(): Number } interface F3 : D1, D2 open class D4 { fun foo(): Int = 42 } class F5 : F3, D4() fun box(): String { val z = F5() var result = z.foo() val d4: D4 = z val f3: F3 = z val d2: D2 = z val d1: D1 = z result += d4.foo() result += f3.foo() as Int result += d2.foo() as Int result += d1.foo() as Int return if (result == 5 * 42) "OK" else "Fail: $result" }
apache-2.0
a333f17f4085dc120f0d903e83fe5fe7
14.9
58
0.515723
2.620879
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/webview/events/TopLoadingStartEvent.kt
2
771
package abi44_0_0.host.exp.exponent.modules.api.components.webview.events import abi44_0_0.com.facebook.react.bridge.WritableMap import abi44_0_0.com.facebook.react.uimanager.events.Event import abi44_0_0.com.facebook.react.uimanager.events.RCTEventEmitter /** * Event emitted when loading has started */ class TopLoadingStartEvent(viewId: Int, private val mEventData: WritableMap) : Event<TopLoadingStartEvent>(viewId) { companion object { const val EVENT_NAME = "topLoadingStart" } override fun getEventName(): String = EVENT_NAME override fun canCoalesce(): Boolean = false override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) = rctEventEmitter.receiveEvent(viewTag, eventName, mEventData) }
bsd-3-clause
45a2b23289c26fee24ec2769244879ff
31.125
78
0.776913
4.057895
false
false
false
false
AndroidX/androidx
work/work-runtime/src/main/java/androidx/work/impl/WorkDatabasePathHelper.kt
3
4325
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work.impl import android.content.Context import android.os.Build import androidx.annotation.DoNotInline import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo import androidx.work.Logger import java.io.File private val TAG = Logger.tagWithPrefix("WrkDbPathHelper") /** * @return The name of the database. */ internal const val WORK_DATABASE_NAME = "androidx.work.workdb" // Supporting files for a SQLite database private val DATABASE_EXTRA_FILES = arrayOf("-journal", "-shm", "-wal") /** * Keeps track of {@link WorkDatabase} paths. * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) object WorkDatabasePathHelper { /** * Migrates [WorkDatabase] to the no-backup directory. * * @param context The application context. */ @JvmStatic fun migrateDatabase(context: Context) { val defaultDatabasePath = getDefaultDatabasePath(context) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && defaultDatabasePath.exists()) { Logger.get().debug(TAG, "Migrating WorkDatabase to the no-backup directory") migrationPaths(context).forEach { (source, destination) -> if (source.exists()) { if (destination.exists()) { Logger.get().warning(TAG, "Over-writing contents of $destination") } val renamed = source.renameTo(destination) val message = if (renamed) { "Migrated ${source}to $destination" } else { "Renaming $source to $destination failed" } Logger.get().debug(TAG, message) } } } } /** * Returns a [Map] of all paths which need to be migrated to the no-backup directory. * * @param context The application [Context] * @return a [Map] of paths to be migrated from source -> destination */ fun migrationPaths(context: Context): Map<File, File> { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val databasePath = getDefaultDatabasePath(context) val migratedPath = getDatabasePath(context) val map = DATABASE_EXTRA_FILES.associate { extra -> File(databasePath.path + extra) to File(migratedPath.path + extra) } map + (databasePath to migratedPath) } else emptyMap() } /** * @param context The application [Context] * @return The database path before migration to the no-backup directory. */ fun getDefaultDatabasePath(context: Context): File { return context.getDatabasePath(WORK_DATABASE_NAME) } /** * @param context The application [Context] * @return The the migrated database path. */ fun getDatabasePath(context: Context): File { return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // No notion of a backup directory exists. getDefaultDatabasePath(context) } else { getNoBackupPath(context) } } /** * Return the path for a [File] path in the [Context.getNoBackupFilesDir] * identified by the [String] fragment. * * @param context The application [Context] * @return the [File] */ @RequiresApi(23) private fun getNoBackupPath(context: Context): File { return File(Api21Impl.getNoBackupFilesDir(context), WORK_DATABASE_NAME) } } @RequiresApi(21) internal object Api21Impl { @DoNotInline fun getNoBackupFilesDir(context: Context): File { return context.noBackupFilesDir } }
apache-2.0
95823bec3933d594756e44d70524c1a0
33.333333
93
0.637225
4.431352
false
false
false
false
smmribeiro/intellij-community
plugins/editorconfig/src/org/editorconfig/language/codeinsight/quickfixes/EditorConfigConvertToPlainPatternQuickFix.kt
12
1501
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight.quickfixes import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.codeStyle.CodeStyleManager import org.editorconfig.language.messages.EditorConfigBundle import org.editorconfig.language.psi.EditorConfigCharClass import org.editorconfig.language.services.EditorConfigElementFactory class EditorConfigConvertToPlainPatternQuickFix : LocalQuickFix { override fun getFamilyName() = EditorConfigBundle.get("quickfix.charclass.convert.to.plain.pattern.description") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val charClass = descriptor.psiElement as? EditorConfigCharClass ?: return val header = charClass.header val letter = charClass.charClassLetterList.first() val headerOffset = header.textOffset val range = charClass.textRange val actualRange = range.startOffset - headerOffset until range.endOffset - headerOffset val text = header.text val newText = text.replaceRange(actualRange, letter.text) val factory = EditorConfigElementFactory.getInstance(project) val newHeader = factory.createHeader(newText) CodeStyleManager.getInstance(project).performActionWithFormatterDisabled { header.replace(newHeader) } } }
apache-2.0
da015fcf12a2fd93c5691c35d996455b
45.90625
140
0.813458
4.9375
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/MoveConstructorsAfterFieldsConversion.kt
5
4850
// 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.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.assignmentStatement import org.jetbrains.kotlin.nj2k.tree.* class MoveConstructorsAfterFieldsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClassBody) return recurse(element) if (element.declarations.none { it is JKInitDeclaration }) return recurse(element) moveInitBlocks(element, isStatic = false) moveInitBlocks(element, isStatic = true) return recurse(element) } private fun moveInitBlocks(element: JKClassBody, isStatic: Boolean) { val data = computeDeclarationsData(element, isStatic) element.declarations = collectNewDeclarations(element, data, isStatic) } private fun computeDeclarationsData( element: JKClassBody, isStatic: Boolean, ): DeclarationsData { val moveAfter = mutableMapOf<JKDeclaration, JKDeclaration>() val forwardlyReferencedFields = mutableSetOf<JKField>() val declarationsToAdd = mutableListOf<JKDeclaration>() val order = element.declarations.withIndex().associateTo(mutableMapOf()) { (index, value) -> value to index } for (declaration in element.declarations) { when { declaration is JKInitDeclaration && declaration.isStatic == isStatic -> { declarationsToAdd += declaration val fields = findAllUsagesOfFieldsIn(declaration, element) { it.hasOtherModifier(OtherModifier.STATIC) == isStatic } moveAfter[declaration] = declaration val lastDependentField = fields.maxByOrNull(order::getValue) ?: continue val initDeclarationIndex = order.getValue(declaration) if (order.getValue(lastDependentField) < initDeclarationIndex) continue moveAfter[declaration] = lastDependentField for (field in fields) { if (order.getValue(field) > initDeclarationIndex) { forwardlyReferencedFields += field } } } declaration is JKField && declaration.hasOtherModifier(OtherModifier.STATIC) == isStatic -> { if (declaration.initializer !is JKStubExpression && declaration in forwardlyReferencedFields) { val assignment = createFieldAssignmentInitDeclaration(declaration, isStatic) moveAfter[assignment] = declarationsToAdd.last() order[assignment] = order.getValue(declarationsToAdd.last()) declarationsToAdd += assignment } } } } return DeclarationsData(order, moveAfter, declarationsToAdd) } @OptIn(ExperimentalStdlibApi::class) private fun collectNewDeclarations( element: JKClassBody, data: DeclarationsData, isStatic: Boolean, ): List<JKDeclaration> { var index = 0 val newDeclarations = buildList { for (declaration in element.declarations) { if (declaration !is JKInitDeclaration || declaration.isStatic != isStatic) { add(declaration) } val declarationIndex = data.order.getValue(declaration) while (index <= data.declarationsToAdd.lastIndex) { val initDeclaration = data.declarationsToAdd[index] val moveAfterIndex = data.order.getValue(data.moveAfter.getValue(initDeclaration)) if (declarationIndex >= moveAfterIndex) { add(initDeclaration) index++ } else { break } } } } return newDeclarations } private data class DeclarationsData( val order: Map<JKDeclaration, Int>, val moveAfter: Map<JKDeclaration, JKDeclaration>, val declarationsToAdd: List<JKDeclaration>, ) private fun createFieldAssignmentInitDeclaration(field: JKField, isStatic: Boolean): JKInitDeclaration { val initializer = field.initializer field.initializer = JKStubExpression() val block = JKBlockImpl(assignmentStatement(field, initializer, symbolProvider)) return if (isStatic) JKJavaStaticInitDeclaration(block) else JKKtInitDeclaration(block) } }
apache-2.0
fa644543a800d128a18a7b6ebdcdce0a
43.916667
158
0.629278
5.61993
false
false
false
false
mglukhikh/intellij-community
python/src/com/jetbrains/python/inspections/PyNamedTupleInspection.kt
1
4034
// Copyright 2000-2017 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.jetbrains.python.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import com.jetbrains.python.codeInsight.stdlib.PyStdlibTypeProvider import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyTargetExpression import com.jetbrains.python.psi.types.TypeEvalContext import java.util.* class PyNamedTupleInspection : PyInspection() { companion object { fun inspectFieldsOrder(cls: PyClass, context: TypeEvalContext, callback: (PsiElement, String, ProblemHighlightType) -> Unit) { val fieldsProcessor = FieldsProcessor(context) cls.processClassLevelDeclarations(fieldsProcessor) registerErrorOnTargetsAboveBound(fieldsProcessor.lastFieldWithoutDefaultValue, fieldsProcessor.fieldsWithDefaultValue, "Fields with a default value must come after any fields without a default.", callback) } private fun registerErrorOnTargetsAboveBound(bound: PyTargetExpression?, targets: TreeSet<PyTargetExpression>, message: String, callback: (PsiElement, String, ProblemHighlightType) -> Unit) { if (bound != null) { targets .headSet(bound) .forEach { callback(it, message, ProblemHighlightType.GENERIC_ERROR) } } } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session) private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPyClass(node: PyClass?) { super.visitPyClass(node) if (node != null && LanguageLevel.forElement(node).isAtLeast(LanguageLevel.PYTHON36) && PyStdlibTypeProvider.isTypingNamedTupleDirectInheritor(node, myTypeEvalContext)) { inspectFieldsOrder(node, myTypeEvalContext, this::registerProblem) } } } private class FieldsProcessor(private val context: TypeEvalContext) : PsiScopeProcessor { val lastFieldWithoutDefaultValue: PyTargetExpression? get() = lastFieldWithoutDefaultValueBox.result val fieldsWithDefaultValue: TreeSet<PyTargetExpression> private val lastFieldWithoutDefaultValueBox: MaxBy<PyTargetExpression> init { val offsetComparator = compareBy(PyTargetExpression::getTextOffset) lastFieldWithoutDefaultValueBox = MaxBy(offsetComparator) fieldsWithDefaultValue = TreeSet(offsetComparator) } override fun execute(element: PsiElement, state: ResolveState): Boolean { if (element is PyTargetExpression) { val annotation = element.annotation if (annotation != null && PyTypingTypeProvider.isClassVarAnnotation(annotation, context)) { return true } when { element.findAssignedValue() != null -> fieldsWithDefaultValue.add(element) else -> lastFieldWithoutDefaultValueBox.apply(element) } } return true } } private class MaxBy<T>(private val comparator: Comparator<T>) { var result: T? = null private set fun apply(t: T) { if (result == null || comparator.compare(result, t) < 0) { result = t } } } }
apache-2.0
8b5ff8a6946d10d173c86a9be9777a54
37.798077
140
0.689638
5.314888
false
false
false
false
viartemev/requestmapper
src/main/kotlin/com/viartemev/requestmapper/utils/CommonUtils.kt
1
619
package com.viartemev.requestmapper.utils fun String.unquote(): String = if (length >= 2 && first() == '"' && last() == '"') substring(1, this.length - 1) else this fun String.inCurlyBrackets(): Boolean = length >= 2 && first() == '{' && last() == '}' fun String.unquoteCurlyBrackets(): String = if (this.inCurlyBrackets()) this.drop(1).dropLast(1) else this fun String.addCurlyBrackets(): String = "{$this}" fun List<String>.dropFirstEmptyStringIfExists(): List<String> = if (this.isNotEmpty() && this.first().isEmpty()) this.drop(1) else this fun String.isNumeric(): Boolean = this.toBigDecimalOrNull() != null
mit
d605f277321db995a768f9a6e682b60b
46.615385
135
0.680129
3.684524
false
false
false
false
FuturemanGaming/FutureBot-Discord
src/main/kotlin/com/futuremangaming/futurebot/music/PlayerSendHandler.kt
1
1392
/* * Copyright 2014-2017 FuturemanGaming * * 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.futuremangaming.futurebot.music import com.sedmelluq.discord.lavaplayer.player.AudioPlayer import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame import net.dv8tion.jda.core.audio.AudioSendHandler class PlayerSendHandler(private val player: AudioPlayer) : AudioSendHandler { private var lastFrame: AudioFrame? = null override fun provide20MsAudio(): ByteArray? { if (lastFrame === null) { lastFrame = player.provide() } val data = lastFrame?.data lastFrame = null return data } override fun canProvide(): Boolean { if (lastFrame === null) { lastFrame = player.provide() } return lastFrame !== null } override fun isOpus(): Boolean = true }
apache-2.0
a46e2a0152222fb5f419d97a81526b0f
29.26087
77
0.694684
4.256881
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/ProjectCardHolderViewModel.kt
1
25817
package com.kickstarter.viewmodels import android.util.Pair import androidx.annotation.NonNull import com.kickstarter.R import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.utils.NumberUtils import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.ProgressBarUtils import com.kickstarter.libs.utils.extensions.ProjectMetadata import com.kickstarter.libs.utils.extensions.deadlineCountdownValue import com.kickstarter.libs.utils.extensions.isCompleted import com.kickstarter.libs.utils.extensions.metadataForProject import com.kickstarter.libs.utils.extensions.negate import com.kickstarter.models.Category import com.kickstarter.models.Project import com.kickstarter.models.User import com.kickstarter.models.extensions.replaceSmallImageWithMediumIfEmpty import com.kickstarter.services.DiscoveryParams import com.kickstarter.ui.data.Editorial import com.kickstarter.ui.viewholders.ProjectCardViewHolder import org.joda.time.DateTime import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface ProjectCardHolderViewModel { interface Inputs { /** Call to configure view model with a project and current discovery params. */ fun configureWith(projectAndDiscoveryParams: Pair<Project, DiscoveryParams>) /** Call when the project card has been clicked. */ fun projectCardClicked() /** Call when the heart button is clicked. */ fun heartButtonClicked() } interface Outputs { /** Emits the project's number of backers. */ fun backersCountTextViewText(): Observable<String> /** Emits to determine if backing view should be shown. */ fun backingViewGroupIsGone(): Observable<Boolean> /** Emits the a string representing how much time the project has remaining. */ fun deadlineCountdownText(): Observable<String> /** Emits to determine if featured view should be shown. */ fun featuredViewGroupIsGone(): Observable<Boolean> /** Emits list of friends who have also backed this project. */ fun friendsForNamepile(): Observable<List<User>> /** Emits to determine if second face in facepile should be shown. */ fun friendAvatar2IsGone(): Observable<Boolean> /** Emits to determine if third face in facepile should be shown. */ fun friendAvatar3IsGone(): Observable<Boolean> /** Emits URL string of first friend's avatar. */ fun friendAvatarUrl1(): Observable<String> /** Emits URL string of second friend's avatar. */ fun friendAvatarUrl2(): Observable<String> /** Emits URL string of third friend's avatar. */ fun friendAvatarUrl3(): Observable<String> /** Emits to determine if project has a photo to display. */ fun imageIsInvisible(): Observable<Boolean> /** Emits to determine if friends who have also backed should be shown. */ fun friendBackingViewIsHidden(): Observable<Boolean> /** Emits to determine if successful funding state should be shown. */ fun fundingSuccessfulViewGroupIsGone(): Observable<Boolean> /** Emits to determine if unsuccessful funding state should be shown. */ fun fundingUnsuccessfulViewGroupIsGone(): Observable<Boolean> /** Emits a Boolean determining if the project's location should be shown. */ fun locationContainerIsGone(): Observable<Boolean> /** Emits the displayable name of the location of the project. */ fun locationName(): Observable<String> /** Emits to determine if metadata container should be shown. */ fun metadataViewGroupIsGone(): Observable<Boolean> /** Emits background drawable resource ID of metadata container. */ fun metadataViewGroupBackgroundDrawable(): Observable<Int> /** Emits project to be used for calculating countdown. */ fun projectForDeadlineCountdownDetail(): Observable<Project> /** Emits percentage representing project funding. */ fun percentageFundedForProgressBar(): Observable<Int> /** Emits to determine if funded progress bar should be shown. */ fun percentageFundedProgressBarIsGone(): Observable<Boolean> /** Emits string representation of project funding percentage. */ fun percentageFundedTextViewText(): Observable<String> /** Emits URL string of project cover photo. */ fun photoUrl(): Observable<String> /** Emits project name and blurb. */ fun nameAndBlurbText(): Observable<Pair<String, String>> /** Emits when project card is clicked. */ fun notifyDelegateOfProjectClick(): Observable<Project> /** Emits time project was canceled. */ fun projectCanceledAt(): Observable<DateTime> /** Emits to determine if stats container should be shown. */ fun projectCardStatsViewGroupIsGone(): Observable<Boolean> /** Emits time project was unsuccessfully funded. */ fun projectFailedAt(): Observable<DateTime> /** Emits to determine if state container should be shown. */ fun projectStateViewGroupIsGone(): Observable<Boolean> /** Emits to determine if project (sub)category tag should be shown. */ fun projectSubcategoryIsGone(): Observable<Boolean> /** Emits project (sub)category. */ fun projectSubcategoryName(): Observable<String> /** Emits time project was successfully funded. */ fun projectSuccessfulAt(): Observable<DateTime> /** Emits time project was suspended. */ fun projectSuspendedAt(): Observable<DateTime> /** Emits to determine if project tags container should be shown. */ fun projectTagContainerIsGone(): Observable<Boolean> /** Emits to determine if project we love tag container should be shown. */ fun projectWeLoveIsGone(): Observable<Boolean> /** Emits project's root category. */ fun rootCategoryNameForFeatured(): Observable<String> /** Emits to determine if saved container should shown. */ fun savedViewGroupIsGone(): Observable<Boolean> /** Emits to determine if padding should be added to top of view. */ fun setDefaultTopPadding(): Observable<Boolean> /** Emits a drawable id that corresponds to whether the project is saved. */ fun heartDrawableId(): Observable<Int> /** Emits the current [Project] to Toggle save */ fun notifyDelegateOfHeartButtonClicked(): Observable<Project> } class ViewModel(environment: Environment) : ActivityViewModel<ProjectCardViewHolder?>(environment), Inputs, Outputs { private fun shouldShowLocationTag(params: DiscoveryParams): Boolean { return params.tagId() != null && params.tagId() == Editorial.LIGHTS_ON.tagId } private fun areParamsAllOrSameCategoryAsProject(categoryPair: Pair<Category?, Category>): Boolean { return ObjectUtils.isNotNull(categoryPair.first) && categoryPair.first?.id() == categoryPair.second.id() } private val heartButtonClicked = PublishSubject.create<Void>() private val discoveryParams = PublishSubject.create<DiscoveryParams?>() private val project = PublishSubject.create<Project?>() private val projectCardClicked = PublishSubject.create<Void?>() private val backersCountTextViewText: Observable<String> private val backingViewGroupIsGone: Observable<Boolean> private val deadlineCountdownText: Observable<String> private val featuredViewGroupIsGone: Observable<Boolean> private val friendAvatar2IsGone: Observable<Boolean> private val friendAvatar3IsGone: Observable<Boolean> private val friendAvatarUrl1: Observable<String> private val friendAvatarUrl2: Observable<String> private val friendAvatarUrl3: Observable<String> private val friendBackingViewIsHidden: Observable<Boolean> private val friendsForNamepile: Observable<List<User>> private val fundingSuccessfulViewGroupIsGone: Observable<Boolean> private val fundingUnsuccessfulViewGroupIsGone: Observable<Boolean> private val imageIsInvisible: Observable<Boolean> private val locationName = BehaviorSubject.create<String>() private val locationContainerIsGone = BehaviorSubject.create<Boolean>() private val metadataViewGroupBackground: Observable<Int> private val metadataViewGroupIsGone: Observable<Boolean> private val nameAndBlurbText: Observable<Pair<String, String>> private val notifyDelegateOfProjectClick: Observable<Project> private val percentageFundedForProgressBar: Observable<Int> private val percentageFundedProgressBarIsGone: Observable<Boolean> private val percentageFundedTextViewText: Observable<String> private val photoUrl: Observable<String> private val projectForDeadlineCountdownDetail: Observable<Project> private val projectCardStatsViewGroupIsGone: Observable<Boolean> private val projectStateViewGroupIsGone: Observable<Boolean> private val projectCanceledAt: Observable<DateTime> private val projectFailedAt: Observable<DateTime> private val projectSubcategoryName: Observable<String> private val projectSubcategoryIsGone: Observable<Boolean> private val projectSuccessfulAt: Observable<DateTime> private val projectSuspendedAt: Observable<DateTime> private val projectTagContainerIsGone: Observable<Boolean> private val projectWeLoveIsGone: Observable<Boolean> private val rootCategoryNameForFeatured: Observable<String> private val savedViewGroupIsGone: Observable<Boolean> private val setDefaultTopPadding: Observable<Boolean> private val heartDrawableId = BehaviorSubject.create<Int>() private val notifyDelegateOfHeartButtonClicked = BehaviorSubject.create<Project>() @JvmField val inputs: Inputs = this @JvmField val outputs: Outputs = this override fun configureWith(projectAndDiscoveryParams: Pair<Project, DiscoveryParams>) { project.onNext(projectAndDiscoveryParams.first) discoveryParams.onNext(projectAndDiscoveryParams.second) } override fun heartButtonClicked() { this.heartButtonClicked.onNext(null) } override fun projectCardClicked() { projectCardClicked.onNext(null) } @NonNull override fun heartDrawableId(): Observable<Int> = this.heartDrawableId override fun backersCountTextViewText(): Observable<String> = backersCountTextViewText override fun backingViewGroupIsGone(): Observable<Boolean> = backingViewGroupIsGone override fun deadlineCountdownText(): Observable<String> = deadlineCountdownText override fun featuredViewGroupIsGone(): Observable<Boolean> = featuredViewGroupIsGone override fun friendAvatar2IsGone(): Observable<Boolean> = friendAvatar2IsGone override fun friendAvatar3IsGone(): Observable<Boolean> = friendAvatar3IsGone override fun friendAvatarUrl1(): Observable<String> = friendAvatarUrl1 override fun friendAvatarUrl2(): Observable<String> = friendAvatarUrl2 override fun friendAvatarUrl3(): Observable<String> = friendAvatarUrl3 override fun friendBackingViewIsHidden(): Observable<Boolean> = friendBackingViewIsHidden override fun friendsForNamepile(): Observable<List<User>> = friendsForNamepile override fun fundingSuccessfulViewGroupIsGone(): Observable<Boolean> = fundingSuccessfulViewGroupIsGone override fun fundingUnsuccessfulViewGroupIsGone(): Observable<Boolean> = fundingUnsuccessfulViewGroupIsGone override fun imageIsInvisible(): Observable<Boolean> = imageIsInvisible override fun locationContainerIsGone(): Observable<Boolean> = locationContainerIsGone override fun locationName(): Observable<String> = locationName override fun metadataViewGroupBackgroundDrawable(): Observable<Int> = metadataViewGroupBackground override fun metadataViewGroupIsGone(): Observable<Boolean> = metadataViewGroupIsGone override fun nameAndBlurbText(): Observable<Pair<String, String>> = nameAndBlurbText override fun notifyDelegateOfProjectClick(): Observable<Project> = notifyDelegateOfProjectClick override fun percentageFundedForProgressBar(): Observable<Int> = percentageFundedForProgressBar override fun percentageFundedProgressBarIsGone(): Observable<Boolean> = percentageFundedProgressBarIsGone override fun percentageFundedTextViewText(): Observable<String> = percentageFundedTextViewText override fun photoUrl(): Observable<String> = photoUrl override fun projectCardStatsViewGroupIsGone(): Observable<Boolean> = projectCardStatsViewGroupIsGone override fun projectForDeadlineCountdownDetail(): Observable<Project> = projectForDeadlineCountdownDetail override fun projectStateViewGroupIsGone(): Observable<Boolean> = projectStateViewGroupIsGone override fun projectSubcategoryIsGone(): Observable<Boolean> = projectSubcategoryIsGone override fun projectSubcategoryName(): Observable<String> = projectSubcategoryName override fun projectCanceledAt(): Observable<DateTime> = projectCanceledAt override fun projectFailedAt(): Observable<DateTime> = projectFailedAt override fun projectSuccessfulAt(): Observable<DateTime> = projectSuccessfulAt override fun projectSuspendedAt(): Observable<DateTime> = projectSuspendedAt override fun projectTagContainerIsGone(): Observable<Boolean> = projectTagContainerIsGone override fun projectWeLoveIsGone(): Observable<Boolean> = projectWeLoveIsGone override fun rootCategoryNameForFeatured(): Observable<String> = rootCategoryNameForFeatured override fun setDefaultTopPadding(): Observable<Boolean> = setDefaultTopPadding override fun savedViewGroupIsGone(): Observable<Boolean> = savedViewGroupIsGone override fun notifyDelegateOfHeartButtonClicked(): Observable<Project> = this.notifyDelegateOfHeartButtonClicked init { projectForDeadlineCountdownDetail = project backersCountTextViewText = project .map { it?.backersCount() } .map { value -> value?.let { it -> NumberUtils.format( it ) } } backingViewGroupIsGone = project .map { it?.metadataForProject() !== ProjectMetadata.BACKING } deadlineCountdownText = project .map { it.deadlineCountdownValue() } .map { NumberUtils.format(it) } project .map { p -> if (p.isStarred()) R.drawable.icon__heart else R.drawable.icon__heart_outline } .subscribe(this.heartDrawableId) project .compose(Transformers.takeWhen(heartButtonClicked)) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .compose(bindToLifecycle()) .subscribe { notifyDelegateOfHeartButtonClicked.onNext(it) } featuredViewGroupIsGone = project .map { it?.metadataForProject() !== ProjectMetadata.CATEGORY_FEATURED } friendAvatarUrl1 = project .filter(Project::isFriendBacking) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .map { it[0].avatar().replaceSmallImageWithMediumIfEmpty() } .filter { it.isNotEmpty() } friendAvatarUrl2 = project .filter(Project::isFriendBacking) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .filter { it.size > 1 } .map { it[1].avatar().replaceSmallImageWithMediumIfEmpty() } .filter { it.isNotEmpty() } friendAvatarUrl3 = project .filter(Project::isFriendBacking) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .filter { it.size > 2 } .map { it[2].avatar().replaceSmallImageWithMediumIfEmpty() } .filter { it.isNotEmpty() } friendAvatar2IsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .map { it != null && it.size > 1 } .map { it.negate() } friendAvatar3IsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .map { it != null && it.size > 2 } .map { it.negate() } friendBackingViewIsHidden = project .map(Project::isFriendBacking) .map { it.negate() } friendsForNamepile = project .filter(Project::isFriendBacking) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } fundingUnsuccessfulViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { ( it.state() != Project.STATE_CANCELED && it.state() != Project.STATE_FAILED && it.state() != Project.STATE_SUSPENDED ) } fundingSuccessfulViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.state() != Project.STATE_SUCCESSFUL } imageIsInvisible = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.photo() } .map { ObjectUtils.isNull(it) } project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.location() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.displayableName() } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe { locationName.onNext(it) } discoveryParams .map { shouldShowLocationTag(it) } .compose(Transformers.combineLatestPair(project)) .map { distanceSortAndProject: Pair<Boolean, Project>? -> distanceSortAndProject?.first == true && ObjectUtils.isNotNull( distanceSortAndProject.second.location() ) } .map { it.negate() } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe { locationContainerIsGone.onNext(it) } metadataViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.metadataForProject() == null } metadataViewGroupBackground = backingViewGroupIsGone .map { gone: Boolean -> if (gone) R.drawable.rect_white_grey_stroke else R.drawable.rect_green_grey_stroke } nameAndBlurbText = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { Pair.create( it.name(), it.blurb() ) } notifyDelegateOfProjectClick = project .compose(Transformers.takeWhen(projectCardClicked)) percentageFundedForProgressBar = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { if (it.state() == Project.STATE_LIVE || it.state() == Project.STATE_SUCCESSFUL) it.percentageFunded() else 0.0f }.map { ProgressBarUtils.progress(it) } percentageFundedProgressBarIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.state() == Project.STATE_CANCELED } percentageFundedTextViewText = project .map { it.percentageFunded() } .map { NumberUtils.flooredPercentage(it) } photoUrl = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { if (it.photo() == null) null else it.photo()?.full() } projectCanceledAt = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .filter { it.state() == Project.STATE_CANCELED } .map { it.stateChangedAt() } .compose(Transformers.coalesce(DateTime())) projectCardStatsViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.state() != Project.STATE_LIVE } projectFailedAt = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .filter { it.state() == Project.STATE_FAILED } .map { it.stateChangedAt() } .compose(Transformers.coalesce(DateTime())) projectStateViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.isCompleted() } .map { it.negate() } val projectCategory = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.category() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } projectSubcategoryIsGone = discoveryParams .map { it.category() } .compose(Transformers.combineLatestPair(projectCategory)) .map { areParamsAllOrSameCategoryAsProject(it) }.distinctUntilChanged() projectSubcategoryName = projectCategory .map { it.name() } projectSuccessfulAt = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .filter { it.state() == Project.STATE_SUCCESSFUL } .map { it.stateChangedAt() } .compose(Transformers.coalesce(DateTime())) projectSuspendedAt = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .filter { it.state() == Project.STATE_SUSPENDED } .map { it.stateChangedAt() } .compose(Transformers.coalesce(DateTime())) projectWeLoveIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.staffPick() } .compose(Transformers.coalesce(false)) .compose( Transformers.combineLatestPair( discoveryParams.map { it.staffPicks() } .compose(Transformers.coalesce(false)) ) ) .map { it.first == true && it.second == false } .map { it.negate() } .distinctUntilChanged() projectTagContainerIsGone = Observable.combineLatest<Boolean, Boolean, Pair<Boolean, Boolean>>( projectSubcategoryIsGone, projectWeLoveIsGone ) { a: Boolean?, b: Boolean? -> Pair.create(a, b) } .map { it.first && it.second } .distinctUntilChanged() rootCategoryNameForFeatured = projectCategory .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.root() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.name() } savedViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.metadataForProject() !== ProjectMetadata.SAVING } setDefaultTopPadding = metadataViewGroupIsGone } } }
apache-2.0
3fe9ee3279632ab70ccc3c030e3e74a8
45.019608
120
0.618778
5.378542
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/diagnosticBased/UnusedVariableInspection.kt
1
1957
// 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.k2.codeinsight.inspections.diagnosticBased import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicators.* import org.jetbrains.kotlin.idea.codeinsight.utils.isExplicitTypeReferenceNeededForTypeInference import org.jetbrains.kotlin.idea.codeinsight.utils.removeProperty import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtProperty import kotlin.reflect.KClass internal class UnusedVariableInspection : AbstractKotlinDiagnosticBasedInspection<KtNamedDeclaration, KtFirDiagnostic.UnusedVariable, KotlinApplicatorInput.Empty>( elementType = KtNamedDeclaration::class, ) { override fun getDiagnosticType() = KtFirDiagnostic.UnusedVariable::class override fun getInputByDiagnosticProvider() = inputByDiagnosticProvider<_, KtFirDiagnostic.UnusedVariable, _> { diagnostic -> val ktProperty = diagnostic.psi as? KtProperty ?: return@inputByDiagnosticProvider null if (ktProperty.isExplicitTypeReferenceNeededForTypeInference()) return@inputByDiagnosticProvider null KotlinApplicatorInput } override fun getApplicabilityRange() = ApplicabilityRanges.DECLARATION_NAME override fun getApplicator() = applicator<KtNamedDeclaration, KotlinApplicatorInput.Empty> { familyName(KotlinBundle.lazyMessage("remove.element")) actionName { psi, _ -> KotlinBundle.message("remove.variable.0", psi.name.toString()) } applyTo { psi, _ -> removeProperty(psi as KtProperty) } } }
apache-2.0
54fc8cfd46f15b504aa07d0177153b46
50.526316
158
0.775677
5.303523
false
false
false
false
bitsydarel/DBWeather
dbweatherweather/src/main/java/com/dbeginc/dbweatherweather/viewmodels/WeatherMapper.kt
1
6421
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweatherweather.viewmodels import com.dbeginc.dbweathercommon.utils.round import com.dbeginc.dbweatherdomain.entities.weather.* import com.dbeginc.dbweatherweather.R import org.threeten.bp.Instant import org.threeten.bp.ZoneId import org.threeten.bp.format.DateTimeFormatter import java.util.* /** * Created by darel on 18.09.17. * * Weather ViewModel Mapper */ fun Weather.toUi(): WeatherModel { val unit = if (flags.units == "us") "F" else "C" val currentDayName = Calendar.getInstance().getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()) val today = daily.data.mapIndexed { index, day -> index to day } .first { (_, day) -> day.time.dayOfWeek(timezone) == currentDayName } .second return WeatherModel( location = location.toUi(), current = currently.toUi( location = location.name, timeZone = timezone, unit = unit, sunrise = today.sunriseTime, sunset = today.sunsetTime ), hourly = hourly.data.map { hour -> hour.toUi(unit, timezone) }, daily = daily.data.map { day -> day.toUi( dayName = day.time.dayOfWeek(timezone), timeZone = timezone, unit = unit ) }, alerts = alerts?.map { alert -> alert.toUi(timezone) } ) } fun Currently.toUi(location: String, sunrise: Long, sunset: Long, unit: String, timeZone: String?): CurrentWeatherModel { return CurrentWeatherModel( location = location, temperature = temperature.round(), apparentTemperature = apparentTemperature?.round() ?: 0, icon = icon.getId(), summary = summary, time = time, windSpeed = windSpeed.toMps(), humidity = humidity.toPercent(), cloudCover = cloudCover.toPercent(), precipitationProbability = precipProbability.toPercent(), sunrise = sunrise.toFormattedTime(timeZone), sunset = sunset.toFormattedTime(timeZone), temperatureUnit = unit ) } fun DailyData.toUi(dayName: String, timeZone: String?, unit: String): DayWeatherModel { return DayWeatherModel( dayName = dayName, time = time, summary = summary, icon = icon.getId(), temperatureUnit = unit, temperatureHigh = temperatureHigh.round(), temperatureHighTime = temperatureHighTime, temperatureLow = temperatureLow.round(), temperatureLowTime = temperatureLowTime, apparentTemperatureHigh = apparentTemperatureHigh.round(), apparentTemperatureLow = apparentTemperatureLow.round(), dewPoint = dewPoint, humidity = humidity.toPercent(), pressure = pressure, windSpeed = windSpeed.toPercent(), windGust = windGust, windGustTime = windGustTime, windBearing = windBearing, moonPhase = moonPhase, uvIndex = uvIndex, uvIndexTime = uvIndexTime, sunsetTime = sunsetTime.toFormattedTime(timeZone), sunriseTime = sunriseTime.toFormattedTime(timeZone), precipIntensity = precipIntensity, precipIntensityMax = precipIntensityMax, precipProbability = precipProbability, precipType = precipType ) } fun HourlyData.toUi(unit: String, timeZone: String?): HourWeatherModel { return HourWeatherModel( hourlyTime = time.toHour(timeZone), time = time, icon = icon.getId(), temperature = temperature.round(), temperatureUnit = unit ) } fun Alert.toUi(timeZone: String?): AlertWeatherModel { return AlertWeatherModel( time = time.toFormattedTime(timeZone), title = title, description = description, uri = uri, expires = expires.toFormattedTime(timeZone), severity = severity, regions = regions ) } fun Location.toUi(): WeatherLocationModel { return WeatherLocationModel( name = name, latitude = latitude, longitude = longitude, countryName = countryName, countryCode = countryCode ) } fun Long.dayOfWeek(timeZone: String?): String { val format = DateTimeFormatter.ofPattern("EEEE") return Instant.ofEpochSecond(this) .atZone(ZoneId.of(timeZone ?: TimeZone.getDefault().id)) .format(format) } fun Long.toHour(timeZone: String?) : String { val format = DateTimeFormatter.ofPattern("h a") return Instant.ofEpochSecond(this) .atZone(ZoneId.of(timeZone ?: TimeZone.getDefault().id)) .format(format) } fun Double.toMps() : String = "%d mps".format(this.round()) fun Double.toPercent() : String = "%d%%".format(this.round()) fun Long.toFormattedTime(timeZone: String?) : String { val format = DateTimeFormatter.ofPattern("h:mm a") return Instant.ofEpochSecond(this) .atZone(ZoneId.of(timeZone ?: TimeZone.getDefault().id)) .format(format) } fun String.getId(): Int { return when (this) { "clear-night" -> R.drawable.clear_night "rain" -> R.drawable.rain "snow" -> R.drawable.snow "sleet" -> R.drawable.sleet "wind" -> R.drawable.wind "fog" -> R.drawable.fog "cloudy" -> R.drawable.cloudy "partly-cloudy-day" -> R.drawable.partly_cloudy "partly-cloudy-night" -> R.drawable.cloudy_night else -> R.drawable.clear_day } }
gpl-3.0
5aaf3caf278acd2b9c231a8a73b648bf
33.342246
121
0.609407
4.459028
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueFragment.kt
1
15739
package eu.kanade.tachiyomi.ui.catalogue import android.content.res.Configuration import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.SearchView import android.support.v7.widget.Toolbar import android.view.* import android.view.animation.AnimationUtils import android.widget.ArrayAdapter import android.widget.ProgressBar import android.widget.Spinner import com.afollestad.materialdialogs.MaterialDialog import com.f2prateek.rx.preferences.Preference import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.source.online.LoginSource import eu.kanade.tachiyomi.ui.base.adapter.FlexibleViewHolder import eu.kanade.tachiyomi.ui.base.fragment.BaseRxFragment import eu.kanade.tachiyomi.ui.main.MainActivity import eu.kanade.tachiyomi.ui.manga.MangaActivity import eu.kanade.tachiyomi.util.getResourceDrawable import eu.kanade.tachiyomi.util.snack import eu.kanade.tachiyomi.util.toast import eu.kanade.tachiyomi.widget.DividerItemDecoration import eu.kanade.tachiyomi.widget.EndlessScrollListener import eu.kanade.tachiyomi.widget.IgnoreFirstSpinnerListener import kotlinx.android.synthetic.main.fragment_catalogue.* import kotlinx.android.synthetic.main.toolbar.* import nucleus.factory.RequiresPresenter import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.subjects.PublishSubject import timber.log.Timber import java.util.concurrent.TimeUnit.MILLISECONDS /** * Fragment that shows the manga from the catalogue. * Uses R.layout.fragment_catalogue. */ @RequiresPresenter(CataloguePresenter::class) open class CatalogueFragment : BaseRxFragment<CataloguePresenter>(), FlexibleViewHolder.OnListItemClickListener { /** * Spinner shown in the toolbar to change the selected source. */ private var spinner: Spinner? = null /** * Adapter containing the list of manga from the catalogue. */ private lateinit var adapter: CatalogueAdapter /** * Scroll listener for grid mode. It loads next pages when the end of the list is reached. */ private lateinit var gridScrollListener: EndlessScrollListener /** * Scroll listener for list mode. It loads next pages when the end of the list is reached. */ private lateinit var listScrollListener: EndlessScrollListener /** * Query of the search box. */ private val query: String get() = presenter.query /** * Selected index of the spinner (selected source). */ private var selectedIndex: Int = 0 /** * Time in milliseconds to wait for input events in the search query before doing network calls. */ private val SEARCH_TIMEOUT = 1000L /** * Subject to debounce the query. */ private val queryDebouncerSubject = PublishSubject.create<String>() /** * Subscription of the debouncer subject. */ private var queryDebouncerSubscription: Subscription? = null /** * Subscription of the number of manga per row. */ private var numColumnsSubscription: Subscription? = null /** * Search item. */ private var searchItem: MenuItem? = null /** * Property to get the toolbar from the containing activity. */ private val toolbar: Toolbar get() = (activity as MainActivity).toolbar companion object { /** * Creates a new instance of this fragment. * * @return a new instance of [CatalogueFragment]. */ fun newInstance(): CatalogueFragment { return CatalogueFragment() } } override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View? { return inflater.inflate(R.layout.fragment_catalogue, container, false) } override fun onViewCreated(view: View, savedState: Bundle?) { // If the source list is empty or it only has unlogged sources, return to main screen. val sources = presenter.sources if (sources.isEmpty() || sources.all { it is LoginSource && !it.isLogged() }) { context.toast(R.string.no_valid_sources) activity.onBackPressed() return } // Initialize adapter, scroll listener and recycler views adapter = CatalogueAdapter(this) val glm = catalogue_grid.layoutManager as GridLayoutManager gridScrollListener = EndlessScrollListener(glm, { requestNextPage() }) catalogue_grid.setHasFixedSize(true) catalogue_grid.adapter = adapter catalogue_grid.addOnScrollListener(gridScrollListener) val llm = LinearLayoutManager(activity) listScrollListener = EndlessScrollListener(llm, { requestNextPage() }) catalogue_list.setHasFixedSize(true) catalogue_list.adapter = adapter catalogue_list.layoutManager = llm catalogue_list.addOnScrollListener(listScrollListener) catalogue_list.addItemDecoration( DividerItemDecoration(context.theme.getResourceDrawable(R.attr.divider_drawable))) if (presenter.isListMode) { switcher.showNext() } numColumnsSubscription = getColumnsPreferenceForCurrentOrientation().asObservable() .doOnNext { catalogue_grid.spanCount = it } .skip(1) // Set again the adapter to recalculate the covers height .subscribe { catalogue_grid.adapter = adapter } switcher.inAnimation = AnimationUtils.loadAnimation(activity, android.R.anim.fade_in) switcher.outAnimation = AnimationUtils.loadAnimation(activity, android.R.anim.fade_out) // Create toolbar spinner val themedContext = activity.supportActionBar?.themedContext ?: activity val spinnerAdapter = ArrayAdapter(themedContext, android.R.layout.simple_spinner_item, presenter.sources) spinnerAdapter.setDropDownViewResource(R.layout.spinner_item) val onItemSelected = IgnoreFirstSpinnerListener { position -> val source = spinnerAdapter.getItem(position) if (!presenter.isValidSource(source)) { spinner?.setSelection(selectedIndex) context.toast(R.string.source_requires_login) } else if (source != presenter.source) { selectedIndex = position showProgressBar() glm.scrollToPositionWithOffset(0, 0) llm.scrollToPositionWithOffset(0, 0) presenter.setActiveSource(source) activity.invalidateOptionsMenu() } } selectedIndex = presenter.sources.indexOf(presenter.source) spinner = Spinner(themedContext).apply { adapter = spinnerAdapter setSelection(selectedIndex) onItemSelectedListener = onItemSelected } setToolbarTitle("") toolbar.addView(spinner) showProgressBar() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.catalogue_list, menu) // Initialize search menu searchItem = menu.findItem(R.id.action_search).apply { val searchView = actionView as SearchView if (!query.isBlank()) { expandActionView() searchView.setQuery(query, true) searchView.clearFocus() } searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { onSearchEvent(query, true) return true } override fun onQueryTextChange(newText: String): Boolean { onSearchEvent(newText, false) return true } }) } // Setup filters button menu.findItem(R.id.action_set_filter).apply { if (presenter.source.filters.isEmpty()) { isEnabled = false icon.alpha = 128 } else { isEnabled = true icon.alpha = 255 } } // Show next display mode menu.findItem(R.id.action_display_mode).apply { val icon = if (presenter.isListMode) R.drawable.ic_view_module_white_24dp else R.drawable.ic_view_list_white_24dp setIcon(icon) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_display_mode -> swapDisplayMode() R.id.action_set_filter -> showFiltersDialog() else -> return super.onOptionsItemSelected(item) } return true } override fun onResume() { super.onResume() queryDebouncerSubscription = queryDebouncerSubject.debounce(SEARCH_TIMEOUT, MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { searchWithQuery(it) } } override fun onPause() { queryDebouncerSubscription?.unsubscribe() super.onPause() } override fun onDestroyView() { numColumnsSubscription?.unsubscribe() searchItem?.let { if (it.isActionViewExpanded) it.collapseActionView() } spinner?.let { toolbar.removeView(it) } super.onDestroyView() } /** * Called when the input text changes or is submitted. * * @param query the new query. * @param now whether to send the network call now or debounce it by [SEARCH_TIMEOUT]. */ private fun onSearchEvent(query: String, now: Boolean) { if (now) { searchWithQuery(query) } else { queryDebouncerSubject.onNext(query) } } /** * Restarts the request with a new query. * * @param newQuery the new query. */ private fun searchWithQuery(newQuery: String) { // If text didn't change, do nothing if (query == newQuery) return showProgressBar() catalogue_grid.layoutManager.scrollToPosition(0) catalogue_list.layoutManager.scrollToPosition(0) presenter.restartPager(newQuery) } /** * Requests the next page (if available). Called from scroll listeners when they reach the end. */ private fun requestNextPage() { if (presenter.hasNextPage()) { showGridProgressBar() presenter.requestNext() } } /** * Called from the presenter when the network request is received. * * @param page the current page. * @param mangas the list of manga of the page. */ fun onAddPage(page: Int, mangas: List<Manga>) { hideProgressBar() if (page == 1) { adapter.clear() gridScrollListener.resetScroll() listScrollListener.resetScroll() } adapter.addItems(mangas) } /** * Called from the presenter when the network request fails. * * @param error the error received. */ fun onAddPageError(error: Throwable) { hideProgressBar() Timber.e(error) catalogue_view.snack(error.message ?: "", Snackbar.LENGTH_INDEFINITE) { setAction(R.string.action_retry) { showProgressBar() presenter.requestNext() } } } /** * Called from the presenter when a manga is initialized. * * @param manga the manga initialized */ fun onMangaInitialized(manga: Manga) { getHolder(manga)?.setImage(manga) } /** * Swaps the current display mode. */ fun swapDisplayMode() { presenter.swapDisplayMode() val isListMode = presenter.isListMode activity.invalidateOptionsMenu() switcher.showNext() if (!isListMode) { // Initialize mangas if going to grid view presenter.initializeMangas(adapter.items) } } /** * Returns a preference for the number of manga per row based on the current orientation. * * @return the preference. */ fun getColumnsPreferenceForCurrentOrientation(): Preference<Int> { return if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) presenter.prefs.portraitColumns() else presenter.prefs.landscapeColumns() } /** * Returns the view holder for the given manga. * * @param manga the manga to find. * @return the holder of the manga or null if it's not bound. */ private fun getHolder(manga: Manga): CatalogueGridHolder? { return catalogue_grid.findViewHolderForItemId(manga.id!!) as? CatalogueGridHolder } /** * Shows the progress bar. */ private fun showProgressBar() { progress.visibility = ProgressBar.VISIBLE } /** * Shows the progress bar at the end of the screen. */ private fun showGridProgressBar() { progress_grid.visibility = ProgressBar.VISIBLE } /** * Hides active progress bars. */ private fun hideProgressBar() { progress.visibility = ProgressBar.GONE progress_grid.visibility = ProgressBar.GONE } /** * Called when a manga is clicked. * * @param position the position of the element clicked. * @return true if the item should be selected, false otherwise. */ override fun onListItemClick(position: Int): Boolean { val item = adapter.getItem(position) ?: return false val intent = MangaActivity.newIntent(activity, item, true) startActivity(intent) return false } /** * Called when a manga is long clicked. * * @param position the position of the element clicked. */ override fun onListItemLongClick(position: Int) { val manga = adapter.getItem(position) ?: return val textRes = if (manga.favorite) R.string.remove_from_library else R.string.add_to_library MaterialDialog.Builder(activity) .items(getString(textRes)) .itemsCallback { dialog, itemView, which, text -> when (which) { 0 -> { presenter.changeMangaFavorite(manga) adapter.notifyItemChanged(position) } } }.show() } /** * Show the filter dialog for the source. */ private fun showFiltersDialog() { val allFilters = presenter.source.filters val selectedFilters = presenter.filters .map { filter -> allFilters.indexOf(filter) } .toTypedArray() MaterialDialog.Builder(context) .title(R.string.action_set_filter) .items(allFilters.map { it.name }) .itemsCallbackMultiChoice(selectedFilters) { dialog, positions, text -> val newFilters = positions.map { allFilters[it] } showProgressBar() presenter.setSourceFilter(newFilters) true } .positiveText(android.R.string.ok) .negativeText(android.R.string.cancel) .show() } }
gpl-3.0
58c2c346232bde5f835f83a26afd9a57
31.789583
113
0.629328
5.022017
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapter.kt
2
575
package eu.kanade.tachiyomi.ui.recent_updates import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.MangaChapter import eu.kanade.tachiyomi.data.download.model.Download class RecentChapter(mc: MangaChapter) : Chapter by mc.chapter { val manga = mc.manga private var _status: Int = 0 var status: Int get() = download?.status ?: _status set(value) { _status = value } @Transient var download: Download? = null val isDownloaded: Boolean get() = status == Download.DOWNLOADED }
gpl-3.0
876f7bb046457978e625a0302e125137
25.181818
63
0.709565
3.938356
false
false
false
false
idea4bsd/idea4bsd
platform/lang-impl/src/com/intellij/reporting/ReportExcessiveInlineHint.kt
2
4679
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.reporting import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import java.io.File class ReportExcessiveInlineHint : AnAction() { private val text = "Report Excessive Inline Hint" private val description = "Text line at caret will be anonymously reported to our servers" companion object { private val LOG = Logger.getInstance(ReportExcessiveInlineHint::class.java) } init { val presentation = templatePresentation presentation.text = text presentation.description = description } private val recorderId = "inline-hints-reports" private val file = File(PathManager.getTempPath(), recorderId) override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = false if (!isHintsEnabled()) return CommonDataKeys.PROJECT.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val range = getCurrentLineRange(editor) if (editor.getInlays(range).isNotEmpty()) { e.presentation.isEnabledAndVisible = true } } override fun actionPerformed(e: AnActionEvent) { val project = CommonDataKeys.PROJECT.getData(e.dataContext)!! val editor = CommonDataKeys.EDITOR.getData(e.dataContext)!! val document = editor.document val range = getCurrentLineRange(editor) val inlays = editor.getInlays(range) if (inlays.isNotEmpty()) { val line = document.getText(range) reportInlays(line.trim(), inlays) showHint(project) } } private fun reportInlays(text: String, inlays: List<Inlay>) { val hintManager = ParameterHintsPresentationManager.getInstance() val hints = inlays.mapNotNull { hintManager.getHintText(it) } trySend(text, hints) } private fun trySend(text: String, inlays: List<String>) { val report = InlayReport(text, inlays) writeToFile(createReportLine(recorderId, report)) trySendFileInBackground() } private fun trySendFileInBackground() { LOG.debug("File: ${file.path} Length: ${file.length()}") if (!file.exists() || file.length() == 0L) return ApplicationManager.getApplication().executeOnPooledThread { val text = file.readText() LOG.debug("File text $text") if (StatsSender.send(text, compress = false)) { file.delete() LOG.debug("File deleted") } } } private fun showHint(project: Project) { val notification = Notification( "Inline Hints", "Inline Hints Reporting", "Problematic inline hint was reported", NotificationType.INFORMATION ) notification.notify(project) } private fun writeToFile(line: String) { if (!file.exists()) { file.createNewFile() } file.appendText(line) } private fun getCurrentLineRange(editor: Editor): TextRange { val offset = editor.caretModel.currentCaret.offset val document = editor.document val line = document.getLineNumber(offset) return TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line)) } } private fun isHintsEnabled() = EditorSettingsExternalizable.getInstance().isShowParameterNameHints private fun Editor.getInlays(range: TextRange): List<Inlay> { return inlayModel.getInlineElementsInRange(range.startOffset, range.endOffset) } private class InlayReport(@JvmField var text: String, @JvmField var inlays: List<String>)
apache-2.0
057c245ceea66d9619f5748bbe5db079
33.160584
98
0.739474
4.516409
false
false
false
false
vovagrechka/fucking-everything
alraune/alkjs/src/alraune/alkjs-2.kt
1
1087
package alraune import org.w3c.dom.HTMLElement import vgrechka.* import kotlin.browser.document import kotlin.coroutines.experimental.* import kotlin.js.Promise class ResolvablePromise<T> { var resolve by notNullOnce<(T) -> Unit>() var reject by notNullOnce<(Throwable) -> Unit>() val promise = Promise<T> {resolve, reject -> this.resolve = resolve this.reject = reject } } suspend fun <T> await(p: Promise<T>): T = suspendCoroutine {cont-> p.then({cont.resume(it)}, {cont.resumeWithException(it)}) } fun <T> async(block: suspend () -> T): Promise<T> { val rep = ResolvablePromise<T>() block.startCoroutine(object : Continuation<T> { override val context: CoroutineContext get() = EmptyCoroutineContext override fun resume(value: T) {rep.resolve(value)} override fun resumeWithException(exception: Throwable) {rep.reject(exception)} }) return rep.promise } fun elbyid(domid: String): HTMLElement = document.getElementById(domid) as HTMLElement? ?: bitch("I want element #$domid")
apache-2.0
54feca0b90d80c0ec371f507b97f36bd
18.763636
86
0.678933
4.01107
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/create/CreateThinLvExecutor.kt
2
999
package com.github.kerubistan.kerub.planner.steps.storage.lvm.create import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LogicalVolume import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LvmLv class CreateThinLvExecutor( hostCommandExecutor: HostCommandExecutor, virtualDiskDynDao: VirtualStorageDeviceDynamicDao ) : AbstractCreateLvExecutor<CreateThinLv>(hostCommandExecutor, virtualDiskDynDao) { override fun perform(step: CreateThinLv): LogicalVolume = hostCommandExecutor.execute(step.host) { session -> LvmLv.create( session = session, vgName = step.volumeGroupName, size = step.disk.size, poolName = step.poolName, name = step.disk.id.toString() ) LvmLv.list(session = session, volName = step.disk.id.toString()) .single { it.name == step.disk.id.toString() } } }
apache-2.0
02772e5bb5a414ae7b9893d5352f85e4
37.461538
84
0.771772
3.964286
false
false
false
false