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
noud02/Akatsuki
src/main/kotlin/moe/kyubey/akatsuki/db/schema/Guilds.kt
1
2332
/* * Copyright (c) 2017-2019 Yui * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package moe.kyubey.akatsuki.db.schema import me.aurieh.ares.exposed.pg.jsonbMap import me.aurieh.ares.exposed.pg.pgArray import org.jetbrains.exposed.sql.Table object Guilds : Table() { val id = long("id") .uniqueIndex() .primaryKey() val name = varchar("name", 100) val lang = varchar("lang", 5) val prefixes = pgArray<String>("prefixes", "varchar") val forceLang = bool("forceLang") val starboard = bool("starboard") val starboardChannel = long("starboardChannel") .nullable() val logs = bool("logs") val modlogs = bool("modlogs") val modlogChannel = long("modlogChannel") .nullable() val rolemeRoles = jsonbMap<String, Long>("rolemeRoles") val welcome = bool("welcome") val welcomeChannel = long("welcomeChannel") .nullable() val welcomeMessage = varchar("welcomeMessage", 2000) val leaveMessage = varchar("leaveMessage", 2000) val ignoredChannels = pgArray<Long>("ignoredChannels", "BIGINT") val levelMessages = bool("levelMessages") val mutedRole = long("mutedRole") .nullable() val antiInvite = bool("antiInvite") }
mit
4e69eb97833545a9b784fd7387ce755d
39.224138
70
0.691681
4.105634
false
false
false
false
androidx/androidx
glance/glance-appwidget/integration-tests/demos/src/main/java/androidx/glance/appwidget/demos/DefaultStateAppWidget.kt
3
3439
package androidx.glance.appwidget.demos import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.ui.unit.dp import androidx.datastore.preferences.core.intPreferencesKey import androidx.glance.Button import androidx.glance.GlanceId import androidx.glance.GlanceModifier import androidx.glance.action.ActionParameters import androidx.glance.action.actionParametersOf import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.action.ActionCallback import androidx.glance.appwidget.action.actionRunCallback import androidx.glance.appwidget.appWidgetBackground import androidx.glance.appwidget.state.updateAppWidgetState import androidx.glance.background import androidx.glance.currentState import androidx.glance.layout.Alignment import androidx.glance.layout.Row import androidx.glance.layout.fillMaxSize import androidx.glance.layout.padding import androidx.glance.text.Text import androidx.glance.text.TextAlign import androidx.glance.text.TextStyle // Defines a state key for [currentState] private val CountClicksKey = intPreferencesKey("CountClicks") // Defines an action key for [actionRunCallback] private val ClickValueKey = ActionParameters.Key<Int>("ClickValue") // Showcases a simple widget that uses the default [stateDefinition] of [GlanceAppWidget] to store // the +/- clicks values. class DefaultStateAppWidget : GlanceAppWidget() { @Composable override fun Content() { // Get the current stored value for the given Key. val count = currentState(CountClicksKey) ?: 0 Row( modifier = GlanceModifier.fillMaxSize() .appWidgetBackground() .padding(16.dp) .background(R.color.default_widget_background), verticalAlignment = Alignment.CenterVertically ) { Button( modifier = GlanceModifier.defaultWeight(), text = "-", style = TextStyle(textAlign = TextAlign.Center), onClick = actionRunCallback<ClickAction>( actionParametersOf(ClickValueKey to -1) ) ) Text( modifier = GlanceModifier.defaultWeight(), text = "$count", style = TextStyle(textAlign = TextAlign.Center) ) Button( modifier = GlanceModifier.defaultWeight(), text = "+", style = TextStyle(textAlign = TextAlign.Center), onClick = actionRunCallback<ClickAction>( actionParametersOf(ClickValueKey to 1) ) ) } } } class ClickAction : ActionCallback { override suspend fun onAction( context: Context, glanceId: GlanceId, parameters: ActionParameters ) { // Get the current state of the given widget and the value provided in the ActionParameters updateAppWidgetState(context, glanceId) { state -> state[CountClicksKey] = (state[CountClicksKey] ?: 0) + (parameters[ClickValueKey] ?: 0) } // Trigger the widget update DefaultStateAppWidget().update(context, glanceId) } } class DefaultStateAppWidgetReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget: GlanceAppWidget = DefaultStateAppWidget() }
apache-2.0
eaaf29e0c2b2a84644b6d8db9a7ee249
36.391304
99
0.688572
5.079764
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/lang/core/psi/ElmPsiElementImpl.kt
1
2963
package org.elm.lang.core.psi import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.extapi.psi.StubBasedPsiElementBase import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.StubBasedPsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.stubs.StubElement import org.elm.lang.core.ElmFileType import org.elm.lang.core.resolve.reference.ElmReference import org.elm.workspace.ElmProject import org.elm.workspace.elmWorkspace /** * Base interface for all Elm Psi elements */ interface ElmPsiElement : PsiElement { /** * Get the file containing this element as an [ElmFile] */ val elmFile: ElmFile /** * Get the Elm project which this element's file belongs to. * * Returns null if the containing Elm project's manifest (`elm.json`) has not * yet been attached to the workspace. */ val elmProject: ElmProject? } /** * Base class for normal Elm Psi elements */ abstract class ElmPsiElementImpl(node: ASTNode) : ASTWrapperPsiElement(node), ElmPsiElement { override val elmFile: ElmFile get() = containingFile as ElmFile override val elmProject: ElmProject? get() = elmFile.elmProject // Make the type-system happy by using our reference interface instead of PsiReference override fun getReferences(): Array<ElmReference> { val ref = getReference() as? ElmReference ?: return EMPTY_REFERENCE_ARRAY return arrayOf(ref) } } /** * Base class for Elm Psi elements which can be stubbed */ abstract class ElmStubbedElement<StubT : StubElement<*>> : StubBasedPsiElementBase<StubT>, StubBasedPsiElement<StubT>, ElmPsiElement { constructor(node: ASTNode) : super(node) constructor(stub: StubT, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override val elmFile: ElmFile get() = containingFile as ElmFile override val elmProject: ElmProject? get() = project.elmWorkspace.findProjectForFile(elmFile.virtualFile) // Make the type-system happy by using our reference interface instead of PsiReference override fun getReferences(): Array<ElmReference> { val ref = getReference() as? ElmReference ?: return EMPTY_REFERENCE_ARRAY return arrayOf(ref) } override fun getUseScope(): SearchScope { // Restrict find-usages to only look at `*.elm` files in the current IntelliJ project. val baseScope = GlobalSearchScope.projectScope(project) return GlobalSearchScope.getScopeRestrictedByFileTypes(baseScope, ElmFileType) } // this is needed to match how [ASTWrapperPsiElement] implements `toString()` override fun toString(): String = "${javaClass.simpleName}($elementType)" } private val EMPTY_REFERENCE_ARRAY = emptyArray<ElmReference>()
mit
362eb7a2b2595536bb2ce73b08bcae5c
32.303371
94
0.724941
4.608087
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/ui/view/bbcode/prototype/AgeRestrictionPrototype.kt
1
2924
package me.proxer.app.ui.view.bbcode.prototype import android.graphics.Typeface import android.view.Gravity.CENTER import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.LinearLayout.VERTICAL import androidx.core.view.updateMargins import me.proxer.app.R import me.proxer.app.ui.view.bbcode.BBArgs import me.proxer.app.ui.view.bbcode.BBCodeView import me.proxer.app.ui.view.bbcode.BBTree import me.proxer.app.ui.view.bbcode.prototype.BBPrototype.Companion.REGEX_OPTIONS import me.proxer.app.util.data.PreferenceHelper import me.proxer.app.util.extension.dip import me.proxer.app.util.extension.resolveColor import me.proxer.app.util.extension.safeInject import org.koin.core.KoinComponent /** * @author Ruben Gees */ object AgeRestrictionPrototype : AutoClosingPrototype, KoinComponent { override val startRegex = Regex(" *age18( .*?)?", REGEX_OPTIONS) override val endRegex = Regex("/ *age18 *", REGEX_OPTIONS) private val preferenceHelper by safeInject<PreferenceHelper>() override fun makeViews(parent: BBCodeView, children: List<BBTree>, args: BBArgs): List<View> { val childViews = super.makeViews(parent, children, args) return when { childViews.isEmpty() -> childViews !preferenceHelper.isAgeRestrictedMediaAllowed -> listOf(FrameLayout(parent.context).apply { val text = parent.context.getString(R.string.view_bbcode_hide_age_restricted) layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, WRAP_CONTENT) addView(TextPrototype.makeView(parent, args + BBArgs(text = text)).apply { setTag(R.id.ignore_tag, Unit) gravity = CENTER }) }) else -> listOf(LinearLayout(parent.context).apply { val fourDip = dip(4) val text = parent.context.getString(R.string.view_bbcode_age_restricted) layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, WRAP_CONTENT) orientation = VERTICAL setPadding(fourDip, fourDip, fourDip, fourDip) setBackgroundColor(parent.context.resolveColor(R.attr.colorSelectedSurface)) addView(TextPrototype.makeView(parent, args + BBArgs(text = text)).apply { setTag(R.id.ignore_tag, Unit) layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { updateMargins(bottom = fourDip * 4) } typeface = Typeface.DEFAULT_BOLD gravity = CENTER }) childViews.forEach { addView(it) } }) } } }
gpl-3.0
8722bf770c4d474bcb16573d277267a3
37.986667
103
0.669631
4.533333
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/model/entity/DashboardItem.kt
1
1057
package com.intfocus.template.model.entity /** * Created by liuruilin on 2017/8/1. */ class DashboardItem { var obj_link: String? = null var obj_title: String? = null var obj_id: String? = null var template_id: String? = null var objectType: String? = null var paramsMappingBean: HashMap<String, String>? = null constructor() constructor(obj_link: String, obj_title: String, obj_id: String, template_id: String, objectType: String) : this() { this.obj_link = obj_link this.obj_title = obj_title this.obj_id = obj_id this.template_id = template_id this.objectType = objectType } constructor(obj_link: String, obj_title: String, obj_id: String, template_id: String, objectType: String, paramsMappingBean: HashMap<String, String>) : this() { this.obj_link = obj_link this.obj_title = obj_title this.obj_id = obj_id this.template_id = template_id this.objectType = objectType this.paramsMappingBean = paramsMappingBean } }
gpl-3.0
b2147f8c3011c519a3923eac3528e70b
32.03125
164
0.647114
3.682927
false
false
false
false
saki4510t/libcommon
app/src/main/java/com/serenegiant/libcommon/EffectCameraFragment.kt
1
5491
package com.serenegiant.libcommon /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2022 saki [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. */ import android.content.Context import android.os.Build import android.os.Bundle import android.os.Environment import android.util.Log import android.view.View import androidx.annotation.RequiresApi import androidx.documentfile.provider.DocumentFile import com.serenegiant.gl.GLEffect import com.serenegiant.media.MediaFileUtils import com.serenegiant.mediastore.MediaStoreUtils import com.serenegiant.service.ServiceRecorder import com.serenegiant.system.BuildCheck import com.serenegiant.utils.FileUtils import com.serenegiant.widget.EffectCameraGLSurfaceView import com.serenegiant.widget.GLPipelineView import java.io.IOException class EffectCameraFragment : AbstractCameraFragment() { private var mRecorder: ServiceRecorder? = null override fun isRecording(): Boolean { return mRecorder != null } override fun internalStartRecording() { if (DEBUG) Log.v(TAG, "internalStartRecording:mRecorder=$mRecorder") if (mRecorder == null) { if (DEBUG) Log.v(TAG, "internalStartRecording:get PostMuxRecorder") mRecorder = ServiceRecorder(requireContext(), mCallback) } else { Log.w(TAG, "internalStartRecording:recorder is not null, already start recording?") } } override fun internalStopRecording() { if (DEBUG) Log.v(TAG, "internalStopRecording:mRecorder=$mRecorder") val recorder = mRecorder mRecorder = null recorder?.release() } override fun onFrameAvailable() { val recorder = mRecorder recorder?.frameAvailableSoon() } private var mRecordingSurfaceId = 0 private val mCallback = object: ServiceRecorder.Callback { override fun onConnected() { if (DEBUG) Log.v(TAG, "onConnected:") if (mRecordingSurfaceId != 0) { mCameraView!!.removeSurface(mRecordingSurfaceId) mRecordingSurfaceId = 0 } val recorder = mRecorder if (recorder != null) { try { recorder.setVideoSettings(VIDEO_WIDTH, VIDEO_HEIGHT, VIDEO_FPS, 0.25f) recorder.setAudioSettings(SAMPLE_RATE, CHANNEL_COUNT) recorder.prepare() } catch (e: Exception) { Log.w(TAG, e) stopRecording() // 非同期で呼ばないとデッドロックするかも } } } @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) override fun onPrepared() { if (DEBUG) Log.v(TAG, "onPrepared:") val recorder = mRecorder if (recorder != null) { try { val surface = recorder.inputSurface // API>=18 if (surface != null) { mRecordingSurfaceId = surface.hashCode() mCameraView!!.addSurface(mRecordingSurfaceId, surface, true) } else { Log.w(TAG, "surface is null") stopRecording() // 非同期で呼ばないとデッドロックするかも } } catch (e: Exception) { Log.w(TAG, e) stopRecording() // 非同期で呼ばないとデッドロックするかも } } } override fun onReady() { if (DEBUG) Log.v(TAG, "onReady:") val recorder = mRecorder if (recorder != null) { val context: Context = requireContext() try { val output: DocumentFile? = if (BuildCheck.isAPI29()) { // API29以降は対象範囲別ストレージ MediaStoreUtils.getContentDocument( context, "video/mp4", null, FileUtils.getDateTimeString() + ".mp4", null) } else { val dir = MediaFileUtils.getRecordingRoot( context, Environment.DIRECTORY_MOVIES, Const.REQUEST_ACCESS_SD) dir!!.createFile("*/*", FileUtils.getDateTimeString() + ".mp4") } if (DEBUG) Log.v(TAG, "onReady:output=$output," + output?.uri) if (output != null) { recorder.start(output) } else { throw IOException() } } catch (e: Exception) { Log.w(TAG, e) stopRecording() // 非同期で呼ばないとデッドロックするかも } } } override fun onDisconnected() { if (DEBUG) Log.v(TAG, "onDisconnected:") if (mRecordingSurfaceId != 0) { mCameraView!!.removeSurface(mRecordingSurfaceId) mRecordingSurfaceId = 0 } stopRecording() } } override fun onLongClick(view: View): Boolean { super.onLongClick(view) if (mCameraView is EffectCameraGLSurfaceView) { val v = view as EffectCameraGLSurfaceView v.effect = (v.effect + 1) % GLEffect.EFFECT_NUM return true } return false } companion object { private const val DEBUG = true // TODO set false on release private val TAG = EffectCameraFragment::class.java.simpleName fun newInstance(pipelineMode: Int = GLPipelineView.EFFECT_ONLY): EffectCameraFragment { val fragment = EffectCameraFragment() val args = Bundle() args.putInt(ARGS_KEY_LAYOUT_ID, R.layout.fragment_camera_effect) args.putInt(ARGS_KEY_TITLE_ID, R.string.title_effect_camera) args.putInt(ARGS_KEY_PIPELINE_MODE, pipelineMode) fragment.arguments = args return fragment } } }
apache-2.0
44b93a82e2c7f50944abd3e36a1023ee
29.36
89
0.706569
3.438835
false
false
false
false
ligee/kotlin-jupyter
build-plugin/src/build/InstallTasksConfigurator.kt
1
6410
package build import build.util.makeDirs import build.util.makeTaskName import build.util.writeJson import org.gradle.api.Project import org.gradle.api.tasks.Copy import org.gradle.api.tasks.TaskProvider import org.gradle.kotlin.dsl.get import org.gradle.kotlin.dsl.register import java.io.File class InstallTasksConfigurator( private val project: Project, private val settings: RootSettingsExtension, ) { fun registerLocalInstallTasks() { project.tasks.register<Copy>(COPY_RUN_KERNEL_PY_TASK) { group = LOCAL_INSTALL_GROUP dependsOn(makeTaskName(settings.cleanInstallDirTaskPrefix, true)) moduleFromDistributionDir(settings.runKotlinKernelModule) moduleFromDistributionDir(settings.kotlinKernelModule) into(settings.localInstallDir) from(settings.distributionDir.resolve(settings.localRunPy)) } project.tasks.register<Copy>(COPY_NB_EXTENSION_TASK) { group = LOCAL_INSTALL_GROUP from(settings.nbExtensionDir) into(settings.localInstallDir) } registerInstallTasks(true, settings.localInstallDir, settings.localInstallDir) project.tasks.register(UNINSTALL_TASK) { group = LOCAL_INSTALL_GROUP dependsOn(makeTaskName(settings.cleanInstallDirTaskPrefix, false)) } } fun registerInstallTasks(local: Boolean, specPath: File, mainInstallPath: File) { val groupName = if (local) LOCAL_INSTALL_GROUP else DISTRIBUTION_GROUP val cleanDirTask = project.tasks.named(makeTaskName(settings.cleanInstallDirTaskPrefix, local)) val shadowJar = project.tasks.named(SHADOW_JAR_TASK) val updateLibrariesTask = project.tasks.named(UPDATE_LIBRARIES_TASK) project.tasks.register<Copy>(makeTaskName(settings.copyLibrariesTaskPrefix, local)) { dependsOn(cleanDirTask, updateLibrariesTask) group = groupName from(settings.librariesDir) into(mainInstallPath.librariesDir) } project.tasks.register<Copy>(makeTaskName(settings.installLibsTaskPrefix, local)) { dependsOn(cleanDirTask) group = groupName from(project.configurations["deploy"]) into(mainInstallPath.localJarsDir) } project.tasks.register<Copy>(makeTaskName(settings.installKernelTaskPrefix, local)) { dependsOn(cleanDirTask, shadowJar) group = groupName from(shadowJar.get().outputs) into(mainInstallPath.localJarsDir) } listOf(true, false).forEach { debug -> val specTaskName = registerTaskForSpecs(debug, local, groupName, cleanDirTask, shadowJar, specPath, mainInstallPath) registerMainInstallTask(debug, local, groupName, specTaskName) } } private fun registerTaskForSpecs( debug: Boolean, local: Boolean, group: String, cleanDir: TaskProvider<*>, shadowJar: TaskProvider<*>, specPath: File, mainInstallPath: File ): String { val taskName = makeTaskName("create${debugStr(debug)}Specs", local) project.tasks.register(taskName) { this.group = group dependsOn(cleanDir, shadowJar) doLast { val kernelFile = project.files(shadowJar).singleFile val libsCp = project.files(project.configurations["deploy"]).files.map { it.name } makeDirs(mainInstallPath.localJarsDir) makeDirs(mainInstallPath.configDir) makeDirs(specPath) writeJson( mapOf( "mainJar" to kernelFile.name, "mainClass" to settings.mainClassFQN, "classPath" to libsCp, "debuggerPort" to if (debug) settings.debuggerPort else "" ), mainInstallPath.jarArgsFile ) makeKernelSpec(specPath, local) } } return taskName } private fun registerMainInstallTask(debug: Boolean, local: Boolean, group: String, specsTaskName: String) { project.tasks.register(mainInstallTaskName(debug, local)) { this.group = group dependsOn( makeTaskName(settings.cleanInstallDirTaskPrefix, local), if (local) COPY_RUN_KERNEL_PY_TASK else PREPARE_DISTRIBUTION_DIR_TASK, makeTaskName(settings.installKernelTaskPrefix, local), makeTaskName(settings.installLibsTaskPrefix, local), specsTaskName, makeTaskName(settings.copyLibrariesTaskPrefix, local), ) } } private fun makeKernelSpec(installPath: File, localInstall: Boolean) { val firstArg = if (localInstall) installPath.resolve(settings.localRunPy).toString() else "-m" fun execPythonArgs(vararg args: String) = listOf("python", firstArg, *args) val argv = execPythonArgs(settings.runKotlinKernelModule, "{connection_file}") val jarsPathDetectorArgv = execPythonArgs(settings.kotlinKernelModule, "detect-jars-location") writeJson( mapOf( "display_name" to "Kotlin", "language" to "kotlin", "interrupt_mode" to "message", "argv" to argv, "metadata" to mapOf( "jar_path_detect_command" to jarsPathDetectorArgv, ), ), installPath.resolve(settings.kernelFile) ) project.copy { from(settings.nbExtensionDir, settings.logosDir) into(installPath) } } private val File.localJarsDir get() = resolve(settings.runKotlinKernelModule).resolve(settings.jarsPath) private val File.librariesDir get() = resolve(settings.runKotlinKernelModule).resolve(settings.librariesDir) private val File.configDir get() = resolve(settings.runKotlinKernelModule).resolve(settings.configDir) private val File.jarArgsFile get() = resolve(settings.runKotlinKernelModule).resolve(settings.jarArgsFile) private fun Copy.moduleFromDistributionDir(moduleName: String) { from(settings.distributionDir.resolve(moduleName)) { into(moduleName) } } }
apache-2.0
0b8cd27999a9bf18e626351f4fa31e2b
38.813665
128
0.63947
4.588404
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/cafeteria/CafeteriaNotificationProvider.kt
1
3570
package de.tum.`in`.tumcampusapp.component.ui.cafeteria import android.app.PendingIntent import android.content.Context import androidx.core.app.NotificationCompat import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.notifications.NotificationProvider import de.tum.`in`.tumcampusapp.component.notifications.model.AppNotification import de.tum.`in`.tumcampusapp.component.notifications.model.InstantNotification import de.tum.`in`.tumcampusapp.component.notifications.persistence.NotificationType import de.tum.`in`.tumcampusapp.component.other.locations.LocationManager import de.tum.`in`.tumcampusapp.component.ui.cafeteria.controller.CafeteriaMenuManager import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.MenuType import de.tum.`in`.tumcampusapp.component.ui.cafeteria.repository.CafeteriaLocalRepository import de.tum.`in`.tumcampusapp.database.TcaDb import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.DateTimeUtils import org.joda.time.DateTime class CafeteriaNotificationProvider(context: Context) : NotificationProvider(context) { private val cafeteriaMenuManager = CafeteriaMenuManager(context) private val cafeteriaLocalRepository = CafeteriaLocalRepository(TcaDb.getInstance(context)) override fun getNotificationBuilder(): NotificationCompat.Builder { return NotificationCompat.Builder(context, Const.NOTIFICATION_CHANNEL_CAFETERIA) .setAutoCancel(true) .setSmallIcon(R.drawable.ic_cutlery) .setGroup(GROUP_KEY_CAFETERIA) .setGroupSummary(true) .setShowWhen(false) .setColor(notificationColorAccent) } override fun buildNotification(): AppNotification? { val cafeteriaId = LocationManager(context).getCafeteria() if (cafeteriaId == Const.NO_CAFETERIA_FOUND) { return null } val cafeteria = cafeteriaLocalRepository.getCafeteriaWithMenus(cafeteriaId) val menus = cafeteria.menus.filter { it.menuType != MenuType.SIDE_DISH } val intent = cafeteria.getIntent(context) val inboxStyle = NotificationCompat.InboxStyle() menus.forEach { inboxStyle.addLine(it.notificationTitle) } val title = context.getString(R.string.cafeteria) val favoriteDishes = cafeteriaMenuManager.getFavoriteDishesServed(cafeteriaId, DateTime.now()) // If any of the user's favorite dishes are served, we include them in the notification // text. Otherwise, we simply put the day's date. val text = if (favoriteDishes.isNotEmpty()) { val dishes = favoriteDishes.joinToString(", ") { it.name } context.getString(R.string.including_format_string, dishes) } else { DateTimeUtils.getDateString(cafeteria.nextMenuDate) } val pendingIntent = PendingIntent.getActivity( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) val summaryNotification = getNotificationBuilder() .setContentTitle(title) .setContentText(text) .setStyle(inboxStyle) .setContentIntent(pendingIntent) .build() // We can pass 0 as the notification ID because only one notification at a time // will be active return InstantNotification(NotificationType.CAFETERIA, cafeteria.id, summaryNotification) } companion object { private const val GROUP_KEY_CAFETERIA = "de.tum.in.tumcampus.CAFETERIA" } }
gpl-3.0
72b2dd1eb5d8b2438659098277061631
44.189873
102
0.718768
4.741036
false
false
false
false
geckour/Glyph
app/src/main/java/jp/org/example/geckour/glyph/ui/StatsSequenceFragment.kt
1
2662
package jp.org.example.geckour.glyph.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import io.realm.Realm import jp.org.example.geckour.glyph.adapter.StatsFragmentRecyclerAdapter import jp.org.example.geckour.glyph.databinding.FragmentStatisticsBinding import jp.org.example.geckour.glyph.db.model.Sequence import jp.org.example.geckour.glyph.ui.model.Statistics import jp.org.example.geckour.glyph.util.parse class StatsSequenceFragment : Fragment() { companion object { fun createInstance(): StatsSequenceFragment = StatsSequenceFragment() } private lateinit var binding: FragmentStatisticsBinding private lateinit var adapter: StatsFragmentRecyclerAdapter private val realm: Realm = Realm.getDefaultInstance() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentStatisticsBinding.inflate(inflater, container, false) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) adapter = StatsFragmentRecyclerAdapter((activity as StatsActivity).bitmap) binding.recyclerView.adapter = adapter val splitList: List<List<Statistics>> = List(4) { getSequenceStatistics(it + 2).sortedBy { it.sequenceData.name } } adapter.addItems(splitList.reversed().flatten()) } private fun getSequenceStatistics(difficulty: Int): List<Statistics> { if ((difficulty in 2..5).not()) return emptyList() return realm.where(Sequence::class.java) .equalTo("size", difficulty) .findAll() .toList() .map { sequence -> sequence.message.map { it.parse() }.let { Statistics( Statistics.Data(sequence.id, it.joinToString(" ") { it.name }, sequence.correctCount, sequence.examCount, null), it.map { Statistics.Data(it.id, it.name, it.correctCount, it.examCount, null) } ) } } } override fun onDestroy() { super.onDestroy() realm.close() } }
gpl-2.0
8410ef5f03a1b53f50ccd4ba2ee75fb8
34.986486
90
0.592036
5.250493
false
false
false
false
grueni75/GeoDiscoverer
Source/Platform/Target/Android/mobile/src/main/java/com/untouchableapps/android/geodiscoverer/ui/activity/RequestPermissions.kt
1
4053
//============================================================================ // Name : RequestPermissions.kt // Author : Matthias Gruenewald // Copyright : Copyright 2010-2021 Matthias Gruenewald // // This file is part of GeoDiscoverer. // // GeoDiscoverer 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. // // GeoDiscoverer 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 GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>. // //============================================================================ package com.untouchableapps.android.geodiscoverer.ui.activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.Settings import android.util.Log import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.untouchableapps.android.geodiscoverer.GDApplication import com.untouchableapps.android.geodiscoverer.R import com.untouchableapps.android.geodiscoverer.core.GDAppInterface import com.untouchableapps.android.geodiscoverer.ui.theme.AndroidTheme import java.util.* import kotlin.system.exitProcess @ExperimentalMaterial3Api class RequestPermissions : ComponentActivity() { val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { permissions -> permissions.entries.forEach { Log.d("GDApp", "${it.key} = ${it.value}") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AndroidTheme { content() } } } override fun onResume() { super.onResume() if (!GDApplication.checkPermissions(this)) { requestPermissionLauncher.launch(GDApplication.requiredPermissions) /*if (!Settings.canDrawOverlays(applicationContext)) { val packageName = applicationContext.packageName val t = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName")) Toast.makeText( this, getString(R.string.request_permissions_overlay_instructions), Toast.LENGTH_LONG ).show() startActivity(t) }*/ } else { Toast.makeText( this, getString(R.string.request_permissions_wait_for_restart), Toast.LENGTH_LONG ).show() val app: GDApplication = application as GDApplication app.scheduleRestart(); Timer().schedule(object : TimerTask() { override fun run() { exitProcess(0); } }, 3000) finish(); } } @ExperimentalMaterial3Api @Composable fun content() { Scaffold( topBar = { SmallTopAppBar( title = { Text(stringResource(id = R.string.app_name)) } ) }, content = { _ -> Column( modifier = Modifier .padding(10.dp) ) { Text( text = stringResource(id = R.string.request_permissions_description) ) } } ) } @ExperimentalMaterial3Api @Preview(showBackground = true) @Composable fun preview() { AndroidTheme { content() } } }
gpl-3.0
8fa78d5cf11254243a2cb7354acfb665
29.704545
100
0.673328
4.405435
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/completion/providers/EQNameCompletionType.kt
1
1545
/* * Copyright (C) 2019 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.completion.providers import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xdm.types.element enum class EQNameCompletionType { NCName, QNamePrefix, QNameLocalName, URIQualifiedNameBracedURI, URIQualifiedNameLocalName } fun XsQNameValue.completionType(element: PsiElement): EQNameCompletionType? = when (isLexicalQName) { true -> when { prefix == null -> EQNameCompletionType.NCName prefix?.element === element -> EQNameCompletionType.QNamePrefix localName?.element === element -> EQNameCompletionType.QNameLocalName else -> null } else -> when { namespace?.element === element -> EQNameCompletionType.URIQualifiedNameBracedURI localName?.element === element -> EQNameCompletionType.URIQualifiedNameLocalName else -> null } }
apache-2.0
bbb9d4640fd69ff6dc4e210a28fb7378
35.785714
101
0.734628
4.504373
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackSearchAdapter.kt
1
2966
package eu.kanade.tachiyomi.ui.manga.track import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import com.bumptech.glide.load.engine.DiskCacheStrategy import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.glide.GlideApp import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.util.gone import eu.kanade.tachiyomi.util.inflate import kotlinx.android.synthetic.main.track_search_item.view.* import java.util.* class TrackSearchAdapter(context: Context) : ArrayAdapter<TrackSearch>(context, R.layout.track_search_item, ArrayList<TrackSearch>()) { override fun getView(position: Int, view: View?, parent: ViewGroup): View { var v = view // Get the data item for this position val track = getItem(position) // Check if an existing view is being reused, otherwise inflate the view val holder: TrackSearchHolder // view lookup cache stored in tag if (v == null) { v = parent.inflate(R.layout.track_search_item) holder = TrackSearchHolder(v) v.tag = holder } else { holder = v.tag as TrackSearchHolder } holder.onSetValues(track) return v } fun setItems(syncs: List<TrackSearch>) { setNotifyOnChange(false) clear() addAll(syncs) notifyDataSetChanged() } class TrackSearchHolder(private val view: View) { fun onSetValues(track: TrackSearch) { view.track_search_title.text = track.title view.track_search_summary.text = track.summary GlideApp.with(view.context).clear(view.track_search_cover) if (!track.cover_url.isNullOrEmpty()) { GlideApp.with(view.context) .load(track.cover_url) .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .centerCrop() .into(view.track_search_cover) } if (track.publishing_status.isNullOrBlank()) { view.track_search_status.gone() view.track_search_status_result.gone() } else { view.track_search_status_result.text = track.publishing_status.capitalize() } if (track.publishing_type.isNullOrBlank()) { view.track_search_type.gone() view.track_search_type_result.gone() } else { view.track_search_type_result.text = track.publishing_type.capitalize() } if (track.start_date.isNullOrBlank()) { view.track_search_start.gone() view.track_search_start_result.gone() } else { view.track_search_start_result.text = track.start_date } } } }
apache-2.0
618a2e29c07f057b1bc8d2a69eeb6be0
35.56962
96
0.595415
4.407132
false
false
false
false
hitoshura25/Media-Player-Omega-Android
auth_framework/src/main/java/com/vmenon/mpo/auth/framework/SharedPrefsAuthState.kt
1
5670
package com.vmenon.mpo.auth.framework import android.content.Context import androidx.annotation.VisibleForTesting import com.google.gson.Gson import com.vmenon.mpo.auth.data.AuthState import com.vmenon.mpo.auth.domain.CipherEncryptedData import com.vmenon.mpo.auth.domain.Credentials import com.vmenon.mpo.auth.domain.CredentialsResult import com.vmenon.mpo.auth.domain.CredentialsResult.RequiresBiometricAuth import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.launch import javax.crypto.Cipher open class SharedPrefsAuthState(context: Context) : AuthState { private val cryptographyManager = CryptographyManager() private val gson = Gson() private val sharedPreferences = context.getSharedPreferences( SHARED_PREFS_FILE, Context.MODE_PRIVATE ) private var biometricEncryptionCipher: Cipher? = null @VisibleForTesting protected var biometricDecryptionCipher: Cipher? = null private val credentialState = MutableSharedFlow<CredentialsResult>(replay = 1) private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) @VisibleForTesting protected var storedCredentials: CredentialsResult? = null protected set(value) { if (field != value) { field = value scope.launch { credentialState.emit(value ?: CredentialsResult.None) } } } init { scope.launch { getCredentials() } } override suspend fun getCredentials(): CredentialsResult { if (storedCredentials == null || storedCredentials is RequiresBiometricAuth) { storedCredentials = readFromSharedPrefs() } return storedCredentials ?: CredentialsResult.None } override fun credentials(): Flow<CredentialsResult> = credentialState override suspend fun didUserLogOut(): Boolean = sharedPreferences.getBoolean(USER_LOGGED_OUT, true) override suspend fun storeCredentials(credentials: Credentials) { storeToSharedPrefs(credentials) this.storedCredentials = CredentialsResult.Success(credentials) } override suspend fun userLoggedOut() { val encrypted = sharedPreferences.getBoolean(ENCRYPTED_WITH_BIOMETRICS, false) if (!encrypted) { sharedPreferences.edit().clear().apply() } sharedPreferences.edit().putBoolean(USER_LOGGED_OUT, true).apply() this.storedCredentials = null this.biometricDecryptionCipher = null this.biometricEncryptionCipher = null } override suspend fun encryptCredentials(cipher: Cipher) { if (biometricEncryptionCipher != cipher) { biometricEncryptionCipher = cipher sharedPreferences.edit().putBoolean(ENCRYPTED_WITH_BIOMETRICS, true).apply() when (val credentialsResult = getCredentials()) { is CredentialsResult.Success -> storeToSharedPrefs( credentialsResult.credentials ) } } } override suspend fun decryptCredentials(cipher: Cipher) { if (biometricDecryptionCipher != cipher) { biometricDecryptionCipher = cipher } if (getCredentials() is CredentialsResult.Success) { sharedPreferences.edit().putBoolean(USER_LOGGED_OUT, false).apply() } } private fun readFromSharedPrefs(): CredentialsResult { val encrypted = sharedPreferences.getBoolean(ENCRYPTED_WITH_BIOMETRICS, false) val credentialsJson = sharedPreferences.getString(CREDENTIALS, null) return if (credentialsJson != null) { if (encrypted) { val encryptedCredentials = gson.fromJson( credentialsJson, CipherEncryptedData::class.java ) biometricDecryptionCipher?.let { biometricCipher -> val decrypted = cryptographyManager.decryptData( encryptedCredentials.ciphertext, biometricCipher ) CredentialsResult.Success(gson.fromJson(decrypted, Credentials::class.java)) } ?: RequiresBiometricAuth(encryptedCredentials) } else { CredentialsResult.Success(gson.fromJson(credentialsJson, Credentials::class.java)) } } else CredentialsResult.None } private fun storeToSharedPrefs(credentials: Credentials) { val credentialJSON = gson.toJson(credentials) val encrypted = sharedPreferences.getBoolean(ENCRYPTED_WITH_BIOMETRICS, false) if (encrypted) { biometricEncryptionCipher?.let { biometricCipher -> val cipherWrapper = cryptographyManager.encryptData(credentialJSON, biometricCipher) val encryptedJSON = Gson().toJson(cipherWrapper) sharedPreferences.edit().putString(CREDENTIALS, encryptedJSON).apply() } } else { sharedPreferences.edit().putString(CREDENTIALS, credentialJSON).apply() } sharedPreferences.edit().putBoolean(USER_LOGGED_OUT, false).apply() } companion object { private const val SHARED_PREFS_FILE = "mpo_credentials" private const val CREDENTIALS = "credentials" private const val ENCRYPTED_WITH_BIOMETRICS = "encrypted_with_biometrics" private const val USER_LOGGED_OUT = "credentials_cleared" } }
apache-2.0
ed4e26732f705509c9c37f4a700ac948
38.93662
100
0.668783
5.33396
false
false
false
false
edsilfer/android-kotlin-support
kotlin-support/src/main/java/br/com/edsilfer/kotlin_support/extensions/KotlinSupportLibrary_View.kt
1
1373
package br.com.edsilfer.kotlin_support.extensions import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.BitmapDrawable import android.view.View import android.view.View.MeasureSpec fun View.getBitmapDrawable(): BitmapDrawable { val spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) measure(spec, spec) layout(0, 0, measuredWidth, measuredHeight) val b = Bitmap.createBitmap(measuredWidth, measuredHeight, Bitmap.Config.ARGB_8888) val c = Canvas(b) c.translate(-scrollX.toFloat(), -scrollY.toFloat()) draw(c) isDrawingCacheEnabled = true val cacheBmp = drawingCache val viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true) destroyDrawingCache() return BitmapDrawable(resources, viewBmp) } fun View.getBitmap(): Bitmap { isDrawingCacheEnabled = true val bitmap = Bitmap.createBitmap(getDrawingCache()) isDrawingCacheEnabled = false return bitmap } fun View.locateView(): Rect? { val loc_int = IntArray(2) try { getLocationOnScreen(loc_int) } catch (npe: NullPointerException) { return null } val location = Rect() location.left = loc_int[0] location.top = loc_int[1] location.right = location.left + width location.bottom = location.top + height return location }
apache-2.0
859aa1153bdac8e1cc0cd0a3c923a597
27.625
87
0.723234
4.135542
false
false
false
false
saletrak/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/MarkDownStringExtensions.kt
2
422
package io.github.feelfreelinux.wykopmobilny.utils val String.markdownBold : String get() = "**${this}**" val String.markdownItalic : String get() = "_${this}_" val String.markdownQuote : String get() = "\n> ${this}" fun String.markdownLink(description : String): String = "[$description](${this})" val String.markdownSourceCode : String get() = "`${this}`" val String.markdownSpoiler : String get() = "\n! ${this}"
mit
a2d3e791cceb9f1a57dd90e78f7ef1b4
31.461538
81
0.682464
3.734513
false
false
false
false
Heiner1/AndroidAPS
automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt
1
3779
package info.nightscout.androidaps.plugins.general.automation import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.interfaces.ConfigBuilder import info.nightscout.androidaps.interfaces.Loop import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.automation.actions.Action import info.nightscout.androidaps.plugins.general.automation.actions.ActionLoopEnable import info.nightscout.androidaps.plugins.general.automation.actions.ActionStopProcessing import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnectorTest import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerDummy import org.json.JSONObject import org.junit.Assert import org.junit.Test import org.mockito.Mock class AutomationEventTest : TestBase() { @Mock lateinit var loopPlugin: Loop @Mock lateinit var rh: ResourceHelper @Mock lateinit var configBuilder: ConfigBuilder var injector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { if (it is AutomationEvent) { it.aapsLogger = aapsLogger } if (it is Action) { it.aapsLogger = aapsLogger } if (it is ActionLoopEnable) { it.loopPlugin = loopPlugin it.rh = rh it.configBuilder = configBuilder it.rxBus = RxBus(aapsSchedulers, aapsLogger) } } } @Test fun testCloneEvent() { // create test object val event = AutomationEvent(injector) event.title = "Test" event.trigger = TriggerDummy(injector).instantiate(JSONObject(TriggerConnectorTest.oneItem)) as TriggerConnector event.addAction(ActionLoopEnable(injector)) // export to json val eventJsonExpected = "{\"userAction\":false,\"autoRemove\":false,\"readOnly\":false,\"trigger\":\"{\\\"data\\\":{\\\"connectorType\\\":\\\"AND\\\",\\\"triggerList\\\":[\\\"{\\\\\\\"data\\\\\\\":{\\\\\\\"connectorType\\\\\\\":\\\\\\\"AND\\\\\\\",\\\\\\\"triggerList\\\\\\\":[]},\\\\\\\"type\\\\\\\":\\\\\\\"TriggerConnector\\\\\\\"}\\\"]},\\\"type\\\":\\\"TriggerConnector\\\"}\",\"title\":\"Test\",\"systemAction\":false,\"actions\":[\"{\\\"type\\\":\\\"ActionLoopEnable\\\"}\"],\"enabled\":true}" Assert.assertEquals(eventJsonExpected, event.toJSON()) // clone val clone = AutomationEvent(injector).fromJSON(eventJsonExpected, 1) // check title Assert.assertEquals(event.title, clone.title) // check trigger Assert.assertNotNull(clone.trigger) Assert.assertFalse(event.trigger === clone.trigger) // not the same object reference Assert.assertEquals(event.trigger.javaClass, clone.trigger.javaClass) Assert.assertEquals(event.trigger.toJSON(), clone.trigger.toJSON()) // check action Assert.assertEquals(1, clone.actions.size) Assert.assertFalse(event.actions === clone.actions) // not the same object reference Assert.assertEquals(clone.toJSON(), clone.toJSON()) } @Test fun hasStopProcessing() { val event = AutomationEvent(injector) event.title = "Test" event.trigger = TriggerDummy(injector).instantiate(JSONObject(TriggerConnectorTest.oneItem)) as TriggerConnector Assert.assertFalse(event.hasStopProcessing()) event.addAction(ActionStopProcessing(injector)) Assert.assertTrue(event.hasStopProcessing()) } }
agpl-3.0
365ee0e1741d3e450f13dbd87f5a6dc7
43.988095
488
0.679809
4.71197
false
true
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/dragHelpers/SimpleItemTouchHelperCallback.kt
1
1636
package info.nightscout.androidaps.utils.dragHelpers import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper.ACTION_STATE_DRAG import androidx.recyclerview.widget.ItemTouchHelper.DOWN import androidx.recyclerview.widget.ItemTouchHelper.END import androidx.recyclerview.widget.ItemTouchHelper.START import androidx.recyclerview.widget.ItemTouchHelper.UP import androidx.recyclerview.widget.RecyclerView const val ALPHA_FULL = 1f const val ALPHA_DRAGGING = 0.5f class SimpleItemTouchHelperCallback : ItemTouchHelper.SimpleCallback(UP or DOWN or START or END, 0) { override fun isLongPressDragEnabled() = false override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { val adapter = recyclerView.adapter as ItemTouchHelperAdapter val from = viewHolder.layoutPosition val to = target.layoutPosition adapter.onItemMove(from, to) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {} override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) { super.onSelectedChanged(viewHolder, actionState) if (actionState == ACTION_STATE_DRAG) { viewHolder?.itemView?.alpha = ALPHA_DRAGGING } } override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) { super.clearView(recyclerView, viewHolder) viewHolder.itemView.alpha = ALPHA_FULL (recyclerView.adapter as ItemTouchHelperAdapter).onDrop() } }
agpl-3.0
2b0004854db878d8855e58a7f83d5a82
38.902439
132
0.766504
5.160883
false
false
false
false
wbaumann/SmartReceiptsLibrary
app/src/main/java/co/smartreceipts/android/identity/widget/account/AccountFragment.kt
1
8165
package co.smartreceipts.android.identity.widget.account import android.content.Context import android.os.Bundle import android.view.* import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import co.smartreceipts.android.R import co.smartreceipts.android.databinding.AccountInfoFragmentBinding import co.smartreceipts.android.date.DateFormatter import co.smartreceipts.android.identity.apis.organizations.OrganizationModel import co.smartreceipts.core.identity.store.EmailAddress import co.smartreceipts.android.identity.widget.account.organizations.OrganizationsListAdapter import co.smartreceipts.android.identity.widget.account.subscriptions.SubscriptionsListAdapter import co.smartreceipts.android.purchases.subscriptions.RemoteSubscription import co.smartreceipts.android.widget.model.UiIndicator import com.jakewharton.rxbinding3.view.clicks import dagger.android.support.AndroidSupportInjection import io.reactivex.Observable import kotlinx.android.synthetic.main.account_info_fragment.* import javax.inject.Inject class AccountFragment : Fragment(), AccountView { @Inject lateinit var presenter: AccountPresenter @Inject lateinit var router: AccountRouter @Inject lateinit var dateFormatter: DateFormatter private var wasPreviouslySentToLogin: Boolean = false private lateinit var subscriptionsAdapter: SubscriptionsListAdapter private lateinit var organizationsAdapter: OrganizationsListAdapter override lateinit var applySettingsClicks: Observable<OrganizationModel> override lateinit var uploadSettingsClicks: Observable<OrganizationModel> override val logoutButtonClicks: Observable<Unit> get() = logout_button.clicks() private var _binding: AccountInfoFragmentBinding? = null private val binding get() = _binding!! override fun onAttach(context: Context?) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) if (savedInstanceState != null) { wasPreviouslySentToLogin = savedInstanceState.getBoolean(OUT_BOOLEAN_WAS_PREVIOUSLY_SENT_TO_LOGIN_SCREEN, false) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = AccountInfoFragmentBinding.inflate(inflater, container, false) subscriptionsAdapter = SubscriptionsListAdapter(dateFormatter) binding.subscriptionsList.apply { layoutManager = LinearLayoutManager(requireContext()) adapter = subscriptionsAdapter } organizationsAdapter = OrganizationsListAdapter() binding.organizationsList.apply { layoutManager = LinearLayoutManager(requireContext()) adapter = organizationsAdapter } applySettingsClicks = organizationsAdapter.getApplySettingsStream() uploadSettingsClicks = organizationsAdapter.getUploadSettingsStream() return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val fragmentActivity = requireActivity() val toolbar = fragmentActivity.findViewById<Toolbar>(R.id.toolbar) (fragmentActivity as AppCompatActivity).setSupportActionBar(toolbar) } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { super.onCreateOptionsMenu(menu, inflater) menu?.clear() } override fun onOptionsItemSelected(item: MenuItem?): Boolean { return if (item?.itemId == android.R.id.home) { router.navigateBack() true } else { super.onOptionsItemSelected(item) } } override fun onStart() { super.onStart() updateProperScreen() val actionBar = (requireActivity() as AppCompatActivity).supportActionBar actionBar?.apply { setHomeButtonEnabled(true) setDisplayHomeAsUpEnabled(true) setTitle(R.string.menu_main_my_account) subtitle = "" } this.presenter.subscribe() } override fun onStop() { this.presenter.unsubscribe() super.onStop() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(OUT_BOOLEAN_WAS_PREVIOUSLY_SENT_TO_LOGIN_SCREEN, wasPreviouslySentToLogin) } override fun updateProperScreen() { wasPreviouslySentToLogin = router.navigateToProperLocation(wasPreviouslySentToLogin) } override fun presentEmail(emailAddress: EmailAddress) { login_field_email.text = emailAddress } override fun presentOrganizations(uiIndicator: UiIndicator<List<OrganizationModel>>) { when (uiIndicator.state) { UiIndicator.State.Success -> { progress_bar.visibility = View.GONE organization_group.visibility = View.VISIBLE organizationsAdapter.setOrganizations(uiIndicator.data.get()) } UiIndicator.State.Loading -> { organization_group.visibility = View.GONE progress_bar.visibility = View.VISIBLE } UiIndicator.State.Error -> { organization_group.visibility = View.GONE progress_bar.visibility = View.GONE } UiIndicator.State.Idle -> { organization_group.visibility = View.GONE progress_bar.visibility = View.GONE } } } override fun presentApplyingResult(uiIndicator: UiIndicator<Unit>) { when (uiIndicator.state) { UiIndicator.State.Success -> { Toast.makeText(context, getString(R.string.organization_apply_success), Toast.LENGTH_SHORT).show() } UiIndicator.State.Error -> { Toast.makeText(context, getString(R.string.organization_apply_error), Toast.LENGTH_SHORT).show() } else -> { throw IllegalStateException("Applying settings must return only Success or Error result") } } } override fun presentUpdatingResult(uiIndicator: UiIndicator<Unit>) { when (uiIndicator.state) { UiIndicator.State.Loading -> { progress_bar.visibility = View.VISIBLE } UiIndicator.State.Success -> { Toast.makeText(context, getString(R.string.organization_update_success), Toast.LENGTH_SHORT).show() progress_bar.visibility = View.GONE } UiIndicator.State.Error -> { progress_bar.visibility = View.GONE Toast.makeText(context, getString(R.string.organization_update_error), Toast.LENGTH_SHORT).show() } else -> { throw IllegalStateException("Updating organization settings must return only Success or Error result") } } } override fun presentOcrScans(remainingScans: Int) { ocr_scans_remaining.text = getString(R.string.ocr_configuration_scans_remaining, remainingScans) val listener: View.OnClickListener = View.OnClickListener { router.navigateToOcrFragment() } ocr_scans_remaining.setOnClickListener(listener) ocr_label.setOnClickListener(listener) } override fun presentSubscriptions(subscriptions: List<RemoteSubscription>) { subscriptions_group.visibility = View.VISIBLE subscriptionsAdapter.setSubscriptions(subscriptions) } companion object { @JvmStatic fun newInstance() = AccountFragment() const val OUT_BOOLEAN_WAS_PREVIOUSLY_SENT_TO_LOGIN_SCREEN = "out_bool_was_previously_sent_to_login_screen" } override fun onDestroyView() { super.onDestroyView() _binding = null } }
agpl-3.0
5cfac7415b11cbb51d3c92352b3edf57
34.973568
124
0.689039
5.138452
false
false
false
false
searene/OneLetterOnePage
src/main/kotlin/com/searene/service/PDFService.kt
1
3859
package com.searene.service import com.searene.domain.CharacterContainer import com.searene.properties.PDFProperties import org.apache.fop.apps.FopFactory import org.apache.fop.apps.MimeConstants import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.io.BufferedOutputStream import java.io.File import java.io.InputStream import java.io.OutputStream import javax.annotation.PostConstruct import javax.xml.bind.JAXBContext import javax.xml.bind.util.JAXBSource import javax.xml.transform.Result import javax.xml.transform.Source import javax.xml.transform.TransformerFactory import javax.xml.transform.sax.SAXResult import javax.xml.transform.stream.StreamSource @Service class PDFService { private val logger = LoggerFactory.getLogger(PDFService::class.java) @Autowired private lateinit var pdfProperties: PDFProperties private val xslFileName = "pdf.xsl" private val fopFactory = FopFactory.newInstance(File("/data/one-letter-one-page/fop.xconf")) @PostConstruct fun init() { // create root path if not exists val file = File(pdfProperties.rootPath) file.mkdirs() } fun <T> convertInstanceToPDF(obj: Any, clazz: Class<T>, pdf: OutputStream, xslFileInputStream: InputStream) { val foUserAgent = fopFactory.newFOUserAgent() // configure foUserAgent as desired // Setup output val out: OutputStream = BufferedOutputStream(pdf) try { // Construct fop with desired output format val fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out) // Setup XSLT val factory = TransformerFactory.newInstance() val transformer = factory.newTransformer(StreamSource(xslFileInputStream)) // Setup input for XSLT transformation val jaxbContext = JAXBContext.newInstance(clazz) val src: Source = JAXBSource(jaxbContext, obj) // Resulting SAX events (the generated FO) must be piped through to FOP val res: Result = SAXResult(fop.getDefaultHandler()) // Start XSLT transformation and FOP processing transformer.transform(src, res) } finally { out.close() } } /** * Converts a CharacterContainer object to a PDF file. * @param team the CharacterContainer object * @param pdf the target PDF output stream * @param xslFile xsl File */ fun convertCharacterContainerToPDF(charactersContainer: CharacterContainer, pdf: OutputStream) { val foUserAgent = fopFactory.newFOUserAgent() // configure foUserAgent as desired // Setup output val out: OutputStream = BufferedOutputStream(pdf) try { // Construct fop with desired output format val fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out) // Setup XSLT val factory = TransformerFactory.newInstance() val transformer = factory.newTransformer(StreamSource(getResourceFileAsStream(xslFileName))) // Setup input for XSLT transformation val jaxbContext = JAXBContext.newInstance(CharacterContainer::class.java) val src: Source = JAXBSource(jaxbContext, charactersContainer) // Resulting SAX events (the generated FO) must be piped through to FOP val res: Result = SAXResult(fop.getDefaultHandler()) // Start XSLT transformation and FOP processing transformer.transform(src, res) } finally { out.close() } } private fun getResourceFileAsStream(fileName: String): InputStream { val classLoader = PDFService::class.java.getClassLoader(); return classLoader.getResourceAsStream(fileName) } }
apache-2.0
8f49bc99c80297142d496771d5605861
34.081818
113
0.699663
4.466435
false
false
false
false
PolymerLabs/arcs
javatests/arcs/core/testutil/AssertVariableOrderingTest.kt
1
25991
/* * Copyright 2021 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.testutil import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import kotlin.test.fail import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class AssertVariableOrderingTest { fun verifyExceptionMessage(expected: String, block: () -> Unit) { var caught: AssertionError? = null try { block() } catch (e: AssertionError) { caught = e } if (caught == null) { fail("Expected an exception to be thrown, but was completed successfully.") } assertThat(caught.message).isEqualTo(expected.trimIndent()) } @Test fun emptyInputs() { assertVariableOrdering<Int>(emptyList(), sequence(emptyList()), group(emptyList())) } @Test fun parallelSequences() { // Interleaved with full coverage assertVariableOrdering( (1..9).toList(), group( sequence(2, 3, 5, 7), sequence(4, 6, 8), sequence(1, 9) ) ) // Interleaved with unmatched items. assertVariableOrdering( listOf(44, 1, 2, 3, 66, 4, 5, 6, 7, 22, 8, 9), group( sequence(2, 3, 5, 7), sequence(4, 6, 8), sequence(1, 9) ), allowUnmatched = true ) // In order. assertVariableOrdering( (1..6).toList(), group( sequence(1, 2, 3), sequence(4), sequence(5, 6) ) ) } @Test fun parallelGroups() { // Interleaved with full coverage assertVariableOrdering( (1..9).toList(), group( group(2, 3, 5, 7), group(4, 6, 8), group(1, 9) ) ) // Interleaved with unmatched items. assertVariableOrdering( listOf(44, 1, 2, 3, 66, 4, 5, 6, 7, 22, 8, 9), group( group(2, 3, 5, 7), group(4, 6, 8), group(1, 9) ), allowUnmatched = true ) // In order. assertVariableOrdering( (1..6).toList(), group( group(1, 2, 3), group(4), group(5, 6) ) ) } @Test fun simpleNestedConstraints() { val actual = listOf( "g", "X", "f", "Y", "t", "Q", "R", "z", "S", "B1", "A1", "A2", "m", "B2", "w", "K", "J" ) // Test re-use of a constraint ojbect in different calls to assertVariableOrdering. val nested = sequence( sequence("X", "Y"), sequence("Q", "R", "S"), group( sequence("A1", "A2"), sequence("B1", "B2") ), group("J", "K") ) // Use the allowUnmatched flag to ignore the lower-case items. assertVariableOrdering(actual, nested, allowUnmatched = true) // Add a parallel group to capture the lower-case items. assertVariableOrdering(actual, group(nested, group("g", "f", "t", "z", "m", "w"))) // Nested groups - pointless when not re-using constraint objects, but should still work. assertVariableOrdering( actual, group( group( group("z", "B1"), group("A2", "S", "w"), group("A1") ), group("f", "R"), group(group("K", "t", "m")) ), allowUnmatched = true ) // Nested sequences - similarly pointless, but again should still work. assertVariableOrdering( actual, sequence( sequence("g", "X", "f"), sequence( sequence("Y"), sequence("t"), sequence("R", "B1") ), sequence(sequence("B2", "w", "K", "J")) ), allowUnmatched = true ) } @Test fun deeplyNestedConstraints() { assertVariableOrdering( (1..30).toList(), sequence(1, 2), group( sequence( group(5, 4), group(6, 7) ), sequence(3, 8) ), group( sequence( group(12, 16, 15), group( sequence(21, 23, 28, 29), group(24, 22, 19) ) ), sequence(25, 26, 27), sequence(9, 10, 13, 18, 20), group(17, 11, 14) ), group(30) ) } @Test fun duplicateValues() { val actual = listOf('a', 'a', 'x', 'b', 'a', 'b', 'y', 'b', 'z') val expected = listOf('a', 'a', 'b', 'a', 'b', 'b') assertVariableOrdering(actual, sequence(expected), allowUnmatched = true) assertVariableOrdering(actual, group(expected), allowUnmatched = true) // Repeated values in constraints should only match repeated values in actual. assertFailsWith<AssertionError> { assertVariableOrdering(listOf('a', 'b'), sequence('a', 'a'), allowUnmatched = true) } assertVariableOrdering(listOf('a', 'b', 'a'), sequence('a', 'a'), allowUnmatched = true) assertFailsWith<AssertionError> { assertVariableOrdering(listOf('a', 'b'), group('a', 'a'), allowUnmatched = true) } assertVariableOrdering(listOf('a', 'b', 'a'), group('a', 'a'), allowUnmatched = true) } @Test fun duplicateConstraints() { val actual = listOf('a', 'b', 'x', 'a', 'y', 'b') val seq = sequence('a', 'b') val grp = group('a', 'b') assertVariableOrdering(actual, seq, seq, allowUnmatched = true) assertVariableOrdering(actual, grp, grp, allowUnmatched = true) assertFailsWith<AssertionError> { assertVariableOrdering( listOf(1, 2), sequence(group(1, 2), group(1, 2)) ) } assertVariableOrdering( listOf(1, 2, 1, 2), sequence(group(1, 2), group(1, 2)) ) assertFailsWith<AssertionError> { assertVariableOrdering( listOf(1, 2), group(sequence(1, 2), sequence(1, 2)) ) } assertVariableOrdering( listOf(1, 2, 1, 2), group(sequence(1, 2), sequence(1, 2)) ) } @Test fun reuseValueConstraintObjects() { val seq = sequence(1, 2) val grp = group(3, 4, 5) // In a single call. assertVariableOrdering( listOf(1, 2, 5, 3, 4, 10, 3, 1, 4, 2, 5, 20, 30), sequence(seq, grp), group(10), group(seq, grp), sequence(20, 30) ) assertThat(seq.maxIndex).isEqualTo(9) assertThat(grp.maxIndex).isEqualTo(10) // Across multiple calls - note that the new matches occur at an earlier index than the // last matches of the previous call. assertVariableOrdering( listOf(1, 2, 5, 3, 4, 10), seq, grp, single(10) ) assertThat(seq.maxIndex).isEqualTo(1) assertThat(grp.maxIndex).isEqualTo(4) } @Test fun reuseNestedConstraintObjects() { val seq = sequence(sequence(1, 2), group(3, 4)) val grp = group(single(5), sequence(6, 7)) // In a single call. assertVariableOrdering( listOf(1, 2, 4, 3, 6, 5, 7, 10, 1, 6, 2, 3, 4, 7, 5, 20), sequence(seq, grp), group(10), group(seq, grp), single(20) ) assertThat(seq.maxIndex).isEqualTo(12) assertThat(grp.maxIndex).isEqualTo(14) // Across multiple calls - note that the new matches occur at an earlier index than the // last matches of the previous call. assertVariableOrdering( listOf(1, 2, 3, 4, 5, 6, 7, 10), seq, grp, single(10) ) assertThat(seq.maxIndex).isEqualTo(3) assertThat(grp.maxIndex).isEqualTo(6) } @Test fun singleValueConstraint() { assertVariableOrdering( (1..18).toList(), single(2), sequence(4, 5), group( single(12), single(7), sequence(9, 10, 15) ), group(18, 17), allowUnmatched = true ) verifyExceptionMessage( """ assertVariableOrdering: single constraint failed with unmatched values: [x] Actual Match result 0 | a seq(>a<, b) 1 | b seq(a, >b<) : ?? sng(x) 2 | c 3 | d 4 | e """ ) { assertVariableOrdering( listOf("a", "b", "c", "d", "e"), sequence("a", "b"), single("x"), group("d", "e") ) } } @Test fun complexValueTypes_setOfInt() { val listOfSets = listOf(setOf(1, 2), setOf(3, 4, 5), setOf(6)) assertVariableOrdering( listOfSets, sequence(setOf(1, 2), setOf(3, 4, 5)), // API quirk: a single setOf() matches the group(Iterable<T>) method instead of the // intended vararg one. group(listOf(setOf())) works but single() is more readable. single(setOf(6)) ) verifyExceptionMessage( """ assertVariableOrdering: sequence constraint failed with unmatched values: [[8, 9]] Actual Match result 0 | [1, 2] seq(>[1, 2]<, [8, 9], [6]) : ?? seq([1, 2], >[8, 9]<, [6]) 1 | [3, 4, 5] 2 | [6] seq([1, 2], [8, 9], >[6]<) """ ) { assertVariableOrdering( listOfSets, sequence(setOf(1, 2), setOf(8, 9), setOf(6)) ) } } @Test fun complexValueTypes_dataClass() { data class Bob(val x: Int, val y: String = "") val listOfBobs = listOf(Bob(1, "one"), Bob(2), Bob(3, "three"), Bob(4), Bob(5)) assertVariableOrdering( listOfBobs, group( sequence(Bob(1, "one"), Bob(4)), sequence(Bob(2), Bob(3, "three")) ), sequence(Bob(5)) ) verifyExceptionMessage( """ assertVariableOrdering: group constraint failed with unmatched values: [Bob(x=10, y=ten)] Actual Match result 0 | Bob(x=1, y=one) 1 | Bob(x=2, y=) grp(>Bob(x=2, y=)<, Bob(x=10, y=ten)) : ?? grp(Bob(x=2, y=), >Bob(x=10, y=ten)<) 2 | Bob(x=3, y=three) 3 | Bob(x=4, y=) 4 | Bob(x=5, y=) """ ) { assertVariableOrdering( listOfBobs, group(Bob(2), Bob(10, "ten")) ) } } @Test fun nestedConstraintFailures() { val actual = listOf("a1", "z", "b1", "a2", "b2", "a3", "x", "y") verifyExceptionMessage( """ assertVariableOrdering: sequence constraint failed with unmatched values: [a1] Actual Match result 0 | a1 grp(>a1<, z) 1 | z grp(a1, >z<) : ?? seq(>a1<, a2, a3) 2 | b1 3 | a2 seq(a1, >a2<, a3) 4 | b2 5 | a3 seq(a1, a2, >a3<) 6 | x 7 | y """ ) { assertVariableOrdering( actual, group("a1", "z"), group( sequence("a1", "a2", "a3"), sequence("b1", "b2") ), sequence("x", "y") ) } verifyExceptionMessage( """ assertVariableOrdering: group constraint failed with unmatched values: [z, k] Actual Match result 0 | a1 seq(>a1<, z) 1 | z seq(a1, >z<) 2 | b1 grp(>b1<, z, b2, k) 3 | a2 4 | b2 grp(b1, z, >b2<, k) : ?? grp(b1, >z<, b2, k) : ?? grp(b1, z, b2, >k<) 5 | a3 6 | x 7 | y """ ) { assertVariableOrdering( actual, sequence("a1", "z"), group("b1", "z", "b2", "k") ) } } @Test fun failureMessageFormatting_zeroMatches() { verifyExceptionMessage( """ assertVariableOrdering: sequence constraint failed with unmatched values: [elit, sed, eiusmod] Actual Match result : ?? seq(>elit<, sed, eiusmod) : ?? seq(elit, >sed<, eiusmod) : ?? seq(elit, sed, >eiusmod<) 0 | lorem 1 | ipsum 2 | dolor 3 | sit 4 | consectetur """ ) { assertVariableOrdering( listOf("lorem", "ipsum", "dolor", "sit", "consectetur"), sequence("elit", "sed", "eiusmod") ) } verifyExceptionMessage( """ assertVariableOrdering: group constraint failed with unmatched values: [lorem] Actual Match result : ?? grp(>lorem<) 0 | elit 1 | eiusmod """ ) { assertVariableOrdering( listOf("elit", "eiusmod"), group("lorem") ) } } @Test fun failureMessageFormatting_runsOfMatchesAndMisses() { verifyExceptionMessage( """ assertVariableOrdering: sequence constraint failed with unmatched values: [5, 23, 1, -8, 5, 40] Actual Match result 0 | 1 1 | 2 seq(>2<, 4, 5, 6, 5, 9, 23, 1, 12, -8, 5, 40, 14) 2 | 3 3 | 4 seq(2, >4<, 5, 6, 5, 9, 23, 1, 12, -8, 5, 40, 14) 4 | 5 seq(2, 4, >5<, 6, 5, 9, 23, 1, 12, -8, 5, 40, 14) 5 | 6 seq(2, 4, 5, >6<, 5, 9, 23, 1, 12, -8, 5, 40, 14) : ?? seq(2, 4, 5, 6, >5<, 9, 23, 1, 12, -8, 5, 40, 14) 6 | 7 7 | 8 8 | 9 seq(2, 4, 5, 6, 5, >9<, 23, 1, 12, -8, 5, 40, 14) : ?? seq(2, 4, 5, 6, 5, 9, >23<, 1, 12, -8, 5, 40, 14) : ?? seq(2, 4, 5, 6, 5, 9, 23, >1<, 12, -8, 5, 40, 14) 9 | 10 10 | 11 11 | 12 seq(2, 4, 5, 6, 5, 9, 23, 1, >12<, -8, 5, 40, 14) : ?? seq(2, 4, 5, 6, 5, 9, 23, 1, 12, >-8<, 5, 40, 14) : ?? seq(2, 4, 5, 6, 5, 9, 23, 1, 12, -8, >5<, 40, 14) : ?? seq(2, 4, 5, 6, 5, 9, 23, 1, 12, -8, 5, >40<, 14) 12 | 13 13 | 14 seq(2, 4, 5, 6, 5, 9, 23, 1, 12, -8, 5, 40, >14<) """ ) { assertVariableOrdering( (1..14).toList(), sequence(2, 4, 5, 6, 5, 9, 23, 1, 12, -8, 5, 40, 14) ) } } @Test fun failureMessageFormatting_unmatchedBeforeAndAfterFullInput() { verifyExceptionMessage( """ assertVariableOrdering: sequence constraint failed with unmatched values: [x, y] Actual Match result : ?? seq(>x<, y) : ?? seq(x, >y<) 0 | a 1 | b """ ) { assertVariableOrdering( listOf("a", "b"), sequence("x", "y"), group("a", "b") ) } verifyExceptionMessage( """ assertVariableOrdering: group constraint failed with unmatched values: [x, y] Actual Match result 0 | a grp(>a<, b) 1 | b grp(a, >b<) : ?? grp(>x<, y) : ?? grp(x, >y<) """ ) { assertVariableOrdering( listOf("a", "b"), group("a", "b"), group("x", "y") ) } } @Test fun failureMessageFormatting_constraintsSatisfiedWithUnmatchedValues() { verifyExceptionMessage( """ assertVariableOrdering: all constraints satisfied but some values not matched: [ipsum, consectetur, elit] 0 | lorem 1 | ipsum <- unmatched 2 | dolor 3 | sit 4 | consectetur <- unmatched 5 | elit <- unmatched 6 | sed 7 | eiusmod """ ) { assertVariableOrdering( listOf("lorem", "ipsum", "dolor", "sit", "consectetur", "elit", "sed", "eiusmod"), group( sequence("dolor", "sit", "eiusmod"), group("lorem", "sed") ) ) } } @Test fun nestedGroup_mustIteratePermutationsForOverlappingConstraints() { // This wouldn't work without the permutation logic in Constraint.NestGroup, because seq(X,Z) // matches the first X and the Z, leaving inputs Y-X to fail against seq(X,Y). Additionally, // the extra non-overlapping sequences must be left out of the permutation processing to avoid // a factorial explosion. assertVariableOrdering( listOf("X", "Y", "X", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"), group( sequence("X", "Z"), sequence("X", "Y"), single("a"), single("b"), single("c"), single("d"), single("e"), single("f"), single("g"), single("h"), single("i"), single("j"), single("k"), single("l") ) ) // Try every permutation over 4 inputs. val a = sequence(1, 2) val b = sequence(1, 3) val c = sequence(1, 4) val d = sequence(1, 5) listOf( listOf(a, b, c, d), listOf(a, b, d, c), listOf(a, c, d, b), listOf(a, c, b, d), listOf(a, d, b, c), listOf(a, d, c, b), listOf(b, c, d, a), listOf(b, c, a, d), listOf(b, d, a, c), listOf(b, d, c, a), listOf(b, a, c, d), listOf(b, a, d, c), listOf(c, d, a, b), listOf(c, d, b, a), listOf(c, a, b, d), listOf(c, a, d, b), listOf(c, b, d, a), listOf(c, b, a, d), listOf(d, a, b, c), listOf(d, a, c, b), listOf(d, b, c, a), listOf(d, b, a, c), listOf(d, c, a, b), listOf(d, c, b, a) ).forEach { assertVariableOrdering( listOf(9, 8, 1, 2, 1, 3, 1, 4, 1, 5, 7), sequence(9, 8), group(it), single(7) ) } } @Test fun nestedGroup_errorReportFromOverlappingConstraintWithInvalidValue() { verifyExceptionMessage( """ assertVariableOrdering: sequence constraint failed with unmatched values: [-2] Actual Match result 0 | 0 seq(>0<, -2) : ?? seq(0, >-2<) 1 | 1 2 | 0 3 | 2 4 | 0 5 | 3 """ ) { assertVariableOrdering( listOf(0, 1, 0, 2, 0, 3), group( sequence(0, 3), sequence(0, -2), sequence(0, 1) ) ) } } @Test fun nestedGroup_errorReportFromNonOverlappingConstraintWithInvalidValue() { verifyExceptionMessage( """ assertVariableOrdering: sequence constraint failed with unmatched values: [-6] Actual Match result 0 | 0 1 | 1 2 | 5 seq(>5<, -6) : ?? seq(5, >-6<) 3 | 6 4 | 0 5 | 3 """ ) { assertVariableOrdering( listOf(0, 1, 5, 6, 0, 3), group( sequence(0, 3), sequence(5, -6), sequence(0, 1) ) ) } } @Test fun nestedGroup_errorReportFromOverlappingConstraints() { verifyExceptionMessage( """ assertVariableOrdering: no ordering found to satisfy constraints with common values in a nested group [Constraints] seq(1, 5) grp(0, 1, 2) seq(5, 3, 6) [Sample failure] Actual Match result 0 | 9 sng(9) : ?? seq(>5<, 3, 6) 1 | 0 grp(>0<, 1, 2) 2 | 1 seq(>1<, 5) 3 | 2 grp(0, 1, >2<) 4 | 1 grp(0, >1<, 2) 5 | 5 seq(1, >5<) 6 | 3 seq(5, >3<, 6) 7 | 6 seq(5, 3, >6<) """ ) { assertVariableOrdering( listOf(9, 0, 1, 2, 1, 5, 3, 6), single(9), group( sequence(1, 5), sequence(5, 3, 6), group(0, 1, 2) ) ) } } @Test fun nestedGroup_pathologicalInputs() { // This has 13 overlapping constraints in the group; 13! is 6,227,020,800 orderings which // is not feasible to brute force. The pruning algorithm in NestGroup.process() succesfully // completes this call with just 46,496 invocations of runPermutations. assertFailsWith<AssertionError> { assertVariableOrdering( listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14), group( sequence(1, 2), sequence(2, 3), sequence(3, 4), sequence(4, 5), sequence(5, 6), sequence(6, 7), sequence(7, 8), sequence(8, 9), sequence(9, 10), sequence(10, 11), sequence(11, 12), sequence(12, 13), sequence(13, 14) ) ) }.let { assertThat(it).hasMessageThat().contains("no ordering found to satisfy constraints") } // The following test would time out without the safety limit check in NestGroup.process(). assertFailsWith<RuntimeException> { assertVariableOrdering( listOf( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ), group( sequence(0, 1), sequence(0, 2), sequence(0, 3), sequence(0, 4), sequence(0, 5), sequence(0, 6, 7), sequence(0, 7), sequence(0, 8), sequence(0, 9), sequence(0, 10), sequence(0, 11), sequence(0, 12), sequence(0, 13) ) ) }.let { assertThat(it).hasMessageThat() .contains("NestGroup required too many permutations to complete") } } @Test fun deeplyNestedGroups_successfulMatch() { assertVariableOrdering( listOf(9, 0, 1, 3, 2, 2, 3, 4, 0, 5, 8, 4, 7), group( sequence( single(9), group( group( sequence(0, 1), sequence(2, 0) ), sequence(3, 2) ) ), group( sequence(3, 4), group(4, 5) ), sequence(8, 7) ) ) } @Test fun deeplyNestedGroups_failureInNonOverlappingConstraint() { // This should fail in the "noPermute" loop in NestGroup.process assertFailsWith<AssertionError> { assertVariableOrdering( listOf(9, 0, 1, 3, 2, 2, 3, 4, 0, 5, 8, 4, 7), group( sequence( single(9), group( group( sequence(0, 1), sequence(2, 0) ), sequence(3, 2) ) ), group( sequence(3, 4), group(4, 5) ), sequence(-8, 7) // -8 is not in actual ) ) }.let { assertThat(it).hasMessageThat() .contains("sequence constraint failed with unmatched values: [-8]") } } @Test fun deeplyNestedGroups_failureInOverlappingConstraint() { // This should fail in the first "toPermute" loop in NestGroup.process assertFailsWith<AssertionError> { assertVariableOrdering( listOf(9, 0, 1, 3, 2, 2, 3, 4, 0, 5, 8, 4, 7), group( sequence( single(9), group( group( sequence(0, 1), sequence(2, 0) ), sequence(3, 2, -5) // -5 is not in actual ) ), group( sequence(3, 4), group(4, 5) ), sequence(8, 7) ) ) }.let { assertThat(it).hasMessageThat() .contains("sequence constraint failed with unmatched values: [-5]") } } @Test fun deeplyNestedGroups_failureDuringPermutationAnalysis() { assertFailsWith<AssertionError> { assertVariableOrdering( listOf(9, 0, 1, 3, 2, 2, 3, 4, 0, 5, 8, 4, 7), group( sequence( single(9), group( group( sequence(0, 1), sequence(2, 0) ), sequence(3, 2) ) ), group( sequence(3, 4), group(4, 5, 8) // Extra 8 can't be satisfied but will pass the first "toPermute" check ), sequence(8, 7) ) ) }.let { assertThat(it).hasMessageThat().contains("no ordering found to satisfy constraints") } } @Test fun deeplyNestedGroups_unmatchedValues() { assertFailsWith<AssertionError> { assertVariableOrdering( listOf(9, 0, 1, -5, 3, 2, 2, 3, 4, -1, 0, 5, 8, 4, 7, -6), group( sequence( single(9), group( group( sequence(0, 1), sequence(2, 0) ), sequence(3, 2) ) ), group( sequence(3, 4), group(4, 5) ), sequence(8, 7) ) ) }.let { assertThat(it).hasMessageThat() .contains("all constraints satisfied but some values not matched: [-5, -1, -6]") } } @Test fun regressionTest_nestedGroupMustClearMatchArrayCorrectly() { // The first impl of runPermutations did not clear the match array correctly, so processing // of the next permutation was polluted by the failed match entries from previous ones. assertVariableOrdering( listOf("A", "B", "C", "A", "D", "E", "X", "C", "Y"), group( sequence("A", "D", "E"), sequence("A", "B", "C"), sequence("X", "C", "Y") ) ) // Make sure the clearing logic works with a non-zero 'from' starting index. assertVariableOrdering( listOf("k", "l", "f", "A", "B", "C", "A", "D", "E", "X", "C", "Y"), sequence("k", "l", "f"), group( sequence("A", "D", "E"), sequence("A", "B", "C"), sequence("X", "C", "Y") ) ) } @Test fun valueSets() { assertThat(single(7).valueSet).isEqualTo(setOf(7)) val s1 = sequence(1, 2, 1, 3, 4) val g1 = group(2, 4, 5, 5) assertThat(s1.valueSet).isEqualTo(setOf(1, 2, 3, 4)) assertThat(g1.valueSet).isEqualTo(setOf(2, 4, 5)) assertThat(sequence(s1, g1).valueSet).isEqualTo(setOf(1, 2, 3, 4, 5)) assertThat(group(s1, g1).valueSet).isEqualTo(setOf(1, 2, 3, 4, 5)) val s2 = sequence( group("y", "x", "a"), single("x"), sequence("y", "a") ) val g2 = group( sequence("a", "b", "a", "c", "d"), group("a", "c", "e") ) assertThat(sequence(s2, g2).valueSet).isEqualTo(setOf("a", "b", "c", "d", "e", "x", "y")) assertThat(group(s2, g2).valueSet).isEqualTo(setOf("a", "b", "c", "d", "e", "x", "y")) } }
bsd-3-clause
9cadc72c7da422a46c85fa1e4809eec9
26.13048
113
0.494017
3.440694
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/internal/baseKotlinInternalUastUtils.kt
3
7785
// 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.uast.kotlin import com.intellij.lang.Language import com.intellij.psi.* import com.intellij.psi.util.PsiTypesUtil import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.elements.FakeFileForLightClass import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.asJava.elements.KtLightMember import org.jetbrains.kotlin.asJava.findFacadeClass import org.jetbrains.kotlin.asJava.getAccessorLightMethods import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.ArrayFqNames import org.jetbrains.kotlin.resolve.references.ReferenceAccess import org.jetbrains.kotlin.utils.addToStdlib.constant import org.jetbrains.uast.* @Suppress("NOTHING_TO_INLINE") inline fun String?.orAnonymous(kind: String = ""): String = this ?: "<anonymous" + (if (kind.isNotBlank()) " $kind" else "") + ">" fun <T> lz(initializer: () -> T) = lazy(LazyThreadSafetyMode.SYNCHRONIZED, initializer) inline fun <reified T : UDeclaration, reified P : PsiElement> unwrap(element: P): P { val unwrapped = if (element is T) element.javaPsi else element assert(unwrapped !is UElement) return unwrapped as P } fun unwrapFakeFileForLightClass(file: PsiFile): PsiFile = (file as? FakeFileForLightClass)?.ktFile ?: file fun getContainingLightClass(original: KtDeclaration): KtLightClass? = (original.containingClassOrObject?.toLightClass() ?: original.containingKtFile.findFacadeClass()) fun getKotlinMemberOrigin(element: PsiElement?): KtDeclaration? { (element as? KtLightMember<*>)?.lightMemberOrigin?.auxiliaryOriginalElement?.let { return it } (element as? KtLightElement<*, *>)?.kotlinOrigin?.let { return it as? KtDeclaration } return null } fun KtExpression.unwrapBlockOrParenthesis(): KtExpression { val innerExpression = KtPsiUtil.safeDeparenthesize(this) if (innerExpression is KtBlockExpression) { val statement = innerExpression.statements.singleOrNull() ?: return this return KtPsiUtil.safeDeparenthesize(statement) } return innerExpression } fun KtExpression.readWriteAccess(): ReferenceAccess { var expression = getQualifiedExpressionForSelectorOrThis() loop@ while (true) { when (val parent = expression.parent) { is KtParenthesizedExpression, is KtAnnotatedExpression, is KtLabeledExpression -> expression = parent as KtExpression else -> break@loop } } val assignment = expression.getAssignmentByLHS() if (assignment != null) { return when (assignment.operationToken) { KtTokens.EQ -> ReferenceAccess.WRITE else -> ReferenceAccess.READ_WRITE } } return if ((expression.parent as? KtUnaryExpression)?.operationToken in constant { setOf(KtTokens.PLUSPLUS, KtTokens.MINUSMINUS) }) ReferenceAccess.READ_WRITE else ReferenceAccess.READ } fun KtElement.canAnalyze(): Boolean { if (!isValid) return false val containingFile = containingFile as? KtFile ?: return false // EA-114080, EA-113475, EA-134193 if (containingFile.doNotAnalyze != null) return false // To prevent exceptions during analysis return true } val PsiClass.isEnumEntryLightClass: Boolean get() = (this as? KtLightClass)?.kotlinOrigin is KtEnumEntry val KtTypeReference.nameElement: PsiElement? get() = this.typeElement?.let { (it as? KtUserType)?.referenceExpression?.getReferencedNameElement() ?: it.navigationElement } internal fun KtClassOrObject.toPsiType(): PsiType { val lightClass = toLightClass() ?: return UastErrorType return PsiTypesUtil.getClassType(lightClass) } fun PsiElement.getMaybeLightElement(sourcePsi: KtExpression? = null): PsiElement? { if (this is KtProperty && sourcePsi?.readWriteAccess()?.isWrite == true) { with(getAccessorLightMethods()) { (setter ?: backingField)?.let { return it } // backingField is for val property assignments in init blocks } } return when (this) { is KtDeclaration -> { val lightElement = toLightElements().firstOrNull() if (lightElement != null) return lightElement if (this is KtPrimaryConstructor) { // annotations don't have constructors (but in Kotlin they do), so resolving to the class here (this.parent as? KtClassOrObject)?.takeIf { it.isAnnotation() }?.toLightClass()?.let { return it } } when (val uElement = this.toUElement()) { is UDeclaration -> uElement.javaPsi is UDeclarationsExpression -> uElement.declarations.firstOrNull()?.javaPsi is ULambdaExpression -> (uElement.uastParent as? KotlinLocalFunctionUVariable)?.javaPsi else -> null } } is KtElement -> null else -> this } } private val KtCallElement.isAnnotationArgument: Boolean // KtAnnotationEntry (or KtCallExpression when annotation is nested) -> KtValueArgumentList -> KtValueArgument -> arrayOf call get() = when (val elementAt2 = parents.elementAtOrNull(2)) { is KtAnnotationEntry -> true is KtCallExpression -> elementAt2.getParentOfType<KtAnnotationEntry>(true, KtDeclaration::class.java) != null else -> false } fun isAnnotationArgumentArrayInitializer(ktCallElement: KtCallElement, fqNameOfCallee: FqName): Boolean { return ktCallElement.isAnnotationArgument && fqNameOfCallee in ArrayFqNames.ARRAY_CALL_FQ_NAMES } private val KtBlockExpression.isFunctionBody: Boolean get() { return (parent as? KtNamedFunction)?.bodyBlockExpression == this } /** * Depending on type owner kind, type conversion to [PsiType] would vary. For example, we need to convert `Unit` to `void` only if the given * type is used as a return type of a function. Usually, the "context" of type conversion would be the owner of the type to be converted, * but it's not guaranteed. So, the caller/user of the type conversion should specify the kind of the type owner. */ enum class TypeOwnerKind { UNKNOWN, TYPE_REFERENCE, CALL_ELEMENT, DECLARATION, EXPRESSION, } val KtElement.typeOwnerKind: TypeOwnerKind get() = when (this) { is KtTypeReference -> TypeOwnerKind.TYPE_REFERENCE is KtCallElement -> TypeOwnerKind.CALL_ELEMENT is KtDeclaration -> TypeOwnerKind.DECLARATION is KtExpression -> TypeOwnerKind.EXPRESSION else -> TypeOwnerKind.UNKNOWN } fun convertUnitToVoidIfNeeded( context: KtElement, typeOwnerKind: TypeOwnerKind, boxed: Boolean ): PsiType? { fun PsiPrimitiveType.orBoxed() = if (boxed) getBoxedType(context) else this return when { typeOwnerKind == TypeOwnerKind.DECLARATION && context is KtNamedFunction -> PsiType.VOID.orBoxed() typeOwnerKind == TypeOwnerKind.EXPRESSION && context is KtBlockExpression && context.isFunctionBody -> PsiType.VOID.orBoxed() else -> null } } /** Returns true if the given element is written in Kotlin. */ fun isKotlin(element: PsiElement?): Boolean { return element != null && isKotlin(element.language) } /** Returns true if the given language is Kotlin. */ fun isKotlin(language: Language?): Boolean { return language == KotlinLanguage.INSTANCE }
apache-2.0
39063353260fe046dd0bf453d6cb06b1
39.759162
158
0.718304
4.802591
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/commands/uncategorized/UserinfoCommand.kt
1
11152
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.commands.uncategorized import me.duncte123.botcommons.messaging.EmbedUtils import me.duncte123.botcommons.messaging.MessageUtils.sendEmbed import me.duncte123.botcommons.messaging.MessageUtils.sendMsg import me.duncte123.weebJava.types.StatusType import ml.duncte123.skybot.Settings.PATREON import ml.duncte123.skybot.entities.jda.DunctebotGuild import ml.duncte123.skybot.extensions.* import ml.duncte123.skybot.objects.CooldownScope import ml.duncte123.skybot.objects.Emotes.* import ml.duncte123.skybot.objects.command.Command import ml.duncte123.skybot.objects.command.CommandContext import ml.duncte123.skybot.utils.FinderUtils import net.dv8tion.jda.api.OnlineStatus import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Activity import net.dv8tion.jda.api.entities.Member import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.entities.User.UserFlag import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent import java.time.OffsetDateTime import java.time.temporal.ChronoUnit class UserinfoCommand : Command() { private val nitroUserLink = "**[Nitro User:](https://github.com/DuncteBot/SkyBot/issues/201#issuecomment-486182959 \"Click for more info on the nitro user check\")**" init { this.name = "userinfo" this.aliases = arrayOf("user", "i", "whois", "ui", "retrieveuserinfo") this.help = "Get some information about yourself or from another user" this.usage = "[@user]" this.cooldown = 30 this.cooldownScope = CooldownScope.GUILD } override fun execute(ctx: CommandContext) { val event = ctx.event val args = ctx.args if (ctx.invoke.lowercase() == "retrieveuserinfo") { if (args.isEmpty()) { sendMsg(ctx, "Missing arguments for retrieving user information") return } ctx.jda.retrieveUserById(args[0]).queue( { renderUserEmbed(ctx, it, ctx.guild) }, { sendMsg(ctx, "Could not get user info: ${it.message}") } ) return } var u: User? = null var m: Member? = null if (args.isEmpty()) { u = event.author m = event.member } else { val members = FinderUtils.searchMembers(ctx.argsRaw, ctx) if (members.isNotEmpty()) { m = members[0] u = m.user } else { val users = FinderUtils.searchUsers(ctx.argsRaw, ctx) if (users.isNotEmpty()) { u = users[0] } } } // if we have a user but not a member if (u != null && m == null) { renderUserEmbed(ctx, u, ctx.guild) return } if (m == null) { sendMsg(ctx, "This user could not be found.") return } renderMemberEmbed(event, m, ctx) } private fun renderUserEmbed(ctx: CommandContext, user: User, guild: DunctebotGuild) { val times = user.parseTimeCreated() val embed = EmbedUtils.getDefaultEmbed() .setColor(guild.color) .setThumbnail(user.getStaticAvatarUrl()) .setDescription( """User info for ${user.asMention} ${user.badgeLine} | |**User Tag:** ${user.asTag.escapeMarkDown()} |**User Id:** ${user.id} |**Account Created:** ${times.first} (${times.second}) |$nitroUserLink ${user.isNitro.toEmoji()} |**Bot Account:** ${user.isBot.toEmoji()} | |_Use `${guild.settings.customPrefix}avatar [user]` to get a user's avatar_ """.trimMargin() ) sendEmbed(ctx, embed) } private fun generateJoinOrder(members: List<Member>, member: Member) = buildString { val joins = members.stream().sorted(Comparator.comparing(Member::getTimeJoined)).toList() var index = joins.indexOf(member) index -= 3 if (index < 0) { index = 0 } appendLine() if (joins[index] == member) { append("[${joins[index].effectiveName.escapeMarkDown()}]($PATREON)") } else { append(joins[index].effectiveName.escapeMarkDown()) } for (i in index + 1 until index + 7) { if (i >= joins.size) { break } val mbr = joins[i] var usrName = mbr.effectiveName.escapeMarkDown() if (mbr == member) { usrName = "[$usrName]($PATREON)" } append(" \\> ") append(usrName) } } private fun getJoinPosition(members: List<Member>, member: Member): Long { return members.stream().sorted(Comparator.comparing(Member::getTimeJoined)) .takeWhile { it != member }.count() + 1 } private fun renderMemberEmbed(event: GuildMessageReceivedEvent, member: Member, ctx: CommandContext) { val user = member.user val userTimes = user.parseTimeCreated() val memberTimes = member.parseTimeJoined() var boostEmote = "" val boostingSinceMsg = if (member.timeBoosted == null) { "" } else { val boostTime = member.timeBoosted!! val boostTimes = boostTime.parseTimes() boostEmote = boostTime.toBoostEmote() "\n**Boosting since:** ${boostTimes.first} (${boostTimes.second})" } val userNitro = user.isNitro val nitroBadge = if (userNitro) " $DISCORD_NITRO" else "" val loadedMembers = event.guild.loadMembers().get() val embed = EmbedUtils.getDefaultEmbed() .setColor(member.color) .setThumbnail(user.getStaticAvatarUrl()) .setDescription( """User info for ${member.asMention}$nitroBadge ${user.badgeLine} $boostEmote | |**User Tag:** ${user.asTag.escapeMarkDown()} |**User Id:** ${user.id} |**Display Name:** ${member.effectiveName.escapeMarkDown()} |**Account Created:** ${userTimes.first} (${userTimes.second}) |$nitroUserLink ${userNitro.toEmoji()} |**Joined Server:** ${memberTimes.first} (${memberTimes.second}) |**Join position:** #${getJoinPosition(loadedMembers, member)} |**Join Order:** ${generateJoinOrder(loadedMembers, member)} |**Bot Account:** ${user.isBot.toEmoji()} |**Boosting:** ${(member.timeBoosted != null).toEmoji()}$boostingSinceMsg | |_Use `${ctx.prefix}avatar [user]` to get a user's avatar_ """.trimMargin() ) // If we don't have permission to send files or our weebSh key is null if (!ctx.selfMember.hasPermission(event.channel, Permission.MESSAGE_ATTACH_FILES) || ctx.config.apis.weebSh == null ) { sendEmbed(ctx, embed, true) return } ctx.weebApi.generateDiscordStatus( StatusType.values().random(), user.getStaticAvatarUrl() + "?size=256" ).async { event.channel.sendFile(it, "stat.png") .setEmbeds(embed.setThumbnail("attachment://stat.png").build()) .queue(null) { sendEmbed(ctx, embed.setThumbnail(user.effectiveAvatarUrl), true) } } } private fun toWeebshStatus(member: Member): StatusType { if (member.activities.isNotEmpty() && member.activities.any { it.type == Activity.ActivityType.STREAMING }) { return StatusType.STREAMING } return when (member.onlineStatus) { OnlineStatus.ONLINE -> StatusType.ONLINE OnlineStatus.DO_NOT_DISTURB -> StatusType.DND OnlineStatus.IDLE -> StatusType.IDLE else -> StatusType.OFFLINE } } private val User.isNitro: Boolean get() = this.avatarId != null && (this.avatarId as String).startsWith("a_") private val User.badgeLine: String get() = this.flags.mapNotNull { it.toEmote() }.joinToString(" ") private fun UserFlag.toEmote(): String? { return when (this) { UserFlag.STAFF -> DISCORD_STAFF UserFlag.PARTNER -> DISCORD_PARTNER UserFlag.HYPESQUAD -> DISCORD_HYPESQUAD UserFlag.HYPESQUAD_BRAVERY -> DISCORD_HYPESQUAD_BRAVERY UserFlag.HYPESQUAD_BRILLIANCE -> DISCORD_HYPESQUAD_BRILLIANCE UserFlag.HYPESQUAD_BALANCE -> DISCORD_HYPESQUAD_BALANCE UserFlag.BUG_HUNTER_LEVEL_1 -> DISCORD_BUG_HUNTER_1 UserFlag.BUG_HUNTER_LEVEL_2 -> DISCORD_BUG_HUNTER_2 UserFlag.EARLY_SUPPORTER -> DISCORD_EARLY_SUPPORTER // No emotes / not needed // UserFlag.TEAM_USER -> "" // UserFlag.SYSTEM -> "" // UserFlag.VERIFIED_BOT -> "" UserFlag.VERIFIED_DEVELOPER -> DISCORD_VERIFIED_DEVELOPER else -> null } } /*private fun OnlineStatus.toEmote() = when (this) { OnlineStatus.ONLINE -> "<:online2:464520569975603200>" OnlineStatus.IDLE -> "<:away2:464520569862357002>" OnlineStatus.DO_NOT_DISTURB -> "<:dnd2:464520569560498197>" else -> "<:offline2:464520569929334784>" }*/ private fun OffsetDateTime.toBoostEmote(): String { return when (this.until(OffsetDateTime.now(), ChronoUnit.MONTHS)) { 0L, 1L -> { "<:booster:738374009300975686>" } 2L -> { "<:booster2:738374044247654480>" } 3L -> { "<:booster3:738374173159850054>" } else -> { "<:booster4:738374213970165782>" } } } }
agpl-3.0
3be4c29b82c00c37e754e9f1b504d32e
35.444444
170
0.571467
4.272797
false
false
false
false
ligi/PassAndroid
android/src/main/java/org/ligi/passandroid/model/ApplePassbookQuirkCorrector.kt
1
8361
package org.ligi.passandroid.model import org.ligi.passandroid.Tracker import org.ligi.passandroid.model.pass.PassField import org.ligi.passandroid.model.pass.PassImpl import org.threeten.bp.DateTimeException import org.threeten.bp.ZonedDateTime class ApplePassbookQuirkCorrector(val tracker: Tracker) { fun correctQuirks(pass: PassImpl) { // Vendor specific fixes careForTUIFlight(pass) careForAirBerlin(pass) careForWestbahn(pass) careForAirCanada(pass) careForUSAirways(pass) careForVirginAustralia(pass) careForCathayPacific(pass) careForSWISS(pass) careForRenfe(pass) //general fixes tryToFindDate(pass) } private fun tryToFindDate(pass: PassImpl) { if (pass.calendarTimespan == null) { val foundDate = pass.fields.filter { "date" == it.key }.map { try { ZonedDateTime.parse(it.value) } catch (e: DateTimeException) { null } }.firstOrNull { it != null } if (foundDate != null) { tracker.trackEvent("quirk_fix", "find_date", "find_date", 0L) pass.calendarTimespan = PassImpl.TimeSpan(from = foundDate) } } } private fun getPassFieldForKey(pass: PassImpl, key: String): PassField? { return pass.fields.firstOrNull { it.key != null && it.key == key } } private fun getPassFieldThatMatchesLabel(pass: PassImpl, matcher: String): PassField? { return pass.fields.firstOrNull { val label = it.label label != null && label.matches(matcher.toRegex()) } } private fun careForRenfe(pass: PassImpl) { if (pass.creator == null || pass.creator != "RENFE OPERADORA") { return } tracker.trackEvent("quirk_fix", "description_replace", "RENFE OPERADORA", 0L) val optionalDepart = getPassFieldForKey(pass, "boardingTime") val optionalArrive = getPassFieldForKey(pass, "destino") if (optionalDepart != null && optionalArrive != null) { tracker.trackEvent("quirk_fix", "description_replace", "RENFE OPERADORA", 1L) pass.description = optionalDepart.label + " -> " + optionalArrive.label } } private fun careForSWISS(pass: PassImpl) { if (pass.creator == null || pass.creator != "SWISS") { return } tracker.trackEvent("quirk_fix", "description_replace", "SWISS", 0L) val optionalDepart = getPassFieldForKey(pass, "depart") val optionalArrive = getPassFieldForKey(pass, "destination") if (optionalDepart != null && optionalArrive != null) { tracker.trackEvent("quirk_fix", "description_replace", "SWISS", 1L) pass.description = optionalDepart.value + " -> " + optionalArrive.value } } private fun careForCathayPacific(pass: PassImpl) { if (pass.creator == null || pass.creator != "Cathay Pacific") { return } tracker.trackEvent("quirk_fix", "description_replace", "cathay_pacific", 0L) val optionalDepart = getPassFieldForKey(pass, "departure") val optionalArrive = getPassFieldForKey(pass, "arrival") if (optionalDepart != null && optionalArrive != null) { tracker.trackEvent("quirk_fix", "description_replace", "cathay_pacific", 1L) pass.description = optionalDepart.label + " -> " + optionalArrive.label } } private fun careForVirginAustralia(pass: PassImpl) { // also good identifier could be "passTypeIdentifier": "pass.com.virginaustralia.boardingpass if (pass.creator == null || pass.creator != "Virgin Australia") { return } tracker.trackEvent("quirk_fix", "description_replace", "virgin_australia", 0L) val optionalDepart = getPassFieldForKey(pass, "origin") val optionalArrive = getPassFieldForKey(pass, "destination") if (optionalDepart != null && optionalArrive != null) { tracker.trackEvent("quirk_fix", "description_replace", "virgin_australia", 1L) pass.description = optionalDepart.label + " -> " + optionalArrive.label } } private fun careForAirCanada(pass: PassImpl) { if (pass.creator == null || pass.creator != "Air Canada") { return } tracker.trackEvent("quirk_fix", "description_replace", "air_canada", 0L) val optionalDepart = getPassFieldForKey(pass, "depart") val optionalArrive = getPassFieldForKey(pass, "arrive") if (optionalDepart != null && optionalArrive != null) { tracker.trackEvent("quirk_fix", "description_replace", "air_canada", 1L) pass.description = optionalDepart.label + " -> " + optionalArrive.label } } private fun careForUSAirways(pass: PassImpl) { if (pass.creator == null || pass.creator != "US Airways") { return } tracker.trackEvent("quirk_fix", "description_replace", "usairways", 0L) val optionalDepart = getPassFieldForKey(pass, "depart") val optionalArrive = getPassFieldForKey(pass, "destination") if (optionalDepart != null && optionalArrive != null) { tracker.trackEvent("quirk_fix", "description_replace", "usairways", 1L) pass.description = optionalDepart.label + " -> " + optionalArrive.label } } private fun careForWestbahn(pass: PassImpl) { if (pass.calendarTimespan != null || (pass.creator ?: "") != "WESTbahn") { return } tracker.trackEvent("quirk_fix", "description_replace", "westbahn", 0L) val originField = getPassFieldForKey(pass, "from") val destinationField = getPassFieldForKey(pass, "to") var description = "WESTbahn" if (originField != null) { val value = originField.value if (value != null) { tracker.trackEvent("quirk_fix", "description_replace", "westbahn", 1L) description = value } } if (destinationField != null) { tracker.trackEvent("quirk_fix", "description_replace", "westbahn", 2L) description += "->" + destinationField.value!! } pass.description = description } private fun careForTUIFlight(pass: PassImpl) { if (pass.description != "TUIfly pass") { return } tracker.trackEvent("quirk_fix", "description_replace", "tuiflight", 0L) val originField = getPassFieldForKey(pass, "Origin") val destinationField = getPassFieldForKey(pass, "Des") val seatField = getPassFieldForKey(pass, "SeatNumber") if (originField != null && destinationField != null) { tracker.trackEvent("quirk_fix", "description_replace", "tuiflight", 1L) var description = originField.value + "->" + destinationField.value if (seatField != null) { tracker.trackEvent("quirk_fix", "description_replace", "tuiflight", 2L) description += " @" + seatField.value!! } pass.description = description } } private fun careForAirBerlin(pass: PassImpl) { if (pass.description != "boardcard") { return } val flightRegex = "\\b\\w{1,3}\\d{3,4}\\b" var flightField = getPassFieldThatMatchesLabel(pass, flightRegex) if (flightField == null) { flightField = getPassFieldThatMatchesLabel(pass, flightRegex) } val seatField = getPassFieldForKey(pass, "seat") val boardingGroupField = getPassFieldForKey(pass, "boardingGroup") if (flightField != null && seatField != null && boardingGroupField != null) { tracker.trackEvent("quirk_fix", "description_replace", "air_berlin", 0L) var description = flightField.label + " " + flightField.value description += " | " + seatField.label + " " + seatField.value description += " | " + boardingGroupField.label + " " + boardingGroupField.value pass.description = description } // otherwise fallback to default - better save than sorry } }
gpl-3.0
598cc9405d72d65cf0c256fc43db58c5
35.832599
102
0.604832
4.116691
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/bloggingprompts/onboarding/BloggingPromptsOnboardingDialogFragment.kt
1
10015
package org.wordpress.android.ui.bloggingprompts.onboarding import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult import androidx.core.text.bold import androidx.core.text.buildSpannedString import androidx.lifecycle.ViewModelProvider import com.google.android.flexbox.FlexDirection import com.google.android.flexbox.FlexWrap import com.google.android.flexbox.FlexboxLayoutManager import com.google.android.flexbox.JustifyContent import com.google.android.material.snackbar.Snackbar import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.analytics.AnalyticsTracker.Stat import org.wordpress.android.databinding.BloggingPromptsOnboardingDialogContentViewBinding import org.wordpress.android.ui.ActivityLauncher import org.wordpress.android.ui.avatars.AVATAR_LEFT_OFFSET_DIMEN import org.wordpress.android.ui.avatars.AvatarItemDecorator import org.wordpress.android.ui.avatars.TrainOfAvatarsAdapter import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.DismissDialog import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.DoNothing import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.OpenEditor import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.OpenRemindersIntro import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.OpenSitePicker import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingDialogFragment.DialogType.ONBOARDING import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingUiState.Ready import org.wordpress.android.ui.featureintroduction.FeatureIntroductionDialogFragment import org.wordpress.android.ui.main.SitePickerActivity import org.wordpress.android.ui.main.SitePickerAdapter.SitePickerMode.BLOGGING_PROMPTS_MODE import org.wordpress.android.ui.main.UpdateSelectedSiteListener import org.wordpress.android.ui.mysite.SelectedSiteRepository import org.wordpress.android.ui.posts.PostUtils.EntryPoint.BLOGGING_PROMPTS_INTRODUCTION import org.wordpress.android.util.RtlUtils import org.wordpress.android.util.SnackbarItem import org.wordpress.android.util.SnackbarItem.Action import org.wordpress.android.util.SnackbarItem.Info import org.wordpress.android.util.SnackbarSequencer import org.wordpress.android.util.extensions.exhaustive import org.wordpress.android.util.image.ImageManager import org.wordpress.android.viewmodel.observeEvent import javax.inject.Inject class BloggingPromptsOnboardingDialogFragment : FeatureIntroductionDialogFragment() { @Inject lateinit var imageManager: ImageManager @Inject lateinit var snackbarSequencer: SnackbarSequencer private lateinit var viewModel: BloggingPromptsOnboardingViewModel private lateinit var dialogType: DialogType private val sitePickerLauncher = registerForActivityResult(StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { val selectedSiteLocalId = result.data?.getIntExtra( SitePickerActivity.KEY_SITE_LOCAL_ID, SelectedSiteRepository.UNAVAILABLE ) ?: SelectedSiteRepository.UNAVAILABLE viewModel.onSiteSelected(selectedSiteLocalId) (activity as? UpdateSelectedSiteListener)?.onUpdateSelectedSiteResult(result.resultCode, result.data) } } enum class DialogType { ONBOARDING, INFORMATION } companion object { const val TAG = "BLOGGING_PROMPTS_ONBOARDING_DIALOG_FRAGMENT" const val KEY_DIALOG_TYPE = "KEY_DIALOG_TYPE" @JvmStatic fun newInstance(type: DialogType): BloggingPromptsOnboardingDialogFragment = BloggingPromptsOnboardingDialogFragment().apply { arguments = Bundle().apply { putSerializable(KEY_DIALOG_TYPE, type) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this, viewModelFactory).get(BloggingPromptsOnboardingViewModel::class.java) setupHeaderTitle() setupHeaderIcon() setupUiStateObserver() setupActionObserver() setupSnackbarObserver() viewModel.start(dialogType) } @Suppress("UseCheckOrError") override fun onAttach(context: Context) { super.onAttach(context) arguments?.let { dialogType = it.getSerializable(KEY_DIALOG_TYPE) as DialogType } (requireActivity().applicationContext as WordPress).component().inject(this) if (dialogType == ONBOARDING && context !is BloggingPromptsReminderSchedulerListener) { throw IllegalStateException( "$context must implement ${BloggingPromptsReminderSchedulerListener::class.simpleName}" ) } } private fun setupHeaderTitle() { setHeaderTitle(R.string.blogging_prompts_onboarding_header_title) } private fun setupHeaderIcon() { setHeaderIcon(R.drawable.ic_outline_lightbulb_orange_gradient_40dp) } private fun setupContent(readyState: Ready) { val contentBinding = BloggingPromptsOnboardingDialogContentViewBinding.inflate(layoutInflater) setContent(contentBinding.root) with(contentBinding) { contentTop.text = getString(readyState.contentTopRes) cardCoverView.setOnClickListener { /*do nothing*/ } promptCard.promptContent.text = getString(readyState.promptRes) val layoutManager = FlexboxLayoutManager( context, FlexDirection.ROW, FlexWrap.NOWRAP ).apply { justifyContent = JustifyContent.CENTER } promptCard.answeredUsersRecycler.addItemDecoration( AvatarItemDecorator(RtlUtils.isRtl(context), requireContext(), AVATAR_LEFT_OFFSET_DIMEN) ) promptCard.answeredUsersRecycler.layoutManager = layoutManager val adapter = TrainOfAvatarsAdapter( imageManager, uiHelpers ) promptCard.answeredUsersRecycler.adapter = adapter adapter.loadData(readyState.respondents) setPrimaryButtonText(readyState.primaryButtonLabel) togglePrimaryButtonVisibility(readyState.isPrimaryButtonVisible) setPrimaryButtonListener { readyState.onPrimaryButtonClick() } setSecondaryButtonText(readyState.secondaryButtonLabel) toggleSecondaryButtonVisibility(readyState.isSecondaryButtonVisible) setSecondaryButtonListener { readyState.onSecondaryButtonClick() } setDismissAnalyticsEvent(Stat.BLOGGING_PROMPTS_INTRODUCTION_SCREEN_DISMISSED, emptyMap()) contentBottom.text = getString(readyState.contentBottomRes) contentNote.text = buildSpannedString { bold { append("${getString(readyState.contentNoteTitle)} ") } append(getString(readyState.contentNoteContent)) } } } private fun setupUiStateObserver() { viewModel.uiState.observe(this) { uiState -> when (uiState) { is Ready -> { setupContent(uiState) } }.exhaustive } } private fun setupActionObserver() { viewModel.action.observe(this) { action -> when (action) { is OpenEditor -> { activity?.let { startActivity( ActivityLauncher.openEditorWithBloggingPrompt( it, action.promptId, BLOGGING_PROMPTS_INTRODUCTION ) ) } } is OpenSitePicker -> { val intent = Intent(context, SitePickerActivity::class.java).apply { putExtra(SitePickerActivity.KEY_SITE_LOCAL_ID, action.selectedSite) putExtra(SitePickerActivity.KEY_SITE_PICKER_MODE, BLOGGING_PROMPTS_MODE) } sitePickerLauncher.launch(intent) } is OpenRemindersIntro -> { activity?.let { dismiss() (it as BloggingPromptsReminderSchedulerListener) .onSetPromptReminderClick(action.selectedSiteLocalId) } } is DismissDialog -> { dismiss() } DoNothing -> {} // noop }.exhaustive } } private fun setupSnackbarObserver() { viewModel.snackBarMessage.observeEvent(viewLifecycleOwner) { holder -> snackbarSequencer.enqueue( SnackbarItem( Info( view = getSuperBinding().coordinatorLayout, textRes = holder.message, duration = Snackbar.LENGTH_LONG ), holder.buttonTitle?.let { Action( textRes = holder.buttonTitle, clickListener = { holder.buttonAction() } ) }, dismissCallback = { _, event -> holder.onDismissAction(event) } ) ) } } }
gpl-2.0
36e8dbcca8ae0c63fcf01818e286ac9b
44.112613
120
0.66031
5.598099
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/mediapicker/loader/DeviceListBuilder.kt
1
8608
package org.wordpress.android.ui.mediapicker.loader import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.async import kotlinx.coroutines.withContext import org.wordpress.android.R import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.utils.MediaUtils import org.wordpress.android.fluxc.utils.MimeTypes import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.ui.mediapicker.MediaItem import org.wordpress.android.ui.mediapicker.MediaItem.Identifier.LocalUri import org.wordpress.android.ui.mediapicker.MediaType import org.wordpress.android.ui.mediapicker.MediaType.AUDIO import org.wordpress.android.ui.mediapicker.MediaType.DOCUMENT import org.wordpress.android.ui.mediapicker.MediaType.IMAGE import org.wordpress.android.ui.mediapicker.MediaType.VIDEO import org.wordpress.android.ui.mediapicker.loader.MediaSource.MediaLoadingResult import org.wordpress.android.ui.mediapicker.loader.MediaSource.MediaLoadingResult.Empty import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.util.LocaleManagerWrapper import org.wordpress.android.util.MediaUtilsWrapper import javax.inject.Inject import javax.inject.Named @Suppress("LongParameterList") class DeviceListBuilder( private val localeManagerWrapper: LocaleManagerWrapper, private val deviceMediaLoader: DeviceMediaLoader, private val mediaUtilsWrapper: MediaUtilsWrapper, private val site: SiteModel?, @param:Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher, override val mediaTypes: Set<MediaType>, private val pageSize: Int ) : MediaSource, MediaSourceWithTypes { private val mimeTypes = MimeTypes() private val cache = mutableMapOf<MediaType, Result>() override suspend fun load( forced: Boolean, loadMore: Boolean, filter: String? ): MediaLoadingResult { if (!loadMore) { cache.clear() } val lowerCaseFilter = filter?.lowercase(localeManagerWrapper.getLocale()) return withContext(bgDispatcher) { val mediaItems = mutableListOf<MediaItem>() val deferredJobs = mediaTypes.map { mediaType -> when (mediaType) { IMAGE, VIDEO, AUDIO -> async { mediaType to loadMedia( mediaType, lowerCaseFilter ) } DOCUMENT -> async { mediaType to loadDownloads(lowerCaseFilter) } } } val results = deferredJobs.map { it.await() } // This is necessary because of the following use case: // - Page size is 5, we have 10 new images, 10 audio files that are all older than all the images // - We load first 5 images and first five audio files // - The 5 other images are newer than the currently loaded audio files // - We shouldn't show any audio files until we show all the images // The following solution goes through all the results and finds the last item in each list. // From these items it picks the newest one (the last one we definitely want to show) // This item sets the threshold for the visible items in all the list val lastShownTimestamp = results.fold(0L) { timestamp, (_, result) -> val nextTimestamp = result?.nextTimestamp if (nextTimestamp != null && nextTimestamp > timestamp) { nextTimestamp } else { timestamp } } // Here we filter out all the items older than the selected last visible item results.forEach { (mediaType, result) -> if (result != null) { val visibleItems = result.items.takeWhile { it.dataModified >= lastShownTimestamp } cache[mediaType] = result.copy(visibleItems = visibleItems.size) mediaItems.addAll(visibleItems) } } mediaItems.sortByDescending { it.dataModified } if (filter.isNullOrEmpty() || mediaItems.isNotEmpty()) { MediaLoadingResult.Success(mediaItems, lastShownTimestamp > 0L) } else { Empty( UiStringRes(R.string.media_empty_search_list), image = R.drawable.img_illustration_empty_results_216dp ) } } } private fun loadMedia(mediaType: MediaType, filter: String?): Result? { if (!cache[mediaType].shouldLoadMoreData()) { return cache[mediaType] } val lastDateModified = cache[mediaType]?.nextTimestamp val deviceMediaList = deviceMediaLoader.loadMedia(mediaType, filter, pageSize, lastDateModified) val result = deviceMediaList.items.mapNotNull { val mimeType = deviceMediaLoader.getMimeType(it.uri) val isMimeTypeSupported = mimeType != null && site?.let { mediaUtilsWrapper.isMimeTypeSupportedBySitePlan( site, mimeType ) } ?: true && MediaUtils.isSupportedMimeType( mimeType ) if (isMimeTypeSupported) { MediaItem(LocalUri(it.uri), it.uri.toString(), it.title, mediaType, mimeType, it.dateModified) } else { null } } addPage(mediaType, result, deviceMediaList.next) return cache[mediaType] } private suspend fun loadDownloads(filter: String?): Result? = withContext(bgDispatcher) { if (!cache[DOCUMENT].shouldLoadMoreData()) { return@withContext cache[DOCUMENT] } val lastDateModified = cache[DOCUMENT]?.nextTimestamp val documentsList = deviceMediaLoader.loadDocuments(filter, pageSize, lastDateModified) val filteredPage = documentsList.items.mapNotNull { document -> val mimeType = deviceMediaLoader.getMimeType(document.uri) val isMimeTypeSupported = mimeType != null && site?.let { mediaUtilsWrapper.isMimeTypeSupportedBySitePlan( site, mimeType ) } ?: true && MediaUtils.isSupportedMimeType( mimeType ) val isSupportedApplicationType = mimeType != null && mimeTypes.isSupportedApplicationType(mimeType) if (isSupportedApplicationType && isMimeTypeSupported) { MediaItem( LocalUri(document.uri), document.uri.toString(), document.title, DOCUMENT, mimeType, document.dateModified ) } else { null } } addPage(DOCUMENT, filteredPage, documentsList.next) return@withContext cache[DOCUMENT] } private fun addPage(mediaType: MediaType, page: List<MediaItem>, nextTimestamp: Long?) { val newData = cache[mediaType]?.items?.toMutableList() ?: mutableListOf() newData.addAll(page) cache[mediaType] = Result(newData, nextTimestamp) } data class Result(val items: List<MediaItem>, val nextTimestamp: Long? = null, val visibleItems: Int = 0) // We only want to show more data if there isn't already a page loaded that wasn't shown before private fun Result?.shouldLoadMoreData(): Boolean { return this == null || (nextTimestamp != null && this.items.size <= (visibleItems + pageSize)) } class DeviceListBuilderFactory @Inject constructor( private val localeManagerWrapper: LocaleManagerWrapper, private val deviceMediaLoader: DeviceMediaLoader, private val mediaUtilsWrapper: MediaUtilsWrapper, @param:Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) { fun build(mediaTypes: Set<MediaType>, site: SiteModel?): DeviceListBuilder { return DeviceListBuilder( localeManagerWrapper, deviceMediaLoader, mediaUtilsWrapper, site, bgDispatcher, mediaTypes, PAGE_SIZE ) } companion object { private const val PAGE_SIZE = 32 } } }
gpl-2.0
04c4fec5a3ad9c3b6bf8718be6d18ca3
42.695431
111
0.61652
5.320148
false
false
false
false
micolous/metrodroid
src/main/java/au/id/micolous/metrodroid/fragment/NumberPickerPreferenceFragment.kt
1
1282
package au.id.micolous.metrodroid.fragment import android.view.View import android.widget.NumberPicker import androidx.preference.PreferenceDialogFragmentCompat import au.id.micolous.metrodroid.ui.NumberPickerPreference import au.id.micolous.farebot.R import au.id.micolous.metrodroid.multi.Log class NumberPickerPreferenceFragment : PreferenceDialogFragmentCompat() { var numberPicker: NumberPicker? = null override fun onBindDialogView(view: View?) { super.onBindDialogView(view) numberPicker = view?.findViewById(R.id.edit) Log.d("NumberPicker", "numberPicker = $numberPicker, preference = $preference") val pref = preference as? NumberPickerPreference ?: return Log.d("NumberPicker", "pref value = ${pref.value}") numberPicker?.isEnabled = true numberPicker?.minValue = pref.minValue numberPicker?.maxValue = pref.maxValue numberPicker?.value = pref.value } override fun onDialogClosed(positiveResult: Boolean) { if (positiveResult) { val pref = preference as? NumberPickerPreference ?: return val value = numberPicker?.value ?: return if (pref.callChangeListener(value)) { pref.value = value } } } }
gpl-3.0
6e50560cfd8a32fb6830180b1122796d
35.628571
87
0.691888
4.949807
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-5/app/src/main/java/dev/mfazio/pennydrop/data/PennyDropDao.kt
1
2600
package dev.mfazio.pennydrop.data import androidx.lifecycle.LiveData import androidx.room.* import dev.mfazio.pennydrop.types.Player import java.time.OffsetDateTime @Dao abstract class PennyDropDao { @Query("SELECT * FROM players WHERE playerName = :playerName") abstract fun getPlayer(playerName: String): Player? /* This is a transaction since GameWithPlayers pulls from multiple tables. */ @Transaction @Query("SELECT * FROM games ORDER BY startTime DESC LIMIT 1") abstract fun getCurrentGameWithPlayers(): LiveData<GameWithPlayers> @Transaction @Query( """ SELECT * FROM game_statuses WHERE gameId = ( SELECT gameId FROM games ORDER BY startTime DESC LIMIT 1) ORDER BY gamePlayerNumber """ ) abstract fun getCurrentGameStatuses(): LiveData<List<GameStatus>> @Insert abstract suspend fun insertGame(game: Game): Long @Insert abstract suspend fun insertPlayer(player: Player): Long @Insert abstract suspend fun insertPlayers(players: List<Player>): List<Long> @Insert abstract suspend fun insertGameStatuses(gameStatuses: List<GameStatus>) @Update abstract suspend fun updateGame(game: Game) @Update abstract suspend fun updateGameStatuses(gameStatuses: List<GameStatus>) @Query( """ UPDATE games SET endTime = :endDate, gameState = :gameState WHERE endTime IS NULL """ ) abstract suspend fun closeOpenGames( endDate: OffsetDateTime = OffsetDateTime.now(), gameState: GameState = GameState.Cancelled ) @Transaction open suspend fun startGame(players: List<Player>): Long { this.closeOpenGames() val gameId = this.insertGame( Game( gameState = GameState.Started, currentTurnText = "The game has begun!\n", canRoll = true ) ) val playerIds = players.map { player -> getPlayer(player.playerName)?.playerId ?: insertPlayer(player) } this.insertGameStatuses( playerIds.mapIndexed { index, playerId -> GameStatus( gameId, playerId, index, index == 0 ) } ) return gameId } @Transaction open suspend fun updateGameAndStatuses(game: Game, statuses: List<GameStatus>) { this.updateGame(game) this.updateGameStatuses(statuses) } }
apache-2.0
70e22a1fa4da90aac43d30997ccffc13
25.814433
84
0.612692
5.029014
false
false
false
false
siarhei-luskanau/android-iot-doorbell
navigation/src/main/kotlin/siarhei/luskanau/iot/doorbell/navigation/DefaultAppNavigation.kt
1
1933
package siarhei.luskanau.iot.doorbell.navigation import android.os.Bundle import androidx.fragment.app.FragmentActivity import androidx.navigation.NavController import androidx.navigation.NavDirections import androidx.navigation.fragment.NavHostFragment import siarhei.luskanau.iot.doorbell.common.AppNavigation import siarhei.luskanau.iot.doorbell.ui.splash.SplashNavigation import timber.log.Timber class DefaultAppNavigation( private val activity: FragmentActivity ) : AppNavigation, SplashNavigation { private fun getNavController(): NavController = (activity.supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment) .navController @Suppress("TooGenericExceptionCaught") private fun navigateTo(direction: NavDirections) = try { getNavController().navigate(direction) } catch (e: Exception) { Timber.e(e) } override fun goBack(): Boolean = getNavController().popBackStack() override fun goDoorbellListToPermissions() = navigateTo(NavRootDirections.actionDoorbellListToPermissions()) override fun navigateToImageList(doorbellId: String) = navigateTo( NavRootDirections.actionDoorbellListToImageList( doorbellId = doorbellId ) ) override fun navigateToImageDetails(doorbellId: String, imageId: String) = navigateTo( NavRootDirections.actionImageListToImageDetails( doorbellId = doorbellId, imageId = imageId ) ) override fun buildImageDetailsArgs(doorbellId: String, imageId: String): Bundle = NavRootDirections.actionImageListToImageDetails( doorbellId = doorbellId, imageId = imageId ).arguments override fun onSplashComplete() = navigateTo(NavRootDirections.actionSplashToDoorbellList()) }
mit
bc6a63e298264c3214f847183a02045b
32.327586
99
0.707191
5.44507
false
false
false
false
Turbo87/intellij-emberjs
src/main/kotlin/com/emberjs/navigation/EmberGotoClassContributor.kt
1
3117
package com.emberjs.navigation import com.emberjs.icons.EmberIconProvider import com.emberjs.icons.EmberIcons import com.emberjs.index.EmberNameIndex import com.emberjs.resolver.EmberName import com.emberjs.utils.isInRepoAddon import com.emberjs.utils.parentEmberModule import com.intellij.navigation.DelegatingItemPresentation import com.intellij.navigation.GotoClassContributor import com.intellij.navigation.NavigationItem import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.util.indexing.FindSymbolParameters.searchScopeFor class EmberGotoClassContributor : GotoClassContributor { private val iconProvider by lazy { EmberIconProvider() } override fun getQualifiedName(item: NavigationItem?): String? { if (item is DelegatingNavigationItem) { return item.presentation?.presentableText?.replace("-", qualifiedNameSeparator) } return null } override fun getQualifiedNameSeparator() = " " /** * Get all entries from the module index and extract the `displayName` property. */ override fun getNames(project: Project, includeNonProjectItems: Boolean): Array<String> { return EmberNameIndex.getAllKeys(project) .map { it.displayName } .toTypedArray() } override fun getItemsByName(name: String, pattern: String, project: Project, includeNonProjectItems: Boolean): Array<NavigationItem> { val scope = searchScopeFor(project, includeNonProjectItems) val psiManager = PsiManager.getInstance(project) // Collect all matching modules from the index return EmberNameIndex.getFilteredPairs(scope) { it.displayName == name } // Find the corresponding PsiFiles .mapNotNull { (module, file) -> psiManager.findFile(file)?.let { Pair(module, it) } } // Convert search results for LookupElements .map { convert(it.first, it.second) } .toTypedArray() } private fun convert(module: EmberName, file: PsiFile): DelegatingNavigationItem { val presentation = DelegatingItemPresentation(file.presentation) .withPresentableText(module.displayName) .withLocationString(getLocation(file)) .withIcon(iconProvider.getIcon(module) ?: DEFAULT_ICON) return DelegatingNavigationItem(file) .withPresentation(presentation) } private fun getLocation(file: PsiFile): String? { val root = file.virtualFile.parentEmberModule ?: return null val prefix = file.virtualFile.path.removePrefix(root.path) return when { root.isInRepoAddon -> "(${root.name} addon)" prefix.startsWith("/app/") -> null prefix.startsWith("/addon/") -> "(addon)" prefix.startsWith("/tests/dummy/app/") -> "(dummy app)" prefix.startsWith("/tests/") -> "(test)" else -> null } } companion object { val DEFAULT_ICON = EmberIcons.EMPTY_16 } }
apache-2.0
3d0985f43a9c70ab5c083e3df9590fce
37.9625
138
0.680462
4.89325
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidJavadoc/src/main/kotlin/com/eden/orchid/javadoc/pages/JavadocPackagePage.kt
1
2316
@file:Suppress(SuppressedWarnings.DEPRECATION) package com.eden.orchid.javadoc.pages import com.copperleaf.javadoc.json.models.JavaPackageDoc import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.javadoc.JavadocGenerator import com.eden.orchid.javadoc.resources.PackageDocResource import com.eden.orchid.utilities.SuppressedWarnings @Archetype(value = ConfigArchetype::class, key = "${JavadocGenerator.GENERATOR_KEY}.packagePages") @Description(value = "Documentation for a Java package.", name = "Java Package") class JavadocPackagePage( context: OrchidContext, val packageDoc: JavaPackageDoc, val classes: List<JavadocClassPage> ) : BaseJavadocPage(PackageDocResource(context, packageDoc), "javadocPackage", packageDoc.name) { val innerPackages: MutableList<JavadocPackagePage> = ArrayList() override val itemIds: List<String> get() = listOf(packageDoc.qualifiedName) fun hasInterfaces(): Boolean { return classes.any { it.classDoc.kind == "interface" } } val interfaces: List<JavadocClassPage> get() { return classes.filter { it.classDoc.kind == "interface" } } fun hasAnnotations(): Boolean { return classes.any { it.classDoc.kind == "@interface" } } val annotations: List<JavadocClassPage> get() { return classes.filter { it.classDoc.kind == "@interface" } } fun hasEnums(): Boolean { return classes.any { it.classDoc.kind == "enum" } } val enums: List<JavadocClassPage> get() { return classes.filter { it.classDoc.kind == "enum" } } fun hasExceptions(): Boolean { return classes.any { it.classDoc.kind == "exception" } } val exceptions: List<JavadocClassPage> get() { return classes.filter { it.classDoc.kind == "exception" } } fun hasOrdinaryClasses(): Boolean { return classes.any { it.classDoc.kind == "class" } } val ordinaryClasses: List<JavadocClassPage> get() { return classes.filter { it.classDoc.kind == "class" } } }
mit
056b4983abe2faf872a3f34aeeba1188
31.619718
98
0.675734
4.296846
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/RefactoringCase.kt
4
2257
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions.internal.refactoringTesting import com.intellij.openapi.project.Project internal sealed class RandomMoveRefactoringResult { internal class Success(val caseData: String) : RandomMoveRefactoringResult() internal class ExceptionCaused(val caseData: String, val message: String) : RandomMoveRefactoringResult() internal companion object Failed : RandomMoveRefactoringResult() } internal interface RefactoringCase { fun tryCreateAndRun(project: Project): RandomMoveRefactoringResult } internal fun RefactoringCase.tryCreateAndRun(project: Project, refactoringCountBeforeCheck: Int): RandomMoveRefactoringResult { require(refactoringCountBeforeCheck >= 1) { "refactoringCountBeforeCheck must be greater than zero" } if (refactoringCountBeforeCheck == 1) return tryCreateAndRun(project) var maxTries = refactoringCountBeforeCheck * 10 var exception: RandomMoveRefactoringResult.ExceptionCaused? = null val refactoringSequence = generateSequence { if (maxTries-- < 0) return@generateSequence null val refactoringResult = tryCreateAndRun(project) if (refactoringResult is RandomMoveRefactoringResult.ExceptionCaused) { exception = refactoringResult return@generateSequence null } refactoringResult } val caseHistory = refactoringSequence .filterIsInstance<RandomMoveRefactoringResult.Success>() .take(refactoringCountBeforeCheck) .map { it.caseData } .foldIndexed("") { index, acc, argument -> "$acc\n\nRefactoring #${index + 1}:\n$argument" } exception?.run { val exceptionCaseData = if (caseHistory.isNotEmpty()) "Refactorings sequence:\n$caseHistory\ncaused an exception on further refactoring\n$caseData" else caseData RandomMoveRefactoringResult.ExceptionCaused(exceptionCaseData, message) }?.let { return it } return if (caseHistory.isNotEmpty()) RandomMoveRefactoringResult.Success(caseHistory) else RandomMoveRefactoringResult.Failed }
apache-2.0
b8ea17b688bc187c4cfbe3ad5c6b84e3
37.931034
158
0.747452
4.96044
false
false
false
false
walleth/kethereum
extensions/src/main/kotlin/org/kethereum/extensions/Int.kt
1
404
package org.kethereum.extensions fun Int.toByteArray() = ByteArray(4) { i -> shr(8 * (3 - i)).toByte() } fun Int.toMinimalByteArray() = toByteArray().let { it.copyOfRange(it.minimalStart(), 4) } private fun ByteArray.minimalStart() = indexOfFirst { it != 0.toByte() }.let { if (it == -1) 4 else it } fun ByteArray.removeLeadingZero() = if (first() == 0.toByte()) copyOfRange(1, size) else this
mit
4297e694840a325419cd8cb15fd79dc3
32.75
104
0.665842
3.311475
false
false
false
false
ftomassetti/kolasu
emf/src/main/kotlin/com/strumenta/kolasu/emf/Metamodel.kt
1
5482
package com.strumenta.kolasu.emf import com.strumenta.kolasu.model.* import com.strumenta.kolasu.validation.Result import org.eclipse.emf.ecore.* import org.eclipse.emf.ecore.resource.Resource import java.math.BigDecimal import java.math.BigInteger import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import kotlin.reflect.KClass import kotlin.reflect.KType interface EDataTypeHandler { fun canHandle(ktype: KType): Boolean fun toDataType(ktype: KType): EDataType fun external(): Boolean } interface EClassTypeHandler { fun canHandle(ktype: KType): Boolean { return if (ktype.classifier is KClass<*>) { canHandle(ktype.classifier as KClass<*>) } else { false } } fun canHandle(kclass: KClass<*>): Boolean fun toEClass(kclass: KClass<*>, eClassProvider: ClassifiersProvider): EClass fun external(): Boolean } interface ClassifiersProvider { fun isDataType(ktype: KType): Boolean { return try { provideDataType(ktype) true } catch (e: Exception) { false } } fun provideClass(kClass: KClass<*>): EClass fun provideDataType(ktype: KType): EDataType? } class KolasuClassHandler(val kolasuKClass: KClass<*>, val kolasuEClass: EClass) : EClassTypeHandler { override fun canHandle(kclass: KClass<*>): Boolean = kclass == kolasuKClass override fun toEClass(kclass: KClass<*>, eClassProvider: ClassifiersProvider): EClass { return kolasuEClass } override fun external(): Boolean = true } class KolasuDataTypeHandler(val kolasuKClass: KClass<*>, val kolasuDataType: EDataType) : EDataTypeHandler { override fun canHandle(ktype: KType): Boolean { return ktype.classifier == kolasuKClass && ktype.arguments.isEmpty() } override fun toDataType(ktype: KType): EDataType { return kolasuDataType } override fun external(): Boolean = true } val LocalDateHandler = KolasuClassHandler(LocalDate::class, STARLASU_METAMODEL.getEClass("LocalDate")) val LocalTimeHandler = KolasuClassHandler(LocalTime::class, STARLASU_METAMODEL.getEClass("LocalTime")) val LocalDateTimeHandler = KolasuClassHandler(LocalDateTime::class, STARLASU_METAMODEL.getEClass("LocalDateTime")) val NodeHandler = KolasuClassHandler(Node::class, STARLASU_METAMODEL.getEClass("ASTNode")) val NamedHandler = KolasuClassHandler(Named::class, STARLASU_METAMODEL.getEClass("Named")) val PositionHandler = KolasuClassHandler(Position::class, STARLASU_METAMODEL.getEClass("Position")) val PossiblyNamedHandler = KolasuClassHandler(PossiblyNamed::class, STARLASU_METAMODEL.getEClass("PossiblyNamed")) val ReferenceByNameHandler = KolasuClassHandler(ReferenceByName::class, STARLASU_METAMODEL.getEClass("ReferenceByName")) val ResultHandler = KolasuClassHandler(Result::class, STARLASU_METAMODEL.getEClass("Result")) val StatementHandler = KolasuClassHandler(Statement::class, STARLASU_METAMODEL.getEClass("Statement")) val ExpressionHandler = KolasuClassHandler(Expression::class, STARLASU_METAMODEL.getEClass("Expression")) val EntityDeclarationHandler = KolasuClassHandler( EntityDeclaration::class, STARLASU_METAMODEL .getEClass("EntityDeclaration") ) val StringHandler = KolasuDataTypeHandler(String::class, EcorePackage.eINSTANCE.eString) val CharHandler = KolasuDataTypeHandler(Char::class, EcorePackage.eINSTANCE.eChar) val BooleanHandler = KolasuDataTypeHandler(Boolean::class, EcorePackage.eINSTANCE.eBoolean) val IntHandler = KolasuDataTypeHandler(Int::class, EcorePackage.eINSTANCE.eInt) val IntegerHandler = KolasuDataTypeHandler(Integer::class, EcorePackage.eINSTANCE.eInt) val FloatHandler = KolasuDataTypeHandler(Float::class, EcorePackage.eINSTANCE.eFloat) val DoubleHandler = KolasuDataTypeHandler(Double::class, EcorePackage.eINSTANCE.eDouble) val BigIntegerHandler = KolasuDataTypeHandler(BigInteger::class, EcorePackage.eINSTANCE.eBigInteger) val BigDecimalHandler = KolasuDataTypeHandler(BigDecimal::class, EcorePackage.eINSTANCE.eBigDecimal) val LongHandler = KolasuDataTypeHandler(Long::class, EcorePackage.eINSTANCE.eLong) val KClass<*>.eClassifierName: String get() = this.java.eClassifierName val Class<*>.eClassifierName: String get() = if (this.enclosingClass != null) { "${this.enclosingClass.simpleName}${this.simpleName}" } else { this.simpleName } class ResourceClassTypeHandler(val resource: Resource, val ownPackage: EPackage) : EClassTypeHandler { override fun canHandle(klass: KClass<*>): Boolean = getPackage(packageName(klass)) != null private fun getPackage(packageName: String): EPackage? = resource.contents.find { it is EPackage && it != ownPackage && it.name == packageName } as EPackage? override fun toEClass(kclass: KClass<*>, eClassProvider: ClassifiersProvider): EClass { return getPackage(packageName(kclass))!!.eClassifiers.find { it is EClass && it.name == kclass.simpleName } as EClass? ?: throw NoClassDefFoundError(kclass.qualifiedName) } override fun external(): Boolean = true } internal fun EPackage.hasClassifierNamed(name: String): Boolean { return this.eClassifiers.any { it.name == name } } internal fun EPackage.classifierByName(name: String): EClassifier { return this.eClassifiers.find { it.name == name } ?: throw IllegalArgumentException( "No classifier named $name was found" ) }
apache-2.0
7c382b7dc437500dcc9d9728cbdbed8b
40.530303
120
0.751915
3.978229
false
false
false
false
marius-m/wt4
database2/src/main/java/lt/markmerkk/migrations/Migration1To2.kt
1
7780
package lt.markmerkk.migrations import lt.markmerkk.DBConnProvider import lt.markmerkk.Tags import lt.markmerkk.TimeProvider import lt.markmerkk.entities.LogTime import lt.markmerkk.entities.TicketCode import lt.markmerkk.toBoolean import lt.markmerkk.utils.UriUtils import org.joda.time.DateTime import org.slf4j.LoggerFactory import java.sql.Connection import java.sql.SQLException /** * Migration for worklog (not used yet) */ class Migration1To2( private val oldDatabase: DBConnProvider, private val newDatabase: DBConnProvider, private val timeProvider: TimeProvider ) : DBMigration { override val migrateVersionFrom: Int = 1 override val migrateVersionTo: Int = 2 override fun migrate(conn: Connection) { val sql = "" + "CREATE TABLE `worklog` (\n" + " `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" + " `start` BIGINT NOT NULL DEFAULT 0,\n" + " `end` BIGINT NOT NULL DEFAULT 0,\n" + " `duration` BIGINT NOT NULL DEFAULT 0,\n" + " `code` VARCHAR(50) DEFAULT '' NOT NULL,\n" + " `comment` TEXT DEFAULT '' NOT NULL,\n" + " `remote_id` BIGINT NOT NULL DEFAULT -1,\n" + " `is_deleted` TINYINT NOT NULL DEFAULT 0,\n" + " `is_dirty` TINYINT NOT NULL DEFAULT 0,\n" + " `is_error` TINYINT NOT NULL DEFAULT 0,\n" + " `error_message` TEXT NOT NULL DEFAULT '',\n" + " `fetchTime` BIGINT NOT NULL DEFAULT 0,\n" + " `URL` VARCHAR(1000) NOT NULL DEFAULT ''\n" + ");" try { val createTableStatement = conn.createStatement() logger.debug("Creating new table: $sql") createTableStatement.execute(sql) logger.debug("Migrating data to new database") moveFromOldDatabase() } catch (e: SQLException) { logger.error("Error executing migration from $migrateVersionFrom to $migrateVersionTo", e) } } private fun moveFromOldDatabase() { val now = DateTime.now().millis if (!oldDatabase.exist()) { logger.info("No old database") return } logger.info("Migrating old database") val oldConn = oldDatabase.connect() val newConn = newDatabase.connect() try { moveSingleLog(oldConn, newConn) } catch (e: SQLException) { logger.warn("Error moving old database", e) } finally { oldConn.close() newConn.close() } } private fun moveSingleLog( oldConnection: Connection, newConnection: Connection ) { val sql = "SELECT * FROM Log" val oldWorklogs: MutableList<LocalLogOld> = mutableListOf() try { val statement = oldConnection.createStatement() val rs = statement.executeQuery(sql) while (rs.next()) { val start = rs.getLong("start") val end = rs.getLong("end") val task = rs.getString("task") val comment = rs.getString("comment") val uri = rs.getString("uri") val deleted = rs.getInt("deleted") val dirty = rs.getInt("dirty") val error = rs.getInt("error") val errorMessage: String = rs.getString("errorMessage") ?: "" oldWorklogs.add(LocalLogOld( start = start, end = end, taskRaw = task, commentRaw = comment, uriRaw = uri, deleted = deleted.toBoolean(), dirty = dirty.toBoolean(), error = error.toBoolean(), errorMessageRaw = errorMessage )) } } catch (e: SQLException) { logger.warn("Could not read old database", e) } oldWorklogs.map { val logTime = LogTime.fromRaw( timeProvider, it.start, it.end ) val ticketCode = TicketCode.new(it.task) val remoteId = UriUtils.parseUri(it.uri) LocalLogNew( start = logTime.startAsRaw, end = logTime.endAsRaw, duration = logTime.durationAsRaw, code = ticketCode.code, comment = it.comment, remoteId = remoteId, isDeleted = it.deleted, isError = it.error, isDirty = it.dirty, errorMessage = it.errorMessage, fetchTime = 0, url = it.uri ) }.forEach { newLog -> try { val preparedStatement = newConnection.prepareStatement( "INSERT INTO worklog(" + "start," + "end," + "duration," + "code," + "comment," + "remote_id," + "is_deleted," + "is_dirty," + "is_error," + "error_message," + "fetchTime," + "URL" + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);" ) preparedStatement.setLong(1, newLog.start) preparedStatement.setLong(2, newLog.end) preparedStatement.setLong(3, newLog.duration) preparedStatement.setString(4, newLog.code) preparedStatement.setString(5, newLog.comment) preparedStatement.setLong(6, newLog.remoteId) preparedStatement.setBoolean(7, newLog.isDeleted) preparedStatement.setBoolean(8, newLog.isDirty) preparedStatement.setBoolean(9, newLog.isError) preparedStatement.setString(10, newLog.errorMessage) preparedStatement.setLong(11, newLog.fetchTime) preparedStatement.setString(12, newLog.url) preparedStatement.execute() } catch (e: SQLException) { logger.warn("Error inserting value $newLog due to ${e.message}") } } } private data class LocalLogOld( val start: Long, val end: Long, val taskRaw: String?, val commentRaw: String?, val uriRaw: String?, val deleted: Boolean, val dirty: Boolean, val error: Boolean, val errorMessageRaw: String? ) { val task = taskRaw?.replace("null", "") ?: "" val comment = commentRaw?.replace("null", "") ?: "" val uri = uriRaw?.replace("null", "") ?: "" val errorMessage = errorMessageRaw?.replace("null", "") ?: "" } private data class LocalLogNew( val start: Long, val end: Long, val duration: Long, val code: String, val comment: String, val remoteId: Long, val isDeleted: Boolean, val isDirty: Boolean, val isError: Boolean, val errorMessage: String, val fetchTime: Long, val url: String ) companion object { private val logger = LoggerFactory.getLogger(Tags.DB)!! } }
apache-2.0
40181730b0d5bd9c2eccf8ce47cb7a98
37.519802
102
0.494216
4.983985
false
false
false
false
zhudyos/uia
server/src/main/kotlin/io/zhudy/uia/BizCodes.kt
1
1872
package io.zhudy.uia /** * 业务错误码定义枚举. * * @author Kevin Zou <[email protected]> */ enum class BizCodes(override val code: Int, override val msg: String) : BizCode { // ====================================================== // // 公共错误码 0 - 999 // // ====================================================== // /** * 未知错误. */ C_0(0, "未知错误"), C_500(500, "服务器内部错误"), /** * HTTP Request 参数错误. */ C_999(999, "HTTP Request 参数错误"), // ====================================================== // // client 错误码 1000 - 1999 // // ====================================================== // /** * 未发现指定 client_id 客户端记录. */ C_1000(1000, "未发现指定 client_id 客户端记录"), C_1001(1001, "client_secret 不匹配"), C_1002(1002, "redirect_uri 不在白名单内"), // ====================================================== // // user 错误码 2000 - 2999 // // ====================================================== // /** * 未发现指定 email 的用户. */ C_2000(2000, "未发现指定 email 的用户"), C_2001(2001, "未发现指定 uid 的用户"), C_2002(2002, "未发现指定的 unionid 的用户"), C_2011(2011, "password 不匹配"), /** * oauth2 错误码. */ C_3000(3000, "非法的 redirect_uri"), C_3001(3001, "refresh_token 过期/或不存在"), C_3002(3002, "refresh_token 的 client_id 非法"), C_3003(3003, "authorization_code 的 client_id 非法"), C_3004(3004, "code 不存在或者已使用") // ; override fun toString(): String { return "[$code] $msg" } }
apache-2.0
b5c05f2316c4a9f1243974a682fba234
26.186441
81
0.375312
3.494553
false
false
false
false
octarine-noise/BetterFoliage
src/main/kotlin/mods/betterfoliage/client/texture/LeafParticleRegistry.kt
1
2911
package mods.betterfoliage.client.texture import mods.betterfoliage.BetterFoliageMod import mods.octarinecore.client.resource.* import mods.octarinecore.stripStart import net.minecraft.client.renderer.texture.TextureAtlasSprite import net.minecraft.util.ResourceLocation import net.minecraftforge.client.event.TextureStitchEvent import net.minecraftforge.common.MinecraftForge import net.minecraftforge.fml.common.eventhandler.EventPriority import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object LeafParticleRegistry { val typeMappings = TextureMatcher() val particles = hashMapOf<String, IconSet>() operator fun get(type: String) = particles[type] ?: particles["default"]!! init { MinecraftForge.EVENT_BUS.register(this) } @SubscribeEvent(priority = EventPriority.HIGH) fun handleLoadModelData(event: LoadModelDataEvent) { particles.clear() typeMappings.loadMappings(ResourceLocation(BetterFoliageMod.DOMAIN, "leaf_texture_mappings.cfg")) } @SubscribeEvent fun handlePreStitch(event: TextureStitchEvent.Pre) { val allTypes = (typeMappings.mappings.map { it.type } + "default").distinct() allTypes.forEach { leafType -> val particleSet = IconSet("betterfoliage", "blocks/falling_leaf_${leafType}_%d").apply { onPreStitch(event.map) } if (leafType == "default" || particleSet.num > 0) particles[leafType] = particleSet } } @SubscribeEvent fun handlePostStitch(event: TextureStitchEvent.Post) { particles.forEach { (_, particleSet) -> particleSet.onPostStitch(event.map) } } } class TextureMatcher { data class Mapping(val domain: String?, val path: String, val type: String) { fun matches(iconLocation: ResourceLocation): Boolean { return (domain == null || domain == iconLocation.namespace) && iconLocation.path.stripStart("blocks/").contains(path, ignoreCase = true) } } val mappings: MutableList<Mapping> = mutableListOf() fun getType(resource: ResourceLocation) = mappings.filter { it.matches(resource) }.map { it.type }.firstOrNull() fun getType(iconName: String) = ResourceLocation(iconName).let { getType(it) } fun loadMappings(mappingLocation: ResourceLocation) { mappings.clear() resourceManager[mappingLocation]?.getLines()?.let { lines -> lines.filter { !it.startsWith("//") }.filter { !it.isEmpty() }.forEach { line -> val line2 = line.trim().split('=') if (line2.size == 2) { val mapping = line2[0].trim().split(':') if (mapping.size == 1) mappings.add(Mapping(null, mapping[0].trim(), line2[1].trim())) else if (mapping.size == 2) mappings.add(Mapping(mapping[0].trim(), mapping[1].trim(), line2[1].trim())) } } } } }
mit
f6414940e82b8046c4b3178cbf6d6084
41.202899
125
0.672621
4.280882
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/Icosphere.kt
1
6748
package graphics.scenery import graphics.scenery.utils.extensions.minus import graphics.scenery.utils.extensions.plus import graphics.scenery.utils.extensions.times import org.joml.Vector3f import java.util.* import kotlin.math.* /** * Constructs a Icosphere with the given [radius] and number of [subdivisions]. * * @author Ulrik Günther <[email protected]>, based on code by Andreas Kahler, http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html * @param[radius] The radius of the sphere * @param[subdivisions] Number of subdivisions of the base icosahedron */ open class Icosphere(val radius: Float, val subdivisions: Int) : Mesh("Icosphere") { fun MutableList<Vector3f>.addVertex(vararg v: Float) { this.add(Vector3f(v)) } fun MutableList<Triple<Int, Int, Int>>.addFace(i: Int, j: Int, k: Int) { this.add(kotlin.Triple(i, j, k)) } protected fun createBaseVertices(vertices: MutableList<Vector3f>, indices: MutableList<Triple<Int, Int, Int>>) { val s = sqrt((5.0f - sqrt(5.0f)) / 10.0f) val t = sqrt((5.0f + sqrt(5.0f)) / 10.0f) vertices.addVertex(-s, t, 0.0f) vertices.addVertex(s, t, 0.0f) vertices.addVertex(-s, -t, 0.0f) vertices.addVertex(s, -t, 0.0f) vertices.addVertex(0.0f, -s, t) vertices.addVertex(0.0f, s, t) vertices.addVertex(0.0f, -s, -t) vertices.addVertex(0.0f, s, -t) vertices.addVertex(t, 0.0f, -s) vertices.addVertex(t, 0.0f, s) vertices.addVertex(-t, 0.0f, -s) vertices.addVertex(-t, 0.0f, s) indices.addFace(0, 11, 5) indices.addFace(0, 5, 1) indices.addFace(0, 1, 7) indices.addFace(0, 7, 10) indices.addFace(0, 10, 11) // 5 adjacent faces indices.addFace(1, 5, 9) indices.addFace(5, 11, 4) indices.addFace(11, 10, 2) indices.addFace(10, 7, 6) indices.addFace(7, 1, 8) // 5 faces around point 3 indices.addFace(3, 9, 4) indices.addFace(3, 4, 2) indices.addFace(3, 2, 6) indices.addFace(3, 6, 8) indices.addFace(3, 8, 9) // 5 adjacent faces indices.addFace(4, 9, 5) indices.addFace(2, 4, 11) indices.addFace(6, 2, 10) indices.addFace(8, 6, 7) indices.addFace(9, 8, 1) } protected fun refineTriangles(recursionLevel: Int, vertices: MutableList<Vector3f>, indices: MutableList<Triple<Int, Int, Int>>): MutableList<Triple<Int, Int, Int>> { // refine triangles var faces = indices (0 until recursionLevel).forEach { val faces2 = ArrayList<Triple<Int, Int, Int>>(indices.size * 3) for (triangle in faces) { // replace triangle by 4 triangles val a = vertices.getMiddlePoint(triangle.first, triangle.second) val b = vertices.getMiddlePoint(triangle.second, triangle.third) val c = vertices.getMiddlePoint(triangle.third, triangle.first) faces2.addFace(triangle.first, a, c) faces2.addFace(triangle.second, b, a) faces2.addFace(triangle.third, c, b) faces2.addFace(a, b, c) } faces = faces2 } return faces } protected fun MutableList<Vector3f>.addVertex(v: Vector3f): Int { this.add(v.normalize()) return this.size - 1 } private val middlePointIndexCache = HashMap<Long, Int>() protected fun MutableList<Vector3f>.getMiddlePoint(p1: Int, p2: Int): Int { // first check if we have it already val firstIsSmaller = p1 < p2 val smallerIndex = if(firstIsSmaller) { p1 } else { p2 } val greaterIndex = if(!firstIsSmaller) { p1 } else { p2 } val key: Long = (smallerIndex.toLong() shl 32) + greaterIndex.toLong() val ret = middlePointIndexCache[key] if (ret != null) { return ret } // not in cache, calculate it val point1 = this[p1] val point2 = this[p2] val middle = (point1 + point2) * 0.5f // add vertex makes sure point is on unit sphere val i = this.addVertex(middle) // store it, return index middlePointIndexCache.put(key, i) return i } private fun vertexToUV(n: Vector3f): Vector3f { val u = 0.5f - 0.5f * atan2(n.x(), -n.z())/ PI.toFloat() val v = 1.0f - acos(n.y()) / PI.toFloat() return Vector3f(u, v, 0.0f) } init { val vertexBuffer = ArrayList<Vector3f>() val indexBuffer = ArrayList<Triple<Int, Int, Int>>() createBaseVertices(vertexBuffer, indexBuffer) val faces = refineTriangles(subdivisions, vertexBuffer, indexBuffer) geometry { vertices = BufferUtils.allocateFloat(faces.size * 3 * 3) normals = BufferUtils.allocateFloat(faces.size * 3 * 3) texcoords = BufferUtils.allocateFloat(faces.size * 3 * 2) indices = BufferUtils.allocateInt(0) faces.forEach { f -> val v1 = vertexBuffer[f.first] val v2 = vertexBuffer[f.second] val v3 = vertexBuffer[f.third] val uv1 = vertexToUV(v1.normalize()) val uv2 = vertexToUV(v2.normalize()) val uv3 = vertexToUV(v3.normalize()) (v1 * radius).get(vertices).position(vertices.position() + 3) (v2 * radius).get(vertices).position(vertices.position() + 3) (v3 * radius).get(vertices).position(vertices.position() + 3) v1.get(normals).position(normals.position() + 3) v2.get(normals).position(normals.position() + 3) v3.get(normals).position(normals.position() + 3) val uvNormal = (uv2 - uv1).cross(uv3 - uv1) if(uvNormal.z() < 0.0f) { if(uv1.x() < 0.25f) { uv1.x = uv1.x() + 1.0f } if(uv2.x() < 0.25f) { uv2.x = uv2.x() + 1.0f } if(uv3.x() < 0.25f) { uv3.x = uv3.x() + 1.0f } } uv1.get(texcoords).position(texcoords.position() + 2) uv2.get(texcoords).position(texcoords.position() + 2) uv3.get(texcoords).position(texcoords.position() + 2) } vertices.flip() normals.flip() texcoords.flip() } boundingBox = generateBoundingBox() } }
lgpl-3.0
8eaa6bcc57e594016129bad9cd94d476
34.140625
150
0.555654
3.639159
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/event/internal/EventServiceImpl.kt
1
7687
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.event.internal import dagger.Reusable import io.reactivex.Single import javax.inject.Inject import org.hisp.dhis.android.core.category.CategoryOptionComboService import org.hisp.dhis.android.core.enrollment.EnrollmentCollectionRepository import org.hisp.dhis.android.core.enrollment.EnrollmentStatus import org.hisp.dhis.android.core.enrollment.internal.EnrollmentServiceImpl import org.hisp.dhis.android.core.event.* import org.hisp.dhis.android.core.event.EventService import org.hisp.dhis.android.core.organisationunit.OrganisationUnitService import org.hisp.dhis.android.core.program.ProgramCollectionRepository import org.hisp.dhis.android.core.program.ProgramStageCollectionRepository @Reusable @Suppress("LongParameterList", "TooManyFunctions") internal class EventServiceImpl @Inject constructor( private val enrollmentRepository: EnrollmentCollectionRepository, private val eventRepository: EventCollectionRepository, private val programRepository: ProgramCollectionRepository, private val programStageRepository: ProgramStageCollectionRepository, private val enrollmentService: EnrollmentServiceImpl, private val organisationUnitService: OrganisationUnitService, private val categoryOptionComboService: CategoryOptionComboService, private val eventDateUtils: EventDateUtils ) : EventService { override fun blockingHasDataWriteAccess(eventUid: String): Boolean { val event = eventRepository.uid(eventUid).blockingGet() ?: return false return programStageRepository.uid(event.programStage()).blockingGet()?.access()?.data()?.write() ?: false } override fun hasDataWriteAccess(eventUid: String): Single<Boolean> { return Single.just(blockingHasDataWriteAccess(eventUid)) } override fun blockingIsInOrgunitRange(event: Event): Boolean { return event.eventDate()?.let { eventDate -> event.organisationUnit()?.let { orgunitUid -> organisationUnitService.blockingIsDateInOrgunitRange(orgunitUid, eventDate) } } ?: true } override fun isInOrgunitRange(event: Event): Single<Boolean> { return Single.just(blockingIsInOrgunitRange(event)) } override fun blockingHasCategoryComboAccess(event: Event): Boolean { return event.attributeOptionCombo()?.let { categoryOptionComboService.blockingHasAccess(it, event.eventDate()) } ?: true } override fun hasCategoryComboAccess(event: Event): Single<Boolean> { return Single.just(blockingHasCategoryComboAccess(event)) } override fun blockingIsEditable(eventUid: String): Boolean { return blockingGetEditableStatus(eventUid) is EventEditableStatus.Editable } override fun isEditable(eventUid: String): Single<Boolean> { return Single.just(blockingIsEditable(eventUid)) } @Suppress("ComplexMethod") override fun blockingGetEditableStatus(eventUid: String): EventEditableStatus { val event = eventRepository.uid(eventUid).blockingGet() val program = programRepository.uid(event.program()).blockingGet() val programStage = programStageRepository.uid(event.programStage()).blockingGet() return when { event.status() == EventStatus.COMPLETED && programStage.blockEntryForm() == true -> EventEditableStatus.NonEditable(EventNonEditableReason.BLOCKED_BY_COMPLETION) eventDateUtils.isEventExpired( event = event, completeExpiryDays = program.completeEventsExpiryDays() ?: 0, programPeriodType = programStage.periodType() ?: program.expiryPeriodType(), expiryDays = program.expiryDays() ?: 0 ) -> EventEditableStatus.NonEditable(EventNonEditableReason.EXPIRED) !blockingHasDataWriteAccess(eventUid) -> EventEditableStatus.NonEditable(EventNonEditableReason.NO_DATA_WRITE_ACCESS) !blockingIsInOrgunitRange(event) -> EventEditableStatus.NonEditable(EventNonEditableReason.EVENT_DATE_IS_NOT_IN_ORGUNIT_RANGE) !blockingHasCategoryComboAccess(event) -> EventEditableStatus.NonEditable(EventNonEditableReason.NO_CATEGORY_COMBO_ACCESS) event.enrollment()?.let { !enrollmentService.blockingIsOpen(it) } ?: false -> EventEditableStatus.NonEditable(EventNonEditableReason.ENROLLMENT_IS_NOT_OPEN) event.organisationUnit()?.let { !organisationUnitService.blockingIsInCaptureScope(it) } ?: false -> EventEditableStatus.NonEditable(EventNonEditableReason.ORGUNIT_IS_NOT_IN_CAPTURE_SCOPE) else -> EventEditableStatus.Editable() } } override fun getEditableStatus(eventUid: String): Single<EventEditableStatus> { return Single.just(blockingGetEditableStatus(eventUid)) } override fun blockingCanAddEventToEnrollment(enrollmentUid: String, programStageUid: String): Boolean { val enrollment = enrollmentRepository.uid(enrollmentUid).blockingGet() val programStage = programStageRepository.uid(programStageUid).blockingGet() if (enrollment == null || programStage == null) { return false } val isActiveEnrollment = enrollment.status() == EnrollmentStatus.ACTIVE val acceptMoreEvents = if (programStage.repeatable() == true) true else getEventCount(enrollmentUid, programStageUid) == 0 return isActiveEnrollment && acceptMoreEvents } override fun canAddEventToEnrollment(enrollmentUid: String, programStageUid: String): Single<Boolean> { return Single.just(blockingCanAddEventToEnrollment(enrollmentUid, programStageUid)) } private fun getEventCount(enrollmentUid: String, programStageUid: String): Int { return eventRepository .byEnrollmentUid().eq(enrollmentUid) .byProgramStageUid().eq(programStageUid) .byDeleted().isFalse .blockingCount() } }
bsd-3-clause
568c24be0031f8db0baf3be5ecfc10c5
45.307229
113
0.731365
5.107641
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/TryStatementConversion.kt
5
3830
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.conversions import org.jetbrains.kotlin.j2k.ast.Nullability.NotNull import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.JKJavaDisjunctionType import org.jetbrains.kotlin.nj2k.types.updateNullability import org.jetbrains.kotlin.nj2k.useExpression import org.jetbrains.kotlin.utils.addToStdlib.safeAs class TryStatementConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKJavaTryStatement) return recurse(element) return if (element.isTryWithResources) recurse(convertTryStatementWithResources(element)) else recurse(convertNoResourcesTryStatement(element)) } private fun convertNoResourcesTryStatement(tryStatement: JKJavaTryStatement): JKStatement = JKExpressionStatement( JKKtTryExpression( tryStatement::tryBlock.detached(), tryStatement::finallyBlock.detached(), tryStatement.catchSections.flatMap(::convertCatchSection) ) ).withFormattingFrom(tryStatement) private fun convertTryStatementWithResources(tryStatement: JKJavaTryStatement): JKStatement { val body = resourceDeclarationsToUseExpression( tryStatement.resourceDeclarations, JKBlockStatement(tryStatement::tryBlock.detached()) ) return if (tryStatement.finallyBlock !is JKBodyStub || tryStatement.catchSections.isNotEmpty()) { JKExpressionStatement( JKKtTryExpression( JKBlockImpl(listOf(body)), tryStatement::finallyBlock.detached(), tryStatement.catchSections.flatMap(::convertCatchSection) ) ).withFormattingFrom(tryStatement) } else body } private fun resourceDeclarationsToUseExpression( resourceDeclarations: List<JKJavaResourceElement>, innerStatement: JKStatement ): JKStatement = resourceDeclarations .reversed() .fold(innerStatement) { inner, element -> val (receiver, name) = when (element) { is JKJavaResourceExpression -> element::expression.detached() to null is JKJavaResourceDeclaration -> element.declaration::initializer.detached() to element.declaration::name.detached() } JKExpressionStatement( useExpression( receiver = receiver, variableIdentifier = name, body = inner, symbolProvider = symbolProvider ) ) } private fun convertCatchSection(javaCatchSection: JKJavaTryCatchSection): List<JKKtTryCatchSection> { javaCatchSection.block.detach(javaCatchSection) val typeElement = javaCatchSection.parameter.type val parameterTypes = typeElement.type.safeAs<JKJavaDisjunctionType>()?.disjunctions ?: listOf(typeElement.type) return parameterTypes.map { type -> val parameter = JKParameter( JKTypeElement(type.updateNullability(NotNull), typeElement.annotationList.copyTreeAndDetach()), javaCatchSection.parameter.name.copyTreeAndDetach() ) JKKtTryCatchSection( parameter, javaCatchSection.block.copyTreeAndDetach() ).withFormattingFrom(javaCatchSection) } } }
apache-2.0
edd132884dc8430be3931b4485761ee7
44.070588
135
0.658486
5.856269
false
false
false
false
dahlstrom-g/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/dotnet/DotnetIcon.kt
13
1766
// 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.intellij.build.images.sync.dotnet import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardCopyOption internal class DotnetIcon(private val file: Path) { class Braces(val start: String, val end: String) companion object { val BRACES = listOf(Braces("[", "]"), Braces("(", ")")) } private val extension = "." + file.toFile().extension private val fullName = file.fileName.toString().removeSuffix(extension) val name: String val suffix: String override fun toString() = fullName override fun hashCode() = file.hashCode() override fun equals(other: Any?) = other is DotnetIcon && file.toString() == other.file.toString() init { var suffix = "" var name = fullName for (braces in BRACES) { val start = fullName.lastIndexOf(braces.start) val end = fullName.lastIndexOf(braces.end) if (start in 1 until end) { name = fullName.removeSuffix(fullName.substring(start..end)) suffix = fullName.removePrefix(name) .removePrefix(braces.start) .removeSuffix(braces.end) break } } this.name = name this.suffix = suffix } fun changeSuffix(suffix: String) : DotnetIcon { if (!Files.exists(file)) error("$file not exist") if (this.suffix == suffix) return this val name = "$name$suffix$extension" val target = file.parent?.resolve(name) ?: Paths.get(name) Files.move(file, target, StandardCopyOption.REPLACE_EXISTING) return DotnetIcon(target) } fun delete() { if (Files.exists(file)) Files.delete(file) } }
apache-2.0
7b728f76424c7aae8ebd09dd600348bb
32.961538
140
0.6812
3.915743
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionShortcutManager.kt
8
6434
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.intention.impl import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionBean import com.intellij.codeInsight.intention.IntentionManager import com.intellij.codeInsight.intention.IntentionShortcuts.WRAPPER_PREFIX import com.intellij.codeInsight.intention.impl.config.IntentionActionWrapper import com.intellij.codeInsight.intention.impl.config.IntentionManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.ShortcutSet import com.intellij.openapi.actionSystem.impl.ActionConfigurationCustomizer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.KeymapManagerListener import com.intellij.openapi.keymap.impl.ActionShortcutRestrictions import com.intellij.openapi.keymap.impl.ui.KeymapPanel import com.intellij.openapi.project.Project import com.intellij.openapi.wm.WindowManager /** Wraps intentions in [IntentionActionAsAction] to make it possible to assign shortcuts to them */ @Service(Service.Level.APP) class IntentionShortcutManager : Disposable { private var registeredKeymap: Keymap? = null /** Check if intention has a shortcut assigned */ fun hasShortcut(intention: IntentionAction): Boolean = getShortcutSet(intention)?.shortcuts?.isNotEmpty() == true /** Get possible shortcuts assigned to intention */ fun getShortcutSet(intention: IntentionAction): ShortcutSet? = ActionManager.getInstance().findIntentionWrapper(intention)?.shortcutSet /** Remove the first shortcuts assigned to intention and unregister the wrapping [IntentionActionAsAction] if no shortcuts remain */ fun removeFirstIntentionShortcut(intention: IntentionAction) { val shortcuts = getShortcutSet(intention)?.shortcuts ?: return shortcuts.firstOrNull()?.let { KeymapManager.getInstance()?.activeKeymap?.removeShortcut(intention.wrappedActionId, it) } if (shortcuts.size <= 1) { ActionManager.getInstance().unregister(intention) } } /** Show the keyboard shortcut panel to assign a shortcut */ fun promptForIntentionShortcut(intention: IntentionAction, project: Project) { ActionManager.getInstance().register(intention) val km = KeymapManager.getInstance() val activeKeymap = km?.activeKeymap ?: return // not available ApplicationManager.getApplication().invokeLater { val window = WindowManager.getInstance().suggestParentWindow(project) ?: return@invokeLater val actionId = intention.wrappedActionId val action = ActionShortcutRestrictions.getInstance().getForActionId(actionId) KeymapPanel.addKeyboardShortcut(actionId, action, activeKeymap, window) } } private fun ActionManager.register(intention: IntentionAction) { if (findIntentionWrapper(intention) == null) { registerAction(intention.wrappedActionId, IntentionActionAsAction(intention)) } } private fun ActionManager.unregister(intention: IntentionAction) { unregisterAction(intention.wrappedActionId) } private fun ActionManager.findIntentionWrapper(intention: IntentionAction): AnAction? = getAction(intention.wrappedActionId) internal fun findIntention(wrappedActionId: String): IntentionAction? = IntentionManager.getInstance().availableIntentions.firstOrNull { it.wrappedActionId == wrappedActionId } /** Register all intentions with shortcuts and keep them up to date */ private fun registerIntentionsInActiveKeymap(actionManager: ActionManager) { actionManager.registerIntentionsInKeymap(KeymapManager.getInstance().activeKeymap) val busConnection = ApplicationManager.getApplication().messageBus.connect(this) busConnection.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener { override fun activeKeymapChanged(keymap: Keymap?) { actionManager.unregisterIntentionsInKeymap() actionManager.registerIntentionsInKeymap(keymap) } }) IntentionManagerImpl.EP_INTENTION_ACTIONS.addExtensionPointListener(object : ExtensionPointListener<IntentionActionBean> { override fun extensionAdded(extension: IntentionActionBean, pluginDescriptor: PluginDescriptor) { actionManager.registerIntentionsInKeymap(registeredKeymap) } override fun extensionRemoved(extension: IntentionActionBean, pluginDescriptor: PluginDescriptor) { actionManager.unregisterIntentionsInExtension(extension) } }, this) } private fun ActionManager.registerIntentionsInKeymap(keymap: Keymap?) { keymap?.wrappedIntentionActions()?.forEach { register(it) } registeredKeymap = keymap } private fun ActionManager.unregisterIntentionsInKeymap() { registeredKeymap?.wrappedIntentionActions()?.forEach { unregister(it) } registeredKeymap = null } private fun ActionManager.unregisterIntentionsInExtension(extension: IntentionActionBean) { registeredKeymap?.wrappedIntentionActions()?.forEach { intention -> if (intention is IntentionActionWrapper && intention.implementationClassName == extension.className) { unregister(intention) } } } /** Collect all intentions with assigned shortcuts in a keymap */ private fun Keymap.wrappedIntentionActions(): Sequence<IntentionAction> { val intentionsById = IntentionManager.getInstance().intentionActions.associateBy { it.wrappedActionId } return actionIdList .asSequence() .filter { it.startsWith(WRAPPER_PREFIX) } .mapNotNull { intentionsById[it] } } override fun dispose() {} class InitListener : ActionConfigurationCustomizer { override fun customize(actionManager: ActionManager) { getInstance().registerIntentionsInActiveKeymap(actionManager) } } companion object { @JvmStatic fun getInstance(): IntentionShortcutManager = service() } }
apache-2.0
837b2f01938a703d4796748e01a3b6fc
41.893333
158
0.787224
5.252245
false
false
false
false
millross/pac4j-async
vertx-pac4j-async-demo/src/test/kotlin/org/pac4j/async/vertx/client/TestIndirectClient.kt
1
1540
package org.pac4j.async.vertx.client import org.pac4j.async.core.context.AsyncWebContext import org.pac4j.async.oauth.client.AsyncOAuth20Client import org.pac4j.async.oauth.config.OAuth20Configuration import org.pac4j.async.vertx.AUTH_BASE_URL import org.pac4j.async.vertx.TEST_CLIENT_ID import org.pac4j.async.vertx.TEST_CLIENT_SECRET import org.pac4j.async.vertx.profile.indirect.TestOAuth20Profile import org.pac4j.async.vertx.profile.indirect.TestOAuth20ProfileDefinition import org.pac4j.async.vertx.profile.indirect.TestOAuthCredentialsExtractor import org.pac4j.async.vertx.profile.indirect.TestUrlProfileCalculator /** * */ class TestIndirectClient: AsyncOAuth20Client<TestOAuth20Profile, OAuth20Configuration<TestOAuth20Profile, TestOAuth20ProfileDefinition>, TestUrlProfileCalculator>() { var baseAuthorizationUrl = AUTH_BASE_URL init { setConfiguration(OAuth20Configuration()) configuration.key = TEST_CLIENT_ID configuration.secret = TEST_CLIENT_SECRET profileUrlCalculator = TestUrlProfileCalculator() } override fun notifySessionRenewal(oldSessionId: String?, context: AsyncWebContext) { // Intentional noop } override fun clientInit(context: AsyncWebContext?) { configuration.api = TestOAuth20Api(baseAuthorizationUrl) configuration.setProfileDefinition(TestOAuth20ProfileDefinition()) configuration.isWithState = true defaultCredentialsExtractor(TestOAuthCredentialsExtractor()) super.clientInit(context) } }
apache-2.0
17a28792a2ff24080dacfd99c83571bd
38.512821
166
0.78961
4
false
true
false
false
flesire/ontrack
ontrack-job/src/main/java/net/nemerosa/ontrack/job/orchestrator/JobOrchestrator.kt
1
1902
package net.nemerosa.ontrack.job.orchestrator import net.nemerosa.ontrack.job.* import java.util.* import kotlin.streams.toList class JobOrchestrator( private val jobScheduler: JobScheduler, private val name: String, private val jobOrchestratorSuppliers: Collection<JobOrchestratorSupplier> ) : Job { private val cache = HashSet<JobKey>() override fun getKey(): JobKey { return JobCategory.CORE.getType("orchestrator").withName("Orchestrator").getKey(name) } override fun getTask(): JobRun { return JobRun { this.orchestrate(it) } } @Synchronized fun orchestrate(runListener: JobRunListener) { // Complete list of registrations val registrations = jobOrchestratorSuppliers .flatMap { it.collectJobRegistrations().toList() } // List of registration keys val keys = registrations .map { registration -> registration.job.key } // Jobs to unschedule val toRemove = HashSet(cache) toRemove.removeAll(keys) toRemove.forEach { jobScheduler.unschedule(it) } // Jobs to add / update val toRegister = HashSet(keys) toRegister.removeAll(toRemove) registrations .filter { jobRegistration -> toRegister.contains(jobRegistration.job.key) } .forEach { jobRegistration -> schedule(jobRegistration, runListener) } // Resets the cache cache.clear() cache.addAll(keys) } private fun schedule(jobRegistration: JobRegistration, runListener: JobRunListener) { runListener.message("Scheduling: %s", jobRegistration.job.key) jobScheduler.schedule(jobRegistration.job, jobRegistration.schedule) } override fun getDescription(): String { return name } override fun isDisabled(): Boolean { return false } }
mit
647494f695d2e870d6658acc7acd832e
31.237288
93
0.658254
4.743142
false
false
false
false
ralfstuckert/pdftools
src/main/kotlin/rst/pdftools/compare/Color.kt
1
603
package rst.pdftools.compare import java.awt.Color val MAX_VECTOR_LENGTH:Double = Math.sqrt(3.0* 255.0*255.0) fun Color.normalizedDistanceTo(other:Color): Double { val distanceR = red- other.red val distanceG = green - other.green val distanceB = blue - other.blue val distance = Math.sqrt((distanceR * distanceR + distanceG * distanceG + distanceB * distanceB).toDouble()) return distance / MAX_VECTOR_LENGTH } fun Int.asColor(): Color = Color(this) fun Int.normalizedRgbDistanceTo(other:Int):Double = Color(this).normalizedDistanceTo(Color(other))
mit
8f9b3182f328c9bd66d073b529e1e0a4
25.217391
98
0.701493
3.589286
false
false
false
false
vkurdin/idea-php-lambda-folding
src/ru/vkurdin/idea/php/lambdafolding/PhpOptionTypeProvider.kt
1
4545
package ru.vkurdin.idea.php.lambdafolding import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.jetbrains.php.PhpIndex import com.jetbrains.php.lang.psi.elements.* import com.jetbrains.php.lang.psi.elements.Function import com.jetbrains.php.lang.psi.resolve.types.PhpType import com.jetbrains.php.lang.psi.resolve.types.PhpTypeProvider2 class PhpOptionTypeProvider : PhpTypeProvider2 { companion object { private val OPTION_CLASSES = hashSetOf( "\\PhpOption\\Option", "\\PhpOption\\Some", "\\PhpOption\\None" ) private val TYPE_IMMUTABLE_FUNCTIONS = hashSetOf( "filter", "filterNot", "forAll" ) private val INNER_TYPE_SEPARATOR = "#✈#" } override fun getKey() = '✈' override fun getBySignature(signature: String, project: Project): MutableCollection<out PhpNamedElement>? = if (signature.startsWith("\\PhpOption\\Option<")) { PhpIndex.getInstance(project).getClassesByFQN("\\PhpOption\\Option") } else { PhpIndex.getInstance(project).getClassesByFQN(signature) } override fun getType(element: PsiElement?) : String? = when (element) { is MethodReference -> element.inferOptionalCallType() is Parameter -> element.inferOptionalCallType() else -> null } private fun Parameter.inferOptionalCallType() = // Option<T> -> Function(function ($arg) { return $arg; }) letIf { firstChild !is ClassReference } ?. parent ?. let { it as? ParameterList } ?. letIf { it.parameters.isNotEmpty() && it.parameters.first() === this } ?. parent ?. letIf { it is Function && it.isClosure } ?. parent ?. parent ?. parent ?. let { it as? MethodReference } ?. classReference ?. type ?. getOptionalTypesSequence() ?. letIf { it.any() } ?. first() ?. let { it.substring(18, it.length - 1).replace(INNER_TYPE_SEPARATOR, "|") } private fun MethodReference.inferOptionalCallType() = classReference ?. let { when { // Option::fromValue() it is ClassReference && it.fqn in OPTION_CLASSES && name == "fromValue" -> inferStaticCallType() // Option<T> -> filter, -> filterNot, -> forAll name in TYPE_IMMUTABLE_FUNCTIONS -> it.type.getOptionalTypes() // Option<T> -> map name == "map" && it.type.hasOptionalTypes() -> inferMapCallType() // Option<T> -> flatMap name == "flatMap" && it.type.hasOptionalTypes() -> inferFlatmapCallType() else -> null } } private fun MethodReference.inferFlatmapCallType() = getFirstPassedClosure() ?. getLocalType(true) ?. getOptionalTypes() private fun MethodReference.inferMapCallType() = getFirstPassedClosure() ?. getLocalType(true) ?. types ?. asSequence() ?. filterNot { it.startsWith("#✈\\PhpOption\\Option") } ?. map { it.removePrefix("#✈") } ?. joinToString(INNER_TYPE_SEPARATOR) ?. letIf { it.isNotBlank() } ?. let { "\\PhpOption\\Option<$it>" } private fun MethodReference.inferStaticCallType() = parameters . letIf { it.isNotEmpty() && it.first() is PhpTypedElement } ?. first() ?. let { "\\PhpOption\\Option<${(it as PhpTypedElement).type.toString().replace("|", INNER_TYPE_SEPARATOR)}>" } private fun MethodReference.getFirstPassedClosure() : Function? = parameters . letIf { it.isNotEmpty() } ?. first() . let { it as? PhpExpression } ?. firstChild . let { it as? Function } ?. letIf { it.isClosure } private fun PhpType.getOptionalTypes() : String? = getOptionalTypesSequence() . letIf { it.any() } ?. joinToString("|") private fun PhpType.getOptionalTypesSequence() : Sequence<String> = types.asSequence() . filter { it.startsWith("#✈\\PhpOption\\Option<") } . map { it.substring(2) } private fun PhpType.hasOptionalTypes() : Boolean = getOptionalTypesSequence().any() }
mit
4ee1290e836435be1be80712727ebffb
33.105263
119
0.563396
4.64176
false
false
false
false
RuneSuite/client
plugins/src/main/java/org/runestar/client/plugins/windowtransparency/WindowTransparency.kt
1
1673
package org.runestar.client.plugins.windowtransparency import org.runestar.client.api.Application import org.runestar.client.api.plugins.AbstractPlugin import org.runestar.client.api.plugins.PluginSettings import java.awt.Component import java.awt.Window import javax.swing.SwingUtilities /** * Tested on: * * Windows 10 - Java 8, 9, 10, 11 * */ class WindowTransparency : AbstractPlugin<WindowTransparency.Settings>() { /** * Use reflection to bypass [java.awt.Frame.setOpacity] checks for [java.awt.Frame.isUndecorated] */ private companion object { // public peer method removed in Java 9 val peerField by lazy { Component::class.java.getDeclaredField("peer").apply { isAccessible = true } } val opacityField by lazy { Window::class.java.getDeclaredField("opacity").apply { isAccessible = true } } // public in Java 8 but not exported in 9+ val setOpacityMethod by lazy { Class.forName("java.awt.peer.WindowPeer").getDeclaredMethod("setOpacity", java.lang.Float.TYPE) } } override val defaultSettings = Settings() override val name = "Window Transparency" override fun start() { setOpacity(settings.opacity) } override fun stop() { setOpacity(1f) } private fun setOpacity(opacity: Float) { SwingUtilities.invokeLater { val frame = Application.frame opacityField.setFloat(frame, opacity) setOpacityMethod.invoke(peerField.get(frame), opacity) } } class Settings( val opacity: Float = 0.3f ) : PluginSettings() }
mit
20f6f1d6a2b9bf33863ca611896a5768
26
107
0.656306
4.391076
false
false
false
false
dyoung81/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/Settings.kt
1
7284
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper import POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId import com.pokegoapi.api.inventory.Pokeball import java.io.File import java.util.* class Settings(val properties: Properties) { val pokeballItems = mapOf(Pair(ItemId.ITEM_POKE_BALL, Pokeball.POKEBALL), Pair(ItemId.ITEM_ULTRA_BALL, Pokeball.ULTRABALL), Pair(ItemId.ITEM_GREAT_BALL, Pokeball.GREATBALL), Pair(ItemId.ITEM_MASTER_BALL, Pokeball.MASTERBALL)) val startingLatitude = getPropertyOrDie("Starting Latitude", "latitude", String::toDouble) val startingLongitude = getPropertyOrDie("Starting Longitude", "longitude", String::toDouble) val username = properties.getProperty("username") val password = if (properties.containsKey("password")) properties.getProperty("password") else String(Base64.getDecoder().decode(properties.getProperty("base64_password", ""))) val token = properties.getProperty("token", "") val speed = getPropertyIfSet("Speed", "speed", 2.778, String::toDouble) val shouldDropItems = getPropertyIfSet("Item Drop", "drop_items", false, String::toBoolean) val uselessItems = if (shouldDropItems) { mapOf( Pair(ItemId.ITEM_REVIVE, getPropertyIfSet("Max number of items to keep from type ITEM_REVIVE", "item_revive", 20, String::toInt)), Pair(ItemId.ITEM_MAX_REVIVE, getPropertyIfSet("Max number of items to keep from type ITEM_MAX_REVIVE", "item_max_revive", 10, String::toInt)), Pair(ItemId.ITEM_POTION, getPropertyIfSet("Max number of items to keep from type ITEM_POTION", "item_potion", 0, String::toInt)), Pair(ItemId.ITEM_SUPER_POTION, getPropertyIfSet("Max number of items to keep from type ITEM_SUPER_POTION", "item_super_potion", 30, String::toInt)), Pair(ItemId.ITEM_HYPER_POTION, getPropertyIfSet("Max number of items to keep from type ITEM_HYPER_POTION", "item_hyper_potion", 50, String::toInt)), Pair(ItemId.ITEM_MAX_POTION, getPropertyIfSet("Max number of items to keep from type ITEM_MAX_POTION", "item_max_potion", 50, String::toInt)), Pair(ItemId.ITEM_POKE_BALL, getPropertyIfSet("Max number of items to keep from type ITEM_POKE_BALL", "item_poke_ball", 50, String::toInt)), Pair(ItemId.ITEM_GREAT_BALL, getPropertyIfSet("Max number of items to keep from type ITEM_GREAT_BALL", "item_great_ball", 50, String::toInt)), Pair(ItemId.ITEM_ULTRA_BALL, getPropertyIfSet("Max number of items to keep from type ITEM_ULTRA_BALL", "item_ultra_ball", 50, String::toInt)), Pair(ItemId.ITEM_MASTER_BALL, getPropertyIfSet("Max number of items to keep from type ITEM_MASTER_BALL", "item_master_ball", 10, String::toInt)), Pair(ItemId.ITEM_RAZZ_BERRY, getPropertyIfSet("Max number of items to keep from type ITEM_RAZZ_BERRY", "item_razz_berry", 50, String::toInt)) ) } else { mapOf( Pair(ItemId.ITEM_REVIVE, 20), Pair(ItemId.ITEM_MAX_REVIVE, 10), Pair(ItemId.ITEM_POTION, 0), Pair(ItemId.ITEM_SUPER_POTION, 30), Pair(ItemId.ITEM_HYPER_POTION, 50), Pair(ItemId.ITEM_MAX_POTION, 50), Pair(ItemId.ITEM_POKE_BALL, 50), Pair(ItemId.ITEM_GREAT_BALL, 50), Pair(ItemId.ITEM_ULTRA_BALL, 50), Pair(ItemId.ITEM_MASTER_BALL, 10), Pair(ItemId.ITEM_RAZZ_BERRY, 50) ) } val desiredCatchProbability = getPropertyIfSet("Desired chance to catch a Pokemon with 1 ball", "desired_catch_probability", 0.8, String::toDouble) val shouldAutoTransfer = getPropertyIfSet("Autotransfer", "autotransfer", false, String::toBoolean) val keepPokemonAmount = getPropertyIfSet("minimum keep pokemon amount", "keep_pokemon_amount", 1, String::toInt) val shouldDisplayKeepalive = getPropertyIfSet("Display Keepalive Coordinates", "display_keepalive", true, String::toBoolean) val shouldDisplayPokestopName = getPropertyIfSet("Display Pokestop Name", "display_pokestop_name", false, String::toBoolean) val shouldDisplayPokestopSpinRewards = getPropertyIfSet("Display Pokestop Rewards", "display_pokestop_rewards", true, String::toBoolean) val shouldDisplayPokemonCatchRewards = getPropertyIfSet("Display Pokemon Catch Rewards", "display_pokemon_catch_rewards", true, String::toBoolean) val walkOnly = getPropertyIfSet("Only walk to hatch eggs", "walk_only", false, String::toBoolean) val transferCPThreshold = getPropertyIfSet("Minimum CP to keep a pokemon", "transfer_cp_threshold", 400, String::toInt) val transferIVThreshold = getPropertyIfSet("Minimum IV percentage to keep a pokemon", "transfer_iv_threshold", 80, String::toInt) val ignoredPokemon = if (shouldAutoTransfer) { getPropertyIfSet("Never transfer these Pokemon", "ignored_pokemon", "EEVEE,MEWTWO,CHARMANDER", String::toString).split(",") } else { listOf() } val obligatoryTransfer = if (shouldAutoTransfer) { getPropertyIfSet("list of pokemon you always want to trancsfer regardless of CP", "obligatory_transfer", "DODUO,RATTATA,CATERPIE,PIDGEY", String::toString).split(",") } else { listOf() } val candyRequiredByPokemon = getCandyByPokemon() val autoEvolve = getPropertyIfSet("list of pokemon you want to evolve when able to", "auto_evolve", "CATERPIE,PIDGEY,WEEDLE", String::toString).split(",") //This method only exists because I wasn't sure if this data was stored somewhere else. If it is then this can be removed. private fun getCandyByPokemon(): Map<Int, Int> { val lines = File("pokemon-candy.csv").readLines() return lines.map { val split = it.split(",") Pair(split[0].toInt(), split[1].toInt()) }.toMap() } private fun <T> getPropertyOrDie(description: String, property: String, conversion: (String) -> T): T { val settingString = "$description setting (\"$property\")" if (!properties.containsKey(property)) { println("$settingString not specified in config.properties!") System.exit(1) } return conversion(properties.getProperty(property)) } private fun <T> getPropertyIfSet(description: String, property: String, default: T, conversion: (String) -> T): T { val settingString = "$description setting (\"$property\")" val defaulting = "defaulting to \"$default\"" if (!properties.containsKey(property)) { println("$settingString not specified, $defaulting.") return default } try { return conversion(properties.getProperty(property)) } catch (e: Exception) { println("$settingString is invalid, defaulting to $default: ${e.message}") return default } } }
gpl-3.0
47d1a26c74bd5d7383b72fd08a1becd9
55.465116
180
0.678062
4.076105
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/panel/ImageSample.kt
2
1952
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.ui.panel import io.kvision.form.upload.uploadInput import io.kvision.html.button import io.kvision.panel.VPanel import io.kvision.panel.vPanel import org.w3c.files.FileReader object ImageSample : VPanel() { init { vPanel(spacing = 10) { val button = button("Button") val upload = uploadInput("/") { showUpload = false showCancel = false } button("Add image to button").onClick { upload.value?.firstOrNull()?.let { upload.getNativeFile(it) }?.slice()?.let { blob -> // // Important part is here // val reader = FileReader() reader.addEventListener("load", { val dataUrl = it.target.asDynamic().result console.log("[IS.init]") console.log(dataUrl) button.image = dataUrl }) reader.readAsDataURL(blob) } } } } }
apache-2.0
daecf3febfec04ed8570cc3948ddba8b
34.490909
101
0.594775
4.658711
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Texture.kt
1
2531
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.PUTFIELD import org.objectweb.asm.Type.* import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 @DependsOn(Node::class) class Texture : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Node>() } .and { it.instanceFields.count { it.type == IntArray::class.type } == 5 } class files : OrderMapper.InConstructor.Field(Texture::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class pixels : OrderMapper.InConstructor.Field(Texture::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class isLoaded : OrderMapper.InConstructor.Field(Texture::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == BOOLEAN_TYPE } } class reset : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.instructions.count { it.isField } == 1 } } class int1 : OrderMapper.InConstructor.Field(Texture::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class animationDirection : OrderMapper.InConstructor.Field(Texture::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class animationSpeed : OrderMapper.InConstructor.Field(Texture::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @MethodParameters("n") class animate : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(INT_TYPE) } } }
mit
e07af4268d632bfd9287a76a768e7285
44.214286
124
0.713947
4.204319
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/kotlin.code-insight.k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/structureView/KotlinFirStructureElementPresentation.kt
1
5737
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.k2.codeinsight.structureView import com.intellij.navigation.ColoredItemPresentation import com.intellij.navigation.LocationPresentation import com.intellij.openapi.editor.colors.CodeInsightColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.util.Iconable import com.intellij.psi.NavigatablePsiElement import com.intellij.psi.PsiNamedElement import com.intellij.util.PsiIconUtil import com.intellij.util.ui.StartupUiUtil import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.renderer.declarations.impl.KtDeclarationRendererForSource import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtDeclarationSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtSymbolOrigin import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.idea.codeInsight.KotlinCodeInsightBundle import org.jetbrains.kotlin.idea.base.codeInsight.KotlinIconProvider.getIconFor import org.jetbrains.kotlin.psi.* import javax.swing.Icon private const val rightArrow = '\u2192' internal class KotlinFirStructureElementPresentation( private val isInherited: Boolean, navigatablePsiElement: NavigatablePsiElement, ktElement : KtElement, pointer: KtSymbolPointer<*>? ) : ColoredItemPresentation, LocationPresentation { private val attributesKey = getElementAttributesKey(isInherited, navigatablePsiElement) private val elementText = getElementText(navigatablePsiElement, ktElement, pointer) private val locationString = getElementLocationString(isInherited, ktElement, pointer) private val icon = getElementIcon(navigatablePsiElement, ktElement, pointer) override fun getTextAttributesKey() = attributesKey override fun getPresentableText() = elementText override fun getLocationString() = locationString override fun getIcon(unused: Boolean) = icon override fun getLocationPrefix(): String { return if (isInherited) " " else LocationPresentation.DEFAULT_LOCATION_PREFIX } override fun getLocationSuffix(): String { return if (isInherited) "" else LocationPresentation.DEFAULT_LOCATION_SUFFIX } private fun getElementAttributesKey(isInherited: Boolean, navigatablePsiElement: NavigatablePsiElement): TextAttributesKey? { if (isInherited) { return CodeInsightColors.NOT_USED_ELEMENT_ATTRIBUTES } if (navigatablePsiElement is KtModifierListOwner && KtPsiUtil.isDeprecated(navigatablePsiElement)) { return CodeInsightColors.DEPRECATED_ATTRIBUTES } return null } private fun getElementIcon(navigatablePsiElement: NavigatablePsiElement, ktElement: KtElement, pointer: KtSymbolPointer<*>?): Icon? { if (navigatablePsiElement !is KtElement) { return navigatablePsiElement.getIcon(Iconable.ICON_FLAG_VISIBILITY) } if (pointer != null) { analyze(ktElement) { pointer.restoreSymbol()?.let { return getIconFor(it) } } } if (!navigatablePsiElement.isValid) { return null } return PsiIconUtil.getProvidersIcon(navigatablePsiElement, Iconable.ICON_FLAG_VISIBILITY) } private fun getElementText(navigatablePsiElement: NavigatablePsiElement, ktElement : KtElement, pointer: KtSymbolPointer<*>?): String? { if (navigatablePsiElement is KtObjectDeclaration && navigatablePsiElement.isObjectLiteral()) { return KotlinCodeInsightBundle.message("object.0", (navigatablePsiElement.getSuperTypeList()?.text?.let { " : $it" } ?: "")) } if (pointer != null) { analyze(ktElement) { val symbol = pointer.restoreSymbol() if (symbol is KtDeclarationSymbol) { return symbol.render(KtDeclarationRendererForSource.WITH_SHORT_NAMES) } } } val text = navigatablePsiElement.name if (!text.isNullOrEmpty()) { return text } if (navigatablePsiElement is KtAnonymousInitializer) { return KotlinCodeInsightBundle.message("class.initializer") } return null } private fun getElementLocationString(isInherited: Boolean, ktElement: KtElement, pointer: KtSymbolPointer<*>?): String? { if (!isInherited || pointer == null) return null analyze(ktElement) { val symbol = pointer.restoreSymbol() if (symbol is KtCallableSymbol && symbol.origin == KtSymbolOrigin.SUBSTITUTION_OVERRIDE) { val containerPsi = symbol.psi?.parent if (containerPsi is PsiNamedElement) { containerPsi.name?.let { return withRightArrow(it) } } } val containingSymbol = symbol?.getContainingSymbol() if (ktElement is KtDeclaration && containingSymbol == ktElement.getSymbol()) { return null } if (containingSymbol is KtNamedSymbol) { return withRightArrow(containingSymbol.name.asString()) } } return null } private fun withRightArrow(str: String): String { return if (StartupUiUtil.getLabelFont().canDisplay(rightArrow)) rightArrow + str else "->$str" } }
apache-2.0
91fbc241897faafccc3604b8cd30bc27
39.408451
140
0.696357
5.366698
false
false
false
false
allotria/intellij-community
platform/core-api/src/com/intellij/codeWithMe/ClientId.kt
1
8772
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeWithMe import com.intellij.codeWithMe.ClientId.Companion.withClientId import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.Disposer import com.intellij.util.Processor import java.util.concurrent.Callable import java.util.function.BiConsumer import java.util.function.Function /** * ClientId is a global context class that is used to distinguish the originator of an action in multi-client systems * In such systems, each client has their own ClientId. Current process also can have its own ClientId, with this class providing methods to distinguish local actions from remote ones. * * It's up to the application to preserve and propagate the current value across background threads and asynchronous activities. */ data class ClientId(val value: String) { enum class AbsenceBehavior { /** * Return localId if ClientId is not set */ RETURN_LOCAL, /** * Throw an exception if ClientId is not set */ THROW } companion object { /** * Default client id for local application */ val defaultLocalId = ClientId("Host") /** * Specifies behavior for ClientId.current */ var AbsenceBehaviorValue = AbsenceBehavior.RETURN_LOCAL /** * Controls propagation behavior. When false, decorateRunnable does nothing. */ var propagateAcrossThreads = false /** * The ID considered local to this process. All other IDs (except for null) are considered remote */ @JvmStatic var localId = defaultLocalId private set /** * True if and only if the current ClientID is local to this process */ @JvmStatic val isCurrentlyUnderLocalId: Boolean get() = currentOrNull.isLocal /** * Gets the current ClientId. Subject to AbsenceBehaviorValue */ @JvmStatic val current: ClientId get() = when (AbsenceBehaviorValue) { AbsenceBehavior.RETURN_LOCAL -> currentOrNull ?: localId AbsenceBehavior.THROW -> currentOrNull ?: throw NullPointerException("ClientId not set") } /** * Gets the current ClientId. Can be null if none was set. */ @JvmStatic val currentOrNull: ClientId? get() = ClientIdService.tryGetInstance()?.clientIdValue?.let(::ClientId) /** * Overrides the ID that is considered to be local to this process. Can be only invoked once. */ @JvmStatic fun overrideLocalId(newId: ClientId) { require(localId == defaultLocalId) localId = newId } /** * Returns true if and only if the given ID is considered to be local to this process */ @JvmStatic fun isLocalId(clientId: ClientId?): Boolean { return clientId.isLocal } /** * Is true if and only if the given ID is considered to be local to this process */ val ClientId?.isLocal: Boolean get() = this == null || this == localId /** * Returns true if the given ID is local or a client is still in the session. * Consider subscribing to a proper lifetime instead of this check. */ @JvmStatic fun isValidId(clientId: ClientId?): Boolean { return clientId.isValid } /** * Is true if the given ID is local or a client is still in the session. * Consider subscribing to a proper lifetime instead of this check */ @JvmStatic val ClientId?.isValid: Boolean get() = ClientIdService.tryGetInstance()?.isValid(this) ?: true /** * Returns a disposable object associated with the given ID. * Consider using a lifetime that is usually passed along with the ID */ @JvmStatic fun ClientId?.toDisposable(): Disposable { return ClientIdService.tryGetInstance()?.toDisposable(this) ?: Disposer.newDisposable() } /** * Invokes a runnable under the given ClientId */ @JvmStatic fun withClientId(clientId: ClientId?, action: Runnable) = withClientId(clientId) { action.run() } /** * Computes a value under given ClientId */ @JvmStatic fun <T> withClientId(clientId: ClientId?, action: Callable<T>): T = withClientId(clientId) { action.call() } /** * Computes a value under given ClientId */ @JvmStatic inline fun <T> withClientId(clientId: ClientId?, action: () -> T): T { val clientIdService = ClientIdService.tryGetInstance() ?: return action() if (!clientIdService.isValid(clientId)) { Logger.getInstance(ClientId::class.java).warn("Invalid clientId: $clientId", Throwable()) } val foreignMainThreadActivity = clientIdService.checkLongActivity && ApplicationManager.getApplication().isDispatchThread && !clientId.isLocal val old = clientIdService.clientIdValue try { clientIdService.clientIdValue = clientId?.value if (foreignMainThreadActivity) { val beforeActionTime = System.currentTimeMillis() val result = action() val delta = System.currentTimeMillis() - beforeActionTime if (delta > 1000) { Logger.getInstance(ClientId::class.java).warn("LONG MAIN THREAD ACTIVITY by ${clientId?.value}. Stack trace:\n${getStackTrace()}") } return result } else return action() } finally { clientIdService.clientIdValue = old } } @JvmStatic fun decorateRunnable(runnable: Runnable) : Runnable { if (!propagateAcrossThreads) { return runnable } val currentId = currentOrNull return Runnable { withClientId(currentId) { runnable.run() } } } @JvmStatic fun <T> decorateCallable(callable: Callable<T>) : Callable<T> { if (!propagateAcrossThreads) return callable val currentId = currentOrNull return Callable { withClientId(currentId, callable) } } @JvmStatic fun <T, R> decorateFunction(function: Function<T, R>) : Function<T, R> { if (!propagateAcrossThreads) return function val currentId = currentOrNull return Function { withClientId(currentId) { function.apply(it) } } } @JvmStatic fun <T, U> decorateBiConsumer(biConsumer: BiConsumer<T, U>) : BiConsumer<T, U> { if (!propagateAcrossThreads) return biConsumer val currentId = currentOrNull return BiConsumer { t, u -> withClientId(currentId) { biConsumer.accept(t, u) } } } @JvmStatic fun <T> decorateProcessor(processor: Processor<T>) : Processor<T> { if (!propagateAcrossThreads) return processor val currentId = currentOrNull return Processor { withClientId(currentId) { processor.process(it) } } } /** Sets current ClientId. * Please, TRY NOT TO USE THIS METHOD except cases you sure you know what it does and there is no another ways. * In most cases it's convenient and preferable to use [withClientId]. */ @JvmStatic fun trySetCurrentClientId(clientId: ClientId?) { val clientIdService = ClientIdService.tryGetInstance() if (clientIdService != null) { clientIdService.clientIdValue = clientId?.value } } } } fun isForeignClientOnServer(): Boolean { return !ClientId.isCurrentlyUnderLocalId && ClientId.localId == ClientId.defaultLocalId } fun getStackTrace(): String { val builder = StringBuilder() val trace = Thread.currentThread().stackTrace for (element in trace) { with(builder) { append("\tat $element\n") } } return builder.toString() }
apache-2.0
19357145f62a040ff9c0ea9af19b5912
35.252066
184
0.600205
5.394834
false
false
false
false
pnemonic78/Fractals
fractals-android/app/src/main/kotlin/com/github/fractals/MainActivity.kt
1
6926
/* * Copyright 2016, Moshe Waisberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fractals import android.Manifest import android.annotation.TargetApi import android.app.Activity import android.content.Context import android.content.pm.PackageManager.PERMISSION_GRANTED import android.os.Build import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.schedulers.Schedulers /** * Main activity. * * @author Moshe Waisberg */ class MainActivity : Activity(), FractalsListener { private lateinit var mainView: FractalsView private val disposables = CompositeDisposable() private var menuStop: MenuItem? = null private var menuSave: MenuItem? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mainView = findViewById(R.id.fractals) mainView.setFractalsListener(this) } override fun onDestroy() { super.onDestroy() mainView.stop() disposables.clear() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) val rendering = !mainView.isIdle() menuStop = menu.findItem(R.id.menu_stop) menuStop!!.isVisible = rendering menuSave = menu.findItem(R.id.menu_save_file) menuSave!!.isVisible = rendering return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_stop -> { stop() return true } R.id.menu_fullscreen -> { if (actionBar?.isShowing == true) { showFullscreen() } else { showNormalScreen() } return true } R.id.menu_save_file -> { saveToFile() return true } } return super.onOptionsItemSelected(item) } /** * Save the bitmap to a file. */ private fun saveToFile() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val activity: Activity = this@MainActivity if (activity.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) { activity.requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_SAVE) return } } // Busy saving? val menuItem = menuSave ?: return if (!menuItem.isVisible) { return } menuItem.isVisible = false val context: Context = this val bitmap = mainView.bitmap SaveFileTask(context, bitmap).apply { subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(SaveFileObserver(context, bitmap)) disposables.add(this) } } override fun onRenderFieldPan(view: Fractals, dx: Int, dy: Int) { } override fun onRenderFieldZoom(view: Fractals, scale: Double) { } override fun onRenderFieldStarted(view: Fractals) { if (view == mainView) { runOnUiThread { menuStop?.isVisible = true menuSave?.isVisible = true } } } override fun onRenderFieldFinished(view: Fractals) { if (view == mainView) { runOnUiThread { menuStop?.isVisible = false menuSave?.isVisible = true Toast.makeText(this, R.string.finished, Toast.LENGTH_SHORT).show() } } } override fun onRenderFieldCancelled(view: Fractals) { if (view == mainView) { runOnUiThread { menuStop?.isVisible = false } } } @TargetApi(Build.VERSION_CODES.M) override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_SAVE) { if (permissions.isNotEmpty() && (permissions[0] == Manifest.permission.WRITE_EXTERNAL_STORAGE)) { if (grantResults.isNotEmpty() && (grantResults[0] == PERMISSION_GRANTED)) { saveToFile() return } } } } /** * Maximise the image in fullscreen mode. * @return `true` if screen is now fullscreen. */ private fun showFullscreen(): Boolean { val actionBar = actionBar if ((actionBar != null) && actionBar.isShowing) { // Hide the status bar. window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) // Hide the action bar. actionBar.hide() return true } return false } /** * Restore the image to non-fullscreen mode. * @return `true` if screen was fullscreen. */ private fun showNormalScreen(): Boolean { val actionBar = actionBar if (actionBar != null && !actionBar.isShowing) { // Show the status bar. window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_LAYOUT_STABLE) // Show the action bar. actionBar.show() return true } return false } override fun onBackPressed() { if (showNormalScreen()) { return } super.onBackPressed() } private fun stop() { menuStop?.isVisible = false mainView.stop() mainView.clear() } private fun start() { mainView.start() } override fun onResume() { super.onResume() start() } companion object { private const val REQUEST_SAVE = 0x5473 // "SAVE" } }
apache-2.0
34783f2d54ae3d0408d2deb67fd363e4
28.47234
122
0.596448
4.737346
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/test/flow/operators/TakeTest.kt
1
3410
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlin.test.* class TakeTest : TestBase() { @Test fun testTake() = runTest { val flow = flow { emit(1) emit(2) } assertEquals(3, flow.take(2).sum()) assertEquals(3, flow.take(Int.MAX_VALUE).sum()) assertEquals(1, flow.take(1).single()) assertEquals(2, flow.drop(1).take(1).single()) } @Test fun testIllegalArgument() { assertFailsWith<IllegalArgumentException> { flowOf(1).take(0) } assertFailsWith<IllegalArgumentException> { flowOf(1).take(-1) } } @Test fun testTakeSuspending() = runTest { val flow = flow { emit(1) yield() emit(2) yield() } assertEquals(3, flow.take(2).sum()) assertEquals(3, flow.take(Int.MAX_VALUE).sum()) assertEquals(1, flow.take(1).single()) assertEquals(2, flow.drop(1).take(1).single()) } @Test fun testEmptyFlow() = runTest { val sum = emptyFlow<Int>().take(10).sum() assertEquals(0, sum) } @Test fun testNonPositiveValues() { val flow = flowOf(1) assertFailsWith<IllegalArgumentException> { flow.take(-1) } assertFailsWith<IllegalArgumentException> { flow.take(0) } } @Test fun testCancelUpstream() = runTest { var cancelled = false val flow = flow { coroutineScope { launch(start = CoroutineStart.ATOMIC) { hang { cancelled = true } } emit(1) } } assertEquals(1, flow.take(1).single()) assertTrue(cancelled) } @Test fun testErrorCancelsUpstream() = runTest { var cancelled = false val flow = flow { coroutineScope { launch(start = CoroutineStart.ATOMIC) { hang { cancelled = true } } emit(1) } }.take(2) .map<Int, Int> { throw TestException() }.catch { emit(42) } assertEquals(42, flow.single()) assertTrue(cancelled) } @Test fun takeWithRetries() = runTest { val flow = flow { expect(1) emit(1) expect(2) emit(2) while (true) { emit(42) expectUnreached() } }.retry(2) { expectUnreached() true }.take(2) val sum = flow.sum() assertEquals(3, sum) finish(3) } @Test fun testNonIdempotentRetry() = runTest { var count = 0 flow { while (true) emit(1) } .retry { count++ % 2 != 0 } .take(1) .collect { expect(1) } finish(2) } @Test fun testNestedTake() = runTest { val inner = flow { emit(1) expectUnreached() }.take(1) val outer = flow { while(true) { emitAll(inner) } } assertEquals(listOf(1, 1, 1), outer.take(3).toList()) } }
apache-2.0
c0839ebde798bd53693397e7764ef051
22.197279
102
0.480645
4.377407
false
true
false
false
SmokSmog/smoksmog-android
app/src/main/kotlin/com/antyzero/smoksmog/permission/PermissionHelper.kt
1
870
package com.antyzero.smoksmog.permission import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.support.v4.content.ContextCompat /** * Makes permission checks easier * * Provides scenarios for post and pre Marshmallow OS versions */ class PermissionHelper(private val context: Context) { val isGrantedAccessCoarseLocation: Boolean get() = isGranted(Manifest.permission.ACCESS_COARSE_LOCATION) fun get(permissionKey: String) = isGranted(permissionKey) private fun isGranted(permission: String): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED } else { return true // TODO check manifest } } }
gpl-3.0
c06d3085d087ef9e911ad21a7f758b7a
28
110
0.733333
4.652406
false
false
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/widget/WideRatioRelativeLayout.kt
1
1962
/* * Copyright 2015-2019 The twitlatte 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 com.github.moko256.twitlatte.widget import android.content.Context import android.util.AttributeSet import android.widget.RelativeLayout /** * Created by moko256 on 2017/03/05. * * @author moko256 */ class WideRatioRelativeLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : RelativeLayout(context, attrs, defStyle) { override fun onMeasure(widthSpec: Int, heightSpec: Int) { val heightSize: Int val widthSize: Int when { MeasureSpec.getMode(heightSpec) != MeasureSpec.EXACTLY -> { widthSize = MeasureSpec.getSize(widthSpec) heightSize = widthSize / 16 * 9 } MeasureSpec.getMode(widthSpec) != MeasureSpec.EXACTLY -> { heightSize = MeasureSpec.getSize(heightSpec) widthSize = heightSize / 9 * 16 } else -> { widthSize = MeasureSpec.getSize(widthSpec) heightSize = MeasureSpec.getSize(heightSpec) } } super.onMeasure( MeasureSpec.makeMeasureSpec(widthSize + paddingLeft + paddingRight, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize + paddingTop + paddingBottom, MeasureSpec.EXACTLY) ) } }
apache-2.0
3462e139ed6561b9db72c93fe948b9db
31.716667
105
0.654434
4.808824
false
false
false
false
leafclick/intellij-community
java/idea-ui/src/com/intellij/internal/SharedIndexMetadata.kt
1
4444
// 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 import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import com.google.common.collect.ImmutableSortedMap import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.util.SystemInfo import com.intellij.util.indexing.IndexInfrastructureVersion import java.util.* import kotlin.collections.HashMap object SharedIndexMetadata { private const val METADATA_VERSION = "2" fun selectBestSuitableIndex(ourVersion: IndexInfrastructureVersion, candidates: List<SharedIndexInfo>): Pair<SharedIndexInfo, IndexInfrastructureVersion>? { val nodes = candidates .mapNotNull{ if (it.metadata["metadata_version"]?.asText() != METADATA_VERSION) return@mapNotNull null val baseVersions = it.metadata.mapFromPath("indexes", "base_versions") ?: return@mapNotNull null val fileIndexVersions = it.metadata.mapFromPath("indexes", "file_index_versions") ?: return@mapNotNull null val stubIndexVersions = it.metadata.mapFromPath("indexes", "stub_index_versions") ?: return@mapNotNull null IndexInfrastructureVersion(baseVersions, fileIndexVersions, stubIndexVersions) to it }.toMap() val best = ourVersion.pickBestSuitableVersion(nodes.keys) ?: return null val match = nodes[best] ?: return null return match to best } fun writeIndexMetadata(indexName: String, indexKind: String, sourcesHash: String, infrastructureVersion: IndexInfrastructureVersion, aliases: Collection<String> = setOf()): ByteArray { try { val om = ObjectMapper() val root = om.createObjectNode() root.put("metadata_version", METADATA_VERSION) root.putObject("sources").also { sources -> sources.put("os", IndexInfrastructureVersion.Os.getOs().osName) sources.put("os_name", SystemInfo.getOsNameAndVersion()) sources.put("hash", sourcesHash) sources.put("kind", indexKind) sources.put("name", indexName) sources.putArray("aliases").let { aliasesNode -> aliases.map { it.toLowerCase().trim() }.toSortedSet().forEach { aliasesNode.add(it) } } } root.putObject("environment").also { build -> build.put("os", IndexInfrastructureVersion.Os.getOs().osName) build.put("os_name", SystemInfo.getOsNameAndVersion()) root.putObject("intellij").also { ij -> ij.put("product_code", ApplicationInfo.getInstance().build.productCode) ij.put("version", ApplicationInfo.getInstance().fullVersion) ij.put("build", ApplicationInfo.getInstance().build.toString()) } } root.putObject("indexes").also { indexes -> indexes.put("weak_hash", infrastructureVersion.weakVersionHash) indexes.putObjectFromMap("base_versions", infrastructureVersion.baseIndexes) indexes.putObjectFromMap("file_index_versions", infrastructureVersion.fileBasedIndexVersions) indexes.putObjectFromMap("stub_index_versions", infrastructureVersion.stubIndexVersions) } return om.writerWithDefaultPrettyPrinter().writeValueAsBytes(root) //NOTE: should we include information about index sizes here too? } catch (t: Throwable) { throw RuntimeException("Failed to generate shared index metadata JSON. ${t.message}", t) } } private fun ObjectNode.putObjectFromMap(name: String, map: Map<String, String>) { putObject(name).also { obj -> map.entries.sortedBy { it.key.toLowerCase() }.forEach { (k, v) -> obj.put(k, v) } } } private fun ObjectNode.mapFromPath(vararg path: String): SortedMap<String, String>? { if (path.isEmpty()) return toMap() val first = path.first() val child = (get(first) as? ObjectNode) ?: return null return child.mapFromPath(*path.drop(1).toTypedArray()) } private fun ObjectNode.toMap() : SortedMap<String, String>? { val result = HashMap<String, String>() for (key in this.fieldNames()) { if (result.containsKey(key)) return null val value = get(key)?.asText() ?: return null result[key] = value } return ImmutableSortedMap.copyOf(result) } }
apache-2.0
6142d3a918353765d87ac6667adc46de
42.568627
140
0.687219
4.548618
false
false
false
false
leafclick/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/util/PersistentUtil.kt
1
3782
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.util import com.intellij.openapi.application.PathManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtilRt import com.intellij.util.indexing.impl.MapIndexStorage import com.intellij.util.io.IOUtil import com.intellij.vcs.log.VcsLogProvider import com.intellij.vcs.log.impl.VcsLogIndexer import com.intellij.vcs.log.util.PersistentUtil.LOG_CACHE import java.io.File import java.nio.file.Path object PersistentUtil { @JvmField val LOG_CACHE = File(PathManager.getSystemPath(), "vcs-log") private const val CORRUPTION_MARKER = "corruption.marker" @JvmStatic val corruptionMarkerFile: File get() = File(LOG_CACHE, CORRUPTION_MARKER) @JvmStatic fun calcLogId(project: Project, logProviders: Map<VirtualFile, VcsLogProvider>): String { val hashcode = calcHash(logProviders) { it.supportedVcs.name } return project.locationHash + "." + Integer.toHexString(hashcode) } @JvmStatic fun calcIndexId(project: Project, logProviders: Map<VirtualFile, VcsLogIndexer>): String { val hashcode = calcHash(logProviders) { it.supportedVcs.name } return project.locationHash + "." + Integer.toHexString(hashcode) } private fun <T> calcHash(logProviders: Map<VirtualFile, T>, mapping: (T) -> String): Int { val sortedRoots = logProviders.keys.sortedBy { it.path } return StringUtil.join(sortedRoots, { root -> root.path + "." + mapping(logProviders.getValue(root)) }, ".").hashCode() } } class StorageId(private val projectName: String, private val subdirName: String, private val logId: String, val version: Int) { private val safeLogId = PathUtilRt.suggestFileName(logId, true, true) private val safeProjectName = PathUtilRt.suggestFileName("${projectName.take(7)}.$logId", false, false) val subdir by lazy { File(File(LOG_CACHE, subdirName), safeProjectName) } // do not forget to change cleanupStorageFiles method when editing this one @JvmOverloads fun getStorageFile(kind: String, forMapIndexStorage: Boolean = false): Path { val storageFile = if (forMapIndexStorage) getFileForMapIndexStorage(kind) else getFile(kind) if (!storageFile.exists()) { for (oldVersion in 0 until version) { StorageId(projectName, subdirName, logId, oldVersion).cleanupStorageFiles(kind, forMapIndexStorage) } IOUtil.deleteAllFilesStartingWith(File(File(LOG_CACHE, subdirName), "$safeLogId.")) } return getFile(kind).toPath() } private fun cleanupStorageFiles(kind: String, forMapIndexStorage: Boolean) { val oldStorageFile = if (forMapIndexStorage) getFileForMapIndexStorage(kind) else getFile(kind) IOUtil.deleteAllFilesStartingWith(oldStorageFile) } fun cleanupAllStorageFiles(): Boolean { return FileUtil.deleteWithRenaming(subdir) } private fun getFile(kind: String): File { return File(subdir, "$kind.$version") } private fun getFileForMapIndexStorage(kind: String = ""): File { return MapIndexStorage.getIndexStorageFile(getFile(kind).toPath()).toFile() } }
apache-2.0
902beeacba8b876831fd581e6b8a326f
39.677419
127
0.752776
4.093074
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/rebase/interactive/dialog/ChangeEntryStateActions.kt
1
5051
// 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 git4idea.rebase.interactive.dialog import com.intellij.ide.DataManager import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonPainter import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.ui.AnActionButton import com.intellij.ui.ComponentUtil import com.intellij.ui.TableUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import git4idea.i18n.GitBundle import git4idea.rebase.GitRebaseEntry import java.awt.Component import java.awt.Dimension import java.awt.Insets import java.awt.event.InputEvent import java.awt.event.KeyEvent import javax.swing.Icon import javax.swing.JButton import javax.swing.KeyStroke internal open class ChangeEntryStateSimpleAction( protected val action: GitRebaseEntry.Action, title: String, description: String, icon: Icon?, protected val table: GitRebaseCommitsTableView ) : AnActionButton(title, description, icon), DumbAware { constructor(action: GitRebaseEntry.Action, icon: Icon?, table: GitRebaseCommitsTableView) : this(action, action.name.capitalize(), action.name.capitalize(), icon, table) init { val keyStroke = KeyStroke.getKeyStroke( KeyEvent.getExtendedKeyCodeForChar(action.mnemonic.toInt()), InputEvent.ALT_MASK ) shortcutSet = CustomShortcutSet(KeyboardShortcut(keyStroke, null)) this.registerCustomShortcutSet(table, null) } override fun actionPerformed(e: AnActionEvent) { table.selectedRows.forEach { row -> table.setValueAt(action, row, GitRebaseCommitsTableModel.COMMIT_ICON_COLUMN) } } override fun updateButton(e: AnActionEvent) { super.updateButton(e) actionIsEnabled(e, true) if (table.editingRow != -1 || table.selectedRowCount == 0) { actionIsEnabled(e, false) } } protected open fun actionIsEnabled(e: AnActionEvent, isEnabled: Boolean) { e.presentation.isEnabled = isEnabled } } internal open class ChangeEntryStateButtonAction( action: GitRebaseEntry.Action, table: GitRebaseCommitsTableView ) : ChangeEntryStateSimpleAction(action, null, table), CustomComponentAction, DumbAware { companion object { private val BUTTON_HEIGHT = JBUI.scale(28) } protected val button = object : JButton(action.name.capitalize()) { init { preferredSize = Dimension(preferredSize.width, BUTTON_HEIGHT) border = object : DarculaButtonPainter() { override fun getBorderInsets(c: Component?): Insets { return JBUI.emptyInsets() } } isFocusable = false displayedMnemonicIndex = 0 addActionListener { val toolbar = ComponentUtil.getParentOfType(ActionToolbar::class.java, this) val dataContext = toolbar?.toolbarDataContext ?: DataManager.getInstance().getDataContext(this) actionPerformed( AnActionEvent.createFromAnAction(this@ChangeEntryStateButtonAction, null, GitInteractiveRebaseDialog.PLACE, dataContext) ) } } } override fun actionIsEnabled(e: AnActionEvent, isEnabled: Boolean) { super.actionIsEnabled(e, isEnabled) button.isEnabled = isEnabled } override fun createCustomComponent(presentation: Presentation, place: String) = BorderLayoutPanel().addToCenter(button).apply { border = JBUI.Borders.emptyLeft(6) } } internal class FixupAction(table: GitRebaseCommitsTableView) : ChangeEntryStateButtonAction(GitRebaseEntry.Action.FIXUP, table) { override fun actionPerformed(e: AnActionEvent) { val selectedRows = table.selectedRows if (selectedRows.size == 1) { table.setValueAt(action, selectedRows.first(), GitRebaseCommitsTableModel.COMMIT_ICON_COLUMN) } else { selectedRows.drop(1).forEach { row -> table.setValueAt(action, row, GitRebaseCommitsTableModel.COMMIT_ICON_COLUMN) } } } } internal class RewordAction(table: GitRebaseCommitsTableView) : ChangeEntryStateButtonAction(GitRebaseEntry.Action.REWORD, table) { override fun updateButton(e: AnActionEvent) { super.updateButton(e) if (table.selectedRowCount != 1) { actionIsEnabled(e, false) } } override fun actionPerformed(e: AnActionEvent) { TableUtil.editCellAt(table, table.selectedRows.single(), GitRebaseCommitsTableModel.SUBJECT_COLUMN) } } internal class ShowGitRebaseCommandsDialog(private val project: Project, private val table: GitRebaseCommitsTableView) : DumbAwareAction(GitBundle.getString("rebase.interactive.dialog.view.git.commands.text")) { private fun getEntries(): List<GitRebaseEntry> = table.model.entries.map { it.entry } override fun actionPerformed(e: AnActionEvent) { val dialog = GitRebaseCommandsDialog(project, getEntries()) dialog.show() } }
apache-2.0
84358edad316063abbf6c44d8e34ae70
35.085714
140
0.756088
4.37316
false
false
false
false
byoutline/kickmaterial
app/src/main/java/com/byoutline/secretsauce/activities/WebViewFlickrActivity.kt
1
1429
package com.byoutline.secretsauce.activities import android.os.Bundle import android.view.KeyEvent import android.webkit.WebView import android.webkit.WebViewClient /** * WebView that hides flick redirect (which normally require pressing back twice * to get back to application) * @author Sebastian Kacprzak <sebastian.kacprzak at byoutline.com> */ class WebViewFlickrActivity : WebViewActivityV7() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Do not launch external browser for redirect. webview.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { view.loadUrl(url) return false } } } /** * Overridden to use [.onBackPressed] instead of webview back * if there is only one element left in history. * @param keyCode * * * @param event * * * @return */ override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { val canGoBack = webview.canGoBackOrForward(-2) val isBack = keyCode == KeyEvent.KEYCODE_BACK if (isBack && canGoBack) { webview.goBack() return true } else if (isBack) { onBackPressed() return true } return super.onKeyDown(keyCode, event) } }
apache-2.0
7e47ba86bc405e812eed549338e08b9e
28.770833
88
0.635409
4.779264
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/collections/irrelevantImplMutableListKotlin.kt
2
2522
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME // FILE: A.java public class A extends AImpl implements java.util.List<String> { public <T> T[] toArray(T[] a) {return null;} public Object[] toArray() {return null;} } // FILE: test.kt public abstract class AImpl { fun add(element: String): Boolean { throw UnsupportedOperationException() } fun remove(element: Any?): Boolean { throw UnsupportedOperationException() } @JvmSuppressWildcards(suppress = false) fun addAll(elements: Collection<String>): Boolean { throw UnsupportedOperationException() } fun addAll(index: Int, elements: Collection<@JvmWildcard String>): Boolean { throw UnsupportedOperationException() } fun removeAll(elements: Collection<*>): Boolean { throw UnsupportedOperationException() } fun retainAll(elements: Collection<*>): Boolean { throw UnsupportedOperationException() } fun clear() { throw UnsupportedOperationException() } fun set(index: Int, element: String): String { throw UnsupportedOperationException() } fun add(index: Int, element: String) { throw UnsupportedOperationException() } fun remove(index: Int): String { throw UnsupportedOperationException() } fun listIterator(): MutableListIterator<String> { throw UnsupportedOperationException() } fun listIterator(index: Int): MutableListIterator<String> { throw UnsupportedOperationException() } fun subList(fromIndex: Int, toIndex: Int): MutableList<String> { throw UnsupportedOperationException() } fun size(): Int = 56 fun isEmpty(): Boolean { throw UnsupportedOperationException() } fun contains(element: Any?) = true fun containsAll(elements: Collection<*>): Boolean { throw UnsupportedOperationException() } fun get(index: Int): String { throw UnsupportedOperationException() } fun indexOf(element: Any?): Int { throw UnsupportedOperationException() } fun lastIndexOf(element: Any?): Int { throw UnsupportedOperationException() } fun iterator(): MutableIterator<String> { throw UnsupportedOperationException() } } class X : A() fun box(): String { val x = X() if (x.size != 56) return "fail 1" if (!x.contains("")) return "fail 2" return "OK" }
apache-2.0
42b7cb975c5effebbd4b50b3ee5a25a5
23.019048
80
0.650278
5.054108
false
false
false
false
eggheadgames/android-in-app-payments
library/src/amazon/java/com/billing/BillingService.kt
1
1857
package com.billing import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import com.amazon.device.iap.PurchasingService class BillingService(private val context: Context, private val inAppSkuKeys: List<String>, private val subscriptionSkuKeys: List<String>) : IBillingService() { private var mAmazonBillingListener: AmazonBillingListener? = null override fun init(key: String?) { mAmazonBillingListener = AmazonBillingListener(this) PurchasingService.registerListener(context, mAmazonBillingListener) val keys: MutableList<String> = ArrayList() keys.addAll(inAppSkuKeys) keys.addAll(subscriptionSkuKeys) keys.splitMessages(MAX_SKU_LIMIT).forEach { PurchasingService.getProductData(it.toSet()) } PurchasingService.getPurchaseUpdates(true) } override fun buy(activity: Activity, sku: String) { PurchasingService.purchase(sku) } override fun subscribe(activity: Activity, sku: String) { PurchasingService.purchase(sku) } override fun unsubscribe(activity: Activity, sku: String) { try { val intent = Intent() intent.action = Intent.ACTION_VIEW intent.data = Uri.parse("https://www.amazon.com/gp/mas/your-account/myapps/yoursubscriptions/ref=mas_ya_subs") activity.startActivity(intent) activity.finish() } catch (e: Exception) { e.printStackTrace() } } override fun enableDebugLogging(enable: Boolean) { mAmazonBillingListener?.enableDebugLogging(enable) } companion object { const val MAX_SKU_LIMIT = 100 } } fun List<String>.splitMessages(maxSize: Int): List<List<String>> { return this.chunked(maxSize) }
mit
1949236819a633fd80deddbeb67e3ec6
29.966667
122
0.677975
4.249428
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_User_Option.kt
1
4378
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject class DanaRS_Packet_Option_Get_User_Option( injector: HasAndroidInjector ) : DanaRS_Packet(injector) { @Inject lateinit var danaPump: DanaPump init { opCode = BleEncryption.DANAR_PACKET__OPCODE_OPTION__GET_USER_OPTION aapsLogger.debug(LTag.PUMPCOMM, "Requesting user settings") } override fun handleMessage(data: ByteArray) { var dataIndex = DATA_START var dataSize = 1 danaPump.timeDisplayType24 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0 dataIndex += dataSize dataSize = 1 danaPump.buttonScrollOnOff = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 1 dataIndex += dataSize dataSize = 1 danaPump.beepAndAlarm = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 danaPump.lcdOnTimeSec = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 danaPump.backlightOnTimeSec = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 danaPump.selectedLanguage = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 danaPump.units = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 danaPump.shutdownHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 danaPump.lowReservoirRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 danaPump.cannulaVolume = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 danaPump.refillAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val selectableLanguage1 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val selectableLanguage2 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val selectableLanguage3 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val selectableLanguage4 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 val selectableLanguage5 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) // Pump's screen on time can't be less than 5 failed = danaPump.lcdOnTimeSec < 5 aapsLogger.debug(LTag.PUMPCOMM, "timeDisplayType24: " + danaPump.timeDisplayType24) aapsLogger.debug(LTag.PUMPCOMM, "buttonScrollOnOff: " + danaPump.buttonScrollOnOff) aapsLogger.debug(LTag.PUMPCOMM, "beepAndAlarm: " + danaPump.beepAndAlarm) aapsLogger.debug(LTag.PUMPCOMM, "lcdOnTimeSec: " + danaPump.lcdOnTimeSec) aapsLogger.debug(LTag.PUMPCOMM, "backlightOnTimeSec: " + danaPump.backlightOnTimeSec) aapsLogger.debug(LTag.PUMPCOMM, "selectedLanguage: " + danaPump.selectedLanguage) aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaPump.units == DanaPump.UNITS_MGDL) "MGDL" else "MMOL") aapsLogger.debug(LTag.PUMPCOMM, "shutdownHour: " + danaPump.shutdownHour) aapsLogger.debug(LTag.PUMPCOMM, "lowReservoirRate: " + danaPump.lowReservoirRate) aapsLogger.debug(LTag.PUMPCOMM, "refillAmount: " + danaPump.refillAmount) aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage1: $selectableLanguage1") aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage2: $selectableLanguage2") aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage3: $selectableLanguage3") aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage4: $selectableLanguage4") aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage5: $selectableLanguage5") } override fun getFriendlyName(): String { return "OPTION__GET_USER_OPTION" } }
agpl-3.0
a674eb260be437aecc28c7f87e7d8755
47.120879
119
0.699863
4.958097
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/klib/KotlinNativeLibraryNameUtil.kt
5
1352
// 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.gradle.configuration.klib import com.intellij.openapi.util.IntellijInternalApi import org.jetbrains.annotations.NonNls object KotlinNativeLibraryNameUtil { @NonNls @IntellijInternalApi const val KOTLIN_NATIVE_LIBRARY_PREFIX = "Kotlin/Native" @IntellijInternalApi const val KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE = "$KOTLIN_NATIVE_LIBRARY_PREFIX " @NonNls internal const val GRADLE_LIBRARY_PREFIX = "Gradle: " private val IDE_LIBRARY_NAME_REGEX = Regex("^$KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE([^\\s]+) - ([^\\s]+)( \\[([\\w ,()*]+)])?$") // N.B. Returns null if this is not IDE name of Kotlin/Native library. fun parseIDELibraryName(ideLibraryName: String): Triple<String, String, String?>? { val match = IDE_LIBRARY_NAME_REGEX.matchEntire(ideLibraryName) ?: return null val kotlinVersion = match.groups[1]!!.value val libraryName = match.groups[2]!!.value val platformPart = match.groups[4]?.value return Triple(kotlinVersion, libraryName, platformPart) } fun isGradleLibraryName(ideLibraryName: String) = ideLibraryName.startsWith(GRADLE_LIBRARY_PREFIX) }
apache-2.0
945626673725bcc8d7c849f1743dcd72
39.969697
158
0.719675
4.134557
false
false
false
false
ingokegel/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/CodeProcessorCheckinHandler.kt
1
2429
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.checkin import com.intellij.codeInsight.actions.AbstractLayoutCodeProcessor import com.intellij.ide.util.DelegatingProgressIndicator import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsConfiguration import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** * [CheckinMetaHandler] is only implemented for correct execution order of [CheckinHandler]-s. * To allow running handlers provided by [CheckinHandlerFactory] before the ones provided by [VcsCheckinHandlerFactory]. * * Should only be used in Commit Tool Window. Commit Dialog is not supported. * * @see com.intellij.openapi.vcs.impl.CheckinHandlersManagerImpl.getRegisteredCheckinHandlerFactories * @see com.intellij.vcs.commit.NonModalCommitWorkflowHandler.runAllHandlers */ abstract class CodeProcessorCheckinHandler( val commitPanel: CheckinProjectPanel ) : CheckinHandler(), CheckinMetaHandler, CommitCheck<CommitProblem> { val project: Project get() = commitPanel.project val settings: VcsConfiguration get() = VcsConfiguration.getInstance(project) abstract fun createCodeProcessor(): AbstractLayoutCodeProcessor override suspend fun runCheck(indicator: ProgressIndicator): CommitProblem? { val processor = createCodeProcessor() withContext(Dispatchers.Default) { val noTextIndicator = NoTextIndicator(indicator) ProgressManager.getInstance().executeProcessUnderProgress( { processor.processFilesUnderProgress(noTextIndicator) }, noTextIndicator ) } FileDocumentManager.getInstance().saveAllDocuments() return null } /** * Does nothing as no problem is reported in [runCheck]. */ override fun showDetails(problem: CommitProblem) = Unit /** * Do nothing - interface is implemented to override execution order. */ override fun runCheckinHandlers(runnable: Runnable) = runnable.run() } internal class NoTextIndicator(indicator: ProgressIndicator) : DelegatingProgressIndicator(indicator) { override fun setText(text: String?) = Unit }
apache-2.0
71f7b81646eedd8515b6c1f906105ee9
36.96875
120
0.792919
4.96728
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ToRawStringLiteralIntention.kt
1
3397
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.text.StringUtilRt import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateEntry import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset class ToRawStringLiteralIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>( KtStringTemplateExpression::class.java, KotlinBundle.lazyMessage("to.raw.string.literal") ), LowPriorityAction { override fun isApplicableTo(element: KtStringTemplateExpression): Boolean { val text = element.text if (text.startsWith("\"\"\"")) return false // already raw val escapeEntries = element.entries.filterIsInstance<KtEscapeStringTemplateEntry>() for (entry in escapeEntries) { val c = entry.unescapedValue.singleOrNull() ?: return false if (Character.isISOControl(c) && c != '\n' && c != '\r') return false } val converted = convertContent(element) return !converted.contains("\"\"\"") && !hasTrailingSpaces(converted) } override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) { val startOffset = element.startOffset val endOffset = element.endOffset val currentOffset = editor?.caretModel?.currentCaret?.offset ?: startOffset val text = convertContent(element) val replaced = element.replaced(KtPsiFactory(element).createExpression("\"\"\"" + text + "\"\"\"")) val offset = when { startOffset == currentOffset -> startOffset endOffset == currentOffset -> replaced.endOffset else -> minOf(currentOffset + 2, replaced.endOffset) } editor?.caretModel?.moveToOffset(offset) } private fun convertContent(element: KtStringTemplateExpression): String { val text = buildString { val entries = element.entries for ((index, entry) in entries.withIndex()) { val value = entry.value() if (value.endsWith("$") && index < entries.size - 1) { val nextChar = entries[index + 1].value().first() if (nextChar.isJavaIdentifierStart() || nextChar == '{') { append("\${\"$\"}") continue } } append(value) } } return StringUtilRt.convertLineSeparators(text, "\n") } private fun hasTrailingSpaces(text: String): Boolean { var afterSpace = false for (c in text) { if ((c == '\n' || c == '\r') && afterSpace) return true afterSpace = c == ' ' || c == '\t' } return false } private fun KtStringTemplateEntry.value() = if (this is KtEscapeStringTemplateEntry) this.unescapedValue else text }
apache-2.0
726266d7416d0981bb37b9e5f0ce3c46
39.452381
158
0.65234
5.062593
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/tests/test/org/jetbrains/kotlin/util/KotlinVersionUtilsTest.kt
1
5023
// 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.util import org.junit.Test import kotlin.test.assertFalse import kotlin.test.assertTrue class KotlinVersionUtilsTest { @Test fun exactRequirement() { assertTrue( parseKotlinVersionRequirement("1.5.0").matches("1.5.0"), ) assertFalse( parseKotlinVersionRequirement("1.5.0").matches("1.5.0-RC"), ) assertTrue( parseKotlinVersionRequirement("1.5.0-RC1").matches("1.5.0-rc1") ) } @Test fun sameVersionOrHigher() { assertTrue( parseKotlinVersionRequirement("1.4.0+").matches("1.4.0") ) assertTrue( parseKotlinVersionRequirement("1.4.0+").matches("1.4.10") ) assertTrue( parseKotlinVersionRequirement("1.4.0-M1+").matches("1.4.0-M1") ) assertTrue( parseKotlinVersionRequirement("1.4.0-M1+").matches("1.4.0-M2") ) assertTrue( parseKotlinVersionRequirement("1.4.0-M1+").matches("1.4.0-RC") ) assertFalse( parseKotlinVersionRequirement("1.4.0-RC2+").matches("1.4.0-RC1") ) assertTrue( parseKotlinVersionRequirement("1.4.0-RC2+").matches("1.4.0-RC3") ) assertTrue( parseKotlinVersionRequirement("1.4.0-RC3+").matches("1.4.0-rc-4") ) assertFalse( parseKotlinVersionRequirement("1.5.10+").matches("1.5.0-rc") ) assertFalse( parseKotlinVersionRequirement("1.5.10+").matches("1.5.0") ) assertTrue( parseKotlinVersionRequirement("1.5+").matches("1.5.0") ) assertTrue( parseKotlinVersionRequirement("1.5+").matches("1.5.10") ) assertFalse( parseKotlinVersionRequirement("1.5+").matches("1.5.0-rc") ) assertTrue( parseKotlinVersionRequirement("1.5.20-dev+").matches("1.5.20") ) assertTrue( parseKotlinVersionRequirement("1.5.20-dev+").matches("1.5.20-M1") ) assertTrue( parseKotlinVersionRequirement("1.5.20-dev+").matches("1.5.20-dev-39") ) assertTrue( parseKotlinVersionRequirement("1.5.20-dev+").matches("1.5.20-dev39") ) assertFalse( parseKotlinVersionRequirement("1.5.20-dev+").matches("1.5.20-SNAPSHOT") ) } @Test fun ranges() { assertTrue( parseKotlinVersionRequirement("1.4.0 <=> 1.5.0").matches("1.4.0") ) assertTrue( parseKotlinVersionRequirement("1.4.0 <=> 1.5.0").matches("1.4.10") ) assertTrue( parseKotlinVersionRequirement("1.4.0 <=> 1.5.0").matches("1.4.20-M2") ) assertFalse( parseKotlinVersionRequirement("1.4.0 <=> 1.5.0").matches("1.4.0-rc") ) assertFalse( parseKotlinVersionRequirement("1.4.0 <=> 1.5.0").matches("1.5.10-rc1") ) assertTrue( parseKotlinVersionRequirement("1.4.0 <=> 1.5.0").matches("1.5.0-alpha1") ) assertTrue( parseKotlinVersionRequirement("1.4.0 <=> 1.5.0").matches("1.5.0-rc") ) assertTrue( parseKotlinVersionRequirement("1.5.20-dev+").matches("1.5.20-dev-10") ) assertTrue( parseKotlinVersionRequirement("1.5.20-dev+").matches("1.5.20-dev10") ) } @Test fun wildcard() { assertTrue( parseKotlinVersion("1.5.30").toWildcard() > parseKotlinVersion("1.5.22") ) assertTrue( parseKotlinVersion("1.5.30").toWildcard() > parseKotlinVersion("1.5") ) assertTrue( parseKotlinVersion("1.5.31").toWildcard() > parseKotlinVersion("1.5.30") ) assertTrue( parseKotlinVersion("1.5.30").toWildcard() < parseKotlinVersion("1.5.30") ) assertTrue( parseKotlinVersion("1.5.30").toWildcard() < parseKotlinVersion("1.5.30-rc") ) assertTrue( parseKotlinVersion("1.5.30").toWildcard() < parseKotlinVersion("1.5.30-alpha1") ) assertTrue( parseKotlinVersion("1.5.30").toWildcard() < parseKotlinVersion("1.5.30-M1") ) assertTrue( parseKotlinVersion("1.5.30").toWildcard() < parseKotlinVersion("1.5.30-dev-42") ) assertTrue( parseKotlinVersion("1.5.30").toWildcard() < parseKotlinVersion("1.5.30-dev-1") ) assertTrue( parseKotlinVersion("1.5.30").toWildcard() < parseKotlinVersion("1.5.30-snapshot") ) assertTrue( parseKotlinVersion("1.5.30").toWildcard() < parseKotlinVersion("1.5.30-unknown") ) } }
apache-2.0
e6806fbbb868006c61aa7a945c2aaf1c
26.151351
158
0.553056
3.813971
false
false
false
false
siosio/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/worktree/MavenRootModelAdapterBridge.kt
1
11181
// 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.importing.worktree import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.pom.java.LanguageLevel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerComponentBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.idea.maven.importing.MavenModelUtil import org.jetbrains.idea.maven.importing.MavenRootModelAdapterInterface import org.jetbrains.idea.maven.model.MavenArtifact import org.jetbrains.idea.maven.model.MavenConstants import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.utils.Path import org.jetbrains.idea.maven.utils.Url import org.jetbrains.jps.model.JpsElement import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer import java.io.File @Retention(AnnotationRetention.SOURCE) private annotation class NotRequiredToImplement; class MavenRootModelAdapterBridge(private val myMavenProject: MavenProject, private val module: ModuleBridge, private val project: Project, initialModuleEntity: ModuleEntity, private val legacyBridgeModifiableModelsProvider: IdeModifiableModelsProviderBridge, private val builder: WorkspaceEntityStorageBuilder) : MavenRootModelAdapterInterface { private var moduleEntity: ModuleEntity = initialModuleEntity private val legacyBridge = ModuleRootComponentBridge.getInstance(module) private val modifiableModel = legacyBridge.getModifiableModel(builder, builder.toStorage(), RootConfigurationAccessor()) private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project) private val entitySource = MavenExternalSource.INSTANCE override fun init(isNewlyCreatedModule: Boolean) {} override fun getRootModel(): ModifiableRootModel { return modifiableModel } override fun getSourceRootUrls(includingTests: Boolean): Array<String> { return legacyBridge.sourceRootUrls } override fun getModule(): Module { return module } @NotRequiredToImplement override fun clearSourceFolders() { } override fun <P : JpsElement?> addSourceFolder(path: String, rootType: JpsModuleSourceRootType<P>) { createSourceRoot(rootType, path, false) } override fun addGeneratedJavaSourceFolder(path: String, rootType: JavaSourceRootType, ifNotEmpty: Boolean) { createSourceRoot(rootType, path, true) } override fun addGeneratedJavaSourceFolder(path: String, rootType: JavaSourceRootType) { createSourceRoot(rootType, path, true) } private fun <P : JpsElement?> createSourceRoot(rootType: JpsModuleSourceRootType<P>, path: String, generated: Boolean) { val typeId = getTypeId(rootType) val contentRootEntity = getContentRootFor(toUrl(path)) ?: error("Can't find content root for the source root $path") val sourceRootEntity = builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(VfsUtilCore.pathToUrl(path)), typeId, entitySource) when (rootType) { is JavaSourceRootType -> builder.addJavaSourceRootEntity(sourceRootEntity, generated, "") is JavaResourceRootType -> builder.addJavaResourceRootEntity(sourceRootEntity, generated, "") else -> TODO() } } private fun <P : JpsElement?> getTypeId(rootType: JpsModuleSourceRootType<P>): String { return if (rootType.isForTests()) return JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID else JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID } override fun hasRegisteredSourceSubfolder(f: File): Boolean { val url: String = toUrl(f.path).url return builder.entities(SourceRootEntity::class.java).filter { VfsUtilCore.isEqualOrAncestor(url, it.url.url) }.any() } private fun toUrl(path: String): Url { return toPath(path).toUrl() } override fun toPath(path: String): Path { if (!FileUtil.isAbsolute(path)) { return Path(File(myMavenProject.directory, path).path) } return Path(path) } override fun getSourceFolder(folder: File): SourceFolder? { return legacyBridge.contentEntries.flatMap { it.sourceFolders.asList() }.find { it.url == VfsUtilCore.fileToUrl(folder) } } override fun isAlreadyExcluded(f: File): Boolean { val url = toUrl(f.path).url return moduleEntity.contentRoots.filter { cre -> VfsUtilCore.isUnder(url, cre.excludedUrls.map { it.url }) }.any() } override fun addExcludedFolder(path: String) { getContentRootFor(toUrl(path))?.let { builder.modifyEntity(ModifiableContentRootEntity::class.java, it) { this.excludedUrls = this.excludedUrls + virtualFileManager.fromUrl(VfsUtilCore.pathToUrl(path)) } } } private fun getContentRootFor(url: Url): ContentRootEntity? { return moduleEntity.contentRoots.firstOrNull { VfsUtilCore.isEqualOrAncestor(it.url.url, url.url) } } @NotRequiredToImplement override fun unregisterAll(path: String, under: Boolean, unregisterSources: Boolean) { } @NotRequiredToImplement override fun hasCollision(sourceRootPath: String): Boolean { return false } override fun useModuleOutput(production: String, test: String) { TODO("not implemented") } override fun addModuleDependency(moduleName: String, scope: DependencyScope, testJar: Boolean) { val dependency = ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(moduleName), false, toEntityScope(scope), testJar) moduleEntity = builder.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { this.dependencies = this.dependencies + dependency } } private fun toEntityScope(scope: DependencyScope): ModuleDependencyItem.DependencyScope { return when (scope) { DependencyScope.COMPILE -> ModuleDependencyItem.DependencyScope.COMPILE DependencyScope.PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED DependencyScope.RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME DependencyScope.TEST -> ModuleDependencyItem.DependencyScope.TEST } } override fun findModuleByName(moduleName: String): Module? { return ModuleManagerComponentBridge(project).modules.firstOrNull { it.name == moduleName } } private fun MavenArtifact.ideaLibraryName(): String = "${this.libraryName}"; override fun addSystemDependency(artifact: MavenArtifact, scope: DependencyScope) { assert(MavenConstants.SCOPE_SYSTEM == artifact.scope) { "Artifact scope should be \"system\"" } val roots = ArrayList<LibraryRoot>() roots.add(LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)), LibraryRootTypeId.COMPILED)) val libraryTableId = LibraryTableId.ModuleLibraryTableId(ModuleId(moduleEntity.name)) val libraryEntity = builder.addLibraryEntity(artifact.ideaLibraryName(), libraryTableId, roots, emptyList(), entitySource) builder.addLibraryPropertiesEntity(libraryEntity, "repository", "<properties maven-id=\"${artifact.mavenId}\" />") } override fun addLibraryDependency(artifact: MavenArtifact, scope: DependencyScope, provider: IdeModifiableModelsProvider, project: MavenProject): LibraryOrderEntry { val roots = ArrayList<LibraryRoot>() roots.add(LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)), LibraryRootTypeId.COMPILED)) roots.add( LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "javadoc", "jar")), WorkspaceModuleImporter.JAVADOC_TYPE)) roots.add( LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "sources", "jar")), LibraryRootTypeId.SOURCES)) val libraryTableId = LibraryTableId.ProjectLibraryTableId; //(ModuleId(moduleEntity.name)) val libraryEntity = builder.addLibraryEntity(artifact.ideaLibraryName(), libraryTableId, roots, emptyList(), entitySource) builder.addLibraryPropertiesEntity(libraryEntity, "repository", "<properties maven-id=\"${artifact.mavenId}\" />") val libDependency = ModuleDependencyItem.Exportable.LibraryDependency(LibraryId(libraryEntity.name, libraryTableId), false, toEntityScope(scope)) moduleEntity = builder.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity, { this.dependencies += this.dependencies + libDependency }) val last = legacyBridge.orderEntries.last() assert(last is LibraryOrderEntry && last.libraryName == artifact.ideaLibraryName()) return last as LibraryOrderEntry } override fun findLibrary(artifact: MavenArtifact): Library? { return legacyBridge.getModuleLibraryTable().libraries.firstOrNull { it.name == artifact.ideaLibraryName() } } override fun setLanguageLevel(level: LanguageLevel) { try { modifiableModel.getModuleExtension(LanguageLevelModuleExtension::class.java)?.apply { languageLevel = level } } catch (e: IllegalArgumentException) { //bad value was stored } } }
apache-2.0
917e8bc80fbe3318f3dd38bd04fbf551
43.907631
155
0.703157
5.568227
false
false
false
false
ptkNktq/AndroidNotificationNotifier
AndroidApp/data/repository/src/main/java/me/nya_n/notificationnotifier/data/repository/source/UserSettingDataStore.kt
1
1059
package me.nya_n.notificationnotifier.data.repository.source import android.content.SharedPreferences import me.nya_n.notificationnotifier.model.UserSetting class UserSettingDataStore( pref: SharedPreferences ) : KeyValueDataStore(pref) { fun get(): UserSetting { return UserSetting( get(KEY_HOST, DEFAULT_HOST), get(KEY_PORT, DEFAULT_PORT), get(KEY_IS_PACKAGE_VISIBILITY_GRANTED, DEFAULT_IS_PACKAGE_VISIBILITY_GRANTED) ) } fun save(setting: UserSetting) { put(KEY_HOST, setting.host) put(KEY_PORT, setting.port) put(KEY_IS_PACKAGE_VISIBILITY_GRANTED, setting.isPackageVisibilityGranted) } companion object { const val DATA_STORE_NAME = "settings" const val KEY_HOST = "host" const val DEFAULT_HOST = "" const val KEY_PORT = "port" const val DEFAULT_PORT = -1 const val KEY_IS_PACKAGE_VISIBILITY_GRANTED = "isPackageVisibilityGranted" const val DEFAULT_IS_PACKAGE_VISIBILITY_GRANTED = false } }
mit
9c0844eed6c97da191d3aabb809a33e9
31.121212
89
0.668555
4.088803
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/util/userDataUtil.kt
4
1309
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.util import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.util.Key import kotlin.reflect.KProperty class DataNodeUserDataProperty<in R : DataNode<*>, T : Any>(val key: Key<T>) { operator fun getValue(thisRef: R, property: KProperty<*>) = thisRef.getUserData(key) operator fun setValue(thisRef: R, property: KProperty<*>, value: T?) = thisRef.putUserData(key, value) } class CopyableDataNodeUserDataProperty<in R : DataNode<*>, T : Any>(val key: Key<T>) { operator fun getValue(thisRef: R, property: KProperty<*>) = thisRef.getCopyableUserData(key) operator fun setValue(thisRef: R, property: KProperty<*>, value: T?) = thisRef.putCopyableUserData(key, value) } class NotNullableCopyableDataNodeUserDataProperty<in R : DataNode<*>, T : Any>(val key: Key<T>, val defaultValue: T) { operator fun getValue(thisRef: R, property: KProperty<*>) = thisRef.getCopyableUserData(key) ?: defaultValue operator fun setValue(thisRef: R, property: KProperty<*>, value: T) { thisRef.putCopyableUserData(key, if (value != defaultValue) value else null) } }
apache-2.0
eb9f930a58b63a2b544bc23406dd00fd
47.518519
158
0.737204
4.142405
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/highlighting/src/org/jetbrains/kotlin/idea/base/highlighting/KotlinHighlightingUtils.kt
1
3421
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("KotlinHighlightingUtils") package org.jetbrains.kotlin.idea.base.highlighting import com.intellij.codeInsight.daemon.OutsidersPsiFileSupport import com.intellij.openapi.project.DumbService import com.intellij.psi.PsiManager import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.idea.base.util.getOutsiderFileOrigin import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.NotUnderContentRootModuleInfo import org.jetbrains.kotlin.idea.core.script.IdeScriptReportSink import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.psi.KtCodeFragment import org.jetbrains.kotlin.psi.KtFile import kotlin.script.experimental.api.ScriptDiagnostic @ApiStatus.Internal fun KtFile.shouldHighlightErrors(): Boolean { if (isCompiled) { return false } if (this is KtCodeFragment && context != null) { return true } val canCheckScript = shouldCheckScript() if (canCheckScript == true) { return this.shouldHighlightScript() } return RootKindFilter.projectSources.copy(includeScriptsOutsideSourceRoots = canCheckScript == null).matches(this) } @ApiStatus.Internal fun KtFile.shouldHighlightFile(): Boolean { if (this is KtCodeFragment && context != null) { return true } if (isCompiled) return false if (OutsidersPsiFileSupport.isOutsiderFile(virtualFile)) { val origin = getOutsiderFileOrigin(project, virtualFile) ?: return false val psiFileOrigin = PsiManager.getInstance(project).findFile(origin) as? KtFile ?: return false return psiFileOrigin.shouldHighlightFile() } val shouldCheckScript = shouldCheckScript() if (shouldCheckScript == true) { return this.shouldHighlightScript() } return if (shouldCheckScript != null) { RootKindFilter.everything.matches(this) && moduleInfo !is NotUnderContentRootModuleInfo } else { RootKindFilter.everything.copy(includeScriptsOutsideSourceRoots = true).matches(this) } } private fun KtFile.shouldCheckScript(): Boolean? = runReadAction { when { // to avoid SNRE from stub (KTIJ-7633) DumbService.getInstance(project).isDumb -> null isScript() -> true else -> false } } private fun KtFile.shouldHighlightScript(): Boolean { if (KotlinPlatformUtils.isCidr) { // There is no Java support in CIDR. So do not highlight errors in KTS if running in CIDR. return false } if (!ScriptConfigurationManager.getInstance(project).hasConfiguration(this)) return false if (IdeScriptReportSink.getReports(this).any { it.severity == ScriptDiagnostic.Severity.FATAL }) { return false } if (!ScriptDefinitionsManager.getInstance(project).isReady()) return false return RootKindFilter.projectSources.copy(includeScriptsOutsideSourceRoots = true).matches(this) }
apache-2.0
f75998717180e849c10ae56a081194dd
36.195652
120
0.758258
4.567423
false
false
false
false
ohmae/VoiceMessageBoard
app/src/main/java/net/mm2d/android/vmb/MainActivity.kt
1
9554
/* * Copyright (c) 2014 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.android.vmb import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.util.TypedValue import android.view.* import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ShareCompat import androidx.core.view.updatePadding import kotlinx.android.synthetic.main.activity_main.* import net.mm2d.android.vmb.dialog.EditStringDialog import net.mm2d.android.vmb.dialog.EditStringDialog.ConfirmStringListener import net.mm2d.android.vmb.dialog.RecognizerDialog.RecognizeListener import net.mm2d.android.vmb.dialog.SelectStringDialog.SelectStringListener import net.mm2d.android.vmb.dialog.SelectThemeDialog.SelectThemeListener import net.mm2d.android.vmb.font.FontUtils import net.mm2d.android.vmb.history.HistoryDelegate import net.mm2d.android.vmb.recognize.VoiceInputDelegate import net.mm2d.android.vmb.settings.Settings import net.mm2d.android.vmb.theme.Theme import net.mm2d.android.vmb.theme.ThemeDelegate import net.mm2d.android.vmb.util.ViewUtils import java.util.* /** * 起動後から表示されるActivity。 * * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class MainActivity : AppCompatActivity(), SelectThemeListener, SelectStringListener, ConfirmStringListener, RecognizeListener { private val settings by lazy { Settings.get() } private lateinit var themeDelegate: ThemeDelegate private lateinit var historyDelegate: HistoryDelegate private lateinit var voiceInputDelegate: VoiceInputDelegate private lateinit var gestureDetector: GestureDetector private lateinit var scaleDetector: ScaleGestureDetector private lateinit var showHistoryMenu: MenuItem private lateinit var clearHistoryMenu: MenuItem private var fontSizeMin: Float = 0.0f private var fontSizeMax: Float = 0.0f private var fontSize: Float = 0.0f override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) supportActionBar?.title = null scaleDetector = ScaleGestureDetector(this, ScaleListener()) gestureDetector = GestureDetector(this, GestureListener()) fontSizeMin = resources.getDimension(R.dimen.font_size_min) fontSizeMax = resources.getDimension(R.dimen.font_size_max) editFab.setOnClickListener { startEdit() } val listener = { _: View, event: MotionEvent -> gestureDetector.onTouchEvent(event) scaleDetector.onTouchEvent(event) false } scrollView.setOnTouchListener(listener) textView.setOnTouchListener(listener) themeDelegate = ThemeDelegate(this, scrollView, textView, toolbar?.overflowIcon) themeDelegate.apply() historyDelegate = HistoryDelegate(this, historyFab) voiceInputDelegate = VoiceInputDelegate(this, RECOGNIZER_REQUEST_CODE, PERMISSION_REQUEST_CODE) { setText(it) } restoreInstanceState(savedInstanceState) ViewUtils.execOnLayout(scrollView) { updatePadding() } } /** * Bundleがあればそこから、なければ初期値をViewに設定する。 * * @param savedInstanceState State */ private fun restoreInstanceState(savedInstanceState: Bundle?) { if (savedInstanceState == null) { // 画面幅に初期文字列が収まる大きさに調整 val width = resources.displayMetrics.widthPixels val initialText = textView.text.toString() fontSize = if (initialText[0] <= '\u007e') { width.toFloat() / initialText.length * 2 } else { width.toFloat() / initialText.length } textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize) } else { // テキストとフォントサイズを復元 fontSize = savedInstanceState.getFloat(TAG_FONT_SIZE) val text = savedInstanceState.getString(TAG_TEXT) textView.text = text textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // テキストとフォントサイズを保存 outState.putFloat(TAG_FONT_SIZE, fontSize) outState.putString(TAG_TEXT, textView.text.toString()) } override fun onStart() { super.onStart() FontUtils.setFont(textView, settings) } override fun onResume() { super.onResume() requestedOrientation = settings.screenOrientation updatePadding() } override fun onConfigurationChanged(newConfig: Configuration?) { super.onConfigurationChanged(newConfig) ViewUtils.execOnLayout(scrollView) { updatePadding() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { voiceInputDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults) } override fun onRecognize(results: ArrayList<String>) { voiceInputDelegate.onRecognize(results) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { voiceInputDelegate.onActivityResult(requestCode, resultCode, data) } /** * テキストの編集を開始する。 */ private fun startEdit() { val string = textView.text.toString() EditStringDialog.show(this, string) } /** * 文字列を設定する。 * * Activityからも設定できるようにpublic * onSaveInstanceStateでここで設定した文字列は保持される。 * * @param string 表示する文字列 */ private fun setText(string: String) { textView.text = string historyDelegate.put(string) scrollView.scrollTo(0, 0) updatePadding() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) showHistoryMenu = menu.findItem(R.id.action_show_history) clearHistoryMenu = menu.findItem(R.id.action_clear_history) return true } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { if (historyDelegate.exist()) { showHistoryMenu.isEnabled = true clearHistoryMenu.isEnabled = true } else { showHistoryMenu.isEnabled = false clearHistoryMenu.isEnabled = false } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_settings -> startActivity(Intent(this, SettingsActivity::class.java)) R.id.action_theme -> themeDelegate.showDialog() R.id.action_show_history -> historyDelegate.showSelectDialog() R.id.action_clear_history -> historyDelegate.showClearDialog() R.id.action_share -> ShareCompat.IntentBuilder.from(this) .setText(textView.text) .setType("text/plain") .startChooser() else -> return super.onOptionsItemSelected(item) } return true } override fun onSelectTheme(theme: Theme) { themeDelegate.select(theme) } override fun onSelectString(string: String) { setText(string) if (settings.shouldShowEditorAfterSelect()) { startEdit() } } override fun onConfirmString(string: String) { setText(string) } /** * タッチイベントをClickとLongClickに振り分ける。 * * 直接OnClickを使うとピンチ時に反応するため、 * GestureDetectorを利用する。 */ private inner class GestureListener : GestureDetector.SimpleOnGestureListener() { override fun onSingleTapUp(e: MotionEvent): Boolean { voiceInputDelegate.start() return true } override fun onLongPress(e: MotionEvent) { if (settings.shouldShowEditorWhenLongTap()) { startEdit() } } } /** * ピンチ操作でフォントサイズを調整する。 */ private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() { override fun onScale(detector: ScaleGestureDetector): Boolean { val factor = detector.scaleFactor fontSize = (fontSize * factor).coerceIn(fontSizeMin, fontSizeMax) textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize) updatePadding() return true } } private fun updatePadding() { scrollView.post { val diff = scrollView.height - textView.height scrollView.updatePadding(top = if (diff > 0) diff / 2 else 0) } } companion object { private const val TAG_FONT_SIZE = "TAG_FONT_SIZE" private const val TAG_TEXT = "TAG_TEXT" private const val RECOGNIZER_REQUEST_CODE = 1 private const val PERMISSION_REQUEST_CODE = 2 } }
mit
27eaca53b1a6e3df0381adafa2829d87
32.595588
93
0.657146
4.526003
false
false
false
false
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/player/gesture/PopupPlayerGestureListener.kt
1
9896
package org.schabi.newpipe.player.gesture import android.util.Log import android.view.MotionEvent import android.view.View import android.view.ViewConfiguration import androidx.core.math.MathUtils import org.schabi.newpipe.MainActivity import org.schabi.newpipe.ktx.AnimationType import org.schabi.newpipe.ktx.animate import org.schabi.newpipe.player.ui.PopupPlayerUi import kotlin.math.abs import kotlin.math.hypot import kotlin.math.max import kotlin.math.min class PopupPlayerGestureListener( private val playerUi: PopupPlayerUi, ) : BasePlayerGestureListener(playerUi) { private var isMoving = false private var initialPopupX: Int = -1 private var initialPopupY: Int = -1 private var isResizing = false // initial coordinates and distance between fingers private var initPointerDistance = -1.0 private var initFirstPointerX = -1f private var initFirstPointerY = -1f private var initSecPointerX = -1f private var initSecPointerY = -1f override fun onTouch(v: View, event: MotionEvent): Boolean { super.onTouch(v, event) if (event.pointerCount == 2 && !isMoving && !isResizing) { if (DEBUG) { Log.d(TAG, "onTouch() 2 finger pointer detected, enabling resizing.") } onPopupResizingStart() // record coordinates of fingers initFirstPointerX = event.getX(0) initFirstPointerY = event.getY(0) initSecPointerX = event.getX(1) initSecPointerY = event.getY(1) // record distance between fingers initPointerDistance = hypot( initFirstPointerX - initSecPointerX.toDouble(), initFirstPointerY - initSecPointerY.toDouble() ) isResizing = true } if (event.action == MotionEvent.ACTION_MOVE && !isMoving && isResizing) { if (DEBUG) { Log.d( TAG, "onTouch() ACTION_MOVE > v = [$v], e1.getRaw =" + "[${event.rawX}, ${event.rawY}]" ) } return handleMultiDrag(event) } if (event.action == MotionEvent.ACTION_UP) { if (DEBUG) { Log.d( TAG, "onTouch() ACTION_UP > v = [$v], e1.getRaw =" + " [${event.rawX}, ${event.rawY}]" ) } if (isMoving) { isMoving = false onScrollEnd(event) } if (isResizing) { isResizing = false initPointerDistance = (-1).toDouble() initFirstPointerX = (-1).toFloat() initFirstPointerY = (-1).toFloat() initSecPointerX = (-1).toFloat() initSecPointerY = (-1).toFloat() onPopupResizingEnd() player.changeState(player.currentState) } if (!playerUi.isPopupClosing) { playerUi.savePopupPositionAndSizeToPrefs() } } v.performClick() return true } override fun onScrollEnd(event: MotionEvent) { super.onScrollEnd(event) if (playerUi.isInsideClosingRadius(event)) { playerUi.closePopup() } else if (!playerUi.isPopupClosing) { playerUi.closeOverlayBinding.closeButton.animate(false, 200) binding.closingOverlay.animate(false, 200) } } private fun handleMultiDrag(event: MotionEvent): Boolean { if (initPointerDistance == -1.0 || event.pointerCount != 2) { return false } // get the movements of the fingers val firstPointerMove = hypot( event.getX(0) - initFirstPointerX.toDouble(), event.getY(0) - initFirstPointerY.toDouble() ) val secPointerMove = hypot( event.getX(1) - initSecPointerX.toDouble(), event.getY(1) - initSecPointerY.toDouble() ) // minimum threshold beyond which pinch gesture will work val minimumMove = ViewConfiguration.get(player.context).scaledTouchSlop if (max(firstPointerMove, secPointerMove) <= minimumMove) { return false } // calculate current distance between the pointers val currentPointerDistance = hypot( event.getX(0) - event.getX(1).toDouble(), event.getY(0) - event.getY(1).toDouble() ) val popupWidth = playerUi.popupLayoutParams.width.toDouble() // change co-ordinates of popup so the center stays at the same position val newWidth = popupWidth * currentPointerDistance / initPointerDistance initPointerDistance = currentPointerDistance playerUi.popupLayoutParams.x += ((popupWidth - newWidth) / 2.0).toInt() playerUi.checkPopupPositionBounds() playerUi.updateScreenSize() playerUi.changePopupSize(min(playerUi.screenWidth.toDouble(), newWidth).toInt()) return true } private fun onPopupResizingStart() { if (DEBUG) { Log.d(TAG, "onPopupResizingStart called") } binding.loadingPanel.visibility = View.GONE playerUi.hideControls(0, 0) binding.fastSeekOverlay.animate(false, 0) binding.currentDisplaySeek.animate(false, 0, AnimationType.ALPHA, 0) } private fun onPopupResizingEnd() { if (DEBUG) { Log.d(TAG, "onPopupResizingEnd called") } } override fun onLongPress(e: MotionEvent?) { playerUi.updateScreenSize() playerUi.checkPopupPositionBounds() playerUi.changePopupSize(playerUi.screenWidth) } override fun onFling( e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float ): Boolean { return if (player.popupPlayerSelected()) { val absVelocityX = abs(velocityX) val absVelocityY = abs(velocityY) if (absVelocityX.coerceAtLeast(absVelocityY) > TOSS_FLING_VELOCITY) { if (absVelocityX > TOSS_FLING_VELOCITY) { playerUi.popupLayoutParams.x = velocityX.toInt() } if (absVelocityY > TOSS_FLING_VELOCITY) { playerUi.popupLayoutParams.y = velocityY.toInt() } playerUi.checkPopupPositionBounds() playerUi.windowManager.updateViewLayout(binding.root, playerUi.popupLayoutParams) return true } return false } else { true } } override fun onDownNotDoubleTapping(e: MotionEvent): Boolean { // Fix popup position when the user touch it, it may have the wrong one // because the soft input is visible (the draggable area is currently resized). playerUi.updateScreenSize() playerUi.checkPopupPositionBounds() playerUi.popupLayoutParams.let { initialPopupX = it.x initialPopupY = it.y } return true // we want `super.onDown(e)` to be called } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { if (DEBUG) Log.d(TAG, "onSingleTapConfirmed() called with: e = [$e]") if (isDoubleTapping) return true if (player.exoPlayerIsNull()) return false onSingleTap() return true } override fun onScroll( initialEvent: MotionEvent, movingEvent: MotionEvent, distanceX: Float, distanceY: Float ): Boolean { if (isResizing) { return super.onScroll(initialEvent, movingEvent, distanceX, distanceY) } if (!isMoving) { playerUi.closeOverlayBinding.closeButton.animate(true, 200) } isMoving = true val diffX = (movingEvent.rawX - initialEvent.rawX) val posX = MathUtils.clamp( initialPopupX + diffX, 0f, (playerUi.screenWidth - playerUi.popupLayoutParams.width).toFloat() ) val diffY = (movingEvent.rawY - initialEvent.rawY) val posY = MathUtils.clamp( initialPopupY + diffY, 0f, (playerUi.screenHeight - playerUi.popupLayoutParams.height).toFloat() ) playerUi.popupLayoutParams.x = posX.toInt() playerUi.popupLayoutParams.y = posY.toInt() // -- Determine if the ClosingOverlayView (red X) has to be shown or hidden -- val showClosingOverlayView: Boolean = playerUi.isInsideClosingRadius(movingEvent) // Check if an view is in expected state and if not animate it into the correct state val expectedVisibility = if (showClosingOverlayView) View.VISIBLE else View.GONE if (binding.closingOverlay.visibility != expectedVisibility) { binding.closingOverlay.animate(showClosingOverlayView, 200) } playerUi.windowManager.updateViewLayout(binding.root, playerUi.popupLayoutParams) return true } override fun getDisplayPortion(e: MotionEvent): DisplayPortion { return when { e.x < playerUi.popupLayoutParams.width / 3.0 -> DisplayPortion.LEFT e.x > playerUi.popupLayoutParams.width * 2.0 / 3.0 -> DisplayPortion.RIGHT else -> DisplayPortion.MIDDLE } } override fun getDisplayHalfPortion(e: MotionEvent): DisplayPortion { return when { e.x < playerUi.popupLayoutParams.width / 2.0 -> DisplayPortion.LEFT_HALF else -> DisplayPortion.RIGHT_HALF } } companion object { private val TAG = PopupPlayerGestureListener::class.java.simpleName private val DEBUG = MainActivity.DEBUG private const val TOSS_FLING_VELOCITY = 2500 } }
gpl-3.0
25c0f71961f6052e14a3581e51393121
33.968198
97
0.602162
4.562471
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/MainActivityExtensions.kt
1
2293
package com.maubis.scarlet.base import android.content.Context import android.content.Intent import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTypeface import com.maubis.scarlet.base.settings.sheet.ThemeColorPickerBottomSheet import com.maubis.scarlet.base.settings.sheet.TypefacePickerBottomSheet import com.maubis.scarlet.base.support.sheets.openSheet import com.maubis.scarlet.base.support.ui.font.sPreferenceTypeface import com.maubis.scarlet.base.support.ui.sThemeLabel const val INTENT_KEY_ADDITIONAL_ACTION = "additional_action" enum class MainActivityActions { NIL, COLOR_PICKER, TYPEFACE_PICKER; fun intent(context: Context): Intent { val intent = Intent(context, MainActivity::class.java) intent.putExtra(INTENT_KEY_ADDITIONAL_ACTION, this.name) return intent } } fun MainActivity.handleIntent() { val actionFromIntent = intent.getStringExtra(INTENT_KEY_ADDITIONAL_ACTION) if (actionFromIntent === null || actionFromIntent.isEmpty()) { return } val action = try { MainActivityActions.valueOf(actionFromIntent) } catch (exception: Exception) { null } if (action === null) { return } performAction(action) } fun MainActivity.performAction(action: MainActivityActions) { val activity = this when (action) { MainActivityActions.NIL -> { } MainActivityActions.COLOR_PICKER -> { openSheet(this, ThemeColorPickerBottomSheet().apply { this.onThemeChange = { theme -> if (sThemeLabel != theme.name) { sThemeLabel = theme.name sAppTheme.notifyChange(activity) activity.startActivity(MainActivityActions.COLOR_PICKER.intent(activity)) activity.finish() } } }) } MainActivityActions.TYPEFACE_PICKER -> { openSheet(this, TypefacePickerBottomSheet().apply { this.onTypefaceChange = { typeface -> if (sPreferenceTypeface != typeface.name) { sPreferenceTypeface = typeface.name sAppTypeface.notifyChange(activity) activity.startActivity(MainActivityActions.TYPEFACE_PICKER.intent(activity)) activity.finish() } } }) } } }
gpl-3.0
bce96988f3853a171f57618076045bec
29.586667
88
0.706498
4.277985
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/RemoveRedundantQualifiersForCallsConversion.kt
2
1470
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.identifier import org.jetbrains.kotlin.nj2k.symbols.JKUniverseClassSymbol import org.jetbrains.kotlin.nj2k.symbols.isStaticMember import org.jetbrains.kotlin.nj2k.tree.* class RemoveRedundantQualifiersForCallsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKQualifiedExpression) return recurse(element) val needRemoveQualifier = when (val receiver = element.receiver.receiverExpression()) { is JKClassAccessExpression -> receiver.identifier is JKUniverseClassSymbol is JKFieldAccessExpression, is JKCallExpression -> element.selector.identifier?.isStaticMember == true else -> false } if (needRemoveQualifier) { element.invalidate() return recurse(element.selector.withFormattingFrom(element.receiver).withFormattingFrom(element)) } return recurse(element) } private fun JKExpression.receiverExpression() = when (this) { is JKQualifiedExpression -> selector else -> this } }
apache-2.0
c194258ebe738e0e5b0f7f86a33d6ed9
46.451613
129
0.753741
4.983051
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/internal/inspector/components/DataContextDialog.kt
2
4992
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.inspector.components import com.intellij.ide.DataManager import com.intellij.ide.impl.DataManagerImpl import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Comparing import com.intellij.ui.ColoredTableCellRenderer import com.intellij.ui.ScreenUtil import com.intellij.ui.dsl.builder.Align import com.intellij.ui.dsl.builder.actionListener import com.intellij.ui.dsl.builder.panel import com.intellij.ui.table.JBTable import com.intellij.util.ui.JBUI import java.awt.Component import javax.swing.Action import javax.swing.JComponent import javax.swing.JTable import javax.swing.table.DefaultTableModel class DataContextDialog( project: Project?, val contextComponent: JComponent ) : DialogWrapper(project) { init { init() } override fun getDimensionServiceKey() = "UiInternal.DataContextDialog" override fun createActions(): Array<Action> { return arrayOf(cancelAction) } override fun createCenterPanel(): JComponent? { val table = JBTable() table.setDefaultRenderer(Object::class.java, MyTableCellRenderer()) table.model = buildTreeModel(false) val panel = panel { row { @Suppress("DialogTitleCapitalization") checkBox("Show GetDataRule") // NON-NLS .actionListener { event, component -> table.model = buildTreeModel(component.isSelected) } } row { scrollCell(table) .align(Align.FILL) .resizableColumn() }.resizableRow() } val screenBounds = ScreenUtil.getMainScreenBounds() val width = (screenBounds.width * 0.8).toInt() val height = (screenBounds.height * 0.8).toInt() return panel.withPreferredSize(width, height) } private fun buildTreeModel(showDataRules: Boolean): DefaultTableModel { val model = DefaultTableModel() model.addColumn("Key") model.addColumn("Value") model.addColumn("Value type") val values = mutableMapOf<String, Any>() var component: Component? = contextComponent while (component != null) { val result = collectDataFrom(component, showDataRules) .filter { data -> !Comparing.equal(values[data.key], data.value) } // filter out identical overrides if (result.isNotEmpty()) { if (model.rowCount > 0) { model.appendEmptyRow() } model.appendHeader(component) for (data in result) { model.appendRow(data, values[data.key] != null) values[data.key] = data.value } } component = component.parent } return model } private fun DefaultTableModel.appendHeader(component: Component) { addRow(arrayOf(Header("$component"), null, getClassName(component))) } private fun DefaultTableModel.appendRow(data: ContextData, overridden: Boolean) { addRow(arrayOf(getKeyPresentation(data.key, overridden), getValuePresentation(data.value), getClassName(data.value))) } private fun DefaultTableModel.appendEmptyRow() { addRow(arrayOf("", "", "")) } private fun collectDataFrom(component: Component, showDataRules: Boolean): List<ContextData> { val dataManager = DataManager.getInstance() val provider = DataManagerImpl.getDataProviderEx(component) ?: return emptyList() val result = mutableListOf<ContextData>() for (key in DataKey.allKeys()) { val data = when { showDataRules -> dataManager.getCustomizedData( key.name, dataManager.getDataContext(component.parent), provider) else -> provider.getData(key.name) } ?: continue result += ContextData(key.name, data) } return result } private fun getKeyPresentation(key: String, overridden: Boolean) = when { overridden -> "*OVERRIDDEN* ${key}" else -> key } private fun getValuePresentation(value: Any) = when (value) { is Array<*> -> value.contentToString() else -> value.toString() } private fun getClassName(value: Any): String { val clazz: Class<*> = value.javaClass return when { clazz.isAnonymousClass -> "${clazz.superclass.simpleName}$..." else -> clazz.simpleName } } private class MyTableCellRenderer : ColoredTableCellRenderer() { override fun customizeCellRenderer(table: JTable, value: Any?, selected: Boolean, hasFocus: Boolean, row: Int, column: Int) { if (value != null) { append(value.toString()) } val isHeader = table.model.getValueAt(row, 0) is Header if (isHeader) { background = JBUI.CurrentTheme.Table.Selection.background(false) } } } private class ContextData(val key: String, val value: Any) private class Header(val key: String) { override fun toString(): String = key } }
apache-2.0
25556cd53cd194e1c3902c191bc973df
30.802548
129
0.688502
4.398238
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/config/GitDownloadAndInstall.kt
9
4559
// 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 git4idea.config import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import com.google.common.hash.Hashing import com.google.common.io.Files import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.util.io.HttpRequests import git4idea.i18n.GitBundle import org.tukaani.xz.XZInputStream import java.io.ByteArrayInputStream import java.io.File private const val feedUrl = "https://download.jetbrains.com/jdk/feed/v1/gits.json.xz" private val LOG = Logger.getInstance("#git4idea.config.GitDownloadAndInstall") fun downloadAndInstallGit(project: Project, onSuccess: () -> Unit = {}) { val errorNotifier = NotificationErrorNotifier(project) when { SystemInfo.isWindows -> WindowsExecutableProblemHandler(project).downloadAndInstall(errorNotifier, onSuccess) SystemInfo.isMac -> MacExecutableProblemHandler(project).downloadAndInstall(errorNotifier, onSuccess) } } internal data class GitInstaller( val os: String, val arch: String, val version: String, val url: String, val fileName: String, val pkgFileName: String?, val sha256: String ) internal fun fetchInstaller(errorNotifier: ErrorNotifier, condition: (GitInstaller) -> Boolean): GitInstaller? { val installers = try { downloadListOfGitInstallers() } catch (t: Throwable) { LOG.warn(t) errorNotifier.showError(GitBundle.message("install.general.error")) return null } val matchingInstaller = installers.find(condition) if (matchingInstaller != null) { return matchingInstaller } else { LOG.warn("Couldn't find installer among $installers") errorNotifier.showError(GitBundle.message("install.general.error")) return null } } private fun downloadListOfGitInstallers(): List<GitInstaller> { val compressedJson = downloadGitJson() val jsonBytes = try { ByteArrayInputStream(compressedJson).use { input -> XZInputStream(input).use { it.readBytes() } } } catch (t: Throwable) { throw RuntimeException("Failed to unpack the list of available Gits from $feedUrl. ${t.message}", t) } return try { parse(readTree(jsonBytes)) } catch (t: Throwable) { throw RuntimeException("Failed to parse the downloaded list of available Gits. ${t.message}", t) } } private fun downloadGitJson(): ByteArray { return HttpRequests .request(feedUrl) .productNameAsUserAgent() .readBytes(ProgressManager.getInstance().progressIndicator) } private fun readTree(rawData: ByteArray) = ObjectMapper().readTree(rawData) as? ObjectNode ?: error("Unexpected JSON data") private fun parse(node: ObjectNode) : List<GitInstaller> { val items = node["gits"] as? ArrayNode ?: error("`gits` element is missing in JSON") val result = mutableListOf<GitInstaller>() for (item in items.filterIsInstance<ObjectNode>()) { result.add( GitInstaller( item["os"]?.asText() ?: continue, item["arch"]?.asText() ?: continue, item["version"]?.asText() ?: continue, item["url"]?.asText() ?: continue, item["fileName"]?.asText() ?: continue, item["pkgFileName"]?.asText(), item["sha256"]?.asText() ?: continue ) ) } return result } internal fun downloadGit(installer: GitInstaller, fileToSave: File, project: Project, errorNotifier: ErrorNotifier) : Boolean { try { HttpRequests .request(installer.url) .productNameAsUserAgent() .saveToFile(fileToSave, ProgressManager.getInstance().progressIndicator) verifyHashCode(installer, fileToSave) return true } catch (e: Exception) { LOG.warn("Couldn't download ${installer.fileName} from ${installer.url}", e) errorNotifier.showError(GitBundle.message("install.general.error"), getLinkToConfigure(project)) return false } } private fun verifyHashCode(installer: GitInstaller, downloadedFile: File) { val actualHashCode = Files.asByteSource(downloadedFile).hash(Hashing.sha256()).toString() if (!actualHashCode.equals(installer.sha256, ignoreCase = true)) { throw IllegalStateException("SHA-256 checksums does not match. Actual value is $actualHashCode, expected ${installer.sha256}") } }
apache-2.0
35ab303961a325e803ee62213a599581
33.022388
158
0.731959
4.178735
false
false
false
false
smmribeiro/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/ExternalSystemJdkComboBoxUtil.kt
9
2819
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("ExternalSystemJdkComboBoxUtil") @file:ApiStatus.Internal package com.intellij.openapi.externalSystem.service.ui import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil.* import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.roots.ui.configuration.SdkComboBox import com.intellij.openapi.roots.ui.configuration.SdkListItem import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider.SdkInfo import org.jetbrains.annotations.ApiStatus private val RESOLVING_JDK by lazy { ExternalSystemBundle.message("external.system.java.in.resolving") } fun SdkComboBox.getSelectedJdkReference(sdkLookupProvider: SdkLookupProvider): String? { return sdkLookupProvider.resolveJdkReference(selectedItem) } fun SdkComboBox.setSelectedJdkReference(sdkLookupProvider: SdkLookupProvider, jdkReference: String?) { when (jdkReference) { USE_PROJECT_JDK -> selectedItem = showProjectSdkItem() USE_JAVA_HOME -> selectedItem = addJdkReferenceItem(JAVA_HOME, getJavaHome()) null -> when (val sdkInfo = sdkLookupProvider.getSdkInfo()) { SdkInfo.Undefined -> selectedItem = showNoneSdkItem() SdkInfo.Unresolved -> selectedItem = addJdkReferenceItem(RESOLVING_JDK, null, true) is SdkInfo.Resolving -> selectedItem = addJdkReferenceItem(sdkInfo.name, sdkInfo.versionString, true) is SdkInfo.Resolved -> setSelectedSdk(sdkInfo.name) } else -> return setSelectedSdk(jdkReference) } } fun SdkComboBox.addJdkReferenceItem(name: String, homePath: String?): SdkListItem { val type = getJavaSdkType() val isValid = isValidJdk(homePath) val versionString = if (isValid) type.getVersionString(homePath) else null return addSdkReferenceItem(type, name, versionString, isValid) } fun SdkComboBox.addJdkReferenceItem(name: String, versionString: String?, isValid: Boolean): SdkListItem { val type = getJavaSdkType() return addSdkReferenceItem(type, name, versionString, isValid) } fun SdkLookupProvider.resolveJdkReference(item: SdkListItem?): String? { return when (item) { is SdkListItem.ProjectSdkItem -> USE_PROJECT_JDK is SdkListItem.SdkItem -> item.sdk.name is SdkListItem.InvalidSdkItem -> item.sdkName is SdkListItem.SdkReferenceItem -> when (item.name) { JAVA_HOME -> USE_JAVA_HOME RESOLVING_JDK -> getSdk()?.name else -> when (val sdkInfo = getSdkInfo()) { SdkInfo.Undefined -> null SdkInfo.Unresolved -> null is SdkInfo.Resolving -> null is SdkInfo.Resolved -> sdkInfo.name } } else -> null } }
apache-2.0
0eca7c78945ecce6fa3033254857e752
43.046875
140
0.765165
4.390966
false
true
false
false
smmribeiro/intellij-community
platform/testFramework/src/com/intellij/testFramework/utils/inlays/InlayParameterHintsTest.kt
3
8523
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework.utils.inlays import com.intellij.codeInsight.daemon.impl.HintRenderer import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.VisualPosition import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.util.TextRange import com.intellij.rt.execution.junit.FileComparisonFailure import com.intellij.testFramework.VfsTestUtil import com.intellij.testFramework.fixtures.CodeInsightTestFixture import junit.framework.ComparisonFailure import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import java.util.regex.Pattern class InlayHintsChecker(private val myFixture: CodeInsightTestFixture) { private var isParamHintsEnabledBefore = false companion object { val pattern: Pattern = Pattern.compile("(<caret>)|(<selection>)|(</selection>)|<(hint|HINT|Hint|hINT)\\s+text=\"([^\"\n\r]+)\"\\s*/>") private val default = ParameterNameHintsSettings() } fun setUp() { val settings = EditorSettingsExternalizable.getInstance() isParamHintsEnabledBefore = settings.isShowParameterNameHints settings.isShowParameterNameHints = true } fun tearDown() { EditorSettingsExternalizable.getInstance().isShowParameterNameHints = isParamHintsEnabledBefore val hintSettings = ParameterNameHintsSettings.getInstance() hintSettings.loadState(default.state) } val manager = ParameterHintsPresentationManager.getInstance() val inlayPresenter: (Inlay<*>) -> String = { (it.renderer as HintRenderer).text ?: throw IllegalArgumentException("No text set to hint") } val inlayFilter: (Inlay<*>) -> Boolean = { manager.isParameterHint(it) } fun checkParameterHints() = checkInlays(inlayPresenter, inlayFilter) fun checkInlays(inlayPresenter: (Inlay<*>) -> String, inlayFilter: (Inlay<*>) -> Boolean) { val file = myFixture.file!! val document = myFixture.getDocument(file) val originalText = document.text val expectedInlaysAndCaret = extractInlaysAndCaretInfo(document) myFixture.doHighlighting() verifyInlaysAndCaretInfo(expectedInlaysAndCaret, originalText, inlayPresenter, inlayFilter) } fun verifyInlaysAndCaretInfo(expectedInlaysAndCaret: CaretAndInlaysInfo, originalText: String) = verifyInlaysAndCaretInfo(expectedInlaysAndCaret, originalText, inlayPresenter, inlayFilter) private fun verifyInlaysAndCaretInfo(expectedInlaysAndCaret: CaretAndInlaysInfo, originalText: String, inlayPresenter: (Inlay<*>) -> String, inlayFilter: (Inlay<*>) -> Boolean) { val file = myFixture.file!! val document = myFixture.getDocument(file) val actual: List<InlayInfo> = getActualInlays(inlayPresenter, inlayFilter) val expected = expectedInlaysAndCaret.inlays if (expectedInlaysAndCaret.inlays.size != actual.size || actual.zip(expected).any { it.first != it.second }) { val entries: MutableList<Pair<Int, String>> = mutableListOf() actual.forEach { entries.add(Pair(it.offset, buildString { append("<") append((if (it.highlighted) "H" else "h")) append((if (it.current) "INT" else "int")) append(" text=\"") append(it.text) append("\"/>") }))} if (expectedInlaysAndCaret.caretOffset != null) { val actualCaretOffset = myFixture.editor.caretModel.offset val actualInlaysBeforeCaret = myFixture.editor.caretModel.visualPosition.column - myFixture.editor.offsetToVisualPosition(actualCaretOffset).column val first = entries.indexOfFirst { it.first == actualCaretOffset } val insertIndex = if (first == -1) -entries.binarySearch { it.first - actualCaretOffset } - 1 else first + actualInlaysBeforeCaret entries.add(insertIndex, Pair(actualCaretOffset, "<caret>")) } val proposedText = StringBuilder(document.text) entries.asReversed().forEach { proposedText.insert(it.first, it.second) } VfsTestUtil.TEST_DATA_FILE_PATH.get(file.virtualFile)?.let { originalPath -> throw FileComparisonFailure("Hints differ", originalText, proposedText.toString(), originalPath) } ?: throw ComparisonFailure("Hints differ", originalText, proposedText.toString()) } if (expectedInlaysAndCaret.caretOffset != null) { assertEquals("Unexpected caret offset", expectedInlaysAndCaret.caretOffset, myFixture.editor.caretModel.offset) val position = myFixture.editor.offsetToVisualPosition(expectedInlaysAndCaret.caretOffset) assertEquals("Unexpected caret visual position", VisualPosition(position.line, position.column + expectedInlaysAndCaret.inlaysBeforeCaret), myFixture.editor.caretModel.visualPosition) val selectionModel = myFixture.editor.selectionModel if (expectedInlaysAndCaret.selection == null) assertFalse(selectionModel.hasSelection()) else assertEquals("Unexpected selection", expectedInlaysAndCaret.selection, TextRange(selectionModel.selectionStart, selectionModel.selectionEnd)) } } private fun getActualInlays(inlayPresenter: (Inlay<*>) -> String, inlayFilter: (Inlay<*>) -> Boolean): List<InlayInfo> { val editor = myFixture.editor val allInlays = editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength) + editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength) val hintManager = ParameterHintsPresentationManager.getInstance() return allInlays .filterNotNull() .filter { inlayFilter(it) } .map { val isHighlighted: Boolean val isCurrent: Boolean if (hintManager.isParameterHint(it)) { isHighlighted = hintManager.isHighlighted(it) isCurrent = hintManager.isCurrent(it) } else { isHighlighted = false isCurrent = false } InlayInfo(it.offset, inlayPresenter(it), isHighlighted, isCurrent) } .sortedBy { it.offset } } fun extractInlaysAndCaretInfo(document: Document): CaretAndInlaysInfo { val text = document.text val matcher = pattern.matcher(text) val inlays = mutableListOf<InlayInfo>() var extractedLength = 0 var caretOffset : Int? = null var inlaysBeforeCaret = 0 var selectionStart : Int? = null var selectionEnd : Int? = null while (matcher.find()) { val start = matcher.start() val matchedLength = matcher.end() - start val realStartOffset = start - extractedLength when { matcher.group(1) != null -> { caretOffset = realStartOffset inlays.asReversed() .takeWhile { it.offset == caretOffset } .forEach { inlaysBeforeCaret++ } } matcher.group(2) != null -> selectionStart = realStartOffset matcher.group(3) != null -> selectionEnd = realStartOffset else -> inlays += InlayInfo(realStartOffset, matcher.group(5), matcher.group(4).startsWith("H"), matcher.group(4).endsWith("INT")) } removeText(document, realStartOffset, matchedLength) extractedLength += (matcher.end() - start) } return CaretAndInlaysInfo(caretOffset, inlaysBeforeCaret, if (selectionStart == null || selectionEnd == null) null else TextRange(selectionStart, selectionEnd), inlays) } private fun removeText(document: Document, realStartOffset: Int, matchedLength: Int) { WriteCommandAction.runWriteCommandAction(myFixture.project, { document.replaceString(realStartOffset, realStartOffset + matchedLength, "") }) } } class CaretAndInlaysInfo (val caretOffset: Int?, val inlaysBeforeCaret: Int, val selection: TextRange?, val inlays: List<InlayInfo>) data class InlayInfo (val offset: Int, val text: String, val highlighted: Boolean, val current: Boolean)
apache-2.0
52fd1ed3992cbcebbf25ec5548bb9bef
44.100529
140
0.697407
5.118919
false
false
false
false
googlearchive/android-InteractiveSliceProvider
app/src/main/java/com/example/android/interactivesliceprovider/slicebuilders/ReservationSliceBuilder.kt
1
3673
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.interactivesliceprovider.slicebuilders import android.content.Context import android.net.Uri import androidx.core.graphics.drawable.IconCompat import androidx.slice.builders.ListBuilder import androidx.slice.builders.SliceAction import androidx.slice.builders.cell import androidx.slice.builders.gridRow import androidx.slice.builders.header import androidx.slice.builders.list import com.example.android.interactivesliceprovider.InteractiveSliceProvider import com.example.android.interactivesliceprovider.SliceActionsBroadcastReceiver import com.example.android.interactivesliceprovider.R import com.example.android.interactivesliceprovider.R.drawable import com.example.android.interactivesliceprovider.SliceBuilder class ReservationSliceBuilder( val context: Context, sliceUri: Uri ) : SliceBuilder(sliceUri) { override fun buildSlice() = list(context, sliceUri, ListBuilder.INFINITY) { header { title = "Upcoming trip to Seattle" subtitle = "Feb 1 - 19 | 2 guests" primaryAction = SliceAction.create( SliceActionsBroadcastReceiver.getIntent( context, InteractiveSliceProvider.ACTION_TOAST, "Primary Action for Reservation Slice" ), IconCompat.createWithResource(context, drawable.ic_location), ListBuilder.ICON_IMAGE, "Primary" ) } addAction( SliceAction.create( SliceActionsBroadcastReceiver.getIntent( context, InteractiveSliceProvider.ACTION_TOAST, "show location on map" ), IconCompat.createWithResource(context, drawable.ic_location), ListBuilder.ICON_IMAGE, "Show reservation location" ) ) addAction( SliceAction.create( SliceActionsBroadcastReceiver.getIntent( context, InteractiveSliceProvider.ACTION_TOAST, "contact host" ), IconCompat.createWithResource(context, drawable.ic_text), ListBuilder.ICON_IMAGE, "Contact host" ) ) gridRow { cell { addImage( IconCompat.createWithResource( context, R.drawable.reservation ), ListBuilder.LARGE_IMAGE ) setContentDescription("Image of your reservation in Seattle") } } gridRow { cell { addTitleText("Check In") addText("12:00 PM, Feb 1") } cell { addTitleText("Check Out") addText("11:00 AM, Feb 19") } } } companion object { const val TAG = "ListSliceBuilder" } }
apache-2.0
3cec0a90c5df3b31250848365d3cc24d
35.019608
82
0.606044
5.377745
false
false
false
false
marktony/ZhiHuDaily
app/src/main/java/com/marktony/zhihudaily/timeline/GuokrHandpickFragment.kt
1
5349
/* * Copyright 2016 lizhaotailang * * 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.marktony.zhihudaily.timeline import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v4.content.LocalBroadcastManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.marktony.zhihudaily.R import com.marktony.zhihudaily.data.ContentType import com.marktony.zhihudaily.data.GuokrHandpickNewsResult import com.marktony.zhihudaily.data.PostType import com.marktony.zhihudaily.details.DetailsActivity import com.marktony.zhihudaily.interfaze.OnRecyclerViewItemOnClickListener import com.marktony.zhihudaily.service.CacheService import kotlinx.android.synthetic.main.fragment_timeline_page.* /** * Created by lizhaotailang on 2017/5/24. * * Main UI for the guokr handpick news. * Displays a grid of [GuokrHandpickNewsResult]s. */ class GuokrHandpickFragment : Fragment(), GuokrHandpickContract.View { override lateinit var mPresenter: GuokrHandpickContract.Presenter private var mAdapter: GuokrHandpickNewsAdapter? = null private lateinit var mLayoutManager: LinearLayoutManager private var mOffset = 0 private var mIsFirstLoad = true private var mListSize = 0 override val isActive: Boolean get() = isAdded && isResumed companion object { fun newInstance(): GuokrHandpickFragment = GuokrHandpickFragment() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_timeline_page, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) context?.let { refresh_layout.setColorSchemeColors(ContextCompat.getColor(context!!, R.color.colorAccent)) } refresh_layout.setOnRefreshListener { mPresenter.load(true, true, 0, 20) mOffset = 0 } mLayoutManager = LinearLayoutManager(context) recycler_view.layoutManager = mLayoutManager recycler_view.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy > 0 && mLayoutManager.findLastCompletelyVisibleItemPosition() == mListSize - 1) { loadMore() } } }) } override fun onResume() { super.onResume() mPresenter.start() setLoadingIndicator(mIsFirstLoad) if (mIsFirstLoad) { mPresenter.load(true, false, mOffset, 20) mIsFirstLoad = false } else { mPresenter.load(false, false, mOffset, 20) } } override fun setLoadingIndicator(active: Boolean) { refresh_layout.post { refresh_layout.isRefreshing = active } } override fun showResult(list: MutableList<GuokrHandpickNewsResult>) { mOffset = list.size if (mAdapter == null) { mAdapter = GuokrHandpickNewsAdapter(list) mAdapter?.setItemClickListener(object : OnRecyclerViewItemOnClickListener { override fun onItemClick(v: View, position: Int) { val intent = Intent(activity, DetailsActivity::class.java).apply { putExtra(DetailsActivity.KEY_ARTICLE_ID, list[position].id) putExtra(DetailsActivity.KEY_ARTICLE_TYPE, ContentType.TYPE_GUOKR_HANDPICK) putExtra(DetailsActivity.KEY_ARTICLE_TITLE, list[position].title) putExtra(DetailsActivity.KEY_ARTICLE_IS_FAVORITE, list[position].isFavorite) } startActivity(intent) } }) recycler_view.adapter = mAdapter } else { mAdapter?.updateData(list) } mListSize = list.size empty_view.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE recycler_view.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE for ((_, _, _, _, _, id) in list) { val intent = Intent(CacheService.BROADCAST_FILTER_ACTION) intent.putExtra(CacheService.FLAG_ID, id) intent.putExtra(CacheService.FLAG_TYPE, PostType.GUOKR) LocalBroadcastManager.getInstance(context!!).sendBroadcast(intent) } } private fun loadMore() { mPresenter.load(true, false, mOffset, 20) } }
apache-2.0
9f26cb82895c7fa36b60c560247db5dd
35.636986
184
0.67751
4.814581
false
false
false
false
aosp-mirror/platform_frameworks_support
core/ktx/src/main/java/androidx/core/graphics/Canvas.kt
1
2840
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.graphics import android.graphics.Canvas import android.graphics.Matrix /** * Wrap the specified [block] in calls to [Canvas.save] * and [Canvas.restoreToCount]. */ inline fun Canvas.withSave(block: Canvas.() -> Unit) { val checkpoint = save() try { block() } finally { restoreToCount(checkpoint) } } /** * Wrap the specified [block] in calls to [Canvas.save]/[Canvas.translate] * and [Canvas.restoreToCount]. */ inline fun Canvas.withTranslation( x: Float = 0.0f, y: Float = 0.0f, block: Canvas.() -> Unit ) { val checkpoint = save() translate(x, y) try { block() } finally { restoreToCount(checkpoint) } } /** * Wrap the specified [block] in calls to [Canvas.save]/[Canvas.rotate] * and [Canvas.restoreToCount]. */ inline fun Canvas.withRotation( degrees: Float = 0.0f, pivotX: Float = 0.0f, pivotY: Float = 0.0f, block: Canvas.() -> Unit ) { val checkpoint = save() rotate(degrees, pivotX, pivotY) try { block() } finally { restoreToCount(checkpoint) } } /** * Wrap the specified [block] in calls to [Canvas.save]/[Canvas.scale] * and [Canvas.restoreToCount]. */ inline fun Canvas.withScale( x: Float = 1.0f, y: Float = 1.0f, pivotX: Float = 0.0f, pivotY: Float = 0.0f, block: Canvas.() -> Unit ) { val checkpoint = save() scale(x, y, pivotX, pivotY) try { block() } finally { restoreToCount(checkpoint) } } /** * Wrap the specified [block] in calls to [Canvas.save]/[Canvas.skew] * and [Canvas.restoreToCount]. */ inline fun Canvas.withSkew( x: Float = 0.0f, y: Float = 0.0f, block: Canvas.() -> Unit ) { val checkpoint = save() skew(x, y) try { block() } finally { restoreToCount(checkpoint) } } /** * Wrap the specified [block] in calls to [Canvas.save]/[Canvas.concat] * and [Canvas.restoreToCount]. */ inline fun Canvas.withMatrix( matrix: Matrix = Matrix(), block: Canvas.() -> Unit ) { val checkpoint = save() concat(matrix) try { block() } finally { restoreToCount(checkpoint) } }
apache-2.0
479b7e4ad3d683344134185d0683c6d3
21.72
75
0.623239
3.622449
false
false
false
false
luhaoaimama1/JavaZone
JavaTest_Zone/src/kt/LazyStudy.kt
1
525
package kt class LazyStudy { var pop: String? = null fun initPop():String? { if (pop == null) { pop = "haha" } val callback=A@{ println("callback1") return@A } callback.invoke() println("callback2") return pop } } fun main(args: Array<String>) { val lazyStudy = LazyStudy() lazyStudy.initPop() println("before ___pop:${lazyStudy.pop}") lazyStudy.pop = null println("after ___pop:${lazyStudy.pop}") }
epl-1.0
786c91b5ea9c1234824272d87ff3fd75
20.04
45
0.52381
3.832117
false
false
false
false
sujeet4github/MyLangUtils
LangKotlin/Idiomatic/src/main/kotlin/idiomatic/Apply.kt
1
842
package idiomaticKotlin import org.apache.commons.dbcp2.BasicDataSource // Don't do this fun blub(){ val dataSource = BasicDataSource() dataSource.driverClassName = "com.mysql.jdbc.Driver" dataSource.url = "jdbc:mysql://domain:3309/db" dataSource.username = "username" dataSource.password = "password" dataSource.maxTotal = 40 dataSource.maxIdle = 40 dataSource.minIdle = 4 } // The extension function apply() helps to group and centralize // initialization code for an object. // Besides, we don't have to repeat the variable name over and over again. // Do this instead val dataSource = BasicDataSource().apply { driverClassName = "com.mysql.jdbc.Driver" url = "jdbc:mysql://domain:3309/db" username = "username" password = "password" maxTotal = 40 maxIdle = 40 minIdle = 4 }
gpl-3.0
e620759689be609663a1a86af4532360
27.066667
74
0.703088
3.792793
false
false
false
false
sonnytron/FitTrainerBasic
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/activities/WorkoutActivity.kt
1
2312
package com.sonnyrodriguez.fittrainer.fittrainerbasic.activities import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.sonnyrodriguez.fittrainer.fittrainerbasic.FitTrainerApplication import com.sonnyrodriguez.fittrainer.fittrainerbasic.database.WorkoutObject import com.sonnyrodriguez.fittrainer.fittrainerbasic.fragments.StartWorkoutFragment import com.sonnyrodriguez.fittrainer.fittrainerbasic.fragments.WorkoutStatusFragment import com.sonnyrodriguez.fittrainer.fittrainerbasic.library.replaceFragmentDSL import com.sonnyrodriguez.fittrainer.fittrainerbasic.models.LocalExerciseObject import com.sonnyrodriguez.fittrainer.fittrainerbasic.models.MuscleEnum import com.sonnyrodriguez.fittrainer.fittrainerbasic.ui.FragmentContainerUi import com.sonnyrodriguez.fittrainer.fittrainerbasic.values.KeyConstants import org.jetbrains.anko.setContentView class WorkoutActivity: AppCompatActivity() { internal var exercises = ArrayList<LocalExerciseObject>() var completedWorkout = false var workoutTitle = "" lateinit var workoutObject: WorkoutObject companion object { fun newIntent(workoutObject: WorkoutObject): Intent { val intent = Intent(FitTrainerApplication.instance, WorkoutActivity::class.java) intent.putExtra(KeyConstants.INTENT_WORKOUT_OBJECT, workoutObject) return intent } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) FragmentContainerUi().setContentView(this) workoutObject = intent.getParcelableExtra(KeyConstants.INTENT_WORKOUT_OBJECT) exercises.clear() exercises.addAll(workoutObject.exerciseMetaList) workoutTitle = workoutObject.title if (completedWorkout) { // show workout finished status } else { initializeStatus() } } internal fun initializeStatus() { val muscleTitles = exercises.map { MuscleEnum.fromMuscleNumber(it.muscleGroup).title } val limitedMuscles = ArrayList<String>() limitedMuscles.addAll( muscleTitles.filter { !limitedMuscles.contains(it) } ) replaceFragmentDSL(StartWorkoutFragment.newInstance(workoutObject, this)) } }
apache-2.0
1d6f59449a546927319704596a95a1fe
41.036364
94
0.764706
5.070175
false
false
false
false
sonnytron/FitTrainerBasic
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/activities/CameraActivity.kt
1
4319
package com.sonnyrodriguez.fittrainer.fittrainerbasic.activities import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.os.Environment import android.os.PersistableBundle import android.support.v7.app.AppCompatActivity import android.widget.ImageButton import com.flurgle.camerakit.CameraListener import com.sonnyrodriguez.fittrainer.fittrainerbasic.FitTrainerApplication import com.sonnyrodriguez.fittrainer.fittrainerbasic.R import com.sonnyrodriguez.fittrainer.fittrainerbasic.values.KeyConstants import com.flurgle.camerakit.CameraView import com.sonnyrodriguez.fittrainer.fittrainerbasic.database.ExerciseObject import com.sonnyrodriguez.fittrainer.fittrainerbasic.file.PhotoFileManager import com.sonnyrodriguez.fittrainer.fittrainerbasic.presenter.ExercisePresenterHelper import com.sonnyrodriguez.fittrainer.fittrainerbasic.presenter.SingleExercisePresenter import com.sonnyrodriguez.fittrainer.fittrainerbasic.values.UIConstants import dagger.android.AndroidInjection import org.jetbrains.anko.find import javax.inject.Inject class CameraActivity: AppCompatActivity(), SingleExercisePresenter { var fileManager: PhotoFileManager? = null var exerciseSavedString: String? = null var localImages: ArrayList<String> = arrayListOf() lateinit var localExerciseObject: ExerciseObject var exerciseId: Long = 0L var exerciseIndex: Int = 0 @Inject lateinit var exercisePresenterHelper: ExercisePresenterHelper val exercisePhotoPath: String by lazy { val externalDirectory = getExternalFilesDir(Environment.DIRECTORY_PICTURES) if (externalDirectory == null) { return@lazy filesDir.absolutePath } else { return@lazy externalDirectory.absolutePath } } var camera: CameraView? = null lateinit var shutterButton: ImageButton lateinit var flashButton: ImageButton var cameraListener = object : CameraListener() { override fun onPictureTaken(jpeg: ByteArray?) { super.onPictureTaken(jpeg) jpeg?.let { val rawBitmap: Bitmap = BitmapFactory.decodeByteArray(it, 0, it.size) fileManager?.let { fileMan -> fileMan.ensurePhotoPath().apply { fileMan.createImagePath(rawBitmap, filePathString()).apply { setValueForResult(this) } } } } } } companion object { fun newIntent(exerciseObject: ExerciseObject): Intent { val intent = Intent(FitTrainerApplication.instance, CameraActivity::class.java) intent.putExtra(KeyConstants.INTENT_EXERCISE_INDEX, exerciseObject) return intent } } override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState, persistentState) setContentView(R.layout.camera_activity) localExerciseObject = intent.getParcelableExtra(KeyConstants.INTENT_EXERCISE_INDEX) initializeCamera() } internal fun initializeCamera() { camera = find(R.id.camera_object) shutterButton = find(R.id.camera_activity_shutter) flashButton = find(R.id.camera_activity_flash) localImages.addAll(localExerciseObject.imageList) fileManager = PhotoFileManager(exercisePhotoPath) camera?.start() camera?.setCameraListener(cameraListener) exercisePresenterHelper.onCreate(this) } override fun onResume() { super.onResume() camera?.start() } override fun onPause() { super.onPause() camera?.stop() } internal fun setValueForResult(valueString: String) { localImages.add(valueString) localExerciseObject.imageList = localImages exercisePresenterHelper.saveSingleExercise(localExerciseObject) } internal fun filePathString(): String = "$exerciseId${UIConstants.DEFAULT_FILE_PATH_VALUE_BAR}$exerciseIndex${UIConstants.DEFAULT_FILE_PATH_VALUE_BAR}${UIConstants.FILE_INTERMEDIATE_NAME}" override fun singleExerciseSaved() { finish() } }
apache-2.0
88b14f2a81791fa03db6b7c2fb4a201e
36.556522
160
0.715906
5.027939
false
false
false
false
yuttadhammo/BodhiTimer
app/src/main/java/org/yuttadhammo/BodhiTimer/TimePickerDialog.kt
1
2472
/* This file is part of Bodhi Timer. Bodhi Timer 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. Bodhi Timer 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 Bodhi Timer. If not, see <http://www.gnu.org/licenses/>. */ package org.yuttadhammo.BodhiTimer import android.content.Context import android.view.View import android.widget.TimePicker /** * Dialog box with an arbitrary number of number pickers * * THIS IS AN UNUSED EXPERIMENT! */ class TimePickerDialog(context: Context) : SlidingPickerDialog(context) { override val layout: Int = R.layout.timepicker_dialog private var timePicker: TimePicker? = null override fun setupTimePicker() { // Time Picker timePicker = findViewById(R.id.timePicker) timePicker!!.setIs24HourView(true) setHour(mTimes) setMinute(mTimes) } /** * {@inheritDoc} */ override fun onClick(v: View) { when (v.id) { R.id.btnOk -> { val hsel = hour val msel = minute val ssel = 0 val values = intArrayOf(hsel, msel, ssel) returnResults(values) } R.id.btnCancel -> dismiss() R.id.btn1 -> setFromPreset(i1) R.id.btn2 -> setFromPreset(i2) R.id.btn3 -> setFromPreset(i3) R.id.btn4 -> setFromPreset(i4) R.id.btnadv -> setFromAdv() } } override fun getStringFromUI(): String { var h = hour.toString() + "" var m = minute.toString() + "" if (h.length == 1) h = "0$h" if (m.length == 1) m = "0$m" return "$h:$m" } // Helper functions private fun setMinute(times: IntArray?) { timePicker!!.minute = times!![1] } private fun setHour(times: IntArray?) { timePicker!!.hour = times!![0] } private val minute: Int get() = timePicker!!.minute private val hour: Int get() = timePicker!!.hour }
gpl-3.0
3cb442d358c4cfd263c8af4960f010b2
27.425287
73
0.606392
4.099502
false
false
false
false
AntriKodSoft/ColorHub
app/src/main/java/layout/MainFragment.kt
1
4480
package layout import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentTransaction import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import cheetatech.com.colorhub.R import cheetatech.com.colorhub.adapters.MainPageAdapter import cheetatech.com.colorhub.controller.ColorLists import cheetatech.com.colorhub.listeners.OnItemSelect import cheetatech.com.colorhub.listeners.RecyclerItemClickListener import cheetatech.com.colorhub.models.MainPageModel class MainFragment : Fragment(){ private var mColorListener: ColorPicker1.OnColorListener? = null fun setListener(mColorListener: ColorPicker1.OnColorListener?){ this.mColorListener = mColorListener } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater!!.inflate(R.layout.fragment_main, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) var lists = ColorLists(activity.resources) var mRecyclerView = view?.findViewById(R.id.main_page_recycler_view) as RecyclerView var mlist : MutableList<MainPageModel> = mutableListOf( MainPageModel("Flat","#2980B9"), MainPageModel("Material","#F44336"), MainPageModel("Social","#3AAF85"), MainPageModel("Metro","#FA6800"), MainPageModel("Html","#FF1493"), MainPageModel("ColorPalette X","#ADFF2F"), MainPageModel("ColorPalette Y","#AA00FF") ) var manager = GridLayoutManager(activity.applicationContext, 1) with(mRecyclerView){ layoutManager = manager as RecyclerView.LayoutManager? setHasFixedSize(true) } var adapter = MainPageAdapter(context, mlist, object: OnItemSelect{ override fun onAddColor(color: String) { } override fun onItemSelected(position: Int) { } }) mRecyclerView.adapter = adapter mRecyclerView.addOnItemTouchListener(object : RecyclerItemClickListener(context, OnItemClickListener { view, position -> var fragment : Fragment? = null; fragment = when(position){ 0 -> ColorKotlinFragment.newInstance(lists.flatList!!, itemListener) 1 -> MaterialUIFragment.newInstance(lists, itemListener) 2 -> ColorKotlinFragment.newInstance(lists.socialList!!, itemListener) 3 -> ColorKotlinFragment.newInstance(lists.metroList!!, itemListener) 4 -> ColorKotlinFragment.newInstance(lists.htmlList!!, itemListener) 5 -> ColorPicker1.newInstance(itemListener) 6 -> ColorPicker3.newInstance (itemListener) else -> { null } } val transaction = fragmentManager.beginTransaction() with(transaction){ add(R.id.root_frame, fragment) setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) addToBackStack(null) commit() } }){}) } var itemListener = object : OnItemSelect{ override fun onAddColor(color: String) { mColorListener?.onAddColor(color) } override fun onItemSelected(position: Int) { } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is ColorPicker1.OnColorListener) { mColorListener = context as ColorPicker1.OnColorListener? } else { throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mColorListener = null } companion object { fun newInstance(mColorListener: ColorPicker1.OnColorListener?): MainFragment { val fragment = MainFragment() fragment.setListener(mColorListener) return fragment } } }
gpl-3.0
5b6fc44f55bcee3714f18ae276b683fe
34.555556
128
0.646205
5.096701
false
false
false
false
tonyofrancis/Fetch
fetch2/src/main/java/com/tonyodev/fetch2/provider/DownloadProvider.kt
1
1342
package com.tonyodev.fetch2.provider import com.tonyodev.fetch2.Download import com.tonyodev.fetch2.PrioritySort import com.tonyodev.fetch2.Status import com.tonyodev.fetch2.database.FetchDatabaseManagerWrapper class DownloadProvider(private val fetchDatabaseManagerWrapper: FetchDatabaseManagerWrapper) { fun getDownloads(): List<Download> { return fetchDatabaseManagerWrapper.get() } fun getDownload(id: Int): Download? { return fetchDatabaseManagerWrapper.get(id) } fun getDownloads(ids: List<Int>): List<Download?> { return fetchDatabaseManagerWrapper.get(ids) } fun getByGroup(group: Int): List<Download> { return fetchDatabaseManagerWrapper.getByGroup(group) } fun getByGroupReplace(group: Int, download: Download): List<Download> { val downloads = getByGroup(group) as ArrayList val index = downloads.indexOfFirst { it.id == download.id } if (index != -1) { downloads[index] = download } return downloads } fun getByStatus(status: Status): List<Download> { return fetchDatabaseManagerWrapper.getByStatus(status) } fun getPendingDownloadsSorted(prioritySort: PrioritySort): List<Download> { return fetchDatabaseManagerWrapper.getPendingDownloadsSorted(prioritySort) } }
apache-2.0
b7ff657dd77e31646eef098432614e01
29.522727
94
0.714605
4.458472
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/lists/ManageListsDialogFragmentViewModel.kt
1
3166
package com.battlelancer.seriesguide.lists import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.liveData import androidx.lifecycle.viewModelScope import com.battlelancer.seriesguide.provider.SgRoomDatabase import com.battlelancer.seriesguide.shows.database.SgShow2Minimal import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /** * Loads show details and lists with the initial is on list state for the item, * allows to modify the state without changing the database. */ class ManageListsDialogFragmentViewModel( application: Application, showId: Long ) : AndroidViewModel(application) { val showDetails = liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) { val showDetails = SgRoomDatabase.getInstance(application) .sgShow2Helper() .getShowMinimal(showId) emit(showDetails) if (showDetails != null) { loadLists(showDetails) } } data class ListWithItem( val listId: String, val listName: String, val isItemOnListOriginal: Boolean, val isItemOnList: Boolean ) val listsWithItem = MutableLiveData<List<ListWithItem>>() private fun loadLists(showDetails: SgShow2Minimal) { viewModelScope.launch(Dispatchers.IO) { val showTmdbId = showDetails.tmdbId ?: 0 if (showTmdbId > 0) { val listHelper = SgRoomDatabase.getInstance(getApplication()).sgListHelper() val listItemsForShow = listHelper.getListItemsWithTmdbId(showTmdbId) val initialListsWithItem = listHelper .getListsForExport() .map { list -> val isItemOnList = listItemsForShow.find { list.listId == it.listId } != null ListWithItem( listId = list.listId, listName = list.name, isItemOnListOriginal = isItemOnList, isItemOnList = isItemOnList ) } listsWithItem.postValue(initialListsWithItem) } } } fun setIsItemOnList(listId: String, value: Boolean) { val listsWithItem = listsWithItem.value ?: return val indexToReplace = listsWithItem.indexOfFirst { it.listId == listId } if (indexToReplace >= 0) { val updatedLists = listsWithItem.toMutableList() updatedLists[indexToReplace] = listsWithItem[indexToReplace].copy(isItemOnList = value) this.listsWithItem.postValue(updatedLists) } } } class ManageListsDialogFragmentViewModelFactory( private val application: Application, private val showId: Long ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return ManageListsDialogFragmentViewModel(application, showId) as T } }
apache-2.0
48c33ddff5a65d2ad4690cec01326ac7
35.390805
101
0.657296
5.198686
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/immutable/StatSeries.kt
1
13187
package ca.josephroque.bowlingcompanion.statistics.immutable import android.content.Context import android.database.Cursor import android.os.Parcel import android.support.v7.preference.PreferenceManager import ca.josephroque.bowlingcompanion.common.interfaces.IIdentifiable import ca.josephroque.bowlingcompanion.common.interfaces.KParcelable import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.common.interfaces.readDate import ca.josephroque.bowlingcompanion.common.interfaces.writeDate import ca.josephroque.bowlingcompanion.database.Contract.BowlerEntry import ca.josephroque.bowlingcompanion.database.Contract.GameEntry import ca.josephroque.bowlingcompanion.database.Contract.FrameEntry import ca.josephroque.bowlingcompanion.database.Contract.LeagueEntry import ca.josephroque.bowlingcompanion.database.Contract.SeriesEntry import ca.josephroque.bowlingcompanion.database.Contract.TeamBowlerEntry import ca.josephroque.bowlingcompanion.database.DatabaseHelper import ca.josephroque.bowlingcompanion.games.Frame import ca.josephroque.bowlingcompanion.games.Game import ca.josephroque.bowlingcompanion.games.lane.Pin import ca.josephroque.bowlingcompanion.leagues.League import ca.josephroque.bowlingcompanion.matchplay.MatchPlayResult import ca.josephroque.bowlingcompanion.scoring.Fouls import ca.josephroque.bowlingcompanion.settings.Settings import ca.josephroque.bowlingcompanion.utils.DateUtils import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.async import java.util.Date /** * Copyright (C) 2018 Joseph Roque * * An immutable Series for calculating statistics, created from the database. */ class StatSeries( override val id: Long, val games: List<StatGame>, val date: Date ) : IIdentifiable, KParcelable { val total: Int get() = games.sumBy { it.score } // MARK: Constructor private constructor(p: Parcel): this( id = p.readLong(), games = arrayListOf<StatGame>().apply { val parcelableArray = p.readParcelableArray(StatGame::class.java.classLoader)!! this.addAll(parcelableArray.map { return@map it as StatGame }) }, date = p.readDate()!! ) // MARK: Parcelable override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeLong(id) writeParcelableArray(games.toTypedArray(), 0) writeDate(date) } companion object { @Suppress("unused") private const val TAG = "StatSeries" @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::StatSeries) private val queryFields = ( "series.${SeriesEntry._ID} as sid, " + "series.${SeriesEntry.COLUMN_SERIES_DATE}, " + "${StatGame.QUERY_FIELDS.joinToString(separator = ", ")}, " + "${StatFrame.QUERY_FIELDS.joinToString(separator = ", ")} ") fun loadSeriesForTeam(context: Context, teamId: Long): Deferred<List<StatSeries>> { val preferences = PreferenceManager.getDefaultSharedPreferences(context) val includeOpen = Settings.BooleanSetting.IncludeOpen.getValue(preferences) val includeEvents = Settings.BooleanSetting.IncludeEvents.getValue(preferences) val query = ("SELECT " + queryFields + "FROM ${TeamBowlerEntry.TABLE_NAME} as teamBowlers " + "INNER JOIN ${BowlerEntry.TABLE_NAME} as bowler " + "ON ${TeamBowlerEntry.COLUMN_BOWLER_ID}=bowler.${BowlerEntry._ID} " + "INNER JOIN ${LeagueEntry.TABLE_NAME} as league " + "ON bowler.${BowlerEntry._ID}=${LeagueEntry.COLUMN_BOWLER_ID} " + "INNER JOIN ${SeriesEntry.TABLE_NAME} as series " + "ON league.${LeagueEntry._ID}=${SeriesEntry.COLUMN_LEAGUE_ID} " + "INNER JOIN ${GameEntry.TABLE_NAME} as game " + "ON series.${SeriesEntry._ID}=game.${GameEntry.COLUMN_SERIES_ID} " + "INNER JOIN ${FrameEntry.TABLE_NAME} as frame " + "ON game.${GameEntry._ID}=frame.${FrameEntry.COLUMN_GAME_ID} " + "WHERE teamBowlers.${TeamBowlerEntry.COLUMN_TEAM_ID}=? " + (if (!includeOpen) "AND league.${LeagueEntry.COLUMN_LEAGUE_NAME}!=? " else "") + (if (!includeEvents) "AND league.${LeagueEntry.COLUMN_IS_EVENT}!=? " else "") + "ORDER BY " + "series.${SeriesEntry.COLUMN_SERIES_DATE}, " + "series.${SeriesEntry._ID}, " + "game.${GameEntry.COLUMN_GAME_NUMBER}, " + "frame.${FrameEntry.COLUMN_FRAME_NUMBER}") val args = listOfNotNull( teamId.toString(), if (!includeOpen) League.PRACTICE_LEAGUE_NAME else null, if (!includeEvents) "1" else null ).toTypedArray() return loadSeries(context, query, args) } fun loadSeriesForBowler(context: Context, bowlerId: Long): Deferred<List<StatSeries>> { val preferences = PreferenceManager.getDefaultSharedPreferences(context) val includeOpen = Settings.BooleanSetting.IncludeOpen.getValue(preferences) val includeEvents = Settings.BooleanSetting.IncludeEvents.getValue(preferences) val query = ("SELECT " + queryFields + "FROM ${LeagueEntry.TABLE_NAME} as league " + "INNER JOIN ${SeriesEntry.TABLE_NAME} as series " + "ON league.${LeagueEntry._ID}=${SeriesEntry.COLUMN_LEAGUE_ID} " + "INNER JOIN ${GameEntry.TABLE_NAME} as game " + "ON series.${SeriesEntry._ID}=game.${GameEntry.COLUMN_SERIES_ID} " + "INNER JOIN ${FrameEntry.TABLE_NAME} as frame " + "ON game.${GameEntry._ID}=frame.${FrameEntry.COLUMN_GAME_ID} " + "WHERE league.${LeagueEntry.COLUMN_BOWLER_ID}=? " + (if (!includeOpen) "AND league.${LeagueEntry.COLUMN_LEAGUE_NAME}!=? " else "") + (if (!includeEvents) "AND league.${LeagueEntry.COLUMN_IS_EVENT}!=? " else "") + "ORDER BY " + "series.${SeriesEntry.COLUMN_SERIES_DATE}, " + "series.${SeriesEntry._ID}, " + "game.${GameEntry.COLUMN_GAME_NUMBER}, " + "frame.${FrameEntry.COLUMN_FRAME_NUMBER}") val args = listOfNotNull( bowlerId.toString(), if (!includeOpen) League.PRACTICE_LEAGUE_NAME else null, if (!includeEvents) "1" else null ).toTypedArray() return loadSeries(context, query, args) } fun loadSeriesForLeague(context: Context, leagueId: Long): Deferred<List<StatSeries>> { val query = ("SELECT " + queryFields + "FROM ${SeriesEntry.TABLE_NAME} as series " + "INNER JOIN ${GameEntry.TABLE_NAME} as game " + "ON series.${SeriesEntry._ID}=game.${GameEntry.COLUMN_SERIES_ID} " + "INNER JOIN ${FrameEntry.TABLE_NAME} as frame " + "ON game.${GameEntry._ID}=frame.${FrameEntry.COLUMN_GAME_ID} " + "WHERE series.${SeriesEntry.COLUMN_LEAGUE_ID}=? " + "ORDER BY " + "series.${SeriesEntry.COLUMN_SERIES_DATE}, " + "series.${SeriesEntry._ID}, " + "game.${GameEntry.COLUMN_GAME_NUMBER}, " + "frame.${FrameEntry.COLUMN_FRAME_NUMBER}") val args = arrayOf(leagueId.toString()) return loadSeries(context, query, args) } fun loadSeriesForSeries(context: Context, seriesId: Long): Deferred<List<StatSeries>> { val query = ("SELECT " + queryFields + "FROM ${SeriesEntry.TABLE_NAME} as series " + "INNER JOIN ${GameEntry.TABLE_NAME} as game " + "ON series.${SeriesEntry._ID}=game.${GameEntry.COLUMN_SERIES_ID} " + "INNER JOIN ${FrameEntry.TABLE_NAME} as frame " + "ON game.${GameEntry._ID}=frame.${FrameEntry.COLUMN_GAME_ID} " + "WHERE series.${SeriesEntry._ID}=? " + "ORDER BY game.${GameEntry.COLUMN_GAME_NUMBER}, frame.${FrameEntry.COLUMN_FRAME_NUMBER}") val args = arrayOf(seriesId.toString()) return loadSeries(context, query, args) } private fun loadSeries(context: Context, query: String, args: Array<String>): Deferred<List<StatSeries>> { return async(CommonPool) { val db = DatabaseHelper.getInstance(context).writableDatabase var lastGameId: Long = -1 var lastSeriesId: Long = -1 val series: MutableList<StatSeries> = ArrayList() var games: MutableList<StatGame> = ArrayList(League.MAX_NUMBER_OF_GAMES) var frames: MutableList<StatFrame> = ArrayList(Game.NUMBER_OF_FRAMES) fun buildSeriesFromCursor(cursor: Cursor): StatSeries { return StatSeries( id = cursor.getLong(cursor.getColumnIndex("sid")), games = games, date = DateUtils.seriesDateToDate(cursor.getString(cursor.getColumnIndex(SeriesEntry.COLUMN_SERIES_DATE))) ) } fun buildGameFromCursor(cursor: Cursor): StatGame { return StatGame( id = cursor.getLong(cursor.getColumnIndex("gid")), ordinal = cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_GAME_NUMBER)), score = cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_SCORE)), isManual = cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_IS_MANUAL)) == 1, frames = frames, matchPlay = MatchPlayResult.fromInt(cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_MATCH_PLAY)))!! ) } var cursor: Cursor? = null try { cursor = db.rawQuery(query, args, null) if (cursor.moveToFirst()) { while (!cursor.isAfterLast) { val newGameId = cursor.getLong(cursor.getColumnIndex("gid")) if (newGameId != lastGameId && lastGameId != -1L) { cursor.moveToPrevious() games.add(buildGameFromCursor(cursor)) frames = ArrayList(Game.NUMBER_OF_FRAMES) cursor.moveToNext() } val newSeriesId = cursor.getLong(cursor.getColumnIndex("sid")) if (newSeriesId != lastSeriesId && lastSeriesId != -1L) { cursor.moveToPrevious() series.add(buildSeriesFromCursor(cursor)) games = ArrayList(League.MAX_NUMBER_OF_GAMES) cursor.moveToNext() } frames.add(StatFrame( id = cursor.getLong(cursor.getColumnIndex("fid")), ordinal = cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_FRAME_NUMBER)), isAccessed = cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_IS_ACCESSED)) == 1, pinState = Array(Frame.NUMBER_OF_BALLS) { return@Array Pin.deckFromInt(cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_PIN_STATE[it]))) }, ballFouled = BooleanArray(Frame.NUMBER_OF_BALLS) { return@BooleanArray Fouls.foulIntToString(cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_FOULS))).contains((it + 1).toString()) } )) lastSeriesId = newSeriesId lastGameId = newGameId cursor.moveToNext() } cursor.moveToPrevious() games.add(buildGameFromCursor(cursor)) series.add(buildSeriesFromCursor(cursor)) } } finally { cursor?.close() } return@async series } } } }
mit
4d83a96216204e359ac90db0fc60376c
50.511719
174
0.561159
4.950075
false
false
false
false
googlecodelabs/android-compose-codelabs
AdaptiveUICodelab/app/src/main/java/com/example/reply/data/local/LocalEmailsDataProvider.kt
1
13456
/* * 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 * * 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.example.reply.data.local import com.example.reply.R import com.example.reply.data.Email import com.example.reply.data.EmailAttachment import com.example.reply.data.MailboxType /** * A static data store of [Email]s. */ object LocalEmailsDataProvider { private val threads = listOf( Email( 4L, LocalAccountsDataProvider.getContactAccountByUid(11L), listOf( LocalAccountsDataProvider.getDefaultUserAccount(), LocalAccountsDataProvider.getContactAccountByUid(8L), LocalAccountsDataProvider.getContactAccountByUid(5L) ), "Brazil trip", """ Thought we might be able to go over some details about our upcoming vacation. I've been doing a bit of research and have come across a few paces in Northern Brazil that I think we should check out. One, the north has some of the most predictable wind on the planet. I'd love to get out on the ocean and kitesurf for a couple of days if we're going to be anywhere near or around Taiba. I hear it's beautiful there and if you're up for it, I'd love to go. Other than that, I haven't spent too much time looking into places along our road trip route. I'm assuming we can find places to stay and things to do as we drive and find places we think look interesting. But... I know you're more of a planner, so if you have ideas or places in mind, lets jot some ideas down! Maybe we can jump on the phone later today if you have a second. """.trimIndent(), createAt = "2 hours ago", isStarred = true ), Email( 5L, LocalAccountsDataProvider.getContactAccountByUid(13L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Update to Your Itinerary", "", createAt = "2 hours ago", ), Email( 6L, LocalAccountsDataProvider.getContactAccountByUid(10L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Recipe to try", "Raspberry Pie: We should make this pie recipe tonight! The filling is " + "very quick to put together.", createAt = "2 hours ago", mailbox = MailboxType.SENT ), Email( 7L, LocalAccountsDataProvider.getContactAccountByUid(9L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Delivered", "Your shoes should be waiting for you at home!", createAt = "2 hours ago", ), Email( 8L, LocalAccountsDataProvider.getContactAccountByUid(13L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Your update on Google Play Store is live!", """ Your update, 0.1.1, is now live on the Play Store and available for your alpha users to start testing. Your alpha testers will be automatically notified. If you'd rather send them a link directly, go to your Google Play Console and follow the instructions for obtaining an open alpha testing link. """.trimIndent(), mailbox = MailboxType.TRASH, createAt = "3 hours ago", ), Email( 9L, LocalAccountsDataProvider.getContactAccountByUid(10L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "(No subject)", """ Hey, Wanted to email and see what you thought of """.trimIndent(), createAt = "3 hours ago", mailbox = MailboxType.DRAFTS ) ) val allEmails = mutableListOf( Email( 0L, LocalAccountsDataProvider.getContactAccountByUid(9L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Package shipped!", """ Cucumber Mask Facial has shipped. Keep an eye out for a package to arrive between this Thursday and next Tuesday. If for any reason you don't receive your package before the end of next week, please reach out to us for details on your shipment. As always, thank you for shopping with us and we hope you love our specially formulated Cucumber Mask! """.trimIndent(), createAt = "20 mins ago", isStarred = true, threads = threads, ), Email( 1L, LocalAccountsDataProvider.getContactAccountByUid(6L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Brunch this weekend?", """ I'll be in your neighborhood doing errands and was hoping to catch you for a coffee this Saturday. If you don't have anything scheduled, it would be great to see you! It feels like its been forever. If we do get a chance to get together, remind me to tell you about Kim. She stopped over at the house to say hey to the kids and told me all about her trip to Mexico. Talk to you soon, Ali """.trimIndent(), createAt = "40 mins ago", threads = threads, ), Email( 2L, LocalAccountsDataProvider.getContactAccountByUid(5L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Bonjour from Paris", "Here are some great shots from my trip...", listOf( EmailAttachment(R.drawable.paris_1, "Bridge in Paris"), EmailAttachment(R.drawable.paris_2, "Bridge in Paris at night"), EmailAttachment(R.drawable.paris_3, "City street in Paris"), EmailAttachment(R.drawable.paris_4, "Street with bike in Paris") ), true, createAt = "1 hour ago", threads = threads, ), Email( 3L, LocalAccountsDataProvider.getContactAccountByUid(8L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "High school reunion?", """ Hi friends, I was at the grocery store on Sunday night.. when I ran into Genie Williams! I almost didn't recognize her afer 20 years! Anyway, it turns out she is on the organizing committee for the high school reunion this fall. I don't know if you were planning on going or not, but she could definitely use our help in trying to track down lots of missing alums. If you can make it, we're doing a little phone-tree party at her place next Saturday, hoping that if we can find one person, thee more will... """.trimIndent(), createAt = "2 hours ago", mailbox = MailboxType.SENT ), Email( 4L, LocalAccountsDataProvider.getContactAccountByUid(11L), listOf( LocalAccountsDataProvider.getDefaultUserAccount(), LocalAccountsDataProvider.getContactAccountByUid(8L), LocalAccountsDataProvider.getContactAccountByUid(5L) ), "Brazil trip", """ Thought we might be able to go over some details about our upcoming vacation. I've been doing a bit of research and have come across a few paces in Northern Brazil that I think we should check out. One, the north has some of the most predictable wind on the planet. I'd love to get out on the ocean and kitesurf for a couple of days if we're going to be anywhere near or around Taiba. I hear it's beautiful there and if you're up for it, I'd love to go. Other than that, I haven't spent too much time looking into places along our road trip route. I'm assuming we can find places to stay and things to do as we drive and find places we think look interesting. But... I know you're more of a planner, so if you have ideas or places in mind, lets jot some ideas down! Maybe we can jump on the phone later today if you have a second. """.trimIndent(), createAt = "2 hours ago", isStarred = true ), Email( 5L, LocalAccountsDataProvider.getContactAccountByUid(13L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Update to Your Itinerary", "", createAt = "2 hours ago", ), Email( 6L, LocalAccountsDataProvider.getContactAccountByUid(10L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Recipe to try", "Raspberry Pie: We should make this pie recipe tonight! The filling is " + "very quick to put together.", createAt = "2 hours ago", mailbox = MailboxType.SENT ), Email( 7L, LocalAccountsDataProvider.getContactAccountByUid(9L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Delivered", "Your shoes should be waiting for you at home!", createAt = "2 hours ago", ), Email( 8L, LocalAccountsDataProvider.getContactAccountByUid(13L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Your update on Google Play Store is live!", """ Your update, 0.1.1, is now live on the Play Store and available for your alpha users to start testing. Your alpha testers will be automatically notified. If you'd rather send them a link directly, go to your Google Play Console and follow the instructions for obtaining an open alpha testing link. """.trimIndent(), mailbox = MailboxType.TRASH, createAt = "3 hours ago", ), Email( 9L, LocalAccountsDataProvider.getContactAccountByUid(10L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "(No subject)", """ Hey, Wanted to email and see what you thought of """.trimIndent(), createAt = "3 hours ago", mailbox = MailboxType.DRAFTS ), Email( 10L, LocalAccountsDataProvider.getContactAccountByUid(5L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Try a free TrailGo account", """ Looking for the best hiking trails in your area? TrailGo gets you on the path to the outdoors faster than you can pack a sandwich. Whether you're an experienced hiker or just looking to get outside for the afternoon, there's a segment that suits you. """.trimIndent(), createAt = "3 hours ago", mailbox = MailboxType.TRASH ), Email( 11L, LocalAccountsDataProvider.getContactAccountByUid(5L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Free money", """ You've been selected as a winner in our latest raffle! To claim your prize, click on the link. """.trimIndent(), createAt = "3 hours ago", mailbox = MailboxType.SPAM ) ) /** * Get an [Email] with the given [id]. */ fun get(id: Long): Email? { return allEmails.firstOrNull { it.id == id } } /** * Create a new, blank [Email]. */ fun create(): Email { return Email( System.nanoTime(), // Unique ID generation. LocalAccountsDataProvider.getDefaultUserAccount(), createAt = "Just now", ) } /** * Create a new [Email] that is a reply to the email with the given [replyToId]. */ fun createReplyTo(replyToId: Long): Email { val replyTo = get(replyToId) ?: return create() return Email( id = System.nanoTime(), sender = replyTo.recipients.firstOrNull() ?: LocalAccountsDataProvider.getDefaultUserAccount(), recipients = listOf(replyTo.sender) + replyTo.recipients, subject = replyTo.subject, isStarred = replyTo.isStarred, isImportant = replyTo.isImportant, createAt = "Just now", ) } /** * Get a list of [EmailFolder]s by which [Email]s can be categorized. */ fun getAllFolders() = listOf( "Receipts", "Pine Elementary", "Taxes", "Vacation", "Mortgage", "Grocery coupons" ) }
apache-2.0
0c1adb8f29556831ef9c3ee1ecd96cd0
41.853503
703
0.600178
4.833333
false
false
false
false
AsynkronIT/protoactor-kotlin
proto-actor/src/main/kotlin/actor/proto/OneForOneStrategy.kt
1
1804
package actor.proto import mu.KotlinLogging import java.time.Duration private val logger = KotlinLogging.logger {} class OneForOneStrategy(private val decider: (PID, Exception) -> SupervisorDirective, private val maxNrOfRetries: Int, private val withinTimeSpan: Duration? = null) : SupervisorStrategy { override fun handleFailure(supervisor: Supervisor, child: PID, rs: RestartStatistics, reason: Exception) { val directive: SupervisorDirective = decider(child, reason) when (directive) { SupervisorDirective.Resume -> supervisor.resumeChildren(child) SupervisorDirective.Restart -> { if (requestRestartPermission(rs)) { logger.debug("Restarting ${child.toShortString()} Reason $reason") supervisor.restartChildren(reason, child) } else { logger.debug("Stopping ${child.toShortString()} Reason $reason") supervisor.stopChildren(child) } } SupervisorDirective.Stop -> { logger.debug("Stopping ${child.toShortString()} Reason $reason") supervisor.stopChildren(child) } SupervisorDirective.Escalate -> supervisor.escalateFailure(reason, child) } } private fun requestRestartPermission(rs: RestartStatistics): Boolean { return when (maxNrOfRetries) { 0 -> false else -> { rs.fail() when { withinTimeSpan == null || rs.isWithinDuration(withinTimeSpan) -> rs.failureCount <= maxNrOfRetries else -> { rs.reset() true } } } } } }
apache-2.0
d3755b721aa0085fa33832c5e2a5a203
40.953488
187
0.569845
5.169054
false
false
false
false
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/53.HelloKotlin-函数式编程.kt
1
1240
package com.zj.example.kotlin.shengshiyuan.helloworld /** * 函数式编程 * * CreateTime: 18/5/29 08:41 * @author 郑炯 */ fun main(vararg args: String) { val e = HelloKotlin53() /** * 在默认情况下,lambda表达式中最后一个表达式的值,会隐式作为该lambda表达式的返回值, * 但是我们也可以通过全限定的return语法来显示从lambda表达式来返回值. */ val addValue1 = e.myCalculate(1, 2, { a, b -> return@myCalculate a + b }) /** * 在默认情况下,lambda表达式中最后一个表达式的值,会隐式作为该lambda表达式的返回值, * 但是我们也可以通过全限定的return语法来显示从lambda表达式来返回值. */ val addValue2 = e.myCalculate(1, 2, { a, b -> a + b //最后一个表达式的值 }) val addValue3 = e.myCalculate(1, 2, { a, b -> a + b }) val addValue4 = e.myCalculate(1, 2) { a, b -> a + b } println("add->$addValue1") println("add->$addValue2") println("add->$addValue3") println("add->$addValue4") } class HelloKotlin53 { fun myCalculate(a: Int, b: Int, calculate: (Int, Int) -> Int): Int { return calculate(a, b) } }
mit
30cbc1e65afeb158af8e4f2395456d42
20.23913
72
0.597336
2.870588
false
false
false
false
jabbink/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/tasks/ReleasePokemon.kt
2
4278
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.tasks import POGOProtos.Networking.Responses.ReleasePokemonResponseOuterClass.ReleasePokemonResponse.Result import ink.abb.pogo.api.util.PokemonMetaRegistry import ink.abb.pogo.scraper.Bot import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.Task import ink.abb.pogo.scraper.util.Log import ink.abb.pogo.scraper.util.pokemon.getIv import ink.abb.pogo.scraper.util.pokemon.getIvPercentage import ink.abb.pogo.scraper.util.pokemon.shouldTransfer import java.util.concurrent.atomic.AtomicInteger class ReleasePokemon : Task { override fun run(bot: Bot, ctx: Context, settings: Settings) { val pokemonMap = ctx.api.inventory.pokemon // prevent concurrent modification exception val groupedPokemon = pokemonMap.map { it.value }.groupBy { it.pokemonData.pokemonId } val sortByIV = settings.sortByIv val pokemonCounts = hashMapOf<String, Int>() groupedPokemon.forEach { val sorted = if (sortByIV) { it.value.sortedByDescending { it.pokemonData.getIv() } } else { it.value.sortedByDescending { it.pokemonData.cp } } for ((index, pokemon) in sorted.withIndex()) { // don't drop favorited, deployed, or nicknamed pokemon val isFavourite = pokemon.pokemonData.nickname.isNotBlank() || pokemon.pokemonData.favorite != 0 || !pokemon.pokemonData.deployedFortId.isEmpty() || (ctx.api.playerData.hasBuddyPokemon() && ctx.api.playerData.buddyPokemon.id == pokemon.pokemonData.id) if (!isFavourite) { val ivPercentage = pokemon.pokemonData.getIvPercentage() // never transfer highest rated Pokemon (except for obligatory transfer) if (settings.obligatoryTransfer.contains(pokemon.pokemonData.pokemonId) || index >= settings.keepPokemonAmount) { val (shouldRelease, reason) = pokemon.pokemonData.shouldTransfer(settings, pokemonCounts, bot.api.inventory.candies.getOrPut(PokemonMetaRegistry.getMeta(pokemon.pokemonData.pokemonId).family, { AtomicInteger(0) })) if (shouldRelease) { Log.yellow("Going to transfer ${pokemon.pokemonData.pokemonId.name} with " + "CP ${pokemon.pokemonData.cp} and IV $ivPercentage%; reason: $reason") val result = bot.api.queueRequest(ink.abb.pogo.api.request.ReleasePokemon().withPokemonId(pokemon.pokemonData.id)).toBlocking().first().response if (result.result == Result.SUCCESS) { Log.green("Successfully transfered ${pokemon.pokemonData.pokemonId.name} with " + "CP ${pokemon.pokemonData.cp} and IV $ivPercentage%") if (ctx.pokemonInventoryFullStatus.get()) { // Just released a pokemon so the inventory is not full anymore ctx.pokemonInventoryFullStatus.set(false) if (settings.catchPokemon) Log.green("Inventory freed, enabling catching of pokemon") } ctx.pokemonStats.second.andIncrement ctx.server.releasePokemon(pokemon.pokemonData.id) ctx.server.sendProfile() } else { Log.red("Failed to transfer ${pokemon.pokemonData.pokemonId.name}: ${result.result}") } } } } } } } }
gpl-3.0
d22bc5018f48747be6dc8e5c04bc8403
54.558442
172
0.592099
5.044811
false
false
false
false
lijunzz/LongChuanGang
ui/src/main/kotlin/net/junzz/app/ui/widget/RoundAvatar.kt
1
2941
package net.junzz.app.ui.widget import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.drawable.LayerDrawable import android.support.annotation.ColorInt import android.support.v4.content.ContextCompat import android.support.v7.widget.AppCompatImageView import android.util.AttributeSet import android.view.View import net.junzz.app.ui.R import net.junzz.app.ui.view.RoundDrawable import net.junzz.app.util.ImageUtils import net.junzz.app.util.LogUtils /** * 圆形头像 */ class RoundAvatar : AppCompatImageView { constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private val defaultDrawable = RoundDrawable(Color.GRAY) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val minimumWidth = suggestedMinimumWidth val minimumHeight = suggestedMinimumHeight var viewWidth = resolveMeasured(widthMeasureSpec, minimumWidth) var viewHeight = resolveMeasured(heightMeasureSpec, minimumHeight) viewHeight = Math.min(viewWidth, viewHeight) viewWidth = viewHeight setMeasuredDimension(viewWidth, viewHeight) // 设置 Drawable 的宽高,否则直接使用将不显示 defaultDrawable.intrinsicWidth = viewWidth defaultDrawable.intrinsicHeight = viewHeight } private fun resolveMeasured(measureSpec: Int, desired: Int): Int { val result: Int val specSize = View.MeasureSpec.getSize(measureSpec) when (View.MeasureSpec.getMode(measureSpec)) { View.MeasureSpec.UNSPECIFIED -> result = desired View.MeasureSpec.AT_MOST -> result = Math.max(specSize, desired) View.MeasureSpec.EXACTLY -> result = specSize else -> result = specSize } return result } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) LogUtils.debug("onDraw::$drawable") // 默认圆 // 将会打印 Log 两次,Java 版只打印一次 if (drawable == null) { setImageDrawable(defaultDrawable) } } private fun avatarDrawable(@ColorInt color: Int): LayerDrawable { val bgDrawable = RoundDrawable(color) val personDrawable = ContextCompat.getDrawable(context, R.drawable.ic_person_white_24dp) val layers = arrayOf(bgDrawable, personDrawable) return LayerDrawable(layers) } /** * 设置头像 */ fun setImageAvatar(avatar: String) { try { val avatarColor = Color.parseColor(avatar) setImageDrawable(avatarDrawable(avatarColor)) } catch (e: Exception) { ImageUtils.showAvatar(this, avatar, this) } } }
gpl-3.0
47cd396e9b639e8e1e3482e559a8b6b6
31.511364
112
0.689969
4.512618
false
false
false
false
spaceisstrange/ToListen
ToListen/app/src/main/java/io/spaceisstrange/tolisten/ui/fragments/songs/SongsFragment.kt
1
2751
/* * Made with <3 by Fran González (@spaceisstrange) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package io.spaceisstrange.tolisten.ui.fragments.songs import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.realm.Realm import io.realm.RealmChangeListener import io.spaceisstrange.tolisten.R import io.spaceisstrange.tolisten.data.database.Database import io.spaceisstrange.tolisten.data.model.Song import io.spaceisstrange.tolisten.ui.adapters.SongsAdapter import kotlinx.android.synthetic.main.fragment_base_list.* /** * Fragment showing the list of songs stored */ class SongsFragment : Fragment() { /** * Adapter used in the list */ var albumAdapter: SongsAdapter = SongsAdapter() /** * Listener of the Realm database */ lateinit var realmListener: RealmChangeListener<Realm> override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_base_list, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Setup the ReyclerView albumAdapter.onClick = { song -> // TODO: Do something with the song } savedList.adapter = albumAdapter savedList.layoutManager = LinearLayoutManager(context) // Load the data from the database albumAdapter.updateSongs(loadData()) // Add a listener to the database so we update the data whenever we add new things realmListener = RealmChangeListener { realm -> albumAdapter.updateSongs(loadData()) } Realm.getDefaultInstance().addChangeListener(realmListener) } /** * Loads and returns the data from the database */ fun loadData(): List<Song> { return Database.getSongs() } }
gpl-3.0
f7ad653df8637267a13e03d2c4f7a0b9
32.962963
116
0.721455
4.330709
false
false
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/chmod.kt
1
3917
/* * Copyright 2016 Karl Tauber * * 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.devcharly.kotlin.ant import org.apache.tools.ant.taskdefs.Chmod import org.apache.tools.ant.taskdefs.ExecuteOn import org.apache.tools.ant.types.Environment.Variable import org.apache.tools.ant.types.ResourceCollection import org.apache.tools.ant.util.FileNameMapper /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ fun Ant.chmod( file: String? = null, dir: String? = null, perm: String? = null, includes: String? = null, excludes: String? = null, defaultexcludes: Boolean? = null, parallel: Boolean? = null, type: FileDirBoth? = null, maxparallel: Int? = null, verbose: Boolean? = null, os: String? = null, osfamily: String? = null, nested: (KChmod.() -> Unit)? = null) { Chmod().execute("chmod") { task -> if (file != null) task.setFile(project.resolveFile(file)) if (dir != null) task.setDir(project.resolveFile(dir)) if (perm != null) task.setPerm(perm) if (includes != null) task.setIncludes(includes) if (excludes != null) task.setExcludes(excludes) if (defaultexcludes != null) task.setDefaultexcludes(defaultexcludes) if (parallel != null) task.setParallel(parallel) if (type != null) task.setType(ExecuteOn.FileDirBoth().apply { this.value = type.value }) if (maxparallel != null) task.setMaxParallel(maxparallel) if (verbose != null) task.setVerbose(verbose) if (os != null) task.setOs(os) if (osfamily != null) task.setOsFamily(osfamily) if (nested != null) nested(KChmod(task)) } } class KChmod(override val component: Chmod) : IFileNameMapperNested, IResourceCollectionNested { fun env(key: String? = null, value: String? = null, path: String? = null, file: String? = null) { component.addEnv(Variable().apply { _init(component.project, key, value, path, file) }) } fun arg(value: String? = null, line: String? = null, path: String? = null, pathref: String? = null, file: String? = null, prefix: String? = null, suffix: String? = null) { component.createArg().apply { component.project.setProjectReference(this) _init(value, line, path, pathref, file, prefix, suffix) } } fun srcfile(prefix: String? = null, suffix: String? = null) { component.createSrcfile().apply { _init(prefix, suffix) } } fun targetfile(prefix: String? = null, suffix: String? = null) { component.createTargetfile().apply { _init(prefix, suffix) } } fun include(name: String? = null, If: String? = null, unless: String? = null) { component.createInclude().apply { _init(name, If, unless) } } fun exclude(name: String? = null, If: String? = null, unless: String? = null) { component.createExclude().apply { _init(name, If, unless) } } fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) { component.createPatternSet().apply { component.project.setProjectReference(this) _init(includes, excludes, includesfile, excludesfile, nested) } } override fun _addFileNameMapper(value: FileNameMapper) = component.add(value) override fun _addResourceCollection(value: ResourceCollection) = component.add(value) }
apache-2.0
3f92cce7bba8d2beb73cfd5cf2784248
32.478632
172
0.671688
3.373816
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/util/TimeExpiringCache.kt
1
3745
/* * 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.nlj.util import java.time.Clock import java.time.Duration import java.util.TreeMap /** * A cache which holds an arbitrary [DataType] and stores it, as well * as the time at which it was added to the cache. On updates, it will * check to prune itself to remove anything older than the configured * timeout. * NOTE: it's possible the pruning does not remove ALL elements older * than the configured timeout as we store the elements according to * the value of their [IndexType], not their insertion timestamp. * This is because retrieval is much handier when done via the value * of [IndexType]. This means that it's possible older values will * not be pruned when expected, but if the ordering of [IndexType] * roughly follows the insertion order, it should not be too bad. */ class TimeExpiringCache<IndexType, DataType>( /** * The amount of time after which an element should be pruned from the cache */ private val dataTimeout: Duration, /** * The maximum amount of elements we'll allow in the cache */ private val maxNumElements: Int, private val clock: Clock = Clock.systemUTC() ) { private val cache: TreeMap<IndexType, Container<DataType>> = TreeMap() fun insert(index: IndexType, data: DataType) { val container = Container(data, clock.millis()) synchronized(cache) { cache[index] = container clean(clock.millis() - dataTimeout.toMillis()) } } fun get(index: IndexType): DataType? { synchronized(cache) { val container = cache.getOrDefault(index, null) ?: return null return container.data } } /** * For each element in this cache, in descending order of the value of their * [IndexType], run the given [predicate]. If [predicate] returns false, stop * the iteration. */ fun forEachDescending(predicate: (DataType) -> Boolean) { synchronized(cache) { val iter = cache.descendingMap().iterator() while (iter.hasNext()) { val (_, container) = iter.next() if (!predicate(container.data)) { break } } } } private fun clean(expirationTimestamp: Long) { synchronized(cache) { val iter = cache.entries.iterator() while (iter.hasNext()) { val (_, container) = iter.next() if (cache.size > maxNumElements) { iter.remove() } else if (container.timeAdded <= expirationTimestamp) { iter.remove() } else { // We'll break out of the loop once we find an insertion time that // is not older than the expiration cutoff break } } } } /** * Holds an instance of [Type] as well as when it was * added to the data structure so that we can time out * old [Container]s */ private data class Container<Type>(var data: Type, var timeAdded: Long) }
apache-2.0
d7649850c3d1940d123dae08922b84e2
34.666667
86
0.622163
4.501202
false
false
false
false
siempredelao/Distance-From-Me-Android
app/src/main/java/gc/david/dfm/DefaultConnectionManager.kt
1
1205
/* * Copyright (c) 2019 David Aguiar Gonzalez * * 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 gc.david.dfm import android.content.Context import android.net.ConnectivityManager import gc.david.dfm.adapter.systemService /** * Created by david on 10.01.17. */ class DefaultConnectionManager(private val context: Context) : ConnectionManager { override fun isOnline(): Boolean = isOnline(context) private fun isOnline(context: Context): Boolean { val connectivityManager = context.systemService<ConnectivityManager>(Context.CONNECTIVITY_SERVICE) val networkInfo = connectivityManager.activeNetworkInfo return networkInfo?.isConnected == true } }
apache-2.0
e4c4a79afe469c4fcdb14eb38febf5c8
33.428571
106
0.751037
4.513109
false
false
false
false
wenhaiz/ListenAll
app/src/main/java/com/wenhaiz/himusic/utils/OkHttpUtil.kt
1
5385
package com.wenhaiz.himusic.utils import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.os.Bundle import android.util.Log import com.wenhaiz.himusic.common.Config import okhttp3.Call import okhttp3.Callback import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.json.JSONArray import org.json.JSONObject import java.io.IOException import java.util.concurrent.TimeUnit object OkHttpUtil { const val TAG = "OkHttpUtil" private const val NETWORK_NOT_AVAILABLE = 0 const val NETWORK_AVAILABLE = 1 const val ARG_NETWORK_STATE = "state" const val ARG_NETWORK_DESC = "msg" @JvmStatic private var client: OkHttpClient? = null @JvmStatic fun getHttpClient(): OkHttpClient { if (client == null) { synchronized(OkHttpUtil::class.java) { if (client == null) { client = OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .build() } } } return client as OkHttpClient } @JvmStatic fun checkNetWork(context: Context): Bundle { val conn: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork: NetworkInfo? = conn.activeNetworkInfo val connect = if (activeNetwork != null && activeNetwork.isConnected) { activeNetwork.type } else { -1 } val bundle = Bundle() if (connect != -1) {//有网络连接 val sp = context.getSharedPreferences(Config.NAME, Context.MODE_PRIVATE) val onlyWifi = sp.getBoolean(Config.ONLY_WIFI, false) //如果网络可用 if (onlyWifi && connect == ConnectivityManager.TYPE_WIFI || !onlyWifi) { bundle.putInt(ARG_NETWORK_STATE, NETWORK_AVAILABLE) } else { bundle.putInt(ARG_NETWORK_STATE, NETWORK_NOT_AVAILABLE) bundle.putString(ARG_NETWORK_DESC, "非wifi网络自动停止加载") } } else {//没有网络连接 bundle.putInt(ARG_NETWORK_STATE, NETWORK_NOT_AVAILABLE) bundle.putString(ARG_NETWORK_DESC, "没有网络") } return bundle } @JvmStatic fun getForXiami(context: Context, url: String, callback: ResponseCallBack) { //start request LogUtil.d(TAG, url) callback.onStart() val networkData = checkNetWork(context) if (networkData.getInt("state", 0) == 0) { callback.onFailure(networkData.getString("msg")) LogUtil.e("test", networkData.getString("msg")) return } val request = Request.Builder() .url(url) .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8") .addHeader("Connection", "keep-alive") .addHeader("Upgrade-Insecure-Requests", "1") .addHeader("Referer", "http://m.xiami.com/") .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36") .get() .build() val newCall = getHttpClient().newCall(request) newCall.enqueue(object : Callback { override fun onFailure(call: Call?, e: IOException?) { if (e != null) { callback.onFailure("请求失败") getHttpClient().dispatcher().cancelAll() } } override fun onResponse(call: Call?, response: Response?) { if (response == null) { callback.onFailure("response == null") } else { val body = response.body()!!.string() when { body.startsWith("jsonp") -> { val realJsonStr = body.substring(body.indexOf("(") + 1, body.lastIndexOf(")")) callback.onJsonObjectResponse(JSONObject(realJsonStr).getJSONObject("data")) } body.startsWith("{") -> callback.onJsonObjectResponse(JSONObject(body)) body.contains("</") -> callback.onHtmlResponse(body) else -> { Log.d(TAG, "$body ") callback.onFailure("response body:$body") } } } } }) } } abstract class BaseResponseCallback : ResponseCallBack { override fun onStart() { } override fun onResponse(response: Response) { } override fun onJsonObjectResponse(jsonObject: JSONObject) { } override fun onJsonArrayResponse(jsonArray: JSONArray) { } override fun onHtmlResponse(html: String) { } override fun onFailure(msg: String) { } } interface ResponseCallBack { fun onStart() fun onResponse(response: Response) fun onJsonObjectResponse(jsonObject: JSONObject) fun onJsonArrayResponse(jsonArray: JSONArray) fun onHtmlResponse(html: String) fun onFailure(msg: String) }
apache-2.0
f9a547d4c04f09835baf98b3058e91d7
32.031056
159
0.573444
4.659947
false
false
false
false