repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
JiangKlijna/leetcode-learning
kt/058 Length of Last Word/LengthofLastWord.kt
1
615
/** * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. * If the last word does not exist, return 0. * Note: A word is defined as a character sequence consists of non-space characters only. * For example, Given s = "Hello World", return 5. */ class LengthofLastWord { fun lengthOfLastWord(s: String): Int { var n = s.length - 1 if (n == -1) return 0 while (n >= 0 && s[n] == ' ') n-- val size = n + 1 while (n >= 0) { if (s[n] == ' ') return size - n - 1 n-- } return size } }
mit
779a224dd4fba892c9bf3239ded80ca2
25.73913
136
0.595122
2.900943
false
false
false
false
jitsi/jibri
src/main/kotlin/org/jitsi/jibri/util/extensions/Process.kt
1
1250
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.jibri.util.extensions import java.lang.reflect.Field /** * Mimic the "pid" member of Java 9's [Process]. */ val Process.pidValue: Long get() { var pid: Long = -1 try { if (javaClass.name == "java.lang.UNIXProcess" || javaClass.name == "java.lang.ProcessImpl" ) { val field: Field = javaClass.getDeclaredField("pid") field.isAccessible = true pid = field.getLong(this) field.isAccessible = false } } catch (e: Exception) { pid = -1 } return pid }
apache-2.0
28194fb67aed89ce50194d3b10d3c5bd
30.25
75
0.616
4.139073
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/InverterCommand.kt
1
1614
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.api.commands.Command import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils import java.awt.Color import net.perfectdreams.loritta.morenitta.LorittaBot class InverterCommand(loritta: LorittaBot) : AbstractCommand(loritta, "invert", listOf("inverter"), category = net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { override fun getDescriptionKey() = LocaleKeyData("commands.command.invert.description") override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY // TODO: Fix Detailed Usage override fun needsToUploadFiles(): Boolean { return true } override suspend fun run(context: CommandContext,locale: BaseLocale) { OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "invert") val image = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; } for (x in 0 until image.width) { for (y in 0 until image.height) { val rgba = image.getRGB(x, y) var col = Color(rgba, true) col = Color( 255 - col.red, 255 - col.green, 255 - col.blue) image.setRGB(x, y, col.rgb) } } context.sendFile(image, "invertido.png", context.getAsMention(true)) } }
agpl-3.0
289a2c71726e5bd5003750854ff424c4
37.452381
178
0.776952
3.90799
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/database/DbOpenHelper.kt
2
2149
package eu.kanade.tachiyomi.data.database import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import eu.kanade.tachiyomi.data.database.tables.* class DbOpenHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { companion object { /** * Name of the database file. */ const val DATABASE_NAME = "tachiyomi.db" /** * Version of the database. */ const val DATABASE_VERSION = 6 } override fun onCreate(db: SQLiteDatabase) = with(db) { execSQL(MangaTable.createTableQuery) execSQL(ChapterTable.createTableQuery) execSQL(TrackTable.createTableQuery) execSQL(CategoryTable.createTableQuery) execSQL(MangaCategoryTable.createTableQuery) execSQL(HistoryTable.createTableQuery) // DB indexes execSQL(MangaTable.createUrlIndexQuery) execSQL(MangaTable.createFavoriteIndexQuery) execSQL(ChapterTable.createMangaIdIndexQuery) execSQL(HistoryTable.createChapterIdIndexQuery) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { if (oldVersion < 2) { db.execSQL(ChapterTable.sourceOrderUpdateQuery) // Fix kissmanga covers after supporting cloudflare db.execSQL("""UPDATE mangas SET thumbnail_url = REPLACE(thumbnail_url, '93.174.95.110', 'kissmanga.com') WHERE source = 4""") } if (oldVersion < 3) { // Initialize history tables db.execSQL(HistoryTable.createTableQuery) db.execSQL(HistoryTable.createChapterIdIndexQuery) } if (oldVersion < 4) { db.execSQL(ChapterTable.bookmarkUpdateQuery) } if (oldVersion < 5) { db.execSQL(ChapterTable.addScanlator) } if (oldVersion < 6) { db.execSQL(TrackTable.addTrackingUrl) } } override fun onConfigure(db: SQLiteDatabase) { db.setForeignKeyConstraintsEnabled(true) } }
apache-2.0
f734ac239f7330e17e41a03f3e246e3b
31.560606
97
0.651
4.651515
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/ui/main/battery/doze/DozeInfoFragment.kt
1
3676
package com.androidvip.hebf.ui.main.battery.doze import android.os.Build import android.os.Bundle import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.androidvip.hebf.R import com.androidvip.hebf.ui.base.BaseFragment import com.androidvip.hebf.runSafeOnUiThread import com.androidvip.hebf.show import com.androidvip.hebf.utils.Doze import com.androidvip.hebf.utils.Logger import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlinx.android.synthetic.main.fragment_doze_whitelist.* import kotlinx.coroutines.launch @RequiresApi(api = Build.VERSION_CODES.M) class DozeInfoFragment : BaseFragment() { private lateinit var fab: FloatingActionButton private lateinit var rv: RecyclerView private lateinit var mAdapter: RecyclerView.Adapter<*> private val dozeRecords = mutableListOf<Doze.DozeRecord>() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_doze_summary, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) lifecycleScope.launch { if (!isRooted()) { rootRequired.show() } } rv = view.findViewById(R.id.doze_record_recycler_view) val refreshLayout = view.findViewById<SwipeRefreshLayout>(R.id.doze_swipe_to_refresh_summary) val typedValueAccent = TypedValue() requireActivity().theme.resolveAttribute(R.attr.colorAccent, typedValueAccent, true) refreshLayout.setColorSchemeColors(ContextCompat.getColor(findContext(), typedValueAccent.resourceId)) refreshLayout.setOnRefreshListener { Logger.logDebug("Retrieving doze records", findContext()) lifecycleScope.launch(workerContext) { dozeRecords.clear() dozeRecords.addAll(Doze.getDozeRecords().reversed()) runSafeOnUiThread { refreshLayout.isRefreshing = false mAdapter.notifyDataSetChanged() } } } refreshLayout.isRefreshing = true if (isActivityAlive) { fab = requireActivity().findViewById(R.id.doze_fab) } Logger.logDebug("Retrieving doze records", findContext()) lifecycleScope.launch(workerContext) { dozeRecords.clear() dozeRecords.addAll(Doze.getDozeRecords().reversed()) runSafeOnUiThread { refreshLayout.isRefreshing = false mAdapter = DozeRecordAdapter(findContext(), dozeRecords) val layoutManager = GridLayoutManager(findContext(), defineRecyclerViewColumns()) rv.layoutManager = layoutManager rv.adapter = mAdapter } } } override fun onResume() { super.onResume() runCatching { fab.hide() fab.setOnClickListener(null) } } private fun defineRecyclerViewColumns(): Int { val isTablet = resources.getBoolean(R.bool.is_tablet) val isLandscape = resources.getBoolean(R.bool.is_landscape) return if (isTablet || isLandscape) 2 else 1 } }
apache-2.0
bdd51e5001d8953c52c4ff46a9087a93
36.520408
116
0.693961
5.19209
false
false
false
false
google-home/sample-app-for-matter-android
app/src/main/java/com/google/homesampleapp/screens/device/DeviceFragment.kt
1
15382
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.homesampleapp.screens.device import android.app.Activity.RESULT_OK import android.content.res.Resources import android.graphics.drawable.Drawable import android.os.Bundle import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.IntentSenderRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.navigation.findNavController import androidx.navigation.fragment.findNavController import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.homesampleapp.ALLOW_DEVICE_SHARING_ON_DUMMY_DEVICE import com.google.homesampleapp.BackgroundWorkAlertDialogAction import com.google.homesampleapp.DeviceState import com.google.homesampleapp.ON_OFF_SWITCH_DISABLED_WHEN_DEVICE_OFFLINE import com.google.homesampleapp.PERIODIC_UPDATE_INTERVAL_DEVICE_SCREEN_SECONDS import com.google.homesampleapp.R import com.google.homesampleapp.TaskStatus import com.google.homesampleapp.TaskStatus.InProgress import com.google.homesampleapp.data.DevicesStateRepository import com.google.homesampleapp.databinding.FragmentDeviceBinding import com.google.homesampleapp.displayString import com.google.homesampleapp.formatTimestamp import com.google.homesampleapp.isDummyDevice import com.google.homesampleapp.lifeCycleEvent import com.google.homesampleapp.screens.shared.SelectedDeviceViewModel import com.google.homesampleapp.stateDisplayString import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject import timber.log.Timber /** * The Device Fragment shows all the information about the device that was selected in the Home * screen and supports the following actions: * ``` * - toggle the on/off state of the device * - share the device with another Matter commissioner app * - inspect the device (get all info we can from the clusters supported by the device) * ``` * When the Fragment is viewable, a periodic ping is sent to the device to get its latest * information. Main use case is to update the device's online status dynamically. */ @AndroidEntryPoint class DeviceFragment : Fragment() { @Inject internal lateinit var devicesStateRepository: DevicesStateRepository // Fragment binding. private lateinit var binding: FragmentDeviceBinding // The ViewModel for the currently selected device. private val selectedDeviceViewModel: SelectedDeviceViewModel by activityViewModels() // The fragment's ViewModel. private val viewModel: DeviceViewModel by viewModels() // The Activity launcher that launches the "shareDevice" activity in Google Play Services. private lateinit var shareDeviceLauncher: ActivityResultLauncher<IntentSenderRequest> // Background work dialog. private lateinit var backgroundWorkAlertDialog: AlertDialog // Error alert dialog. private lateinit var errorAlertDialog: AlertDialog // ----------------------------------------------------------------------------------------------- // Lifecycle functions override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Share Device Step 2. // An activity launcher is registered. It will be launched // at step 3 (in the viewModel) when the user triggers the "Share Device" action and the // Google Play Services (GPS) API (commissioningClient.shareDevice()) returns the IntentSender // to be used to launch the proper activity in GPS. // CODELAB: shareDeviceLauncher definition shareDeviceLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result -> // Share Device Step 5. // The Share Device activity in GPS has completed. val resultCode = result.resultCode if (resultCode == RESULT_OK) { Timber.d("ShareDevice: Success with resultCode [[${resultCode}]") } else { Timber.d("ShareDevice: Failed with resultCode [[${resultCode}]") showErrorAlertDialog("Device Sharing Failed", "Result code: ${resultCode}") } updateShareDeviceButton(true) viewModel.shareDeviceCompleted(selectedDeviceViewModel.selectedDeviceLiveData.value!!) } // CODELAB SECTION END } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { super.onCreateView(inflater, container, savedInstanceState) Timber.d(lifeCycleEvent("onCreateView()")) // Setup the binding with the fragment. binding = DataBindingUtil.inflate(inflater, R.layout.fragment_device, container, false) // Setup UI elements and livedata observers. setupUiElements() setupObservers() return binding.root } override fun onResume() { super.onResume() Timber.d( "onResume(): Starting periodic ping on device with interval [${PERIODIC_UPDATE_INTERVAL_DEVICE_SCREEN_SECONDS}] seconds") viewModel.startDevicePeriodicPing(selectedDeviceViewModel.selectedDeviceLiveData.value!!) } override fun onPause() { super.onPause() Timber.d("onPause(): Stopping periodic ping on device") viewModel.stopDevicePeriodicPing() } // ----------------------------------------------------------------------------------------------- // Setup UI elements private fun setupUiElements() { // Bacjkground Work AlertDialog backgroundWorkAlertDialog = MaterialAlertDialogBuilder(requireContext()).create() // Error AlertDialog errorAlertDialog = MaterialAlertDialogBuilder(requireContext()) .setPositiveButton(resources.getString(R.string.ok)) { _, _ -> // Nothing to do. } .create() // Navigate back binding.topAppBar.setOnClickListener { Timber.d("topAppBar.setOnClickListener") findNavController().popBackStack() } // Info / Inspect device menu button val description = getString(R.string.inspect_description) val descriptionHtml = Html.fromHtml(description, Html.FROM_HTML_MODE_LEGACY) binding.topAppBar.setOnMenuItemClickListener { MaterialAlertDialogBuilder(requireContext()) .setTitle( getString( R.string.inspect_device_name, selectedDeviceViewModel.selectedDeviceLiveData.value?.device?.name)) .setMessage(descriptionHtml) .setPositiveButton(resources.getString(R.string.ok)) { _, _ -> viewModel.inspectDescriptorCluster( selectedDeviceViewModel.selectedDeviceLiveData.value!!) } .show() true } // Share Device Button binding.shareButton.setOnClickListener { val deviceName = selectedDeviceViewModel.selectedDeviceLiveData.value?.device?.name!! val deviceId = selectedDeviceViewModel.selectedDeviceLiveData.value?.device?.deviceId if (isDummyDevice(deviceName) && !ALLOW_DEVICE_SHARING_ON_DUMMY_DEVICE) { // Device sharing not allowed on a dummy device. MaterialAlertDialogBuilder(requireContext()) .setTitle("Share device $deviceName") .setMessage(getString(R.string.share_dummy_device)) .setPositiveButton(resources.getString(R.string.ok)) { _, _ -> } .setPositiveButton(resources.getString(R.string.ok)) { _, _ -> viewModel.inspectDescriptorCluster( selectedDeviceViewModel.selectedDeviceLiveData.value!!) } .show() } else { // Disable the button. It's state is properly re-enabled either via the // shareDeviceStatus LiveData updates on the processing, or when the activity completes and // our launcher handler takes care of it. updateShareDeviceButton(false) // Trigger the processing for sharing the device viewModel.shareDevice(requireActivity(), deviceId!!) } } // Change the on/off state of the device binding.onoffSwitch.setOnClickListener { val isOn = binding.onoffSwitch.isChecked viewModel.updateDeviceStateOn(selectedDeviceViewModel.selectedDeviceLiveData.value!!, isOn) } // Remove Device binding.removeButton.setOnClickListener { val deviceId = selectedDeviceViewModel.selectedDeviceIdLiveData.value MaterialAlertDialogBuilder(requireContext()) .setTitle("Remove this device?") .setMessage( "This device will be removed and unlinked from this sample app. Other services and connection-types may still have access.") .setNegativeButton(resources.getString(R.string.cancel)) { _, _ -> // nothing to do } .setPositiveButton(resources.getString(R.string.yes_remove_it)) { _, _ -> // TODO: the log message below never shows up, don't know why. selectedDeviceViewModel.resetSelectedDevice() val bundle = Bundle() bundle.putString("snackbarMsg", "Removing device [${deviceId}]") // This must be done before calling viewModel.removeDevice() otherwise the bundle won't // make it in HomeFragment.onViewCreated(). // TODO: to be investigated requireView() .findNavController() .navigate(R.id.action_deviceFragment_to_homeFragment, bundle) viewModel.removeDevice(deviceId!!) } .show() } } private fun showBackgroundWorkAlertDialog(title: String?, message: String?) { if (title != null) { backgroundWorkAlertDialog.setTitle(title) } if (message != null) { backgroundWorkAlertDialog.setMessage(message) } backgroundWorkAlertDialog.show() } private fun hideBackgroundWorkAlertDialog() { backgroundWorkAlertDialog.hide() } private fun showErrorAlertDialog(title: String?, message: String?) { if (title != null) { errorAlertDialog.setTitle(title) } if (message != null) { errorAlertDialog.setMessage(message) } errorAlertDialog.show() } private fun updateShareDeviceButton(enable: Boolean) { binding.shareButton.isEnabled = enable } // ----------------------------------------------------------------------------------------------- // Setup Observers private fun setupObservers() { // Generic status about actions processed in this screen. devicesStateRepository.lastUpdatedDeviceState.observe(viewLifecycleOwner) { Timber.d( "devicesStateRepository.lastUpdatedDeviceState.observe: [${devicesStateRepository.lastUpdatedDeviceState.value}]") updateDeviceInfo(devicesStateRepository.lastUpdatedDeviceState.value) } // The current status of the share device action. viewModel.shareDeviceStatus.observe(viewLifecycleOwner) { status -> val isButtonEnabled = status !is InProgress updateShareDeviceButton(isButtonEnabled) if (status is TaskStatus.Failed) { showErrorAlertDialog(status.message, status.cause.toString()) } } // Background work alert dialog actions. viewModel.backgroundWorkAlertDialogAction.observe(viewLifecycleOwner) { action -> if (action is BackgroundWorkAlertDialogAction.Show) { showBackgroundWorkAlertDialog(action.title, action.message) } else if (action is BackgroundWorkAlertDialogAction.Hide) { hideBackgroundWorkAlertDialog() } } // The ViewModel calls the GPS shareDevice() API to get the IntentSender used with the // Android Activity Result API. Once the ViewModel has the IntentSender, it posts // it via LiveData so the Fragment can use that value to launch the activity. // If sender was null, then model triggered a failed task status. No need to worry // about that here. viewModel.shareDeviceIntentSender.observe(viewLifecycleOwner) { sender -> Timber.d("ShareDevice: Launch GPS activity to share device [${sender}]") shareDeviceLauncher.launch(IntentSenderRequest.Builder(sender!!).build()) } // Observer on the currently selected device selectedDeviceViewModel.selectedDeviceIdLiveData.observe(viewLifecycleOwner) { deviceId -> Timber.d( "selectedDeviceViewModel.selectedDeviceIdLiveData.observe is called with deviceId [${deviceId}]") updateDeviceInfo(null) } } // ----------------------------------------------------------------------------------------------- // UI update functions private fun updateDeviceInfo(deviceState: DeviceState?) { if (selectedDeviceViewModel.selectedDeviceIdLiveData.value == -1L) { // Device was just removed, nothing to do. We'll move to HomeFragment. return } val deviceUiModel = selectedDeviceViewModel.selectedDeviceLiveData.value // Device state deviceUiModel?.let { val isOnline = when (deviceState) { null -> deviceUiModel.isOnline else -> deviceState.online } val isOn = when (deviceState) { null -> deviceUiModel.isOn else -> deviceState.on } binding.topAppBar.title = deviceUiModel.device.name val shapeOffDrawable = getDrawable("device_item_shape_off") val shapeOnDrawable = getDrawable("device_item_shape_on") val shapeDrawable = if (isOnline && isOn) shapeOnDrawable else shapeOffDrawable binding.shareLine1TextView.text = getString(R.string.share_device_name, deviceUiModel.device.name) binding.onOffTextView.text = stateDisplayString(isOnline, isOn) binding.stateLayout.background = shapeDrawable if (ON_OFF_SWITCH_DISABLED_WHEN_DEVICE_OFFLINE) { binding.onoffSwitch.isEnabled = isOnline } else { binding.onoffSwitch.isEnabled = true } binding.onoffSwitch.isChecked = isOn binding.techInfoDetailsTextView.text = getString( R.string.share_device_info, formatTimestamp(deviceUiModel.device.dateCommissioned!!, null), deviceUiModel.device.deviceId.toString(), deviceUiModel.device.vendorId, deviceUiModel.device.productId, deviceUiModel.device.deviceType.displayString()) } } private fun getDrawable(name: String): Drawable? { val resources: Resources = requireContext().resources val resourceId = resources.getIdentifier(name, "drawable", requireContext().packageName) return resources.getDrawable(resourceId) } }
apache-2.0
2f10c9d2d314ee4e38187fb522a0b2d0
39.478947
138
0.696918
5.101824
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/data/errors.kt
1
1165
package io.kotest.data import io.kotest.assertions.Failures import io.kotest.assertions.MultiAssertionError @PublishedApi internal class ErrorCollector { private val errors = mutableListOf<Throwable>() operator fun plusAssign(t: Throwable) { errors += t } fun assertAll() { if (errors.size == 1) { throw errors[0] } else if (errors.size > 1) { throw MultiAssertionError(errors) } } } @PublishedApi internal fun error(e: Throwable, headers: List<String>, values: List<*>): AssertionError { val params = headers.zip(values).joinToString(", ") // Include class name for non-assertion errors, since the class is often meaningful and there might not // be a message (e.g. NullPointerException) val message = when (e) { is AssertionError -> e.message else -> e.toString() } return Failures.failure("Test failed for $params with error $message") } @PublishedApi internal fun forNoneError(headers: List<String>, values: List<*>): AssertionError { val params = headers.zip(values).joinToString(", ") return Failures.failure("Test passed for $params but expected failure") }
apache-2.0
8669f6caef78e17790f38cf079dea234
28.125
106
0.68927
4.236364
false
true
false
false
marvec/engine
lumeer-core/src/main/kotlin/io/lumeer/core/util/js/DataFilterJsonTask.kt
2
9640
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.lumeer.core.util.js import com.google.gson.* import io.lumeer.api.model.* import io.lumeer.api.model.Collection import io.lumeer.api.model.common.Resource import io.lumeer.core.js.JsEngineFactory import io.lumeer.core.util.Tuple import org.graalvm.polyglot.Context import org.graalvm.polyglot.Value import java.io.IOException import java.nio.charset.StandardCharsets import java.util.concurrent.Callable import java.util.logging.Level import java.util.logging.Logger import java.lang.Double import java.lang.Float import java.time.LocalDateTime import java.time.ZoneOffset import java.time.ZonedDateTime data class DataFilterJsonTask(val documents: List<Document>, val collections: List<Collection>, val linkTypes: List<LinkType>, val linkInstances: List<LinkInstance>, val query: Query, val collectionsPermissions: Map<String, AllowedPermissions>, val linkTypesPermissions: Map<String, AllowedPermissions>, val constraintData: ConstraintData, val includeChildren: Boolean, val language: Language = Language.EN) : Callable<Tuple<List<Document>, List<LinkInstance>>> { override fun call(): Tuple<List<Document>, List<LinkInstance>> { val emptyTuple = Tuple<List<Document>, List<LinkInstance>>(emptyList(), emptyList()) val context = getContext() return try { val filterJsValue = getFunction(context) val json = convertToJson(DataFilterJson(documents, collections, linkTypes, linkInstances, query, collectionsPermissions, linkTypesPermissions, constraintData, includeChildren, language.toLanguageTag())) val result = filterJsValue.execute(json) if (result != null) { val documentsMap = documents.groupBy { it.id } val resultDocumentsList = mutableListOf<Document>() val resultDocuments = result.getMember("documentsIds") for (i in 0 until resultDocuments.arraySize) resultDocumentsList.addAll(documentsMap[resultDocuments.getArrayElement(i).asString()].orEmpty()) val linkInstancesMap = linkInstances.groupBy { it.id } val resultLinksList = mutableListOf<LinkInstance>() val resultLinks = result.getMember("linkInstancesIds") for (i in 0 until resultLinks.arraySize) resultLinksList.addAll(linkInstancesMap[resultLinks.getArrayElement(i).asString()].orEmpty()) Tuple(resultDocumentsList, resultLinksList) } else { logger.log(Level.SEVERE, "Error filtering data - null result.") emptyTuple } } catch (e: Exception) { logger.log(Level.SEVERE, "Error filtering data: ", e) emptyTuple } finally { context.close() } } companion object { private val logger: Logger = Logger.getLogger(DataFilterJsonTask::class.simpleName) private const val FILTER_JS = "filterDocumentsAndLinksIdsFromJson" private var filterJsCode: String? = null private val engine = JsEngineFactory.getEngine() fun getContext(): Context { val context = Context .newBuilder("js") .engine(engine) .allowAllAccess(true) .build() context.initialize("js") return context } fun getFunction(context: Context): Value { if (filterJsCode != null) { context.eval("js", filterJsCode) return context.getBindings("js").getMember(FILTER_JS) } else { throw IOException("Filters JS code not present.") } } fun convertToJson(dataFilterJson: DataFilterJson): String { val strategy: ExclusionStrategy = object : ExclusionStrategy { override fun shouldSkipField(field: FieldAttributes): Boolean { if (field.declaringClass == Document::class.java && !listOf("id", "data", "metaData", "collectionId").contains(field.name)) { return true } if (field.declaringClass == Collection::class.java && !listOf("id", "attributes").contains(field.name)) { return true } if (field.declaringClass == Resource::class.java && !listOf("id").contains(field.name)) { return true } if (field.declaringClass == LinkType::class.java && !listOf("id", "attributes", "collectionIds").contains(field.name)) { return true } if (field.declaringClass == LinkInstance::class.java && !listOf("id", "data", "linkTypeId", "documentIds").contains(field.name)) { return true } if (field.declaringClass == User::class.java && !listOf("id", "name", "email").contains(field.name)) { return true } if (field.declaringClass == Attribute::class.java && !listOf("id", "name", "constraint").contains(field.name)) { return true } return false } override fun shouldSkipClass(clazz: Class<*>?): Boolean { return false } } val conditionTypeSerializer: JsonSerializer<ConditionType> = JsonSerializer<ConditionType> { condition, _, _ -> JsonPrimitive(condition.value) } // we need to use java.lang.Double because we use Java objects as input parameters val doubleSerializer: JsonSerializer<Double> = JsonSerializer<Double> { number: Double, _, _ -> when { number.isNaN -> JsonPrimitive("NaN") number.isInfinite -> JsonPrimitive("Infinity") else -> JsonPrimitive(number) } } // we need to use java.lang.Float because we use Java objects as input parameters val floatSerializer: JsonSerializer<Float> = JsonSerializer<Float> { number, _, _ -> when { number.isNaN -> JsonPrimitive("NaN") number.isInfinite -> JsonPrimitive("Infinity") else -> JsonPrimitive(number) } } val localDateTimeSerializer: JsonSerializer<LocalDateTime> = JsonSerializer<LocalDateTime> { dt, srcType, _ -> JsonPrimitive(dt.toInstant(ZoneOffset.UTC).epochSecond) } val zonedDateTimeSerializer2: JsonSerializer<ZonedDateTime> = JsonSerializer<ZonedDateTime> { dt, srcType, _ -> JsonPrimitive(dt.toInstant().epochSecond) } return GsonBuilder() .addSerializationExclusionStrategy(strategy) .registerTypeAdapter(ConditionType::class.java, conditionTypeSerializer) .registerTypeAdapter(Double::class.java, doubleSerializer) .registerTypeAdapter(Float::class.java, floatSerializer) .registerTypeAdapter(LocalDateTime::class.java, localDateTimeSerializer) .registerTypeAdapter(ZonedDateTime::class.java, zonedDateTimeSerializer2) .create() .toJson(dataFilterJson) } init { try { DataFilterJsonTask::class.java.getResourceAsStream("/lumeer-data-filters.min.js").use { stream -> filterJsCode = String(stream.readAllBytes(), StandardCharsets.UTF_8).plus("; function ${FILTER_JS}(json) { return Filter.filterDocumentsAndLinksIdsFromJson(json); }") } } catch (ioe: IOException) { filterJsCode = null } } } } data class DataFilterJson(val documents: List<Document>, val collections: List<Collection>, val linkTypes: List<LinkType>, val linkInstances: List<LinkInstance>, val query: Query, val collectionsPermissions: Map<String, AllowedPermissions>, val linkTypesPermissions: Map<String, AllowedPermissions>, val constraintData: ConstraintData, val includeChildren: Boolean, val language: String)
gpl-3.0
89f53d8395a57ac30e36062c72c3cabb
45.570048
214
0.584025
5.317154
false
false
false
false
fluttercommunity/plus_plugins
packages/share_plus/share_plus/android/src/main/kotlin/dev/fluttercommunity/plus/share/SharePlusPendingIntent.kt
1
1413
package dev.fluttercommunity.plus.share import android.content.* import android.os.Build /** * This helper class allows us to use FLAG_MUTABLE on the PendingIntent used in the Share class, * as it allows us to make the underlying Intent explicit, therefore avoiding any risks an implicit * mutable Intent may carry. * * When the PendingIntent is sent, the system will instantiate this class and call `onReceive` on it. */ internal class SharePlusPendingIntent: BroadcastReceiver() { companion object { /** * Static member to access the result of the system instantiated instance */ var result: String = "" } /** * Handler called after an action was chosen. Called only on success. */ override fun onReceive(context: Context, intent: Intent) { // Extract chosen ComponentName val chosenComponent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // Only available from API level 33 onwards intent.getParcelableExtra(Intent.EXTRA_CHOSEN_COMPONENT, ComponentName::class.java) } else { // Deprecated in API level 33 intent.getParcelableExtra<ComponentName>(Intent.EXTRA_CHOSEN_COMPONENT) } // Unambiguously identify the chosen action if (chosenComponent != null) { result = chosenComponent.flattenToString() } } }
bsd-3-clause
5961e3885ac5b05f3881a7b95aa8727b
35.230769
101
0.672328
4.839041
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/animations/expandableelement/ExpandableElementMessageContent.kt
1
1964
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RoundRectShape import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Row import com.facebook.litho.Style import com.facebook.litho.core.margin import com.facebook.litho.core.padding import com.facebook.litho.dp import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.sp import com.facebook.litho.view.background class ExpandableElementMessageContent( private val messageText: String, private val messageTextColor: Int, private val backgroundColor: Int ) : KComponent() { override fun ComponentScope.render(): Component { return Row( style = Style.padding(all = 8.dp) .margin(all = 8.dp) .background(getMessageBackground(backgroundColor))) { child(Text(textSize = 18.sp, textColor = messageTextColor, text = messageText)) } } fun getMessageBackground(color: Int): ShapeDrawable { val roundedRectShape = RoundRectShape( floatArrayOf(40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f), null, floatArrayOf(40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f)) return ShapeDrawable(roundedRectShape).also { it.paint.color = color } } }
apache-2.0
96a72f8ff76e290275548b619eb9ae76
34.709091
89
0.71945
4.057851
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/about/AboutThisAppFragment.kt
1
2899
package jp.toastkid.yobidashi.about import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.core.net.toUri import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.ContentScrollable import jp.toastkid.lib.intent.GooglePlayIntentFactory import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.BuildConfig import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.about.license.LicenseHtmlLoaderUseCase import jp.toastkid.yobidashi.databinding.FragmentAboutBinding /** * About this app. * * @author toastkidjp */ class AboutThisAppFragment : Fragment(), ContentScrollable { /** * Data Binding. */ private var binding: FragmentAboutBinding? = null private lateinit var preferenceApplier: PreferenceApplier override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) binding = DataBindingUtil.inflate(inflater, LAYOUT_ID, container, false) binding?.fragment = this binding?.settingsAppVersion?.text = BuildConfig.VERSION_NAME val context = context ?: return binding?.root preferenceApplier = PreferenceApplier(context) return binding?.root } /** * Show licenses dialog. */ fun licenses() { binding?.licenseContent?.let { LicenseHtmlLoaderUseCase().invoke(it) } } fun checkUpdate() { startActivity(GooglePlayIntentFactory()(BuildConfig.APPLICATION_ID)) } fun privacyPolicy() { val browserViewModel = activity?.let { ViewModelProvider(it).get(BrowserViewModel::class.java) } ?: return popBackStack() browserViewModel.open(getString(R.string.link_privacy_policy).toUri()) } fun aboutAuthorApp() { startActivity( Intent(Intent.ACTION_VIEW) .also { it.data = Uri.parse("market://search?q=pub:toastkidjp") } ) } private fun popBackStack() { activity?.supportFragmentManager?.popBackStack() } override fun toTop() { binding?.aboutScroll?.smoothScrollTo(0, 0) } override fun toBottom() { binding?.aboutScroll?.smoothScrollTo(0, binding?.root?.measuredHeight ?: 0) } override fun onDetach() { binding = null super.onDetach() } companion object { /** * Layout ID. */ @LayoutRes private const val LAYOUT_ID = R.layout.fragment_about } }
epl-1.0
b3d457a78312ffea14507761042054a6
25.842593
99
0.67989
4.791736
false
false
false
false
xfournet/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ModuleChangesGroupingPolicy.kt
1
1922
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vcs.changes.ui.ChangesModuleGroupingPolicy.Companion.HIDE_EXCLUDED_FILES import com.intellij.openapi.vcs.changes.ui.ChangesModuleGroupingPolicy.Companion.MODULE_CACHE import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder.* import javax.swing.tree.DefaultTreeModel class ModuleChangesGroupingPolicy(val project: Project, val model: DefaultTreeModel) : BaseChangesGroupingPolicy() { private val myIndex = ProjectFileIndex.getInstance(project) override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? { val file = resolveVirtualFile(nodePath) file?.let { myIndex.getModuleForFile(file, HIDE_EXCLUDED_FILES) }?.let { module -> val grandParent = nextPolicy?.getParentNodeFor(nodePath, subtreeRoot) ?: subtreeRoot val cachingRoot = getCachingRoot(grandParent, subtreeRoot) MODULE_CACHE.getValue(cachingRoot)[module]?.let { return it } ChangesBrowserModuleNode(module).let { it.markAsHelperNode() model.insertNodeInto(it, grandParent, grandParent.childCount) MODULE_CACHE.getValue(cachingRoot)[module] = it DIRECTORY_CACHE.getValue(cachingRoot)[staticFrom(it.moduleRoot).key] = it IS_CACHING_ROOT.set(it, true) MODULE_CACHE.getValue(it)[module] = it DIRECTORY_CACHE.getValue(it)[staticFrom(it.moduleRoot).key] = it return it } } return null } class Factory(val project: Project) : ChangesGroupingPolicyFactory() { override fun createGroupingPolicy(model: DefaultTreeModel) = ModuleChangesGroupingPolicy(project, model) } }
apache-2.0
151e71de3e4533d32ebbd2726ad8ddfc
43.72093
140
0.761186
4.358277
false
false
false
false
Kotlin/dokka
plugins/javadoc/src/main/kotlin/org/jetbrains/dokka/javadoc/translators/documentables/JavadocPageContentBuilder.kt
1
3326
package org.jetbrains.dokka.javadoc.translators.documentables import org.jetbrains.dokka.javadoc.pages.JavadocSignatureContentNode import org.jetbrains.dokka.DokkaConfiguration import org.jetbrains.dokka.base.signatures.SignatureProvider import org.jetbrains.dokka.base.transformers.pages.comments.CommentsToContentConverter import org.jetbrains.dokka.base.translators.documentables.PageContentBuilder import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.properties.PropertyContainer import org.jetbrains.dokka.pages.ContentKind import org.jetbrains.dokka.pages.ContentNode import org.jetbrains.dokka.utilities.DokkaLogger import java.lang.IllegalStateException class JavadocPageContentBuilder( commentsConverter: CommentsToContentConverter, signatureProvider: SignatureProvider, logger: DokkaLogger ) : PageContentBuilder(commentsConverter, signatureProvider, logger) { fun PageContentBuilder.DocumentableContentBuilder.javadocGroup( dri: DRI = mainDRI.first(), sourceSets: Set<DokkaConfiguration.DokkaSourceSet> = mainSourcesetData, extra: PropertyContainer<ContentNode> = mainExtra, block: JavadocContentBuilder.() -> Unit ) { +JavadocContentBuilder( mainDri = dri, mainExtra = extra, mainSourceSet = sourceSets, ).apply(block).build() } open inner class JavadocContentBuilder( private val mainDri: DRI, private val mainExtra: PropertyContainer<ContentNode>, private val mainSourceSet: Set<DokkaConfiguration.DokkaSourceSet>, ) { var annotations: ContentNode? = null var modifiers: ContentNode? = null var signatureWithoutModifiers: ContentNode? = null var supertypes: ContentNode? = null fun annotations(block: PageContentBuilder.DocumentableContentBuilder.() -> Unit) { val built = buildContentForBlock(block) if(built.hasAnyContent()) annotations = built } fun modifiers(block: PageContentBuilder.DocumentableContentBuilder.() -> Unit) { val built = buildContentForBlock(block) if(built.hasAnyContent()) modifiers = built } fun signatureWithoutModifiers(block: PageContentBuilder.DocumentableContentBuilder.() -> Unit) { signatureWithoutModifiers = buildContentForBlock(block) } fun supertypes(block: PageContentBuilder.DocumentableContentBuilder.() -> Unit) { val built = buildContentForBlock(block) if(built.hasAnyContent()) supertypes = built } private fun buildContentForBlock(block: PageContentBuilder.DocumentableContentBuilder.() -> Unit) = contentFor( dri = mainDri, sourceSets = mainSourceSet, kind = ContentKind.Symbol, extra = mainExtra, block = block ) fun build(): JavadocSignatureContentNode = JavadocSignatureContentNode( dri = mainDri, annotations = annotations, modifiers = modifiers, signatureWithoutModifiers = signatureWithoutModifiers ?: throw IllegalStateException("JavadocSignatureContentNode should have at least a signature"), supertypes = supertypes ) } }
apache-2.0
a5b8d7f26cdbe7b0ec50fd763766d2aa
40.5875
161
0.700541
5.287758
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/DoubleJumpMetaEntity.kt
1
2964
package com.github.shynixn.blockball.core.logic.persistence.entity import com.github.shynixn.blockball.api.business.annotation.YamlSerialize import com.github.shynixn.blockball.api.business.enumeration.ParticleType import com.github.shynixn.blockball.api.persistence.entity.DoubleJumpMeta import com.github.shynixn.blockball.api.persistence.entity.Particle import com.github.shynixn.blockball.api.persistence.entity.Sound /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class DoubleJumpMetaEntity : DoubleJumpMeta { /** Is the effect enabled or disabled?*/ @YamlSerialize(orderNumber = 1, value = "enabled") override var enabled: Boolean = true /** Cooldown between activating this effect.*/ @YamlSerialize(orderNumber = 2, value = "cooldown") override var cooldown: Int = 2 /** Vertical strength modifier.*/ @YamlSerialize(orderNumber = 3, value = "vertical-strength") override var verticalStrength: Double = 1.0 /** Horizontal strength modifier.*/ @YamlSerialize(orderNumber = 4, value = "horizontal-strength") override var horizontalStrength: Double = 2.0 /** ParticleEffect being played when activating this.*/ @YamlSerialize(orderNumber = 5, value = "particle-effect", implementation = ParticleEntity::class) override val particleEffect: Particle = ParticleEntity(ParticleType.EXPLOSION_NORMAL.name) /** SoundEffect being played when activating this.*/ @YamlSerialize(orderNumber = 6, value = "sound-effect", implementation = SoundEntity::class) override val soundEffect: Sound = SoundEntity("GHAST_FIREBALL", 10.0, 1.0) init { particleEffect.amount = 4 particleEffect.speed = 0.0002 particleEffect.offset.x = 2.0 particleEffect.offset.y = 2.0 particleEffect.offset.z = 2.0 } }
apache-2.0
36eefe0a48b50a23775e0c78c785c73d
46.063492
102
0.738866
4.252511
false
false
false
false
devmil/muzei-bingimageoftheday
app/src/main/java/de/devmil/muzei/bingimageoftheday/BingImageContentProvider.kt
1
5703
/* * Copyright 2014 Devmil Solutions * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.devmil.muzei.bingimageoftheday import android.content.ContentProvider import android.content.ContentUris import android.content.ContentValues import android.database.Cursor import android.database.MatrixCursor import android.net.Uri import android.os.Binder import android.os.ParcelFileDescriptor import android.provider.OpenableColumns import android.webkit.MimeTypeMap import com.google.android.apps.muzei.api.provider.Artwork import com.google.android.apps.muzei.api.provider.ProviderContract import java.io.FileNotFoundException /** * Used in place of [androidx.core.content.FileProvider] to share images from * [BingImageOfTheDayArtProvider] to external apps. * * This extracts the name for [OpenableColumns.DISPLAY_NAME] from the byline of the * artwork (rather than the file name itself) and extracts the type of file * from the webUri. */ class BingImageContentProvider : ContentProvider() { companion object { private val DEFAULT_PROJECTION = arrayOf( OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE) } override fun onCreate(): Boolean { return true } override fun query( uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String? ): Cursor? { val context = context ?: return null val result = MatrixCursor(projection ?: DEFAULT_PROJECTION) // Clear the calling app's identity as it cannot be used when // accessing the non-exported BingImageOfTheDayArtProvider val token = Binder.clearCallingIdentity() try { val id = ContentUris.parseId(uri) val contentUri = ProviderContract.getContentUri(BuildConfig.BING_IMAGE_OF_THE_DAY_AUTHORITY) val artworkUri = ContentUris.withAppendedId(contentUri, id) val artwork = context.contentResolver.query(artworkUri, null, null, null, null)?.use { if (it.moveToFirst()) { Artwork.fromCursor(it) } else { null } } if (artwork != null && artwork.data.exists()) { result.newRow().apply { add(OpenableColumns.DISPLAY_NAME, artwork.byline) add(OpenableColumns.SIZE, artwork.data.length()) } } } finally { Binder.restoreCallingIdentity(token) } return result } override fun getType(uri: Uri): String? { val context = context ?: return null // Clear the calling app's identity as it cannot be used when // accessing the non-exported BingImageOfTheDayArtProvider val token = Binder.clearCallingIdentity() try { val id = ContentUris.parseId(uri) val contentUri = ProviderContract.getContentUri(BuildConfig.BING_IMAGE_OF_THE_DAY_AUTHORITY) val artworkUri = ContentUris.withAppendedId(contentUri, id) val artwork = context.contentResolver.query(artworkUri, null, null, null, null)?.use { if (it.moveToFirst()) { Artwork.fromCursor(it) } else { null } } if (artwork?.webUri != null) { // Taken from FileProvider's source val lastDot: Int = artwork.webUri.toString().lastIndexOf('.') if (lastDot >= 0) { val extension: String = artwork.webUri.toString().substring(lastDot + 1) val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) if (mime != null) { return mime } } return "application/octet-stream" } } finally { Binder.restoreCallingIdentity(token) } return null } override fun insert(uri: Uri, values: ContentValues?): Uri? { return null } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { return 0 } override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int { return 0 } @Throws(FileNotFoundException::class) override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? { val context = context ?: return null // Clear the calling app's identity as it cannot be used when // accessing the non-exported BingImageOfTheDayArtProvider val token = Binder.clearCallingIdentity() try { val id = ContentUris.parseId(uri) val contentUri = ProviderContract.getContentUri(BuildConfig.BING_IMAGE_OF_THE_DAY_AUTHORITY) val artworkUri = ContentUris.withAppendedId(contentUri, id) return context.contentResolver.openFileDescriptor(artworkUri, mode) } finally { Binder.restoreCallingIdentity(token) } } }
apache-2.0
4913448ca8cbaa3f6ff6b542772c230e
37.533784
115
0.628967
5.020246
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/intentions/WrapLambdaExprIntention.kt
2
1386
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsBlockExpr import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.RsLambdaExpr import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.parentOfType class WrapLambdaExprIntention : RsElementBaseIntentionAction<RsExpr>() { override fun getText() = "Add braces to lambda expression" override fun getFamilyName() = text override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsExpr? { val lambdaExpr = element.parentOfType<RsLambdaExpr>() ?: return null val body = lambdaExpr.expr ?: return null return if (body !is RsBlockExpr) body else null } override fun invoke(project: Project, editor: Editor, ctx: RsExpr) { val relativeCaretPosition = editor.caretModel.offset - ctx.textOffset val bodyStr = "\n${ctx.text}\n" val blockExpr = RsPsiFactory(project).createBlockExpr(bodyStr) val offset = ((ctx.replace(blockExpr)) as RsBlockExpr).block.expr?.textOffset ?: return editor.caretModel.moveToOffset(offset + relativeCaretPosition) } }
mit
21e20df44be16514260c0255219bc3ee
37.5
104
0.738095
4.149701
false
false
false
false
Fitbit/MvRx
mvrx-mocking/src/main/kotlin/com/airbnb/mvrx/mocking/MockBuilder.kt
1
58657
@file:Suppress("Detekt.ParameterListWrapping") package com.airbnb.mvrx.mocking import android.os.Parcelable import android.util.Log import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import com.airbnb.mvrx.Async import com.airbnb.mvrx.InternalMavericksApi import com.airbnb.mvrx.MavericksView import com.airbnb.mvrx.MavericksViewModel import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.PersistState import com.airbnb.mvrx.mocking.MavericksMock.Companion.DEFAULT_INITIALIZATION_NAME import com.airbnb.mvrx.mocking.MavericksMock.Companion.DEFAULT_STATE_NAME import com.airbnb.mvrx.mocking.MavericksMock.Companion.RESTORED_STATE_NAME import java.util.concurrent.atomic.AtomicInteger import kotlin.reflect.KFunction import kotlin.reflect.KProperty import kotlin.reflect.KProperty0 import kotlin.reflect.KProperty1 import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.primaryConstructor /** * Used with [MockableMavericksView.provideMocks] for mocking a Mavericks view that has no view models (eg only static content and arguments). * * @param defaultArgs If your view takes arguments you must provide an instance of those arguments here to be used as the default value for your mocks. * If your view has no arguments, pass null (and use Nothing as the type). * For example, if you use Fragments this would be the arguments that you initialize the Fragment with. * If you use the [Mavericks.KEY_ARG] key to pass a single Parcelable class to your Fragment you can pass that class here, * and it will automatically be wrapped in a Bundle with the [Mavericks.KEY_ARG] key. Otherwise you can pass a [Bundle] and * it will be passed along as-is to your Fragment when it is created. * * @param mockBuilder Optionally provide other argument variations via the [MockBuilder] DSL * * @see mockSingleViewModel */ fun <V : MockableMavericksView, Args : Parcelable> V.mockNoViewModels( defaultArgs: Args?, mockBuilder: MockBuilder<V, Args>.() -> Unit = {} ): MockBuilder<V, Args> = MockBuilder<V, Args>(defaultArgs).apply { mockBuilder() build(this@mockNoViewModels) } /** * Use this to split a Views's mocks into groups. Each group is defined with the normal mock * definition functions, and this function combines them. * This is helpful when mocks need different default states or arguments, so each group can have its own default. * Additionally, splitting mocks into groups allows tests to run faster as groups can be tested in parallel. * * @param mocks Each pair is a String description of the mock group, paired to the mock builder - ie ["Dog" to dogMocks()]. The string description * used to create the pair is prepended to the name of each mock in the group, so you can omit a reference to the group type in the individual mocks. */ inline fun <reified V : MockableMavericksView> V.combineMocks( vararg mocks: Pair<String, MavericksViewMocks<V, *>> ): MavericksViewMocks<V, *> = object : MavericksViewMocks<V, Parcelable>() { init { validate(V::class.simpleName!!) } override val mockGroups: List<List<MavericksMock<V, out Parcelable>>> get() { return mocks.map { (prefix, mocker) -> mocker.mocks.map { MavericksMock( name = "$prefix : ${it.name}", argsProvider = it.argsProvider, statesProvider = it.statesProvider, forInitialization = it.forInitialization, type = it.type ) } } } } /** * Define state values for a [MavericksView] that should be used in tests. * This is for use with [MockableMavericksView.provideMocks] when the view has a single view model. * * In the [mockBuilder] lambda you can use [MockBuilder.args] to define mock arguments that should be used to initialize the view and create the * initial view model state. Use [SingleViewModelMockBuilder.state] to define complete state objects. * * It is recommended that the "Default" mock state for a view represent the most canonical, complete * form of the View. For example, all data loaded, with no empty or null instances. * * Other mock variations should test alterations to this "default" state, with each variant testing * a minimal difference (ideally only one change). For example, a variant may test that a single * property is null or empty. * * This pattern is encouraged because: * 1. The tools for defining mock variations are designed to enable easy modification of the default * 2. Each mock variant is only one line of code, and is easily maintained * 3. Each variant tests a single edge case * * @param V The type of Mavericks view that is being mocked * @param viewModelReference A reference to the view model that will be mocked. Use the "::" operator for this - "MyFragment::myViewModel" * @param defaultState An instance of your State that represents the canonical version of your view. It will be the basis for your tests. * @param defaultArgs If your view takes arguments you must provide an instance of those arguments here to be used as the default value for your mocks. * If your view has no arguments, pass null (and use Nothing as the type). * For example, if you use Fragments this would be the arguments that you initialize the Fragment with. * If you use the [Mavericks.KEY_ARG] key to pass a single Parcelable class to your Fragment you can pass that class here, * and it will automatically be wrapped in a Bundle with the [Mavericks.KEY_ARG] key. Otherwise you can pass a [Bundle] and * it will be passed along as-is to your Fragment when it is created. * * @param mockBuilder A lambda where the [SingleViewModelMockBuilder] DSL can be used to specify additional mock variants. * @see mockTwoViewModels * @see mockNoViewModels */ fun <V : MockableMavericksView, Args : Parcelable, S : MavericksState> V.mockSingleViewModel( viewModelReference: KProperty1<V, MavericksViewModel<S>>, defaultState: S, defaultArgs: Args?, mockBuilder: SingleViewModelMockBuilder<V, Args, S>.() -> Unit ): MockBuilder<V, Args> = SingleViewModelMockBuilder(viewModelReference, defaultState, defaultArgs).apply { mockBuilder() build(this@mockSingleViewModel) } /** * Similar to [mockSingleViewModel], but for the two view model case. */ fun <V : MockableMavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, Args : Parcelable> V.mockTwoViewModels( viewModel1Reference: KProperty1<V, VM1>, defaultState1: S1, viewModel2Reference: KProperty1<V, VM2>, defaultState2: S2, defaultArgs: Args?, mockBuilder: TwoViewModelMockBuilder<V, VM1, S1, VM2, S2, Args>.() -> Unit ): MockBuilder<V, Args> = TwoViewModelMockBuilder( viewModel1Reference, defaultState1, viewModel2Reference, defaultState2, defaultArgs ).apply { mockBuilder() build(this@mockTwoViewModels) } /** * Similar to [mockTwoViewModels], but for the three view model case. */ @Suppress("Detekt.ParameterListWrapping") @SuppressWarnings("Detekt.LongParameterList") fun <V : MockableMavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>, Args : Parcelable> V.mockThreeViewModels( viewModel1Reference: KProperty1<V, VM1>, defaultState1: S1, viewModel2Reference: KProperty1<V, VM2>, defaultState2: S2, viewModel3Reference: KProperty1<V, VM3>, defaultState3: S3, defaultArgs: Args?, mockBuilder: ThreeViewModelMockBuilder<V, VM1, S1, VM2, S2, VM3, S3, Args>.() -> Unit ): MockBuilder<V, Args> = ThreeViewModelMockBuilder( viewModel1Reference, defaultState1, viewModel2Reference, defaultState2, viewModel3Reference, defaultState3, defaultArgs ).apply { mockBuilder() build(this@mockThreeViewModels) } /** * Similar to [mockTwoViewModels], but for the four view model case. */ @Suppress("Detekt.ParameterListWrapping") @SuppressWarnings("Detekt.LongParameterList") fun <V : MockableMavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>, S4 : MavericksState, VM4 : MavericksViewModel<S4>, Args : Parcelable> V.mockFourViewModels( viewModel1Reference: KProperty1<V, VM1>, defaultState1: S1, viewModel2Reference: KProperty1<V, VM2>, defaultState2: S2, viewModel3Reference: KProperty1<V, VM3>, defaultState3: S3, viewModel4Reference: KProperty1<V, VM4>, defaultState4: S4, defaultArgs: Args?, mockBuilder: FourViewModelMockBuilder<V, VM1, S1, VM2, S2, VM3, S3, VM4, S4, Args>.() -> Unit ): MockBuilder<V, Args> = FourViewModelMockBuilder( viewModel1Reference, defaultState1, viewModel2Reference, defaultState2, viewModel3Reference, defaultState3, viewModel4Reference, defaultState4, defaultArgs ).apply { mockBuilder() build(this@mockFourViewModels) } /** * Similar to [mockTwoViewModels], but for the five view model case. */ @Suppress("Detekt.ParameterListWrapping") @SuppressWarnings("Detekt.LongParameterList") fun <V : MockableMavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>, S4 : MavericksState, VM4 : MavericksViewModel<S4>, S5 : MavericksState, VM5 : MavericksViewModel<S5>, Args : Parcelable> V.mockFiveViewModels( viewModel1Reference: KProperty1<V, VM1>, defaultState1: S1, viewModel2Reference: KProperty1<V, VM2>, defaultState2: S2, viewModel3Reference: KProperty1<V, VM3>, defaultState3: S3, viewModel4Reference: KProperty1<V, VM4>, defaultState4: S4, viewModel5Reference: KProperty1<V, VM5>, defaultState5: S5, defaultArgs: Args?, mockBuilder: FiveViewModelMockBuilder<V, VM1, S1, VM2, S2, VM3, S3, VM4, S4, VM5, S5, Args>.() -> Unit ): MockBuilder<V, Args> = FiveViewModelMockBuilder( viewModel1Reference, defaultState1, viewModel2Reference, defaultState2, viewModel3Reference, defaultState3, viewModel4Reference, defaultState4, viewModel5Reference, defaultState5, defaultArgs ).apply { mockBuilder() build(this@mockFiveViewModels) } @Suppress("Detekt.ParameterListWrapping") @SuppressWarnings("Detekt.LongParameterList") fun <V : MockableMavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>, S4 : MavericksState, VM4 : MavericksViewModel<S4>, S5 : MavericksState, VM5 : MavericksViewModel<S5>, S6 : MavericksState, VM6 : MavericksViewModel<S6>, Args : Parcelable> V.mockSixViewModels( viewModel1Reference: KProperty1<V, VM1>, defaultState1: S1, viewModel2Reference: KProperty1<V, VM2>, defaultState2: S2, viewModel3Reference: KProperty1<V, VM3>, defaultState3: S3, viewModel4Reference: KProperty1<V, VM4>, defaultState4: S4, viewModel5Reference: KProperty1<V, VM5>, defaultState5: S5, viewModel6Reference: KProperty1<V, VM6>, defaultState6: S6, defaultArgs: Args?, mockBuilder: SixViewModelMockBuilder<V, VM1, S1, VM2, S2, VM3, S3, VM4, S4, VM5, S5, VM6, S6, Args>.() -> Unit ): MockBuilder<V, Args> = SixViewModelMockBuilder( viewModel1Reference, defaultState1, viewModel2Reference, defaultState2, viewModel3Reference, defaultState3, viewModel4Reference, defaultState4, viewModel5Reference, defaultState5, viewModel6Reference, defaultState6, defaultArgs ).apply { mockBuilder() build(this@mockSixViewModels) } @Suppress("Detekt.ParameterListWrapping") @SuppressWarnings("Detekt.LongParameterList") fun <V : MockableMavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>, S4 : MavericksState, VM4 : MavericksViewModel<S4>, S5 : MavericksState, VM5 : MavericksViewModel<S5>, S6 : MavericksState, VM6 : MavericksViewModel<S6>, S7 : MavericksState, VM7 : MavericksViewModel<S7>, Args : Parcelable> V.mockSevenViewModels( viewModel1Reference: KProperty1<V, VM1>, defaultState1: S1, viewModel2Reference: KProperty1<V, VM2>, defaultState2: S2, viewModel3Reference: KProperty1<V, VM3>, defaultState3: S3, viewModel4Reference: KProperty1<V, VM4>, defaultState4: S4, viewModel5Reference: KProperty1<V, VM5>, defaultState5: S5, viewModel6Reference: KProperty1<V, VM6>, defaultState6: S6, viewModel7Reference: KProperty1<V, VM7>, defaultState7: S7, defaultArgs: Args?, mockBuilder: SevenViewModelMockBuilder<V, VM1, S1, VM2, S2, VM3, S3, VM4, S4, VM5, S5, VM6, S6, VM7, S7, Args>.() -> Unit ): MockBuilder<V, Args> = SevenViewModelMockBuilder( viewModel1Reference, defaultState1, viewModel2Reference, defaultState2, viewModel3Reference, defaultState3, viewModel4Reference, defaultState4, viewModel5Reference, defaultState5, viewModel6Reference, defaultState6, viewModel7Reference, defaultState7, defaultArgs ).apply { mockBuilder() build(this@mockSevenViewModels) } /** * Defines a unique variation of a View's state for testing purposes. * * A view is represented completely by: * 1. The arguments used to initialize it * 2. The State classes of all ViewModels used by the View * * For proper mocking, the View MUST NOT reference data from any other sources, such as static * singletons, dependency injection, shared preferences, etc. All of this should be channeled * through the ViewModel and State. Otherwise a mock cannot deterministically and completely * be used to test the View. * * An exception is Android OS level View state, with things such as scroll and cursor positions. * These are not feasible to track in state, and are generally independent and inconsequential in * testing. * * It is recommended that the "Default" mock state for a view represent the most canonical, complete * form of the View. For example, all data loaded, with no empty or null instances. * * Other mock variations should test alterations to this "default" state, with each variant testing * a minimal difference (ideally only one change). For example, a variant may test that a single * property is null or empty. * * This pattern is encouraged because: * 1. The tools for defining mock variations are designed to enable easy modification of the default * 2. Each mock variant is only one line of code, and is easily maintained * 3. Each variant tests a single edge case */ class MavericksMock<V : MavericksView, Args : Parcelable> @PublishedApi internal constructor( val name: String, @PublishedApi internal val argsProvider: () -> Args?, @PublishedApi internal val statesProvider: () -> List<MockState<V, *>>, /** * If true, this mock tests the view being created either from arguments or with the viewmodels' * default constructor (when [args] is null). */ val forInitialization: Boolean = false, val type: Type = Type.Custom ) { /** * Returns the arguments that should be used to initialize the Mavericks view. If null, the view models will be * initialized purely with the mock states instead. */ val args: Args? by lazy { argsProvider() } /** * The State to set on each ViewModel in the View. There should be a one to one match. */ val states: List<MockState<V, *>> by lazy { statesProvider() } /** * Find a mocked state value for the given view model property. * * If null is returned it means the initial state should be created through the * default mavericks mechanism of arguments. */ fun stateForViewModelProperty(property: KProperty<*>, existingViewModel: Boolean): MavericksState? { if (forInitialization && !existingViewModel) { // In the multi viewmodel case, an "existing" view model needs to be mocked with initial state (since it's args // would be from a different view), but for viewmodels being created in this view we can use args to create initial state. return null } // It's possible to have multiple viewmodels of the same type within a fragment. To differentiate them we look // at the property names. val viewModelToUse = states.firstOrNull { it.viewModelProperty.name == property.name } return viewModelToUse?.state ?: error("No state found for ViewModel property '${property.name}'. Available view models are ${states.map { it.viewModelProperty.name }}") } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MavericksMock<*, *> if (name != other.name) return false if (forInitialization != other.forInitialization) return false if (type != other.type) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + forInitialization.hashCode() result = 31 * result + type.hashCode() return result } val isDefaultInitialization: Boolean get() = type == Type.DefaultInitialization val isDefaultState: Boolean get() = type == Type.DefaultState val isForProcessRecreation: Boolean get() = type == Type.ProcessRecreation /** * There are a set of standard mock variants that all Views have. Beyond that users can define * custom mock variants. */ enum class Type { /** Uses view arguments to test the initialization pathway of Mavericks. */ DefaultInitialization, /** Uses the default state of a mock builder to represent the canonical form of a View. */ DefaultState, /** Takes the default state and applies the process used to save and restore state. The output * state approximates the State after app process recreation. (This cannot be exact because * in practice it may rely on arguments set in a previous Fragment.) */ ProcessRecreation, /** Any additional mock variant defined by the user. */ Custom } companion object { internal const val DEFAULT_INITIALIZATION_NAME = "Default initialization" internal const val DEFAULT_STATE_NAME = "Default state" internal const val RESTORED_STATE_NAME = "Default state after process recreation" } } /** * A mocked State value and a reference to the ViewModel that the State is intended for. */ data class MockState<V : MavericksView, S : MavericksState> internal constructor( val viewModelProperty: KProperty1<V, MavericksViewModel<S>>, val state: S ) /** * Provides a DSL for defining variations to the default mock state. */ class SingleViewModelMockBuilder<V : MockableMavericksView, Args : Parcelable, S : MavericksState> internal constructor( private val viewModelReference: KProperty1<V, MavericksViewModel<S>>, private val defaultState: S, defaultArgs: Args? ) : MockBuilder<V, Args>(defaultArgs, viewModelReference.pairDefault(defaultState)) { /** * Provide a state object via the lambda for the view model being mocked. * The receiver of the lambda is the default state provided in the top level mock method. For simplicity you * can modify the receiver directly. * * The DSL provided by [DataClassSetDsl] can be used for simpler state modification. * * Mock variations should test alterations to the "default" state, with each variant testing * a minimal difference (ideally only one change). For example, a variant may test that a single * property is null or empty. * * @param name Describes the UI the state puts the view in. Should be unique. * @param args The arguments that should be provided to the view. * This is only useful if the view accesses arguments directly to get data that is not provided in the view model state. * In other cases it should be omitted. By default the args you set as default in the top level mock method will be used. * The receiver of the lambda is the default args. * @param stateBuilder A lambda whose return object is the state for this mock. The lambda receiver is the default state. */ fun state(name: String, args: (Args.() -> Args)? = null, stateBuilder: S.() -> S) { addState( name = name, argsProvider = evaluateArgsLambda(args), statesProvider = { listOf(MockState(viewModelReference, defaultState.stateBuilder())) } ) } /** * Helper to mock the loading and failure state of an Async property on your state. * Creates two different mocked states stemmed from the given state - one where the async property is set to Loading * and one where it is set to Fail. */ fun <T, A : Async<T>> stateForLoadingAndFailure( state: S = defaultState, asyncPropertyBlock: S.() -> KProperty0<A> ) { val asyncProperty = state.asyncPropertyBlock() // Split "myProperty" to "My property" val asyncName = asyncProperty.name.replace(Regex("[A-Z]")) { " ${it.value.toLowerCase()}" }.trim() .capitalize() state("$asyncName loading") { state.setLoading { asyncProperty } } state("$asyncName failed") { state.setNetworkFailure { asyncProperty } } } } private fun <V : MockableMavericksView, S : MavericksState, VM : MavericksViewModel<S>> KProperty1<V, VM>.pairDefault( state: MavericksState ): Pair<KProperty1<V, MavericksViewModel<MavericksState>>, MavericksState> { @Suppress("UNCHECKED_CAST") return (this to state) as Pair<KProperty1<V, MavericksViewModel<MavericksState>>, MavericksState> } class TwoViewModelMockBuilder< V : MockableMavericksView, VM1 : MavericksViewModel<S1>, S1 : MavericksState, VM2 : MavericksViewModel<S2>, S2 : MavericksState, Args : Parcelable> internal constructor( val vm1: KProperty1<V, VM1>, val defaultState1: S1, val vm2: KProperty1<V, VM2>, val defaultState2: S2, defaultArgs: Args? ) : MockBuilder<V, Args>( defaultArgs, vm1.pairDefault(defaultState1), vm2.pairDefault(defaultState2) ) { /** * Provide state objects for each view model in the view. * * The DSL provided by [DataClassSetDsl] can be used for simpler state modification. * * Mock variations should test alterations to the "default" state, with each variant testing * a minimal difference (ideally only one change). For example, a variant may test that a single * property is null or empty. * * @param name Describes the UI these states put the view in. Should be unique. * @param args The arguments that should be provided to the view. * This is only useful if the view accesses arguments directly to get data that is not provided in the view model state. * In other cases it should be omitted. By default the args you set as default in the top level mock method will be used. * The receiver of the lambda is the default args. * @param statesBuilder A lambda that is used to define state objects for each view model. */ fun state( name: String, args: (Args.() -> Args)? = null, statesBuilder: TwoStatesBuilder<V, S1, VM1, S2, VM2>.() -> Unit ) { addState( name, evaluateArgsLambda(args), { TwoStatesBuilder( vm1, defaultState1, vm2, defaultState2 ).apply(statesBuilder).states } ) } /** * Helper to mock the loading and failure state of an Async property on your state in the first view model. * Creates two different mocked states stemmed from the given state - one where the async property is set to Loading * and one where it is set to Fail. */ fun <T, A : Async<T>> viewModel1StateForLoadingAndFailure( state: S1 = defaultState1, asyncPropertyBlock: S1.() -> KProperty0<A> ) { val asyncProperty = state.asyncPropertyBlock() val asyncName = asyncProperty.splitNameByCase() state("$asyncName loading") { viewModel1 { state.setLoading { asyncProperty } } } state("$asyncName failed") { viewModel1 { state.setNetworkFailure { asyncProperty } } } } /** * Helper to mock the loading and failure state of an Async property on your state in the second view model. * Creates two different mocked states stemmed from the given state - one where the async property is set to Loading * and one where it is set to Fail. */ fun <T, A : Async<T>> viewModel2StateForLoadingAndFailure( state: S2 = defaultState2, asyncPropertyBlock: S2.() -> KProperty0<A> ) { val asyncProperty = state.asyncPropertyBlock() val asyncName = asyncProperty.splitNameByCase() state("$asyncName loading") { viewModel2 { state.setLoading { asyncProperty } } } state("$asyncName failed") { viewModel2 { state.setNetworkFailure { asyncProperty } } } } } // Split "myProperty" to "My property" private fun KProperty0<Any?>.splitNameByCase(): String { return name.replace(Regex("[A-Z]")) { " ${it.value.toLowerCase()}" }.trim().capitalize() } /** * Helper to provide mock state definitions for multiple view models. * * Usage is like: * * viewModel1 { * // receiver is default state, make change and return new state * } * * viewModel2 { * // receiver is default state, make change and return new state * } */ open class TwoStatesBuilder< V : MavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>> internal constructor( val vm1: KProperty1<V, VM1>, val defaultState1: S1, val vm2: KProperty1<V, VM2>, val defaultState2: S2 ) { private val stateMap = mutableMapOf<KProperty1<V, MavericksViewModel<MavericksState>>, MavericksState>() internal val states: List<MockState<V, *>> get() = stateMap.map { entry -> MockState( entry.key, entry.value ) } protected infix fun <VM : MavericksViewModel<S>, S : MavericksState> KProperty1<V, VM>.setStateTo( state: S ) { @Suppress("UNCHECKED_CAST") stateMap[this as KProperty1<V, MavericksViewModel<MavericksState>>] = state } init { vm1 setStateTo defaultState1 vm2 setStateTo defaultState2 } /** * Define a state to be used when mocking your first view model (as defined in the top level mock method). * If this method isn't called, your default state will be used automatically. * For convenience, the receiver of the lambda is the default state. */ fun viewModel1(stateBuilder: S1.() -> S1) { vm1 setStateTo defaultState1.stateBuilder() } /** * Define a state to be used when mocking your second view model (as defined in the top level mock method). * If this method isn't called, your default state will be used automatically. * For convenience, the receiver of the lambda is the default state. */ fun viewModel2(stateBuilder: S2.() -> S2) { vm2 setStateTo defaultState2.stateBuilder() } } class ThreeViewModelMockBuilder< V : MockableMavericksView, VM1 : MavericksViewModel<S1>, S1 : MavericksState, VM2 : MavericksViewModel<S2>, S2 : MavericksState, VM3 : MavericksViewModel<S3>, S3 : MavericksState, Args : Parcelable> internal constructor( val vm1: KProperty1<V, VM1>, val defaultState1: S1, val vm2: KProperty1<V, VM2>, val defaultState2: S2, val vm3: KProperty1<V, VM3>, val defaultState3: S3, defaultArgs: Args? ) : MockBuilder<V, Args>( defaultArgs, vm1.pairDefault(defaultState1), vm2.pairDefault(defaultState2), vm3.pairDefault(defaultState3) ) { /** * Provide state objects for each view model in the view. * * @param name Describes the UI these states put the view in. Should be unique. * @param args The arguments that should be provided to the view. * This is only used if the view accesses arguments directly to get data that is not provided in the view model state. * In other cases it should be omitted. This must be provided if the view accesses args directly. * @param statesBuilder A lambda that is used to define state objects for each view model. See [ThreeStatesBuilder] */ fun state( name: String, args: (Args.() -> Args)? = null, statesBuilder: ThreeStatesBuilder<V, S1, VM1, S2, VM2, S3, VM3>.() -> Unit ) { addState( name, evaluateArgsLambda(args), { ThreeStatesBuilder( vm1, defaultState1, vm2, defaultState2, vm3, defaultState3 ).apply(statesBuilder).states } ) } /** * Helper to mock the loading and failure state of an Async property on your state in the first view model. * Creates two different mocked states stemmed from the given state - one where the async property is set to Loading * and one where it is set to Fail. */ fun <T, A : Async<T>> viewModel1StateForLoadingAndFailure( state: S1 = defaultState1, asyncPropertyBlock: S1.() -> KProperty0<A> ) { val asyncProperty = state.asyncPropertyBlock() val asyncName = asyncProperty.splitNameByCase() state("$asyncName loading") { viewModel1 { state.setLoading { asyncProperty } } } state("$asyncName failed") { viewModel1 { state.setNetworkFailure { asyncProperty } } } } /** * Helper to mock the loading and failure state of an Async property on your state in the second view model. * Creates two different mocked states stemmed from the given state - one where the async property is set to Loading * and one where it is set to Fail. */ fun <T, A : Async<T>> viewModel2StateForLoadingAndFailure( state: S2 = defaultState2, asyncPropertyBlock: S2.() -> KProperty0<A> ) { val asyncProperty = state.asyncPropertyBlock() val asyncName = asyncProperty.splitNameByCase() state("$asyncName loading") { viewModel2 { state.setLoading { asyncProperty } } } state("$asyncName failed") { viewModel2 { state.setNetworkFailure { asyncProperty } } } } /** * Helper to mock the loading and failure state of an Async property on your state in the third view model. * Creates two different mocked states stemmed from the given state - one where the async property is set to Loading * and one where it is set to Fail. */ fun <T, A : Async<T>> viewModel3StateForLoadingAndFailure( state: S3 = defaultState3, asyncPropertyBlock: S3.() -> KProperty0<A> ) { val asyncProperty = state.asyncPropertyBlock() val asyncName = asyncProperty.splitNameByCase() state("$asyncName loading") { viewModel3 { state.setLoading { asyncProperty } } } state("$asyncName failed") { viewModel3 { state.setNetworkFailure { asyncProperty } } } } } open class ThreeStatesBuilder< V : MavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>> internal constructor( vm1: KProperty1<V, VM1>, defaultState1: S1, vm2: KProperty1<V, VM2>, defaultState2: S2, val vm3: KProperty1<V, VM3>, val defaultState3: S3 ) : TwoStatesBuilder<V, S1, VM1, S2, VM2>(vm1, defaultState1, vm2, defaultState2) { init { vm3 setStateTo defaultState3 } /** * Define a state to be used when mocking your third view model (as defined in the top level mock method). * If this method isn't called, your default state will be used automatically. * For convenience, the receiver of the lambda is the default state. */ fun viewModel3(stateBuilder: S3.() -> S3) { vm3 setStateTo defaultState3.stateBuilder() } } class FourViewModelMockBuilder< V : MockableMavericksView, VM1 : MavericksViewModel<S1>, S1 : MavericksState, VM2 : MavericksViewModel<S2>, S2 : MavericksState, VM3 : MavericksViewModel<S3>, S3 : MavericksState, VM4 : MavericksViewModel<S4>, S4 : MavericksState, Args : Parcelable> internal constructor( val vm1: KProperty1<V, VM1>, val defaultState1: S1, val vm2: KProperty1<V, VM2>, val defaultState2: S2, val vm3: KProperty1<V, VM3>, val defaultState3: S3, val vm4: KProperty1<V, VM4>, val defaultState4: S4, defaultArgs: Args? ) : MockBuilder<V, Args>( defaultArgs, vm1.pairDefault(defaultState1), vm2.pairDefault(defaultState2), vm3.pairDefault(defaultState3), vm4.pairDefault(defaultState4) ) { /** * Provide state objects for each view model in the view. * * @param name Describes the UI these states put the view in. Should be unique. * @param args The arguments that should be provided to the view. * This is only used if the view accesses arguments directly to get data that is not provided in the view model state. * In other cases it should be omitted. This must be provided if the view accesses args directly. * @param statesBuilder A lambda that is used to define state objects for each view model. See [FourStatesBuilder] */ fun state( name: String, args: (Args.() -> Args)? = null, statesBuilder: FourStatesBuilder<V, S1, VM1, S2, VM2, S3, VM3, S4, VM4>.() -> Unit ) { addState( name, evaluateArgsLambda(args), { FourStatesBuilder( vm1, defaultState1, vm2, defaultState2, vm3, defaultState3, vm4, defaultState4 ).apply(statesBuilder).states } ) } } open class FourStatesBuilder< V : MavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>, S4 : MavericksState, VM4 : MavericksViewModel<S4>> internal constructor( vm1: KProperty1<V, VM1>, defaultState1: S1, vm2: KProperty1<V, VM2>, defaultState2: S2, vm3: KProperty1<V, VM3>, defaultState3: S3, val vm4: KProperty1<V, VM4>, val defaultState4: S4 ) : ThreeStatesBuilder<V, S1, VM1, S2, VM2, S3, VM3>( vm1, defaultState1, vm2, defaultState2, vm3, defaultState3 ) { init { vm4 setStateTo defaultState4 } /** * Define a state to be used when mocking your fourth view model (as defined in the top level mock method). * If this method isn't called, your default state will be used automatically. * For convenience, the receiver of the lambda is the default state. */ fun viewModel4(stateBuilder: S4.() -> S4) { vm4 setStateTo defaultState4.stateBuilder() } } class FiveViewModelMockBuilder< V : MockableMavericksView, VM1 : MavericksViewModel<S1>, S1 : MavericksState, VM2 : MavericksViewModel<S2>, S2 : MavericksState, VM3 : MavericksViewModel<S3>, S3 : MavericksState, VM4 : MavericksViewModel<S4>, S4 : MavericksState, VM5 : MavericksViewModel<S5>, S5 : MavericksState, Args : Parcelable> internal constructor( val vm1: KProperty1<V, VM1>, val defaultState1: S1, val vm2: KProperty1<V, VM2>, val defaultState2: S2, val vm3: KProperty1<V, VM3>, val defaultState3: S3, val vm4: KProperty1<V, VM4>, val defaultState4: S4, val vm5: KProperty1<V, VM5>, val defaultState5: S5, defaultArgs: Args? ) : MockBuilder<V, Args>( defaultArgs, vm1.pairDefault(defaultState1), vm2.pairDefault(defaultState2), vm3.pairDefault(defaultState3), vm4.pairDefault(defaultState4), vm5.pairDefault(defaultState5) ) { /** * Provide state objects for each view model in the view. * * @param name Describes the UI these states put the view in. Should be unique. * @param args The arguments that should be provided to the view. * This is only used if the view accesses arguments directly to get data that is not provided in the view model state. * In other cases it should be omitted. This must be provided if the view accesses args directly. * @param statesBuilder A lambda that is used to define state objects for each view model. See [FiveStatesBuilder] */ fun state( name: String, args: (Args.() -> Args)? = null, statesBuilder: FiveStatesBuilder<V, S1, VM1, S2, VM2, S3, VM3, S4, VM4, S5, VM5>.() -> Unit ) { addState( name, evaluateArgsLambda(args), { FiveStatesBuilder( vm1, defaultState1, vm2, defaultState2, vm3, defaultState3, vm4, defaultState4, vm5, defaultState5 ).apply(statesBuilder).states } ) } } open class FiveStatesBuilder< V : MavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>, S4 : MavericksState, VM4 : MavericksViewModel<S4>, S5 : MavericksState, VM5 : MavericksViewModel<S5>> internal constructor( vm1: KProperty1<V, VM1>, defaultState1: S1, vm2: KProperty1<V, VM2>, defaultState2: S2, vm3: KProperty1<V, VM3>, defaultState3: S3, vm4: KProperty1<V, VM4>, defaultState4: S4, val vm5: KProperty1<V, VM5>, val defaultState5: S5 ) : FourStatesBuilder<V, S1, VM1, S2, VM2, S3, VM3, S4, VM4>( vm1, defaultState1, vm2, defaultState2, vm3, defaultState3, vm4, defaultState4 ) { init { vm5 setStateTo defaultState5 } /** * Define a state to be used when mocking your fifth view model (as defined in the top level mock method). * If this method isn't called, your default state will be used automatically. * For convenience, the receiver of the lambda is the default state. */ fun viewModel5(stateBuilder: S5.() -> S5) { vm5 setStateTo defaultState5.stateBuilder() } } class SixViewModelMockBuilder< V : MockableMavericksView, VM1 : MavericksViewModel<S1>, S1 : MavericksState, VM2 : MavericksViewModel<S2>, S2 : MavericksState, VM3 : MavericksViewModel<S3>, S3 : MavericksState, VM4 : MavericksViewModel<S4>, S4 : MavericksState, VM5 : MavericksViewModel<S5>, S5 : MavericksState, VM6 : MavericksViewModel<S6>, S6 : MavericksState, Args : Parcelable> internal constructor( val vm1: KProperty1<V, VM1>, val defaultState1: S1, val vm2: KProperty1<V, VM2>, val defaultState2: S2, val vm3: KProperty1<V, VM3>, val defaultState3: S3, val vm4: KProperty1<V, VM4>, val defaultState4: S4, val vm5: KProperty1<V, VM5>, val defaultState5: S5, val vm6: KProperty1<V, VM6>, val defaultState6: S6, defaultArgs: Args? ) : MockBuilder<V, Args>( defaultArgs, vm1.pairDefault(defaultState1), vm2.pairDefault(defaultState2), vm3.pairDefault(defaultState3), vm4.pairDefault(defaultState4), vm5.pairDefault(defaultState5), vm6.pairDefault(defaultState6) ) { /** * Provide state objects for each view model in the view. * * @param name Describes the UI these states put the view in. Should be unique. * @param args The arguments that should be provided to the view. * This is only used if the view accesses arguments directly to get data that is not provided in the view model state. * In other cases it should be omitted. This must be provided if the view accesses args directly. * @param statesBuilder A lambda that is used to define state objects for each view model. See [SixStatesBuilder] */ fun state( name: String, args: (Args.() -> Args)? = null, statesBuilder: SixStatesBuilder<V, S1, VM1, S2, VM2, S3, VM3, S4, VM4, S5, VM5, S6, VM6>.() -> Unit ) { addState( name, evaluateArgsLambda(args), { SixStatesBuilder( vm1, defaultState1, vm2, defaultState2, vm3, defaultState3, vm4, defaultState4, vm5, defaultState5, vm6, defaultState6 ).apply(statesBuilder).states } ) } } open class SixStatesBuilder< V : MavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>, S4 : MavericksState, VM4 : MavericksViewModel<S4>, S5 : MavericksState, VM5 : MavericksViewModel<S5>, S6 : MavericksState, VM6 : MavericksViewModel<S6>> internal constructor( vm1: KProperty1<V, VM1>, defaultState1: S1, vm2: KProperty1<V, VM2>, defaultState2: S2, vm3: KProperty1<V, VM3>, defaultState3: S3, vm4: KProperty1<V, VM4>, defaultState4: S4, vm5: KProperty1<V, VM5>, defaultState5: S5, val vm6: KProperty1<V, VM6>, val defaultState6: S6 ) : FiveStatesBuilder<V, S1, VM1, S2, VM2, S3, VM3, S4, VM4, S5, VM5>( vm1, defaultState1, vm2, defaultState2, vm3, defaultState3, vm4, defaultState4, vm5, defaultState5 ) { init { vm6 setStateTo defaultState6 } /** * Define a state to be used when mocking your sixth view model (as defined in the top level mock method). * If this method isn't called, your default state will be used automatically. * For convenience, the receiver of the lambda is the default state. */ fun viewModel6(stateBuilder: S6.() -> S6) { vm6 setStateTo defaultState6.stateBuilder() } } class SevenViewModelMockBuilder< V : MockableMavericksView, VM1 : MavericksViewModel<S1>, S1 : MavericksState, VM2 : MavericksViewModel<S2>, S2 : MavericksState, VM3 : MavericksViewModel<S3>, S3 : MavericksState, VM4 : MavericksViewModel<S4>, S4 : MavericksState, VM5 : MavericksViewModel<S5>, S5 : MavericksState, VM6 : MavericksViewModel<S6>, S6 : MavericksState, VM7 : MavericksViewModel<S7>, S7 : MavericksState, Args : Parcelable> internal constructor( val vm1: KProperty1<V, VM1>, val defaultState1: S1, val vm2: KProperty1<V, VM2>, val defaultState2: S2, val vm3: KProperty1<V, VM3>, val defaultState3: S3, val vm4: KProperty1<V, VM4>, val defaultState4: S4, val vm5: KProperty1<V, VM5>, val defaultState5: S5, val vm6: KProperty1<V, VM6>, val defaultState6: S6, val vm7: KProperty1<V, VM7>, val defaultState7: S7, defaultArgs: Args? ) : MockBuilder<V, Args>( defaultArgs, vm1.pairDefault(defaultState1), vm2.pairDefault(defaultState2), vm3.pairDefault(defaultState3), vm4.pairDefault(defaultState4), vm5.pairDefault(defaultState5), vm6.pairDefault(defaultState6), vm7.pairDefault(defaultState7) ) { /** * Provide state objects for each view model in the view. * * @param name Describes the UI these states put the view in. Should be unique. * @param args The arguments that should be provided to the view. * This is only used if the view accesses arguments directly to get data that is not provided in the view model state. * In other cases it should be omitted. This must be provided if the view accesses args directly. * @param statesBuilder A lambda that is used to define state objects for each view model. See [SevenStatesBuilder] */ fun state( name: String, args: (Args.() -> Args)? = null, statesBuilder: SevenStatesBuilder<V, S1, VM1, S2, VM2, S3, VM3, S4, VM4, S5, VM5, S6, VM6, S7, VM7>.() -> Unit ) { addState( name, evaluateArgsLambda(args), { SevenStatesBuilder( vm1, defaultState1, vm2, defaultState2, vm3, defaultState3, vm4, defaultState4, vm5, defaultState5, vm6, defaultState6, vm7, defaultState7 ).apply(statesBuilder).states } ) } } open class SevenStatesBuilder< V : MavericksView, S1 : MavericksState, VM1 : MavericksViewModel<S1>, S2 : MavericksState, VM2 : MavericksViewModel<S2>, S3 : MavericksState, VM3 : MavericksViewModel<S3>, S4 : MavericksState, VM4 : MavericksViewModel<S4>, S5 : MavericksState, VM5 : MavericksViewModel<S5>, S6 : MavericksState, VM6 : MavericksViewModel<S6>, S7 : MavericksState, VM7 : MavericksViewModel<S7>> internal constructor( vm1: KProperty1<V, VM1>, defaultState1: S1, vm2: KProperty1<V, VM2>, defaultState2: S2, vm3: KProperty1<V, VM3>, defaultState3: S3, vm4: KProperty1<V, VM4>, defaultState4: S4, vm5: KProperty1<V, VM5>, defaultState5: S5, vm6: KProperty1<V, VM6>, defaultState6: S6, val vm7: KProperty1<V, VM7>, val defaultState7: S7 ) : SixStatesBuilder<V, S1, VM1, S2, VM2, S3, VM3, S4, VM4, S5, VM5, S6, VM6>( vm1, defaultState1, vm2, defaultState2, vm3, defaultState3, vm4, defaultState4, vm5, defaultState5, vm6, defaultState6 ) { init { vm7 setStateTo defaultState7 } /** * Define a state to be used when mocking your seventh view model (as defined in the top level mock method). * If this method isn't called, your default state will be used automatically. * For convenience, the receiver of the lambda is the default state. */ fun viewModel7(stateBuilder: S7.() -> S7) { vm7 setStateTo defaultState7.stateBuilder() } } /** * This placeholder can be used as a NO-OP implementation of [MockableMavericksView.provideMocks]. */ object EmptyMocks : EmptyMavericksViewMocks() open class EmptyMavericksViewMocks : MavericksViewMocks<MockableMavericksView, Nothing>(allowCreationOfThisInstance = true) { override val mocks: List<MavericksMock<MockableMavericksView, out Nothing>> = emptyList() override val mockGroups: List<List<MavericksMock<MockableMavericksView, out Nothing>>> = emptyList() } /** * Defines a set of mocks for a Mavericks view. * * Use helper functions such as [mockSingleViewModel] to create this, instead of creating it directly. */ open class MavericksViewMocks<V : MockableMavericksView, Args : Parcelable> @PublishedApi internal constructor( allowCreationOfThisInstance: Boolean = false ) { /** * A list of mocks to use when testing a view. Each mock represents a unique state to be tested. * * At least one of [mocks] or [mockGroups] must be implemented. */ open val mocks: List<MavericksMock<V, out Args>> get() = mockGroups.flatten() /** * An optional breakdown of [mocks] to categorize them into groups. * * Groups allow splitting up a view with lots of mocks so they can be run in separate tests (better parallelization), * with separate default arguments and states. This is useful for complicated views that * want to share different default arguments or states with many mocks. */ open val mockGroups: List<List<MavericksMock<V, out Args>>> get() = listOf(mocks) init { require(allowCreationForTesting || allowCreationOfThisInstance || numAllowedCreationsOfMocks.get() > 0) { "Mock creation is not allowed! provideMocks() CANNOT be called directly. " + "Instead, call MavericksViewMocks#getFrom()" } } fun validate(viewName: String) { // TODO eli_hart: 2018-11-06 Gather all validation errors in one exception instead of failing early, so that you don't have to do multiple test runs to catch multiple issues val errorIntro = "Invalid mocks defined for $viewName. " val (mocksWithArgsOnly, mocksWithState) = mocks.partition { it.states.isEmpty() } fun List<MavericksMock<V, *>>.validateUniqueNames() { val nameCounts = groupingBy { it.name }.eachCount() nameCounts.forEach { (name, count) -> require(count == 1) { "$errorIntro '$name' was used multiple times. Mavericks mock state and argument names must be unique." } } } // We allow args and states to share names, such as "default", since they are different use cases. mocksWithArgsOnly.validateUniqueNames() mocksWithState.validateUniqueNames() } interface ViewMocksProvider { fun mavericksViewMocks(view: MockableMavericksView): MavericksViewMocks<out MockableMavericksView, out Parcelable> } object DefaultViewMocksProvider : ViewMocksProvider { override fun mavericksViewMocks(view: MockableMavericksView): MavericksViewMocks<out MockableMavericksView, out Parcelable> { return provideMocksFunction.call(view) as MavericksViewMocks<out MockableMavericksView, out Parcelable> } } companion object { /** * Exposed for internal tests to allow us to workaround the requirement that this class * can only be created via [getFrom]. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <R> allowCreationForTesting(block: () -> R): R { allowCreationForTesting = true val result: R = block() allowCreationForTesting = false return result } private var allowCreationForTesting: Boolean = false private val provideMocksFunction: KFunction<*> by lazy { MockableMavericksView::class.findFunction("provideMocks") } /** * A Provider of [MavericksViewMocks] will be used to retrieve mocks first before calling [MockableMavericksView.provideMocks]. */ var mockProvider: ViewMocksProvider = DefaultViewMocksProvider /** * Tracks how many mock instances are being validly created. This allows our gating * to be done in a thread safe way. */ private val numAllowedCreationsOfMocks = AtomicInteger(0) /** * Retrieves the mocks from a view provided by [mockProvider]. * If not set will default to [DefaultViewMocksProvider] * * All access to mocks is gated behind this function so that it can enforce that * mocks are only used in debug mode, and so that this function can access mocks * reflectively. By only accessing mocks reflectively they are allowed to be stripped * by minification for non debug builds. * * This returns empty if [MockableMavericks.enableMavericksViewMocking] is disabled. */ fun getFrom(view: MockableMavericksView): MavericksViewMocks<out MockableMavericksView, out Parcelable> { if (!MockableMavericks.enableMavericksViewMocking) { Log.w("MockBuilder", "Mocks accessed in non debug build") return EmptyMocks } numAllowedCreationsOfMocks.incrementAndGet() val mocks = mockProvider.mavericksViewMocks(view) require(numAllowedCreationsOfMocks.decrementAndGet() >= 0) { "numAllowedCreationsOfMocks is negative" } return mocks } } } open class MockBuilder<V : MockableMavericksView, Args : Parcelable> internal constructor( internal val defaultArgs: Args?, vararg defaultStatePairs: Pair<KProperty1<V, MavericksViewModel<MavericksState>>, MavericksState> ) : MavericksViewMocks<V, Args>(), DataClassSetDsl { internal val defaultStates = defaultStatePairs.map { MockState(it.first, it.second) } @VisibleForTesting override val mocks = mutableListOf<MavericksMock<V, Args>>() init { val viewModelProperties = defaultStates.map { it.viewModelProperty } require(viewModelProperties.distinct().size == defaultStates.size) { "Duplicate viewmodels were passed to the mock method - ${viewModelProperties.map { it.name }}" } // Even if args are null this is useful to add because it tests the code flow where initial state // is created from its defaults. // This isn't necessary in the case of "existingViewModel" tests, but we can't know whether that's the case // at this point, so we need to add it anyway. addState( name = DEFAULT_INITIALIZATION_NAME, forInitialization = true, type = MavericksMock.Type.DefaultInitialization ) if (defaultStates.isNotEmpty()) { addState( name = DEFAULT_STATE_NAME, type = MavericksMock.Type.DefaultState ) addState( name = RESTORED_STATE_NAME, statesProvider = { defaultStates.map { it.copy(state = it.state.toRestoredState()) } }, type = MavericksMock.Type.ProcessRecreation ) } } /** * Provide an instance of arguments to use when initializing a view and creating initial view model state. * It is only valid to call this if you defined default arguments in the top level mock method. * For convenience, the receiver of the lambda is the default arguments. * * @param name Describes what state these arguments put the view in. Should be unique. */ fun args(name: String, builder: Args.() -> Args) { addState(name, argsProvider = evaluateArgsLambda(builder), forInitialization = true) } internal fun evaluateArgsLambda(builder: (Args.() -> Args)?): () -> Args? { if (builder == null) { return { defaultArgs } } requireNotNull(defaultArgs) { "Args cannot be provided unless you have set a default value for them in the top level mock method" } return { builder.invoke(defaultArgs) } } protected fun addState( name: String, argsProvider: () -> Args? = { defaultArgs }, statesProvider: () -> List<MockState<V, *>> = { defaultStates }, forInitialization: Boolean = false, type: MavericksMock.Type = MavericksMock.Type.Custom ) { mocks.add( MavericksMock( name = name, argsProvider = argsProvider, statesProvider = statesProvider, forInitialization = forInitialization, type = type ) ) } internal fun build(view: V) { validate(view::class.java.simpleName) } private fun <S : MavericksState> S.toRestoredState(): S { val klass = this::class /** Filter out params that don't have an associated @PersistState prop. * Map the parameter name to the current value of its associated property * Reduce the @PersistState parameters into a bundle mapping the parameter name to the property value. */ val primaryConstructor = klass.primaryConstructor ?: error("No primary constructor for $this") return primaryConstructor .parameters .filter { kParameter -> kParameter.annotations.any { it.annotationClass == PersistState::class } || !kParameter.isOptional } .map { param -> val prop = klass.declaredMemberProperties.single { it.name == param.name } @Suppress("UNCHECKED_CAST") val value = (prop as? KProperty1<S, Any?>)?.get(this) param to value } .let { pairs -> primaryConstructor.callBy(pairs.toMap()) } } }
apache-2.0
b92fbea5c5ac53d6855eacc03a51d03d
34.636087
181
0.649607
4.24866
false
false
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderCustomFilterDialog.kt
2
11665
package eu.kanade.tachiyomi.ui.reader import android.app.Dialog import android.graphics.Color import android.os.Bundle import android.support.annotation.ColorInt import android.support.v4.app.DialogFragment import android.view.View import android.widget.SeekBar import com.afollestad.materialdialogs.MaterialDialog import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.util.plusAssign import eu.kanade.tachiyomi.widget.SimpleSeekBarListener import kotlinx.android.synthetic.main.reader_custom_filter_dialog.view.* import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.subscriptions.CompositeSubscription import uy.kohesive.injekt.injectLazy import java.util.concurrent.TimeUnit /** * Custom dialog which can be used to set overlay value's */ class ReaderCustomFilterDialog : DialogFragment() { companion object { /** Integer mask of alpha value **/ private const val ALPHA_MASK: Long = 0xFF000000 /** Integer mask of red value **/ private const val RED_MASK: Long = 0x00FF0000 /** Integer mask of green value **/ private const val GREEN_MASK: Long = 0x0000FF00 /** Integer mask of blue value **/ private const val BLUE_MASK: Long = 0x000000FF } /** * Provides operations to manage preferences */ private val preferences by injectLazy<PreferencesHelper>() /** * Subscription used for filter overlay */ private lateinit var subscriptions: CompositeSubscription /** * Subscription used for custom brightness overlay */ private var customBrightnessSubscription: Subscription? = null /** * Subscription used for color filter overlay */ private var customFilterColorSubscription: Subscription? = null /** * This method will be called after onCreate(Bundle) * @param savedState The last saved instance state of the Fragment. */ override fun onCreateDialog(savedState: Bundle?): Dialog { val dialog = MaterialDialog.Builder(activity!!) .customView(R.layout.reader_custom_filter_dialog, false) .positiveText(android.R.string.ok) .build() subscriptions = CompositeSubscription() onViewCreated(dialog.view, savedState) return dialog } /** * Called immediately after onCreateView() * @param view The View returned by onCreateDialog. * @param savedInstanceState If non-null, this fragment is being re-constructed */ override fun onViewCreated(view: View, savedInstanceState: Bundle?) = with(view) { // Initialize subscriptions. subscriptions += preferences.colorFilter().asObservable() .subscribe { setColorFilter(it, view) } subscriptions += preferences.customBrightness().asObservable() .subscribe { setCustomBrightness(it, view) } // Get color and update values val color = preferences.colorFilterValue().getOrDefault() val brightness = preferences.customBrightnessValue().getOrDefault() val argb = setValues(color, view) // Set brightness value txt_brightness_seekbar_value.text = brightness.toString() brightness_seekbar.progress = brightness // Initialize seekBar progress seekbar_color_filter_alpha.progress = argb[0] seekbar_color_filter_red.progress = argb[1] seekbar_color_filter_green.progress = argb[2] seekbar_color_filter_blue.progress = argb[3] // Set listeners switch_color_filter.isChecked = preferences.colorFilter().getOrDefault() switch_color_filter.setOnCheckedChangeListener { _, isChecked -> preferences.colorFilter().set(isChecked) } custom_brightness.isChecked = preferences.customBrightness().getOrDefault() custom_brightness.setOnCheckedChangeListener { _, isChecked -> preferences.customBrightness().set(isChecked) } seekbar_color_filter_alpha.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { setColorValue(value, ALPHA_MASK, 24) } } }) seekbar_color_filter_red.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { setColorValue(value, RED_MASK, 16) } } }) seekbar_color_filter_green.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { setColorValue(value, GREEN_MASK, 8) } } }) seekbar_color_filter_blue.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { setColorValue(value, BLUE_MASK, 0) } } }) brightness_seekbar.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { preferences.customBrightnessValue().set(value) } } }) } /** * Set enabled status of seekBars belonging to color filter * @param enabled determines if seekBar gets enabled * @param view view of the dialog */ private fun setColorFilterSeekBar(enabled: Boolean, view: View) = with(view) { seekbar_color_filter_red.isEnabled = enabled seekbar_color_filter_green.isEnabled = enabled seekbar_color_filter_blue.isEnabled = enabled seekbar_color_filter_alpha.isEnabled = enabled } /** * Set enabled status of seekBars belonging to custom brightness * @param enabled value which determines if seekBar gets enabled * @param view view of the dialog */ private fun setCustomBrightnessSeekBar(enabled: Boolean, view: View) = with(view) { brightness_seekbar.isEnabled = enabled } /** * Set the text value's of color filter * @param color integer containing color information * @param view view of the dialog */ fun setValues(color: Int, view: View): Array<Int> { val alpha = getAlphaFromColor(color) val red = getRedFromColor(color) val green = getGreenFromColor(color) val blue = getBlueFromColor(color) //Initialize values with(view) { txt_color_filter_alpha_value.text = alpha.toString() txt_color_filter_red_value.text = red.toString() txt_color_filter_green_value.text = green.toString() txt_color_filter_blue_value.text = blue.toString() } return arrayOf(alpha, red, green, blue) } /** * Manages the custom brightness value subscription * @param enabled determines if the subscription get (un)subscribed * @param view view of the dialog */ private fun setCustomBrightness(enabled: Boolean, view: View) { if (enabled) { customBrightnessSubscription = preferences.customBrightnessValue().asObservable() .sample(100, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .subscribe { setCustomBrightnessValue(it, view) } subscriptions.add(customBrightnessSubscription) } else { customBrightnessSubscription?.let { subscriptions.remove(it) } setCustomBrightnessValue(0, view, true) } setCustomBrightnessSeekBar(enabled, view) } /** * Sets the brightness of the screen. Range is [-75, 100]. * From -75 to -1 a semi-transparent black view is shown at the top with the minimum brightness. * From 1 to 100 it sets that value as brightness. * 0 sets system brightness and hides the overlay. */ private fun setCustomBrightnessValue(value: Int, view: View, isDisabled: Boolean = false) = with(view) { // Set black overlay visibility. if (value < 0) { brightness_overlay.visibility = View.VISIBLE val alpha = (Math.abs(value) * 2.56).toInt() brightness_overlay.setBackgroundColor(Color.argb(alpha, 0, 0, 0)) } else { brightness_overlay.visibility = View.GONE } if (!isDisabled) txt_brightness_seekbar_value.text = value.toString() } /** * Manages the color filter value subscription * @param enabled determines if the subscription get (un)subscribed * @param view view of the dialog */ private fun setColorFilter(enabled: Boolean, view: View) { if (enabled) { customFilterColorSubscription = preferences.colorFilterValue().asObservable() .sample(100, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .subscribe { setColorFilterValue(it, view) } subscriptions.add(customFilterColorSubscription) } else { customFilterColorSubscription?.let { subscriptions.remove(it) } view.color_overlay.visibility = View.GONE } setColorFilterSeekBar(enabled, view) } /** * Sets the color filter overlay of the screen. Determined by HEX of integer * @param color hex of color. * @param view view of the dialog */ private fun setColorFilterValue(@ColorInt color: Int, view: View) = with(view) { color_overlay.visibility = View.VISIBLE color_overlay.setBackgroundColor(color) setValues(color, view) } /** * Updates the color value in preference * @param color value of color range [0,255] * @param mask contains hex mask of chosen color * @param bitShift amounts of bits that gets shifted to receive value */ fun setColorValue(color: Int, mask: Long, bitShift: Int) { val currentColor = preferences.colorFilterValue().getOrDefault() val updatedColor = (color shl bitShift) or (currentColor and mask.inv().toInt()) preferences.colorFilterValue().set(updatedColor) } /** * Returns the alpha value from the Color Hex * @param color color hex as int * @return alpha of color */ fun getAlphaFromColor(color: Int): Int { return color shr 24 and 0xFF } /** * Returns the red value from the Color Hex * @param color color hex as int * @return red of color */ fun getRedFromColor(color: Int): Int { return color shr 16 and 0xFF } /** * Returns the green value from the Color Hex * @param color color hex as int * @return green of color */ fun getGreenFromColor(color: Int): Int { return color shr 8 and 0xFF } /** * Returns the blue value from the Color Hex * @param color color hex as int * @return blue of color */ fun getBlueFromColor(color: Int): Int { return color and 0xFF } /** * Called when dialog is dismissed */ override fun onDestroyView() { subscriptions.unsubscribe() super.onDestroyView() } }
apache-2.0
b9c0ac9c02b8a72cb103062ed50a7214
34.351515
108
0.643892
4.834231
false
false
false
false
stoman/CompetitiveProgramming
problems/2020adventofcode03b/submissions/accepted/Stefan.kt
2
598
import java.util.* fun count(map: List<List<Boolean>>, right: Int, down: Int): Int { var column = 0 var r = 0 for (i in map.indices step down) { if (map[i][column % map[i].size]) { r++ } column += right } return r } fun main() { val s = Scanner(System.`in`) val mutableMap: MutableList<List<Boolean>> = mutableListOf() while (s.hasNext()) { mutableMap.add(s.next().toList().map { it == '#' }) } val map: List<List<Boolean>> = mutableMap.toList() println(count(map, 1, 1) * count(map, 3, 1) * count(map, 5, 1) * count(map, 7, 1) * count(map, 1, 2)) }
mit
8664d6e7c1283b9d3b841178886db66e
22.92
103
0.578595
2.945813
false
false
false
false
msebire/intellij-community
community-guitests/testSrc/com/intellij/testGuiFramework/tests/community/focus/GoToClassTwiceFocusTest.kt
1
2797
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.tests.community.focus import com.intellij.openapi.actionSystem.ShortcutSet import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.keymap.KeymapUtil import com.intellij.testGuiFramework.fixtures.IdeFrameFixture import com.intellij.testGuiFramework.impl.GuiTestCase import com.intellij.testGuiFramework.impl.LogActionsDuringTest import com.intellij.testGuiFramework.impl.ScreenshotsDuringTest import com.intellij.testGuiFramework.tests.community.CommunityProjectCreator import com.intellij.testGuiFramework.util.Key.ESCAPE import org.fest.swing.core.SmartWaitRobot import org.fest.swing.timing.Pause import org.junit.Rule import org.junit.Test import java.lang.Math.tan import java.util.* import javax.swing.KeyStroke class GoToClassTwiceFocusTest : GuiTestCase() { private val typedString = "hefuihwefwehrf;werfwerfw" private val actionKeyStroke: KeyStroke by lazy { val activeKeymapShortcuts: ShortcutSet = KeymapUtil.getActiveKeymapShortcuts("GotoClass") KeymapUtil.getKeyStroke(activeKeymapShortcuts)!! } @Test fun testGoToClassFocusTwice() { CommunityProjectCreator.importCommandLineAppAndOpenMain() Pause.pause(1000) ideFrame { focusOnEditor() repeat(20) { intensiveCpuCalc() openGoToClassSearchAndType(this@GoToClassTwiceFocusTest) focusOnEditor() } } } private fun startIntensiveCalcOnEdt() { for (i in 0..1000) ApplicationManager.getApplication().invokeLater { println(intensiveCpuCalc().toString()) } } private fun startIntensiveCalcOnParallel() { ApplicationManager.getApplication().executeOnPooledThread { for (i in 0..100) ApplicationManager.getApplication().executeOnPooledThread { for (k in 0..1000) println(intensiveCpuCalc().toString()) } } } private fun intensiveCpuCalc(): Double { val rand = Random() val salt = rand.nextDouble() fun f(a: Double): Double = tan(rand.nextDouble() * tan(rand.nextDouble() * tan(rand.nextDouble() * tan(a + 0.001)))) fun g(n: Int, a: Double): Double { var res = a for (i in 0..n) res = f(res) return res } return g(10000, salt) } private fun IdeFrameFixture.focusOnEditor() { editor { moveTo(89) } } private fun openGoToClassSearchAndType(guiTestCase: GuiTestCase) { val smartRobot = guiTestCase.robot() as SmartWaitRobot smartRobot.shortcut(actionKeyStroke) smartRobot.shortcutAndTypeString(actionKeyStroke, typedString, 100) Pause.pause(500) FocusIssuesUtil.checkSearchEnteredText(typedString) shortcut(ESCAPE) } }
apache-2.0
314221ad3b9c1c4d67d5b7a643d8b41c
32.309524
140
0.749732
4.237879
false
true
false
false
MisumiRize/Factoria
lib/src/main/java/org/factoria/pool/ClassPool.kt
1
1304
package org.factoria.pool import android.content.Context import dalvik.system.DexFile import org.factoria.fixture.ClassFixture import org.factoria.FixturePool import org.yaml.snakeyaml.Yaml import java.io.InputStream import java.util.* import kotlin.text.Regex class ClassPool(val context: Context) : FixturePool { val yamlLoader = Yaml() override val pool = HashMap<String, ClassFixture>() override fun addFile(basename: String, iStream: InputStream) { val className = basename.capitalize() val fullName = DexFile(context.getPackageCodePath()).entries().asSequence().first { klass -> klass.splitBy(".").last() == className } val klass = Class.forName(fullName) @suppress("UNCHECKED_CAST") val yamlData = yamlLoader.load(iStream) as Map<String, Map<String, Any>> yamlData.forEach { entry -> val constructor = klass.getDeclaredConstructor() constructor.setAccessible(true) val obj = constructor.newInstance() entry.value.forEach { field -> val f = klass.getDeclaredField(field.key) f.setAccessible(true) f.set(obj, field.value) } pool.put(entry.key, ClassFixture(obj!!, klass)) } } }
apache-2.0
355b6d11f73a153fff6307e89f1a6f7c
30.047619
100
0.645706
4.346667
false
false
false
false
rock3r/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/processors/ProjectComplexityProcessor.kt
1
730
package io.gitlab.arturbosch.detekt.core.processors import io.gitlab.arturbosch.detekt.api.DetektVisitor import io.gitlab.arturbosch.detekt.api.internal.CyclomaticComplexity import org.jetbrains.kotlin.com.intellij.openapi.util.Key import org.jetbrains.kotlin.psi.KtFile class ProjectComplexityProcessor : AbstractProcessor() { override val visitor = ComplexityVisitor() override val key = complexityKey } val complexityKey = Key<Int>("complexity") class ComplexityVisitor : DetektVisitor() { override fun visitKtFile(file: KtFile) { val complexity = CyclomaticComplexity.calculate(file) { ignoreSimpleWhenEntries = false } file.putUserData(complexityKey, complexity) } }
apache-2.0
4c6c961bff2fbd487ad05d11195d599f
29.416667
68
0.760274
4.345238
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/preferences/HeaderPreference.kt
1
2217
/* * Copyright (c) 2022 Brayan Oliveira <[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 com.ichi2.preferences import android.content.Context import android.util.AttributeSet import androidx.core.content.withStyledAttributes import androidx.preference.Preference import com.ichi2.anki.LanguageUtils import com.ichi2.anki.R /** * Preference used on the headers of [com.ichi2.anki.preferences.HeaderFragment] */ class HeaderPreference @JvmOverloads // fixes: Error inflating class com.ichi2.preferences.HeaderPreference constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.preferenceStyle, defStyleRes: Int = R.style.Preference ) : Preference(context, attrs, defStyleAttr, defStyleRes) { init { context.withStyledAttributes(attrs, R.styleable.HeaderPreference) { val entries = getTextArray(R.styleable.HeaderPreference_summaryEntries) if (entries != null) { summary = buildHeaderSummary(*entries) } } } companion object { /** * Join [entries] with ` • ` as separator * to build a summary string for some preferences categories * e.g. `foo`, `bar`, `hi` -> `foo • bar • hi` */ fun buildHeaderSummary(vararg entries: CharSequence): String { return if (!LanguageUtils.appLanguageIsRTL()) { entries.joinToString(separator = " • ") } else { entries.reversed().joinToString(separator = " • ") } } } }
gpl-3.0
15c359cc1fb6aec370a328c8412ae7a9
35.783333
84
0.676031
4.260618
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/test/java/org/wordpress/android/fluxc/network/rest/wpapi/NonceRestClientTest.kt
1
5065
package org.wordpress.android.fluxc.network.rest.wpapi import com.android.volley.NoConnectionError import com.android.volley.RequestQueue import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import junit.framework.TestCase import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpapi.Nonce.Available import org.wordpress.android.fluxc.network.rest.wpapi.Nonce.FailedRequest import org.wordpress.android.fluxc.network.rest.wpapi.Nonce.Unknown import org.wordpress.android.fluxc.network.rest.wpapi.WPAPIResponse.Error import org.wordpress.android.fluxc.network.rest.wpapi.WPAPIResponse.Success import org.wordpress.android.fluxc.test import org.wordpress.android.fluxc.utils.CurrentTimeProvider import java.util.Date @RunWith(MockitoJUnitRunner::class) class NonceRestClientTest { @Mock lateinit var wpApiEncodedRequestBuilder: WPAPIEncodedBodyRequestBuilder @Mock lateinit var currentTimeProvider: CurrentTimeProvider @Mock lateinit var dispatcher: Dispatcher @Mock lateinit var requestQueue: RequestQueue @Mock lateinit var userAgent: UserAgent private lateinit var subject: NonceRestClient private val time = 123456L @Before fun setUp() { subject = NonceRestClient(wpApiEncodedRequestBuilder, currentTimeProvider, dispatcher, requestQueue, userAgent) whenever(currentTimeProvider.currentDate()).thenReturn(Date(time)) } @Test fun `successful nonce request`() = test { val site = SiteModel().apply { url = "asiteurl.com" username = "a_username" password = "a_password" } val body = mapOf( "log" to site.username, "pwd" to site.password, "redirect_to" to "${site.url}/wp-admin/admin-ajax.php?action=rest-nonce" ) val expectedNonce = "1expectedNONCE" val response = Success(expectedNonce) whenever(wpApiEncodedRequestBuilder.syncPostRequest(subject, "${site.url}/wp-login.php", body = body)) .thenReturn(response) val actual = subject.requestNonce(site) TestCase.assertEquals(Available(expectedNonce), actual) } @Test fun `invalid nonce of '0' returns FailedRequest`() = test { val site = SiteModel().apply { url = "asiteurl.com" username = "a_username" password = "a_password" } val body = mapOf( "log" to site.username, "pwd" to site.password, "redirect_to" to "${site.url}/wp-admin/admin-ajax.php?action=rest-nonce" ) val invalidNonce = "0" val response = Success(invalidNonce) whenever(wpApiEncodedRequestBuilder.syncPostRequest(subject, "${site.url}/wp-login.php", body = body)) .thenReturn(response) val actual = subject.requestNonce(site) TestCase.assertEquals(FailedRequest(time), actual) } @Test fun `failed nonce request reuturn FailedRequest`() = test { val site = SiteModel().apply { url = "asiteurl.com" username = "a_username" password = "a_password" } val body = mapOf( "log" to site.username, "pwd" to site.password, "redirect_to" to "${site.url}/wp-admin/admin-ajax.php?action=rest-nonce" ) val baseNetworkError = mock<BaseNetworkError>() baseNetworkError.message = "an_error_message" val response = Error<String>(baseNetworkError) whenever(wpApiEncodedRequestBuilder.syncPostRequest(subject, "${site.url}/wp-login.php", body = body)) .thenReturn(response) val actual = subject.requestNonce(site) TestCase.assertEquals(FailedRequest(time), actual) } @Test fun `failed nonce request with connection error returns Unknown`() = test { val site = SiteModel().apply { url = "asiteurl.com" username = "a_username" password = "a_password" } val body = mapOf( "log" to site.username, "pwd" to site.password, "redirect_to" to "${site.url}/wp-admin/admin-ajax.php?action=rest-nonce" ) val baseNetworkError = mock<BaseNetworkError>() baseNetworkError.volleyError = NoConnectionError() val response = Error<String>(baseNetworkError) whenever(wpApiEncodedRequestBuilder.syncPostRequest(subject, "${site.url}/wp-login.php", body = body)) .thenReturn(response) val actual = subject.requestNonce(site) TestCase.assertEquals(Unknown, actual) } }
gpl-2.0
b048efbe20ec9b64c88228441d9cffe6
35.970803
119
0.664758
4.362618
false
true
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/data/LocalDataHolderHelper.kt
1
1687
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data import org.lanternpowered.api.data.Key import org.lanternpowered.api.util.optional.orNull import org.lanternpowered.api.util.uncheckedCast import org.spongepowered.api.data.value.Value object LocalDataHolderHelper { /** * Matches the contents of the two [LocalDataHolder]s. * * @param dataHolderA The first data holder * @param dataHolderB The second data holder * @return Whether the contents match */ @JvmStatic fun matchContents(dataHolderA: LocalDataHolder, dataHolderB: LocalDataHolder): Boolean { val keyRegistryA = dataHolderA.keyRegistry val keyRegistryB = dataHolderB.keyRegistry // The same keys have to be present in both of the containers if (keyRegistryA.keys.size != keyRegistryB.keys.size) return false for (registrationA in keyRegistryA.registrations) { val registrationB = keyRegistryB[registrationA.key.uncheckedCast<Key<Value<Any>>>()] ?: return false // Get the values from both of the containers and match them val valueA = registrationA.anyDataProvider().get(dataHolderA).orNull() val valueB = registrationB.anyDataProvider().get(dataHolderB).orNull() if (valueA != valueB) return false } return true } }
mit
7b6f95b2c6440c885b92607207efe074
34.145833
112
0.688797
4.336761
false
false
false
false
LISTEN-moe/android-app
app/src/main/kotlin/me/echeung/moemoekyun/adapter/SongDetailAdapter.kt
1
2202
package me.echeung.moemoekyun.adapter import android.app.Activity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.databinding.DataBindingUtil import me.echeung.moemoekyun.R import me.echeung.moemoekyun.client.auth.AuthUtil import me.echeung.moemoekyun.client.model.Song import me.echeung.moemoekyun.databinding.SongDetailsBinding import me.echeung.moemoekyun.util.SongActionsUtil import me.echeung.moemoekyun.util.ext.openUrl import org.koin.core.component.KoinComponent import org.koin.core.component.inject class SongDetailAdapter( private val activity: Activity, songs: List<Song>, ) : ArrayAdapter<Song>(activity, 0, songs), KoinComponent { private val authUtil: AuthUtil by inject() private val songActionsUtil: SongActionsUtil by inject() override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val inflater = LayoutInflater.from(context) val binding: SongDetailsBinding var view = convertView if (view == null) { binding = DataBindingUtil.inflate(inflater, R.layout.song_details, parent, false) view = binding.root view.tag = binding } else { binding = view.tag as SongDetailsBinding } val song = getItem(position) ?: return binding.root binding.song = song binding.isAuthenticated = authUtil.isAuthenticated binding.isFavorite = song.favorite binding.requestBtn.setOnClickListener { songActionsUtil.request(activity, song) } binding.favoriteBtn.setOnClickListener { songActionsUtil.toggleFavorite(activity, song) song.favorite = !song.favorite binding.isFavorite = song.favorite } binding.albumArt.setOnLongClickListener { val albumArtUrl = song.albumArtUrl ?: return@setOnLongClickListener false context.openUrl(albumArtUrl) true } binding.root.setOnLongClickListener { songActionsUtil.copyToClipboard(context, song) true } return binding.root } }
mit
3f60f9baaa087dcad0610fdbb1433d76
31.865672
93
0.702543
4.860927
false
false
false
false
ageery/kwicket
buildSrc/src/main/kotlin/org/kwicket/gradle/Versions.kt
1
761
package org.kwicket.gradle object Versions { const val kotlinVersion = "1.2.61" const val dokkaVersion = "0.9.16" const val bintrayVersion = "1.8.4" const val artifactoryVersion = "4.7.5" const val releasePluginVersion = "2.6.0" const val sonarqubePluginVersion = "2.6" const val wicketVersion = "8.0.0" const val wicketStuffVersion = wicketVersion const val wicketBootstrapVersion = "2.0.2" const val kotlinxHtmlVersion = "0.6.8" const val springVersion = "4.3.13.RELEASE" const val dependencyManagementVersion = "1.0.6.RELEASE" const val bootVersion = "2.0.4.RELEASE" const val servletApiVersion = "3.1.0" const val wicketWebjarsVersion = "2.0.6" const val kotlinCoroutinesVersion = "0.22.5" }
apache-2.0
3279a8f889010a8f02ada628fd845843
35.285714
59
0.693824
3.252137
false
false
false
false
bobrofon/easysshfs
app/src/main/java/ru/nsu/bobrofon/easysshfs/mountpointlist/MountpointFragment.kt
1
3567
package ru.nsu.bobrofon.easysshfs.mountpointlist import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.AbsListView import android.widget.AdapterView import android.widget.ListAdapter import ru.nsu.bobrofon.easysshfs.EasySSHFSFragment import ru.nsu.bobrofon.easysshfs.R import ru.nsu.bobrofon.easysshfs.mountpointlist.mountpoint.MountPointsArrayAdapter import ru.nsu.bobrofon.easysshfs.mountpointlist.mountpoint.MountStateChangeObserver /** * Activities containing this fragment MUST implement the [OnFragmentInteractionListener] * interface. */ class MountpointFragment : EasySSHFSFragment(), AdapterView.OnItemClickListener, MountStateChangeObserver { private var onFragmentInteractionListener: OnFragmentInteractionListener? = null private lateinit var listView: AbsListView private lateinit var listAdapter: ListAdapter private lateinit var mountPointsList: MountPointsList override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val context = context!! val shell = shell!! setHasOptionsMenu(true) val view = inflater.inflate(R.layout.fragment_mountpoint, container, false) mountPointsList = MountPointsList.instance(context) listAdapter = MountPointsArrayAdapter(context, mountPointsList.mountPoints, shell) listView = view.findViewById(android.R.id.list) listView.adapter = listAdapter listView.onItemClickListener = this mountPointsList.registerMountObserver(this) // mountPointsList.autoMount(); return view } override fun onDestroyView() { mountPointsList.unregisterMountObserver(this) super.onDestroyView() } override fun onAttach(context: Context) { super.onAttach(context) appActivity?.onSectionAttached(R.string.mount_point_list_title) onFragmentInteractionListener = appActivity } override fun onDetach() { onFragmentInteractionListener = null super.onDetach() } override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) { // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. onFragmentInteractionListener?.onFragmentInteraction(position) } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. */ interface OnFragmentInteractionListener { fun onFragmentInteraction(id: Int) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) if (!drawerStatus.isDrawerOpen) { inflater.inflate(R.menu.list, menu) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.action_new_mount_point) { onFragmentInteractionListener?.onFragmentInteraction(listAdapter.count) return true } return super.onOptionsItemSelected(item) } override fun onMountStateChanged() { listView.invalidateViews() } }
mit
2d1eeda370668c33e857ef1a6cc3b39d
31.724771
91
0.724418
4.859673
false
false
false
false
MehdiK/Humanizer.jvm
test/main/kotlin/org/humanizer/jvm/tests/ToQuantityTests.kt
1
7275
package org.humanizer.jvm.tests import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.givenData import org.humanizer.jvm.truncate import org.jetbrains.spek.api.shouldEqual import org.humanizer.jvm.toQuantity import org.humanizer.jvm.ShowQuantityAs public class ToQuantityTests() : Spek() { data class ParamClass(val value: String , val quantity: Int , val expected: String , val format: String = "" , val culture: String = "") { override fun toString(): String { return "\"$value\" " } } init { var data = listOf( ParamClass("case", 0, "0 cases"), ParamClass("case", 1, "1 case"), ParamClass("case", 5, "5 cases"), ParamClass("man", 0, "0 men"), ParamClass("man", 1, "1 man"), ParamClass("man", 2, "2 men"), ParamClass("men", 2, "2 men"), ParamClass("process", 2, "2 processes"), ParamClass("process", 1, "1 process"), ParamClass("processes", 2, "2 processes"), ParamClass("processes", 1, "1 process")) givenData(data) { on("calling toQuantity with quantity ${it.quantity}", { val actual = it.value.toQuantity(it.quantity) it("should be \"${it.expected}\"", { shouldEqual(it.expected, actual) }) }) } data = listOf( ParamClass("case", 0, "0 cases"), ParamClass("case", 1, "1 case"), ParamClass("case", 5, "5 cases"), ParamClass("man", 0, "0 men"), ParamClass("man", 1, "1 man"), ParamClass("man", 2, "2 men"), ParamClass("men", 2, "2 men"), ParamClass("process", 2, "2 processes"), ParamClass("process", 1, "1 process"), ParamClass("processes", 2, "2 processes"), ParamClass("processes", 1, "1 process")) givenData(data) { on("calling toQuantity on quantity ${it.quantity} with unit ${it.value}", { val actual = it.quantity.toQuantity(it.value) it("should be \"${it.expected}\"", { shouldEqual(it.expected, actual) }) }) } data = listOf( ParamClass("case", 0, "cases"), ParamClass("case", 1, "case"), ParamClass("case", 5, "cases"), ParamClass("man", 0, "men"), ParamClass("man", 1, "man"), ParamClass("man", 2, "men"), ParamClass("men", 2, "men"), ParamClass("process", 2, "processes"), ParamClass("process", 1, "process"), ParamClass("processes", 2, "processes"), ParamClass("processes", 1, "process")) givenData(data) { on("calling toQuantity with quantity ${it.quantity}", { val actual = it.value.toQuantity(it.quantity, showQuantityAs = ShowQuantityAs.None) it("should be \"${it.expected}\"", { shouldEqual(it.expected, actual) }) }) } data = listOf( ParamClass("case", 0, "0 cases"), ParamClass("case", 1, "1 case"), ParamClass("case", 5, "5 cases"), ParamClass("man", 0, "0 men"), ParamClass("man", 1, "1 man"), ParamClass("man", 2, "2 men"), ParamClass("men", 2, "2 men"), ParamClass("process", 2, "2 processes"), ParamClass("process", 1, "1 process"), ParamClass("processes", 2, "2 processes"), ParamClass("processes", 1, "1 process")) givenData(data) { on("calling toQuantity with quantity ${it.quantity}", { val actual = it.value.toQuantity(it.quantity, showQuantityAs = ShowQuantityAs.Numeric) it("should be \"${it.expected}\"", { shouldEqual(it.expected, actual) }) }) } data = listOf( ParamClass("case", 0, "zero cases"), ParamClass("case", 1, "one case"), ParamClass("case", 5, "five cases"), ParamClass("man", 0, "zero men"), ParamClass("man", 1, "one man"), ParamClass("man", 2, "two men"), ParamClass("men", 2, "two men"), ParamClass("process", 2, "two processes"), ParamClass("process", 1, "one process"), ParamClass("processes", 2, "two processes"), ParamClass("processes", 1200, "one thousand two hundred processes"), ParamClass("processes", 1, "one process")) givenData(data) { on("calling truncate with quantity ${it.quantity}", { val actual = it.value.toQuantity(it.quantity, showQuantityAs = ShowQuantityAs.Words) it("should be \"${it.expected}\"", { shouldEqual(it.expected, actual) }) }) } /* TODO : Make these tests pass and make Gandalf go away. data = listOf( ParamClass("case", 1, "1 case", ), ParamClass("case", 2, "2 cases", "%,d"), ParamClass("case", 123456, "123,456 cases","%,d"), ParamClass("case", 123456, "123,456.00 cases", "%,2d"), ParamClass("dollar", 0, "$0 dollars", "%f"), ParamClass("dollar", 1, "$1 dollar", "%f"), ParamClass("dollar", 2, "$2 dollars", "%f"), ParamClass("dollar", 2, "$2.00 dollars", "%,2f")) givenData(data) { on("calling truncate with length ${it.quantity}", { val actual = it.value.toQuantity(it.quantity, it.format) it("should be \"${it.expected}\"", { shouldEqual(it.expected, actual) }) }) } data = listOf( ParamClass("case", 0, "0 cases", "N0", "it-IT"), ParamClass("case", 1, "1 case", "N0", "it-IT"), ParamClass("case", 2, "2 cases", "N0", "it-IT"), ParamClass("case", 1234567, "1.234.567 cases", "N0", "it-IT"), ParamClass("case", 1234567, "1.234.567,00 cases", "N2", "it-IT"), ParamClass("euro", 0, "0 € euros", "C0", "es-ES"), ParamClass("euro", 1, "1 € euro", "C0", "es-ES"), ParamClass("euro", 2, "2 € euros", "C0", "es-ES"), ParamClass("euro", 2, "2,00 € euros", "C2", "es-ES")) givenData(data) { on("calling toQuantity with quantity ${it.quantity}", { val actual = it.value.toQuantity(it.quantity, it.format, it.culture) it("should be \"${it.expected}\"", { shouldEqual(it.expected, actual) }) }) } */ } }
apache-2.0
967de9bfeb97ecb43e1501238556fd2b
40.056497
102
0.464153
4.259672
false
false
false
false
colriot/anko
preview/idea-plugin/src/org/jetbrains/kotlin/android/dslpreview/DslPreviewToolWindowManager.kt
1
16857
/* * Copyright 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.kotlin.android.dslpreview import com.android.tools.idea.configurations.ConfigurationListener import com.intellij.compiler.impl.ProjectCompileScope import com.intellij.facet.FacetManager import com.intellij.icons.AllIcons import com.intellij.ide.highlighter.XmlFileType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.compiler.CompileContext import com.intellij.openapi.compiler.CompileStatusNotification import com.intellij.openapi.compiler.CompilerManager import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.module.Module import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.Computable import com.intellij.openapi.wm.WindowManager import com.intellij.psi.* import com.intellij.psi.impl.PsiTreeChangePreprocessor import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.psi.xml.XmlFile import com.intellij.ui.awt.RelativePoint import com.intellij.uiDesigner.core.GridConstraints import com.intellij.uiDesigner.core.GridLayoutManager import com.intellij.util.Alarm.ThreadToUse.SWING_THREAD import org.jetbrains.android.facet.AndroidFacet import org.jetbrains.android.sdk.AndroidTargetData import org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager import org.jetbrains.kotlin.idea.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.idea.internal.Location import org.jetbrains.kotlin.idea.util.InfinitePeriodicalTask import org.jetbrains.kotlin.idea.util.LongRunningReadTask import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFile import javax.swing.DefaultComboBoxModel import javax.swing.JPanel import com.intellij.openapi.Disposable class DslPreviewToolWindowManager( private val myProject: Project, fileEditorManager: FileEditorManager ) : AndroidLayoutPreviewToolWindowManager(myProject, fileEditorManager), DslWorker.Listener, Disposable { private var myDslWorker: DslWorker? = null private var myActivityListModel: DefaultComboBoxModel<Any>? = null private var myLastFile: PsiFile? = null private var myLastAndroidFacet: AndroidFacet? = null private val sourceFileModificationTracker by lazy { myProject.getExtensions(PsiTreeChangePreprocessor.EP_NAME) .first { it is SourceFileModificationTracker } as SourceFileModificationTracker } @Volatile private var lastSourceFileModification = 0L init { ApplicationManager.getApplication().invokeLater(object : Runnable { override fun run() { val task = object : Computable<LongRunningReadTask<Pair<KtClass, String>, String>> { override fun compute(): LongRunningReadTask<Pair<KtClass, String>, String> { return UpdateActivityNameTask() } } InfinitePeriodicalTask(1000, SWING_THREAD, this@DslPreviewToolWindowManager, task).start() } }) } override fun initToolWindow() { super.initToolWindow() myDslWorker = DslWorker(this) val panel = toolWindowForm.contentPanel.getComponent(1) if (panel is JPanel) { val firstToolbar = panel.getComponent(0) val secondToolbar = panel.getComponent(1) panel.remove(firstToolbar) panel.remove(secondToolbar) val manager = GridLayoutManager(3, 1) panel.layout = manager myActivityListModel = DefaultComboBoxModel() val comboBox = ComboBox(myActivityListModel) fun constraints(row: Int, column: Int, init: GridConstraints.() -> Unit): GridConstraints { return with(GridConstraints()) { setRow(row) setColumn(column) init() this } } panel.add(firstToolbar, constraints(0, 0) { fill = GridConstraints.FILL_BOTH }) panel.add(secondToolbar, constraints(1, 0) { fill = GridConstraints.FILL_VERTICAL anchor = GridConstraints.ANCHOR_EAST }) panel.add(comboBox, constraints(2, 0) { fill = GridConstraints.FILL_BOTH }) } resolveAvailableClasses() } override fun getCustomRefreshRenderAction(): AnAction? { return RefreshDslAction() } override fun getComponentName(): String { return "LayoutPreviewToolWindowManager" } override fun disposeComponent() { super.disposeComponent() myDslWorker?.finishWorkingProcess() } override fun isUseInteractiveSelector(): Boolean { return false } override fun getToolWindowId(): String { return "DSL Preview" } override fun isRenderAutomatically(): Boolean { return false } override fun isForceHideOnStart(): Boolean { return true } override fun onXmlReceived(cmd: RobowrapperContext, xml: String) { val filename = cmd.activityClassName + "_converted__.xml" val psiFile = PsiFileFactory.getInstance(myProject).createFileFromText(filename, XmlFileType.INSTANCE, xml) val wrappedPsiFile = LayoutPsiFile(psiFile as XmlFile) render(wrappedPsiFile, cmd.androidFacet, false) } override fun onXmlError(kind: DslWorker.ErrorKind, description: String, alive: Boolean) { showNotification("Dsl processing error ($kind): $description", MessageType.ERROR) } override fun render(): Boolean { val file = myLastFile val facet = myLastAndroidFacet if (file == null || facet == null) { return false } return render(file, facet, false) } private fun getOnCursorPreviewClassDescription(): PreviewClassDescription? { val editor = FileEditorManager.getInstance(myProject).selectedTextEditor ?: return null val psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.document) if (psiFile !is KtFile || editor !is EditorEx) { throw UnsupportedClassException() } val virtualFile = editor.virtualFile val selectionStart = editor.caretModel.primaryCaret.selectionStart val cacheService = KotlinCacheService.getInstance(myProject) val psiElement = psiFile.findElementAt(selectionStart) val KtClass = if (psiElement != null) resolveKtClass(psiElement, cacheService) else null val module = ProjectRootManager.getInstance(myProject) .fileIndex.getModuleForFile(virtualFile) ?: return null val androidFacet = module.resolveAndroidFacet() if (KtClass == null || androidFacet == null) { throw UnsupportedClassException() } return PreviewKtClassDescription(KtClass, androidFacet) } override fun render(psiFile: PsiFile?, facet: AndroidFacet?, forceFullRender: Boolean): Boolean { if (!forceFullRender) { val result = super.render(psiFile, facet, false) if (result) { myLastFile = psiFile myLastAndroidFacet = facet } else { myLastFile = null myLastAndroidFacet = null } return result } var ctx: RobowrapperContext? try { val description = myActivityListModel?.selectedItem as? PreviewClassDescription ?: getOnCursorPreviewClassDescription() ?: return false ctx = RobowrapperContext(description) } catch (e: AndroidFacetNotFoundException) { showNotification("Can't resolve Android facet.", MessageType.ERROR) return false } catch (e: CantCreateDependencyDirectoryException) { showNotification("Can't create Robolectric dependency folder.", MessageType.ERROR) return false } catch (e: UnsupportedClassException) { showNotification("This class is not supported.", MessageType.ERROR) return false } val actualSourceFileModification = sourceFileModificationTracker.modificationCount if (actualSourceFileModification != lastSourceFileModification) { val notification = object : CompileStatusNotification { override fun finished(aborted: Boolean, errors: Int, warnings: Int, compileContext: CompileContext) { if (!aborted && errors == 0) { lastSourceFileModification = actualSourceFileModification myDslWorker?.exec(ctx!!) } else if (errors > 0) { showNotification("Build completed with errors.", MessageType.ERROR) } } } if (ctx!!.androidFacet.isGradleProject) { CompilerManager.getInstance(myProject).make(ProjectCompileScope(myProject), notification) } else { val module = ctx!!.androidFacet.module CompilerManager.getInstance(myProject).make(module, notification) } } else { myDslWorker?.exec(ctx!!) } return true } override fun initListeners(project: Project) {} override fun update(event: PsiTreeChangeEvent) {} override fun dispose() {} override fun getToolWindow() = super.getToolWindow() override fun getToolWindowForm() = super.getToolWindowForm() private fun resolveAvailableClasses() { val cacheService = KotlinCacheService.getInstance(myProject) val activityClasses = getAncestors("android.app.Activity", cacheService) val fragmentClasses = getAncestors("android.app.Fragment", cacheService) val supportFragmentClasses = getAncestors("android.support.v4.app.Fragment", cacheService) if (myActivityListModel != null) { with(myActivityListModel!!) { selectedItem = null removeAllElements() val items = activityClasses + fragmentClasses + supportFragmentClasses items.sortedBy { it.toString() }.forEach { addElement(it) } } } } private fun getAncestors(baseClassName: String, cacheService: KotlinCacheService): Collection<PreviewClassDescription> { val baseClasses = JavaPsiFacade.getInstance(myProject).findClasses(baseClassName, GlobalSearchScope.allScope(myProject)) if (baseClasses.size == 0) return listOf() try { return ClassInheritorsSearch.search(baseClasses[0]) .findAll() .filter { resolveKtClass(it, cacheService) != null } .map { it to it.getModule()?.resolveAndroidFacet() } .filter { it.second != null } .map { PreviewPsiClassDescription(it.first, it.second!!) } } catch (e: IndexNotReadyException) { return listOf() } } override fun isApplicableEditor(textEditor: TextEditor) = true private fun PsiClass.getModule(): Module? { return ProjectRootManager.getInstance(myProject).fileIndex .getModuleForFile(containingFile.virtualFile) } private fun Module.resolveAndroidFacet(): AndroidFacet? { val facetManager = FacetManager.getInstance(this) for (facet in facetManager.allFacets) { if (facet is AndroidFacet) { return facet } } return null } private fun showNotification(text: String, messageType: MessageType) { val statusBar = WindowManager.getInstance().getStatusBar(myProject) ?: return JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(text, messageType, null) .setFadeoutTime(3000) .createBalloon() .show(RelativePoint.getCenterOf(statusBar.component), Balloon.Position.atRight) } private inner class RefreshDslAction : AnAction("Refresh", null, AllIcons.Actions.Refresh) { override fun actionPerformed(e: AnActionEvent) { val configuration = toolWindowForm.configuration if (configuration != null) { // Clear layoutlib bitmap cache (in case files have been modified externally) val target = configuration.target val module = configuration.module if (target != null && module != null) { AndroidTargetData.getTargetData(target, module)?.clearLayoutBitmapCache(module) } AndroidFacet.getInstance(configuration.module)?.refreshResources() configuration.updated(ConfigurationListener.MASK_RENDERING) } render(null, null, true) } } inner class UpdateActivityNameTask : LongRunningReadTask<Pair<KtClass, String>, String>() { override fun prepareRequestInfo(): Pair<KtClass, String>? { val toolWindow = toolWindow if (toolWindow == null || !toolWindow.isVisible) { return null } val editor = FileEditorManager.getInstance(myProject).selectedTextEditor val location = Location.fromEditor(editor, myProject) if (location.editor == null) { return null } val file = location.jetFile if (file == null || !ProjectRootsUtil.isInProjectSource(file)) { return null } val cacheService = KotlinCacheService.getInstance(myProject) val psiElement = file.findElementAt(location.startOffset) val resolvedClass = if (psiElement != null) resolveKtClass(psiElement, cacheService) else null if (resolvedClass == null || resolvedClass !is KtClass) { return null } return Pair(resolvedClass, getQualifiedName(resolvedClass) ?: "") } override fun cloneRequestInfo(requestInfo: Pair<KtClass, String>): Pair<KtClass, String> { val newRequestInfo = super.cloneRequestInfo(requestInfo) assert(requestInfo == newRequestInfo, "cloneRequestInfo should generate same location object") return newRequestInfo } override fun hideResultOnInvalidLocation() { } override fun processRequest(requestInfo: Pair<KtClass, String>): String? { return getQualifiedName(requestInfo.first) } override fun onResultReady(requestInfo: Pair<KtClass, String>, resultText: String?) { if (resultText == null) { return } fun setSelection(): Boolean { var found = false if (myActivityListModel != null) with (myActivityListModel!!) { for (i in 0 .. (size - 1)) { val item = getElementAt(i) if (item != null && resultText == (item as PreviewClassDescription).qualifiedName) { selectedItem = item found = true break } } } return found } // If class with such name was not found (prob. after refactoring) if (!setSelection()) { resolveAvailableClasses() setSelection() } } } }
apache-2.0
6e72a85f2b91be42caeef2ffe360d8e1
37.486301
128
0.646556
5.310964
false
false
false
false
satispay/in-store-api-java-sdk
protocore/src/main/java/com/satispay/protocore/utility/LatencyManager.kt
1
1313
package com.satispay.protocore.utility /* * Sliding time window with 10 values * 15 seconds as the maximum timeout * When the average of the samples exceeds 12.75 (calculated as 15 * 0.85) then the connection is slow */ // Login + First shops page // network 56k -> 3612ms,7264ms,10704ms,20353ms,22792ms,15884ms,13894ms,17033ms,19374ms,22854ms,15490ms,16890ms,17787ms // network 128k -> 765ms,1196ms,1939ms,1822ms,1285ms,950ms,1022ms,1149ms,1260ms,905ms,743ms,977ms,871ms, // network -> 512kb -> 200ms,396ms,304ms,414ms,322ms,307ms,474ms,892ms,1159ms,820ms,639ms,926ms,813ms class LatencyManager(private val window: CircularQueue<Long> = CircularQueue(10)) { private val maxAverageValue = MAX_LATENCY * 0.85 // 1083.75ms fun addEvent(event: Long):Int { synchronized(this){ window.add(event) return window.size } } /*** Return a pair with isSlowConnection and teh value of teh average (on last 10 queue) */ fun isSlowConnectionWithAverage(): Pair<Double,Boolean> { synchronized(this){ val average=window.average() return Pair(average,average > maxAverageValue) } } companion object{ private const val MAX_LATENCY = 1275 // iOS: 12750 // magic number: 15 * 0.85 = 12,7 } }
apache-2.0
58e4ab310d1db3530d6abc41327c3c21
33.578947
119
0.67936
3.290727
false
false
false
false
arturbosch/detekt
detekt-rules-complexity/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/LargeClassSpec.kt
1
1385
package io.gitlab.arturbosch.detekt.rules.complexity import io.github.detekt.test.utils.resourceAsPath import io.gitlab.arturbosch.detekt.api.SourceLocation import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.assertThat import io.gitlab.arturbosch.detekt.test.compileAndLint import io.gitlab.arturbosch.detekt.test.lint import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe private fun subject(threshold: Int) = LargeClass(TestConfig(mapOf("threshold" to threshold))) class LargeClassSpec : Spek({ describe("nested classes are also considered") { it("should detect only the nested large class which exceeds threshold 70") { val findings = subject(threshold = 70).lint(resourceAsPath("NestedClasses.kt")) assertThat(findings).hasSize(1) assertThat(findings).hasSourceLocations(SourceLocation(12, 15)) } } describe("files without classes should not be considered") { it("should not report anything in files without classes") { val code = """ val i = 0 fun f() { println() println() } """ val rule = subject(threshold = 2) assertThat(rule.compileAndLint(code)).isEmpty() } } })
apache-2.0
76388e6e2b8573f8ba7b28f627a90f1a
33.625
93
0.662816
4.632107
false
true
false
false
LachlanMcKee/gsonpath
compiler/standard/src/main/java/gsonpath/adapter/enums/EnumAdapterPropertiesFactory.kt
1
2896
package gsonpath.adapter.enums import com.google.gson.FieldNamingPolicy import com.google.gson.annotations.SerializedName import gsonpath.ProcessingException import gsonpath.annotation.EnumGsonAdapter import gsonpath.util.AnnotationFetcher import gsonpath.util.FieldElementContent import gsonpath.util.TypeHandler import javax.lang.model.element.ElementKind import javax.lang.model.element.TypeElement class EnumAdapterPropertiesFactory( private val typeHandler: TypeHandler, private val annotationFetcher: AnnotationFetcher, private val enumFieldLabelMapper: EnumFieldLabelMapper ) { fun create( ignoreDefaultValue: Boolean, enumElement: TypeElement, fieldNamingPolicy: FieldNamingPolicy): EnumAdapterProperties { val enumFields = typeHandler.getFields(enumElement) { it.kind == ElementKind.ENUM_CONSTANT } return EnumAdapterProperties( enumTypeName = typeHandler.getClassName(enumElement), fields = enumFields.map { createEnumField(enumElement, it, fieldNamingPolicy) }, defaultValue = getDefaultValue(enumElement, enumFields, fieldNamingPolicy, ignoreDefaultValue) ) } private fun createEnumField( enumElement: TypeElement, field: FieldElementContent, fieldNamingPolicy: FieldNamingPolicy ): EnumAdapterProperties.EnumField { val serializedName = annotationFetcher.getAnnotation(enumElement, field.element, SerializedName::class.java) val enumConstantName = field.element.simpleName.toString() return EnumAdapterProperties.EnumField( enumValueTypeName = typeHandler.guessClassName("$enumElement.$enumConstantName"), label = serializedName?.value ?: enumFieldLabelMapper.map(enumConstantName, fieldNamingPolicy)) } private fun getDefaultValue( enumElement: TypeElement, enumFields: List<FieldElementContent>, fieldNamingPolicy: FieldNamingPolicy, ignoreDefaultValue: Boolean ): EnumAdapterProperties.EnumField? { return enumFields .filter { annotationFetcher .getAnnotation(enumElement, it.element, EnumGsonAdapter.DefaultValue::class.java) != null } .apply { if (size > 1) throw ProcessingException("Only one DefaultValue can be defined", enumElement) if (size == 0 && !ignoreDefaultValue) { throw ProcessingException("DefaultValue mut be defined. If you do not want a default " + "value set ignoreDefaultValue=true", enumElement) } } .firstOrNull() ?.let { createEnumField(enumElement, it, fieldNamingPolicy) } } }
mit
dfdee9f58e376bf0fde770763aa6a63b
43.569231
117
0.668163
5.526718
false
false
false
false
jereksel/LibreSubstratum
sublib/themereaderassetmanager/src/main/java/com/jereksel/themereaderassetmanager/Reader.kt
1
5455
package com.jereksel.themereaderassetmanager import android.content.res.AssetManager import android.content.res.AssetManager.ACCESS_BUFFER import com.jereksel.libresubstratumlib.* import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import java.io.InputStream import android.util.Xml import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException import java.io.IOException object Reader { fun read(am: AssetManager, transformer: (InputStream) -> (InputStream) = { it }): ThemePack { val apps = am.list("overlays") val list = apps.map { readTheme(am, it, transformer) } val type3Data: Type3Data? if (apps.isEmpty()) { type3Data = null } else { val app = apps[0] val type3extensions = am.list("overlays/$app") .filter { it.startsWith("type3") } .map { if (it == "type3" || it == "type3.enc") { Type3Extension(am.read("overlays/$app/$it", transformer), true) } else { Type3Extension(it.removePrefix("type3_"), false) } } .sortedWith(compareBy({ !it.default }, { it.name })) if (type3extensions.isEmpty()) { type3Data = null } else { type3Data = Type3Data(type3extensions) } } return ThemePack(list.sortedBy { it.application }, type3Data) } fun readTheme(am: AssetManager, id: String, transformer: (InputStream) -> (InputStream)): Theme { val dir = "overlays/$id" val files = am.list(dir) val type1s = files .filter { it.startsWith("type1") } .groupBy { it[5] } .map { val type = it.key val extensions = it.value .map { if (it.length == 6 || (it.length == 10 && it.endsWith(".enc"))) { Type1Extension(am.read("$dir/$it", transformer), true) } else { val content = am.read("$dir/$it", transformer) val color = getFirstColor(content) ?: "" val name = it.substring(7).removeSuffix(".xml").removeSuffix(".xml.enc") Type1Extension(name, false, color) } } //We want true to be first .sortedWith(compareBy({ !it.default }, { it.name })) Type1Data(extensions, type.toString()) } .sortedBy { it.suffix } val type2 = files .filter { it.startsWith("type2") } .map { if (it == "type2" || it == "type2.enc") { Type2Extension(am.read("$dir/$it", transformer), true) } else { Type2Extension(it.removePrefix("type2_"), false) } } // .ifNotEmptyAdd(Type2Extension("Type2 extension", true)) val type22: List<Type2Extension> if (type2.find { it.default } == null && !type2.isEmpty()) { type22 = type2 + Type2Extension("Type2 extension", true) } else { type22 = type2 } val finalType2 = type22 .sortedWith(compareBy({ !it.default }, { it.name })) val type2Data: Type2Data? type2Data = if (finalType2.isEmpty()) { null } else { Type2Data(finalType2) } return Theme(id, type1s, type2Data) } //Most of this code is from https://developer.android.com/training/basics/network-ops/xml.html fun getFirstColor(content: String): String? { if (content.trim().isEmpty()) { return null } try { val parser = Xml.newPullParser() parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false) parser.setInput(content.reader()) parser.nextTag() parser.require(XmlPullParser.START_TAG, null, "resources") while (parser.next() != XmlPullParser.END_TAG) { if (parser.eventType != XmlPullParser.START_TAG) { continue; } parser.require(XmlPullParser.START_TAG, null, "color"); val color = readText(parser) if (color.startsWith("#")) { return color.trim() } parser.require(XmlPullParser.END_TAG, null, "color"); } } catch (e: XmlPullParserException) { e.printStackTrace() return null } return null } private fun readText(parser: XmlPullParser): String { var result = "" if (parser.next() == XmlPullParser.TEXT) { result = parser.text parser.nextTag() } return result } private fun AssetManager.read(file: String, transformer: (InputStream) -> (InputStream)): String = transformer(this.open(file, ACCESS_BUFFER)).bufferedReader().use { it.readText() } }
mit
f305c54f87f76712d980bdeaaef83718
32.881988
108
0.496609
4.702586
false
false
false
false
chibatching/Kotpref
enum-support/src/test/java/com/chibatching/kotpref/enumpref/EnumSupportTest.kt
1
3024
package com.chibatching.kotpref.enumpref import android.content.Context import android.content.SharedPreferences import androidx.test.core.app.ApplicationProvider import com.chibatching.kotpref.KotprefModel import com.google.common.truth.Truth.assertThat import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.ParameterizedRobolectricTestRunner import org.robolectric.annotation.Config import java.util.Arrays @Config(manifest = Config.NONE) @RunWith(ParameterizedRobolectricTestRunner::class) internal class EnumSupportTest(private val commitAllProperties: Boolean) { companion object { @JvmStatic @ParameterizedRobolectricTestRunner.Parameters(name = "commitAllProperties = {0}") fun data(): Collection<Array<out Any>> { return Arrays.asList(arrayOf(false), arrayOf(true)) } } class Example(private val commitAllProperties: Boolean) : KotprefModel(ApplicationProvider.getApplicationContext<Context>()) { override val commitAllPropertiesByDefault: Boolean get() = commitAllProperties var testEnumValue by enumValuePref(ExampleEnum.FIRST) var testEnumNullableValue: ExampleEnum? by nullableEnumValuePref() var testEnumOrdinal by enumOrdinalPref(ExampleEnum.FIRST) } private lateinit var example: Example private lateinit var pref: SharedPreferences @Before fun setUp() { example = Example(commitAllProperties) pref = example.preferences pref.edit().clear().commit() } @After fun tearDown() { example.clear() } @Test fun enumValuePrefDefaultIsDefined() { assertThat(example.testEnumValue).isEqualTo(ExampleEnum.FIRST) } @Test fun setEnumValuePrefCausePreferenceUpdate() { example.testEnumValue = ExampleEnum.SECOND assertThat(example.testEnumValue).isEqualTo(ExampleEnum.SECOND) assertThat(example.testEnumValue.name).isEqualTo(pref.getString("testEnumValue", "")) } @Test fun enumNullableValuePrefDefaultIsNull() { assertThat(example.testEnumNullableValue).isNull() } @Test fun setEnumNullableValuePrefCausePreferenceUpdate() { example.testEnumNullableValue = ExampleEnum.SECOND assertThat(example.testEnumNullableValue).isEqualTo(ExampleEnum.SECOND) assertThat(example.testEnumNullableValue!!.name).isEqualTo( pref.getString( "testEnumNullableValue", "" ) ) } @Test fun enumOrdinalPrefDefaultIsDefined() { assertThat(example.testEnumOrdinal).isEqualTo(ExampleEnum.FIRST) } @Test fun setEnumOrdinalPrefCausePreferenceUpdate() { example.testEnumOrdinal = ExampleEnum.SECOND assertThat(example.testEnumOrdinal).isEqualTo(ExampleEnum.SECOND) assertThat(example.testEnumOrdinal.ordinal).isEqualTo(pref.getInt("testEnumOrdinal", 0)) } }
apache-2.0
964c07166457f2639843a6bc392b17ed
31.170213
96
0.717923
4.8
false
true
false
false
josmas/mqttps
app/src/main/java/ie/mu/jos/mqttps/Connection.kt
1
3515
package ie.mu.jos.mqttps import android.content.Context import android.util.Log import android.widget.Toast import org.eclipse.paho.android.service.MqttAndroidClient import org.eclipse.paho.client.mqttv3.IMqttActionListener import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken import org.eclipse.paho.client.mqttv3.IMqttToken import org.eclipse.paho.client.mqttv3.MqttCallback import org.eclipse.paho.client.mqttv3.MqttClient import org.eclipse.paho.client.mqttv3.MqttConnectOptions import org.eclipse.paho.client.mqttv3.MqttException import org.eclipse.paho.client.mqttv3.MqttMessage /** * A class to create and handle MQTT connections */ class Connection(private val context: Context) { private var client: MqttAndroidClient? = null internal fun connectMqtt() { try { val options = MqttConnectOptions() options.mqttVersion = MqttConnectOptions.MQTT_VERSION_3_1 val clientId = MqttClient.generateClientId() Log.i(TAG, clientId) //TODO (jos) MQTT broker is hardcoded. client = MqttAndroidClient(this.context, "tcp://test.mosquitto.org:1883", clientId) if (!client!!.isConnected) { client!!.setCallback(object : MqttCallback { override fun connectionLost(cause: Throwable) { logFailure("Lost Connection", exception = cause) //TODO (jos) monitor this behaviour - should I connect again? } @Throws(Exception::class) override fun messageArrived(topic: String, message: MqttMessage) { println(topic + ": " + String(message.payload, "UTF-8")) } override fun deliveryComplete(token: IMqttDeliveryToken) { } }) client!!.connect(options, this, object : IMqttActionListener { override fun onSuccess(asyncActionToken: IMqttToken) { subscribe("jos_test", 1) } override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) { logFailure("connecting", asyncActionToken, exception) } }) } } catch (e: MqttException) { e.printStackTrace() } } private fun logFailure(action: String, asyncActionToken: IMqttToken? = null, exception: Throwable) { Toast.makeText(this.context, "Problem: $action to $asyncActionToken", Toast.LENGTH_LONG).show() Log.e(TAG, "Issues $action to $asyncActionToken") Toast.makeText(this.context, "Problem: " + action, Toast.LENGTH_LONG).show() Log.e(TAG, "Issues " + action + " to " + exception.message) } internal fun subscribe(topic: String, qosLevel: Int) { try { client!!.subscribe(topic, qosLevel, null, object : IMqttActionListener { override fun onSuccess(asyncActionToken: IMqttToken) { Log.i(TAG, "ALL IS GOOD subscribing to " + asyncActionToken) } override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) { logFailure("subscribing", asyncActionToken, exception) } }) } catch (e: MqttException) { e.printStackTrace() } } companion object { val TAG = "Connection" } }
mit
cb51eb6fc7387a99f7e0079df085ae41
35.614583
104
0.601991
4.769335
false
false
false
false
jraska/github-client
plugins/src/main/java/com/jraska/lint/LintXmlParser.kt
1
2252
package com.jraska.lint import com.jraska.module.ModuleMetadata import groovy.util.Node import groovy.util.NodeList import groovy.xml.XmlParser class LintXmlParser( private val moduleMetadata: ModuleMetadata, ) { fun parse(lintXml: String): List<LintIssue> { val testSuiteNode = XmlParser().parseText(lintXml) return (testSuiteNode.get("issue") as NodeList) .map { it as Node } .map { parseIssue(it) } } private fun parseIssue(node: Node): LintIssue { return LintIssue( moduleMetadata, id = node.attributeString("id"), severity = node.severity(), category = node.attributeString("category"), summary = node.attributeString("summary"), priority = node.attributeInt("priority"), message = node.attributeString("message").trimToMaxLength(), errorLine = node.attribute("errorLine1")?.toString()?.trimToMaxLength(), location = location(node) ) } private fun String.trimToMaxLength(): String { val fullMessage = this if (fullMessage.length > MAX_TEXT_LENGTH) { return "${fullMessage.substring(0, MAX_TEXT_LENGTH)}..." } else { return fullMessage } } private fun location(issueNode: Node): String? { val locationNode = (issueNode.get("location") as NodeList).firstOrNull() as Node? ?: return null val absolutePath = locationNode.attributeString("file") val pathIndex = absolutePath.indexOf(moduleMetadata.moduleName) return if (pathIndex == -1) { absolutePath } else { absolutePath.substring(pathIndex) } } private fun Node.attributeString(name: String): String { return attribute(name).toString() } private fun Node.severity(): Severity { val severityString = attributeString("severity") return when (severityString) { "Error" -> Severity.Error "Warning" -> Severity.Warning "Information" -> Severity.Info "Ignore" -> Severity.Ignore "Fatal" -> Severity.Fatal else -> throw IllegalArgumentException("Unknown severity: $severityString") } } private fun Node.attributeInt(name: String): Int { return attribute(name)?.toString()?.toInt() ?: 0 } companion object { private const val MAX_TEXT_LENGTH = 200 } }
apache-2.0
b118132d48e0c7676ee7b016a02b8fb3
27.506329
100
0.674067
4.209346
false
true
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/utils/ui.kt
1
1582
package org.rust.utils import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.TextComponentAccessor import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.ui.DocumentAdapter import com.intellij.util.Alarm import javax.swing.event.DocumentEvent class UiDebouncer(parentDisaposable: Disposable, private val delayMillis: Int = 200) { private val alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, parentDisaposable) fun <T> run(onPooledThread: () -> T, onUiThread: (T) -> Unit) { alarm.cancelAllRequests() val modalityState = ModalityState.current() alarm.addRequest({ val r = onPooledThread() ApplicationManager.getApplication().invokeLater({ onUiThread(r) }, modalityState) }, delayMillis) } } fun pathToDirectoryTextField( disposable: Disposable, title: String, onTextChanged: () -> Unit = {} ): TextFieldWithBrowseButton { val component = TextFieldWithBrowseButton(null, disposable) component.addBrowseFolderListener(title, null, null, FileChooserDescriptorFactory.createSingleFolderDescriptor(), TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT ) component.childComponent.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent?) { onTextChanged() } }) return component }
mit
fee6f36972f58fb4596fc07c1bbdf850
34.954545
93
0.743363
4.990536
false
false
false
false
RedstonerServer/Parcels
src/main/kotlin/io/dico/parcels2/util/ext/Misc.kt
1
2605
package io.dico.parcels2.util.ext import io.dico.dicore.Formatting import io.dico.parcels2.logger import java.io.File fun File.tryCreate(): Boolean { if (exists()) { return !isDirectory } val parent = parentFile if (parent == null || !(parent.exists() || parent.mkdirs()) || !createNewFile()) { logger.warn("Failed to create file $canonicalPath") return false } return true } inline fun Boolean.alsoIfTrue(block: () -> Unit): Boolean = also { if (it) block() } inline fun Boolean.alsoIfFalse(block: () -> Unit): Boolean = also { if (!it) block() } inline fun <R> Any.synchronized(block: () -> R): R = synchronized(this, block) //inline fun <T> T?.isNullOr(condition: T.() -> Boolean): Boolean = this == null || condition() //inline fun <T> T?.isPresentAnd(condition: T.() -> Boolean): Boolean = this != null && condition() inline fun <T> T?.ifNullRun(block: () -> Unit): T? { if (this == null) block() return this } inline fun <T, U> MutableMap<T, U>.editLoop(block: EditLoopScope<T, U>.(T, U) -> Unit) { return EditLoopScope(this).doEditLoop(block) } inline fun <T, U> MutableMap<T, U>.editLoop(block: EditLoopScope<T, U>.() -> Unit) { return EditLoopScope(this).doEditLoop(block) } class EditLoopScope<T, U>(val _map: MutableMap<T, U>) { private var iterator: MutableIterator<MutableMap.MutableEntry<T, U>>? = null lateinit var _entry: MutableMap.MutableEntry<T, U> inline val key get() = _entry.key inline var value get() = _entry.value set(target) = run { _entry.setValue(target) } inline fun doEditLoop(block: EditLoopScope<T, U>.() -> Unit) { val it = _initIterator() while (it.hasNext()) { _entry = it.next() block() } } inline fun doEditLoop(block: EditLoopScope<T, U>.(T, U) -> Unit) { val it = _initIterator() while (it.hasNext()) { val entry = it.next().also { _entry = it } block(entry.key, entry.value) } } fun remove() { iterator!!.remove() } fun _initIterator(): MutableIterator<MutableMap.MutableEntry<T, U>> { iterator?.let { throw IllegalStateException() } return _map.entries.iterator().also { iterator = it } } } operator fun Formatting.plus(other: Formatting) = toString() + other operator fun Formatting.plus(other: String) = toString() + other inline fun <T> Pair<T, T>.forEach(block: (T) -> Unit) { block(first) block(second) }
gpl-2.0
efb4dde5c5e9b6792c055f2c1e5119e7
30.160494
99
0.594626
3.578297
false
false
false
false
antoniolg/Bandhook-Kotlin
app/src/main/java/com/antonioleiva/bandhookkotlin/domain/interactor/GetTopAlbumsInteractor.kt
1
1407
/* * Copyright (C) 2016 Alexey Verein * * 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.antonioleiva.bandhookkotlin.domain.interactor import com.antonioleiva.bandhookkotlin.domain.interactor.base.Event import com.antonioleiva.bandhookkotlin.domain.interactor.base.Interactor import com.antonioleiva.bandhookkotlin.domain.interactor.event.TopAlbumsEvent import com.antonioleiva.bandhookkotlin.domain.repository.AlbumRepository class GetTopAlbumsInteractor(val albumRepository: AlbumRepository) : Interactor { var artistId: String? = null var artistName: String? = null override fun invoke(): Event { if (artistId == null && artistName == null) { throw IllegalStateException("Either mbid or name should be specified") } val albums = albumRepository.getTopAlbums(artistId, artistName) return TopAlbumsEvent(albums) } }
apache-2.0
54b29fc350b11916847d48c4fd888a13
38.111111
82
0.751955
4.495208
false
false
false
false
samtstern/quickstart-android
mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/cloudtextrecognition/CloudDocumentTextRecognitionProcessor.kt
1
2318
package com.google.firebase.samples.apps.mlkit.kotlin.cloudtextrecognition import android.graphics.Bitmap import android.util.Log import com.google.android.gms.tasks.Task import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.document.FirebaseVisionDocumentText import com.google.firebase.ml.vision.document.FirebaseVisionDocumentTextRecognizer import com.google.firebase.samples.apps.mlkit.common.FrameMetadata import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay import com.google.firebase.samples.apps.mlkit.kotlin.VisionProcessorBase /** Processor for the cloud document text detector demo. */ class CloudDocumentTextRecognitionProcessor : VisionProcessorBase<FirebaseVisionDocumentText>() { private val detector: FirebaseVisionDocumentTextRecognizer = FirebaseVision.getInstance().cloudDocumentTextRecognizer override fun detectInImage(image: FirebaseVisionImage): Task<FirebaseVisionDocumentText> { return detector.processImage(image) } override fun onSuccess( originalCameraImage: Bitmap?, results: FirebaseVisionDocumentText, frameMetadata: FrameMetadata, graphicOverlay: GraphicOverlay ) { graphicOverlay.clear() Log.d(TAG, "detected text is: ${results.text}") val blocks = results.blocks for (i in blocks.indices) { val paragraphs = blocks[i].paragraphs for (j in paragraphs.indices) { val words = paragraphs[j].words for (l in words.indices) { val symbols = words[l].symbols for (m in symbols.indices) { val cloudDocumentTextGraphic = CloudDocumentTextGraphic( graphicOverlay, symbols[m] ) graphicOverlay.add(cloudDocumentTextGraphic) graphicOverlay.postInvalidate() } } } } } override fun onFailure(e: Exception) { Log.w(TAG, "Cloud Document Text detection failed.$e") } companion object { private const val TAG = "CloudDocTextRecProc" } }
apache-2.0
ccd365f5c631c8897772a90566a9e3b5
37.633333
97
0.664797
5.116998
false
false
false
false
devmpv/chan-reactor
src/main/kotlin/com/devmpv/model/Board.kt
1
368
package com.devmpv.model import javax.persistence.* /** * Entity containing Information about board. * * @author devmpv */ @Entity class Board( @Id val id: String = "", var title: String = "" ) { @OneToMany(cascade = arrayOf(CascadeType.ALL), fetch = FetchType.LAZY, mappedBy = "board") var threads: MutableSet<Thread>? = null }
mit
21175196dcc41608b80d9353c6c51d4d
18.368421
94
0.633152
3.717172
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/glide/AuthenticatedUriLoader.kt
1
2980
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util.glide import android.accounts.AccountManager import android.content.Context import android.net.Uri import com.bumptech.glide.integration.okhttp3.OkHttpStreamFetcher import com.bumptech.glide.load.data.DataFetcher import com.bumptech.glide.load.model.* import okhttp3.OkHttpClient import de.vanita5.twittnuker.extension.model.authorizationHeader import de.vanita5.twittnuker.extension.model.getCredentials import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.account.cred.Credentials import de.vanita5.twittnuker.model.media.AuthenticatedUri import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.util.media.TwidereMediaDownloader import java.io.InputStream class AuthenticatedUriLoader( val context: Context, val client: OkHttpClient ) : ModelLoader<AuthenticatedUri, InputStream> { override fun getResourceFetcher(model: AuthenticatedUri, width: Int, height: Int): DataFetcher<InputStream> { val headersBuilder = LazyHeaders.Builder() val credentials = model.accountKey?.credentials if (credentials != null && TwidereMediaDownloader.isAuthRequired(credentials, model.uri)) { headersBuilder.addHeader("Authorization", AuthorizationHeaderFactory(model.uri, credentials)) } val glideUrl = GlideUrl(model.uri.toString(), headersBuilder.build()) return OkHttpStreamFetcher(client, glideUrl) } val UserKey.credentials: Credentials? get() { val am = AccountManager.get(context) return AccountUtils.findByAccountKey(am, this)?.getCredentials(am) } internal class AuthorizationHeaderFactory(val uri: Uri, val credentials: Credentials) : LazyHeaderFactory { override fun buildHeader() = credentials.authorizationHeader(uri) } class Factory(val client: OkHttpClient) : ModelLoaderFactory<AuthenticatedUri, InputStream> { override fun build(context: Context, factories: GenericLoaderFactory) = AuthenticatedUriLoader(context, client) override fun teardown() {} } }
gpl-3.0
28f3b0278ecf922a45af67c6cb53941f
40.985915
119
0.761745
4.408284
false
false
false
false
syrop/Victor-Events
events/src/main/kotlin/pl/org/seva/events/event/EventListFragment.kt
1
3569
/* * Copyright (C) 2017 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.events.event import android.annotation.SuppressLint import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.fr_event_list.* import pl.org.seva.events.R import pl.org.seva.events.comm.Comms import pl.org.seva.events.login.Login import pl.org.seva.events.main.extension.* import pl.org.seva.events.main.init.instance class EventListFragment : Fragment(R.layout.fr_event_list) { private val comms by instance<Comms>() private val events by instance<Events>() private val login by instance<Login>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } @SuppressLint("RestrictedApi") override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) add_event_fab { nav(R.id.action_eventsFragment_to_createEventFragment) } events_view.setHasFixedSize(true) events_view.layoutManager = LinearLayoutManager(context) events_view.verticalDivider() events_view.adapter = EventAdapter { position -> eventViewModel.value.withPosition(position) nav(R.id.action_eventsFragment_to_eventDetailsFragment) } (comms.updatedLiveData() + this) { if (comms.isAdminOfAny) add_event_fab.show() else add_event_fab.hide() } (events.updatedLiveData() + this) { if (events.isEmpty) { prompt.visibility = View.VISIBLE events_view.visibility = View.GONE } else { prompt.visibility = View.GONE events_view.visibility = View.VISIBLE checkNotNull(events_view.adapter).notifyDataSetChanged() } } } override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.event_list, menu) menu.findItem(R.id.action_login).isVisible = !login.isLoggedIn menu.findItem(R.id.action_log_out).isVisible = login.isLoggedIn } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_login -> nav(R.id.action_eventsFragment_to_loginConfirmationFragment) R.id.action_log_out -> nav(R.id.action_eventsFragment_to_logOutConfirmationFragment) R.id.action_comms -> nav(R.id.action_eventsFragment_to_commListFragment) R.id.action_system_messages -> nav(R.id.action_eventsFragment_to_systemMessagesFragment) R.id.action_about -> nav(R.id.action_eventsFragment_to_aboutFragment) else -> super.onOptionsItemSelected(item) } }
gpl-3.0
2cf2d646d16e95bc4e9ff932a8a3047e
39.101124
98
0.702998
4.116494
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowDataTypeToInt.kt
1
5028
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute import org.nd4j.ir.OpNamespace import org.nd4j.samediff.frameworkimport.argDescriptorType import org.nd4j.samediff.frameworkimport.findOp import org.nd4j.samediff.frameworkimport.ir.IRAttribute import org.nd4j.samediff.frameworkimport.isNd4jTensorName import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder import org.nd4j.samediff.frameworkimport.process.MappingProcess import org.nd4j.samediff.frameworkimport.rule.MappingRule import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType import org.nd4j.samediff.frameworkimport.rule.attribute.DataTypeToInt import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor import org.tensorflow.framework.* @MappingRule("tensorflow","datatypetoint","attribute") class TensorflowDataTypeToInt(mappingNamesToPerform: Map<String, String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>) : DataTypeToInt<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>(mappingNamesToPerform, transformerArgs) { override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> { return TensorflowIRAttr(inputAttributeValue = attributeValueType, inputAttributeDef = attrDef) } override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> { TODO("Not yet implemented") } override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowTensorName(name, opDef) } override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isNd4jTensorName(name,nd4jOpDescriptor) } override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowAttributeName(name, opDef) } override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isOutputFrameworkAttributeName(name,nd4jOpDescriptor) } override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return argDescriptorType(name,nd4jOpDescriptor) } override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef) } }
apache-2.0
a9b4f81fb919b23897391e5925ad9d83
61.8625
221
0.770286
4.988095
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/project/RsToolchainPathChoosingComboBox.kt
2
3761
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.ComboBoxWithWidePopup import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.ui.AnimatedIcon import com.intellij.ui.ComboboxSpeedSearch import com.intellij.ui.components.fields.ExtendableTextComponent import com.intellij.ui.components.fields.ExtendableTextField import org.rust.openapiext.addTextChangeListener import org.rust.openapiext.pathAsPath import org.rust.stdext.toPathOrNull import java.nio.file.Path import javax.swing.plaf.basic.BasicComboBoxEditor /** * A combobox with browse button for choosing a path to a toolchain, also capable of showing progress indicator. * To toggle progress indicator visibility use [setBusy] method. */ class RsToolchainPathChoosingComboBox(onTextChanged: () -> Unit = {}) : ComponentWithBrowseButton<ComboBoxWithWidePopup<Path>>(ComboBoxWithWidePopup(), null) { private val editor: BasicComboBoxEditor = object : BasicComboBoxEditor() { override fun createEditorComponent(): ExtendableTextField = ExtendableTextField() } private val pathTextField: ExtendableTextField get() = childComponent.editor.editorComponent as ExtendableTextField private val busyIconExtension: ExtendableTextComponent.Extension = ExtendableTextComponent.Extension { AnimatedIcon.Default.INSTANCE } var selectedPath: Path? get() = pathTextField.text?.toPathOrNull() set(value) { pathTextField.text = value?.toString().orEmpty() } init { ComboboxSpeedSearch(childComponent) childComponent.editor = editor childComponent.isEditable = true addActionListener { // Select directory with Cargo binary val descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() FileChooser.chooseFile(descriptor, null, null) { file -> childComponent.selectedItem = file.pathAsPath } } pathTextField.addTextChangeListener { onTextChanged() } } private fun setBusy(busy: Boolean) { if (busy) { pathTextField.addExtension(busyIconExtension) } else { pathTextField.removeExtension(busyIconExtension) } repaint() } /** * Obtains a list of toolchains on a pool using [toolchainObtainer], then fills the combobox and calls [callback] on the EDT. */ @Suppress("UnstableApiUsage") fun addToolchainsAsync(toolchainObtainer: () -> List<Path>, callback: () -> Unit) { setBusy(true) ApplicationManager.getApplication().executeOnPooledThread { var toolchains = emptyList<Path>() try { toolchains = toolchainObtainer() } finally { val executor = AppUIExecutor.onUiThread(ModalityState.any()).expireWith(this) executor.execute { setBusy(false) val oldSelectedPath = selectedPath childComponent.removeAllItems() toolchains.forEach(childComponent::addItem) selectedPath = oldSelectedPath callback() } } } } fun addToolchainsAsync(toolchainObtainer: () -> List<Path>) { addToolchainsAsync(toolchainObtainer) {} } }
mit
48d269504889558356a8a0de6a2719cd
37.377551
159
0.691837
5.312147
false
false
false
false
jk1/youtrack-idea-plugin
src/test/kotlin/com/github/jk1/ytplugin/setup/SetupVariationsTest.kt
1
2847
package com.github.jk1.ytplugin.setup import com.github.jk1.ytplugin.* import com.github.jk1.ytplugin.tasks.YouTrackServer import com.intellij.openapi.project.Project import com.intellij.testFramework.fixtures.IdeaProjectTestFixture import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class SetupVariationsTest : IssueRestTrait, IdeaProjectTrait, SetupConnectionTrait, ComponentAware { private lateinit var fixture: IdeaProjectTestFixture override lateinit var repository: YouTrackServer override val project: Project by lazy { fixture.project } @Before fun setUp() { fixture = getLightCodeInsightFixture() fixture.setUp() } @Test fun `test if connected repository has an issue that can be displayed`() { repository = createYouTrackRepository(serverUrl, token) repository.defaultSearch = "project: AT" val repo = repository.getRepo() val setupTask = SetupRepositoryConnector() val issueId = createIssue() try { setupTask.testConnection(repo, project) issueStoreComponent[repository].update(repository).waitFor(5000) assertEquals(NotifierState.SUCCESS, setupTask.noteState) assertEquals(1, issueStoreComponent[repository].getAllIssues().size) } finally { deleteIssue(issueId) } } @Test fun `test login anonymously feature`() { val serverUrl = "https://ytplugintest.myjetbrains.com/youtrack" repository = createYouTrackRepository(serverUrl, token, loginAnon = true) val repo = repository.getRepo() val setupTask = SetupRepositoryConnector() setupTask.testConnection(repo, project) assertEquals(NotifierState.SUCCESS, setupTask.noteState) } @Test fun `test login anonymously feature with invalid url`() { val serverUrl = "https://ytplugintest" repository = createYouTrackRepository(serverUrl, token, loginAnon = true) val repo = repository.getRepo() val setupTask = SetupRepositoryConnector() setupTask.testConnection(repo, project) assertEquals(NotifierState.LOGIN_ERROR, setupTask.noteState) } @Test fun `test share url feature`() { val serverUrl = "https://ytplugintest.myjetbrains.com/youtrack" repository = createYouTrackRepository(serverUrl, token, shareUrl = true) val repo = repository.getRepo() val setupTask = SetupRepositoryConnector() setupTask.testConnection(repo, project) assertEquals(NotifierState.SUCCESS, setupTask.noteState) } //TODO: add case of null host @After fun tearDown() { issueStoreComponent.remove(repository) cleanUpTaskManager() fixture.tearDown() } }
apache-2.0
74c1a3fa155ae4cd3f4ba2a8cbe756a1
31.735632
100
0.695469
4.674877
false
true
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/user/PushNotificationsPreference.kt
2
824
package com.habitrpg.android.habitica.models.user import com.habitrpg.android.habitica.models.BaseObject import io.realm.RealmObject import io.realm.annotations.RealmClass @RealmClass(embedded = true) open class PushNotificationsPreference : RealmObject(), BaseObject { var unsubscribeFromAll: Boolean = false var invitedParty: Boolean = false var invitedQuest: Boolean = false var majorUpdates: Boolean = false var wonChallenge: Boolean = false var invitedGuild: Boolean = false var newPM: Boolean = false var questStarted: Boolean = false var giftedGems: Boolean = false var giftedSubscription: Boolean = false var partyActivity: Boolean = false var mentionParty: Boolean = false var mentionJoinedGuild: Boolean = false var mentionUnjoinedGuild: Boolean = false }
gpl-3.0
ee441df09e84168ca463a493ace1fd72
34.826087
68
0.757282
4.478261
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengles/BufferObject.kt
1
1399
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengles import org.lwjgl.generator.* class BufferObject(val binding: String): ParameterModifier() { companion object: ModifierKey<BufferObject> override val isSpecial = true override fun validate(param: Parameter) { if ( !param.nativeType.isPointer || param.nativeType.mapping === PointerMapping.OPAQUE_POINTER ) throw IllegalArgumentException("The BufferObject modifier can only be applied on data pointer types or long primitives.") when ( this ) { PIXEL_PACK_BUFFER -> { if ( param.paramType !== ParameterType.OUT ) throw IllegalArgumentException("The specified BufferObject modifier can only be applied on output parameters.") } else -> { if ( param.paramType !== ParameterType.IN ) throw IllegalArgumentException("The specified BufferObject modifier can only be applied on input parameters.") } } } } val ARRAY_BUFFER = BufferObject("GLES20.GL_ARRAY_BUFFER_BINDING") val ELEMENT_ARRAY_BUFFER = BufferObject("GLES20.GL_ELEMENT_ARRAY_BUFFER_BINDING") val PIXEL_PACK_BUFFER = BufferObject("GLES30.GL_PIXEL_PACK_BUFFER_BINDING") val PIXEL_UNPACK_BUFFER = BufferObject("GLES30.GL_PIXEL_UNPACK_BUFFER_BINDING") val DRAW_INDIRECT_BUFFER = BufferObject("GLES31.GL_DRAW_INDIRECT_BUFFER_BINDING")
bsd-3-clause
4fc244ba29b951368338e48d71c50ef5
37.888889
124
0.729807
4.043353
false
false
false
false
codebutler/odyssey
retrograde-app-shared/src/main/java/com/codebutler/retrograde/lib/game/display/FpsCalculator.kt
1
1472
/* * FpsCalculator.kt * * Copyright (C) 2017 Retrograde Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.retrograde.lib.game.display class FpsCalculator { companion object { private var size: Int = 100 } private var lastUpdate = System.currentTimeMillis() private var lastFpsWrite = 0 private var totalFps = 0L private val fpsHistory = LongArray(size) fun update() { val currentUpdate = System.currentTimeMillis() val deltaTime = currentUpdate - lastUpdate + 1 // Add 1 to make sure delta time is non-zero. val fps = 1000 / deltaTime totalFps -= fpsHistory[lastFpsWrite] totalFps += fps fpsHistory[lastFpsWrite++] = fps lastFpsWrite %= 100 lastUpdate = currentUpdate } val fps: Long get() = totalFps / 100 }
gpl-3.0
53ff9000502d251bd7f54f7ea78af317
29.666667
100
0.686821
4.304094
false
false
false
false
IRA-Team/VKPlayer
app/src/main/java/com/irateam/vkplayer/ui/SimpleItemTouchHelperCallback.kt
1
4531
package com.irateam.vkplayer.ui import android.graphics.Canvas import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import android.view.animation.Interpolator class SimpleItemTouchHelperCallback(private val mAdapter: ItemTouchHelperAdapter) : ItemTouchHelper.Callback() { override fun isLongPressDragEnabled(): Boolean { return false } override fun isItemViewSwipeEnabled(): Boolean { return true } override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { // Set movement flags based on the layout manager if (recyclerView.layoutManager is GridLayoutManager) { val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT val swipeFlags = 0 return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags) } else { val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN val swipeFlags = ItemTouchHelper.START or ItemTouchHelper.END return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags) } } private var mCachedMaxScrollSpeed = -1 private fun getMaxDragScroll(recyclerView: RecyclerView): Int { if (mCachedMaxScrollSpeed == -1) { mCachedMaxScrollSpeed = recyclerView.resources.getDimensionPixelSize( android.support.v7.recyclerview.R.dimen.item_touch_helper_max_drag_scroll_per_frame) } return mCachedMaxScrollSpeed } override fun interpolateOutOfBoundsScroll(recyclerView: RecyclerView, viewSize: Int, viewSizeOutOfBounds: Int, totalSize: Int, msSinceStartScroll: Long): Int { val maxScroll = getMaxDragScroll(recyclerView) val absOutOfBounds = Math.abs(viewSizeOutOfBounds) val direction = Math.signum(viewSizeOutOfBounds.toFloat()).toInt() // might be negative if other direction val outOfBoundsRatio = Math.min(1f, 1f * absOutOfBounds / viewSize) val cappedScroll = (direction.toFloat() * maxScroll.toFloat() * sDragViewScrollCapInterpolator.getInterpolation(outOfBoundsRatio)).toInt() val timeRatio: Float if (msSinceStartScroll < 2000) { timeRatio = 0.6f } else if (msSinceStartScroll < 4000) { timeRatio = 0.9f } else { timeRatio = 1.2f } val value = (cappedScroll * sDragScrollInterpolator.getInterpolation(timeRatio)).toInt() if (value == 0) { return if (viewSizeOutOfBounds > 0) 1 else -1 } return value } override fun onMove(recyclerView: RecyclerView, source: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { if (source.itemViewType != target.itemViewType) { return false } // Notify the adapter of the move mAdapter.onItemMove(source.adapterPosition, target.adapterPosition) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, i: Int) { // Notify the adapter of the dismissal mAdapter.onItemDismiss(viewHolder.adapterPosition) } override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { // Fade out the view as it is swiped out of the parent's bounds val alpha = ALPHA_FULL - Math.abs(dX) / viewHolder.itemView.width.toFloat() viewHolder.itemView.alpha = alpha viewHolder.itemView.translationX = dX } else { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } } override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) { // We only want the active item to change if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) { if (viewHolder is ItemTouchHelperViewHolder) { // Let the view holder know that this item is being moved or dragged viewHolder.onItemSelected() } } super.onSelectedChanged(viewHolder, actionState) } override fun clearView(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder) { super.clearView(recyclerView, viewHolder) viewHolder.itemView.alpha = ALPHA_FULL if (viewHolder is ItemTouchHelperViewHolder) { // Tell the view holder it's time to restore the idle state viewHolder.onItemClear() } } companion object { val ALPHA_FULL = 1.0f private val sDragViewScrollCapInterpolator = Interpolator{ val t = it - 1.0f t * t * t * t * t + 1.0f } private val sDragScrollInterpolator = Interpolator{ t -> t * t * t } } }
apache-2.0
cefc47177461b808eaffa90f60e6d359
33.853846
171
0.752814
4.041927
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/net/social/pumpio/PObjectType.kt
1
2403
/* * Copyright (C) 2013 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.pumpio import org.andstatus.app.util.JsonUtils import org.json.JSONObject /** @see [Object Types](https://www.w3.org/TR/activitystreams-vocabulary/.activity-types) * */ internal enum class PObjectType(val id: String, compatibleType: PObjectType?) { ACTIVITY("activity", null) { override fun isTypeOf(jso: JSONObject?): Boolean { var `is` = false if (jso != null) { `is` = if (jso.has("objecttype")) { super.isTypeOf(jso) } else { // It may not have the "objectType" field as in the specification: // http://activitystrea.ms/specs/json/1.0/ jso.has("verb") && jso.has("object") } } return `is` } }, APPLICATION("application", null), PERSON("person", null), COMMENT("comment", null), IMAGE("image", COMMENT), VIDEO("video", COMMENT), NOTE("note", COMMENT), COLLECTION("collection", null), UNKNOWN("unknown", null); private val compatibleType: PObjectType = compatibleType ?: this open fun isTypeOf(jso: JSONObject?): Boolean { var `is` = false if (jso != null) { `is` = id.equals(JsonUtils.optString(jso, "objectType"), ignoreCase = true) } return `is` } companion object { fun compatibleWith(jso: JSONObject?): PObjectType { val type = fromJson(jso) return type.compatibleType } fun fromJson(jso: JSONObject?): PObjectType { for (type in values()) { if (type.isTypeOf(jso)) { return type } } return UNKNOWN } } }
apache-2.0
bf3e446a46a8e4d98e4b01c37c1c38bc
34.865672
218
0.592593
4.32973
false
false
false
false
initrc/android-bootstrap
app/src/main/java/io/github/initrc/bootstrap/view/listener/InfiniteGridScrollListener.kt
1
1299
package io.github.initrc.bootstrap.view.listener import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager /** * Infinite scroll listener. */ class InfiniteGridScrollListener( private val layoutManager: StaggeredGridLayoutManager, private val loadMore: () -> Unit) : RecyclerView.OnScrollListener() { private var prevTotalCount = 0 private var totalCount = 0 private var visibleCount = 0 private var loading = true override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy < 0) return totalCount = layoutManager.itemCount visibleCount = layoutManager.childCount val visibleThreshold = layoutManager.spanCount * 5 val firstVisiblePos = IntArray(layoutManager.spanCount) layoutManager.findFirstVisibleItemPositions(firstVisiblePos) if (loading) { if (totalCount != prevTotalCount) { prevTotalCount = totalCount loading = false } } if (!loading && totalCount - visibleCount <= firstVisiblePos.getOrElse(0) {0} + visibleThreshold) { loadMore() loading = true } } }
mit
87e38c8063dd86d5616a33edc790e34c
33.184211
96
0.655889
5.259109
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mcp/actions/SrgActionBase.kt
1
4374
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.actions import com.demonwav.mcdev.platform.mcp.McpModuleType import com.demonwav.mcdev.platform.mcp.srg.McpSrgMap import com.demonwav.mcdev.platform.mixin.handlers.ShadowHandler import com.demonwav.mcdev.util.ActionData import com.demonwav.mcdev.util.getDataFromActionEvent import com.demonwav.mcdev.util.invokeLater import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.VisualPosition import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiIdentifier import com.intellij.psi.PsiMember import com.intellij.psi.PsiReference import com.intellij.ui.LightColors import com.intellij.ui.awt.RelativePoint abstract class SrgActionBase : AnAction() { override fun actionPerformed(e: AnActionEvent) { val data = getDataFromActionEvent(e) ?: return showBalloon("Unknown failure", e) if (data.element !is PsiIdentifier) { showBalloon("Not a valid element", e) return } val mcpModule = data.instance.getModuleOfType(McpModuleType) ?: return showBalloon("No mappings found", e) mcpModule.srgManager?.srgMap?.onSuccess { srgMap -> var parent = data.element.parent ?: return@onSuccess showBalloon("Not a valid element", e) if (parent is PsiMember) { val shadowTarget = ShadowHandler.getInstance()?.findFirstShadowTargetForReference(parent)?.element if (shadowTarget != null) { parent = shadowTarget } } if (parent is PsiReference) { parent = parent.resolve() ?: return@onSuccess showBalloon("Not a valid element", e) } withSrgTarget(parent, srgMap, e, data) }?.onError { showBalloon(it.message ?: "No MCP data available", e) } ?: showBalloon("No mappings found", e) } abstract fun withSrgTarget(parent: PsiElement, srgMap: McpSrgMap, e: AnActionEvent, data: ActionData) companion object { fun showBalloon(message: String, e: AnActionEvent) { val balloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(message, null, LightColors.YELLOW, null) .setHideOnAction(true) .setHideOnClickOutside(true) .setHideOnKeyOutside(true) .createBalloon() val project = e.project ?: return val statusBar = WindowManager.getInstance().getStatusBar(project) invokeLater { val element = getDataFromActionEvent(e)?.element val editor = getDataFromActionEvent(e)?.editor val at = if (element != null && editor != null) { val pos = editor.offsetToVisualPosition(element.textRange.endOffset - element.textLength / 2) RelativePoint( editor.contentComponent, editor.visualPositionToXY(VisualPosition(pos.line + 1, pos.column)) ) } else RelativePoint.getCenterOf(statusBar.component) balloon.show(at, Balloon.Position.below) } } fun showSuccessBalloon(editor: Editor, element: PsiElement, text: String) { val balloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(text, null, LightColors.SLIGHTLY_GREEN, null) .setHideOnAction(true) .setHideOnClickOutside(true) .setHideOnKeyOutside(true) .createBalloon() invokeLater { val pos = editor.offsetToVisualPosition(element.textRange.endOffset - element.textLength / 2) val at = RelativePoint( editor.contentComponent, editor.visualPositionToXY(VisualPosition(pos.line + 1, pos.column)) ) balloon.show(at, Balloon.Position.below) } } } }
mit
96046d3efff8e4288f733458c2ff78fb
38.053571
114
0.640604
4.981777
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/two/WebPageActivity.kt
1
21695
package com.intfocus.template.subject.two import android.annotation.SuppressLint import android.app.Activity import android.app.AlertDialog import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo import android.net.Uri import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.KeyEvent import android.view.View import android.view.WindowManager import com.github.barteksc.pdfviewer.listener.OnPageErrorListener import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle import com.intfocus.template.BuildConfig import com.intfocus.template.R import com.intfocus.template.constant.Params import com.intfocus.template.constant.Params.BANNER_NAME import com.intfocus.template.constant.Params.GROUP_ID import com.intfocus.template.constant.Params.JAVASCRIPT_INTERFACE_NAME import com.intfocus.template.constant.Params.LINK import com.intfocus.template.constant.Params.OBJECT_ID import com.intfocus.template.constant.Params.OBJECT_TYPE import com.intfocus.template.constant.Params.TEMPLATE_ID import com.intfocus.template.constant.ToastColor import com.intfocus.template.dashboard.mine.adapter.FilterMenuAdapter import com.intfocus.template.filter.FilterDialogFragment import com.intfocus.template.model.response.filter.MenuItem import com.intfocus.template.model.response.filter.MenuResult import com.intfocus.template.ui.BaseActivity import com.intfocus.template.ui.view.WebView4Scroll import com.intfocus.template.ui.view.addressselector.FilterPopupWindow import com.intfocus.template.util.* import com.tencent.smtt.sdk.* import com.zhihu.matisse.Matisse import com.zhihu.matisse.MimeType import com.zhihu.matisse.engine.impl.GlideEngine import com.zhihu.matisse.filter.Filter import kotlinx.android.synthetic.main.activity_subject.* import kotlinx.android.synthetic.main.item_action_bar.* import java.io.File /** * @author liuruilin * @data 2017/11/15 * @describe */ class WebPageActivity : BaseActivity(), WebPageContract.View, OnPageErrorListener, FilterMenuAdapter.FilterMenuListener, FilterPopupWindow.MenuLisenter, FilterDialogFragment.FilterListener, CleanCacheCallback { private val REQUEST_CODE_CHOOSE = 1 private var errorCount: Int = 0 override lateinit var presenter: WebPageContract.Presenter lateinit var bannerName: String lateinit var reportId: String lateinit var templateId: String lateinit var groupId: String lateinit var url: String lateinit var objectType: String private var mWebView: WebView4Scroll? = null private var mOverrideKeyCodes = intArrayOf( KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT ) /** * 图片上传接收参数 */ private var uploadFile: ValueCallback<Uri>? = null private var uploadFiles: ValueCallback<Array<Uri>>? = null /** * 地址选择 */ var locationDataList: ArrayList<MenuItem> = arrayListOf() var msg: MenuResult? = null /** * 菜单 */ var currentPosition = 0 //当前展开的menu var menuDatas: List<MenuItem> = arrayListOf() lateinit var menuAdapter: FilterMenuAdapter lateinit var filterPopupWindow: FilterPopupWindow override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if ("baozhentv" == BuildConfig.FLAVOR) { window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } setContentView(R.layout.activity_subject) init() WebPagePresenter(WebPageModelImpl.getInstance(), this) presenter.load(reportId, templateId, groupId, url) if ("baozhentv" == BuildConfig.FLAVOR) { rl_action_bar.post { setBannerVisibility(View.GONE) } ll_filter.post { ll_filter.visibility = View.GONE } } } override fun setBannerTitle(title: String) { runOnUiThread { tv_banner_title.text = title } } override fun setBannerMenuVisibility(state: Int) { iv_banner_setting.visibility = state } override fun setBannerVisibility(state: Int) { rl_action_bar.visibility = state } override fun setBannerBackVisibility(state: Int) { iv_banner_back.visibility = state } override fun setAddressFilterText(text: String) { if (null != tv_location_address) { tv_location_address.text = text } } private fun setLoadingVisibility(state: Int) { anim_loading.visibility = state } override fun finishActivity() { PageLinkManage.pageBackIntent(this) WebPageModelImpl.destroyInstance() finish() } override fun onDestroy() { super.onDestroy() mWebView?.destroy() } override fun dismissActivity(v: View) { onBackPressed() } override fun onBackPressed() { if (url.startsWith("http")) { val builder = AlertDialog.Builder(this) builder.setTitle("温馨提示") .setMessage("退出当前页面?") .setPositiveButton("确认") { _, _ -> PageLinkManage.pageBackIntent(this) finish() } .setNegativeButton("取消") { _, _ -> } builder.show() } else { PageLinkManage.pageBackIntent(this) finish() } } private fun init() { groupId = intent.getStringExtra(GROUP_ID) reportId = intent.getStringExtra(OBJECT_ID) objectType = intent.getStringExtra(OBJECT_TYPE) bannerName = intent.getStringExtra(BANNER_NAME) templateId = intent.getStringExtra(TEMPLATE_ID) url = intent.getStringExtra(LINK) tv_banner_title.text = bannerName iv_banner_setting.setOnClickListener { launchDropMenuActivity(url) } iv_banner_back.setOnClickListener { onBackPressed() } if (url.toLowerCase().endsWith(".pdf")) { pdfview.visibility = View.INVISIBLE } else { if (!url.startsWith("http")) { initAdapter() } initWebView() } srl_activity_subject.setOnRefreshListener { refresh() } } @SuppressLint("SetJavaScriptEnabled") private fun initWebView() { mWebView = WebView4Scroll(this,srl_activity_subject) browser.addView(mWebView) val webSettings = mWebView?.settings // 允许 JS 执行 webSettings?.javaScriptEnabled = true // 允许点击三方下载链接 弹出本地浏览器选择框 mWebView?.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength -> LogUtil.d(this, "url=" + url) LogUtil.d(this, "userAgent=" + userAgent) LogUtil.d(this, "contentDisposition=" + contentDisposition) LogUtil.d(this, "mimetype=" + mimetype) LogUtil.d(this, "contentLength=" + contentLength) val uri = Uri.parse(url) startActivity(Intent(Intent.ACTION_VIEW, uri)) } webSettings?.cacheMode = if (HttpUtil.isConnected(this)) { // 缓存模式为无缓存 WebSettings.LOAD_NO_CACHE } else { WebSettings.LOAD_CACHE_ELSE_NETWORK } val cacheDir = File(cacheDir, "webviewCache") //设置数据库缓存路径 webSettings?.databasePath = cacheDir.absolutePath //设置 应用 缓存目录 webSettings?.setAppCachePath(cacheDir.absolutePath) //开启 DOM 存储功能 webSettings?.domStorageEnabled = true //开启 数据库 存储功能 webSettings?.databaseEnabled = true //开启 应用缓存 功能 webSettings?.setAppCacheEnabled(true) webSettings?.domStorageEnabled = true // 允许访问文件 webSettings?.allowFileAccess = true // 使用 WebView 推荐的窗口 webSettings?.useWideViewPort = true // 设置网页自适应屏幕大小 webSettings?.loadWithOverviewMode = true // 显示网页滚动条 mWebView?.x5WebViewExtension?.setScrollBarFadingEnabled(false) // 添加 javascript 接口 mWebView?.addJavascriptInterface(CustomJavaScriptsInterface(this), JAVASCRIPT_INTERFACE_NAME) // 设置是否支持缩放 webSettings?.setSupportZoom(false) // 设置是否支持对网页进行长按操作 mWebView?.setOnKeyListener { _, _, _ -> return@setOnKeyListener false } // 设置网页默认编码 webSettings?.defaultTextEncodingName = "utf-8" // 变更 UserAgent if ("baozhentv" == BuildConfig.FLAVOR) { val userAgentWithNewChromeVersion = Regex("Chrome/[0-9.]*\\s+").replace(webSettings?.userAgentString!!, "Chrome/63.0.3239.132 ") LogUtil.d(this, "UserAgent ::: $userAgentWithNewChromeVersion ") webSettings.setUserAgent(userAgentWithNewChromeVersion.replace("MQQBrowser/6.2 TBS/043805 ", "").replace("Version/4.0 ", "").replace("; wv", "")) } mWebView?.webChromeClient = object : WebChromeClient() { // For Android > 4.1.1 override fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String?, capture: String?) { uploadFile = uploadMsg imageSelect() } // For Android >= 5.0 override fun onShowFileChooser(webView: com.tencent.smtt.sdk.WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: WebChromeClient.FileChooserParams?): Boolean { uploadFiles = filePathCallback imageSelect() return true } } mWebView?.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(p0: WebView?, p1: String?): Boolean { p0!!.loadUrl(p1) return true } override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) //是否有筛选数据,有就显示出来 if (locationDataList.isNotEmpty()) { rl_address_filter.visibility = View.VISIBLE LogUtil.d("location", locationDataList.size.toString()) } else { rl_address_filter.visibility = View.GONE } if (menuDatas.isNotEmpty()) { LogUtil.d("faster_select", menuDatas.size.toString()) filter_recycler_view.visibility = View.VISIBLE view_line.visibility = View.VISIBLE menuAdapter.setData(menuDatas) } else { filter_recycler_view.visibility = View.GONE view_line.visibility = View.GONE } srl_activity_subject.isRefreshing = false setLoadingVisibility(View.GONE) } } } /** * 渲染报表 */ override fun show(path: String) { url = path if (url.toLowerCase().endsWith(".pdf")) { showPDF(url) } mWebView?.loadUrl(url) } /** * 错误页面 */ override fun showError(errorPagePath: String) { errorCount += 1 when (errorCount) { 1, 2 -> { ApiHelper.deleteHeadersFile() mWebView?.loadUrl(errorPagePath) } 3 -> { AlertDialog.Builder(this) .setTitle("提示") .setMessage("报表多次加载错误, 是否清理缓存后继续加载?") .setPositiveButton("确定") { _, _ -> CacheCleanManager.clearAppUserCache(this) errorCount = 0 } .setNegativeButton("下一次") { dialog, _ -> errorCount = 2 dialog.dismiss() } .setCancelable(false) .show() mWebView?.loadUrl(errorPagePath) } } } /** * 渲染 PDF 文件 */ override fun showPDF(path: String) { val pdfFile = File(path) if (pdfFile.exists()) { pdfview.fromFile(pdfFile) .defaultPage(0) .enableAnnotationRendering(true) .scrollHandle(DefaultScrollHandle(this)) .spacing(10) // in dp .onPageError(this) .load() browser.visibility = View.GONE pdfview.visibility = View.VISIBLE } else { ToastUtils.show(this, "加载PDF失败") } } /** * 刷新 */ override fun refresh() { srl_activity_subject.isRefreshing = false setLoadingVisibility(View.VISIBLE) show(url) } /** * 刷新 */ fun refreshWithClearCache() { srl_activity_subject.isRefreshing = false setLoadingVisibility(View.VISIBLE) CacheCleanManager.clearAppUserCache(this, this) } override fun onCleanCacheSuccess() { presenter.load(reportId, templateId, groupId, url) } override fun onCleanCacheFailure() { } override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent) { super.onActivityResult(requestCode, resultCode, intent) if (requestCode == Params.REQUEST_CODE_CHOOSE && resultCode == Activity.RESULT_OK) { if (null != uploadFile) { val result = if (resultCode != Activity.RESULT_OK) null else Matisse.obtainResult(intent) uploadFile!!.onReceiveValue(result!![0]) uploadFile = null } if (null != uploadFiles) { val result = if (resultCode != Activity.RESULT_OK) null else Matisse.obtainResult(intent) uploadFiles!!.onReceiveValue(arrayOf(result!![0])) uploadFiles = null } } else { if (null != uploadFile) { uploadFile!!.onReceiveValue(null) uploadFile = null } else if (null != uploadFiles) { uploadFiles!!.onReceiveValue(null) uploadFiles = null } } } override fun goBack() { mWebView?.goBack() } private fun imageSelect() { Matisse.from(this) .choose(MimeType.allOf()) .countable(true) .maxSelectable(1) .addFilter(GifSizeFilter(320, 320, 5 * Filter.K * Filter.K)) .gridExpectedSize( resources.getDimensionPixelSize(R.dimen.grid_expected_size)) .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) .thumbnailScale(0.85f) .imageEngine(GlideEngine()) .forResult(REQUEST_CODE_CHOOSE) } /** * 初始化筛选栏适配器 */ private fun initAdapter() { val mLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) filter_recycler_view.layoutManager = mLayoutManager menuAdapter = FilterMenuAdapter(this, menuDatas, this) filter_recycler_view.adapter = menuAdapter tv_address_filter.setOnClickListener { showDialogFragment() } } private fun showDialogFragment() { val mFragTransaction = supportFragmentManager.beginTransaction() val fragment = supportFragmentManager.findFragmentByTag("dialogFragment") if (fragment != null) { //为了不重复显示dialog,在显示对话框之前移除正在显示的对话框 mFragTransaction.remove(fragment) } val dialogFragment = FilterDialogFragment.newInstance(locationDataList) dialogFragment!!.show(mFragTransaction, "dialogFragment") //显示一个Fragment并且给该Fragment添加一个Tag,可通过findFragmentByTag找到该Fragment } /** * 点击普通筛选栏 */ override fun itemClick(position: Int) { //标记点击位置 menuDatas[position].arrorDirection = true menuAdapter.setData(menuDatas) currentPosition = position showMenuPop(position) } private fun showMenuPop(position: Int) { if (filterPopupWindow == null) { initMenuPopup(position) } else { filterPopupWindow.upDateDatas(menuDatas[position].data!!) } filterPopupWindow.showAsDropDown(view_line) filterPopupWindow.setOnDismissListener { for (menuItem in menuDatas) { menuItem.arrorDirection = false } menuAdapter.setData(menuDatas) } } private fun initMenuPopup(position: Int) { filterPopupWindow = FilterPopupWindow(this, menuDatas[position].data!!, this) filterPopupWindow.init() } /** * 普通排序列表点击 * * @param position */ override fun menuItemClick(position: Int) { for (menuItem in menuDatas[currentPosition].data!!) { menuItem.arrorDirection = false } //标记点击位置 menuDatas[currentPosition].data!![position].arrorDirection = true filterPopupWindow.dismiss() } override fun complete(data: java.util.ArrayList<MenuItem>) { var addStr = "" val size = data.size for (i in 0 until size) { addStr += data[i].name!! + "||" } addStr = addStr.substring(0, addStr.length - 2) val selectedItemPath = String.format("%s.selected_item", FileUtil.reportJavaScriptDataPath(this, groupId, templateId, reportId)) FileUtil.writeFile(selectedItemPath, addStr) refresh() } override fun onPageError(page: Int, t: Throwable?) { ToastUtils.show(this, "加载PDF失败, 失败原因: " + t.toString()) } /** * BannerMenu 下拉菜單點擊事件 */ fun menuItemClick(view: View) { when (view.id) { R.id.ll_share -> share(this, url) R.id.ll_comment -> comment(this, reportId, objectType, bannerName) R.id.ll_copylink -> actionCopyLink() R.id.ll_refresh -> refreshWithClearCache() else -> { } } if (popupWindow.isShowing) { popupWindow.dismiss() } } /** * 拷贝链接 */ private fun actionCopyLink() { val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboardManager.text = url ToastUtils.show(this, "链接已拷贝", ToastColor.SUCCESS) } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { when (keyCode) { KeyEvent.KEYCODE_BACK -> { // mWebView?.let { // return if (it.canGoBack()) { // it.goBack() // true // } else { // onBackPressed() // super.onKeyDown(keyCode, event) // } // } if (mWebView != null && mWebView!!.canGoBack()) { mWebView?.goBack() return true } } } return super.onKeyDown(keyCode, event) } /** * Given a key code, this method will pass it into the web view to handle * accordingly * * @param keycode Native Android KeyCode */ fun handleKeyInjection(keycode: Int) { val jsSend = ("javascript:mAKHandler.handleUri('nativewebsample://KEY_EVENT;" + keycode + ";');") loadJavascriptAction(jsSend) } private fun loadJavascriptAction(jsSend: String) { mWebView?.loadUrl(jsSend) } private fun addAndroidKeyHandler() { val androidKeyHandler = LoadAssetsJsonUtil.getAssetsJsonData("androidKeyHandler.js") mWebView?.loadUrl("javascript:(function(){$androidKeyHandler})()") } override fun onContentChanged() { super.onContentChanged() if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { rl_action_bar.post { setBannerVisibility(View.GONE) } ll_filter.post { ll_filter.visibility = View.GONE } } else { rl_action_bar.post { setBannerVisibility(View.VISIBLE) } ll_filter.post { ll_filter.visibility = View.VISIBLE } } } override fun dispatchKeyEvent(event: KeyEvent): Boolean { if (event.keyCode == KeyEvent.KEYCODE_R) { refresh() } val eventKeyCode = event.keyCode for (i in 0 until mOverrideKeyCodes.size) { if (eventKeyCode == mOverrideKeyCodes[i]) { if (event.action == KeyEvent.ACTION_UP) { handleKeyInjection(eventKeyCode) } return true } } return super.dispatchKeyEvent(event) } }
gpl-3.0
ea4516d894c76de53be57c94682c3a2e
33.173984
157
0.595137
4.615064
false
false
false
false
echsylon/atlantis
demo/app/src/main/java/com/echsylon/atlantis/demo/MainActivity.kt
1
2656
package com.echsylon.atlantis.demo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import androidx.lifecycle.lifecycleScope import com.echsylon.atlantis.Atlantis import com.echsylon.atlantis.demo.databinding.MainActivityBinding import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainActivity : AppCompatActivity() { private val binding by lazy { MainActivityBinding.inflate(LayoutInflater.from(this)) } private val httpClient by lazy { HttpClient.create() } private val atlantis by lazy { Atlantis() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) val configStream = assets.open("atlantis_config.json") val trustStore = assets.open("mock_trust.p12") atlantis.addConfiguration(configStream) atlantis.start(8080, trustStore, "password") binding.actionJson.setOnClickListener { onJsonClick() } binding.actionSerial.setOnClickListener { onNextClick() } binding.actionRandom.setOnClickListener { onRandomClick() } } private fun onJsonClick() { binding.responseJson.text = null binding.actionJson.isEnabled = false lifecycleScope.launch(IO) { httpClient .runCatching { getJsonString() } .onFailure { it.printStackTrace() } .onSuccess { withContext(Main) { binding.responseJson.text = it } } .also { withContext(Main) { binding.actionJson.isEnabled = true } } } } private fun onNextClick() { binding.responseSerial.text = null binding.actionSerial.isEnabled = false lifecycleScope.launch(IO) { httpClient .runCatching { getNextString() } .onFailure { it.printStackTrace() } .onSuccess { withContext(Main) { binding.responseSerial.text = it } } .also { withContext(Main) { binding.actionSerial.isEnabled = true } } } } private fun onRandomClick() { binding.responseRandom.text = null binding.actionRandom.isEnabled = false lifecycleScope.launch(IO) { httpClient .runCatching { getAnyString() } .onFailure { it.printStackTrace() } .onSuccess { withContext(Main) { binding.responseRandom.text = it } } .also { withContext(Main) { binding.actionRandom.isEnabled = true } } } } }
apache-2.0
a1d3c31d57bca305f3efd89b4cab2e2a
38.073529
90
0.661145
4.676056
false
true
false
false
czyzby/ktx
assets-async/src/main/kotlin/ktx/assets/async/AssetManager.kt
2
808
@file:Suppress("PackageDirectoryMismatch") // This extension method has to appear in the libGDX package in order to access package-private fields. package com.badlogic.gdx.assets /** Attempts to cancel loading of asset identified by [fileName]. For internal use. */ fun AssetManager.cancelLoading(fileName: String) { loadQueue.removeAll { it.fileName == fileName } tasks.forEach { if (it.assetDesc.fileName == fileName) it.cancel = true } assetDependencies.remove(fileName) } /** Attempts to cancel loading of assets identified by [fileNames]. For internal use. */ fun AssetManager.cancelLoading(fileNames: Set<String>) { loadQueue.removeAll { it.fileName in fileNames } tasks.forEach { if (it.assetDesc.fileName in fileNames) it.cancel = true } fileNames.forEach(assetDependencies::remove) }
cc0-1.0
a0680542a3e650e135a9f2f4a08cdc43
43.888889
103
0.764851
4.122449
false
false
false
false
HabitRPG/habitica-android
wearos/src/main/java/com/habitrpg/wearos/habitica/data/repositories/TaskLocalRepository.kt
1
4296
package com.habitrpg.wearos.habitica.data.repositories import com.habitrpg.shared.habitica.models.tasks.TaskType import com.habitrpg.shared.habitica.models.tasks.TasksOrder import com.habitrpg.wearos.habitica.models.tasks.Task import com.habitrpg.wearos.habitica.models.tasks.TaskList import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import java.util.Date import javax.inject.Inject import javax.inject.Singleton @Singleton class TaskLocalRepository @Inject constructor() { private val tasks = mapOf( TaskType.HABIT to MutableStateFlow<List<Task>?>(null), TaskType.DAILY to MutableStateFlow<List<Task>?>(null), TaskType.TODO to MutableStateFlow<List<Task>?>(null), TaskType.REWARD to MutableStateFlow<List<Task>?>(null) ) private val taskCountHelperValue = MutableStateFlow<Long>(0) fun getTasks(type: TaskType): Flow<List<Task>> { return tasks[type]!!.filterNotNull() } fun saveTasks(tasks: TaskList, order: TasksOrder?) { val taskMap = mapOf( TaskType.HABIT to sortTasks(tasks.tasks, order?.habits ?: emptyList(), TaskType.HABIT), TaskType.DAILY to sortTasks(tasks.tasks, order?.dailys ?: emptyList(), TaskType.DAILY), TaskType.TODO to sortTasks(tasks.tasks, order?.todos ?: emptyList(), TaskType.TODO), TaskType.REWARD to sortTasks(tasks.tasks, order?.rewards ?: emptyList(), TaskType.REWARD) ) for (type in taskMap) { this.tasks[type.key]?.value = null this.tasks[type.key]?.value = type.value } taskCountHelperValue.value = Date().time } private fun sortTasks(taskMap: MutableMap<String, Task>, taskOrder: List<String>, type: TaskType): List<Task> { val taskList = ArrayList<Task>() var position = 0 for (taskId in taskOrder) { val task = taskMap[taskId] if (task != null) { task.position = position taskList.add(task) position++ taskMap.remove(taskId) } } for (task in taskMap.values) { if (task.type != type) continue task.position = position taskList.add(task) position++ } return taskList } fun updateTask(task: Task) { val oldList = tasks[task.type]?.value?.toMutableList() val index = oldList?.indexOfFirst { task.id == it.id } if (index != null && index >= 0) { oldList[index] = task } else { oldList?.add(0, task) } oldList?.let { tasks[task.type]?.value = null tasks[task.type]?.value = it } taskCountHelperValue.value = Date().time } fun getTask(taskID: String): Flow<Task?> { for (type in tasks.values) { val task = type.value?.firstOrNull { it.id == taskID } if (task != null) { return flowOf(task) } } return emptyFlow() } fun getTaskCounts() = taskCountHelperValue.map { mapOf( TaskType.HABIT.value to (tasks[TaskType.HABIT]?.value?.size ?: 0), TaskType.DAILY.value to (tasks[TaskType.DAILY]?.value?.size ?: 0), TaskType.TODO.value to (tasks[TaskType.TODO]?.value?.size ?: 0), TaskType.REWARD.value to (tasks[TaskType.REWARD]?.value?.size ?: 0), ) } fun getActiveTaskCounts() = taskCountHelperValue.map { mapOf( TaskType.HABIT.value to (tasks[TaskType.HABIT]?.value?.size ?: 0), TaskType.DAILY.value to (tasks[TaskType.DAILY]?.value?.filter { it.isDue == true && !it.completed }?.size ?: 0), TaskType.TODO.value to (tasks[TaskType.TODO]?.value?.filter { !it.completed }?.size ?: 0), TaskType.REWARD.value to (tasks[TaskType.REWARD]?.value?.size ?: 0), ) } fun clearData() { tasks.values.forEach { it.value = emptyList() } taskCountHelperValue.value = 0 } }
gpl-3.0
5c621d23c6e990ae828227ca71f4629a
35.415254
117
0.60568
4.308927
false
false
false
false
InsertKoinIO/koin
core/koin-core/src/commonMain/kotlin/org/koin/core/logger/Logger.kt
1
1497
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.koin.core.logger /** * Abstract Koin Logger * * @author Arnaud Giuliani */ abstract class Logger(var level: Level = Level.INFO) { abstract fun log(level: Level, msg: MESSAGE) private fun canLog(level: Level): Boolean = this.level <= level private fun doLog(level: Level, msg: MESSAGE) { if (canLog(level)) { log(level, msg) } } fun debug(msg: MESSAGE) { doLog(Level.DEBUG, msg) } fun info(msg: MESSAGE) { doLog(Level.INFO, msg) } fun error(msg: MESSAGE) { doLog(Level.ERROR, msg) } fun isAt(lvl: Level): Boolean = this.level <= lvl fun log(lvl: Level, msg : () -> String){ if (isAt(lvl)) doLog(lvl,msg()) } } const val KOIN_TAG = "[Koin]" /** * Log Level */ enum class Level { DEBUG, INFO, ERROR, NONE } typealias MESSAGE = String
apache-2.0
788b9cbe5ca3b23e73746d8e76cee788
22.777778
75
0.645291
3.696296
false
false
false
false
InsertKoinIO/koin
core/koin-test/src/commonMain/kotlin/org/koin/test/check/CheckModules.kt
1
5713
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.koin.test.check import org.koin.core.Koin import org.koin.core.KoinApplication import org.koin.core.annotation.KoinInternalApi import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.core.definition.BeanDefinition import org.koin.core.instance.InstanceFactory import org.koin.core.logger.Level import org.koin.core.module.Module import org.koin.core.parameter.ParametersHolder import org.koin.core.qualifier.Qualifier import org.koin.core.qualifier.TypeQualifier import org.koin.core.scope.Scope import org.koin.dsl.KoinAppDeclaration import org.koin.dsl.koinApplication import org.koin.mp.KoinPlatformTools import org.koin.test.mock.MockProvider import org.koin.test.parameter.MockParameter /** * Check all definition's dependencies - start all modules and check if definitions can run */ fun KoinApplication.checkModules(parameters: CheckParameters? = null) = koin.checkModules(parameters) /** * Verify Modules by running each definition * * @param level - Log level * @param parameters - parameter setup * @param appDeclaration - koin Application */ fun checkModules(level: Level = Level.INFO, parameters: CheckParameters? = null, appDeclaration: KoinAppDeclaration) { startKoin(appDeclaration) .logger(KoinPlatformTools.defaultLogger(level)) .checkModules(parameters) } /** * Check given modules directly * * @param modules - list of modules * @param appDeclaration - Koin app config if needed * @param parameters - Check parameters DSL */ fun checkKoinModules(modules : List<Module>, appDeclaration: KoinAppDeclaration = {}, parameters: CheckParameters? = null) { startKoin(appDeclaration) .modules(modules) .checkModules(parameters) stopKoin() } /** * @see checkModules * * Deprecated */ @Deprecated("use instead checkKoinModules(modules : List<Module>, appDeclaration: KoinAppDeclaration = {}, parameters: CheckParameters? = null)") fun checkKoinModules(level: Level = Level.INFO, parameters: CheckParameters? = null, appDeclaration: KoinAppDeclaration) { startKoin(appDeclaration) .logger(KoinPlatformTools.defaultLogger(level)) .checkModules(parameters) stopKoin() } /** * @see checkKoinModules * * Deprecated */ @Deprecated("use instead checkKoinModules(modules : List<Module>, appDeclaration: KoinAppDeclaration = {}, parameters: CheckParameters? = null)") fun checkKoinModules(vararg modules : Module, level: Level = Level.INFO, parameters: CheckParameters? = null) { startKoin({}) .logger(KoinPlatformTools.defaultLogger(level)) .checkModules(parameters) stopKoin() } /** * Check all definition's dependencies - start all modules and check if definitions can run */ fun Koin.checkModules(parametersDefinition: CheckParameters? = null) { logger.info("[Check] checking modules ...") checkAllDefinitions( declareParameterCreators(parametersDefinition) ) logger.info("[Check] All checked") close() } private fun Koin.declareParameterCreators(parametersDefinition: CheckParameters?) = ParametersBinding(this).also { binding -> parametersDefinition?.invoke(binding) } @OptIn(KoinInternalApi::class) private fun Koin.checkAllDefinitions(allParameters: ParametersBinding) { val scopes: List<Scope> = instantiateAllScopes(allParameters) allParameters.scopeLinks.forEach { scopeLink -> val linkTargets = scopes.filter { it.scopeQualifier == scopeLink.value } scopes.filter { it.scopeQualifier == scopeLink.key } .forEach { scope -> linkTargets.forEach { linkTarget -> scope.linkTo(linkTarget) } } } instanceRegistry.instances.values.toSet().forEach { factory -> checkDefinition(allParameters, factory.beanDefinition, scopes.first { it.scopeQualifier == factory.beanDefinition.scopeQualifier }) } } @OptIn(KoinInternalApi::class) private fun Koin.instantiateAllScopes(allParameters: ParametersBinding): List<Scope> { return scopeRegistry.scopeDefinitions.map { qualifier -> val sourceScopeValue = mockSourceValue(qualifier) getOrCreateScope(qualifier.value, qualifier, sourceScopeValue) } } private fun mockSourceValue(qualifier: Qualifier): Any? { return if (qualifier is TypeQualifier) { MockProvider.makeMock(qualifier.type) } else null } private fun Koin.checkDefinition( allParameters: ParametersBinding, definition: BeanDefinition<*>, scope: Scope ) { val parameters : ParametersHolder = allParameters.parametersCreators[CheckedComponent( definition.qualifier, definition.primaryType )]?.invoke( definition.qualifier ) ?: MockParameter(scope, allParameters.defaultValues) logger.info("[Check] definition: $definition") scope.get<Any>(definition.primaryType, definition.qualifier) { parameters } for (secondaryType in definition.secondaryTypes) { val valueAsSecondary = scope.get<Any>(secondaryType, definition.qualifier) { parameters } require(secondaryType.isInstance(valueAsSecondary)) } }
apache-2.0
61cc2ddc2e49d10988496f98abe68d65
35.388535
145
0.745668
4.314955
false
false
false
false
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/shadowmapper/render/RenderMap.kt
1
10351
package nl.shadowlink.tools.shadowmapper.render import com.jogamp.opengl.GL2 import nl.shadowlink.tools.io.ByteReader import nl.shadowlink.tools.io.ReadFunctions import nl.shadowlink.tools.io.Vector3D import nl.shadowlink.tools.shadowlib.ide.ItemObject import nl.shadowlink.tools.shadowlib.img.ImgItem import nl.shadowlink.tools.shadowlib.ipl.Item_INST import nl.shadowlink.tools.shadowlib.model.model.Model import nl.shadowlink.tools.shadowlib.texturedic.TextureDic import nl.shadowlink.tools.shadowlib.utils.GameType import nl.shadowlink.tools.shadowmapper.FileManager import nl.shadowlink.tools.shadowmapper.gui.PickingType import nl.shadowlink.tools.shadowmapper.utils.GlUtil.drawCube import java.util.* import kotlin.math.sqrt /** * @author Shadow-Link */ class RenderMap( private val gameType: GameType, private val camera: Camera, private val fm: FileManager, ) { private var glDisplayList: IntArray = IntArray(0) var reload = false var loading = false var added = false var tempIDE: ItemObject? = null var tempIPL: Item_INST? = null fun display(gl: GL2) { if (!loading) { if (reload) { loading = true println("Started loading") loadMap(gl) reload = false loading = false println("Loading finished") } if (added) { loading = true println("Loading added model") loadAddedModel(gl) loading = false added = false println("Loading added model finished") } gl.glPushName(PickingType.map) fm.ipls.forEachIndexed { iplIndex, ipl -> if (ipl.selected && ipl.itemsLoaded) { gl.glPushName(iplIndex) ipl.itemsInst.forEachIndexed { instanceIndex, item -> if (!item.name.lowercase(Locale.getDefault()).contains("lod")) { if (getDistance(camera.pos, item.position) < item.drawDistance) { gl.glPushName(instanceIndex) if (item.selected) { gl.glColor3f(0.9f, 0f, 0f) } else { gl.glColor3f(1f, 1f, 1f) } gl.glPushMatrix() gl.glTranslatef(item.position.x, item.position.y, item.position.z) gl.glRotatef(item.axisAngle.w, item.axisAngle.x, item.axisAngle.y, item.axisAngle.z) gl.glCallList(glDisplayList[item.glListID]) gl.glPopMatrix() gl.glPopName() } } } gl.glPopName() } } gl.glPopName() } gl.glFlush() } private fun loadMap(gl: GL2) { // Clear existing display list glDisplayList.forEach { dl -> gl.glDeleteLists(dl, 1) } val boolList: ArrayList<Boolean> = ArrayList<Boolean>() val ideList: ArrayList<ItemObject> = ArrayList<ItemObject>() fm.ipls.forEach { ipl -> if (ipl.selected) { ipl.itemsInst.forEach { instance -> var ideNumber = 0 var ideItem = fm.ides[ideNumber].findItem(instance.name) as? ItemObject while (ideItem == null) { ideNumber++ ideItem = if (ideNumber < fm.ides.size) { fm.ides[ideNumber].findItem(instance.name) as? ItemObject } else { println("I really can't find in IDE: ${instance.name}") break } } if (ideItem != null) { var found = false for (i in ideList.indices) { if (ideList[i] == ideItem) { found = true instance.glListID = i + 1 instance.drawDistance = ideItem.drawDistance[0] } } if (!found) { instance.glListID = ideList.size + 1 instance.drawDistance = ideItem.drawDistance[0] ideList.add(ideItem) boolList.add(false) } } else { instance.glListID = 0 } } ipl.itemsLoaded = true } } glDisplayList = IntArray(ideList.size + 1) println("ideList Size: " + ideList.size) for (imgNumber in fm.imgs.indices) { val rf = ReadFunctions(fm.imgs[imgNumber].path) println("Opened: " + fm.imgs[imgNumber].fileName) for (i in ideList.indices) { if (!boolList[i]) { var modelName = "" var item: ImgItem? = null if (ideList[i].WDD != "null") { modelName = ideList[i].WDD + ".wdd" item = fm.imgs[imgNumber].findItem(modelName) } else { modelName = ideList[i].modelName + ".wdr" item = fm.imgs[imgNumber].findItem(modelName) if (item == null) item = fm.imgs[imgNumber].findItem(ideList[i].modelName + ".wft") } if (item != null) { rf.seek(item.offset) var br = rf.getByteReader(item.size) var mdl: Model? = null if (item.name.endsWith(".wdr")) { println(item.name) mdl = Model().loadWDR(br, item.size) } else if (item.name.endsWith(".wdd")) { mdl = Model().loadWDD(br, item.size, ideList[i]!!.modelName) } else if (item.name.endsWith(".wft")) { println("Loading WFT: " + item.name) mdl = Model().loadWFT(br, item.size) } val texName = ideList[i].textureName + ".wtd" item = fm.imgs[imgNumber].findItem(texName) if (item != null) { rf.seek(item.offset) br = rf.getByteReader(item.size) val txd = TextureDic(texName, br, gameType, true, item.size) mdl?.attachTXD(txd) } glDisplayList[i + 1] = gl.glGenLists(1) gl.glNewList(glDisplayList[i + 1], GL2.GL_COMPILE) if (mdl != null) { mdl.render(gl) } else { drawCube(gl, 10f, 0.1f, 0.5f, 0.9f) } gl.glEndList() mdl!!.reset() boolList[i] = true } } } rf.closeFile() } } private fun loadAddedModel(gl: GL2) { val tempList = glDisplayList // store all glInts to a temp array glDisplayList = IntArray(tempList.size + 1) for (i in tempList.indices) { glDisplayList[i] = tempList[i] } var item: ImgItem? = null var imgID = -1 var i = 0 while (item == null || i < fm.imgs.size) { if (tempIDE!!.WDD != "null") item = fm.imgs[i].findItem(tempIDE!!.WDD + ".wdd") else { item = fm.imgs[i].findItem(tempIDE!!.modelName + ".wdr") if (item == null) item = fm.imgs[i].findItem(tempIDE!!.modelName + ".wft") } if (item != null) imgID = i i++ } if (item != null) { val rf = ReadFunctions(fm.imgs[imgID].fileName) rf.seek(item.offset) var br: ByteReader? = rf.getByteReader(item.size) var mdl: Model? = null if (item.name.endsWith(".wdr")) { println(item.name) mdl = Model().loadWDR(br, item.size) // load the // model // from img } else if (item.name.endsWith(".wdd")) { mdl = Model().loadWDD(br, item.size, tempIDE!!.modelName) } else if (item.name.endsWith(".wft")) { println("Loading WFT: " + item.name) mdl = Model().loadWFT(br, item.size) } br = null item = fm.imgs[imgID].findItem(tempIDE!!.textureName + ".wtd") if (item != null) { rf.seek(item.offset) br = rf.getByteReader(item.size) val txd = TextureDic(tempIDE!!.textureName + ".wtd", br, gameType, true, item.size) mdl?.attachTXD(txd) } glDisplayList[tempList.size] = gl.glGenLists(1) gl.glNewList(glDisplayList[tempList.size], GL2.GL_COMPILE) if (mdl != null) { mdl.render(gl) } else { drawCube(gl, 10f, 0.1f, 0.5f, 0.9f) } gl.glEndList() mdl!!.reset() rf.closeFile() tempIPL!!.glListID = tempList.size } else { tempIPL!!.glListID = 0 } tempIDE = null tempIPL = null } private fun getDistance(test1: Vector3D, test2: Vector3D): Float { val dx = test1.x - test2.x val dy = 0 - test1.z - test2.y val dz = test1.y - test2.z return sqrt((dx * dx + dy * dy + dz * dz).toDouble()).toFloat() } fun addLoadModelToLoad(tempIPL: Item_INST?, tempIDE: ItemObject?) { this.tempIPL = tempIPL this.tempIDE = tempIDE added = true } }
gpl-2.0
0bf1486f96ef200fe6cd4ea06a86f142
40.079365
116
0.45812
4.341862
false
false
false
false
afollestad/drag-select-recyclerview
library/src/main/java/com/afollestad/dragselectrecyclerview/DragSelectTouchListener.kt
1
11367
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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. */ @file:Suppress("MemberVisibilityCanBePrivate", "unused") package com.afollestad.dragselectrecyclerview import android.content.Context import android.os.Handler import android.util.Log import android.view.MotionEvent import android.view.MotionEvent.ACTION_MOVE import android.view.MotionEvent.ACTION_UP import androidx.annotation.RestrictTo import androidx.annotation.RestrictTo.Scope import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.NO_POSITION import com.afollestad.dragselectrecyclerview.Mode.PATH import com.afollestad.dragselectrecyclerview.Mode.RANGE enum class Mode { RANGE, PATH } typealias AutoScrollListener = (scrolling: Boolean) -> Unit /** @author Aidan Follestad (afollestad) */ class DragSelectTouchListener private constructor( context: Context, private val receiver: DragSelectReceiver ) : RecyclerView.OnItemTouchListener { private val autoScrollHandler = Handler() private val autoScrollRunnable = object : Runnable { override fun run() { if (inTopHotspot) { recyclerView?.scrollBy(0, -autoScrollVelocity) autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY.toLong()) } else if (inBottomHotspot) { recyclerView?.scrollBy(0, autoScrollVelocity) autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY.toLong()) } } } var hotspotHeight: Int = context.dimen(R.dimen.dsrv_defaultHotspotHeight) var hotspotOffsetTop: Int = 0 var hotspotOffsetBottom: Int = 0 var autoScrollListener: AutoScrollListener? = null var mode: Mode = RANGE set(mode) { field = mode // Shouldn't maintain an active state through mode changes setIsActive(false, -1) } fun disableAutoScroll() { hotspotHeight = -1 hotspotOffsetTop = -1 hotspotOffsetBottom = -1 } private var recyclerView: RecyclerView? = null private var lastDraggedIndex = -1 private var initialSelection: Int = 0 private var dragSelectActive: Boolean = false private var minReached: Int = 0 private var maxReached: Int = 0 private var hotspotTopBoundStart: Int = 0 private var hotspotTopBoundEnd: Int = 0 private var hotspotBottomBoundStart: Int = 0 private var hotspotBottomBoundEnd: Int = 0 private var inTopHotspot: Boolean = false private var inBottomHotspot: Boolean = false private var autoScrollVelocity: Int = 0 private var isAutoScrolling: Boolean = false companion object { private const val AUTO_SCROLL_DELAY = 25 private const val DEBUG_MODE = false @Suppress("ConstantConditionIf") private fun log(msg: String) { if (!DEBUG_MODE) return Log.d("DragSelectTL", msg) } fun create( context: Context, receiver: DragSelectReceiver, config: (DragSelectTouchListener.() -> Unit)? = null ): DragSelectTouchListener { val listener = DragSelectTouchListener( context = context, receiver = receiver ) if (config != null) { listener.config() } return listener } } private fun notifyAutoScrollListener(scrolling: Boolean) { if (this.isAutoScrolling == scrolling) return log(if (scrolling) "Auto scrolling is active" else "Auto scrolling is inactive") this.isAutoScrolling = scrolling this.autoScrollListener?.invoke(scrolling) } /** * Initializes drag selection. * * @param active True if we are starting drag selection, false to terminate it. * @param initialSelection The index of the item which was pressed while starting drag selection. */ fun setIsActive( active: Boolean, initialSelection: Int ): Boolean { if (active && dragSelectActive) { log("Drag selection is already active.") return false } this.lastDraggedIndex = -1 this.minReached = -1 this.maxReached = -1 this.autoScrollHandler.removeCallbacks(autoScrollRunnable) this.notifyAutoScrollListener(false) this.inTopHotspot = false this.inBottomHotspot = false if (!active) { // Don't do any of the initialization below since we are terminating this.initialSelection = -1 return false } if (!receiver.isIndexSelectable(initialSelection)) { this.dragSelectActive = false this.initialSelection = -1 log("Index $initialSelection is not selectable.") return false } receiver.setSelected( index = initialSelection, selected = true ) this.dragSelectActive = active this.initialSelection = initialSelection this.lastDraggedIndex = initialSelection log("Drag selection initialized, starting at index $initialSelection.") return true } @RestrictTo(Scope.LIBRARY_GROUP) override fun onInterceptTouchEvent( view: RecyclerView, event: MotionEvent ): Boolean { val adapterIsEmpty = view.adapter?.isEmpty() ?: true val result = dragSelectActive && !adapterIsEmpty if (result) { recyclerView = view log("RecyclerView height = ${view.measuredHeight}") if (hotspotHeight > -1) { hotspotTopBoundStart = hotspotOffsetTop hotspotTopBoundEnd = hotspotOffsetTop + hotspotHeight hotspotBottomBoundStart = view.measuredHeight - hotspotHeight - hotspotOffsetBottom hotspotBottomBoundEnd = view.measuredHeight - hotspotOffsetBottom log("Hotspot top bound = $hotspotTopBoundStart to $hotspotTopBoundEnd") log("Hotspot bottom bound = $hotspotBottomBoundStart to $hotspotBottomBoundEnd") } } if (result && event.action == ACTION_UP) { onDragSelectionStop() } return result } @RestrictTo(Scope.LIBRARY_GROUP) override fun onTouchEvent( view: RecyclerView, event: MotionEvent ) { val action = event.action val itemPosition = view.getItemPosition(event) val y = event.y when (action) { ACTION_UP -> { onDragSelectionStop() return } ACTION_MOVE -> { if (hotspotHeight > -1) { // Check for auto-scroll hotspot if (y >= hotspotTopBoundStart && y <= hotspotTopBoundEnd) { inBottomHotspot = false if (!inTopHotspot) { inTopHotspot = true log("Now in TOP hotspot") autoScrollHandler.removeCallbacks(autoScrollRunnable) autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY.toLong()) this.notifyAutoScrollListener(true) } val simulatedFactor = (hotspotTopBoundEnd - hotspotTopBoundStart).toFloat() val simulatedY = y - hotspotTopBoundStart autoScrollVelocity = (simulatedFactor - simulatedY).toInt() / 2 log("Auto scroll velocity = $autoScrollVelocity") } else if (y >= hotspotBottomBoundStart && y <= hotspotBottomBoundEnd) { inTopHotspot = false if (!inBottomHotspot) { inBottomHotspot = true log("Now in BOTTOM hotspot") autoScrollHandler.removeCallbacks(autoScrollRunnable) autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY.toLong()) this.notifyAutoScrollListener(true) } val simulatedY = y + hotspotBottomBoundEnd val simulatedFactor = (hotspotBottomBoundStart + hotspotBottomBoundEnd).toFloat() autoScrollVelocity = (simulatedY - simulatedFactor).toInt() / 2 log("Auto scroll velocity = $autoScrollVelocity") } else if (inTopHotspot || inBottomHotspot) { log("Left the hotspot") autoScrollHandler.removeCallbacks(autoScrollRunnable) this.notifyAutoScrollListener(false) inTopHotspot = false inBottomHotspot = false } } // Drag selection logic if (mode == PATH && itemPosition != NO_POSITION) { // Non-default mode, we select exactly what the user touches over if (lastDraggedIndex == itemPosition) return lastDraggedIndex = itemPosition receiver.setSelected( index = lastDraggedIndex, selected = !receiver.isSelected(lastDraggedIndex) ) return } if (mode == RANGE && itemPosition != NO_POSITION && lastDraggedIndex != itemPosition ) { lastDraggedIndex = itemPosition if (minReached == -1) minReached = lastDraggedIndex if (maxReached == -1) maxReached = lastDraggedIndex if (lastDraggedIndex > maxReached) maxReached = lastDraggedIndex if (lastDraggedIndex < minReached) minReached = lastDraggedIndex selectRange( from = initialSelection, to = lastDraggedIndex, min = minReached, max = maxReached ) if (initialSelection == lastDraggedIndex) { minReached = lastDraggedIndex maxReached = lastDraggedIndex } } return } } } private fun onDragSelectionStop() { dragSelectActive = false inTopHotspot = false inBottomHotspot = false autoScrollHandler.removeCallbacks(autoScrollRunnable) this.notifyAutoScrollListener(false) } @RestrictTo(Scope.LIBRARY_GROUP) override fun onRequestDisallowInterceptTouchEvent(disallow: Boolean) = Unit private fun selectRange( from: Int, to: Int, min: Int, max: Int ) = with(receiver) { if (from == to) { // Finger is back on the initial item, unselect everything else for (i in min..max) { if (i == from) { continue } setSelected(i, false) } return } if (to < from) { // When selecting from one to previous items for (i in to..from) { setSelected(i, true) } if (min > -1 && min < to) { // Unselect items that were selected during this drag but no longer are for (i in min until to) { if (i == from) { continue } setSelected(i, false) } } if (max > -1) { for (i in from + 1..max) { setSelected(i, false) } } } else { // When selecting from one to next items for (i in from..to) { setSelected(i, true) } if (max > -1 && max > to) { // Unselect items that were selected during this drag but no longer are for (i in to + 1..max) { if (i == from) { continue } setSelected(i, false) } } if (min > -1) { for (i in min until from) { setSelected(i, false) } } } } }
apache-2.0
278aaf27bb23eac6b345af028a028dd4
30.400552
99
0.646609
4.53049
false
false
false
false
square/wire
wire-library/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ServiceDescriptorGenerator.kt
1
3495
/* * Copyright (C) 2021 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.kotlin.grpcserver import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.wire.schema.ProtoFile import com.squareup.wire.schema.Schema import com.squareup.wire.schema.Service import com.squareup.wire.schema.internal.SchemaEncoder import com.google.protobuf.DescriptorProtos import com.google.protobuf.Descriptors object ServiceDescriptorGenerator { internal fun addServiceDescriptor( builder: TypeSpec.Builder, service: Service, protoFile: ProtoFile?, schema: Schema, ) = builder .addProperty( PropertySpec.builder( name = "SERVICE_NAME", type = String::class, modifiers = emptyList() ) .initializer("\"${service.type}\"") .build() ) .addProperty( PropertySpec.builder( name = "serviceDescriptor", type = ClassName("io.grpc", "ServiceDescriptor").copy(nullable = true), modifiers = listOf(KModifier.PRIVATE), ) .addAnnotation(Volatile::class) .initializer("null") .mutable(true) .build() ) .apply { FileDescriptorGenerator.addDescriptorDataProperty(this, protoFile, schema) } .addFunction( FunSpec.builder("getServiceDescriptor") .returns(ClassName("io.grpc", "ServiceDescriptor").copy(nullable = true)) .addCode(serviceDescriptorCodeBlock(service, protoFile)) .build() ) private fun serviceDescriptorCodeBlock(service: Service, protoFile: ProtoFile?): CodeBlock { val grpcType = "${service.name}WireGrpc" val builder = CodeBlock.builder() .addStatement("var result = serviceDescriptor") .beginControlFlow("if (result == null)") .beginControlFlow("synchronized($grpcType::class)") .add(resultAssignerCodeBlock(service, protoFile)) .endControlFlow() .endControlFlow() .addStatement("return result") return builder.build() } private fun resultAssignerCodeBlock(service: Service, protoFile: ProtoFile?): CodeBlock { val builder = CodeBlock.builder() .addStatement("result = serviceDescriptor") .beginControlFlow("if (result == null)") .addStatement( "result = %M(SERVICE_NAME)", MemberName( enclosingClassName = ClassName("io.grpc", "ServiceDescriptor"), simpleName = "newBuilder" ) ) service.rpcs.forEach { builder.addStatement(".addMethod(get${it.name}Method())") } if (protoFile != null){ builder.addStatement(""" .setSchemaDescriptor(io.grpc.protobuf.ProtoFileDescriptorSupplier { fileDescriptor("${protoFile.location.path}", emptySet()) })""".trimIndent() ) } builder .addStatement(".build()") .addStatement("serviceDescriptor = result") .endControlFlow() return builder.build() } }
apache-2.0
ca8b47ac39cc125dc402ae58c89785e3
33.95
94
0.681545
4.635279
false
false
false
false
PolymerLabs/arcs
java/arcs/core/util/platform/native/PlatformDuration.kt
1
1619
/* * 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.util /** Provides a platform-dependent version of [ArcsDuration]. */ class PlatformDuration { override fun toString(): String = TODO("Add support for ArcsDuration in Kotlin Native") // See b/169213588 fun toMillis(): String = TODO("Add support for ArcsDuration in Kotlin Native") // See b/169213588 @Suppress("UNUSED_PARAMETER") fun compareTo(other: PlatformDuration): Int = TODO("Add support for ArcsDuration in Kotlin Native") // See b/169213588 override fun equals(other: Any?): Boolean { if (other == null || other !is PlatformDuration) return false return this.compareTo(other) == 0 } companion object { @Suppress("UNUSED_PARAMETER") fun ofMillis(value: Long): PlatformDuration = TODO("Add support for ArcsDuration in Kotlin Native") // See b/169213588 @Suppress("UNUSED_PARAMETER") fun valueOf(value: Long): PlatformDuration = TODO("Add support for ArcsDuration in Kotlin Native") // See b/169213588 @Suppress("UNUSED_PARAMETER") fun ofDays(days: Long): PlatformDuration = TODO("Add support for ArcsDuration in Kotlin Native") // See b/169213588 @Suppress("UNUSED_PARAMETER") fun ofHours(hours: Long): PlatformDuration = TODO("Add support for ArcsDuration in Kotlin Native") // See b/169213588 } }
bsd-3-clause
f0be88be523ee63c8a53c43a221fee3d
32.729167
95
0.70908
3.987685
false
false
false
false
k9mail/k-9
backend/imap/src/main/java/com/fsck/k9/backend/imap/ImapFolderPusher.kt
1
3114
package com.fsck.k9.backend.imap import com.fsck.k9.mail.power.PowerManager import com.fsck.k9.mail.store.imap.IdleRefreshManager import com.fsck.k9.mail.store.imap.IdleRefreshTimeoutProvider import com.fsck.k9.mail.store.imap.IdleResult import com.fsck.k9.mail.store.imap.ImapFolderIdler import com.fsck.k9.mail.store.imap.ImapStore import kotlin.concurrent.thread import timber.log.Timber /** * Listens for changes to an IMAP folder in a dedicated thread. */ class ImapFolderPusher( private val imapStore: ImapStore, private val powerManager: PowerManager, private val idleRefreshManager: IdleRefreshManager, private val callback: ImapPusherCallback, private val accountName: String, private val folderServerId: String, private val idleRefreshTimeoutProvider: IdleRefreshTimeoutProvider ) { @Volatile private var folderIdler: ImapFolderIdler? = null @Volatile private var stopPushing = false fun start() { Timber.v("Starting ImapFolderPusher for %s / %s", accountName, folderServerId) thread(name = "ImapFolderPusher-$accountName-$folderServerId") { Timber.v("Starting ImapFolderPusher thread for %s / %s", accountName, folderServerId) runPushLoop() Timber.v("Exiting ImapFolderPusher thread for %s / %s", accountName, folderServerId) } } fun refresh() { Timber.v("Refreshing ImapFolderPusher for %s / %s", accountName, folderServerId) folderIdler?.refresh() } fun stop() { Timber.v("Stopping ImapFolderPusher for %s / %s", accountName, folderServerId) stopPushing = true folderIdler?.stop() } private fun runPushLoop() { val wakeLock = powerManager.newWakeLock("ImapFolderPusher-$accountName-$folderServerId") wakeLock.acquire() performInitialSync() val folderIdler = ImapFolderIdler.create( idleRefreshManager, wakeLock, imapStore, folderServerId, idleRefreshTimeoutProvider ).also { folderIdler = it } try { while (!stopPushing) { when (folderIdler.idle()) { IdleResult.SYNC -> { callback.onPushEvent(folderServerId) } IdleResult.STOPPED -> { // ImapFolderIdler only stops when we ask it to. // But it can't hurt to make extra sure we exit the loop. stopPushing = true } IdleResult.NOT_SUPPORTED -> { stopPushing = true callback.onPushNotSupported() } } } } catch (e: Exception) { Timber.v(e, "Exception in ImapFolderPusher") this.folderIdler = null callback.onPushError(folderServerId, e) } wakeLock.release() } private fun performInitialSync() { callback.onPushEvent(folderServerId) } }
apache-2.0
6a0c8093ce994968b11e139e7f0be0c8
29.831683
97
0.607258
4.696833
false
false
false
false
danielgimenes/Kotlin-Koans
src/ii_collections/n22Fold.kt
1
588
package ii_collections fun example9() { val result = listOf(1, 2, 3, 4).fold(1, { partResult, element -> element * partResult }) result == 24 } // The same as fun whatFoldDoes(): Int { var result = 1 listOf(1, 2, 3, 4).forEach { element -> result = element * result } return result } fun Shop.getSetOfProductsOrderedByEachCustomer(): Set<Product> { // Return the set of products that were ordered by each of the customers return customers.fold(allOrderedProducts) { orderedByAll, customer -> customer.orderedProducts.intersect(orderedByAll) } }
mit
5a05f49bc1772dd516a74dbd2ed99a90
28.4
92
0.681973
3.92
false
false
false
false
felipefpx/utility-util-android-extensions
android-exts/src/main/kotlin/com/felipeporge/utility/menu/MenuItemExt.kt
1
955
@file:JvmName("MenuUtils") package com.felipeporge.utility.menu import android.content.Context import android.support.v4.content.ContextCompat import android.view.MenuItem import android.view.View import android.widget.FrameLayout import com.felipeporge.utility.R import kotlinx.android.synthetic.main.partial_action_badge.view.* /** * Shows badge on a menu item. * @param context The context. * @param iconResId Icon resource id. * @param count Count to show. */ fun MenuItem.showBadge(context: Context, iconResId: Int, count: Int) { val badge = setActionView(R.layout.partial_action_badge).actionView as FrameLayout badge.badgeActionIconIv?.setImageDrawable(ContextCompat.getDrawable(context, iconResId)) if(count > 0){ badge.badgeActionCountTv.visibility = View.VISIBLE badge.badgeActionCountTv.text = "$count" }else { badge.badgeActionCountTv.visibility = View.INVISIBLE } isVisible = true }
apache-2.0
8dad9243b3fc91265d4c76babf0a3253
29.83871
92
0.753927
3.866397
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/layers/recurrent/cfn/CFNLayersWindow.kt
1
3384
/* 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.layers.recurrent.cfn import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.models.recurrent.LayersWindow import com.kotlinnlp.simplednn.core.layers.models.recurrent.cfn.CFNLayerParameters import com.kotlinnlp.simplednn.core.layers.models.recurrent.cfn.CFNLayer import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import com.kotlinnlp.simplednn.simplemath.ndarray.Shape /** * */ internal sealed class CFNLayersWindow: LayersWindow { /** * */ object Empty : CFNLayersWindow() { override fun getPrevState(): Nothing? = null override fun getNextState(): Nothing? = null } /** * */ object Back : CFNLayersWindow() { override fun getPrevState(): CFNLayer<DenseNDArray> = buildPrevStateLayer() override fun getNextState(): Nothing? = null } /** * */ class Front(val currentLayerOutput: DenseNDArray): CFNLayersWindow() { override fun getPrevState(): Nothing? = null override fun getNextState(): CFNLayer<DenseNDArray> = buildNextStateLayer(currentLayerOutput) } /** * */ class Bilateral(val currentLayerOutput: DenseNDArray): CFNLayersWindow() { override fun getPrevState(): CFNLayer<DenseNDArray> = buildPrevStateLayer() override fun getNextState(): CFNLayer<DenseNDArray> = buildNextStateLayer(currentLayerOutput) } } /** * */ private fun buildPrevStateLayer(): CFNLayer<DenseNDArray> = CFNLayer( inputArray = AugmentedArray(size = 4), inputType = LayerType.Input.Dense, outputArray = AugmentedArray(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.2, 0.2, -0.3, -0.9, -0.8))).apply { activate() }, params = CFNLayerParameters(inputSize = 4, outputSize = 5), activationFunction = Tanh, layersWindow = CFNLayersWindow.Empty, dropout = 0.0 ) /** * */ private fun buildNextStateLayer(currentLayerOutput: DenseNDArray): CFNLayer<DenseNDArray> = CFNLayer( inputArray = AugmentedArray<DenseNDArray>(size = 4), inputType = LayerType.Input.Dense, outputArray = AugmentedArray(DenseNDArrayFactory.emptyArray(Shape(5))).apply { assignErrors(errors = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.1, -0.5, 0.7, 0.2))) }, params = CFNLayerParameters(inputSize = 4, outputSize = 5), activationFunction = Tanh, layersWindow = CFNLayersWindow.Empty, dropout = 0.0 ).apply { inputGate.assignValues(values = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.8, 1.0, -0.8, 0.0, 0.1))) inputGate.assignErrors(errors = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.7, -0.3, -0.2, 0.3, 0.6))) forgetGate.assignValues(values = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.2, -0.1, 0.6, -0.8, 0.5))) forgetGate.assignErrors(errors = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.9, 0.2, -0.5, 1.0))) activatedPrevOutput = currentLayerOutput }
mpl-2.0
eda63782f56e3070ec7cb7bbfe73ed71
32.84
111
0.725768
3.925754
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ConstantConditionIfInspection.kt
1
8169
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf import org.jetbrains.kotlin.idea.intentions.branchedTransformations.unwrapBlockOrParenthesis import org.jetbrains.kotlin.idea.util.hasNoSideEffects import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor class ConstantConditionIfInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return ifExpressionVisitor { expression -> val constantValue = expression.getConditionConstantValueIfAny() ?: return@ifExpressionVisitor val fixes = collectFixes(expression, constantValue) holder.registerProblem( expression.condition!!, KotlinBundle.message("condition.is.always.0", constantValue), *fixes.toTypedArray() ) } } companion object { private fun KtIfExpression.getConditionConstantValueIfAny(): Boolean? { var expr = condition while (expr is KtParenthesizedExpression) { expr = expr.expression } if (expr !is KtConstantExpression) return null val context = condition?.analyze(BodyResolveMode.PARTIAL_WITH_CFA) ?: return null val type = expr.getType(context) ?: return null val constant = ConstantExpressionEvaluator.getConstant(expr, context)?.toConstantValue(type) ?: return null return constant.value as? Boolean } private fun collectFixes( expression: KtIfExpression, constantValue: Boolean? = expression.getConditionConstantValueIfAny() ): List<ConstantConditionIfFix> { if (constantValue == null) return emptyList() val fixes = mutableListOf<ConstantConditionIfFix>() if (expression.branch(constantValue) != null) { val keepBraces = expression.isElseIf() && expression.branch(constantValue) is KtBlockExpression fixes += SimplifyFix( constantValue, expression.isUsedAsExpression(expression.analyze(BodyResolveMode.PARTIAL_WITH_CFA)), keepBraces ) } if (!constantValue && expression.`else` == null) { fixes += RemoveFix() } return fixes } fun applyFixIfSingle(ifExpression: KtIfExpression) { collectFixes(ifExpression).singleOrNull()?.applyFix(ifExpression) } } private interface ConstantConditionIfFix : LocalQuickFix { fun applyFix(ifExpression: KtIfExpression) } private class SimplifyFix( private val conditionValue: Boolean, private val isUsedAsExpression: Boolean, private val keepBraces: Boolean ) : ConstantConditionIfFix { override fun getFamilyName() = name override fun getName() = KotlinBundle.message("simplify.fix.text") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val ifExpression = descriptor.psiElement.getParentOfType<KtIfExpression>(strict = true) ?: return applyFix(ifExpression) } override fun applyFix(ifExpression: KtIfExpression) { val branch = ifExpression.branch(conditionValue)?.let { if (keepBraces) it else it.unwrapBlockOrParenthesis() } ?: return ifExpression.replaceWithBranch(branch, isUsedAsExpression, keepBraces) } } private class RemoveFix : ConstantConditionIfFix { override fun getFamilyName() = name override fun getName() = KotlinBundle.message("remove.fix.text") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val ifExpression = descriptor.psiElement.getParentOfType<KtIfExpression>(strict = true) ?: return applyFix(ifExpression) } override fun applyFix(ifExpression: KtIfExpression) { val parent = ifExpression.parent if (parent.node.elementType == KtNodeTypes.ELSE) { (parent.parent as? KtIfExpression)?.elseKeyword?.delete() parent.delete() } ifExpression.delete() } } } private fun KtIfExpression.branch(thenBranch: Boolean) = if (thenBranch) then else `else` fun KtExpression.replaceWithBranch(branch: KtExpression, isUsedAsExpression: Boolean, keepBraces: Boolean = false) { val caretModel = findExistingEditor()?.caretModel val subjectVariable = (this as? KtWhenExpression)?.subjectVariable?.let(fun(property: KtProperty): KtProperty? { if (property.annotationEntries.isNotEmpty()) return property val initializer = property.initializer ?: return property val references = ReferencesSearch.search(property, LocalSearchScope(this)).toList() return when (references.size) { 0 -> property.takeUnless { initializer.hasNoSideEffects() } 1 -> { if (initializer.hasNoSideEffects()) { references.first().element.replace(initializer) null } else property } else -> property } }) val factory = KtPsiFactory(this) val parent = this.parent val replaced = when { branch !is KtBlockExpression -> { if (subjectVariable != null) { replaced(KtPsiFactory(this).createExpressionByPattern("run { $0\n$1 }", subjectVariable, branch)) } else { replaced(branch) } } isUsedAsExpression -> { if (subjectVariable != null) { branch.addAfter(factory.createNewLine(), branch.addBefore(subjectVariable, branch.statements.firstOrNull())) } replaced(factory.createExpressionByPattern("run $0", branch.text)) } else -> { val firstChildSibling = branch.firstChild.nextSibling val lastChild = branch.lastChild val replaced = if (firstChildSibling != lastChild) { if (keepBraces) { parent.addAfter(branch, this) } else { if (subjectVariable != null) { branch.addAfter(subjectVariable, branch.lBrace) parent.addAfter(KtPsiFactory(this).createExpression("run ${branch.text}"), this) } else { parent.addRangeAfter(firstChildSibling, lastChild.prevSibling, this) } } } else { null } delete() replaced } } if (replaced != null) { caretModel?.moveToOffset(replaced.startOffset) } }
apache-2.0
49757b49d00c65d317c5499a6ae0b3a3
40.892308
158
0.651855
5.43513
false
false
false
false
android/nowinandroid
core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/TimeZoneBroadcastReceiver.kt
1
1540
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.ui import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter class TimeZoneBroadcastReceiver( val onTimeZoneChanged: () -> Unit ) : BroadcastReceiver() { private var registered = false override fun onReceive(context: Context, intent: Intent) { if (intent.action == Intent.ACTION_TIMEZONE_CHANGED) { onTimeZoneChanged() } } fun register(context: Context) { if (!registered) { val filter = IntentFilter() filter.addAction(Intent.ACTION_TIMEZONE_CHANGED) context.registerReceiver(this, filter) registered = true } } fun unregister(context: Context) { if (registered) { context.unregisterReceiver(this) registered = false } } }
apache-2.0
1372b0eda7ad00ce46c7c7f0461bbe44
29.8
75
0.684416
4.583333
false
false
false
false
android/nowinandroid
build-logic/convention/src/main/kotlin/com/google/samples/apps/nowinandroid/Flavor.kt
1
1419
package com.google.samples.apps.nowinandroid import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.dsl.ApplicationProductFlavor import com.android.build.api.dsl.ApplicationVariantDimension import com.android.build.api.dsl.CommonExtension import org.gradle.api.Project enum class FlavorDimension { contentType } // The content for the app can either come from local static data which is useful for demo // purposes, or from a production backend server which supplies up-to-date, real content. // These two product flavors reflect this behaviour. enum class Flavor (val dimension : FlavorDimension, val applicationIdSuffix : String? = null) { demo(FlavorDimension.contentType), prod(FlavorDimension.contentType, ".prod") } fun Project.configureFlavors( commonExtension: CommonExtension<*, *, *, *> ) { commonExtension.apply { flavorDimensions += FlavorDimension.contentType.name productFlavors { Flavor.values().forEach{ create(it.name) { dimension = it.dimension.name if (this@apply is ApplicationExtension && this is ApplicationProductFlavor) { if (it.applicationIdSuffix != null) { this.applicationIdSuffix = it.applicationIdSuffix } } } } } } }
apache-2.0
26c122e5c0d674716b11dc94f4d87ea4
35.410256
97
0.661734
4.745819
false
false
false
false
JetBrains/teamcity-nuget-support
nuget-feed/src/jetbrains/buildServer/nuget/feed/server/json/JsonAutocompleteHandler.kt
1
3247
package jetbrains.buildServer.nuget.feed.server.json import jetbrains.buildServer.nuget.feed.server.NuGetFeedConstants import jetbrains.buildServer.nuget.feed.server.controllers.NuGetFeedHandler import jetbrains.buildServer.nuget.feed.server.index.NuGetFeed import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedData import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedFactory import jetbrains.buildServer.nuget.feedReader.NuGetPackageAttributes import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class JsonAutocompleteHandler(private val feedFactory: NuGetFeedFactory) : NuGetFeedHandler { override fun handleRequest(feedData: NuGetFeedData, request: HttpServletRequest, response: HttpServletResponse) { val nuGetFeed = feedFactory.createFeed(feedData) val query = request.getParameter("q") val id = request.getParameter("id") val skip = request.getParameter("skip")?.toIntOrNull() val take = request.getParameter("take")?.toIntOrNull() ?: NuGetFeedConstants.NUGET_FEED_PACKAGE_SIZE val prerelease = request.getParameter("prerelease")?.toBoolean() ?: false val includeSemVer2 = request.includeSemVer2() if (!query.isNullOrEmpty()) { autocompleteNames(nuGetFeed, response, query, skip, take, prerelease, includeSemVer2) return } if (!id.isNullOrEmpty()) { autocompleteVersions(nuGetFeed, response, id, prerelease, includeSemVer2) return } response.sendError(HttpServletResponse.SC_BAD_REQUEST, "id or q query parameters should be defined.") } private fun autocompleteNames(feed: NuGetFeed, response: HttpServletResponse, id: String, skip: Int?, take: Int, prerelease: Boolean, includeSemVer2: Boolean) { val query = mutableMapOf(NuGetPackageAttributes.ID to id) if (!prerelease) { query[NuGetPackageAttributes.IS_PRERELEASE] = false.toString() } val results = feed.find(query, includeSemVer2).groupBy { it.packageInfo.id } val totalHits = results.size var keys = results.keys.asSequence() skip?.let { keys = keys.drop(it) } response.writeJson(JsonAutocompleteNames(totalHits, keys.take(take).toList())) } private fun autocompleteVersions(feed: NuGetFeed, response: HttpServletResponse, id: String, prerelease: Boolean, includeSemVer2: Boolean) { val query = mutableMapOf(NuGetPackageAttributes.ID to id) if (!prerelease) { query[NuGetPackageAttributes.IS_PRERELEASE] = true.toString() } val results = feed.find(query, includeSemVer2).filter { it.packageInfo.id == id } val versions = results.map { it.version.toString() } response.writeJson(JsonAutocompleteVersions(versions)) } }
apache-2.0
694a4525d5e39c381fa1b45a5a884233
42.293333
117
0.632892
4.782032
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceArrayEqualityOpWithArraysEquals/arrayEQEQ.kt
9
172
// WITH_STDLIB // FIX: Replace '==' with 'contentEquals' fun foo() { val a = arrayOf("a", "b", "c") val b = arrayOf("a", "b", "c") if (a <caret>== b) { } }
apache-2.0
c605e4590046abbb5b9ec971fc90698f
20.5
41
0.465116
2.6875
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/libdivide/src/templates/kotlin/libdivide/templates/libdivide.kt
4
31474
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package libdivide.templates import org.lwjgl.generator.* import libdivide.* val libdivide = "LibDivide".nativeClass(Module.LIBDIVIDE, prefixConstant = "LIBDIVIDE_", prefixMethod = "libdivide_") { nativeImport("libdivide.h") javaImport("static org.lwjgl.system.MathUtil.*") javaImport("static org.lwjgl.system.MemoryUtil.*") documentation = """ Native bindings to ${url("https://libdivide.com/", "libdivide")}. libdivide allows you to replace expensive integer divides with comparatively cheap multiplication and bitshifts. Compilers usually do this, but only when the divisor is known at compile time. libdivide allows you to take advantage of it at runtime. The result is that integer division can become faster - a lot faster. <b>LWJGL</b>: This is a hybrid implementation. Divider recovery methods use standard JNI bindings. All {@code *_gen}, {@code *_do} &amp; {@code *_get_algorithm} functions have been ported to pure Java. This eliminates the JNI overhead and enables the JVM to inline and further optimize these methods. """ IntConstant( "Library version.", "VERSION_MAJOR".."5", "VERSION_MINOR".."0" ) EnumConstant( "", "16_SHIFT_MASK".enum(0x1F), "32_SHIFT_MASK".enum(0x1F), "64_SHIFT_MASK".enum(0x3F), "ADD_MARKER".enum(0x40), "NEGATIVE_DIVISOR".enum(0x80) ) NativeName("libdivide_s16_gen")..internal..libdivide_s16_t("s16_gen_ref", "", int16_t("denom", "")) customMethod(""" @NativeType("struct libdivide_s16_t") public static LibDivideS16 libdivide_s16_gen(@NativeType("int16_t") short denom, @NativeType("struct libdivide_s16_t") LibDivideS16 __result) { if (denom == 0) { throw new IllegalArgumentException("divider must be != 0"); } int magic, more; int absD = denom < 0 ? -denom : denom; int floor_log_2_d = 31 - Integer.numberOfLeadingZeros(absD); if ((absD & (absD - 1)) == 0) { magic = 0; more = floor_log_2_d | (denom < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); } else { int l = 1 << (15 + floor_log_2_d); magic = l / absD; int rem = l % absD; if (absD - rem < 1 << floor_log_2_d) { more = floor_log_2_d - 1; } else { more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; magic <<= 1; } magic++; if (denom < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; magic = -magic; } } __result.magic((short)magic); __result.more((byte)more); return __result; }""") NativeName("libdivide_u16_gen")..internal..libdivide_u16_t("u16_gen_ref", "", uint16_t("denom", "")) customMethod(""" @NativeType("struct libdivide_u16_t") public static LibDivideU16 libdivide_u16_gen(@NativeType("uint16_t") short denom, @NativeType("struct libdivide_u16_t") LibDivideU16 __result) { if (denom == 0) { throw new IllegalArgumentException("divider must be != 0"); } int d = Short.toUnsignedInt(denom); int magic, more; int floor_log_2_d = 31 - Integer.numberOfLeadingZeros(d); if ((d & (d - 1)) == 0) { magic = 0; more = floor_log_2_d; } else { int l = 1 << (16 + floor_log_2_d); magic = Integer.divideUnsigned(l, d); int rem = l - magic * d; if (d - rem < 1 << floor_log_2_d) { more = floor_log_2_d; } else { more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; magic <<= 1; } magic++; } __result.magic((short)magic); __result.more((byte)more); return __result; }""") NativeName("libdivide_s32_gen")..internal..libdivide_s32_t("s32_gen_ref", "", int32_t("denom", "")) customMethod(""" @NativeType("struct libdivide_s32_t") public static LibDivideS32 libdivide_s32_gen(@NativeType("int32_t") int denom, @NativeType("struct libdivide_s32_t") LibDivideS32 __result) { if (denom == 0) { throw new IllegalArgumentException("divider must be != 0"); } int magic, more; int absD = denom < 0 ? -denom : denom; int floor_log_2_d = 31 - Integer.numberOfLeadingZeros(absD); if ((absD & (absD - 1)) == 0) { magic = 0; more = floor_log_2_d | (denom < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); } else { long l = 1L << (31 + floor_log_2_d); magic = (int)(l / absD); int rem = (int)(l % absD); if (absD - rem < 1 << floor_log_2_d) { more = floor_log_2_d - 1; } else { more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; magic <<= 1; } magic++; if (denom < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; magic = -magic; } } __result.magic(magic); __result.more((byte)more); return __result; }""") NativeName("libdivide_u32_gen")..internal..libdivide_u32_t("u32_gen_ref", "", uint32_t("denom", "")) customMethod(""" @NativeType("struct libdivide_u32_t") public static LibDivideU32 libdivide_u32_gen(@NativeType("uint32_t") int denom, @NativeType("struct libdivide_u32_t") LibDivideU32 __result) { if (denom == 0) { throw new IllegalArgumentException("divider must be != 0"); } int magic, more; int floor_log_2_d = 31 - Integer.numberOfLeadingZeros(denom); if ((denom & (denom - 1)) == 0) { magic = 0; more = floor_log_2_d; } else { long l = 1L << (32 + floor_log_2_d); magic = (int)mathDivideUnsigned(l, Integer.toUnsignedLong(denom)); int rem = (int)(l - magic * Integer.toUnsignedLong(denom)); if (Integer.compareUnsigned(denom - rem, 1 << floor_log_2_d) < 0) { more = floor_log_2_d; } else { more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; magic <<= 1; } magic++; } __result.magic(magic); __result.more((byte)more); return __result; }""") NativeName("libdivide_s64_gen")..internal..libdivide_s64_t("s64_gen_ref", "", int64_t("denom", "")) customMethod(""" @NativeType("struct libdivide_s64_t") public static LibDivideS64 libdivide_s64_gen(@NativeType("int64_t") long denom, @NativeType("struct libdivide_s64_t") LibDivideS64 __result) { if (denom == 0L) { throw new IllegalArgumentException("divider must be != 0"); } long magic; int more; long absD = denom < 0L ? -denom : denom; int floor_log_2_d = 63 - Long.numberOfLeadingZeros(absD); if ((absD & (absD - 1)) == 0) { magic = 0L; more = floor_log_2_d | (denom < 0L ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); } else { magic = libdivide_128_div_64_to_64(1L << (floor_log_2_d - 1), 0L, absD, __result.address()); long rem = __result.magic(); if (absD - rem < 1L << floor_log_2_d) { more = floor_log_2_d - 1; } else { more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; magic <<= 1; } magic++; if (denom < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; magic = -magic; } } __result.magic(magic); __result.more((byte)more); return __result; }""") NativeName("libdivide_u64_gen")..internal..libdivide_u64_t("u64_gen_ref", "", uint64_t("denom", "")) customMethod(""" @NativeType("struct libdivide_u64_t") public static LibDivideU64 libdivide_u64_gen(@NativeType("uint64_t") long denom, @NativeType("struct libdivide_u64_t") LibDivideU64 __result) { if (denom == 0L) { throw new IllegalArgumentException("divider must be != 0"); } long magic; int more; int floor_log_2_d = 63 - Long.numberOfLeadingZeros(denom); if ((denom & (denom - 1)) == 0) { magic = 0; more = floor_log_2_d; } else { magic = libdivide_128_div_64_to_64(1L << floor_log_2_d, 0L, denom, __result.address()); long rem = __result.magic(); if (Long.compareUnsigned(denom - rem, 1L << floor_log_2_d) < 0) { more = floor_log_2_d; } else { more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; magic <<= 1; } magic++; } __result.magic(magic); __result.more((byte)more); return __result; }""") NativeName("libdivide_s16_branchfree_gen")..internal..libdivide_s16_branchfree_t("s16_branchfree_gen_ref", "", int16_t("denom", "")) customMethod(""" @NativeType("struct libdivide_s16_branchfree_t") public static LibDivideS16BranchFree libdivide_s16_branchfree_gen(@NativeType("int16_t") short denom, @NativeType("struct libdivide_s16_branchfree_t") LibDivideS16BranchFree __result) { if (denom == 0) { throw new IllegalArgumentException("divider must be != 0"); } int magic, more; int absD = denom < 0 ? -denom : denom; int floor_log_2_d = 31 - Integer.numberOfLeadingZeros(absD); if ((absD & (absD - 1)) == 0) { magic = 0; more = floor_log_2_d | (denom < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); } else { int l = 1 << (15 + floor_log_2_d); magic = l / absD; int rem = l % absD; magic = (magic << 1) + 1; if (absD < rem << 1) { magic++; } more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; if (denom < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; } } __result.magic((short)magic); __result.more((byte)more); return __result; }""") NativeName("libdivide_u16_branchfree_gen")..internal..libdivide_u16_branchfree_t("u16_branchfree_gen_ref", "", uint16_t("denom", "")) customMethod(""" @NativeType("struct libdivide_u16_branchfree_t") public static LibDivideU16BranchFree libdivide_u16_branchfree_gen(@NativeType("uint16_t") short denom, @NativeType("struct libdivide_u16_branchfree_t") LibDivideU16BranchFree __result) { if (denom == 0) { throw new IllegalArgumentException("divider must be != 0"); } if (denom == 1) { throw new IllegalArgumentException("branchfree divider must be != 1"); } int d = Short.toUnsignedInt(denom); int magic, more; int floor_log_2_d = 31 - Integer.numberOfLeadingZeros(d); if ((d & (d - 1)) == 0) { magic = 0; more = floor_log_2_d - 1; } else { int l = 1 << (16 + floor_log_2_d); magic = Integer.divideUnsigned(l, d); int rem = l - magic * d; magic = (magic << 1) + 1; if (d < rem << 1) { magic++; } more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } __result.magic((short)magic); __result.more((byte)(more & LIBDIVIDE_16_SHIFT_MASK)); return __result; }""") NativeName("libdivide_s32_branchfree_gen")..internal..libdivide_s32_branchfree_t("s32_branchfree_gen_ref", "", int32_t("denom", "")) customMethod(""" @NativeType("struct libdivide_s32_branchfree_t") public static LibDivideS32BranchFree libdivide_s32_branchfree_gen(@NativeType("int32_t") int denom, @NativeType("struct libdivide_s32_branchfree_t") LibDivideS32BranchFree __result) { if (denom == 0) { throw new IllegalArgumentException("divider must be != 0"); } int magic, more; int absD = denom < 0 ? -denom : denom; int floor_log_2_d = 31 - Integer.numberOfLeadingZeros(absD); if ((absD & (absD - 1)) == 0) { magic = 0; more = floor_log_2_d | (denom < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); } else { long l = 1L << (31 + floor_log_2_d); magic = (int)(l / absD); int rem = (int)(l % absD); magic = (magic << 1) + 1; if (Integer.compareUnsigned(absD, rem << 1) < 0) { magic++; } more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; if (denom < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; } } __result.magic(magic); __result.more((byte)more); return __result; }""") NativeName("libdivide_u32_branchfree_gen")..internal..libdivide_u32_branchfree_t("u32_branchfree_gen_ref", "", uint32_t("denom", "")) customMethod(""" @NativeType("struct libdivide_u32_branchfree_t") public static LibDivideU32BranchFree libdivide_u32_branchfree_gen(@NativeType("uint32_t") int denom, @NativeType("struct libdivide_u32_branchfree_t") LibDivideU32BranchFree __result) { if (denom == 0) { throw new IllegalArgumentException("divider must be != 0"); } if (denom == 1) { throw new IllegalArgumentException("branchfree divider must be != 1"); } int magic, more; int floor_log_2_d = 31 - Integer.numberOfLeadingZeros(denom); if ((denom & (denom - 1)) == 0) { magic = 0; more = floor_log_2_d - 1; } else { long l = 1L << (32 + floor_log_2_d); magic = (int)mathDivideUnsigned(l, Integer.toUnsignedLong(denom)); int rem = (int)(l - magic * Integer.toUnsignedLong(denom)); magic = (magic << 1) + 1; if (Integer.compareUnsigned(denom, rem << 1) < 0 || Integer.compareUnsigned(rem << 1, rem) < 0) { magic++; } more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } __result.magic(magic); __result.more((byte)(more & LIBDIVIDE_32_SHIFT_MASK)); return __result; }""") NativeName("libdivide_s64_branchfree_gen")..internal..libdivide_s64_branchfree_t("s64_branchfree_gen_ref", "", int64_t("denom", "")) customMethod(""" @NativeType("struct libdivide_s64_branchfree_t") public static LibDivideS64BranchFree libdivide_s64_branchfree_gen(@NativeType("int64_t") long denom, @NativeType("struct libdivide_s64_branchfree_t") LibDivideS64BranchFree __result) { if (denom == 0L) { throw new IllegalArgumentException("divider must be != 0"); } long magic; int more; long absD = denom < 0L ? -denom : denom; int floor_log_2_d = 63 - Long.numberOfLeadingZeros(absD); if ((absD & (absD - 1)) == 0) { magic = 0L; more = floor_log_2_d | (denom < 0L ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); } else { magic = (libdivide_128_div_64_to_64(1L << (floor_log_2_d - 1), 0L, absD, __result.address()) << 1) + 1; long rem = __result.magic(); if (Long.compareUnsigned(absD, rem << 1) < 0) { magic++; } more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; if (denom < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; } } __result.magic(magic); __result.more((byte)more); return __result; } """) NativeName("libdivide_u64_branchfree_gen")..internal..libdivide_u64_branchfree_t("u64_branchfree_gen_ref", "", uint64_t("denom", "")) customMethod(""" @NativeType("struct libdivide_u64_branchfree_t") public static LibDivideU64BranchFree libdivide_u64_branchfree_gen(@NativeType("uint64_t") long denom, @NativeType("struct libdivide_u64_branchfree_t") LibDivideU64BranchFree __result) { if (denom == 0L) { throw new IllegalArgumentException("divider must be != 0"); } if (denom == 1L) { throw new IllegalArgumentException("branchfree divider must be != 1"); } long magic; int more; int floor_log_2_d = 63 - Long.numberOfLeadingZeros(denom); if ((denom & (denom - 1)) == 0) { magic = 0; more = floor_log_2_d - 1; } else { magic = (libdivide_128_div_64_to_64(1L << floor_log_2_d, 0L, denom, __result.address()) << 1) + 1; long rem = __result.magic(); if (Long.compareUnsigned(denom, rem << 1) < 0 || Long.compareUnsigned(rem << 1, rem) < 0) { magic++; } more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } __result.magic(magic); __result.more((byte)(more & LIBDIVIDE_64_SHIFT_MASK)); return __result; }""") NativeName("libdivide_s16_do")..internal..int16_t("s16_do_ref", "", int16_t("numer", ""), libdivide_s16_t.const.p("denom", "")) customMethod( """ public static short libdivide_s16_do(@NativeType("int16_t") short numer, @NativeType("struct libdivide_s16_t const *") LibDivideS16 denom) { return libdivide_s16_do(numer, denom.magic(), denom.more()); } public static short libdivide_s16_do(@NativeType("int16_t") short numer, @NativeType("int16_t") short magic, @NativeType("uint8_t") byte more) { int shift = more & LIBDIVIDE_16_SHIFT_MASK; if (magic == 0) { int sign = more >> 7; int mask = (1 << shift) - 1; int q = numer + ((numer >> 15) & mask); q >>= shift; q = (q ^ sign) - sign; return (short)q; } else { int uq = libdivide_mullhi_s16(magic, numer); if ((more & LIBDIVIDE_ADD_MARKER) != 0) { int sign = more >> 7; uq += (numer ^ sign) - sign; } int q = uq; q >>= shift; q += (q < 0 ? 1 : 0); return (short)q; } }""") NativeName("libdivide_u16_do")..internal..uint16_t("u16_do_ref", "", uint16_t("numer", ""), libdivide_u16_t.const.p("denom", "")) customMethod( """ public static short libdivide_u16_do(@NativeType("uint16_t") short numer, @NativeType("struct libdivide_u16_t const *") LibDivideU16 denom) { return libdivide_u16_do(numer, denom.magic(), denom.more()); } public static short libdivide_u16_do(@NativeType("uint16_t") short numer, @NativeType("uint16_t") short magic, @NativeType("uint8_t") byte more) { int n = Short.toUnsignedInt(numer); if (magic == 0) { return (short)(n >>> more); } else { int q = libdivide_mullhi_u16(magic, numer); if ((more & LIBDIVIDE_ADD_MARKER) != 0) { int t = ((n - q) >>> 1) + q; return (short)(t >>> (more & LIBDIVIDE_16_SHIFT_MASK)); } else { return (short)(q >>> more); } } }""") NativeName("libdivide_s32_do")..internal..int32_t("s32_do_ref", "", int32_t("numer", ""), libdivide_s32_t.const.p("denom", "")) customMethod( """ public static int libdivide_s32_do(@NativeType("int32_t") int numer, @NativeType("struct libdivide_s32_t const *") LibDivideS32 denom) { return libdivide_s32_do(numer, denom.magic(), denom.more()); } public static int libdivide_s32_do(@NativeType("int32_t") int numer, @NativeType("int32_t") int magic, @NativeType("uint8_t") byte more) { int shift = more & LIBDIVIDE_32_SHIFT_MASK; if (magic == 0) { int sign = more >> 7; int mask = (1 << shift) - 1; int q = numer + ((numer >> 31) & mask); q >>= shift; q = (q ^ sign) - sign; return q; } else { int uq = libdivide_mullhi_s32(magic, numer); if ((more & LIBDIVIDE_ADD_MARKER) != 0) { int sign = more >> 7; uq += (numer ^ sign) - sign; } int q = uq; q >>= shift; q += (q < 0 ? 1 : 0); return q; } }""") NativeName("libdivide_u32_do")..internal..uint32_t("u32_do_ref", "", uint32_t("numer", ""), libdivide_u32_t.const.p("denom", "")) customMethod( """ public static int libdivide_u32_do(@NativeType("uint32_t") int numer, @NativeType("struct libdivide_u32_t const *") LibDivideU32 denom) { return libdivide_u32_do(numer, denom.magic(), denom.more()); } public static int libdivide_u32_do(@NativeType("uint32_t") int numer, @NativeType("uint32_t") int magic, @NativeType("uint8_t") byte more) { if (magic == 0) { return numer >>> more; } else { int q = libdivide_mullhi_u32(magic, numer); if ((more & LIBDIVIDE_ADD_MARKER) != 0) { int t = ((numer - q) >>> 1) + q; return t >>> (more & LIBDIVIDE_32_SHIFT_MASK); } else { return q >>> more; } } }""") NativeName("libdivide_s64_do")..internal..int64_t("s64_do_ref", "", int64_t("numer", ""), libdivide_s64_t.const.p("denom", "")) customMethod( """ public static long libdivide_s64_do(@NativeType("int64_t") long numer, @NativeType("struct libdivide_s64_t const *") LibDivideS64 denom) { return libdivide_s64_do(numer, denom.magic(), denom.more()); } public static long libdivide_s64_do(@NativeType("int64_t") long numer, @NativeType("int64_t") long magic, @NativeType("uint8_t") byte more) { int shift = more & LIBDIVIDE_64_SHIFT_MASK; if (magic == 0L) { long mask = (1L << shift) - 1L; long q = numer + ((numer >> 63) & mask); q >>= shift; long sign = more >> 7; q = (q ^ sign) - sign; return q; } else { long uq = mathMultiplyHighS64(magic, numer); if ((more & LIBDIVIDE_ADD_MARKER) != 0) { long sign = more >> 7; uq += (numer ^ sign) - sign; } long q = uq; q >>= shift; q += (q < 0 ? 1 : 0); return q; } }""") NativeName("libdivide_u64_do")..internal..uint64_t("u64_do_ref", "", uint64_t("numer", ""), libdivide_u64_t.const.p("denom", "")) customMethod( """ public static long libdivide_u64_do(@NativeType("uint64_t") long numer, @NativeType("struct libdivide_u64_t const *") LibDivideU64 denom) { return libdivide_u64_do(numer, denom.magic(), denom.more()); } public static long libdivide_u64_do(@NativeType("uint64_t") long numer, @NativeType("uint64_t") long magic, @NativeType("uint8_t") byte more) { if (magic == 0L) { return numer >>> more; } else { long q = mathMultiplyHighU64(magic, numer); if ((more & LIBDIVIDE_ADD_MARKER) != 0) { long t = ((numer - q) >>> 1) + q; return t >>> (more & LIBDIVIDE_64_SHIFT_MASK); } else { return q >>> more; } } }""") NativeName("libdivide_s16_branchfree_do")..internal..int16_t("s16_branchfree_do_ref", "", int16_t("numer", ""), libdivide_s16_branchfree_t.const.p("denom", "")) customMethod( """ public static short libdivide_s16_branchfree_do(@NativeType("int16_t") short numer, @NativeType("struct libdivide_s16_branchfree_t const *") LibDivideS16BranchFree denom) { return libdivide_s16_branchfree_do(numer, denom.magic(), denom.more()); } public static short libdivide_s16_branchfree_do(@NativeType("int16_t") short numer, @NativeType("int16_t") short magic, @NativeType("uint8_t") byte more) { int shift = more & LIBDIVIDE_16_SHIFT_MASK; int sign = more >> 7; int q = libdivide_mullhi_s16(magic, numer); q += numer; int q_sign = q >> 15; q += q_sign & ((1 << shift) - (magic == 0 ? 1 : 0)); q >>= shift; q = (q ^ sign) - sign; return (short)q; }""") NativeName("libdivide_u16_branchfree_do")..internal..uint16_t("u16_branchfree_do_ref", "", uint16_t("numer", ""), libdivide_u16_branchfree_t.const.p("denom", "")) customMethod( """ public static short libdivide_u16_branchfree_do(@NativeType("uint16_t") short numer, @NativeType("struct libdivide_u16_branchfree_t const *") LibDivideU16BranchFree denom) { return libdivide_u16_branchfree_do(numer, denom.magic(), denom.more()); } public static short libdivide_u16_branchfree_do(@NativeType("uint16_t") short numer, @NativeType("uint16_t") short magic, @NativeType("uint8_t") byte more) { int q = libdivide_mullhi_u16(magic, numer); int t = ((Short.toUnsignedInt(numer) - q) >>> 1) + q; return (short)(t >>> more); }""") NativeName("libdivide_s32_branchfree_do")..internal..int32_t("s32_branchfree_do_ref", "", int32_t("numer", ""), libdivide_s32_branchfree_t.const.p("denom", "")) customMethod( """ public static int libdivide_s32_branchfree_do(@NativeType("int32_t") int numer, @NativeType("struct libdivide_s32_branchfree_t const *") LibDivideS32BranchFree denom) { return libdivide_s32_branchfree_do(numer, denom.magic(), denom.more()); } public static int libdivide_s32_branchfree_do(@NativeType("int32_t") int numer, @NativeType("int32_t") int magic, @NativeType("uint8_t") byte more) { int shift = more & LIBDIVIDE_32_SHIFT_MASK; int sign = more >> 7; int q = libdivide_mullhi_s32(magic, numer); q += numer; int q_sign = q >> 31; q += q_sign & ((1 << shift) - (magic == 0 ? 1 : 0)); q >>= shift; q = (q ^ sign) - sign; return q; }""") NativeName("libdivide_u32_branchfree_do")..internal..uint32_t("u32_branchfree_do_ref", "", uint32_t("numer", ""), libdivide_u32_branchfree_t.const.p("denom", "")) customMethod( """ public static int libdivide_u32_branchfree_do(@NativeType("uint32_t") int numer, @NativeType("struct libdivide_u32_branchfree_t const *") LibDivideU32BranchFree denom) { return libdivide_u32_branchfree_do(numer, denom.magic(), denom.more()); } public static int libdivide_u32_branchfree_do(@NativeType("uint32_t") int numer, @NativeType("uint32_t") int magic, @NativeType("uint8_t") byte more) { int q = libdivide_mullhi_u32(magic, numer); int t = ((numer - q) >>> 1) + q; return t >>> more; }""") NativeName("libdivide_s64_branchfree_do")..internal..int64_t("s64_branchfree_do_ref", "", int64_t("numer", ""), libdivide_s64_branchfree_t.const.p("denom", "")) customMethod( """ public static long libdivide_s64_branchfree_do(@NativeType("int64_t") long numer, @NativeType("struct libdivide_s64_branchfree_t const *") LibDivideS64BranchFree denom) { return libdivide_s64_branchfree_do(numer, denom.magic(), denom.more()); } public static long libdivide_s64_branchfree_do(@NativeType("int64_t") long numer, @NativeType("int64_t") long magic, @NativeType("uint8_t") byte more) { int shift = more & LIBDIVIDE_64_SHIFT_MASK; long sign = more >> 7; long q = mathMultiplyHighS64(magic, numer); q += numer; long q_sign = q >> 63; q += q_sign & ((1L << shift) - (magic == 0 ? 1 : 0)); q >>= shift; q = (q ^ sign) - sign; return q; }""") NativeName("libdivide_u64_branchfree_do")..internal..uint64_t("u64_branchfree_do_ref", "", uint64_t("numer", ""), libdivide_u64_branchfree_t.const.p("denom", "")) customMethod( """ public static long libdivide_u64_branchfree_do(@NativeType("uint64_t") long numer, @NativeType("struct libdivide_u64_branchfree_t const *") LibDivideU64BranchFree denom) { return libdivide_u64_branchfree_do(numer, denom.magic(), denom.more()); } public static long libdivide_u64_branchfree_do(@NativeType("uint64_t") long numer, @NativeType("uint64_t") long magic, @NativeType("uint8_t") byte more) { long q = mathMultiplyHighU64(magic, numer); long t = ((numer - q) >>> 1) + q; return t >>> more; }""") int16_t("s16_recover", "", libdivide_s16_t.const.p("denom", "")) uint16_t("u16_recover", "", libdivide_u16_t.const.p("denom", "")) int32_t("s32_recover", "", libdivide_s32_t.const.p("denom", "")) uint32_t("u32_recover", "", libdivide_u32_t.const.p("denom", "")) int64_t("s64_recover", "", libdivide_s64_t.const.p("denom", "")) uint64_t("u64_recover", "", libdivide_u64_t.const.p("denom", "")) int16_t("s16_branchfree_recover", "", libdivide_s16_branchfree_t.const.p("denom", "")) uint16_t("u16_branchfree_recover", "", libdivide_u16_branchfree_t.const.p("denom", "")) int32_t("s32_branchfree_recover", "", libdivide_s32_branchfree_t.const.p("denom", "")) uint32_t("u32_branchfree_recover", "", libdivide_u32_branchfree_t.const.p("denom", "")) int64_t("s64_branchfree_recover", "", libdivide_s64_branchfree_t.const.p("denom", "")) uint64_t("u64_branchfree_recover", "", libdivide_u64_branchfree_t.const.p("denom", "")) // Helper methods customMethod(""" private static long libdivide_128_div_64_to_64(long u1, long u0, long v, long remainder) { long b = (1L << 32); long un64, un10; int s = Long.numberOfLeadingZeros(v); if (s > 0) { v <<= s; un64 = (u1 << s) | ((u0 >>> (64 - s)) & (-s >> 31)); un10 = u0 << s; } else { un64 = u1 | u0; un10 = u0; } long vn1 = v >>> 32; long vn0 = v & 0xFFFF_FFFFL; long un1 = un10 >>> 32; long un0 = un10 & 0xFFFF_FFFFL; long q1 = mathDivideUnsigned(un64, vn1); long rhat = un64 - q1 * vn1; while (Long.compareUnsigned(b, q1) < 0 || Long.compareUnsigned(b * rhat + un1, q1 * vn0) <= 0) { q1--; rhat += vn1; if (rhat >= b) { break; } } long un21 = un64 * b + un1 - q1 * v; long q0 = mathDivideUnsigned(un21, vn1); rhat = un21 - q0 * vn1; while (Long.compareUnsigned(b, q0) < 0 || Long.compareUnsigned(b * rhat + un0, q0 * vn0) <= 0) { q0--; rhat += vn1; if (rhat >= b) { break; } } memPutLong(remainder, (un21 * b + un0 - q0 * v) >>> s); return q1 * b + q0; } private static int libdivide_mullhi_s16(short x, short y) { return (x * y) >> 16; } private static int libdivide_mullhi_u16(short x, short y) { return ((x & 0xFFFF) * (y & 0xFFFF)) >>> 16; } private static int libdivide_mullhi_s32(int x, int y) { return (int)(((long)x * y) >> 32); } private static int libdivide_mullhi_u32(int x, int y) { return (int)(((x & 0xFFFF_FFFFL) * (y & 0xFFFF_FFFFL)) >>> 32); }""") }
bsd-3-clause
3fa7ee15a83fce03d7d5b3c72e14dc27
38.050868
251
0.542225
3.376676
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_bindless_texture.kt
4
15237
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_bindless_texture = "ARBBindlessTexture".nativeClassGL("ARB_bindless_texture", postfix = ARB) { documentation = """ Native bindings to the $registryLink extension. This extension allows OpenGL applications to access texture objects in shaders without first binding each texture to one of a limited number of texture image units. Using this extension, an application can query a 64-bit unsigned integer texture handle for each texture that it wants to access and then use that handle directly in GLSL or assembly-based shaders. The ability to access textures without having to bind and/or re-bind them is similar to the capability provided by the ${NV_shader_buffer_load.link} extension that allows shaders to access buffer objects without binding them. In both cases, these extensions significantly reduce the amount of API and internal GL driver overhead needed to manage resource bindings. This extension also provides similar capability for the image load, store, and atomic functionality provided by OpenGL 4.2 and the ${ARB_shader_image_load_store.link} and ${EXT_shader_image_load_store.link} extensions, where a texture can be accessed without first binding it to an image unit. An image handle can be extracted from a texture object using an API with a set of parameters similar to those for #BindImageTextureEXT(). This extension adds no new data types to GLSL. Instead, it uses existing sampler and image data types and allows them to be populated with texture and image handles. This extension does permit sampler and image data types to be used in more contexts than in unextended GLSL 4.00. In particular, sampler and image types may be used as shader inputs/outputs, temporary variables, and uniform block members, and may be assigned to by shader code. Constructors are provided to convert unsigned integer values to and from sampler and image data types. Additionally, new APIs are provided to load values for sampler and image uniforms with 64-bit handle inputs. The use of existing integer-based Uniform* APIs is still permitted, in which case the integer specified will identify a texture image or image unit. For samplers and images with values specified as texture image or image units, the GL implemenation will translate the unit number to an internal handle as required. To access texture or image resources using handles, the handles must first be made resident. Accessing a texture or image by handle without first making it resident can result in undefined results, including program termination. Since the amount of texture memory required by an application may exceed the amount of memory available to the system, this extension provides API calls allowing applications to manage overall texture memory consumption by making a texture resident and non-resident as required. Requires ${GL40.core}. """ IntConstant( "Accepted by the {@code type} parameter of VertexAttribLPointer.", "UNSIGNED_INT64_ARB"..0x140F ) GLuint64( "GetTextureHandleARB", """ Creates a texture handle using the current state of the texture named {@code texture}, including any embedded sampler state. See #GetTextureSamplerHandleARB() for details. """, GLuint("texture", "the texture object") ) GLuint64( "GetTextureSamplerHandleARB", """ Creates a texture handle using the current non-sampler state from the texture named {@code texture} and the sampler state from the sampler object {@code sampler}. In both cases, a 64-bit unsigned integer handle is returned. The error #INVALID_VALUE is generated if {@code texture} is zero or is not the name of an existing texture object or if {@code sampler} is zero or is not the name of an existing sampler object. The error #INVALID_OPERATION is generated if the texture object {@code texture} is not complete. If an error occurs, a handle of zero is returned. The error #INVALID_OPERATION is generated if the border color (taken from the embedded sampler for GetTextureHandleARB or from the {@code sampler} for GetTextureSamplerHandleARB) is not one of the following allowed values. If the texture's base internal format is signed or unsigned integer, allowed values are (0,0,0,0), (0,0,0,1), (1,1,1,0), and (1,1,1,1). If the base internal format is not integer, allowed values are (0.0,0.0,0.0,0.0), (0.0,0.0,0.0,1.0), (1.0,1.0,1.0,0.0), and (1.0,1.0,1.0,1.0). The handle for each texture or texture/sampler pair is unique; the same handle will be returned if GetTextureHandleARB is called multiple times for the same texture or if GetTextureSamplerHandleARB is called multiple times for the same texture/sampler pair. When a texture object is referenced by one or more texture handles, the texture parameters of the object may not be changed, and the size and format of the images in the texture object may not be re-specified. The error #INVALID_OPERATION is generated if the functions TexImage*, CopyTexImage*, CompressedTexImage*, TexBuffer*, or TexParameter* are called to modify a texture object referenced by one or more texture handles. The contents of the images in a texture object may still be updated via commands such as TexSubImage*, CopyTexSubImage*, and CompressedTexSubImage*, and by rendering to a framebuffer object, even if the texture object is referenced by one or more texture handles. The error #INVALID_OPERATION is generated by #BufferData() if it is called to modify a buffer object bound to a buffer texture while that texture object is referenced by one or more texture handles. The contents of the buffer object may still be updated via buffer update commands such as #BufferSubData() and MapBuffer*, or via the texture update commands, even if the buffer is bound to a texture while that buffer texture object is referenced by one or more texture handles. When a sampler object is referenced by one or more texture handles, the sampler parameters of the object may not be changed. The error #INVALID_OPERATION is generated when calling SamplerParameter* functions to modify a sampler object referenced by one or more texture handles. """, GLuint("texture", "the texture object"), GLuint("sampler", "the sampler object") ) void( "MakeTextureHandleResidentARB", """ Make a texture handle resident, so that it is accessible to shaders for texture mapping operations. While the texture handle is resident, it may be used in texture mapping operations. If a shader attempts to perform a texture mapping operation using a handle that is not resident, the results of that operation are undefined and may lead to application termination. When a texture handle is resident, the texture it references is also considered resident for the purposes of the #AreTexturesResident() command. The error #INVALID_OPERATION is generated if {@code handle} is not a valid texture handle, or if {@code handle} is already resident in the current GL context. """, GLuint64("handle", "the texture handle") ) void( "MakeTextureHandleNonResidentARB", """ Makes a texture handle inaccessible to shaders. The error #INVALID_OPERATION is generated if {@code handle} is not a valid texture handle, or if {@code handle} is not resident in the current GL context. """, GLuint64("handle", "the texture handle") ) GLuint64( "GetImageHandleARB", """ Creates and returns an image handle for level {@code level} of the texture named {@code texture}. If {@code layered} is #TRUE, a handle is created for the entire texture level. If {@code layered} is #FALSE, a handle is created for only the layer {@code layer} of the texture level. {@code format} specifies a format used to interpret the texels of the image when used for image loads, stores, and atomics, and has the same meaning as the {@code format} parameter of #BindImageTextureEXT(). A 64-bit unsigned integer handle is returned if the command succeeds; otherwise, zero is returned. The error #INVALID_VALUE is generated by GetImageHandleARB if: ${ul( "{@code texture} is zero or not the name of an existing texture object;", "the image for the texture level {@code level} doesn't exist (i.e., has a size of zero in {@code texture}); or", "{@code layered} is FALSE and {@code layer} is greater than or equal to the number of layers in the image at level {@code level}." )} The error #INVALID_OPERATION is generated by GetImageHandleARB if: ${ul( "the texture object {@code texture} is not complete (section 3.9.14);", """ {@code layered} is TRUE and the texture is not a three-dimensional, one-dimensional array, two dimensional array, cube map, or cube map array texture. """ )} When a texture object is referenced by one or more image handles, the texture parameters of the object may not be changed, and the size and format of the images in the texture object may not be re-specified. The error #INVALID_OPERATION is generated when calling TexImage*, CopyTexImage*, CompressedTexImage*, TexBuffer*, or TexParameter* functions while a texture object is referenced by one or more image handles. The contents of the images in a texture object may still be updated via commands such as TexSubImage*, CopyTexSubImage*, and CompressedTexSubImage*, and by rendering to a framebuffer object, even if the texture object is referenced by one or more image handles. The error #INVALID_OPERATION is generated by #BufferData() if it is called to modify a buffer object bound to a buffer texture while that texture object is referenced by one or more image handles. The contents of the buffer object may still be updated via buffer update commands such as #BufferSubData() and MapBuffer*, or via the texture update commands, even if the buffer is bound to a texture while that buffer texture object is referenced by one or more image handles. The handle returned for each combination of {@code texture}, {@code level}, {@code layered}, {@code layer}, and {@code format} is unique; the same handle will be returned if GetImageHandleARB is called multiple times with the same parameters. """, GLuint("texture", "the texture object"), GLint("level", "the texture level"), GLboolean("layered", "the layered flag"), GLint("layer", "the texture layer"), GLenum("format", "the texture format") ) void( "MakeImageHandleResidentARB", """ Makes an image handle resident, so that it is accessible to shaders for image loads, stores, and atomic operations. {@code access} specifies whether the texture bound to the image handle will be treated as #READ_ONLY, #WRITE_ONLY, or #READ_WRITE. If a shader reads from an image handle made resident as #WRITE_ONLY, or writes to an image handle made resident as #READ_ONLY, the results of that shader operation are undefined and may lead to application termination. The error #INVALID_OPERATION is generated if {@code handle} is not a valid image handle, or if {@code handle} is already resident in the current GL context. While the image handle is resident, it may be used in image load, store, and atomic operations. If a shader attempts to perform an image operation using a handle that is not resident, the results of that operation are undefined and may lead to application termination. When an image handle is resident, the texture it references is not necessarily considered resident for the purposes of the #AreTexturesResident() command. """, GLuint64("handle", "the image handle"), GLenum("access", "the access type", "#READ_ONLY #WRITE_ONLY #READ_WRITE") ) void( "MakeImageHandleNonResidentARB", "Makes an image handle inaccessible to shaders.", GLuint64("handle", "the image handle") ) val location = GLint("location", "the uniform location") val UniformHandleui64ARB = void( "UniformHandleui64ARB", "Loads a 64-bit unsigned integer handle into a uniform location corresponding to sampler or image variable types.", location, GLuint64("value", "the handle value") ) val UniformHandleui64vARB = void( "UniformHandleui64vARB", "Loads {@code count} 64-bit unsigned integer handles into a uniform location corresponding to sampler or image variable types.", location, AutoSize("values")..GLsizei("count", "the number of handles to load"), GLuint64.const.p("values", "a buffer from which to load the handles") ) void( "ProgramUniformHandleui64ARB", "DSA version of #UniformHandleui64ARB().", GLuint("program", "the program object"), location, UniformHandleui64ARB["value"] ) void( "ProgramUniformHandleui64vARB", "DSA version of #UniformHandleui64vARB().", GLuint("program", "the program object"), location, UniformHandleui64vARB["count"], UniformHandleui64vARB["values"] ) GLboolean( "IsTextureHandleResidentARB", "Returns #TRUE if the specified texture handle is resident in the current context.", GLuint64("handle", "the texture handle") ) GLboolean( "IsImageHandleResidentARB", "Returns #TRUE if the specified image handle is resident in the current context.", GLuint64("handle", "the image handle") ) void( "VertexAttribL1ui64ARB", "Specifies the 64-bit unsigned integer handle value of a generic vertex attribute.", GLuint("index", "the index of the generic vertex attribute to be modified"), GLuint64("x", "the handle value") ) void( "VertexAttribL1ui64vARB", "Pointer version of #VertexAttribL1ui64ARB().", GLuint("index", "the index of the generic vertex attribute to be modified"), Check(1)..GLuint64.const.p("v", "the vertex attribute buffer") ) void( "GetVertexAttribLui64vARB", "Returns the 64-bit unsigned integer handle value of a generic vertex attribute parameter.", GLuint("index", "the generic vertex attribute index"), GLenum("pname", "the parameter to query"), Check(1)..ReturnParam..GLuint64.p("params", "a buffer in which to place the returned data") ) }
bsd-3-clause
21b997bc1244fb8d7e3ce5d40fb8af05
56.501887
160
0.702763
4.776489
false
false
false
false
LanderlYoung/Jenny
compiler/src/main/java/io/github/landerlyoung/jenny/AbsCodeGenerator.kt
1
2646
/** * Copyright 2016 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.landerlyoung.jenny import javax.lang.model.element.ElementKind import javax.lang.model.element.TypeElement import javax.tools.Diagnostic /** * Author: [email protected] * Date: 2016-06-05 * Time: 00:42 * Life with Passion, Code with Creativity. */ abstract class AbsCodeGenerator(protected val mEnv: Environment, protected val mClazz: TypeElement) { protected val mHelper: HandyHelper /** like com.example_package.SomeClass$InnerClass */ protected val mClassName: String /** * like com_example_1package_SomeClass_InnerClass * NestedClass * com.young.jennysampleapp.ComputeIntensiveClass$NestedNativeClass * com_young_jennysampleapp_ComputeIntensiveClass_00024NestedNativeClass */ protected val mJNIClassName: String /** like com/example_package/SomeClass$InnerClass */ protected val mSlashClassName: String /** like String for java.lang.String class */ protected val mSimpleClassName: String init { if (mClazz.kind != ElementKind.CLASS && mClazz.kind != ElementKind.INTERFACE && mClazz.kind != ElementKind.ENUM && mClazz.kind != ElementKind.ANNOTATION_TYPE) { error("type element $mClazz is not class type") } mHelper = HandyHelper(mEnv) mClassName = mHelper.getClassName(mClazz) mJNIClassName = mHelper.toJNIClassName(mClassName) mSlashClassName = mHelper.getSlashClassName(mClassName) mSimpleClassName = mClazz.simpleName.toString() } abstract fun doGenerate(): CppClass fun log(msg: String) { mEnv.messager.printMessage(Diagnostic.Kind.NOTE, LOG_PREFIX + msg + "\n") } fun warn(msg: String) { mEnv.messager.printMessage(Diagnostic.Kind.WARNING, LOG_PREFIX + msg + "\n") } fun error(msg: String) { mEnv.messager.printMessage(Diagnostic.Kind.ERROR, LOG_PREFIX + msg + "\n") } companion object { private const val LOG_PREFIX = "Jenny | " } }
apache-2.0
b52113ffbd0c41348c70b2ec8443d91d
32.075
101
0.69161
4.102326
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opencl/src/templates/kotlin/opencl/CLBinding.kt
4
6367
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opencl import org.lwjgl.generator.* import java.io.* private val NativeClass.capName: String get() = if (templateName.startsWith(prefix)) { if (prefix == "CL") "OpenCL${templateName.substring(2)}" else templateName } else { "${prefixTemplate}_$templateName" } private const val CAPABILITIES_CLASS = "CLCapabilities" private val CLBinding = Generator.register(object : APIBinding( Module.OPENCL, CAPABILITIES_CLASS, APICapabilities.JAVA_CAPABILITIES ) { override fun printCustomJavadoc(writer: PrintWriter, function: Func, documentation: String): Boolean { if (function.nativeClass.templateName.startsWith("CL")) { writer.printOpenCLJavaDoc(documentation, function.nativeName, if (function.has<DeprecatedCL>()) function.get<DeprecatedCL>().after else "2.1") // TODO: update to 2.2 when available return true } return false } private fun PrintWriter.printOpenCLJavaDoc(documentation: String, function: String, version: String) { val link = url("https://www.khronos.org/registry/OpenCL/sdk/$version/docs/man/xhtml/$function.html", "Reference Page") val injectedJavaDoc = if (version != "2.1") "$link - <em>This function is deprecated after OpenCL $version</em>" else link if (documentation.isEmpty()) println("$t/** $injectedJavaDoc */") else { if (documentation.indexOf('\n') == -1) { println("$t/**") print("$t * ") print(documentation.substring("$t/** ".length, documentation.length - " */".length)) } else { print(documentation.substring(0, documentation.length - "\n$t */".length)) } print("\n$t * ") print("\n$t * @see $injectedJavaDoc") println("\n$t */") } } override fun shouldCheckFunctionAddress(function: Func): Boolean = function.nativeClass.templateName != "CL10" override fun generateFunctionAddress(writer: PrintWriter, function: Func) { writer.println("$t${t}long $FUNCTION_ADDRESS = CL.getICD().${function.name};") } private fun PrintWriter.checkExtensionFunctions(nativeClass: NativeClass) { val capName = nativeClass.capName println("\n${t}private boolean check_${nativeClass.templateName}(Set<String> ext) {") print("$t${t}return ext.contains(\"$capName\") && checkExtension(\"$capName\", checkFunctions(") nativeClass.printPointers(this, { it.name }) println("));") println("$t}") } init { javaImport( "static org.lwjgl.system.APIUtil.*", "static org.lwjgl.system.Checks.*" ) documentation = """ Defines the capabilities of an OpenCL platform or device. The instance returned by {@link CL\#createPlatformCapabilities} exposes the functionality present on either the platform or any of its devices. This is unlike the #PLATFORM_EXTENSIONS string, which returns only platform functionality, supported across all platform devices. The instance returned by {@link CL\#createDeviceCapabilities} exposes only the functionality available on that particular device. """ } override fun PrintWriter.generateJava() { generateJavaPreamble() println("public class $CAPABILITIES_CLASS {\n") val classes = super.getClasses("CL") val addresses = classes.getFunctionPointers() println("${t}public final long") println(addresses.map(Func::name).joinToString(",\n$t$t", prefix = "$t$t", postfix = ";\n")) classes.forEach { println(it.getCapabilityJavadoc()) println("${t}public final boolean ${it.capName};") } // ICD/Platform constructor println("\n$t$CAPABILITIES_CLASS(FunctionProvider provider, Set<String> ext) {") println(addresses.joinToString(",\n$t$t$t", prefix = "$t${t}this(ext,\n$t$t$t", postfix = "\n$t$t);\n$t}") { "provider.getFunctionAddress(${it.functionAddress})" }) // Device constructor println("\n$t$CAPABILITIES_CLASS(CLCapabilities caps, Set<String> ext) {") println(addresses.joinToString(",\n$t$t$t", prefix = "$t${t}this(ext,\n$t$t$t", postfix = "\n$t$t);\n$t}") { "caps.${it.name}" }) // Common constructor println("\n${t}private $CAPABILITIES_CLASS(Set<String> ext, long... functions) {") println(addresses.mapIndexed { i, function -> "${function.name} = functions[$i];" }.joinToString("\n$t$t", prefix = "$t$t")) for (extension in classes) { val capName = extension.capName print( if (extension.hasNativeFunctions) "\n$t$t$capName = check_${extension.templateName}(ext);" else "\n$t$t$capName = ext.contains(\"$capName\");" ) } print(""" } private static boolean checkExtension(String extension, boolean supported) { if (supported) { return true; } apiLog("[CL] " + extension + " was reported as available but an entry point is missing."); return false; } """) for (extension in classes) { if (!extension.hasNativeFunctions) { continue } checkExtensionFunctions(extension) } println("\n}") } }) // DSL Extensions fun String.nativeClassCL(templateName: String, postfix: String = "", init: (NativeClass.() -> Unit)? = null) = nativeClass(Module.OPENCL, templateName, prefix = "CL", postfix = postfix, prefixTemplate = "cl", binding = CLBinding, init = init) val NativeClass.extensionLink: String get() = extensionLink(templateName) fun NativeClass.extensionLink( txt: String, prefix: String = txt.substring(0, txt.indexOf('_')), name: String = templateName ) = url("http://www.khronos.org/registry/OpenCL/extensions/$prefix/cl_$txt.txt", name) val NativeClass.extensionName: String get() = "<strong>$templateName</strong>"
bsd-3-clause
acb7dcc994ab32021725b9b12714f2bb
35.597701
192
0.604366
4.477496
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/page/PageBackStackItem.kt
1
443
package org.wikipedia.page import org.wikipedia.history.HistoryEntry class PageBackStackItem(var title: PageTitle?, var historyEntry: HistoryEntry?, var scrollY: Int = 0) { constructor(title: PageTitle?, historyEntry: HistoryEntry?) : this(title, historyEntry, 0) init { // TODO: remove this crash probe upon fixing require(!(title == null || historyEntry == null)) { "Nonnull parameter is in fact null." } } }
apache-2.0
42fdba0702c8e97e13e20798281672dc
33.076923
103
0.697517
4.43
false
false
false
false
dahlstrom-g/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenStructureWizardStep.kt
10
3613
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.wizards import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.externalSystem.service.project.wizard.MavenizedStructureWizardStep import com.intellij.openapi.externalSystem.util.ui.DataView import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.io.FileUtil.createSequentFileName import com.intellij.ui.layout.* import icons.OpenapiIcons import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.project.MavenProjectsManager import java.io.File import javax.swing.Icon class MavenStructureWizardStep( private val builder: AbstractMavenModuleBuilder, context: WizardContext ) : MavenizedStructureWizardStep<MavenProject>(context) { override fun getHelpId() = "reference.dialogs.new.project.fromScratch.maven" override fun getBuilderId(): String? = builder.builderId override fun createView(data: MavenProject) = MavenDataView(data) override fun findAllParents(): List<MavenProject> { val project = context.project ?: return emptyList() val projectsManager = MavenProjectsManager.getInstance(project) return projectsManager.projects } override fun updateProjectData() { context.projectBuilder = builder builder.aggregatorProject = parentData builder.parentProject = parentData builder.projectId = MavenId(groupId, artifactId, version) builder.setInheritedOptions( parentData?.mavenId?.groupId == groupId, parentData?.mavenId?.version == version ) builder.name = entityName builder.contentEntryPath = location } override fun _init() { builder.name?.let { entityName = it } builder.projectId?.let { projectId -> projectId.groupId?.let { groupId = it } projectId.artifactId?.let { artifactId = it } projectId.version?.let { version = it } } } override fun suggestName(): String { val projectFileDirectory = File(context.projectFileDirectory) val moduleNames = findAllModules().map { it.name }.toSet() val artifactIds = parentsData.map { it.mavenId.artifactId }.toSet() return createSequentFileName(projectFileDirectory, "untitled", "") { !it.exists() && it.name !in moduleNames && it.name !in artifactIds } } override fun ValidationInfoBuilder.validateGroupId(): ValidationInfo? { return validateCoordinates() ?: superValidateGroupId() } override fun ValidationInfoBuilder.validateArtifactId(): ValidationInfo? { return validateCoordinates() ?: superValidateArtifactId() } private fun ValidationInfoBuilder.validateCoordinates(): ValidationInfo? { val mavenIds = parentsData.map { it.mavenId.groupId to it.mavenId.artifactId }.toSet() if (groupId to artifactId in mavenIds) { val message = MavenWizardBundle.message("maven.structure.wizard.entity.coordinates.already.exists.error", context.presentationName.capitalize(), "$groupId:$artifactId") return error(message) } return null } class MavenDataView(override val data: MavenProject) : DataView<MavenProject>() { override val location: String = data.directory override val icon: Icon = OpenapiIcons.RepositoryLibraryLogo override val presentationName: String = data.displayName override val groupId: String = data.mavenId.groupId ?: "" override val version: String = data.mavenId.version ?: "" } }
apache-2.0
2c50a4f3a1e89fad14be969d5a694826
39.155556
140
0.745918
4.74147
false
false
false
false
openium/auvergne-webcams-droid
app/src/main/java/fr/openium/auvergnewebcams/ui/settings/RefreshDelayPickerDialog.kt
1
1785
package fr.openium.auvergnewebcams.ui.settings import android.app.Dialog import android.os.Bundle import android.widget.Button import android.widget.NumberPicker import fr.openium.auvergnewebcams.Constants import fr.openium.auvergnewebcams.R import fr.openium.auvergnewebcams.base.AbstractDialog import fr.openium.auvergnewebcams.event.eventNewRefreshDelayValue import fr.openium.auvergnewebcams.utils.PreferencesUtils /** * Created by Openium on 19/02/2019. */ class RefreshDelayPickerDialog : AbstractDialog() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = Dialog(requireContext()).apply { setContentView(R.layout.dialog_refresh_delay_picker) val delayValue = arguments?.getInt(Constants.KEY_DELAY_VALUE, PreferencesUtils.DEFAULT_REFRESH_DELAY) ?: PreferencesUtils.DEFAULT_REFRESH_DELAY val numberPicker = findViewById<NumberPicker>(R.id.numberPickerDialogRefreshDelay).apply { minValue = MIN_VALUE maxValue = MAX_VALUE value = delayValue } findViewById<Button>(R.id.buttonCancelDialogRefreshDelay).setOnClickListener { dismiss() } findViewById<Button>(R.id.buttonOkDialogRefreshDelay).setOnClickListener { eventNewRefreshDelayValue.accept(numberPicker.value) dismiss() } } companion object { private const val MIN_VALUE = 1 private const val MAX_VALUE = 120 fun newInstance(currentValue: Int): RefreshDelayPickerDialog = RefreshDelayPickerDialog().apply { arguments = Bundle().apply { putInt(Constants.KEY_DELAY_VALUE, currentValue) } } } }
mit
2ea9304f1bb490f3548d3526e0f1c7d7
34.019608
113
0.677871
5.014045
false
false
false
false
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter5/5.11.Typealias.kt
4
947
typealias Result = Map<String, Long> interface Exchange<I, O> interface HttpRequest interface HttpResponse typealias HttpExchange = Exchange<HttpRequest, HttpResponse> fun process1(exchange: Exchange<HttpRequest, HttpResponse>): Exchange<HttpRequest, HttpResponse> = TODO() fun process2(exchange: HttpExchange): HttpExchange = TODO() typealias String1 = String typealias String2 = String fun printString(str: String1): Unit = println(str) fun aliases() { val a: String2 = "I am a String" printString(a) } fun volume(width: Int, length: Int, height: Int): Int = width * length * height typealias Width = Int typealias Length = Int typealias Height = Int fun volume2(width: Width, length: Length, height: Height): Int = width * length * height fun volume2test() { val width: Width = 2 val length: Length = 3 val height: Height = 4 volume2(width, length, height) volume2(height, width, length) volume2(width, width, width) }
mit
15362d0a42a301daee6ad3715028c08a
24.621622
105
0.73812
3.728346
false
false
false
false
google/intellij-community
build/tasks/src/org/jetbrains/intellij/build/io/ssh.kt
2
3715
// 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.io import net.schmizz.sshj.xfer.LocalDestFile import net.schmizz.sshj.xfer.LocalFileFilter import net.schmizz.sshj.xfer.LocalSourceFile import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption import java.nio.file.attribute.PosixFilePermission import java.util.* import java.util.concurrent.TimeUnit internal class NioFileDestination(private val file: Path) : LocalDestFile { override fun getLength(): Long { return try { Files.size(file) } catch (e: IOException) { 0 } } override fun getOutputStream(): OutputStream = Files.newOutputStream(file) override fun getOutputStream(append: Boolean): OutputStream = Files.newOutputStream(file, StandardOpenOption.APPEND) override fun getChild(name: String?) = throw UnsupportedOperationException() override fun getTargetFile(filename: String): LocalDestFile { return this } override fun getTargetDirectory(dirname: String?): LocalDestFile { return this } override fun setPermissions(perms: Int) { Files.setPosixFilePermissions(file, fromOctalFileMode(perms)) } override fun setLastAccessedTime(t: Long) { // ignore } override fun setLastModifiedTime(t: Long) { // ignore } } internal class NioFileSource(private val file: Path, private val filePermission: Int = -1) : LocalSourceFile { override fun getName() = file.fileName.toString() override fun getLength() = Files.size(file) override fun getInputStream(): InputStream = Files.newInputStream(file) override fun getPermissions(): Int { return if (filePermission == -1) toOctalFileMode(Files.getPosixFilePermissions(file)) else filePermission } override fun isFile() = true override fun isDirectory() = false override fun getChildren(filter: LocalFileFilter): Iterable<LocalSourceFile> = emptyList() override fun providesAtimeMtime() = false override fun getLastAccessTime() = System.currentTimeMillis() / 1000 override fun getLastModifiedTime() = TimeUnit.MILLISECONDS.toSeconds(Files.getLastModifiedTime(file).toMillis()) } private fun toOctalFileMode(permissions: Set<PosixFilePermission?>): Int { var result = 0 for (permissionBit in permissions) { when (permissionBit) { PosixFilePermission.OWNER_READ -> result = result or 256 PosixFilePermission.OWNER_WRITE -> result = result or 128 PosixFilePermission.OWNER_EXECUTE -> result = result or 64 PosixFilePermission.GROUP_READ -> result = result or 32 PosixFilePermission.GROUP_WRITE -> result = result or 16 PosixFilePermission.GROUP_EXECUTE -> result = result or 8 PosixFilePermission.OTHERS_READ -> result = result or 4 PosixFilePermission.OTHERS_WRITE -> result = result or 2 PosixFilePermission.OTHERS_EXECUTE -> result = result or 1 else -> {} } } return result } private val decodeMap = arrayOf( PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_READ, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_WRITE, PosixFilePermission.GROUP_READ, PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_READ ) private fun fromOctalFileMode(mode: Int): Set<PosixFilePermission> { var mask = 1 val perms = EnumSet.noneOf(PosixFilePermission::class.java) for (flag in decodeMap) { if (mask and mode != 0) { perms.add(flag) } mask = mask shl 1 } return perms }
apache-2.0
e637125bcea80d7ae16a505e1ef0d43b
31.884956
120
0.748587
4.454436
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/JdkUtils.kt
1
2091
// 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 import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtilRt import com.intellij.util.io.URLUtil import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import org.jetbrains.jps.model.JpsGlobal import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.library.JpsOrderRootType import java.nio.file.Files import java.nio.file.Path import java.util.* internal object JdkUtils { fun defineJdk(global: JpsGlobal, jdkName: String, homeDir: Path) { val sdk = JpsJavaExtensionService.getInstance().addJavaSdk(global, jdkName, FileUtilRt.toSystemIndependentName(homeDir.toFile().canonicalPath)) val toolsJar = homeDir.resolve("lib/tools.jar") if (Files.exists(toolsJar)) { sdk.addRoot(toolsJar.toFile(), JpsOrderRootType.COMPILED) } Span.current().addEvent("'$jdkName' JDK set", Attributes.of(AttributeKey.stringKey("jdkHomePath"), homeDir.toString())) } /** * Code is copied from [com.intellij.openapi.projectRoots.impl.JavaSdkImpl.findClasses] */ fun readModulesFromReleaseFile(jbrBaseDir: Path): List<String> { val releaseFile = jbrBaseDir.resolve("release") check(Files.exists(releaseFile)) { "JRE release file is missing: $releaseFile" } Files.newInputStream(releaseFile).use { stream -> val p = Properties() p.load(stream) val jbrBaseUrl = "${URLUtil.JRT_PROTOCOL}${URLUtil.SCHEME_SEPARATOR}${ FileUtilRt.toSystemIndependentName(jbrBaseDir.toAbsolutePath().toString()) }${URLUtil.JAR_SEPARATOR}" val modules = p.getProperty("MODULES") ?: return emptyList() return StringUtilRt.unquoteString(modules).split(' ').map { jbrBaseUrl + it } } } }
apache-2.0
9ff196a292c992c3b5b28da60189ce4f
42.5625
130
0.703013
4.383648
false
false
false
false
google/iosched
mobile/src/main/java/com/google/samples/apps/iosched/ui/signin/SignInViewExtensions.kt
1
3628
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.signin import android.content.Context import android.content.res.Resources import android.graphics.drawable.Drawable import android.net.Uri import android.view.MenuItem import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.Toolbar import androidx.core.view.MenuItemCompat import androidx.lifecycle.Lifecycle.State.STARTED import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import com.google.samples.apps.iosched.R import com.google.samples.apps.iosched.shared.data.signin.AuthenticatedUserInfo import com.google.samples.apps.iosched.ui.MainActivityViewModel import com.google.samples.apps.iosched.util.asGlideTarget import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch fun Toolbar.setupProfileMenuItem( viewModel: MainActivityViewModel, lifecycleOwner: LifecycleOwner ) { inflateMenu(R.menu.profile) val profileItem = menu.findItem(R.id.action_profile) ?: return profileItem.setOnMenuItemClickListener { viewModel.onProfileClicked() true } lifecycleOwner.lifecycleScope.launch { lifecycleOwner.lifecycle.repeatOnLifecycle(STARTED) { viewModel.userInfo.collect { setProfileContentDescription(profileItem, resources, it) } } } val avatarSize = resources.getDimensionPixelSize(R.dimen.nav_account_image_size) val target = profileItem.asGlideTarget(avatarSize) lifecycleOwner.lifecycleScope.launch { lifecycleOwner.lifecycle.repeatOnLifecycle(STARTED) { viewModel.currentUserImageUri.collect { setProfileAvatar(context, target, it) } } } } fun setProfileContentDescription(item: MenuItem, res: Resources, user: AuthenticatedUserInfo?) { val description = if (user?.isSignedIn() == true) { res.getString(R.string.a11y_signed_in_content_description, user.getDisplayName()) } else { res.getString(R.string.a11y_signed_out_content_description) } MenuItemCompat.setContentDescription(item, description) } fun setProfileAvatar( context: Context, target: Target<Drawable>, imageUri: Uri?, placeholder: Int = R.drawable.ic_default_profile_avatar ) { // Inflate the drawable for proper tinting val placeholderDrawable = AppCompatResources.getDrawable(context, placeholder) when (imageUri) { null -> { Glide.with(context) .load(placeholderDrawable) .apply(RequestOptions.circleCropTransform()) .into(target) } else -> { Glide.with(context) .load(imageUri) .apply(RequestOptions.placeholderOf(placeholderDrawable).circleCrop()) .into(target) } } }
apache-2.0
07ea82639a80255fd95dc9c704512427
34.920792
96
0.72409
4.518057
false
false
false
false
allotria/intellij-community
uast/uast-common/src/org/jetbrains/uast/baseElements/UExpression.kt
2
3359
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * Represents an expression or statement (which is considered as an expression in Uast). */ interface UExpression : UElement, UAnnotated { /** * Returns the expression value or null if the value can't be calculated. */ fun evaluate(): Any? = null /** * Returns expression type, or null if type can not be inferred, or if this expression is a statement. */ fun getExpressionType(): PsiType? = null override fun accept(visitor: UastVisitor) { visitor.visitElement(this) visitor.afterVisitElement(this) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitExpression(this, data) } /** * Represents an annotated element. */ interface UAnnotated : UElement { @Deprecated( message = "Will be removed to avoid clash with com.intellij.psi.PsiModifierListOwner#getAnnotations", replaceWith = ReplaceWith(expression = "uAnnotations"), level = DeprecationLevel.WARNING ) @JvmDefault val annotations: List<UAnnotation> get() = uAnnotations /** * Returns the list of annotations applied to the current element. */ @Suppress("DEPRECATION") @JvmDefault val uAnnotations: List<UAnnotation> get() = annotations /** * Looks up for annotation element using the annotation qualified name. * * @param fqName the qualified name to search * @return the first annotation element with the specified qualified name, or null if there is no annotation with such name. */ fun findAnnotation(fqName: String): UAnnotation? = uAnnotations.firstOrNull { it.qualifiedName == fqName } } /** * Represents a labeled element. */ interface ULabeled : UElement { /** * Returns the label name, or null if the label is empty. */ val label: String? /** * Returns the label identifier, or null if the label is empty. */ val labelIdentifier: UIdentifier? } /** * In some cases (user typing, syntax error) elements, which are supposed to exist, are missing. * The obvious example - the lack of the condition expression in [UIfExpression], e.g. 'if () return'. * [UIfExpression.condition] is required to return not-null values, * and Uast implementation should return something instead of 'null' in this case. * * Use [UastEmptyExpression] in this case. */ open class UastEmptyExpression(override val uastParent: UElement?) : UExpression { override val uAnnotations: List<UAnnotation> get() = emptyList() @Deprecated("see the base property description", ReplaceWith("sourcePsi")) override val psi: PsiElement? get() = null override fun asLogString(): String = log() override fun hashCode(): Int = uastParent?.hashCode() ?: super.hashCode() override fun equals(other: Any?): Boolean = if (other is UastEmptyExpression) other.uastParent == uastParent else false @Deprecated("create class instance instead") companion object : UastEmptyExpression(null) { @JvmField val INSTANCE: UastEmptyExpression = this } }
apache-2.0
6f552dbf72efe9884e2cfdda1914a386
29.825688
140
0.721346
4.437252
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.kt
1
3290
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("PluginsAdvertiser") package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.RepositoryHelper import com.intellij.ide.plugins.advertiser.PluginData import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationGroupManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.util.PlatformUtils.isIdeaUltimate import java.io.IOException private const val IGNORE_ULTIMATE_EDITION = "ignoreUltimateEdition" @get:JvmName("getLog") val LOG = Logger.getInstance("#PluginsAdvertiser") private val propertiesComponent get() = PropertiesComponent.getInstance() var isIgnoreUltimate: Boolean get() = propertiesComponent.isTrueValue(IGNORE_ULTIMATE_EDITION) set(value) = propertiesComponent.setValue(IGNORE_ULTIMATE_EDITION, value) @JvmField @Deprecated("Use `notificationGroup` property") val NOTIFICATION_GROUP = notificationGroup val notificationGroup: NotificationGroup get() = NotificationGroupManager.getInstance().getNotificationGroup("Plugins Suggestion") @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Use `installAndEnable(Set, Runnable)`") fun installAndEnablePlugins( pluginIds: Set<String>, onSuccess: Runnable, ) { installAndEnable( LinkedHashSet(pluginIds.map { PluginId.getId(it) }), onSuccess, ) } fun installAndEnable( pluginIds: Set<PluginId>, onSuccess: Runnable, ) = installAndEnable(null, pluginIds, true, onSuccess) fun installAndEnable( project: Project?, pluginIds: Set<PluginId>, showDialog: Boolean = false, onSuccess: Runnable, ) = ProgressManager.getInstance().run(InstallAndEnableTask(project, pluginIds, showDialog, onSuccess)) internal fun getBundledPluginToInstall(plugins: Collection<PluginData>): List<String> { return if (isIdeaUltimate()) { emptyList() } else { val descriptorsById = PluginManagerCore.buildPluginIdMap() plugins .filter { it.isBundled } .filterNot { descriptorsById.containsKey(it.pluginId) } .map { it.pluginName } } } /** * Loads list of plugins, compatible with a current build, from all configured repositories */ @JvmOverloads internal fun loadPluginsFromCustomRepositories(indicator: ProgressIndicator? = null): List<IdeaPluginDescriptor> { return RepositoryHelper .getPluginHosts() .filterNot { it == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository() }.flatMap { try { RepositoryHelper.loadPlugins(it, indicator) } catch (e: IOException) { LOG.info("Couldn't load plugins from $it: $e") LOG.debug(e) emptyList<IdeaPluginDescriptor>() } }.distinctBy { it.pluginId } }
apache-2.0
e10c3082b4e17a0c2779469ffab985d5
32.571429
140
0.77386
4.607843
false
false
false
false
allotria/intellij-community
platform/statistics/src/com/intellij/internal/statistic/eventLog/events/EventsSchemeBuilder.kt
1
7306
// 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.internal.statistic.eventLog.events import com.google.gson.GsonBuilder import com.google.gson.JsonElement import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.intellij.ide.plugins.PluginManagerCore import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger import com.intellij.internal.statistic.service.fus.collectors.FeatureUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.openapi.application.ApplicationStarter import com.intellij.openapi.util.io.FileUtil import java.io.File import java.lang.reflect.Type import kotlin.system.exitProcess object EventsSchemeBuilder { enum class FieldDataType { ARRAY, PRIMITIVE } data class FieldDescriptor(val path: String, val value: Set<String>, val dataType: FieldDataType = FieldDataType.PRIMITIVE) data class EventDescriptor(val event: String, val fields: Set<FieldDescriptor>) data class GroupDescriptor(val id: String, val type: String, val version: Int, val schema: Set<EventDescriptor>, val className: String) data class EventsScheme(val commitHash: String?, val scheme: List<GroupDescriptor>) private fun fieldSchema(field: EventField<*>, fieldName: String, eventName: String, groupId: String): Set<FieldDescriptor> { if (field.name.contains(".")) { throw IllegalStateException("Field name should not contains dots, because dots are used to express hierarchy. " + "Group=$groupId, event=$eventName, field=${field.name}") } if (field == EventFields.PluginInfo || field == EventFields.PluginInfoFromInstance) { return hashSetOf( FieldDescriptor("plugin", hashSetOf("{util#plugin}")), FieldDescriptor("plugin_type", hashSetOf("{util#plugin_type}")), FieldDescriptor("plugin_version", hashSetOf("{util#plugin_version}")) ) } return when (field) { is ObjectEventField -> buildObjectEvenScheme(fieldName, field.fields, eventName, groupId) is ObjectListEventField -> buildObjectEvenScheme(fieldName, field.fields, eventName, groupId) is ListEventField<*> -> { hashSetOf(FieldDescriptor(fieldName, field.validationRule.toHashSet(), FieldDataType.ARRAY)) } is PrimitiveEventField -> hashSetOf(FieldDescriptor(fieldName, field.validationRule.toHashSet())) } } private fun buildObjectEvenScheme(fieldName: String, fields: Array<out EventField<*>>, eventName: String, groupId: String): Set<FieldDescriptor> { val fieldsDescriptors = hashSetOf<FieldDescriptor>() for (eventField in fields) { fieldsDescriptors.addAll(fieldSchema(eventField, fieldName + "." + eventField.name, eventName, groupId)) } return fieldsDescriptors } @JvmStatic fun buildEventsScheme(): List<GroupDescriptor> { val result = mutableListOf<GroupDescriptor>() result.addAll(collectGroupsFromExtensions("counter", FUCounterUsageLogger.instantiateCounterCollectors())) result.addAll(collectGroupsFromExtensions("state", ApplicationUsagesCollector.EP_NAME.extensionList)) result.addAll(collectGroupsFromExtensions("state", ProjectUsagesCollector.EP_NAME.extensionList)) return result } fun collectGroupsFromExtensions(groupType: String, collectors: Collection<FeatureUsagesCollector>): MutableList<GroupDescriptor> { val result = mutableListOf<GroupDescriptor>() for (collector in collectors) { val collectorClass = if (collector.javaClass.enclosingClass != null) collector.javaClass.enclosingClass else collector.javaClass validateGroupId(collector) val group = collector.group ?: continue val eventsDescriptors = group.events.groupBy { it.eventId } .map { (eventName, events) -> EventDescriptor(eventName, buildFields(events, eventName, group.id )) } .toHashSet() val groupDescriptor = GroupDescriptor(group.id, groupType, group.version, eventsDescriptors, collectorClass.name) result.add(groupDescriptor) } return result } private fun validateGroupId(collector: FeatureUsagesCollector) { try { // get group id to check that either group or group id is overridden collector.groupId } catch (e: IllegalStateException) { throw IllegalStateException(e.message + " in " + collector.javaClass.name) } } private fun buildFields(events: List<BaseEventId>, eventName: String, groupId: String): HashSet<FieldDescriptor> { return events.flatMap { it.getFields() } .flatMap { field -> fieldSchema(field, field.name, eventName, groupId) } .groupBy { it.path } .map { (name, values) -> val type = defineDataType(values, name, eventName, groupId) FieldDescriptor(name, values.flatMap { it.value }.toHashSet(), type) } .toHashSet() } private fun defineDataType(values: List<FieldDescriptor>, name: String, eventName: String, groupId: String): FieldDataType { val dataType = values.first().dataType return if (values.any { it.dataType != dataType }) throw IllegalStateException("Field couldn't have multiple types (group=$groupId, event=$eventName, field=$name)") else { dataType } } } class EventsSchemeBuilderAppStarter : ApplicationStarter { override fun getCommandName(): String = "buildEventsScheme" override fun main(args: List<String>) { val outputFile = args.getOrNull(1) val pluginsFile = args.getOrNull(2) val eventsScheme = EventsSchemeBuilder.EventsScheme(System.getenv("INSTALLER_LAST_COMMIT_HASH"), EventsSchemeBuilder.buildEventsScheme()) val text = GsonBuilder() .registerTypeAdapter(EventsSchemeBuilder.FieldDataType::class.java, FieldDataTypeSerializer) .setPrettyPrinting() .create() .toJson(eventsScheme) logEnabledPlugins(pluginsFile) if (outputFile != null) { FileUtil.writeToFile(File(outputFile), text) } else { println(text) } exitProcess(0) } private fun logEnabledPlugins(pluginsFile: String?) { val text = buildString { for (descriptor in PluginManagerCore.getLoadedPlugins()) { if (descriptor.isEnabled) { appendLine(descriptor.name) } } } if (pluginsFile != null) { FileUtil.writeToFile(File(pluginsFile), text) } else { println("Enabled plugins:") println(text) } } object FieldDataTypeSerializer : JsonSerializer<EventsSchemeBuilder.FieldDataType> { override fun serialize(src: EventsSchemeBuilder.FieldDataType?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement { if (src == EventsSchemeBuilder.FieldDataType.PRIMITIVE || src == null) { return context!!.serialize(null) } return context!!.serialize(src.name) } } }
apache-2.0
1bdd5a10405765bb75371e0fefc3f418
43.012048
140
0.705174
4.841617
false
false
false
false
leafclick/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/application/ConfigImportHelperTest.kt
1
8313
// 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.openapi.application import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.SystemInfo import com.intellij.testFramework.PlatformTestUtil.useAppConfigDir import com.intellij.testFramework.fixtures.BareTestFixtureTestCase import com.intellij.testFramework.rules.InMemoryFsRule import com.intellij.testFramework.rules.TempDirectory import com.intellij.util.SystemProperties import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Condition import org.junit.Assume.assumeTrue import org.junit.Rule import org.junit.Test import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.nio.file.attribute.FileTime import java.util.function.Predicate private val LOG = logger<ConfigImportHelperTest>() class ConfigImportHelperTest : BareTestFixtureTestCase() { @JvmField @Rule val memoryFs = InMemoryFsRule(SystemInfo.isWindows) @JvmField @Rule val localTempDir = TempDirectory() @Test fun `config directory is valid for import`() { PropertiesComponent.getInstance().setValue("property.ConfigImportHelperTest", true) try { useAppConfigDir { runBlocking { ApplicationManager.getApplication().stateStore.save(forceSavingAllSettings = true) } assertThat(PathManager.getConfigDir()) .isNotEmptyDirectory() .satisfies(Condition(Predicate<Path> { ConfigImportHelper.isConfigDirectory(it) }, "A valid config directory")) } } finally { PropertiesComponent.getInstance().unsetValue("property.ConfigImportHelperTest") } } @Test fun `find pre-migration config directory`() { val cfg201 = createConfigDir("2020.1", modern = false) val newConfigPath = createConfigDir("2020.1", modern = true) assertThat(ConfigImportHelper.findConfigDirectories(newConfigPath)).containsExactly(cfg201) } @Test fun `find both historic and current config directories`() { val cfg15 = createConfigDir("15", storageTS = 1448928000000) val cfg193 = createConfigDir("2019.1", storageTS = 1574845200000) val cfg201 = createConfigDir("2020.1", storageTS = 1585731600000) val newConfigPath = createConfigDir("2020.2") assertThat(ConfigImportHelper.findConfigDirectories(newConfigPath)).containsExactly(cfg201, cfg193, cfg15) } @Test fun `find recent config directory`() { val cfg201 = createConfigDir("2020.1", storageTS = 100) val cfg211 = createConfigDir("2021.1", storageTS = 200) val cfg221 = createConfigDir("2022.1", storageTS = 300) val newConfigPath = createConfigDir("2022.3") assertThat(ConfigImportHelper.findConfigDirectories(newConfigPath)).containsExactly(cfg221, cfg211, cfg201) writeStorageFile(cfg211, 400) assertThat(ConfigImportHelper.findConfigDirectories(newConfigPath)).containsExactly(cfg211, cfg221, cfg201) } @Test fun `sort if no anchor files`() { val cfg201 = createConfigDir("2020.1") val cfg211 = createConfigDir("2021.1") val cfg221 = createConfigDir("2022.1") val newConfigPath = createConfigDir("2022.3") assertThat(ConfigImportHelper.findConfigDirectories(newConfigPath)).containsExactly(cfg221, cfg211, cfg201) } @Test fun `sort some real historic config dirs`() { val cfg10 = createConfigDir("10", product = "DataGrip", storageTS = 1455035096000) val cfg162 = createConfigDir("2016.2", product = "DataGrip", storageTS = 1466345662000) val cfg161 = createConfigDir("2016.1", product = "DataGrip", storageTS = 1485460719000) val cfg171 = createConfigDir("2017.1", product = "DataGrip", storageTS = 1503006763000) val cfg172 = createConfigDir("2017.2", product = "DataGrip", storageTS = 1510866492000) val cfg163 = createConfigDir("2016.3", product = "DataGrip", storageTS = 1520869009000) val cfg181 = createConfigDir("2018.1", product = "DataGrip", storageTS = 1531238044000) val cfg183 = createConfigDir("2018.3", product = "DataGrip", storageTS = 1545844523000) val cfg182 = createConfigDir("2018.2", product = "DataGrip", storageTS = 1548076635000) val cfg191 = createConfigDir("2019.1", product = "DataGrip", storageTS = 1548225505000) val cfg173 = createConfigDir("2017.3", product = "DataGrip", storageTS = 1549092322000) val newConfigPath = createConfigDir("2020.1", product = "DataGrip") assertThat(ConfigImportHelper.findConfigDirectories(newConfigPath)).containsExactly( cfg173, cfg191, cfg182, cfg183, cfg181, cfg163, cfg172, cfg171, cfg161, cfg162, cfg10) } @Test fun `set keymap - old version`() { doKeyMapTest("2016.4", isMigrationExpected = true) doKeyMapTest("2019.1", isMigrationExpected = true) } @Test fun `set keymap - new version`() { doKeyMapTest("2019.2", isMigrationExpected = false) doKeyMapTest("2019.3", isMigrationExpected = false) } private fun doKeyMapTest(version: String, isMigrationExpected: Boolean) { assumeTrue("macOS-only", SystemInfo.isMac) val oldConfigDir = createConfigDir(version, product = "DataGrip") val newConfigDir = createConfigDir("2019.2", product = "DataGrip") ConfigImportHelper.setKeymapIfNeeded(oldConfigDir, newConfigDir, LOG) val optionFile = newConfigDir.resolve("${PathManager.OPTIONS_DIRECTORY}/keymap.xml") if (isMigrationExpected) { assertThat(optionFile).usingCharset(StandardCharsets.UTF_8).hasContent(""" <application> <component name="KeymapManager"> <active_keymap name="Mac OS X" /> </component> </application> """.trimIndent()) } else { assertThat(optionFile).doesNotExist() } } @Test fun `migrate plugins to empty directory`() { val oldConfigDir = localTempDir.newFolder("oldConfig").toPath() val oldPluginsDir = Files.createDirectories(oldConfigDir.resolve("plugins")) val oldPluginZip = Files.createFile(oldPluginsDir.resolve("my-plugin.zip")) val newConfigDir = localTempDir.newFolder("newConfig").toPath() val newPluginsDir = newConfigDir.resolve("plugins") ConfigImportHelper.doImport(oldConfigDir, newConfigDir, null, oldPluginsDir, newPluginsDir, LOG) assertThat(newPluginsDir).isDirectoryContaining { it.fileName == oldPluginZip.fileName } } @Test fun `do not migrate plugins to existing directory`() { val oldConfigDir = localTempDir.newFolder("oldConfig").toPath() val oldPluginsDir = Files.createDirectories(oldConfigDir.resolve("plugins")) val oldPluginZip = Files.createFile(oldPluginsDir.resolve("old-plugin.zip")) val newConfigDir = localTempDir.newFolder("newConfig").toPath() val newPluginsDir = Files.createDirectories(newConfigDir.resolve("plugins")) val newPluginZip = Files.createFile(newPluginsDir.resolve("new-plugin.zip")) ConfigImportHelper.doImport(oldConfigDir, newConfigDir, null, oldPluginsDir, newPluginsDir, LOG) assertThat(newPluginsDir) .isDirectoryContaining { it.fileName == newPluginZip.fileName } .isDirectoryNotContaining { it.fileName == oldPluginZip.fileName } } private fun createConfigDir(version: String, modern: Boolean = version >= "2020.1", product: String = "IntelliJIdea", storageTS: Long = 0): Path { val path = when { modern -> PathManager.getDefaultConfigPathFor("${product}${version}") SystemInfo.isMac -> "${SystemProperties.getUserHome()}/Library/Preferences/${product}${version}" else -> "${SystemProperties.getUserHome()}/.${product}${version}/config" } val dir = Files.createDirectories(memoryFs.fs.getPath(path).normalize()) if (storageTS > 0) writeStorageFile(dir, storageTS) return dir } private fun writeStorageFile(config: Path, lastModified: Long) { val file = config.resolve("${PathManager.OPTIONS_DIRECTORY}/${StoragePathMacros.NON_ROAMABLE_FILE}") Files.createDirectories(file.parent) Files.write(file, "<application/>".toByteArray()) Files.setLastModifiedTime(file, FileTime.fromMillis(lastModified)) } }
apache-2.0
7d4581c6c3ef9ebdcffe14f75074c980
45.446927
148
0.742331
4.557566
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/callableReference/property/simpleMutableExtension.kt
5
384
var storage = 0 var Int.foo: Int get() { return this + storage } set(value) { storage = this + value } fun box(): String { val pr = Int::foo if (pr.get(42) != 42) return "Fail 1: ${pr.get(42)}" pr.set(200, 39) if (pr.get(-239) != 0) return "Fail 2: ${pr.get(-239)}" if (storage != 239) return "Fail 3: $storage" return "OK" }
apache-2.0
84e4687ba0e0c6a20fe7800cebf81246
20.333333
59
0.513021
2.931298
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/fullJdk/native/nativePropertyAccessors.kt
2
1324
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // FULL_JDK class C { companion object { val defaultGetter: Int = 1 external get var defaultSetter: Int = 1 external get external set } val defaultGetter: Int = 1 external get var defaultSetter: Int = 1 external get external set } val defaultGetter: Int = 1 external get var defaultSetter: Int = 1 external get external set fun check(body: () -> Unit, signature: String): String? { try { body() return "Link error expected" } catch (e: java.lang.UnsatisfiedLinkError) { if (e.message != signature) return "Fail $signature: " + e.message } return null } fun box(): String { return check({defaultGetter}, "NativePropertyAccessorsKt.getDefaultGetter()I") ?: check({defaultSetter = 1}, "NativePropertyAccessorsKt.setDefaultSetter(I)V") ?: check({C.defaultGetter}, "C\$Companion.getDefaultGetter()I") ?: check({C.defaultSetter = 1}, "C\$Companion.setDefaultSetter(I)V") ?: check({C().defaultGetter}, "C.getDefaultGetter()I") ?: check({C().defaultSetter = 1}, "C.setDefaultSetter(I)V") ?: "OK" }
apache-2.0
ecb64de98a1baab69db5d124a05e52cc
23.518519
90
0.598943
4.04893
false
false
false
false
magmaOffenburg/RoboViz
src/main/kotlin/org/magmaoffenburg/roboviz/gui/windows/config/GraphicsPanel.kt
1
9677
package org.magmaoffenburg.roboviz.gui.windows.config import org.magmaoffenburg.roboviz.configuration.Config.Graphics import org.magmaoffenburg.roboviz.rendering.Renderer import java.awt.Dimension import javax.swing.* class GraphicsPanel: JPanel() { // lighting private val lightingLabel = JLabel("Lighting") private val lightingSeparator = JSeparator().apply { maximumSize = Dimension(0, lightingLabel.preferredSize.height) } private val bloomCb = JCheckBox("Bloom", Graphics.useBloom) private val phongCb = JCheckBox("Phong", Graphics.usePhong) private val shadowsCb = JCheckBox("Shadows", Graphics.useShadows) private val softShadowsCb = JCheckBox("Soft Shadows", Graphics.useSoftShadows).apply { isEnabled = Graphics.useShadows } private val shadowResLabel = JLabel("Shadow Resolution:", SwingConstants.RIGHT) private val shadowResSpinner = JSpinner(SpinnerNumberModel(Graphics.shadowResolution, 1, Int.MAX_VALUE, 1)).apply { isEnabled = Graphics.useShadows && Graphics.useSoftShadows } // fsaa private val fsaaLabel = JLabel("Anti-Aliasing") private val fsaaSeparator = JSeparator().apply { maximumSize = Dimension(0, fsaaLabel.preferredSize.height) } private val fsaaCb = JCheckBox("Enabled", Graphics.useFsaa) private val samplesLabel = JLabel("Samples:", SwingConstants.RIGHT) private val samplesSpinner = JSpinner(SpinnerNumberModel(Graphics.fsaaSamples, 1, Int.MAX_VALUE, 1)).apply { isEnabled = Graphics.useFsaa } // general private val generalLabel = JLabel("General Graphics") private val generalSeparator = JSeparator().apply { maximumSize = Dimension(0, generalLabel.preferredSize.height) } private val stereoCb = JCheckBox("Stereo 3D", Graphics.useStereo) private val vsyncCb = JCheckBox("V-Sync", Graphics.useVsync) private val fpsLabel = JLabel("FPS:") private val fpsSpinner = JSpinner(SpinnerNumberModel(Graphics.targetFPS, 1, Int.MAX_VALUE, 1)) private val fpFovLabel = JLabel("First Person FOV:") private val fpFovSpinner = JSpinner(SpinnerNumberModel(Graphics.firstPersonFOV, 1, Int.MAX_VALUE, 1)) private val tpFovLabel = JLabel("Third Person FOV:") private val tpFovSpinner = JSpinner(SpinnerNumberModel(Graphics.thirdPersonFOV, 1, Int.MAX_VALUE, 1)) init { initializeLayout() initializeActions() } /** * initialize the panels layout */ private fun initializeLayout() { val layout = GroupLayout(this).apply { autoCreateGaps = true autoCreateContainerGaps = true } this.layout = layout layout.setHorizontalGroup(layout .createParallelGroup(GroupLayout.Alignment.LEADING) // lighting .addGroup(layout.createSequentialGroup() .addComponent(lightingLabel, 0, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lightingSeparator, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) ) .addComponent(bloomCb, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) .addComponent(phongCb, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) .addComponent(shadowsCb, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) .addGroup(layout.createSequentialGroup() .addComponent(softShadowsCb, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) .addComponent(shadowResLabel, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) .addComponent(shadowResSpinner, 0, 90, 90) ) // fsaa .addGroup(layout.createSequentialGroup() .addComponent(fsaaLabel, 0, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(fsaaSeparator, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) ) .addGroup(layout.createSequentialGroup() .addComponent(fsaaCb, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) .addComponent(samplesLabel, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) .addComponent(samplesSpinner, 0, 90, 90) ) // general .addGroup(layout.createSequentialGroup() .addComponent(generalLabel, 0, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(generalSeparator, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) ) .addComponent(stereoCb, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) .addComponent(vsyncCb, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt()) .addGroup(layout.createSequentialGroup() .addComponent(fpsLabel, 0, 120, 120) .addComponent(fpsSpinner, 0, 90, 90) ) .addGroup(layout.createSequentialGroup() .addComponent(fpFovLabel, 0, 120, 120) .addComponent(fpFovSpinner, 0, 90, 90) ) .addGroup(layout.createSequentialGroup() .addComponent(tpFovLabel, 0, 120, 120) .addComponent(tpFovSpinner, 0, 90, 90) ) ) layout.setVerticalGroup(layout.createSequentialGroup() // lighting .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(lightingLabel) .addComponent(lightingSeparator) ) .addComponent(bloomCb) .addComponent(phongCb) .addComponent(shadowsCb) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(softShadowsCb) .addComponent(shadowResLabel) .addComponent(shadowResSpinner) ) // fsaa .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(fsaaLabel) .addComponent(fsaaSeparator) ) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(fsaaCb) .addComponent(samplesLabel) .addComponent(samplesSpinner) ) // general .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(generalLabel) .addComponent(generalSeparator) ) .addComponent(stereoCb) .addComponent(vsyncCb) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(fpsLabel) .addComponent(fpsSpinner) ) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(fpFovLabel) .addComponent(fpFovSpinner) ) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(tpFovLabel) .addComponent(tpFovSpinner) ) ) } /** * initialize the actions for all gui elements * used by this panel */ private fun initializeActions() { // lighting bloomCb.addActionListener { Graphics.useBloom = bloomCb.isSelected Renderer.renderSettingsChanged = true } phongCb.addActionListener { Graphics.usePhong = phongCb.isSelected Renderer.renderSettingsChanged = true } shadowsCb.addActionListener { Graphics.useShadows = shadowsCb.isSelected softShadowsCb.isEnabled = Graphics.useShadows shadowResSpinner.isEnabled = Graphics.useShadows Renderer.renderSettingsChanged = true } softShadowsCb.addActionListener { Graphics.useSoftShadows = softShadowsCb.isSelected shadowResSpinner.isEnabled = Graphics.useSoftShadows Renderer.renderSettingsChanged = true } shadowResSpinner.addChangeListener { Graphics.shadowResolution = shadowResSpinner.value as Int Renderer.renderSettingsChanged = true } // fsaa fsaaCb.addActionListener { Graphics.useFsaa = fsaaCb.isSelected samplesSpinner.isEnabled = Graphics.useFsaa Renderer.renderSettingsChanged = true } samplesSpinner.addChangeListener { Graphics.fsaaSamples = samplesSpinner.value as Int } // general stereoCb.addActionListener { Graphics.useStereo = stereoCb.isSelected } vsyncCb.addActionListener { Graphics.useVsync = vsyncCb.isSelected } fpsSpinner.addChangeListener { Graphics.targetFPS = fpsSpinner.value as Int } fpFovSpinner.addChangeListener { Graphics.firstPersonFOV = fpFovSpinner.value as Int } tpFovSpinner.addChangeListener { Graphics.thirdPersonFOV = tpFovSpinner.value as Int } } }
apache-2.0
80de87d41d94fb4299a37323a0654246
42.594595
119
0.604113
5.053264
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/NewSelectLesson.kt
6
3669
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.learn.lesson.general import training.dsl.LessonContext import training.dsl.LessonSample import training.dsl.LessonUtil import training.dsl.LessonUtil.checkPositionOfEditor import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.dsl.TaskRuntimeContext import training.learn.LessonsBundle import training.learn.course.KLesson abstract class NewSelectLesson : KLesson("Select", LessonsBundle.message("selection.lesson.name")) { protected val firstString = "first string" protected val thirdString = "third string" protected val beginString = "Begin of the work" protected val endString = "End of the work" protected val selectString = "This is a long string that you can select for refactoring" protected abstract val selectArgument: String protected abstract val selectCall: String protected abstract val sample: LessonSample protected abstract val selectIf: String private val startCaretText: String = "at you" protected abstract val numberOfSelectsForWholeCall: Int override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) caret(startCaretText) actionTask("EditorSelectWord") { restoreIfModifiedOrMoved() LessonsBundle.message("new.selection.select.word", action(it)) } task("EditorSelectWord") { restoreIfModifiedOrMoved() text(LessonsBundle.message("new.selection.select.string", action(it))) trigger(it) { checkSelection(selectString) } test { actions(it) } } task("EditorSelectWord") { restoreIfModifiedOrMoved() text(LessonsBundle.message("new.selection.add.quotes", action(it))) trigger(it) { checkSelection(selectArgument) } test { actions(it) } } task("EditorSelectWord") { proposeRestore { checkPositionOfEditor(previous.sample) l@{ s -> val previousSelection = s.selection ?: return@l true val currentCaret = editor.caretModel.currentCaret currentCaret.selectionStart <= previousSelection.first && currentCaret.selectionEnd >= previousSelection.second } } text(LessonsBundle.message("new.selection.select.call", action(it), numberOfSelectsForWholeCall)) trigger(it) { checkSelection(selectCall) } test { for (i in 1..numberOfSelectsForWholeCall) actions(it) } } actionTask("EditorUnSelectWord") { restoreIfModifiedOrMoved() LessonsBundle.message("new.selection.unselect", action(it)) } waitBeforeContinue(750) prepareRuntimeTask { editor.selectionModel.removeSelection() } caret("if") task("EditorSelectWord") { restoreIfModifiedOrMoved() text(LessonsBundle.message("new.selection.select.if", code("if"), action(it))) trigger(it) { checkSelection(selectIf) } test { for (i in 1..2) actions(it) } } } private fun TaskRuntimeContext.checkSelection(needSelection: String): Boolean { val selectionModel = editor.selectionModel val selection = editor.document.charsSequence.subSequence(selectionModel.selectionStart, selectionModel.selectionEnd) return selection.toString().trim() == needSelection.trim() } override val suitableTips = listOf("smart_selection", "CtrlW") override val helpLinks: Map<String, String> get() = mapOf( Pair(LessonsBundle.message("selection.help.select.code.constructs"), LessonUtil.getHelpLink("working-with-source-code.html#editor_code_selection")), ) }
apache-2.0
5e79ab74c0011796234403b505419d76
33.28972
140
0.717634
4.615094
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/ide/util/gotoByName/LanguageRef.kt
10
2193
// 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.ide.util.gotoByName import com.intellij.lang.DependentLanguage import com.intellij.lang.Language import com.intellij.lang.LanguageUtil import com.intellij.navigation.NavigationItem import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.psi.PsiElement import org.jetbrains.annotations.Nls import javax.swing.Icon data class LanguageRef(val id: String, @field:Nls val displayName: String, val icon: Icon?) { companion object { @JvmStatic fun forLanguage(lang: Language): LanguageRef = LanguageRef(lang.id, lang.displayName, lang.associatedFileType?.icon) @JvmStatic fun forNavigationitem(item: NavigationItem): LanguageRef? = (item as? PsiElement)?.language?.let { forLanguage(it) } @JvmStatic fun forAllLanguages(): List<LanguageRef> { return Language.getRegisteredLanguages() .filter { it !== Language.ANY && it !is DependentLanguage } .sortedWith(LanguageUtil.LANGUAGE_COMPARATOR) .map { forLanguage(it) } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as LanguageRef if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } } data class FileTypeRef(val name: String, val icon: Icon?) { companion object { @JvmStatic fun forFileType(fileType: FileType): FileTypeRef = FileTypeRef(fileType.name, fileType.icon) @JvmStatic fun forAllFileTypes(): List<FileTypeRef> { return FileTypeManager.getInstance().registeredFileTypes .sortedWith(FileTypeComparator.INSTANCE) .map { forFileType(it) } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FileTypeRef if (name != other.name) return false return true } override fun hashCode(): Int { return name.hashCode() } }
apache-2.0
519fb3f8b46ff949ffb05dd18bd22998
28.253333
140
0.713634
4.201149
false
false
false
false
Fotoapparat/Fotoapparat
fotoapparat/src/main/java/io/fotoapparat/selector/FlashSelectors.kt
1
1041
package io.fotoapparat.selector import io.fotoapparat.parameter.Flash typealias FlashSelector = Iterable<Flash>.() -> Flash? /** * @return Selector function which provides a disabled flash firing mode if available. * Otherwise provides `null`. */ fun off(): FlashSelector = single(Flash.Off) /** * @return Selector function which provides a forced on flash firing mode if available. * Otherwise provides `null`. */ fun on(): FlashSelector = single(Flash.On) /** * @return Selector function which provides an auto flash firing mode if available. * Otherwise provides `null`. */ fun autoFlash(): FlashSelector = single(Flash.Auto) /** * @return Selector function which provides an auto flash firing mode with red eye * reduction if available. * Otherwise provides `null`. */ fun autoRedEye(): FlashSelector = single(Flash.AutoRedEye) /** * @return Selector function which provides a torch (continuous on) flash firing mode if * available. * Otherwise provides `null`. */ fun torch(): FlashSelector = single(Flash.Torch)
apache-2.0
ebe1117d93b2b9377d65a4920468eee1
27.162162
88
0.735831
4.098425
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/AbstractDiagnosticBasedMigrationInspection.kt
1
3477
// 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.inspections.migration import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.PsiFile import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactoryWithPsiElement import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.quickfix.QuickFixes import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtTreeVisitorVoid abstract class AbstractDiagnosticBasedMigrationInspection<T : KtElement>( val elementType: Class<T>, ) : AbstractKotlinInspection() { abstract val diagnosticFactory: DiagnosticFactoryWithPsiElement<T, *> open fun getCustomIntentionFactory(): ((Diagnostic) -> IntentionAction?)? = null override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? { if (file !is KtFile) return null val diagnostics by lazy { file.analyzeWithAllCompilerChecks().bindingContext.diagnostics } val actionsFactory = QuickFixes.getInstance().getActionFactories(diagnosticFactory).singleOrNull() ?: error("Must have one factory") val problemDescriptors = mutableListOf<ProblemDescriptor>() file.accept( object : KtTreeVisitorVoid() { override fun visitKtElement(element: KtElement) { super.visitKtElement(element) if (!elementType.isInstance(element) || element.textLength == 0) return val diagnostic = diagnostics.forElement(element) .filter { it.factory == diagnosticFactory } .ifEmpty { return } .singleOrNull() ?: error("Must have one diagnostic") val customIntentionFactory = getCustomIntentionFactory() val intentionAction = if (customIntentionFactory != null) customIntentionFactory(diagnostic) ?: return else actionsFactory.createActions(diagnostic).ifEmpty { return }.singleOrNull() ?: error("Must have one fix") val text = descriptionMessage() ?: DefaultErrorMessages.render(diagnostic) problemDescriptors.add( manager.createProblemDescriptor( element, text, false, arrayOf(IntentionWrapper(intentionAction)), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ), ) } }, ) return problemDescriptors.toTypedArray() } @Nls protected open fun descriptionMessage(): String? = null }
apache-2.0
5af45e58926adc0718826c531706d7df
45.373333
158
0.665516
5.923339
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/inlineVariableOrProperty/fromJavaToKotlin/delegateStaticToStaticMethodWithNameConflict.kt
24
721
fun staticMethod() = Unit //KT-40835 fun a() { JavaClass.field val d = JavaClass() JavaClass.field d.let { JavaClass.field } d.also { JavaClass.field } with(d) { JavaClass.field } with(d) out@{ with(4) { JavaClass.field } } } fun a2() { val d: JavaClass? = null d?.field d?.let { JavaClass.field } d?.also { JavaClass.field } with(d) { JavaClass.field } with(d) out@{ with(4) { JavaClass.field } } } fun JavaClass.b(): Int? = JavaClass.field fun JavaClass.c(): Int = JavaClass.field fun d(d: JavaClass) = JavaClass.field
apache-2.0
a540ebce2be836045aa51260ab0ff643
12.603774
41
0.489598
3.605
false
false
false
false
ingokegel/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRViewTabsFactory.kt
8
4243
// 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.plugins.github.pullrequest.ui.toolwindow import com.intellij.collaboration.ui.codereview.CodeReviewTabs.bindTabText import com.intellij.collaboration.ui.codereview.CodeReviewTabs.bindTabUi import com.intellij.collaboration.ui.codereview.ReturnToListComponent import com.intellij.openapi.Disposable import com.intellij.openapi.application.AppUIExecutor.onUiThread import com.intellij.openapi.application.impl.coroutineDispatchingContext import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.tabs.JBTabs import com.intellij.ui.tabs.TabInfo import com.intellij.ui.tabs.TabsListener import com.intellij.ui.tabs.impl.SingleHeightTabs import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.Flow import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.i18n.GithubBundle.messagePointer import javax.swing.JComponent internal class GHPRViewTabsFactory(private val project: Project, private val backToListAction: () -> Unit, private val disposable: Disposable) { private val uiDisposable = Disposer.newDisposable().also { Disposer.register(disposable, it) } private val scope = CoroutineScope(SupervisorJob() + onUiThread().coroutineDispatchingContext()) .also { Disposer.register(uiDisposable) { it.cancel() } } fun create(infoComponent: JComponent, diffController: GHPRDiffController, filesComponent: JComponent, filesCountModel: Flow<Int?>, notViewedFilesCountModel: Flow<Int?>?, commitsComponent: JComponent, commitsCountModel: Flow<Int?>): JBTabs { return create(infoComponent, filesComponent, filesCountModel, notViewedFilesCountModel, commitsComponent, commitsCountModel).also { val listener = object : TabsListener { override fun selectionChanged(oldSelection: TabInfo?, newSelection: TabInfo?) { diffController.activeTree = when (newSelection?.component) { filesComponent -> GHPRDiffController.ActiveTree.FILES commitsComponent -> GHPRDiffController.ActiveTree.COMMITS else -> null } } } it.addListener(listener) listener.selectionChanged(null, it.selectedInfo) } } private fun create(infoComponent: JComponent, filesComponent: JComponent, filesCountModel: Flow<Int?>, notViewedFilesCountModel: Flow<Int?>?, commitsComponent: JComponent, commitsCountModel: Flow<Int?>): JBTabs { val infoTabInfo = TabInfo(infoComponent).apply { text = GithubBundle.message("pull.request.info") sideComponent = createReturnToListSideComponent() } val filesTabInfo = TabInfo(filesComponent).apply { sideComponent = createReturnToListSideComponent() } val commitsTabInfo = TabInfo(commitsComponent).apply { sideComponent = createReturnToListSideComponent() }.also { scope.bindTabText(it, messagePointer("pull.request.commits"), commitsCountModel) } val tabs = object : SingleHeightTabs(project, uiDisposable) { override fun adjust(each: TabInfo?) = Unit }.apply { addTab(infoTabInfo) addTab(filesTabInfo) addTab(commitsTabInfo) } // after adding to `JBTabs` as `getTabLabel()` is used in `bindTabUi` if (notViewedFilesCountModel == null) { scope.bindTabText(filesTabInfo, messagePointer("pull.request.files"), filesCountModel) } else { scope.bindTabUi(tabs, filesTabInfo, messagePointer("pull.request.files"), filesCountModel, notViewedFilesCountModel) } return tabs } private fun createReturnToListSideComponent(): JComponent { return ReturnToListComponent.createReturnToListSideComponent(GithubBundle.message("pull.request.back.to.list")) { backToListAction() } } }
apache-2.0
d8cb91b90a04fec3916cad65eb8ffdb7
41.44
158
0.719067
4.672907
false
false
false
false
PeteGabriel/Yamda
app/src/main/java/com/dev/moviedb/mvvm/movieDetails/MovieDetailsActivity.kt
1
5546
package com.dev.moviedb.mvvm.movieDetails import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View.GONE import com.dev.moviedb.mvvm.extensions.formatMovieRuntime import com.dev.moviedb.mvvm.extensions.getExtendedDate import com.dev.moviedb.mvvm.extensions.loadBackdropUrl import com.dev.moviedb.mvvm.extensions.loadPosterUrl import com.dev.moviedb.mvvm.nowPlayingMoviesTab.VideoPlayerFragment import com.dev.moviedb.mvvm.repository.remote.dto.MovieDTO import kotlinx.android.synthetic.main.item_movie_detail_layout.* import petegabriel.com.yamda.R /** * This activity shows the details of a certain movie passed * as parameter. * * Yamda 1.0.0 */ class MovieDetailsActivity : AppCompatActivity() { /** * Use this key to pass a certain movie inside a bundle. */ companion object { val ITEM_ARGS_KEY = "movie_item_argument" } private var castingImagesRecyclerView: RecyclerView? = null private var castingImagesAdapter: RecyclerView.Adapter<*>? = null private var castingImagesLayoutManager: RecyclerView.LayoutManager? = null private var backdropImagesRecyclerView: RecyclerView? = null private var backdropImagesAdapter: RecyclerView.Adapter<*>? = null private var backdropImagesLayoutManager: RecyclerView.LayoutManager? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.item_movie_detail_layout) toolbar.title = "" setSupportActionBar(toolbar) //toolbar_title.text = "" //provide up navigation supportActionBar?.setDisplayHomeAsUpEnabled(true) val movie = intent.extras[ITEM_ARGS_KEY] as MovieDTO //toolbar.title = if (movie.title?.isEmpty()!!) movie.name else movie.title provideDataToLayout(movie) genre_description_content.text = formatGenreTags(movie) with(movie.releaseDate){ release_date.text = if (this.isEmpty()) "tba" else this.getExtendedDate() } setupCastingCrewImageList(movie) setupImagesList(movie) if (movie.videos.results.isNotEmpty()) { movieTrailerFab.setOnClickListener({ view -> run { movie.videos.let { val manager = supportFragmentManager val videoPlayerFragDialog = VideoPlayerFragment.newInstance(it.results[0].key) videoPlayerFragDialog.show(manager, "VideoPlayerFragDialog") } } }) }else{ movieTrailerFab.visibility = GONE } } private fun setupImagesList(movie: MovieDTO) { if (movie.images?.backdrops?.size!! > 0) { backdropImagesRecyclerView = findViewById<RecyclerView>(R.id.backdrop_images_container) backdropImagesRecyclerView?.isHorizontalScrollBarEnabled = false backdropImagesRecyclerView?.setHasFixedSize(true) // use a linear layout manager backdropImagesLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) backdropImagesRecyclerView?.layoutManager = backdropImagesLayoutManager // specify an castingImagesAdapter (see also next example) backdropImagesAdapter = BackdropImageListAdapter(movie.images?.backdrops!!) backdropImagesRecyclerView?.adapter = backdropImagesAdapter }else{ textView2.visibility = GONE } } private fun setupCastingCrewImageList(movie: MovieDTO) { if (movie.credits?.cast?.size!! > 0) { castingImagesRecyclerView = findViewById<RecyclerView>(R.id.casting_images_container) castingImagesRecyclerView?.isHorizontalScrollBarEnabled = false castingImagesRecyclerView?.setHasFixedSize(true) // use a linear layout manager castingImagesLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) castingImagesRecyclerView?.layoutManager = castingImagesLayoutManager // specify an castingImagesAdapter (see also next example) val limit = if (movie.credits?.cast?.size!! < 9) movie.credits?.cast?.size!! else 9 castingImagesAdapter = CastingImageListAdapter(movie.credits?.cast!!.copyOfRange(0, limit)) castingImagesRecyclerView?.adapter = castingImagesAdapter }else{ textView.visibility = GONE } } private fun formatGenreTags(movie: MovieDTO) = movie.genres ?.map { genre -> genre.name } ?.fold("", {acc: String, next: String -> if (acc.isEmpty()) acc + next else acc + " | " + next }) override fun onBackPressed() { super.onBackPressed() overridePendingTransition(R.anim.slide_from_left, R.anim.slide_to_right) } private fun provideDataToLayout(movie: MovieDTO) { movie.backdropPath?.let { backdrop_movie_img.loadBackdropUrl(it, false) } movie.posterPath?.let { poster_movie_img.loadPosterUrl(it) } movie.title?.let { movie_name.text = if (movie.title?.isEmpty()!!) movie.name else movie.title } storyline_content.text = movie.overview rating_score?.text = "%.1f".format(movie.voteAverage) runtime_length.text = movie.runtime.formatMovieRuntime() } }
gpl-3.0
2717105392a64fd971b21a86e2a0547b
37.783217
116
0.679048
4.764605
false
false
false
false
googlecodelabs/firebase-iap-optimization
app/app/src/main/java/org/tensorflow/lite/examples/iapoptimizer/MainActivity.kt
1
4426
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.tensorflow.lite.examples.iapoptimizer import android.annotation.SuppressLint import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.tasks.Task import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.analytics.ktx.logEvent import com.google.firebase.ktx.Firebase import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions import com.google.firebase.ml.common.modeldownload.FirebaseModelManager import com.google.firebase.ml.custom.FirebaseCustomRemoteModel private lateinit var firebaseAnalytics: FirebaseAnalytics class MainActivity : AppCompatActivity() { private var predictButton: Button? = null private var acceptButton: Button? = null private var predictedTextView: TextView? = null private var iapOptimizer = IapOptimizer(this) private var predictionResult = "" private var sessionId = "1" @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.tfe_dc_activity_main) // Obtain the FirebaseAnalytics instance. firebaseAnalytics = Firebase.analytics firebaseAnalytics.setUserId("player1") predictButton = findViewById(R.id.predict_button) acceptButton = findViewById(R.id.accept_button) predictedTextView = findViewById(R.id.predicted_text) predictedTextView?.text = "Click predict to see prediction result" predictButton?.setOnClickListener { val result = iapOptimizer.predict() predictedTextView?.text = "The best power-up to suggest: ${result}" predictionResult = result firebaseAnalytics.logEvent("offer_iap"){ param("offer_type", predictionResult) param("offer_id", sessionId) } } acceptButton?.setOnClickListener { firebaseAnalytics.logEvent("offer_accepted") { param("offer_type", predictionResult) param("offer_id", sessionId) } } downloadModel("optimizer") } private fun downloadModel(modelName: String): Task<Void> { val remoteModel = FirebaseCustomRemoteModel.Builder(modelName).build() val firebaseModelManager = FirebaseModelManager.getInstance() return firebaseModelManager .isModelDownloaded(remoteModel) .continueWithTask { task -> // Create update condition if model is already downloaded, otherwise create download // condition. val conditions = if (task.result != null && task.result == true) { FirebaseModelDownloadConditions.Builder() .requireWifi() .build() // Update condition that requires wifi. } else { FirebaseModelDownloadConditions.Builder().build(); // Download condition. } firebaseModelManager.download(remoteModel, conditions) } .addOnSuccessListener { firebaseModelManager.getLatestModelFile(remoteModel) .addOnCompleteListener { val model = it.result if (model == null) { showToast("Failed to get model file.") } else { showToast("Downloaded remote model: $modelName") iapOptimizer.initialize(model) } } } .addOnFailureListener { showToast("Model download failed for $modelName, please check your connection.") } } override fun onDestroy() { iapOptimizer.close() super.onDestroy() } private fun showToast(text: String) { Toast.makeText( this, text, Toast.LENGTH_LONG ).show() } companion object { private const val TAG = "MainActivity" } }
apache-2.0
530669c49fbddbafebf1a84c24c73d61
33.578125
92
0.70854
4.728632
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/UserPicker.kt
1
2750
package alraune import aplight.GelNew import pieces100.* import vgrechka.* @GelNew class UserPickerValue { var id by notNull<Long>() var text by notNull<String>() } fun composeUserPicker__killme(forceId: String? = null, initial: UserPickerValue? = null): AlTag { val select = select().style("width: 100%;") forceId?.let {select.id(it)} val code = StringBuilder() code.ln(""" ${select.jq()}.select2({ ajax: { url: "${UserSearchWebApi.path}", dataType: 'json', delay: 250, data: function (params) { return { q: params.term, // search term page: params.page }; }, processResults: function (data, params) { // parse the results into the format expected by Select2 // since we are using custom formatting functions we do not need to // alter the remote JSON data, except to indicate that infinite // scrolling can be used params.page = params.page || 1; return { results: data.items, pagination: { more: (params.page * ${UserSearchWebApi.pageSize}) < data.totalCount } }; }, cache: true }, placeholder: 'Поиск засранца', escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 1, templateResult: formatFucker, templateSelection: formatFuckerSelection, }) function formatFucker (fucker) { if (fucker.loading) { return ${TS.alraune.escapeHTML}(fucker.text); } var markup = "<div>" + ${TS.alraune.escapeHTML}(fucker.text) + "</div>" return markup } function formatFuckerSelection (fucker) { return ${TS.alraune.escapeHTML}(fucker.text) } """) if (initial != null) { code.ln(""" const data = ${jsonize(initial)} var option = new Option(data.text, data.id, true, true) ${select.jq()}.append(option).trigger('change') // manually trigger the `select2:select` event ${select.jq()}.trigger({ type: 'select2:select', params: { data: data } }) """) } Context1.get().jsOnDomReady.appendIife(code.toString()) return select }
apache-2.0
70cb12581281ea90b2b02e9e403d7b0b
29.411111
98
0.48776
4.940433
false
false
false
false