repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
stephanenicolas/heatControl
app/src/main/java/com/github/stephanenicolas/heatcontrol/features/setting/ui/SettingView.kt
1
4884
package com.github.stephanenicolas.heatcontrol.features.setting.ui import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.CompoundButton.OnCheckedChangeListener import android.widget.EditText import android.widget.FrameLayout import butterknife.BindView import butterknife.ButterKnife import com.github.stephanenicolas.heatcontrol.R import com.github.stephanenicolas.heatcontrol.features.control.state.Host import com.github.stephanenicolas.heatcontrol.features.control.state.SettingState import com.github.stephanenicolas.heatcontrol.features.control.state.SettingStore import com.github.stephanenicolas.heatcontrol.features.control.usecases.SettingController import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject class SettingsView : FrameLayout { @Inject lateinit var settingStore: SettingStore @Inject lateinit var settingController: SettingController @BindView(R.id.edit_text_api_key_value) lateinit var apiKeyView: EditText @BindView(R.id.recycler_hosts) lateinit var recyclerView: RecyclerView @BindView(R.id.reset_button) lateinit var resetButton: Button @BindView(R.id.save_button) lateinit var saveButton: Button 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) { LayoutInflater.from(context).inflate(R.layout.settings_view, this) ButterKnife.bind(this) recyclerView.layoutManager = LinearLayoutManager(context) } override fun onAttachedToWindow() { super.onAttachedToWindow() settingStore.getStateObservable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::updateState) apiKeyView.setOnFocusChangeListener { v, hasFocus -> if(!hasFocus) settingController.setApiKey(apiKeyView.text.toString()) } resetButton.setOnClickListener { settingController.reset() } saveButton.setOnClickListener { settingController.save(settingStore.getState()) } } private fun updateState(state: SettingState) { apiKeyView.setText(state.key) recyclerView.adapter = HostListAdapter(state.hostList, settingController) } } class HostListAdapter(var hosts: List<Host>, var settingController: SettingController) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { val TYPE_HOST: Int = 0 val TYPE_ADD: Int = 1 override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { if (position < hosts.size) { val hostViewViewHolder: HostViewViewHolder = holder as HostViewViewHolder val host: Host = hosts[position] hostViewViewHolder.hostView.setHost(host) hostViewViewHolder.hostView.setSelectCallback(OnCheckedChangeListener { buttonView, isChecked -> settingController.setlectHost(position) }) hostViewViewHolder.hostView.setRenameCallBack(View.OnFocusChangeListener { view, hasFocus -> val name = hostViewViewHolder.hostView.getName() if (!hasFocus) settingController.renameHost(position, name) }) hostViewViewHolder.hostView.setChangeAddressCallBack(View.OnFocusChangeListener { view, hasFocus -> val address = hostViewViewHolder.hostView.getAddress() if (!hasFocus) settingController.changeAddressHost(position, address) }) hostViewViewHolder.hostView.setDeleteCallback(View.OnClickListener { settingController.removeHost(position) }) } else { val addNewHostViewHolder: AddNewHostViewHolder = holder as AddNewHostViewHolder addNewHostViewHolder.button.setOnClickListener { settingController.addHost() } } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val context: Context = parent!!.context when (viewType) { TYPE_HOST -> { return HostViewViewHolder(context) } else -> { return AddNewHostViewHolder(context) } } } override fun getItemCount(): Int { return hosts.size + 1 } override fun getItemViewType(position: Int): Int { if (position == hosts.size) { return TYPE_ADD } else { return TYPE_HOST } } }
apache-2.0
b95bf66373f3bd14f3a8234e3fac5852
39.363636
151
0.712121
5.130252
false
false
false
false
bubelov/coins-android
app/src/main/java/com/bubelov/coins/repository/synclogs/LogsRepository.kt
1
1187
package com.bubelov.coins.repository.synclogs import com.bubelov.coins.data.LogEntry import com.bubelov.coins.data.LogEntryQueries import com.squareup.sqldelight.runtime.coroutines.asFlow import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import java.time.LocalDateTime class LogsRepository( private val queries: LogEntryQueries ) { fun getAll() = queries.selectAll().asFlow().map { it.executeAsList() } fun append(tag: String = "", message: String) = runBlocking { withContext(Dispatchers.IO) { queries.insert( LogEntry( datetime = LocalDateTime.now().toString(), tag = tag, message = message ) ) } } operator fun plusAssign(entry: LogEntry) = runBlocking { queries.insert(entry) } operator fun plusAssign(message: String) { append("", message) } } fun Any.logEntry(message: String) = LogEntry( datetime = LocalDateTime.now().toString(), tag = this.javaClass.simpleName, message = message )
unlicense
b71e15eec7d1745d2f2a1dc2042a5ba0
27.285714
74
0.655434
4.654902
false
false
false
false
TonnyTao/Acornote
Acornote_Kotlin/app/src/main/java/tonnysunm/com/acornote/ui/colortag/ColorTagListAdapterHorizontal.kt
1
3717
package tonnysunm.com.acornote.ui.colortag import android.content.Intent import android.view.LayoutInflater import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.findFragment import androidx.lifecycle.viewModelScope import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.activity_note.* import kotlinx.coroutines.launch import tonnysunm.com.acornote.databinding.ListItemColortagHorizontalBinding import tonnysunm.com.acornote.databinding.ListItemEditBinding import tonnysunm.com.acornote.model.ColorTag import tonnysunm.com.acornote.ui.HomeActivity import tonnysunm.com.acornote.ui.note.NoteActivity import tonnysunm.com.acornote.ui.note.NoteFragment private const val ColorTagType = 0 private const val FooterType = 1 class ColorTagListAdapterHorizontal( var selectedColorTagColor: String?, var array: List<ColorTag> ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = if (viewType == ColorTagType) ViewHolder( ListItemColortagHorizontalBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ).apply { itemView.setOnClickListener { val data = array[this.absoluteAdapterPosition] val fragment = itemView.findFragment<ColorTagListFragmentHorizontal>() val activity = fragment.activity if (activity is HomeActivity) { fragment.navigateToNotesBy(data) } else if (activity is NoteActivity) { val noteFgm = activity.fragment_edit_note as NoteFragment val viewModal = noteFgm.viewModel viewModal.viewModelScope.launch { viewModal.updateColorTag(data) } } } } else EditViewHolder( ListItemEditBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ).apply { itemView.setOnClickListener { val fragment = it.findFragment<ColorTagListFragmentHorizontal>() val activity = fragment.activity ?: return@setOnClickListener val startForResult = activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == AppCompatActivity.RESULT_OK) { } } startForResult.launch(Intent(activity, ColorTagListActivity::class.java)) } } override fun getItemViewType(position: Int) = if (position < array.count()) ColorTagType else FooterType override fun getItemCount() = array.count() + 1 override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is ViewHolder) { val item = array[position] with(holder.binding) { checked = item.color == selectedColorTagColor data = item executePendingBindings() } } } /* ViewHolder */ inner class ViewHolder(val binding: ListItemColortagHorizontalBinding) : RecyclerView.ViewHolder(binding.root) inner class EditViewHolder(binding: ListItemEditBinding) : RecyclerView.ViewHolder(binding.root) }
apache-2.0
2f1477213451b6377ed40751366520c5
37.329897
110
0.630078
5.631818
false
false
false
false
nishtahir/fern
src/main/kotlin/com/nishtahir/fern/internal/FernTransform.kt
1
1854
package com.nishtahir.fern.internal import com.android.build.api.transform.* import com.nishtahir.fern.DecompilerOptionsExtension import org.gradle.api.Project import org.gradle.api.logging.LogLevel import java.io.File import java.util.* class FernTransform(private val project: Project, private val decompilerOptions: DecompilerOptionsExtension) : Transform() { override fun getName() = "fern-android" override fun getInputTypes(): MutableSet<QualifiedContent.ContentType> = Collections.singleton(QualifiedContent.DefaultContentType.CLASSES) override fun isIncremental() = false override fun getScopes(): MutableSet<in QualifiedContent.Scope> = Collections.singleton(QualifiedContent.Scope.PROJECT) override fun transform(invocation: TransformInvocation) { super.transform(invocation) invocation.context.logging.captureStandardOutput(LogLevel.INFO) val inputs = invocation.inputs.flatMap { it.jarInputs + it.directoryInputs } val outputs = inputs.map { input -> val format = if (input is JarInput) Format.JAR else Format.DIRECTORY invocation.outputProvider.getContentLocation( input.name, setOf(QualifiedContent.DefaultContentType.CLASSES), EnumSet.of(QualifiedContent.Scope.PROJECT), format ) } if (decompilerOptions.enabled) { val decompiler = FernDecompiler( sources = inputs.map { it.file }, outputPath = File("${project.buildDir}/decompiled-sources/${project.name}"), options = decompilerOptions ) decompiler.decompileContext() } inputs.zip(outputs) { input, output -> input.file.copyRecursively(output, true) } } }
apache-2.0
4ce7ccefc53da630e3d418d84e9bbd28
35.372549
143
0.666667
4.970509
false
false
false
false
AndroidX/constraintlayout
demoProjects/ExamplesComposeConstraintLayout/app/src/main/java/com/example/examplescomposeconstraintlayout/FlowKeyPad.kt
2
2009
package com.example.examplescomposeconstraintlayout import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.Wrap @Preview(group = "flow1") @Composable fun FlowPad() { val names = arrayOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#") Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Bottom, modifier = Modifier.fillMaxSize() ) { ConstraintLayout( ConstraintSet { val keys = names.map { createRefFor(it) }.toTypedArray() val flow = createFlow( elements = keys, maxElement = 3, wrapMode = Wrap.Aligned, verticalGap = 8.dp, horizontalGap = 8.dp ) constrain(flow) { centerTo(parent) } }, modifier = Modifier .background(Color(0xFFDAB539)) .padding(8.dp) ) { names.map { Button( modifier = Modifier.layoutId(it), onClick = {}, ) { Text(text = it) } } } } }
apache-2.0
80f8edd9886dbf5faf7418e5ad3069b1
33.067797
83
0.598308
4.948276
false
false
false
false
industrial-data-space/trusted-connector
ids-api/src/main/java/de/fhg/aisec/ids/api/router/RouteObject.kt
1
1653
/*- * ========================LICENSE_START================================= * ids-api * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.api.router /** * Bean representing a "route" (e.g., an Apache Camel route) * * @author Julian Schuette ([email protected]) */ class RouteObject { var status: String? = null var uptime: Long = 0 var context: String? = null var shortName: String? = null var dot: String? = null var description: String? = null var id: String? = null constructor() { /* Bean std c'tor */ } constructor( id: String?, description: String?, dot: String?, shortName: String?, context: String?, uptime: Long, status: String? ) { this.id = id this.description = description this.dot = dot this.shortName = shortName this.context = context this.uptime = uptime this.status = status } }
apache-2.0
b1a3a126423a73fbadcd4064c39c6c13
28
75
0.589232
4.282383
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/ClassLister.kt
1
3126
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.util import org.reflections.Reflections import uk.co.nickthecoder.paratask.parameters.GroupedChoiceParameter import uk.co.nickthecoder.tickle.scripts.ScriptManager import java.lang.reflect.Modifier object ClassLister { var reflectionsMap = mutableMapOf<String, Reflections>() private val cache = mutableMapOf<Class<*>, List<Class<*>>>() init { addPackage("uk.co.nickthecoder.tickle") } fun packages(packages: List<String>) { reflectionsMap.clear() packages.forEach { addPackage(it) } } fun addPackage(pack: String) { cache.clear() reflectionsMap[pack] = Reflections(pack) } fun subTypes(type: Class<*>): List<Class<*>> { val cached = cache[type] val results = mutableListOf<Class<*>>() if (cached != null) { results.addAll(cached) } else { // Find all compiled classes of the given type. i.e. NOT scripted languages. reflectionsMap.values.forEach { results.addAll(it.getSubTypesOf(type).filter { !it.isInterface && !Modifier.isAbstract(it.modifiers) }.sortedBy { it.name }) } cache[type] = results.toList() } // Find all scripted class of the given type results.addAll(ScriptManager.subTypes(type)) return results } fun setChoices(choiceParameter: GroupedChoiceParameter<Class<*>>, type: Class<*>) { val value = choiceParameter.value choiceParameter.clear() subTypes(type).groupBy { it.`package` }.forEach { pack, list -> val group = choiceParameter.group(pack?.name ?: "Top-Level") list.forEach { klass -> group.choice(klass.name, klass, klass.simpleName) } } choiceParameter.value = value } fun setNullableChoices(choiceParameter: GroupedChoiceParameter<Class<*>?>, type: Class<*>) { val value = choiceParameter.value choiceParameter.clear() choiceParameter.addChoice("", null, "<none>") subTypes(type).groupBy { it.`package` }.forEach { pack, list -> val group = choiceParameter.group(pack?.name ?: "Top-Level") list.forEach { klass -> group.choice(klass.name, klass, klass.simpleName) } } choiceParameter.value = value } fun clearCache() { cache.clear() } }
gpl-3.0
ef1f36f1aa68346e2fd4a26baf8aa69f
30.575758
140
0.648433
4.504323
false
false
false
false
kittinunf/ReactiveAndroid
sample/src/main/kotlin/com.github.kittinunf.reactiveandroid.sample/view/NestedRecyclerViewActivity.kt
1
1896
package com.github.kittinunf.reactiveandroid.sample.view import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import com.github.kittinunf.reactiveandroid.sample.R import kotlinx.android.synthetic.main.activity_nested_recycler_view.firstRecyclerView import kotlinx.android.synthetic.main.activity_nested_recycler_view.secondRecyclerView class NestedRecyclerViewActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nested_recycler_view) firstRecyclerView.apply { layoutManager = LinearLayoutManager(this@NestedRecyclerViewActivity) // rx_itemsWith(Observable.just(listOf(1, 2, 3, 4, 5, 6, 7, 8)), { parent, viewType -> // val v = LayoutInflater.from(parent?.context).inflate(android.R.layout.simple_list_item_1, parent, false) // ViewHolder(v) // }, { holder, position, item -> // holder.textView.text = item.toString() // }) } secondRecyclerView.apply { layoutManager = LinearLayoutManager(this@NestedRecyclerViewActivity) // rx_itemsWith(Observable.just(listOf(1, 2, 3, 4, 5, 6, 7, 8)), { parent, viewType -> // val v = LayoutInflater.from(parent?.context).inflate(android.R.layout.simple_list_item_1, parent, false) // ViewHolder(v) // }, { holder, position, item -> // holder.textView.text = item.toString() // }) } } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val textView by lazy { view.findViewById<TextView>(android.R.id.text1) } } }
mit
34bfaa1f0b5a85be692674aeebe520ba
41.133333
122
0.674051
4.148796
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/app/UndoManager.kt
1
1495
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.app object UndoManager : UndoManagerInterface { var undoState: UndoState? = null override fun addUndoState(state: UndoState) { synchronized(this) { undoState = state } } override fun undo() { synchronized(this) { undoState?.undo?.run() undoState = null } } override fun clearUndoState() { synchronized(this) { undoState?.dismiss?.run() undoState = null } } override val canUndo: Boolean get() = synchronized(this) { undoState != null } }
gpl-3.0
93a30af3a1e5b9555bb9b1aee637bfd6
27.769231
76
0.646154
4.384164
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/PerfectPaymentsClient.kt
1
3030
package net.perfectdreams.loritta.morenitta.utils import com.github.salomonbrys.kotson.jsonObject import com.github.salomonbrys.kotson.obj import com.github.salomonbrys.kotson.string import com.google.gson.JsonObject import com.google.gson.JsonParser import net.perfectdreams.loritta.morenitta.dao.DonationKey import net.perfectdreams.loritta.morenitta.tables.DonationKeys import io.ktor.client.request.* import io.ktor.client.statement.* import mu.KotlinLogging import net.perfectdreams.loritta.morenitta.dao.Payment import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.utils.payments.PaymentGateway import net.perfectdreams.loritta.morenitta.utils.payments.PaymentReason import java.util.* class PerfectPaymentsClient(val url: String) { private val logger = KotlinLogging.logger {} /** * Creates a payment in PerfectPayments, creates a entry in Loritta's payment table and returns the payment URL * * @return the payment URL */ suspend fun createPayment( loritta: LorittaBot, userId: Long, paymentTitle: String, amount: Long, storedAmount: Long, paymentReason: PaymentReason, externalReference: String, discount: Double? = null, metadata: JsonObject? = null ): String { logger.info { "Requesting PerfectPayments payment URL for $userId" } val payments = loritta.http.post("${url}api/v1/payments") { header("Authorization", loritta.config.loritta.perfectPayments.token) setBody( jsonObject( "title" to paymentTitle, "callbackUrl" to "${loritta.config.loritta.website.url}api/v1/callbacks/perfect-payments", "amount" to amount, "currencyId" to "BRL", "externalReference" to externalReference ).toString() ) }.bodyAsText() val paymentResponse = JsonParser.parseString(payments) .obj val partialPaymentId = UUID.fromString(paymentResponse["id"].string) val paymentUrl = paymentResponse["paymentUrl"].string logger.info { "Payment successfully created for $userId! ID: $partialPaymentId" } loritta.newSuspendedTransaction { DonationKey.find { DonationKeys.expiresAt greaterEq System.currentTimeMillis() } Payment.new { this.userId = userId this.gateway = PaymentGateway.PERFECTPAYMENTS this.reason = paymentReason if (discount != null) this.discount = discount if (metadata != null) this.metadata = metadata this.money = (storedAmount.toDouble() / 100).toBigDecimal() this.createdAt = System.currentTimeMillis() this.referenceId = partialPaymentId } } return paymentUrl } }
agpl-3.0
634e869080783e88419306e434bb31c9
35.083333
115
0.643234
4.926829
false
false
false
false
InnoFang/DesignPatterns
src/io/innofang/builder/example/kotlin/Client.kt
1
397
package io.innofang.builder.example.kotlin /** * Created by Inno Fang on 2017/8/31. */ fun main(args: Array<String>) { val ferrari = Ferrari.build { brand = "ferrari" color = "red" licensePlate = "B88888" } println(ferrari) val audi = Audi.build { brand = "Audi" color = "blue" licensePlate = "C88888" } println(audi) }
gpl-3.0
17df32457a323e7bcc81573316264430
17.090909
42
0.559194
3.254098
false
false
false
false
LorittaBot/Loritta
web/dashboard/spicy-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/dashboard/frontend/utils/LoadingGifs.kt
1
589
package net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils object LoadingGifs { val list = listOf( "https://cdn.discordapp.com/emojis/957368372025262120.gif?size=160&quality=lossless", "https://cdn.discordapp.com/emojis/958906311414796348.gif?size=160&quality=lossless", "https://cdn.discordapp.com/emojis/959551356769820712.gif?size=160&quality=lossless", "https://cdn.discordapp.com/emojis/959557654341103696.gif?size=160&quality=lossless", "https://cdn.discordapp.com/emojis/985919207147470858.gif?size=160&quality=lossless" ) }
agpl-3.0
81cb3af9e5aa0c526465ade130ff27ff
52.636364
93
0.747029
3.236264
false
false
false
false
Blankj/AndroidUtilCode
feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/process/ProcessActivity.kt
1
2807
package com.blankj.utilcode.pkg.feature.process import android.content.Context import android.content.Intent import com.blankj.common.activity.CommonActivity import com.blankj.common.item.CommonItem import com.blankj.common.item.CommonItemClick import com.blankj.common.item.CommonItemTitle import com.blankj.utilcode.pkg.R import com.blankj.utilcode.util.CollectionUtils import com.blankj.utilcode.util.ProcessUtils /** * ``` * author: Blankj * blog : http://blankj.com * time : 2016/10/13 * desc : demo about ProcessUtils * ``` */ class ProcessActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, ProcessActivity::class.java) context.startActivity(starter) } } override fun bindTitleRes(): Int { return R.string.demo_process } override fun bindItems(): MutableList<CommonItem<*>> { val set = ProcessUtils.getAllBackgroundProcesses() return CollectionUtils.newArrayList( CommonItemTitle("getForegroundProcessName", ProcessUtils.getForegroundProcessName()!!), CommonItemTitle("getAllBackgroundProcesses -> ${set.size}", getSetItems(set)), CommonItemTitle("isMainProcess", ProcessUtils.isMainProcess().toString()), CommonItemTitle("getCurrentProcessName", ProcessUtils.getCurrentProcessName()), CommonItemClick(R.string.process_kill_all_background).setOnItemClickListener { _, item, _ -> val bgSet = ProcessUtils.getAllBackgroundProcesses() val killedSet = ProcessUtils.killAllBackgroundProcesses() itemsView.updateItems( CollectionUtils.newArrayList( CommonItemTitle("getForegroundProcessName", ProcessUtils.getForegroundProcessName()), CommonItemTitle("getAllBackgroundProcesses -> ${bgSet.size}", getSetItems(bgSet)), CommonItemTitle("killAllBackgroundProcesses -> ${killedSet.size}", getSetItems(killedSet)), CommonItemTitle("isMainProcess", ProcessUtils.isMainProcess().toString()), CommonItemTitle("getCurrentProcessName", ProcessUtils.getCurrentProcessName()), item ) ) } ) } private fun getSetItems(set: Set<String>): String { val iterator = set.iterator() val sb = StringBuilder() while (iterator.hasNext()) { sb.append("\n").append(iterator.next()) } return if (sb.isNotEmpty()) sb.deleteCharAt(0).toString() else "" } }
apache-2.0
8afdd957d54ccc8a99e312bb300ab768
40.895522
127
0.619523
5.558416
false
false
false
false
Muks14x/susi_android
app/src/main/java/org/fossasia/susi/ai/skills/settings/ChatSettingsFragment.kt
1
13568
package org.fossasia.susi.ai.skills.settings import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.support.design.widget.TextInputEditText import android.support.design.widget.TextInputLayout import android.support.v4.app.ActivityCompat import android.support.v7.app.AlertDialog import android.support.v7.preference.ListPreference import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceFragmentCompat import android.support.v7.widget.AppCompatCheckBox import android.util.Log import android.view.Menu import android.view.View import android.widget.Toast import org.fossasia.susi.ai.R import org.fossasia.susi.ai.helper.Constant import org.fossasia.susi.ai.login.LoginActivity import org.fossasia.susi.ai.helper.PrefManager import org.fossasia.susi.ai.skills.settings.contract.ISettingsPresenter import org.fossasia.susi.ai.skills.settings.contract.ISettingsView import org.fossasia.susi.ai.skills.SkillsActivity /** * The Fragment for Settings Activity * * Created by mayanktripathi on 10/07/17. */ class ChatSettingsFragment : PreferenceFragmentCompat(), ISettingsView { lateinit var settingsPresenter: ISettingsPresenter lateinit var rate: Preference lateinit var server: Preference lateinit var micSettings: Preference lateinit var hotwordSettings: Preference lateinit var share: Preference lateinit var loginLogout: Preference lateinit var resetPassword: Preference lateinit var enterSend: Preference lateinit var speechAlways: Preference lateinit var speechOutput: Preference lateinit var password: TextInputLayout lateinit var newPassword: TextInputLayout lateinit var conPassword: TextInputLayout lateinit var input_url: TextInputLayout lateinit var resetPasswordAlert: AlertDialog lateinit var setServerAlert: AlertDialog lateinit var querylanguage: ListPreference var flag = true override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.pref_settings) (activity as SkillsActivity).title = (activity as SkillsActivity).getString(R.string.action_settings) settingsPresenter = SettingsPresenter(activity as SkillsActivity) settingsPresenter.onAttach(this) setHasOptionsMenu(true) rate = preferenceManager.findPreference(Constant.RATE) server = preferenceManager.findPreference(Constant.SELECT_SERVER) micSettings = preferenceManager.findPreference(Constant.MIC_INPUT) hotwordSettings = preferenceManager.findPreference(Constant.HOTWORD_DETECTION) share = preferenceManager.findPreference(Constant.SHARE) loginLogout = preferenceManager.findPreference(Constant.LOGIN_LOGOUT) resetPassword = preferenceManager.findPreference(Constant.RESET_PASSWORD) enterSend = preferenceManager.findPreference(Constant.ENTER_SEND) speechOutput = preferenceManager.findPreference(Constant.SPEECH_OUTPUT) speechAlways = preferenceManager.findPreference(Constant.SPEECH_ALWAYS) querylanguage = preferenceManager.findPreference(Constant.LANG_SELECT) as ListPreference setLanguage() if (settingsPresenter.getAnonymity()) { loginLogout.title = "Login" } else { loginLogout.title = "Logout" } querylanguage.setOnPreferenceChangeListener { _, newValue -> PrefManager.putString(Constant.LANGUAGE, newValue.toString()) setLanguage() if(!settingsPresenter.getAnonymity()) { settingsPresenter.sendSetting(Constant.LANGUAGE, newValue.toString(), 1) } true } rate.setOnPreferenceClickListener { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName))) true } share.setOnPreferenceClickListener { try { val shareIntent = Intent() shareIntent.action = Intent.ACTION_SEND shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, String.format(getString(R.string.promo_msg_template), String.format(getString(R.string.app_share_url), activity.packageName))) startActivity(shareIntent) } catch (e: Exception) { showToast(getString(R.string.error_msg_retry)) } true } loginLogout.setOnPreferenceClickListener { if (!settingsPresenter.getAnonymity()) { val d = AlertDialog.Builder(activity) d.setMessage("Are you sure ?").setCancelable(false).setPositiveButton("Yes") { _, _ -> settingsPresenter.loginLogout() }.setNegativeButton("No") { dialog, _ -> dialog.cancel() } val alert = d.create() alert.setTitle(getString(R.string.logout)) alert.show() } else { settingsPresenter.loginLogout() } true } if (settingsPresenter.getAnonymity()) { server.isEnabled = true server.setOnPreferenceClickListener { showAlert() true } } else { server.isEnabled = false } if(!settingsPresenter.getAnonymity()) { resetPassword.isEnabled = true resetPassword.setOnPreferenceClickListener { showResetPasswordAlert() true } } else { resetPassword.isEnabled = false } micSettings.isEnabled = settingsPresenter.enableMic() hotwordSettings.isEnabled = settingsPresenter.enableHotword() if(!settingsPresenter.getAnonymity()) { micSettings.setOnPreferenceClickListener { settingsPresenter.sendSetting(Constant.MIC_INPUT, (PrefManager.getBoolean(Constant.MIC_INPUT, false)).toString(), 1) true } enterSend.setOnPreferenceChangeListener { _, newValue -> settingsPresenter.sendSetting(Constant.ENTER_SEND, newValue.toString(), 1) true } speechAlways.setOnPreferenceChangeListener { _, newValue -> settingsPresenter.sendSetting(Constant.SPEECH_ALWAYS, newValue.toString(), 1) true } speechOutput.setOnPreferenceChangeListener { _, newValue -> settingsPresenter.sendSetting(Constant.SPEECH_OUTPUT, newValue.toString(), 1) true } } } override fun onPrepareOptionsMenu(menu: Menu) { val itemSettings = menu.findItem(R.id.menu_settings) itemSettings.isVisible = false val itemAbout = menu.findItem(R.id.menu_about) itemAbout.isVisible = true super.onPrepareOptionsMenu(menu) } fun setLanguage() { val index = querylanguage.findIndexOfValue(PrefManager.getString(Constant.LANGUAGE, Constant.DEFAULT)) querylanguage.setValueIndex(index) querylanguage.summary = querylanguage.entries[index] } fun showAlert() { val builder = AlertDialog.Builder(activity) val promptsView = activity.layoutInflater.inflate(R.layout.alert_change_server, null) input_url = promptsView.findViewById(R.id.input_url) as TextInputLayout val input_url_text = promptsView.findViewById(R.id.input_url_text) as TextInputEditText val customer_server = promptsView.findViewById(R.id.customer_server) as AppCompatCheckBox if (PrefManager.getBoolean(Constant.SUSI_SERVER, true)) { input_url.visibility = View.GONE flag = false } else { input_url.visibility = View.VISIBLE flag = true } customer_server.isChecked = flag input_url_text.setText(PrefManager.getString(Constant.CUSTOM_SERVER, null)) customer_server.setOnCheckedChangeListener { buttonView, isChecked -> if(isChecked) input_url.visibility = View.VISIBLE if(!isChecked) input_url.visibility = View.GONE } builder.setView(promptsView) builder.setTitle(Constant.CHANGE_SERVER) .setCancelable(false) .setNegativeButton(Constant.CANCEL, null) .setPositiveButton(activity.getString(R.string.ok), null) setServerAlert = builder.create() setServerAlert.show() setServerAlert.getButton(AlertDialog.BUTTON_POSITIVE)?.setOnClickListener { settingsPresenter.setServer(customer_server.isChecked, input_url.editText?.text.toString()) } } fun showResetPasswordAlert() { val builder = AlertDialog.Builder(activity) val resetPasswordView = activity.layoutInflater.inflate(R.layout.alert_reset_password, null) password = resetPasswordView.findViewById(R.id.password) as TextInputLayout newPassword = resetPasswordView.findViewById(R.id.newpassword) as TextInputLayout conPassword = resetPasswordView.findViewById(R.id.confirmpassword) as TextInputLayout builder.setView(resetPasswordView) builder.setTitle(Constant.CHANGE_PASSWORD) .setCancelable(false) .setNegativeButton(Constant.CANCEL, null) .setPositiveButton(getString(R.string.ok), null) resetPasswordAlert = builder.create() resetPasswordAlert.show() setupPasswordWatcher() resetPasswordAlert.getButton(AlertDialog.BUTTON_POSITIVE)?.setOnClickListener { settingsPresenter.resetPassword(password.editText?.text.toString(), newPassword.editText?.text.toString(), conPassword.editText?.text.toString()) } } override fun micPermission(): Boolean { return ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED } override fun hotWordPermission(): Boolean { return ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED } override fun startLoginActivity() { val intent = Intent(activity, LoginActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) activity.finish() } fun showToast(message: String) { Toast.makeText(activity, message, Toast.LENGTH_SHORT).show() } override fun onSettingResponse(message: String) { Log.d("settingresponse", message) } override fun passwordInvalid(what: String) { when(what) { Constant.NEW_PASSWORD -> newPassword.error = getString(R.string.pass_validation_text) Constant.PASSWORD -> password.error = getString(R.string.pass_validation_text) Constant.CONFIRM_PASSWORD -> conPassword.error = getString(R.string.pass_validation_text) } } override fun invalidCredentials(isEmpty: Boolean, what: String) { if(isEmpty) { when(what) { Constant.PASSWORD -> password.error = getString(R.string.field_cannot_be_empty) Constant.NEW_PASSWORD -> newPassword.error = getString(R.string.field_cannot_be_empty) Constant.CONFIRM_PASSWORD -> conPassword.error = getString(R.string.field_cannot_be_empty) } } else { conPassword.error = getString(R.string.error_password_matching) } } override fun onResetPasswordResponse(message: String) { resetPasswordAlert.dismiss() if(!message.equals("null")) { showToast(message) } else { showToast(getString(R.string.wrong_password)) showResetPasswordAlert() } } override fun checkUrl(isEmpty: Boolean) { if(isEmpty) { input_url.error = getString(R.string.field_cannot_be_empty) } else { input_url.error = getString(R.string.invalid_url) } } override fun setServerSuccessful() { setServerAlert.dismiss() } fun setupPasswordWatcher() { password.editText?.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> password.error = null if (!hasFocus) settingsPresenter.checkForPassword(password.editText?.text.toString(), Constant.PASSWORD) } newPassword.editText?.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> newPassword.error = null if (!hasFocus) settingsPresenter.checkForPassword(newPassword.editText?.text.toString(), Constant.NEW_PASSWORD) } conPassword.editText?.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> conPassword.error = null if (!hasFocus) settingsPresenter.checkForPassword(conPassword.editText?.text.toString(), Constant.CONFIRM_PASSWORD) } } override fun onDestroyView() { super.onDestroyView() settingsPresenter.onDetach() } }
apache-2.0
76aa554855f4878e099b5ec8172b5464
39.993958
157
0.665979
5.202454
false
false
false
false
android/app-bundle-samples
DynamicCodeLoadingKotlin/app/src/serviceLoader/java/com/google/android/samples/dynamiccodeloading/MainViewModel.kt
1
3252
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.android.samples.dynamiccodeloading import android.app.Application import android.content.Context import android.util.Log import java.util.ServiceLoader /** * An implementation of our ViewModel that uses ServiceLoader. * * ServiceLoader is a standard mechanism in Java that is used to load * concrete service implementations (as defined by an interface) * based on metadata found in META-INF/services/ * * You can find the corresponding metadata file in the storage module * in storage/src/serviceLoader/resources/META-INF/services * * Please note that by default, ServiceLoader involves disk access * and performs slow operations, making the performance of this solution * not optimal for use in Android apps. * * R8 (the new code shrinker and optimizer in Android Studio 3.4) * introduced an optimization where for straightforward ServiceLoader uses * it is able to replace them with straight object instantiation based * on the same metadata from META-INF at build time, * mitigating the performance and disk access issues. * * At the time of writing this sample, a specific version of R8 from master * has to be used. The optimization should be in versions of R8 included with * Android Gradle Plugin 3.5.0+. * * The ServiceLoader approach can be useful if you want to load * multiple implementations of a service. Even though in this sample we only * have one StorageFeature implementation, ServiceLoader.load returns an iterator * with all registered classes. */ class MainViewModel(app: Application) : AbstractMainViewModel(app) { override fun initializeStorageFeature() { // We will need this to pass in dependencies to the StorageFeature.Provider val dependencies: StorageFeature.Dependencies = object : StorageFeature.Dependencies { override fun getContext(): Context = getApplication() override fun getLogger(): Logger = MainLogger } // Ask ServiceLoader for concrete implementations of StorageFeature.Provider // Explicitly use the 2-argument version of load to enable R8 optimization. val serviceLoader = ServiceLoader.load( StorageFeature.Provider::class.java, StorageFeature.Provider::class.java.classLoader ) // Explicitly ONLY use the .iterator() method on the returned ServiceLoader to enable R8 optimization. // When these two conditions are met, R8 replaces ServiceLoader calls with direct object instantiation. storageModule = serviceLoader.iterator().next().get(dependencies) Log.d(TAG, "Loaded storage feature through ServiceLoader") } }
apache-2.0
6139a43abe301770fc69d4ee101875df
43.547945
111
0.74631
4.789396
false
false
false
false
Bombe/Sone
src/main/kotlin/net/pterodactylus/sone/web/ajax/JsonPage.kt
1
2773
package net.pterodactylus.sone.web.ajax import com.fasterxml.jackson.databind.ObjectMapper import freenet.clients.http.ToadletContext import net.pterodactylus.sone.utils.parameters import net.pterodactylus.sone.web.SessionProvider import net.pterodactylus.sone.web.WebInterface import net.pterodactylus.sone.web.page.* import net.pterodactylus.util.web.Page import net.pterodactylus.util.web.Response import java.io.ByteArrayOutputStream import java.io.PrintStream /** * A JSON page is a specialized [Page] that will always return a JSON * object to the browser, e.g. for use with AJAX or other scripting frameworks. */ abstract class JsonPage(protected val webInterface: WebInterface) : Page<FreenetRequest> { private val objectMapper = ObjectMapper() private val sessionProvider: SessionProvider = webInterface protected val core = webInterface.core override fun getPath() = toadletPath override fun isPrefixPage() = false open val needsFormPassword = true open val requiresLogin = true protected fun createSuccessJsonObject() = JsonReturnObject(true) protected fun createErrorJsonObject(error: String) = JsonErrorReturnObject(error) protected fun getCurrentSone(toadletContext: ToadletContext) = sessionProvider.getCurrentSone(toadletContext) override fun handleRequest(request: FreenetRequest, response: Response): Response { if (core.preferences.requireFullAccess && !request.toadletContext.isAllowedFullAccess) { return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(createErrorJsonObject("auth-required").asJsonString()) } if (needsFormPassword && request.parameters["formPassword"] != webInterface.formPassword) { return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(createErrorJsonObject("auth-required").asJsonString()) } if (requiresLogin && (sessionProvider.getCurrentSone(request.toadletContext) == null)) { return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(createErrorJsonObject("auth-required").asJsonString()) } return try { response.setStatusCode(200).setStatusText("OK").setContentType("application/json").write(createJsonObject(request).asJsonString()) } catch (e: Exception) { response.setStatusCode(500).setStatusText(e.message).setContentType("text/plain").write(e.dumpStackTrace()) } } abstract fun createJsonObject(request: FreenetRequest): JsonReturnObject private fun JsonReturnObject.asJsonString(): String = objectMapper.writeValueAsString(this) private fun Throwable.dumpStackTrace(): String = ByteArrayOutputStream().use { PrintStream(it, true, "UTF-8").use { this.printStackTrace(it) } it.toString("UTF-8") } }
gpl-3.0
c3438069c626a6d5105320c0886bdfeb
41.661538
160
0.793004
4.366929
false
false
false
false
nlefler/Glucloser
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/dataSource/jsonAdapter/FoodJsonAdapter.kt
1
774
package com.nlefler.glucloser.a.dataSource.jsonAdapter import com.nlefler.glucloser.a.models.Food import com.nlefler.glucloser.a.models.FoodEntity import com.nlefler.glucloser.a.models.json.FoodJson import com.squareup.moshi.FromJson import com.squareup.moshi.ToJson /** * Created by nathan on 1/31/16. */ public class FoodJsonAdapter() { @FromJson fun fromJson(json: FoodJson): Food { val food = FoodEntity() food.primaryID = json.primaryId food.carbs = json.carbs food.foodName = json.foodName return food } @ToJson fun toJson(food: Food): FoodJson { return FoodJson( primaryId = food.primaryID, foodName = food.foodName, carbs = food.carbs ) } }
gpl-2.0
ccdbe8ef8b41e3d0cbc3dea23d58ff79
26.642857
54
0.655039
3.850746
false
false
false
false
vhromada/Catalog-Spring
src/main/kotlin/cz/vhromada/catalog/web/fo/SongFO.kt
1
1199
package cz.vhromada.catalog.web.fo import java.io.Serializable import java.util.Objects import javax.validation.Valid import javax.validation.constraints.NotBlank import javax.validation.constraints.NotNull /** * A class represents FO for song. * * @author Vladimir Hromada */ data class SongFO( /** * ID */ val id: Int?, /** * Name */ @field:NotBlank val name: String?, /** * Length */ @field:NotNull @field:Valid var length: TimeFO?, /** * Note */ val note: String?, /** * Position */ val position: Int?) : Serializable { override fun equals(other: Any?): Boolean { if (this === other) { return true } return if (other !is SongFO || id == null) { false } else id == other.id } override fun hashCode(): Int { return Objects.hashCode(id) } override fun toString(): String { return String.format("SongFO [id=%d, name=%s, length=%s, note=%s, position=%d]", id, name, length, note, position) } }
mit
ea14233ba437094230bed73310cfb051
18.33871
122
0.516264
4.266904
false
false
false
false
spark/photon-tinker-android
app/src/main/java/io/particle/android/sdk/ui/devicelist/DeviceListActivity.kt
1
2848
package io.particle.android.sdk.ui.devicelist import android.content.Intent import android.os.Bundle import android.os.Handler import androidx.core.os.postDelayed import androidx.fragment.app.Fragment import androidx.fragment.app.commit import androidx.lifecycle.ViewModelProviders import io.particle.android.sdk.cloud.ParticleCloudSDK import io.particle.android.sdk.ui.BaseActivity import io.particle.android.sdk.updateUsernameWithCrashlytics import io.particle.android.sdk.utils.SoftAPConfigRemover import io.particle.android.sdk.utils.WifiFacade import io.particle.android.sdk.utils.ui.Ui import io.particle.mesh.ui.setup.MeshSetupActivity import io.particle.sdk.app.R class DeviceListActivity : BaseActivity() { private var softAPConfigRemover: SoftAPConfigRemover? = null private lateinit var filterViewModel: DeviceFilterViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) updateUsernameWithCrashlytics(ParticleCloudSDK.getCloud().loggedInUsername) setContentView(R.layout.activity_device_list) filterViewModel = ViewModelProviders.of(this).get(DeviceFilterViewModel::class.java) filterViewModel.refreshDevices() softAPConfigRemover = SoftAPConfigRemover(this, WifiFacade.get(this)) // TODO: If exposing deep links into your app, handle intents here. if (Ui.findFrag<Fragment>(this, R.id.fragment_parent) == null) { supportFragmentManager.commit { add(R.id.fragment_parent, DeviceListFragment.newInstance()) } } onProcessIntent(intent) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) onProcessIntent(intent) } private fun onProcessIntent(intent: Intent) { val intentUri = intent.data // we have to do all this nonsense because Branch sends us garbage URIs // which have *two schemes* in them. if (intentUri != null && intentUri.encodedPath != null && (intentUri.encodedPath!!.contains("meshsetup") || intentUri.host != null && intentUri.host!!.contains( "meshsetup" )) ) { startActivity(Intent(this, MeshSetupActivity::class.java)) } } override fun onStart() { super.onStart() softAPConfigRemover!!.removeAllSoftApConfigs() softAPConfigRemover!!.reenableWifiNetworks() } override fun onBackPressed() { val currentFragment = Ui.findFrag<Fragment>(this, R.id.fragment_parent) var deviceList: DeviceListFragment? = null if (currentFragment is DeviceListFragment) { deviceList = currentFragment } if (deviceList?.onBackPressed() != true) { super.onBackPressed() } } }
apache-2.0
4749a5de830d5edf64ad06cc80708fc3
32.904762
117
0.695225
4.723051
false
true
false
false
wireapp/wire-android
app/src/test/kotlin/com/waz/zclient/core/backend/datasources/local/BackendLocalDataSourceTest.kt
1
4029
package com.waz.zclient.core.backend.datasources.local import com.waz.zclient.UnitTest import com.waz.zclient.core.extension.empty import com.waz.zclient.eq import com.waz.zclient.storage.pref.backend.BackendPreferences import org.amshove.kluent.shouldBe import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.Mockito.verify class BackendLocalDataSourceTest : UnitTest() { private lateinit var backendPrefsDataSource: BackendLocalDataSource @Mock private lateinit var backendPreferences: BackendPreferences @Before fun setup() { backendPrefsDataSource = BackendLocalDataSource(backendPreferences) } @Test fun `when environment is called, returns backendPreferences' environment`() { backendPrefsDataSource.environment() verify(backendPreferences).environment } @Test fun `given backendConfig is valid, when getBackendConfig is requested, then return config`() { mockBackendPrefs(valid = true) val response = backendPrefsDataSource.backendConfig() response.fold({ assert(false) { "Expected a valid preference" } }) { assert(it == TEST_PREFERENCE) //TODO @Fernando : Does not verify with kluent: "it shouldBe TEST_PREFERENCE" } } @Test fun `given backendConfig is not valid, when getBackendConfig is requested, then return InvalidBackendConfig error`() { mockBackendPrefs(valid = false) val response = backendPrefsDataSource.backendConfig() response.fold({ it shouldBe InvalidBackendConfig }) { assert(false) //should've got an error } } @Test fun `given url and new backend config, when update backend config is requested, then update backend preferences`() { backendPrefsDataSource.updateBackendConfig(CONFIG_URL, TEST_PREFERENCE) verify(backendPreferences).environment = eq(ENVIRONMENT) verify(backendPreferences).customConfigUrl = eq(CONFIG_URL) verify(backendPreferences).accountsUrl = eq(ACCOUNTS_URL) verify(backendPreferences).baseUrl = eq(BASE_URL) verify(backendPreferences).websocketUrl = eq(WEBSOCKET_URL) verify(backendPreferences).teamsUrl = eq(TEAMS_URL) verify(backendPreferences).websiteUrl = eq(WEBSITE_URL) verify(backendPreferences).blacklistUrl = eq(BLACKLIST_URL) } private fun mockBackendPrefs(valid: Boolean) { `when`(backendPreferences.environment).thenReturn(if (valid) ENVIRONMENT else String.empty()) `when`(backendPreferences.baseUrl).thenReturn(BASE_URL) `when`(backendPreferences.websocketUrl).thenReturn(WEBSOCKET_URL) `when`(backendPreferences.blacklistUrl).thenReturn(BLACKLIST_URL) `when`(backendPreferences.teamsUrl).thenReturn(TEAMS_URL) `when`(backendPreferences.accountsUrl).thenReturn(ACCOUNTS_URL) `when`(backendPreferences.websiteUrl).thenReturn(WEBSITE_URL) } companion object { private const val CONFIG_URL = "https://www.wire.com/config.json" private const val ACCOUNTS_URL = "https://accounts.wire.com" private const val ENVIRONMENT = "custom.environment.link.wire.com" private const val BASE_URL = "https://www.wire.com" private const val WEBSOCKET_URL = "https://websocket.wire.com" private const val BLACKLIST_URL = "https://blacklist.wire.com" private const val TEAMS_URL = "https://teams.wire.com" private const val WEBSITE_URL = "https://wire.com" private val TEST_PREFERENCE = CustomBackendPreferences( ENVIRONMENT, CustomBackendPrefEndpoints( backendUrl = BASE_URL, websocketUrl = WEBSOCKET_URL, blacklistUrl = BLACKLIST_URL, teamsUrl = TEAMS_URL, accountsUrl = ACCOUNTS_URL, websiteUrl = WEBSITE_URL ) ) } }
gpl-3.0
55da9215da7ce76e917e8e6a0b89cbbf
36.654206
122
0.686026
4.756789
false
true
false
false
mozilla-mobile/focus-android
app/src/androidTest/java/org/mozilla/focus/helpers/FeatureSettingsHelper.kt
1
1431
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.helpers import android.content.Context import androidx.test.platform.app.InstrumentationRegistry import org.mozilla.focus.ext.settings class FeatureSettingsHelper { val context: Context = InstrumentationRegistry.getInstrumentation().targetContext private val settings = context.settings // saving default values of feature flags private var shouldShowCfrForTrackingProtection: Boolean = settings.shouldShowCfrForTrackingProtection fun setCfrForTrackingProtectionEnabled(enabled: Boolean) { settings.shouldShowCfrForTrackingProtection = enabled } fun setShowStartBrowsingCfrEnabled(enabled: Boolean) { settings.shouldShowStartBrowsingCfr = enabled } fun setSearchWidgetDialogEnabled(enabled: Boolean) { if (enabled) { settings.addClearBrowsingSessions(4) } else { settings.addClearBrowsingSessions(10) } } // Important: // Use this after each test if you have modified these feature settings // to make sure the app goes back to the default state fun resetAllFeatureFlags() { settings.shouldShowCfrForTrackingProtection = shouldShowCfrForTrackingProtection } }
mpl-2.0
546729444576e433bc4083b2ba3c56d0
34.775
105
0.740741
5.129032
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/settings/background/ViewHolder.kt
1
2821
package jp.toastkid.yobidashi.settings.background import androidx.annotation.StringRes import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.RecyclerView import coil.load import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.ItemSavedImageBinding import timber.log.Timber import java.io.File import java.io.IOException /** * Extended of [RecyclerView.ViewHolder]. * * @param binding Binding object. * @param preferenceApplier Preferences wrapper. * @param onRemoved Action on removed. * * @author toastkidjp */ internal class ViewHolder( private val binding: ItemSavedImageBinding, private val preferenceApplier: PreferenceApplier, private val onRemoved: () -> Unit ) : RecyclerView.ViewHolder(binding.root) { /** * Apply file content. * * @param f background image file */ fun applyContent(f: File?) { if (f == null) { return } binding.image.load(f) binding.text.text = f.nameWithoutExtension binding.remove.setOnClickListener { removeSetImage(f) } binding.root.setOnClickListener { preferenceApplier.backgroundImagePath = f.path snack(R.string.message_change_background_image) } binding.root.setOnLongClickListener { v -> try { val context = v.context if (context is FragmentActivity) { ImageDialogFragment.withUrl(f.toURI().toString()) .show( context.supportFragmentManager, ImageDialogFragment::class.java.simpleName ) } } catch (e: IOException) { Timber.e(e) } true } } /** * Remove set image. * * @param file Image file */ private fun removeSetImage(file: File?) { if (file == null || !file.exists()) { snack(R.string.message_cannot_found_image) return } val successRemove = file.delete() if (!successRemove) { snack(R.string.message_failed_image_removal) return } snack(R.string.message_success_image_removal) onRemoved() } /** * Show [Snackbar] with specified message resource. * * @param messageId Message ID */ private fun snack(@StringRes messageId: Int) { (binding.root.context as? FragmentActivity)?.also { ViewModelProvider(it).get(ContentViewModel::class.java).snackShort(messageId) } } }
epl-1.0
bbe753626b376078f7004feb70eef031
28.395833
89
0.605814
4.822222
false
false
false
false
maballesteros/vertx3-kotlin-rest-jdbc-tutorial
step05/src/rest_utils.kt
1
1675
import com.google.gson.Gson import io.vertx.core.Future import io.vertx.core.Vertx import io.vertx.core.http.HttpServer import io.vertx.ext.web.Router import io.vertx.ext.web.RoutingContext import io.vertx.ext.web.handler.BodyHandler import kotlin.reflect.KClass /** * Created by mike on 14/11/15. */ val GSON = Gson() fun Vertx.restApi(port: Int, body: Router.() -> Unit) { createHttpServer().restApi(this, body).listen(port) { if (it.succeeded()) println("Server listening at $port") else println(it.cause()) } } fun HttpServer.restApi(vertx: Vertx, body: Router.() -> Unit): HttpServer { val router = Router.router(vertx) router.route().handler(BodyHandler.create()) // Required for RoutingContext.bodyAsString router.body() requestHandler { router.accept(it) } return this } fun Router.get(path: String, rctx:RoutingContext.() -> Unit) = get(path).handler { it.rctx() } fun Router.post(path: String, rctx:RoutingContext.() -> Unit) = post(path).handler { it.rctx() } fun Router.put(path: String, rctx:RoutingContext.() -> Unit) = put(path).handler { it.rctx() } fun Router.delete(path: String, rctx:RoutingContext.() -> Unit) = delete(path).handler { it.rctx() } fun RoutingContext.param(name: String): String = request().getParam(name) fun RoutingContext.bodyAs<T>(clazz: KClass<out Any>): T = GSON.fromJson(bodyAsString, clazz.java) as T fun RoutingContext.send<T : Any?>(promise: Promise<T>) { promise .then { val res = if (it == null) "" else GSON.toJson(it) response().end(res) } .fail { response().setStatusCode(500).end(it.toString()) } }
apache-2.0
41699ff087b18f428845acb741b37ace
31.843137
100
0.669851
3.548729
false
false
false
false
xfournet/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/CategoryMemberContributor.kt
6
3183
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve import com.intellij.psi.* import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.PsiTypesUtil.getPsiClass import com.intellij.psi.util.PsiUtil.substituteTypeParameter import com.intellij.psi.util.parents import org.jetbrains.plugins.groovy.dgm.GdkMethodHolder.getHolderForClass import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint class CategoryMemberContributor : NonCodeMembersContributor() { override fun processDynamicElements(qualifierType: PsiType, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) { if (!processor.shouldProcessMethods() && !processor.shouldProcessProperties()) return for (parent in place.parents()) { if (parent is GrMember) break if (parent !is GrClosableBlock) continue val call = checkMethodCall(parent) ?: continue val categories = getCategoryClasses(call, parent) ?: continue val holders = categories.map { getHolderForClass(it, false) } val stateWithContext = state.put(ClassHint.RESOLVE_CONTEXT, call) for (category in holders) { if (!category.processMethods(processor, stateWithContext, qualifierType, place.project)) return } } } private fun getCategoryClasses(call: GrMethodCall, closure: GrClosableBlock): List<PsiClass>? { val closures = call.closureArguments val args = call.expressionArguments if (args.isEmpty()) return null val lastArg = closure == args.last() if (!lastArg && closure != closures.singleOrNull()) return null if (call.resolveMethod() !is GrGdkMethod) return null if (args.size == 1 || args.size == 2 && lastArg) { val tupleType = args.first().type as? GrTupleType tupleType?.let { return it.componentTypes.mapNotNull { getPsiClass(substituteTypeParameter(it, CommonClassNames.JAVA_LANG_CLASS, 0, false)) } } } return args.mapNotNull { (it as? GrReferenceExpression)?.resolve() as? PsiClass } } private fun checkMethodCall(place: PsiElement): GrMethodCall? { val context = place.context val call = when (context) { is GrMethodCall -> context is GrArgumentList -> context.context as? GrMethodCall else -> null } if (call == null) return null val invoked = call.invokedExpression as? GrReferenceExpression if (invoked?.referenceName != "use") return null return call } }
apache-2.0
89988a4be4ff26cce52d16b624f96d8d
42.616438
140
0.747094
4.408587
false
false
false
false
dya-tel/TSU-Schedule
src/main/kotlin/ru/dyatel/tsuschedule/model/Filters.kt
1
1693
package ru.dyatel.tsuschedule.model import android.content.Context import ru.dyatel.tsuschedule.R import ru.dyatel.tsuschedule.layout.FilterView import ru.dyatel.tsuschedule.layout.SubgroupFilterView abstract class Filter(var enabled: Boolean) { abstract fun apply(lesson: GroupLesson): GroupLesson? } abstract class PredefinedFilter : Filter(false) { abstract fun createView(context: Context): FilterView abstract fun save(): Map<String, String> abstract fun load(data: Map<String, String>) } class CommonPracticeFilter : PredefinedFilter() { override fun createView(context: Context) = FilterView(context).also { it.setHeader(R.string.filter_common_practice) it.attachFilter(this) } override fun save() = emptyMap<String, String>() override fun load(data: Map<String, String>) = Unit override fun apply(lesson: GroupLesson): GroupLesson { return with(lesson) { val newSubgroup = subgroup.takeUnless { type == LessonType.PRACTICE } GroupLesson(parity, weekday, time, discipline, auditory, teacher, type, newSubgroup) } } } class SubgroupFilter : PredefinedFilter() { private companion object { const val SUBGROUP_KEY = "subgroup" } var subgroup = 1 override fun createView(context: Context) = SubgroupFilterView(context).also { it.attachFilter(this) } override fun save() = mapOf(SUBGROUP_KEY to subgroup.toString()) override fun load(data: Map<String, String>) { data[SUBGROUP_KEY]?.let { subgroup = it.toInt() } } override fun apply(lesson: GroupLesson) = lesson.takeIf { it.subgroup == null || it.subgroup == subgroup } }
mit
191478515fc5d097b850b1f7b0184665
26.306452
110
0.698169
4.139364
false
false
false
false
TeleSoftas/android-core
telesoftas-common/src/main/kotlin/com/telesoftas/core/common/extension/PresenterExtension.kt
1
3879
package com.telesoftas.core.common.extension import android.app.Activity import android.app.Application import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.view.View import com.telesoftas.core.common.presenter.Presenter import timber.log.Timber @Suppress("UNCHECKED_CAST") fun <V> Presenter<V>.attach(view: V) { when (view) { is Activity -> attachToActivity(this as Presenter<Activity>, view) is Fragment -> attachToFragment(this as Presenter<Fragment>, view) is View -> attachToView(this as Presenter<View>, view) } } private fun <V : View> attachToView(presenter: Presenter<V>, rootView: V) { rootView.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(view: View) { if (rootView == view) { logAttach(presenter, rootView) presenter.takeView(rootView) } } override fun onViewDetachedFromWindow(view: View) { if (rootView == view) { logDetach(presenter, rootView) rootView.removeOnAttachStateChangeListener(this) presenter.dropView() } } }) } private fun <V : Activity> attachToActivity(presenter: Presenter<V>, view: V) { val application = view.application application.registerActivityLifecycleCallbacks(object : SimpleActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { if (view == activity) { logAttach(presenter, view) presenter.takeView(view) } } override fun onActivityDestroyed(activity: Activity) { if (view == activity) { logDetach(presenter, view) application.unregisterActivityLifecycleCallbacks(this) presenter.dropView() } } }) } private fun <V : Fragment> attachToFragment(presenter: Presenter<V>, view: V) { val fragmentManager = view.fragmentManager fragmentManager?.registerFragmentLifecycleCallbacks( object : FragmentManager.FragmentLifecycleCallbacks() { override fun onFragmentCreated( manager: FragmentManager, fragment: Fragment, savedInstanceState: Bundle? ) { if (view == fragment) { logAttach(presenter, view) presenter.takeView(view) } } override fun onFragmentDestroyed(manager: FragmentManager, fragment: Fragment) { if (view == fragment) { logDetach(presenter, view) manager.unregisterFragmentLifecycleCallbacks(this) presenter.dropView() } } }, false) } private fun <V> logAttach(presenter: Presenter<V>, view: V) { Timber.d("Attaching $view to ${presenter.javaClass.simpleName}") } private fun <V> logDetach(presenter: Presenter<V>, view: V) { Timber.d("Detaching $view from ${presenter.javaClass.simpleName}") } internal interface SimpleActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks { override fun onActivityPaused(activity: Activity) {} override fun onActivityResumed(activity: Activity) {} override fun onActivityStarted(activity: Activity) {} override fun onActivityDestroyed(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {} override fun onActivityStopped(activity: Activity) {} override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} }
apache-2.0
0fb759cdec5df0c11bb1b75becdd281b
35.261682
96
0.630575
5.29918
false
false
false
false
Jire/Strukt
src/main/kotlin/org/jire/strukt/FixedStrukts.kt
1
2384
/* * Copyright 2020 Thomas Nappo (Jire) * * 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.jire.strukt import it.unimi.dsi.fastutil.longs.LongHeapPriorityQueue import it.unimi.dsi.fastutil.longs.LongPriorityQueue import net.openhft.chronicle.core.OS import net.openhft.chronicle.core.StruktOS import org.jire.strukt.internal.AbstractStrukts import java.io.File import java.io.RandomAccessFile import java.nio.channels.FileChannel import kotlin.reflect.KClass open class FixedStrukts( type: KClass<*>, val capacity: Long, val persistedTo: File? = null ) : AbstractStrukts(type) { var baseAddress = UNSET_BASE_ADDRESS var baseSize = 0L var offset = 0L val freed: LongPriorityQueue = LongHeapPriorityQueue() val raf = if (persistedTo == null) null else RandomAccessFile(persistedTo, "rw") override fun free() = if (raf == null) { OS.memory().freeMemory(baseAddress, baseSize) true } else { OS.unmap(baseAddress, baseSize) raf.channel.close() raf.close() val file = persistedTo!! file.deleteOnExit() file.delete() } private fun allocateBase() { baseSize = size * (capacity + 1) baseAddress = if (raf == null) OS.memory().allocate(baseSize) else StruktOS.map( raf.channel, FileChannel.MapMode.READ_WRITE, 0, baseSize ) for (field in fields) { field.writeDefault(baseAddress) } offset += size } override fun allocate(): Long { if (!freed.isEmpty) { return freed.dequeueLong() } if (baseAddress == UNSET_BASE_ADDRESS) { allocateBase() return allocate() } val address = baseAddress + offset OS.memory().copyMemory(baseAddress, address, size) offset += size return address } override fun free(address: Long): Boolean { freed.enqueue(address) return true } companion object { private const val UNSET_BASE_ADDRESS = -1L } }
apache-2.0
5c0a76b3058cb7902ed9133aea1c0704
24.37234
81
0.711409
3.516224
false
false
false
false
opengl-8080/kotlin-lifegame
src/main/kotlin/gl8080/lifegame/web/exception/RollBackExceptionMapper.kt
1
849
package gl8080.lifegame.web.exception import javax.transaction.RollbackException import javax.ws.rs.core.Context import javax.ws.rs.core.Response import javax.ws.rs.ext.ExceptionMapper import javax.ws.rs.ext.Provider import javax.ws.rs.ext.Providers @Provider class RollBackExceptionMapper: ExceptionMapper<RollbackException> { @Context lateinit private var providers: Providers override fun toResponse(e: RollbackException?): Response? { val cause = e?.cause val type = cause?.javaClass as Class<Throwable> val exceptionMapper = this.providers.getExceptionMapper(type) if (exceptionMapper == null) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build() } else { return exceptionMapper.toResponse(cause) } } }
mit
500139cd4ea3fdb9c630190df4b00145
27.344828
81
0.697291
4.182266
false
false
false
false
gmillz/SlimFileManager
manager/src/main/java/com/slim/slimfilemanager/settings/SettingsProvider.kt
1
3714
/* * Copyright (C) 2015 The SlimRoms 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.slim.slimfilemanager.settings import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import android.text.TextUtils import com.slim.slimfilemanager.widget.TabItem import java.util.ArrayList import java.util.Arrays object SettingsProvider { // File Manager val KEY_ENABLE_ROOT = "enable_root" val THEME = "app_theme" val SORT_MODE = "sort_mode" val SMALL_INDICATOR = "small_indicator" // Text Editor val USE_MONOSPACE = "use_monospace" val EDITOR_WRAP_CONTENT = "editor_wrap_content" val SUGGESTION_ACTIVE = "suggestion_active" val EDITOR_ENCODING = "editor_encoding" val FONT_SIZE = "font_size" val SPLIT_TEXT = "page_system_active" operator fun get(context: Context): SharedPreferences { return PreferenceManager.getDefaultSharedPreferences(context) } fun put(context: Context): SharedPreferences.Editor { return get(context).edit() } fun put(context: Context, key: String, o: Any) { if (o is Boolean) { put(context).putBoolean(key, o).apply() } else if (o is String) { put(context).putString(key, o).apply() } else if (o is Int) { put(context).putInt(key, o).apply() } } fun getString(context: Context, key: String, defValue: String): String? { return get(context).getString(key, defValue) } fun putString(context: Context, key: String, value: String) { put(context).putString(key, value).apply() } fun getBoolean(context: Context, key: String, defValue: Boolean): Boolean { return get(context).getBoolean(key, defValue) } fun putBoolean(context: Context, key: String, b: Boolean) { put(context).putBoolean(key, b).apply() } fun getInt(context: Context, key: String, defValue: Int): Int { var i: Int try { i = get(context).getInt(key, defValue) } catch (e: Exception) { i = Integer.parseInt(get(context).getString(key, Integer.toString(defValue))!!) } return i } fun putInt(context: Context, key: String, value: Int) { put(context).putInt(key, value).commit() } fun getTabList(context: Context, key: String, def: ArrayList<TabItem>): ArrayList<TabItem> { val items = ArrayList<TabItem>() val array = ArrayList( Arrays.asList(*TextUtils.split(get(context).getString(key, ""), "‚‗‚"))) for (s in array) { items.add(TabItem.fromString(s)) } if (array.isEmpty()) { items.addAll(def) } return items } fun putTabList(context: Context, key: String, tabs: ArrayList<TabItem>) { val items = ArrayList<String>() for (item in tabs) { items.add(item.toString()) } put(context).putString(key, TextUtils.join("‚‗‚", items)).apply() } fun remove(context: Context, key: String) { put(context).remove(key).apply() } }
gpl-3.0
c4c0b1fe60f9a8e73e8dfa569aaa6ec4
30.117647
91
0.635602
4.006494
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/view/SlidingRelativeLayout.kt
1
825
package de.westnordost.streetcomplete.view import android.content.Context import android.util.AttributeSet import android.widget.RelativeLayout /** A relative layout that can be animated via an ObjectAnimator on the yFraction and xFraction * properties. I.e., it can be animated to slide up and down, left and right */ class SlidingRelativeLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr) { var yFraction: Float = 0f set(fraction) { field = fraction if (height != 0) translationY = height * yFraction } var xFraction: Float = 0f set(fraction) { field = fraction if (width != 0) translationX = width * xFraction } }
gpl-3.0
7cb4ec109f968242bfa5b2309956d927
32
95
0.670303
4.6875
false
false
false
false
pdvrieze/ProcessManager
ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/engine/processModel/JoinInstance.kt
1
15110
/* * Copyright (c) 2017. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine.processModel import net.devrieze.util.Handle import net.devrieze.util.overlay import net.devrieze.util.security.SecureObject import nl.adaptivity.process.engine.* import nl.adaptivity.process.processModel.Split import nl.adaptivity.process.processModel.StartNode import nl.adaptivity.process.processModel.engine.ConditionResult import nl.adaptivity.process.processModel.engine.ExecutableCondition import nl.adaptivity.process.processModel.engine.ExecutableJoin import nl.adaptivity.process.processModel.engine.evalCondition import nl.adaptivity.util.multiplatform.assert import nl.adaptivity.util.security.Principal import nl.adaptivity.xmlutil.util.ICompactFragment import kotlin.jvm.JvmStatic class JoinInstance : ProcessNodeInstance<JoinInstance> { interface Builder : ProcessNodeInstance.Builder<ExecutableJoin, JoinInstance> { val isFinished: Boolean get() = state == NodeInstanceState.Complete || state == NodeInstanceState.Failed override fun doProvideTask(engineData: MutableProcessEngineDataAccess): Boolean { if (!isFinished) { val shouldProgress = node.provideTask(engineData, this) if (shouldProgress) { val directSuccessors = processInstanceBuilder.getDirectSuccessorsFor(this.handle) val canAdd = directSuccessors .none { it.state.isCommitted || it.state.isFinal } if (canAdd) { state = NodeInstanceState.Acknowledged return true } } return shouldProgress } return false } override fun doTakeTask(engineData: MutableProcessEngineDataAccess): Boolean { return node.takeTask(this) } override fun doStartTask(engineData: MutableProcessEngineDataAccess): Boolean { if (node.startTask(this)) { return updateTaskState(engineData, cancelState = NodeInstanceState.Cancelled) } else { return false } } override fun doFinishTask(engineData: MutableProcessEngineDataAccess, resultPayload: ICompactFragment?) { if (state == NodeInstanceState.Complete) { return } var committedPredecessorCount = 0 var completedPredecessorCount = 0 predecessors .map { processInstanceBuilder.getChildNodeInstance(it) } .filter { it.state.isCommitted } .forEach { if (!it.state.isFinal) { throw ProcessException("Predecessor $it is committed but not final, cannot finish join without cancelling the predecessor") } else { committedPredecessorCount++ if (it.state == NodeInstanceState.Complete) { if (node.evalCondition(processInstanceBuilder, it, this) == ConditionResult.TRUE) { completedPredecessorCount++ } } } } super.doFinishTask(engineData, resultPayload) // Store before cancelling predecessors, the cancelling will likely hit this child processInstanceBuilder.storeChild(this) processInstanceBuilder.store(engineData) skipPredecessors(engineData) if (committedPredecessorCount < node.min) { throw ProcessException("Finishing the join is not possible as the minimum amount of predecessors ${node.min} was not reached (predecessor count: $committedPredecessorCount)") } engineData.commit() } fun failSkipOrCancel( engineData: MutableProcessEngineDataAccess, cancelState: NodeInstanceState, cause: Throwable ) { when { state.isCommitted -> failTask(engineData, cause) cancelState.isSkipped -> state = NodeInstanceState.Skipped else -> cancel(engineData) } } } class ExtBuilder(instance: JoinInstance, processInstanceBuilder: ProcessInstance.Builder) : ProcessNodeInstance.ExtBuilder<ExecutableJoin, JoinInstance>(instance, processInstanceBuilder), Builder { override var node: ExecutableJoin by overlay { instance.node } override fun build() = if (changed) JoinInstance(this).also { invalidateBuilder(it) } else base override fun skipTask(engineData: MutableProcessEngineDataAccess, newState: NodeInstanceState) = skipTaskImpl(engineData, newState) } class BaseBuilder( node: ExecutableJoin, predecessors: Iterable<Handle<SecureObject<ProcessNodeInstance<*>>>>, processInstanceBuilder: ProcessInstance.Builder, owner: Principal, entryNo: Int, handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(), state: NodeInstanceState = NodeInstanceState.Pending ) : ProcessNodeInstance.BaseBuilder<ExecutableJoin, JoinInstance>( node, predecessors, processInstanceBuilder, owner, entryNo, handle, state ), Builder { override fun build() = JoinInstance(this) override fun skipTask(engineData: MutableProcessEngineDataAccess, newState: NodeInstanceState) = skipTaskImpl(engineData, newState) } override val node: ExecutableJoin get() = super.node as ExecutableJoin @Suppress("UNCHECKED_CAST") override val handle: Handle<SecureObject<JoinInstance>> get() = super.handle as Handle<SecureObject<JoinInstance>> fun canFinish() = predecessors.size >= node.min constructor( node: ExecutableJoin, predecessors: Collection<Handle<SecureObject<ProcessNodeInstance<*>>>>, processInstanceBuilder: ProcessInstance.Builder, hProcessInstance: Handle<SecureObject<ProcessInstance>>, owner: Principal, entryNo: Int, handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(), state: NodeInstanceState = NodeInstanceState.Pending, results: Iterable<ProcessData> = emptyList() ) : super(node, predecessors, processInstanceBuilder, hProcessInstance, owner, entryNo, handle, state, results) { if (predecessors.any { !it.isValid }) { throw ProcessException("When creating joins all handles should be valid $predecessors") } } constructor(builder: Builder) : this( builder.node, builder.predecessors, builder.processInstanceBuilder, builder.hProcessInstance, builder.owner, builder.entryNo, builder.handle, builder.state, builder.results ) override fun builder(processInstanceBuilder: ProcessInstance.Builder) = ExtBuilder(this, processInstanceBuilder) companion object { fun build( joinImpl: ExecutableJoin, predecessors: Set<Handle<SecureObject<ProcessNodeInstance<*>>>>, processInstanceBuilder: ProcessInstance.Builder, entryNo: Int, handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(), state: NodeInstanceState = NodeInstanceState.Pending, body: Builder.() -> Unit ): JoinInstance { return JoinInstance( BaseBuilder( joinImpl, predecessors, processInstanceBuilder, processInstanceBuilder.owner, entryNo, handle, state ).apply(body) ) } fun build( joinImpl: ExecutableJoin, predecessors: Set<Handle<SecureObject<ProcessNodeInstance<*>>>>, processInstance: ProcessInstance, entryNo: Int, handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(), state: NodeInstanceState = NodeInstanceState.Pending, body: Builder.() -> Unit ): JoinInstance { return build(joinImpl, predecessors, processInstance.builder(), entryNo, handle, state, body) } /** * Update the state of the task. Returns true if the task should now be finished by the caller. * @param cancelState The state to use when the instance cannot work * @return `true` if the caller should finish the task, `false` if not */ @JvmStatic private fun Builder.updateTaskState( engineData: MutableProcessEngineDataAccess, cancelState: NodeInstanceState ): Boolean { if (state.isFinal) return false // Don't update if we're already complete val join = node val totalPossiblePredecessors = join.predecessors.size var realizedPredecessors = 0 val instantiatedPredecessors = predecessors.map { processInstanceBuilder.getChildNodeInstance(it).also { if(it.state.isFinal) realizedPredecessors++ } } var mustDecide = false if (realizedPredecessors == totalPossiblePredecessors) { /* Did we receive all possible predecessors. In this case we need to decide */ state = NodeInstanceState.Started mustDecide = true } var complete = 0 var skippedOrNever = 0 var pending = 0 for (predecessor in instantiatedPredecessors) { val condition = node.conditions[predecessor.node.identifier] as? ExecutableCondition val conditionResult = condition.evalCondition(processInstanceBuilder, predecessor, this) if (conditionResult == ConditionResult.NEVER) { skippedOrNever += 1 } else { when (predecessor.state) { NodeInstanceState.Complete -> complete += 1 NodeInstanceState.Skipped, NodeInstanceState.SkippedCancel, NodeInstanceState.Cancelled, NodeInstanceState.SkippedFail, NodeInstanceState.Failed -> skippedOrNever += 1 else -> pending += 1 } } } if (totalPossiblePredecessors - skippedOrNever < join.min) { // XXX this needs to be done in the caller if (complete > 0) { failTask(engineData, ProcessException("Too many predecessors have failed")) } else { // cancelNoncompletedPredecessors(engineData) failSkipOrCancel(engineData, cancelState, ProcessException("Too many predecessors have failed")) } } if (complete >= join.min) { if (totalPossiblePredecessors - complete - skippedOrNever == 0) return true if (complete >= join.max || (realizedPredecessors == totalPossiblePredecessors)) { return true } } if (mustDecide) { if (state==NodeInstanceState.Started) { cancel(engineData) } else { failSkipOrCancel(engineData, cancelState, ProcessException("Unexpected failure to complete join")) } } return false } private fun Builder.skipTaskImpl(engineData: MutableProcessEngineDataAccess, newState: NodeInstanceState) { // Skipping a join merely triggers a recalculation assert(newState == NodeInstanceState.Skipped || newState == NodeInstanceState.SkippedCancel || newState == NodeInstanceState.SkippedFail) val updateResult = updateTaskState(engineData, newState) processInstanceBuilder.storeChild(this) processInstanceBuilder.store(engineData) if (state.isSkipped) { skipPredecessors(engineData) } } private fun Builder.skipPredecessors(engineData: MutableProcessEngineDataAccess) { if (node.isMultiMerge) return // multimerge joins should not have their predecessors skipped val pseudoContext = PseudoInstance.PseudoContext(processInstanceBuilder) pseudoContext.populatePredecessorsFor(handle) val toSkipCancel = mutableListOf<ProcessNodeInstance<*>>() val predQueue = ArrayDeque<IProcessNodeInstance>()//.apply { add(pseudoContext.getNodeInstance(handle)!!) } for (hpred in pseudoContext.getNodeInstance(handle)!!.predecessors) { val pred = pseudoContext.getNodeInstance(hpred) if (pred?.state?.isFinal == false) predQueue.add(pred) } while (predQueue.isNotEmpty()) { val pred = predQueue.removeFirst() when { pred.state.isFinal && pred.node !is StartNode -> Unit pred is PseudoInstance -> if (pred.node !is Split) { pred.state = NodeInstanceState.AutoCancelled for (hppred in pred.predecessors) { pseudoContext.getNodeInstance(hppred)?.let { predQueue.add(it) } } } pred is ProcessNodeInstance<*> -> { if (pred.node !is Split) { toSkipCancel.add(pred) for (hppred in pred.predecessors) { val ppred = pseudoContext.getNodeInstance(hppred) ?: continue predQueue.add(ppred) } } } } } for (predecessor in toSkipCancel) { processInstanceBuilder.updateChild(predecessor.handle) { cancelAndSkip(engineData) } } } } }
lgpl-3.0
2495824daa19b2a4451e06c41e52722b
39.18617
190
0.599669
6.017523
false
false
false
false
alex-tavella/MooV
core-lib/tmdb/src/main/java/br/com/core/tmdb/api/TmdbRequestInterceptor.kt
1
1975
/* * Copyright 2020 Alex Almeida Tavella * * 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 br.com.core.tmdb.api import br.com.moov.core.di.AppScope import com.squareup.anvil.annotations.ContributesBinding import okhttp3.Interceptor import okhttp3.Response import java.util.Locale import javax.inject.Inject @ContributesBinding(AppScope::class) class TmdbRequestInterceptor @Inject constructor( private val apiKey: String, private val cacheDuration: Long ) : Interceptor { companion object { const val QUERY_PARAM_API_KEY = "api_key" const val QUERY_PARAM_LANGUAGE = "language" const val HEADER_PARAM_CACHE_CONTROL = "Cache-Control" } override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val url = request.url.newBuilder() .addQueryParameter(QUERY_PARAM_API_KEY, apiKey) .addQueryParameter(QUERY_PARAM_LANGUAGE, Locale.getDefault().getLanguageString()) .build() val newRequest = request.newBuilder() .url(url) .addHeader(HEADER_PARAM_CACHE_CONTROL, "public, max-age=$cacheDuration") .build() return chain.proceed(newRequest) } } fun Locale.getLanguageString(): String { val sb = StringBuilder() sb.append(language) if (!country.isNullOrBlank() && country.length == 2) { sb.append("-").append(country) } return sb.toString() }
apache-2.0
72f4038eb44d07f53a541461c94069a5
29.859375
93
0.693165
4.247312
false
false
false
false
pdvrieze/ProcessManager
ProcessEngine/servlet/src/main/java/nl/adaptivity/process/engine/servlet/ServletProcessEngine.kt
1
45475
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine.servlet import net.devrieze.util.* import net.devrieze.util.security.AuthenticationNeededException import net.devrieze.util.security.SYSTEMPRINCIPAL import net.devrieze.util.security.SecureObject import nl.adaptivity.io.Writable import nl.adaptivity.io.WritableReader import nl.adaptivity.messaging.* import nl.adaptivity.process.IMessageService import nl.adaptivity.process.MessageSendingResult import nl.adaptivity.process.engine.* import nl.adaptivity.process.engine.ProcessInstance.ProcessInstanceRef import nl.adaptivity.process.engine.processModel.* import nl.adaptivity.process.messaging.ActivityResponse import nl.adaptivity.process.messaging.EndpointServlet import nl.adaptivity.process.messaging.GenericEndpoint import nl.adaptivity.process.processModel.IXmlMessage import nl.adaptivity.process.processModel.RootProcessModel import nl.adaptivity.process.processModel.engine.* import nl.adaptivity.process.util.Constants import nl.adaptivity.rest.annotations.HttpMethod import nl.adaptivity.rest.annotations.RestMethod import nl.adaptivity.rest.annotations.RestParam import nl.adaptivity.rest.annotations.RestParamType import nl.adaptivity.util.DomUtil import nl.adaptivity.util.SerializableData import nl.adaptivity.util.commitSerializable import nl.adaptivity.xmlutil.* import org.jetbrains.annotations.TestOnly import org.w3.soapEnvelope.Envelope import org.w3c.dom.Element import org.w3c.dom.Node import java.io.* import javax.activation.DataHandler import javax.activation.DataSource import javax.jws.WebMethod import javax.jws.WebParam import javax.jws.WebParam.Mode import javax.servlet.ServletConfig import javax.servlet.ServletException import javax.servlet.http.HttpServletResponse import javax.xml.bind.annotation.XmlElementWrapper import javax.xml.namespace.QName import javax.xml.stream.* import javax.xml.stream.events.* import javax.xml.stream.events.Namespace import javax.xml.transform.Result import javax.xml.transform.Source import java.net.URI import java.security.Principal import java.sql.SQLException import java.util.* import java.util.concurrent.ExecutionException import java.util.concurrent.Future import java.util.logging.Level import java.util.logging.Logger import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * The service representing a process engine. * * @param TR The type of transaction used. Mainly used for testing with memory based storage */ /* @ServiceInfo(targetNamespace = ServletProcessEngine.SERVICE_NS, interfaceNS = ServletProcessEngine.SERVICE_NS, interfaceLocalname = "soap", interfacePrefix = "pe", serviceLocalname = ServletProcessEngine.SERVICE_LOCALNAME) */ open class ServletProcessEngine<TR : ProcessTransaction> : EndpointServlet(), GenericEndpoint { private lateinit var processEngine: ProcessEngine<TR, *> private lateinit var messageService: MessageService override val serviceName: QName get() = QName(Constants.PROCESS_ENGINE_NS, SERVICE_LOCALNAME) override val endpointName: String get() = "soap" override val endpointLocation: URI? get() = null inner class MessageService(localEndpoint: EndpointDescriptor) : IMessageService<ServletProcessEngine.NewServletMessage> { override var localEndpoint: EndpointDescriptor = localEndpoint internal set override fun createMessage(message: IXmlMessage): NewServletMessage { return NewServletMessage(message, localEndpoint) } override fun sendMessage( engineData: ProcessEngineDataAccess, protoMessage: NewServletMessage, activityInstanceContext: ActivityInstanceContext ): MessageSendingResult { val nodeHandle = activityInstanceContext.handle protoMessage.setHandle(engineData, activityInstanceContext) val result = MessagingRegistry.sendMessage( protoMessage, MessagingCompletionListener( nodeHandle, protoMessage.owner ), DataSource::class.java, emptyArray() ) if (result.isCancelled) { return MessageSendingResult.FAILED } if (result.isDone) { try { result.get() return MessageSendingResult.ACKNOWLEDGED } catch (e: ExecutionException) { val cause = e.cause if (cause is RuntimeException) { throw cause } throw RuntimeException(cause) } catch (e: InterruptedException) { return MessageSendingResult.SENT } } return MessageSendingResult.SENT } } private inner class MessagingCompletionListener( private val handle: Handle<SecureObject<ProcessNodeInstance<*>>>, private val owner: Principal ) : CompletionListener<DataSource> { override fun onMessageCompletion(future: Future<out DataSource>) { [email protected](future, handle, owner) } } class NewServletMessage( private val message: IXmlMessage, private val localEndpoint: EndpointDescriptor ) : ISendableMessage, Writable { private var activityInstanceContext: ActivityInstanceContext? = null private var data: Writable? = null internal val owner: Principal get() = activityInstanceContext?.owner ?: throw IllegalStateException("The message has not been initialised with a node yet") private val source: XmlReader get() = message.messageBody.getXmlReader() override fun getDestination(): EndpointDescriptor? { return message.endpointDescriptor } override fun getMethod(): String? { return message.method } override fun getHeaders(): Collection<ISendableMessage.IHeader> { val contentType = message.contentType return if (contentType.isEmpty()) { emptyList() } else { listOf(Header("Content-type", contentType)) } } override fun getBodySource(): Writable? = data override fun getBodyReader(): Reader { val d = data return if (d == null) StringReader("") else WritableReader(d) // XXX see if there's a better way } override fun getContentType(): String { return message.contentType } @Throws(IOException::class) override fun writeTo(destination: Writer) { data!!.writeTo(destination) } fun setHandle(engineData: ProcessEngineDataAccess, activityInstanceContext: ActivityInstanceContext) { this.activityInstanceContext = activityInstanceContext try { val processInstance = engineData.instance(activityInstanceContext.processContext.handle).withPermission() data = activityInstanceContext.instantiateXmlPlaceholders(processInstance, source, false, localEndpoint) } catch (e: Exception) { when (e) { is MessagingException -> throw e else -> throw MessagingException(e) } } } override fun getAttachments(): Map<String, DataSource> { return emptyMap() } companion object { @Throws(FactoryConfigurationError::class, XMLStreamException::class) fun fillInActivityMessage( messageBody: Source, result: Result, nodeInstance: ProcessNodeInstance<*>, localEndpoint: EndpointDescriptor ) { // TODO use multiplatform api val xif = XMLInputFactory.newInstance() val xof = XMLOutputFactory.newInstance() val xer = xif.createXMLEventReader(messageBody) val xew = xof.createXMLEventWriter(result) while (xer.hasNext()) { val event = xer.nextEvent() if (event.isStartElement) { val se = event.asStartElement() val eName = se.name if (Constants.MODIFY_NS_STR == eName.namespaceURI) { @Suppress("UNCHECKED_CAST") val attributes = se.attributes as Iterator<Attribute> when (eName.localPart) { "attribute" -> writeAttribute(nodeInstance, xer, attributes, xew) "element" -> writeElement(nodeInstance, xer, attributes, xew, localEndpoint) else -> throw HttpResponseException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unsupported activity modifier" ) } } else { xew.add(se) } } else { if (event.isCharacters) { val c = event.asCharacters() val charData = c.data var i = 0 while (i < charData.length) { if (!Character.isWhitespace(charData[i])) { break } ++i } if (i == charData.length) { continue // ignore it, and go to next event } } if (event is Namespace) { if (event.namespaceURI != Constants.MODIFY_NS_STR) { xew.add(event) } } else { try { xew.add(event) } catch (e: IllegalStateException) { val errorMessage = StringBuilder("Error adding event: ") errorMessage.append(event.toString()).append(' ') if (event.isStartElement) { errorMessage.append('<').append(event.asStartElement().name).append('>') } else if (event.isEndElement) { errorMessage.append("</").append(event.asEndElement().name).append('>') } logger.log(Level.WARNING, errorMessage.toString(), e) // baos.reset(); baos.close(); throw e } } } } } @Throws(XMLStreamException::class) private fun writeElement( nodeInstance: ProcessNodeInstance<*>, `in`: XMLEventReader, attributes: Iterator<Attribute>, out: XMLEventWriter, localEndpoint: EndpointDescriptor ) { var valueName: String? = null run { while (attributes.hasNext()) { val attr = attributes.next() val attrName = attr.name.localPart if ("value" == attrName) { valueName = attr.value } } } run { val ev = `in`.nextEvent() while (!ev.isEndElement) { if (ev.isStartElement) { throw MessagingFormatException("Violation of schema") } if (ev.isAttribute) { val attr = ev as Attribute val attrName = attr.name.localPart if ("value" == attrName) { valueName = attr.value } } } } if (valueName != null) { val xef = XMLEventFactory.newInstance() if ("handle" == valueName) { out.add(xef.createCharacters(java.lang.Long.toString(nodeInstance.getHandleValue()))) } else if ("endpoint" == valueName) { val qname1 = QName(Constants.MY_JBI_NS_STR, "endpointDescriptor", "") val namespaces = listOf( xef.createNamespace( "", Constants.MY_JBI_NS_STR ) ) out.add(xef.createStartElement(qname1, null, namespaces.iterator())) run { // EndpointDescriptor localEndpoint = nodeInstance.getProcessInstance().getEngine().getLocalEndpoint(); out.add(xef.createAttribute("serviceNS", localEndpoint.serviceName!!.namespaceURI)) out.add(xef.createAttribute("serviceLocalName", localEndpoint.serviceName!!.localPart)) out.add(xef.createAttribute("endpointName", localEndpoint.endpointName)) out.add( xef.createAttribute( "endpointLocation", localEndpoint.endpointLocation!!.toString() ) ) } out.add(xef.createEndElement(qname1, namespaces.iterator())) } } else { throw MessagingFormatException("Missing parameter name") } } @Throws(XMLStreamException::class) private fun writeAttribute( nodeInstance: ProcessNodeInstance<*>, `in`: XMLEventReader, attributes: Iterator<Attribute>, out: XMLEventWriter ) { var valueName: String? = null var paramName: String? = null run { while (attributes.hasNext()) { val attr = attributes.next() val attrName = attr.name.localPart if ("value" == attrName) { valueName = attr.value } else if ("name" == attrName) { paramName = attr.value } } } run { val ev = `in`.nextEvent() while (!ev.isEndElement) { if (ev.isStartElement) { throw MessagingFormatException("Violation of schema") } if (ev.isAttribute) { val attr = ev as Attribute val attrName = attr.name.localPart if ("value" == attrName) { valueName = attr.value } else if ("name" == attrName) { paramName = attr.value } } } } if (valueName != null) { val xef = XMLEventFactory.newInstance() when (valueName) { "handle" -> out.add( xef.createAttribute(paramName ?: "handle", nodeInstance.getHandleValue().toString()) ) "owner" -> out.add(xef.createAttribute(paramName ?: "owner", nodeInstance.owner.name)) "instancehandle" -> out.add( xef.createAttribute(paramName ?: "instancehandle", nodeInstance.owner.name) ) } } else { throw MessagingFormatException("Missing parameter name") } } } } override fun destroy() { MessagingRegistry.getMessenger().unregisterEndpoint(this) } override fun getServletInfo(): String { return "ServletProcessEngine" } @TestOnly protected fun init(engine: ProcessEngine<TR, *>) { processEngine = engine } @Throws(ServletException::class) override fun init(config: ServletConfig) { super.init(config) val hostname: String? = config.getInitParameter("hostname") ?: "localhost" val port = config.getInitParameter("port") val localURL: URI localURL = when (port) { null -> URI.create("http://" + hostname + config.servletContext.contextPath) else -> URI.create("http://" + hostname + ":" + port + config.servletContext.contextPath) } messageService = MessageService(asEndpoint(localURL)) val logger = Logger.getLogger(ServletProcessEngine::class.java.name) processEngine = ProcessEngine.newInstance(messageService, logger) as ProcessEngine<TR, *> MessagingRegistry.getMessenger().registerEndpoint(this) } /** * Get the list of all process models in the engine. This will be limited to user owned ones. The list will contain only * a summary of each model including name, id and uuid, not the content. * * XXX check security properly. */ @RestMethod(method = HttpMethod.GET, path = "/processModels") fun getProcesModelRefs( @RestParam( type = RestParamType.PRINCIPAL ) user: Principal ): SerializableData<List<IProcessModelRef<*, *>>> = translateExceptions { processEngine.startTransaction().use { transaction -> val processModels = processEngine.getProcessModels(transaction.readableEngineData, user) val list = ArrayList<IProcessModelRef<ExecutableProcessNode, ExecutableProcessModel>>() for (pm in processModels) { list.add(pm.withPermission().ref) } return transaction.commitSerializable(list, REFS_TAG) } } /** * Get the full process model content for the model with the given handle. * @param handle The handle of the process model * @param user The user whose permissions are verified * @return The process model * @throws FileNotFoundException When the model does not exist. This is translated to a 404 error in http. */ @RestMethod(method = HttpMethod.GET, path = "/processModels/\${handle}") fun getProcessModel( @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): ExecutableProcessModel = translateExceptions { try { processEngine.startTransaction().use { transaction -> val handle1 = if (handle < 0) Handle.invalid<SecureObject<ExecutableProcessModel>>() else Handle(handle) processEngine.invalidateModelCache(handle1) return transaction.commit<ExecutableProcessModel>( processEngine.getProcessModel(transaction.readableEngineData, handle1, user) ?: throw FileNotFoundException() ) } } catch (e: NullPointerException) { throw HandleNotFoundException("Process handle invalid", e) } } /** * Update the process model with the given handle. * @param handle The model handle * @param attachment The actual new model * @param user The user performing the update. This will be verified against ownership and permissions * @return A reference to the model. This may include a newly generated uuid if not was provided. * @throws IOException */ @RestMethod(method = HttpMethod.POST, path = "/processModels/\${handle}") @Throws(IOException::class) fun updateProcessModel( @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @RestParam(name = "processUpload", type = RestParamType.ATTACHMENT) attachment: DataHandler, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): ProcessModelRef<*, *> = translateExceptions { val builder = XmlStreaming.deSerialize(attachment.inputStream, XmlProcessModel.Builder::class.java) return updateProcessModel(handle, builder, user) } /** * Update the process model with the given handle. * @param handle The model handle * @param processModelBuilder The actual new model * @param user The user performing the update. This will be verified against ownership and permissions * @return A reference to the model. This may include a newly generated uuid if not was provided. */ @WebMethod(operationName = "updateProcessModel") fun updateProcessModel( @WebParam(name = "handle") handle: Long, @WebParam( name = "processModel", mode = Mode.IN ) processModelBuilder: RootProcessModel.Builder?, @WebParam(name = "principal", mode = Mode.IN, header = true) @RestParam( type = RestParamType.PRINCIPAL ) user: Principal? ) : ProcessModelRef<*, *> = translateExceptions { if (user == null) throw AuthenticationNeededException("There is no user associated with this request") if (processModelBuilder != null) { processModelBuilder.handle = handle try { processEngine.startTransaction().use { transaction -> val updatedRef = processEngine.updateProcessModel( transaction, if (handle < 0) Handle.invalid() else Handle(handle), ExecutableProcessModel(processModelBuilder), user ) val update2 = ProcessModelRef.get(updatedRef) return transaction.commit(update2) } } catch (e: SQLException) { logger.log(Level.WARNING, "Error updating process model", e) throw HttpResponseException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e) } } throw HttpResponseException(HttpServletResponse.SC_BAD_REQUEST, "The posted process model is not valid") } /** * Add a process model to the system. * @param attachment The process model to add. * @param owner The creator/owner of the model. * @return A reference to the model with handle and a new uuid if none was provided. */ @RestMethod(method = HttpMethod.POST, path = "/processModels") @Throws(IOException::class) fun postProcessModel( @RestParam(name = "processUpload", type = RestParamType.ATTACHMENT) attachment: DataHandler, @RestParam(type = RestParamType.PRINCIPAL) owner: Principal ): ProcessModelRef<*, *>? = translateExceptions { val processModel = XmlStreaming.deSerialize(attachment.inputStream, XmlProcessModel.Builder::class.java) return postProcessModel(processModel, owner) } /** * Add a process model to the system. * @param processModel The process model to add. * @param owner The creator/owner of the model. * @return A reference to the model with handle and a new uuid if none was provided. */ @WebMethod(operationName = "postProcessModel") fun postProcessModel( @WebParam(name = "processModel", mode = Mode.IN) processModel: XmlProcessModel.Builder?, @RestParam(type = RestParamType.PRINCIPAL) @WebParam(name = "principal", mode = Mode.IN, header = true) owner: Principal? ) : ProcessModelRef<*, *>? = translateExceptions { if (owner == null) throw AuthenticationNeededException("There is no user associated with this request") if (processModel != null) { processModel.handle = -1 // The handle cannot be set processEngine.startTransaction().use { transaction -> val newModelRef = processEngine.addProcessModel(transaction, processModel, owner) return transaction.commit(ProcessModelRef.get(newModelRef)) } } return null } /** * Rename the given process model. * @param handle The handle to the model * @param name The new name * @param user The user performing the action. */ @RestMethod(method = HttpMethod.POST, path = "/processModels/\${handle}") @Throws(FileNotFoundException::class) fun renameProcess( @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @RestParam(name = "name", type = RestParamType.QUERY) name: String, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ) { processEngine.renameProcessModel(user, if (handle < 0) Handle.invalid() else Handle(handle), name) } /** * Delete the process model. * @param handle The handle of the process model to delete * @param user A user with permission to delete the model. */ @RestMethod(method = HttpMethod.DELETE, path = "/processModels/\${handle}") fun deleteProcess( @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ) = translateExceptions { processEngine.startTransaction().use { transaction -> if (!processEngine.removeProcessModel( transaction, if (handle < 0) Handle.invalid() else Handle(handle), user )) { throw HttpResponseException(HttpServletResponse.SC_NOT_FOUND, "The given process does not exist") } transaction.commit() } } /** * Create a new process instance and start it. * * @param handle The handle of the process to start. * @param name The name that will allow the user to remember the instance. If `null` a name will * be assigned. This name has no semantic meaning. * @param owner The owner of the process instance. (Who started it). * @return A handle to the process */ @WebMethod @RestMethod(method = HttpMethod.POST, path = "/processModels/\${handle}", query = ["op=newInstance"]) fun startProcess( @WebParam(name = "handle") @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @WebParam(name = "name") @RestParam(name = "name", type = RestParamType.QUERY) name: String?, @WebParam(name = "uuid") @RestParam(name = "uuid", type = RestParamType.QUERY) uuid: String?, @WebParam(name = "owner", header = true) @RestParam(type = RestParamType.PRINCIPAL) owner: Principal ): SerializableData<HProcessInstance> = translateExceptions { processEngine.startTransaction().use { transaction -> val uuid: UUID = uuid?.let { UUID.fromString(it) } ?: UUID.randomUUID() return transaction.commitSerializable( processEngine.startProcess( transaction, owner, if (handle < 0) Handle.invalid() else Handle(handle), name ?: "<unnamed>", uuid, null ), ProcessInstance.HANDLEELEMENTNAME ) } } /** * Get a list of all process instances owned by the current user. This will provide a summary list, providing a subset. * of information from the process instance. * @param owner The user. * @return A list of process instances. */ @RestMethod(method = HttpMethod.GET, path = "/processInstances") @XmlElementWrapper(name = "processInstances", namespace = Constants.PROCESS_ENGINE_NS) fun getProcesInstanceRefs(@RestParam(type = RestParamType.PRINCIPAL) owner: Principal?) : SerializableData<Collection<ProcessInstanceRef>> = translateExceptions { if (owner == null) throw AuthenticationNeededException() processEngine.startTransaction().use { transaction -> val list = ArrayList<ProcessInstanceRef>() for (pi in processEngine.getOwnedProcessInstances(transaction, owner)) { list.add(pi.ref) } transaction.commitSerializable(list, INSTANCEREFS_TAG) } } /** * Get the given process instance. * @param handle The handle of the instance. * @param user A user with permission to see the model. * @return The full process instance. */ @RestMethod(method = HttpMethod.GET, path = "/processInstances/\${handle}") fun getProcessInstance( @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @RestParam(type = RestParamType.PRINCIPAL) user: Principal? ): SerializableData<ProcessInstance> = translateExceptions { processEngine.startTransaction().use { transaction -> return transaction.commitSerializable( processEngine.getProcessInstance( transaction, if (handle < 0) Handle.invalid() else Handle(handle), user!! ) ) } } /** * Cause the process instance state to be re-evaluated. For failed service invocations, this will cause the server to * try again. * @param handle The handle of the instance * @param user A user with appropriate permissions. * @return A string indicating success. */ @RestMethod(method = HttpMethod.GET, path = "/processInstances/\${handle}", query = ["op=tickle"]) @Throws(FileNotFoundException::class) fun tickleProcessInstance( @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): String = translateExceptions { processEngine.startTransaction().use { transaction -> transaction.commit(processEngine.tickleInstance(transaction, handle, user)) return "success" } } /** * Cancel the process instance execution. This will cause all aspects of the instance to be cancelled. Note that this * cannot undo the past. * @param handle The instance to cancel * @param user A user with permission to cancel the instance. * @return The instance that was cancelled. */ @RestMethod(method = HttpMethod.DELETE, path = "/processInstances/\${handle}") fun cancelProcessInstance( @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): ProcessInstance = translateExceptions { processEngine.startTransaction().use { transaction -> return transaction.commit( processEngine.cancelInstance(transaction, if (handle < 0) Handle.invalid() else Handle(handle), user) ) } } /** * Get the data for a specific task. * @param handle The handle * @param user A user with appropriate permissions * @return The node instance. * @throws FileNotFoundException * @throws SQLException * @throws XmlException */ @WebMethod(operationName = "getProcessNodeInstance") fun getProcessNodeInstanceSoap( @WebParam(name = "handle", mode = Mode.IN) handle: Long, @WebParam(name = "user", mode = Mode.IN) user: Principal ): XmlProcessNodeInstance? = translateExceptions { return getProcessNodeInstance(handle, user) } /** * Get the information for a specific task. * @param handle The handle of the task * @param user A user with appropriate permissions * @return the task * @throws FileNotFoundException * @throws SQLException * @throws XmlException */ @RestMethod(method = HttpMethod.GET, path = "/tasks/\${handle}") fun getProcessNodeInstance( @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): XmlProcessNodeInstance? = translateExceptions { processEngine.startTransaction().use { transaction -> val nodeInstance = processEngine.getNodeInstance( transaction, if (handle < 0) Handle.invalid() else Handle(handle), user ) ?: return null return transaction.commit( nodeInstance.toSerializable(transaction.readableEngineData, messageService.localEndpoint) ) } } /** * Update the state of a task. * @param handle Handle of the task to update * @param newState The new state * @param user A user with appropriate permissions * @return the new state of the task. This may be different than requested, for example due to engine semantics. (either further, or no change at all) */ @WebMethod(operationName = "updateTaskState") @Throws(FileNotFoundException::class) fun updateTaskStateSoap( @WebParam(name = "handle", mode = Mode.IN) handle: Long, @WebParam(name = "state", mode = Mode.IN) newState: NodeInstanceState, @WebParam(name = "user", mode = Mode.IN) user: Principal ): NodeInstanceState = translateExceptions { return updateTaskState(handle, newState, user) } /** * Update the state of a task. * @param handle Handle of the task to update * @param newState The new state * @param user A user with appropriate permissions * @return the new state of the task. This may be different than requested, for example due to engine semantics. (either further, or no change at all) */ @RestMethod(method = HttpMethod.POST, path = "/tasks/\${handle}", query = ["state"]) fun updateTaskState( @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @RestParam(name = "state", type = RestParamType.QUERY) newState: NodeInstanceState, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): NodeInstanceState = translateExceptions { try { processEngine.startTransaction().use { transaction -> return transaction.commit( processEngine.updateTaskState( transaction, if (handle < 0) Handle.invalid() else Handle(handle), newState, user ) ) } } catch (e: SQLException) { throw HttpResponseException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e) } } /** * finish a task. Process aware services will need to call this to signal completion. * @param handle Handle of the task to update * @param payload An XML document that is the "result" of the service. * @param user A user with appropriate permissions * @return the new state of the task. This may be different than requested, for example due to engine semantics. (either further, or no change at all) */ @WebMethod(operationName = "finishTask") @RestMethod(method = HttpMethod.POST, path = "/tasks/\${handle}", query = ["state=Complete"]) fun finishTask( @WebParam(name = "handle", mode = Mode.IN) @RestParam(name = "handle", type = RestParamType.VAR) handle: Long, @WebParam(name = "payload", mode = Mode.IN) @RestParam(name = "payload", type = RestParamType.QUERY) payload: Node, @RestParam(type = RestParamType.PRINCIPAL) @WebParam(name = "principal", mode = Mode.IN, header = true) user: Principal ) : NodeInstanceState = translateExceptions { val payloadNode = DomUtil.nodeToFragment(payload) processEngine.startTransaction().use { transaction -> return transaction.commit( processEngine.finishTask( transaction, if (handle < 0) Handle.invalid() else Handle(handle), payloadNode, user ).state ) } } /** * Handle the completing of sending a message and receiving some sort of * reply. If the reply is an ActivityResponse message we handle that * specially. * @throws SQLException */ @OptIn(ProcessInstanceStorage::class) @Throws(FileNotFoundException::class) fun onMessageCompletion( future: Future<out DataSource>, handle: Handle<SecureObject<ProcessNodeInstance<*>>>, owner: Principal ) = translateExceptions { // XXX do this better if (future.isCancelled) { processEngine.startTransaction().use { transaction -> processEngine.cancelledTask(transaction, handle, owner) transaction.commit() } } else { try { val result = future.get() processEngine.startTransaction().use { transaction -> val inst = processEngine.getNodeInstance(transaction, handle, SYSTEMPRINCIPAL) ?: throw HttpResponseException( 404, "The process node with handle $handle does not exist or is not visible" ) assert(inst.state === NodeInstanceState.Pending) if (inst.state === NodeInstanceState.Pending) { val processInstance = transaction.readableEngineData.instance( inst.hProcessInstance ).withPermission() processInstance.update(transaction.writableEngineData) { updateChild(inst) { state = NodeInstanceState.Sent } } } transaction.commit() } try { val domResult = DomUtil.tryParseXml(result.inputStream) ?: throw HttpResponseException( HttpServletResponse.SC_BAD_REQUEST, "Content is not an XML document" ) var rootNode: Element? = domResult.documentElement // If we are seeing a Soap Envelope, if there is an activity response in the header treat that as the root node. if (Envelope.NAMESPACE == rootNode!!.namespaceURI && Envelope.ELEMENTLOCALNAME == rootNode.localName) { val header = DomUtil.getFirstChild( rootNode, Envelope.NAMESPACE, org.w3.soapEnvelope.Header.ELEMENTLOCALNAME ) if (header != null) { rootNode = DomUtil.getFirstChild( header, Constants.PROCESS_ENGINE_NS, ActivityResponse.ELEMENTLOCALNAME ) } } if (rootNode != null) { // If we receive an ActivityResponse, treat that specially. if (Constants.PROCESS_ENGINE_NS == rootNode.namespaceURI && ActivityResponse.ELEMENTLOCALNAME == rootNode.localName) { val taskStateAttr = rootNode.getAttribute(ActivityResponse.ATTRTASKSTATE) try { processEngine.startTransaction().use { transaction -> val nodeInstanceState = NodeInstanceState.valueOf(taskStateAttr) processEngine.updateTaskState(transaction, handle, nodeInstanceState, owner) transaction.commit() return } } catch (e: NullPointerException) { e.printStackTrace() // ignore } catch (e: IllegalArgumentException) { processEngine.startTransaction().use { transaction -> processEngine.errorTask(transaction, handle, e, owner) transaction.commit() } } } } else { processEngine.startTransaction().use { transaction -> // XXX By default assume that we have finished the task processEngine.finishedTask(transaction, handle, result, owner) transaction.commit() } } } catch (e: NullPointerException) { // ignore } catch (e: IOException) { // It's not xml or has more than one xml element ignore that and fall back to handling unknown services } } catch (e: ExecutionException) { logger.log(Level.INFO, "Task $handle: Error in messaging", e.cause) processEngine.startTransaction().use { transaction -> processEngine.errorTask(transaction, handle, e.cause ?: e, owner) transaction.commit() } } catch (e: InterruptedException) { logger.log(Level.INFO, "Task $handle: Interrupted", e) processEngine.startTransaction().use { transaction -> processEngine.cancelledTask(transaction, handle, owner) transaction.commit() } } } } override fun isSameService(other: EndpointDescriptor?): Boolean { return Constants.PROCESS_ENGINE_NS == other!!.serviceName!!.namespaceURI && SERVICE_LOCALNAME == other.serviceName!!.localPart && endpointName == other.endpointName } override fun initEndpoint(config: ServletConfig) { // We know our config, don't do anything. } protected open fun setLocalEndpoint(localURL: URI) { messageService.localEndpoint = asEndpoint(localURL) } private fun asEndpoint(localURL: URI): EndpointDescriptorImpl { return EndpointDescriptorImpl(serviceName, endpointName, localURL) } companion object { private const val serialVersionUID = -6277449163953383974L @Suppress("MemberVisibilityCanBePrivate") const val SERVICE_NS = Constants.PROCESS_ENGINE_NS const val SERVICE_LOCALNAME = "ProcessEngine" @Suppress("unused") @JvmStatic val SERVICE_QNAME = QName(SERVICE_NS, SERVICE_LOCALNAME) /* * Methods inherited from JBIProcessEngine */ internal val logger: Logger get() { val logger = Logger.getLogger(ServletProcessEngine::class.java.name) logger.level = Level.ALL return logger } private val REFS_TAG = QName(SERVICE_NS, "processModels") private val INSTANCEREFS_TAG = QName(SERVICE_NS, "processInstances") } } @OptIn(ExperimentalContracts::class) internal inline fun <E : GenericEndpoint, R> E.translateExceptions(body: E.() -> R): R { contract { callsInPlace(body, InvocationKind.EXACTLY_ONCE) } try { return body() } catch (e: HandleNotFoundException) { throw HttpResponseException(HttpServletResponse.SC_NOT_FOUND, e) } catch (e: SQLException) { ServletProcessEngine.logger.log(Level.WARNING, "Error getting process model references", e) throw HttpResponseException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e) } }
lgpl-3.0
20fe851888b3839d4eb8dfa531ac102f
40.303361
154
0.575811
5.551825
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/visiblequests/VisibleQuestTypeDao.kt
1
2009
package de.westnordost.streetcomplete.data.visiblequests import de.westnordost.streetcomplete.data.Database import de.westnordost.streetcomplete.data.visiblequests.VisibleQuestTypeTable.Columns.QUEST_PRESET_ID import javax.inject.Inject import de.westnordost.streetcomplete.data.visiblequests.VisibleQuestTypeTable.Columns.QUEST_TYPE import de.westnordost.streetcomplete.data.visiblequests.VisibleQuestTypeTable.Columns.VISIBILITY import de.westnordost.streetcomplete.data.visiblequests.VisibleQuestTypeTable.NAME /** Stores which quest types are visible by user selection and which are not */ class VisibleQuestTypeDao @Inject constructor(private val db: Database) { fun put(presetId: Long, questTypeName: String, visible: Boolean) { db.replace(NAME, listOf( QUEST_PRESET_ID to presetId, QUEST_TYPE to questTypeName, VISIBILITY to if (visible) 1 else 0 )) } fun put(presetId: Long, questTypeNames: Iterable<String>, visible: Boolean) { val vis = if (visible) 1 else 0 db.replaceMany(NAME, arrayOf(QUEST_PRESET_ID, QUEST_TYPE, VISIBILITY), questTypeNames.map { arrayOf(presetId, it, vis) } ) } fun get(presetId: Long, questTypeName: String): Boolean = db.queryOne(NAME, columns = arrayOf(VISIBILITY), where = "$QUEST_PRESET_ID = ? AND $QUEST_TYPE = ?", args = arrayOf(presetId, questTypeName) ) { it.getInt(VISIBILITY) != 0 } ?: true fun getAll(presetId: Long): MutableMap<String, Boolean> { val result = mutableMapOf<String, Boolean>() db.query(NAME, where = "$QUEST_PRESET_ID = $presetId") { cursor -> val questTypeName = cursor.getString(QUEST_TYPE) val visible = cursor.getInt(VISIBILITY) != 0 result[questTypeName] = visible } return result } fun clear(presetId: Long) { db.delete(NAME, where = "$QUEST_PRESET_ID = $presetId") } }
gpl-3.0
da6038265d2883806b05ea10f5c5694a
38.392157
101
0.674963
4.348485
false
false
false
false
kropp/intellij-makefile
src/main/kotlin/name/kropp/intellij/makefile/MakefileLangCodeStyleSettingsProvider.kt
1
1050
package name.kropp.intellij.makefile import com.intellij.application.options.* import com.intellij.psi.codeStyle.* class MakefileLangCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() { override fun customizeDefaults(commonSettings: CommonCodeStyleSettings, indentOptions: CommonCodeStyleSettings.IndentOptions) { indentOptions.TAB_SIZE = 4 indentOptions.USE_TAB_CHARACTER = true } override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: SettingsType) { if (settingsType == SettingsType.INDENT_SETTINGS) { consumer.showStandardOptions("TAB_SIZE") } } override fun getCodeSample(settingsType: SettingsType): String { return """# Simple Makefile include make.mk all: hello GCC = gcc \ -O2 <target>.o.c</target>: ifeq ($(FOO),'bar') ${'\t'}$(GCC) -c qwe \ -Wall else ${'\t'}echo "Hello World" endif""" } override fun getIndentOptionsEditor(): IndentOptionsEditor = IndentOptionsEditor() override fun getLanguage() = MakefileLanguage }
mit
63ae3b361fd91169f655ddde7817e830
25.948718
129
0.73619
4.411765
false
false
false
false
PKRoma/github-android
app/src/main/java/com/github/pockethub/android/ui/item/news/CreateEventItem.kt
5
1392
package com.github.pockethub.android.ui.item.news import android.view.View import androidx.core.text.buildSpannedString import com.github.pockethub.android.ui.view.OcticonTextView import com.github.pockethub.android.util.AvatarLoader import com.meisolsson.githubsdk.model.GitHubEvent import com.meisolsson.githubsdk.model.payload.CreatePayload import com.xwray.groupie.kotlinandroidextensions.ViewHolder import kotlinx.android.synthetic.main.news_item.* class CreateEventItem( avatarLoader: AvatarLoader, gitHubEvent: GitHubEvent ) : NewsItem(avatarLoader, gitHubEvent) { override fun bind(holder: ViewHolder, position: Int) { super.bind(holder, position) holder.tv_event_icon.text = OcticonTextView.ICON_CREATE holder.tv_event.text = buildSpannedString { val context = holder.root.context boldActor(context, this, gitHubEvent) val payload = gitHubEvent.payload() as CreatePayload? val refType: String? = payload?.refType()?.name?.toLowerCase() append(" created $refType ") if ("repository" != refType) { append("${payload?.ref()} at ") boldRepo(context, this, gitHubEvent) } else { boldRepoName(context, this, gitHubEvent) } } holder.tv_event_details.visibility = View.GONE } }
apache-2.0
77bcee5ba814f7004174b7285a00005e
36.621622
74
0.679598
4.578947
false
false
false
false
devmil/PaperLaunch
app/src/main/java/de/devmil/paperlaunch/locale/EditSettingActivity.kt
1
2672
package de.devmil.paperlaunch.locale import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.RadioButton import android.widget.Toolbar import de.devmil.paperlaunch.R class EditSettingActivity : Activity() { private var btnOk: Button? = null private var rbEnable: RadioButton? = null private var rbDisable: RadioButton? = null private var toolbar: Toolbar? = null private var imgResult: ImageView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edit_setting) btnOk = findViewById(R.id.activity_edit_setting_btn_ok) rbEnable = findViewById(R.id.activity_edit_setting_rbEnable) rbDisable = findViewById(R.id.activity_edit_setting_rbDisable) toolbar = findViewById(R.id.activity_edit_settings_toolbar) imgResult = findViewById(R.id.activity_edit_setting_img_result) setActionBar(toolbar) var isEnabled = true if(intent.hasExtra(LocaleConstants.EXTRA_BUNDLE)) { val localeBundle = intent.getBundleExtra(LocaleConstants.EXTRA_BUNDLE) if(LocaleBundle.isValid(localeBundle)) { isEnabled = LocaleBundle.from(localeBundle).isEnabled } } rbEnable?.isChecked = isEnabled rbDisable?.isChecked = !isEnabled rbEnable?.setOnCheckedChangeListener { _, _ -> updateResultImage() } rbDisable?.setOnCheckedChangeListener { _, _ -> updateResultImage() } btnOk?.setOnClickListener { rbEnable?.let { itRbEnable -> val localeBundle = LocaleBundle(itRbEnable.isChecked) val resultIntent = Intent() resultIntent.putExtra(LocaleConstants.EXTRA_BUNDLE, localeBundle.toBundle()) val stringResource = if(itRbEnable.isChecked) R.string.activity_edit_setting_description_enable else R.string.activity_edit_setting_description_disable resultIntent.putExtra(LocaleConstants.EXTRA_BLURB, getString(stringResource)) setResult(RESULT_OK, resultIntent) } finish() } updateResultImage() } private fun updateResultImage() { val isEnabled = rbEnable?.isChecked ?: false imgResult?.setImageResource(if(isEnabled) R.mipmap.ic_play_arrow_black_24dp else R.mipmap.ic_pause_black_24dp) } }
apache-2.0
3a414da9edbdaf92088059b6f50c1952
34.626667
118
0.648578
4.849365
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/structure/latex/LatexPartPresentation.kt
1
844
package nl.hannahsten.texifyidea.structure.latex import nl.hannahsten.texifyidea.TexifyIcons import nl.hannahsten.texifyidea.psi.LatexCommands import nl.hannahsten.texifyidea.structure.EditableHintPresentation /** * @author Hannah Schellekens */ class LatexPartPresentation(partCommand: LatexCommands) : EditableHintPresentation { private val partName: String private var hint = "" init { if (partCommand.commandToken.text != "\\part") { throw IllegalArgumentException("command is no \\part-command") } this.partName = partCommand.requiredParameters[0] } override fun getPresentableText() = partName override fun getLocationString() = hint override fun getIcon(b: Boolean) = TexifyIcons.DOT_PART override fun setHint(hint: String) { this.hint = hint } }
mit
d7387d963999ed7b47b54ea94aa2e6ce
25.40625
84
0.716825
4.768362
false
false
false
false
renyuneyun/Easer
app/src/main/java/ryey/easer/ErrorSender.kt
1
2090
/* * Copyright (c) 2016 - 2019 Rui Zhao <[email protected]> * * This file is part of Easer. * * Easer 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. * * Easer 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 Easer. If not, see <http://www.gnu.org/licenses/>. */ package ryey.easer import android.content.Context import org.acra.ReportField import org.acra.data.CrashReportData import org.acra.sender.ReportSender import java.io.File import java.io.FileWriter import java.text.SimpleDateFormat import java.util.* class ErrorSender : ReportSender { override fun send(context: Context, errorContent: CrashReportData) { if (SettingsUtils.logging(context)) { val dir = File(EaserApplication.LOG_DIR) if (!dir.exists()) { dir.mkdirs() } val dateFormat = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss") val date = Date() val filename = dateFormat.format(date) + ".log" val reportFile = File(dir, filename) FileWriter(reportFile).use { for (elem in FIELDS) { it.append("%s: %s\n".format(elem, errorContent.getString(elem))) } } } } companion object { val FIELDS = arrayOf( ReportField.BUILD_CONFIG, ReportField.APP_VERSION_CODE, ReportField.USER_CRASH_DATE, ReportField.ANDROID_VERSION, ReportField.BRAND, ReportField.PHONE_MODEL, ReportField.PRODUCT, ReportField.STACK_TRACE ) } }
gpl-3.0
d8c062f801888f8e701d5611ea994636
32.190476
84
0.627751
4.318182
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-android
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/components/AdProcessor.kt
1
3011
package tv.superawesome.sdk.publisher.common.components import tv.superawesome.sdk.publisher.common.datasources.NetworkDataSourceType import tv.superawesome.sdk.publisher.common.extensions.baseUrl import tv.superawesome.sdk.publisher.common.models.* import tv.superawesome.sdk.publisher.common.network.DataResult interface AdProcessorType { suspend fun process(placementId: Int, ad: Ad): DataResult<AdResponse> } class AdProcessor( private val htmlFormatter: HtmlFormatterType, private val vastParser: VastParserType, private val networkDataSource: NetworkDataSourceType, private val encoder: EncoderType, ) : AdProcessorType { override suspend fun process(placementId: Int, ad: Ad): DataResult<AdResponse> { val response = AdResponse(placementId, ad) when (ad.creative.format) { CreativeFormatType.ImageWithLink -> { response.html = htmlFormatter.formatImageIntoHtml(ad) response.baseUrl = ad.creative.details.image?.baseUrl } CreativeFormatType.RichMedia -> { response.html = htmlFormatter.formatRichMediaIntoHtml(placementId, ad) response.baseUrl = ad.creative.details.url?.baseUrl } CreativeFormatType.Tag -> { response.html = htmlFormatter.formatTagIntoHtml(ad) response.baseUrl = Constants.defaultSuperAwesomeUrl } CreativeFormatType.Video -> { if (ad.isVpaid) { response.html = ad.creative.details.tag } else { ad.creative.details.vast?.let { url -> response.vast = handleVast(url, null) response.baseUrl = response.vast?.url?.baseUrl response.vast?.url?.let { when (val downloadFileResult = networkDataSource.downloadFile(it)) { is DataResult.Success -> response.filePath = downloadFileResult.value is DataResult.Failure -> return downloadFileResult } } ?: return DataResult.Failure(Exception("empty url")) } } } } ad.creative.referral?.let { response.referral = encoder.encodeUrlParamsFromObject(it.toMap()) } return DataResult.Success(response) } private suspend fun handleVast(url: String, initialVast: VastAd?): VastAd? { val result = networkDataSource.getData(url) if (result is DataResult.Success) { val vast = vastParser.parse(result.value) if (vast?.type == VastType.Wrapper && vast.redirect != null) { val mergedVast = vast.merge(initialVast) return handleVast(vast.redirect, mergedVast) } return vast } return initialVast } }
lgpl-3.0
dd3a2afd27720ddabe1fa37e5de81f76
40.819444
96
0.594819
4.952303
false
false
false
false
EricssonResearch/scott-eu
lyo-services/webapp-twin-robot/src/main/java/se/ericsson/cf/scott/sandbox/twin/xtra/trs/TrsMqttPlanManager.kt
1
5258
/* * Copyright (c) 2019 Ericsson Research and others * * 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 se.ericsson.cf.scott.sandbox.twin.xtra.trs import eu.scott.warehouse.domains.trs.TrsServerAck import eu.scott.warehouse.domains.trs.TrsServerAnnouncement import eu.scott.warehouse.domains.trs.TrsXConstants import eu.scott.warehouse.lib.MqttTrsServices import eu.scott.warehouse.lib.MqttTopics import org.eclipse.lyo.oslc4j.core.OSLC4JUtils import org.eclipse.lyo.oslc4j.core.exception.LyoModelException import org.eclipse.lyo.oslc4j.provider.jena.JenaModelHelper import org.eclipse.paho.client.mqttv3.MqttClient import org.eclipse.paho.client.mqttv3.MqttException import org.eclipse.paho.client.mqttv3.MqttMessage import org.slf4j.LoggerFactory import se.ericsson.cf.scott.sandbox.twin.xtra.TwinAdaptorHelper import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import javax.ws.rs.core.UriBuilder import kotlin.math.roundToLong class TrsMqttPlanManager() { private val log = LoggerFactory.getLogger(javaClass) private lateinit var mqttClient: MqttClient private lateinit var trsTopic: String constructor(mqttClient: MqttClient) : this() { this.mqttClient = mqttClient } fun connectAndSubscribeToPlans() { try { registerWithWHC(mqttClient) } catch (e: MqttException) { log.error("Failed to connect to the MQTT broker") } } fun unregisterTwinAndDisconnect() { try { // we need to send LWT by hand due to a clean disconnect mqttClient.publish(MqttTopics.REGISTRATION_ANNOUNCE, getTwinUnregistrationMessage().payload, 2, false) mqttClient.disconnect() log.debug("Disconnected from the MQTT broker") } catch (e: MqttException) { log.error("Failed to disconnect from the MQTT broker") } } private fun registerWithWHC(mqttClient: MqttClient) { val latch = CountDownLatch(1) try { mqttClient.subscribe(MqttTopics.REGISTRATION_ACK) { _, message -> completeRegistration(message, latch) } } catch (e: MqttException) { log.error("Something went wrong with the REG_ACK subscription", e) } try { var n = 1 while (latch.count > 0) { // back off exponentially but no more than 30s val backoffDelay = (Math.exp(n+2.0)*2).coerceAtMost(30000.0) log.trace("Posting the registration message") mqttClient.publish(MqttTopics.REGISTRATION_ANNOUNCE, getTwinRegistrationMessage()) latch.await(backoffDelay.roundToLong(), TimeUnit.MILLISECONDS) if (latch.count > 0) { log.warn("Failed to register the twin with the WHC, attempting again") } // give up after 10 attempts if(n <= 10) { n += 1 } else { log.error("Give up on registration with the WHC") break } } } catch (e: MqttException) { log.error("Failed to publish the twin registration message") log.debug("Failed to publish the twin registration message", e) } catch (e: InterruptedException) { log.error("The program was interrupted before the latch reached zero") } } private fun completeRegistration(message: MqttMessage, latch: CountDownLatch) { val model = MqttTrsServices.extractModelFromMessage(message) try { val serverAck = JenaModelHelper.unmarshalSingle(model, TrsServerAck::class.java) if (getTwinUUID() == serverAck.adaptorId) { log.debug("The WHC registration of the {} has been confirmed", getTwinUUID()) trsTopic = serverAck.trsTopic latch.countDown() } } catch (e: LyoModelException) { log.error("Error unmarshalling TrsServerAck from the server response", e) } } // HELPERS private fun getTwinUUID() = TwinAdaptorHelper.getTwinUUID() private fun getTwinRegistrationMessage(isLeaving: Boolean = false): MqttMessage { val trsUri = UriBuilder.fromUri(OSLC4JUtils.getServletURI()).path("trs").build() val announcement = TrsServerAnnouncement(getTwinUUID(), TrsXConstants.TYPE_TWIN, trsUri, MqttTopics.REGISTRATION_ANNOUNCE, isLeaving) return MqttTrsServices.msgFromResources(announcement) } private fun getTwinUnregistrationMessage(): MqttMessage { return getTwinRegistrationMessage(true) } }
apache-2.0
5cd5b8cc85d4a89ad0851248f50ccc1d
38.238806
130
0.658425
4.448393
false
false
false
false
schaal/ocreader
app/src/main/java/email/schaal/ocreader/util/StringUtils.kt
1
2574
/* * Copyright (C) 2015 Daniel Schaal <[email protected]> * * This file is part of OCReader. * * OCReader 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. * * OCReader 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 OCReader. If not, see <http://www.gnu.org/licenses/>. * */ @file:JvmName("StringUtils") package email.schaal.ocreader.util import android.content.Context import android.graphics.Color import android.text.format.DateUtils import androidx.core.text.HtmlCompat import email.schaal.ocreader.R import email.schaal.ocreader.database.model.Feed import okhttp3.HttpUrl import java.util.* fun String.htmlLink(href: String?) = if(href != null) "<a href=\"${href}\">${this}</a>" else this /** * Utility functions to handle Strings. */ fun getByLine(context: Context, template: String, author: String?, feed: Feed?): String { return if (author != null && feed != null) { String.format(template, context.getString(R.string.by_author_on_feed, author, feed.name.htmlLink(feed.link))) } else if(author != null) { String.format(template, context.getString(R.string.by_author, author)) } else if (feed != null) { String.format(template, context.getString(R.string.on_feed, feed.name.htmlLink(feed.link))) } else { "" } } fun Date.getTimeSpanString(endDate: Date = Date()): CharSequence { return DateUtils.getRelativeTimeSpanString( this.time, endDate.time, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL) } fun String.cleanString(): String { return HtmlCompat.fromHtml(this, HtmlCompat.FROM_HTML_MODE_COMPACT).toString() } fun Int.asCssString(): String { // Use US locale so we always get a . as decimal separator for a valid css value return String.format(Locale.US, "rgba(%d,%d,%d,%.2f)", Color.red(this), Color.green(this), Color.blue(this), Color.alpha(this) / 255.0) } fun HttpUrl.buildBaseUrl(apiRoot: String): HttpUrl { return this .newBuilder() .addPathSegments(apiRoot) .build() }
gpl-3.0
860221c62a8431448dae14e9f03794c0
33.32
117
0.683761
3.79646
false
false
false
false
didi/DoraemonKit
Android/app/src/main/java/com/didichuxing/doraemondemo/amap/DefaultNaviListener.kt
1
5403
package com.didichuxing.doraemondemo.amap import android.content.Context import android.util.Log import com.amap.api.maps.AMap import com.amap.api.maps.AMapUtils import com.amap.api.maps.model.LatLng import com.amap.api.navi.AMapNavi import com.amap.api.navi.AMapNaviListener import com.amap.api.navi.enums.NaviType import com.amap.api.navi.model.* import io.reactivex.disposables.Disposable /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2/25/21-20:00 * 描 述: * 修订历史: * ================================================ */ class DefaultNaviListener(val mAMap: AMap, val mAMapNavi: AMapNavi, val context: Context) : AMapNaviListener { // private var mNaviRouteOverlay: NaviRouteOverlay? = null // // init { // mNaviRouteOverlay = NaviRouteOverlay(mAMap, null) // } private var disp: Disposable? = null private var mNaviLocation: AMapNaviLocation? = null companion object { const val TAG = "DefaultNaviListener" } override fun onInitNaviFailure() { } override fun onInitNaviSuccess() { } override fun onStartNavi(p0: Int) { } override fun onTrafficStatusUpdate() { } /** * 改变位置时自动回调 */ override fun onLocationChange(location: AMapNaviLocation?) { val calculateLineDistance: Float = if (mNaviLocation == null || location == null) -1f else AMapUtils.calculateLineDistance( LatLng(mNaviLocation!!.coord.latitude, mNaviLocation!!.coord.longitude), LatLng(location.coord.latitude, location.coord.longitude) ) if (calculateLineDistance < 0) { Log.v(TAG, "⚠️高德定位:" + location.getString()) } else if (calculateLineDistance > 50) { Log.w(TAG, "⚠️高德定位:跳动距离:" + calculateLineDistance + " " + location.getString()) } else { Log.v(TAG, "⚠️高德定位:跳动距离:" + calculateLineDistance + " " + location.getString()) } mNaviLocation = location } private fun AMapNaviLocation?.getString(): String { return if (this != null) "lat,lng:${coord?.latitude},:${coord?.longitude}, 精度:$accuracy, 速度:$speed, 方向:$bearing, 海拔:$altitude, 时间:$time" else "null" } override fun onGetNavigationText(p0: Int, p1: String?) { } override fun onGetNavigationText(p0: String?) { } override fun onEndEmulatorNavi() { } override fun onArriveDestination() { } override fun onCalculateRouteFailure(p0: Int) { } override fun onCalculateRouteFailure(p0: AMapCalcRouteResult?) { } override fun onReCalculateRouteForYaw() { } override fun onReCalculateRouteForTrafficJam() { } override fun onArrivedWayPoint(p0: Int) { } override fun onGpsOpenStatus(p0: Boolean) { } override fun onNaviInfoUpdate(p0: NaviInfo?) { } override fun updateCameraInfo(p0: Array<out AMapNaviCameraInfo>?) { } override fun updateIntervalCameraInfo( p0: AMapNaviCameraInfo?, p1: AMapNaviCameraInfo?, p2: Int ) { } override fun onServiceAreaUpdate(p0: Array<out AMapServiceAreaInfo>?) { } override fun showCross(p0: AMapNaviCross?) { } override fun hideCross() { } override fun showModeCross(p0: AMapModelCross?) { } override fun hideModeCross() { } override fun showLaneInfo(p0: Array<out AMapLaneInfo>?, p1: ByteArray?, p2: ByteArray?) { } override fun showLaneInfo(p0: AMapLaneInfo?) { } override fun hideLaneInfo() { } override fun onCalculateRouteSuccess(p0: IntArray?) { } /** * 线路规划成功 */ override fun onCalculateRouteSuccess(result: AMapCalcRouteResult?) { // LogHelper.i(TAG, "mAMapNavi.naviPath.coordList===>${mAMapNavi.naviPath.coordList.size}") // RouterManager.mCoordList = mAMapNavi.naviPath.coordList val naviRouteOverlay = NaviRouteOverlay(mAMap, mAMapNavi.naviPath, context) naviRouteOverlay.setShowDefaultLineArrow(true) naviRouteOverlay.addToMap() // naviRouteOverlay.removeFromMap() mAMapNavi.setEmulatorNaviSpeed(10) /** * CRUISE 巡航模式(数值:3) EMULATOR 模拟导航(数值:2) GPS 实时导航(数值:1) NONE 未开始导航(数值:-1) */ mAMapNavi.startNavi(NaviType.GPS) // disp = MockGPSTaskManager.startGpsMockTask(mAMapNavi.naviPath)?.subscribe() } override fun notifyParallelRoad(p0: Int) { } override fun OnUpdateTrafficFacility(p0: Array<out AMapNaviTrafficFacilityInfo>?) { } override fun OnUpdateTrafficFacility(p0: AMapNaviTrafficFacilityInfo?) { } override fun updateAimlessModeStatistics(p0: AimLessModeStat?) { } override fun updateAimlessModeCongestionInfo(p0: AimLessModeCongestionInfo?) { } override fun onPlayRing(p0: Int) { } override fun onNaviRouteNotify(p0: AMapNaviRouteNotifyData?) { } override fun onGpsSignalWeak(p0: Boolean) { } fun onDestroy() { if (disp != null && !disp!!.isDisposed()) { disp!!.dispose() } } }
apache-2.0
6174ea1932a53a0ad6536a6d7d20f5a4
24.88
144
0.629372
3.893905
false
false
false
false
ylegall/BrainSaver
src/main/java/org/ygl/GlobalResolver.kt
1
1533
package org.ygl import org.antlr.v4.runtime.tree.xpath.XPath import org.ygl.BrainSaverParser.* fun resolveGlobals(parser: BrainSaverParser, tree: ProgramContext): Map<String, Symbol> { val globals = HashMap<String, Symbol>() val finalGlobals = HashMap<String, Symbol>() var address = 0 val readSymbols = XPath.findAll(tree, "//atom", parser) .mapNotNull { it as? AtomIdContext } .map { it.text } .toCollection(HashSet()) XPath.findAll(tree, "//globalVariable", parser) .mapNotNull { ctx -> ctx as? GlobalVariableContext } .forEach { ctx -> val name = ctx.Identifier().text if (globals.containsKey(name)) throw CompilationException("global symbol $name redefined", ctx) when (ctx.atom()) { is BrainSaverParser.AtomIntContext -> { globals[name] = Symbol(name, 1, address, Type.INT, ctx.rhs.text.toInt()) address += 1 } is BrainSaverParser.AtomStrContext -> { globals[name] = Symbol(name, 1, address, Type.STRING, ctx.rhs.text) address += ctx.rhs.text.length } } } for ((name, symbol) in globals) { if (!readSymbols.contains(name)) { throw CompilationException("unused global variable $name") } finalGlobals.put(name, symbol) } return finalGlobals }
gpl-3.0
698940bed04f36c401f50a7417a845ee
35.52381
111
0.554468
4.469388
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/misc/FileWatcher.kt
1
6835
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.misc import java.io.File import java.lang.ref.WeakReference import java.nio.file.* import java.nio.file.StandardWatchEventKinds.* import java.util.* class FileWatcher { private val watchServiceByFileSystem = mutableMapOf<FileSystem, WatchService>() private val entriesByDirectory = mutableMapOf<Path, MutableList<Entry>>() @Synchronized fun register(file: File, listener: FileListener, useCanonical: Boolean = true) { register((if (useCanonical) file.canonicalFile else file).toPath(), listener) } @Synchronized fun register(file: Path, listener: FileListener) { val directory: Path if (Files.isDirectory(file)) { directory = file } else { directory = file.parent } var list: MutableList<Entry>? = entriesByDirectory[directory] if (list == null) { list = ArrayList<Entry>() entriesByDirectory.put(directory, list) directory.register(watchService(directory), ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY) } list.add(Entry(listener, file)) } @Synchronized fun unregister(listener: FileListener) { for (list in entriesByDirectory.values) { for (entry in list) { if (entry.weakListener.get() === listener) { list.remove(entry) return } } } } /** * This allows a single FileListener to unregister from just ONE of the files that it is listening to. */ @Synchronized fun unregister(file: Path, dl: FileListener) { val directory: Path if (Files.isDirectory(file)) { directory = file } else { directory = file.parent } val list: MutableList<Entry> = entriesByDirectory[directory] ?: return for (entry in list) { if (entry.weakListener.get() === dl) { list.remove(entry) break } } if (list.isEmpty()) { entriesByDirectory.remove(directory) } } private fun watchService(directory: Path): WatchService = watchService(directory.fileSystem) @Synchronized private fun watchService(filesystem: FileSystem): WatchService = watchServiceByFileSystem[filesystem] ?: createWatchService(filesystem) @Synchronized private fun createWatchService(filesystem: FileSystem): WatchService { val watchService = filesystem.newWatchService()!! watchServiceByFileSystem.put(filesystem, watchService) startPolling(watchService) return watchService } private fun startPolling(watcher: WatchService) { val thread = Thread(Runnable { while (true) { poll(watcher) } }) thread.isDaemon = true thread.start() } private fun poll(watcher: WatchService) { val key: WatchKey try { key = watcher.take() } catch (x: InterruptedException) { return } val directory = key.watchable() as Path /* * I used this tutorial, but it seems broken, as it misses some changes :-( * https://docs.oracle.com/javase/tutorial/essential/io/notification.html * * We cannot reply on WatchService to tell us about ALL changes to the directory, because * we need to perform a reset in order to receive further changes. If the directory is changed AGAIN * before the reset is called, then we will not see the 2nd change. This is common, because * when saving documents, an application will often save to a temporary file, and then rename it to * the real file (e.g. gedit does this). * So instead, we keep track of each listener's file's last modified time-stamp, and check each listener of * this directory to see if their file has changed. * * i.e. we ignore the result of key.pollEvents() */ key.pollEvents() if (!notifyListeners(directory)) { key.cancel() return } val valid = key.reset() if (!valid) { // Directory has been deleted, so remove all the listeners removeAll(directory) } } @Synchronized private fun removeAll(directory: Path) { entriesByDirectory.remove(directory) } @Synchronized private fun notifyListeners(directory: Path): Boolean { val list = entriesByDirectory[directory] ?: return false if (list.isEmpty()) { entriesByDirectory.remove(directory) return false } for (entry in list) { val listener = entry.weakListener.get() if (listener == null) { list.remove(entry) // Recurse to prevent concurrent modification exception. return notifyListeners(directory) } try { entry.check() } catch (e: Exception) { e.printStackTrace() list.remove(entry) // Recurse to prevent concurrent modification exception. return notifyListeners(directory) } } return true } private inner class Entry(listener: FileListener, private val path: Path) { internal val weakListener = WeakReference<FileListener>(listener) internal var lastModified: Long = path.toFile().lastModified() fun check() { val lm = path.toFile().lastModified() if (lastModified != lm) { val listener = this.weakListener.get() if (listener != null) { this.lastModified = lm listener.fileChanged(path) } } } override fun toString(): String { return "FileWatching Entry for listener ${weakListener.get()}" } } companion object { var instance: FileWatcher = FileWatcher() } }
gpl-3.0
1b5c15450fb56ee55ad46d5e4f574305
30.939252
115
0.603511
5.051737
false
false
false
false
nemerosa/ontrack
ontrack-extension-sonarqube/src/main/java/net/nemerosa/ontrack/extension/sonarqube/casc/SonarQubeMeasuresSettingsContext.kt
1
1770
package net.nemerosa.ontrack.extension.sonarqube.casc import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.extension.casc.context.settings.AbstractSubSettingsContext import net.nemerosa.ontrack.extension.casc.schema.* import net.nemerosa.ontrack.extension.sonarqube.measures.SonarQubeMeasuresSettings import net.nemerosa.ontrack.model.settings.CachedSettingsService import net.nemerosa.ontrack.model.settings.SettingsManagerService import org.springframework.stereotype.Component @Component class SonarQubeMeasuresSettingsContext( settingsManagerService: SettingsManagerService, cachedSettingsService: CachedSettingsService, ) : AbstractSubSettingsContext<SonarQubeMeasuresSettings>( "sonarqube-measures", SonarQubeMeasuresSettings::class, settingsManagerService, cachedSettingsService ) { override val type: CascType = cascObject( "SonarQube measures settings", cascField(SonarQubeMeasuresSettings::measures, cascArray( "List of SonarQube measures", cascString ) ), cascField(SonarQubeMeasuresSettings::disabled, required = false), cascField(SonarQubeMeasuresSettings::coverageThreshold, required = false), cascField(SonarQubeMeasuresSettings::blockerThreshold, required = false), ) override fun adjustNodeBeforeParsing(node: JsonNode): JsonNode = node.ifMissing( SonarQubeMeasuresSettings::disabled to SonarQubeMeasuresSettings.DEFAULT_DISABLED, SonarQubeMeasuresSettings::coverageThreshold to SonarQubeMeasuresSettings.DEFAULT_COVERAGE_THRESHOLD, SonarQubeMeasuresSettings::blockerThreshold to SonarQubeMeasuresSettings.DEFAULT_BLOCKER_THRESHOLD, ) }
mit
6e553853d8a5fa9b8e5a0fd3584c77dc
43.275
113
0.772316
5.803279
false
false
false
false
FFlorien/AmpachePlayer
app/src/mock/java/be/florien/anyflow/view/connect/ConnectActivity.kt
1
2155
package be.florien.anyflow.view.connect import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import be.florien.anyflow.R import be.florien.anyflow.api.model.Account import be.florien.anyflow.api.model.AccountList import be.florien.anyflow.databinding.ItemAccountBinding import org.simpleframework.xml.core.Persister import java.io.InputStreamReader /** * Created by florien on 4/03/18. */ class ConnectActivity : ConnectActivityBase() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val reader = InputStreamReader(assets.open("mock_account.xml")) val osd = Persister().read(AccountList::class.java, reader) binding.extra?.mockAccount?.layoutManager = LinearLayoutManager(this) binding.extra?.mockAccount?.adapter = AccountAdapter(osd.accounts) } inner class AccountAdapter(val accounts: List<Account>) : RecyclerView.Adapter<AccountViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AccountViewHolder = AccountViewHolder(parent) override fun getItemCount(): Int = accounts.size override fun onBindViewHolder(holder: AccountViewHolder, position: Int) { holder.bindAccount(accounts[position]) } } inner class AccountViewHolder( parent: ViewGroup, private val binding: ItemAccountBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_account, parent, false)) : RecyclerView.ViewHolder(binding.root) { private lateinit var boundAccount: Account fun bindAccount(account: Account) { boundAccount = account binding.accountName = account.name itemView.setOnClickListener { vm.server = account.server vm.username = account.user vm.password = account.password vm.connect() } } } }
gpl-3.0
780fe12fe07774ca8dfcddc2ae5a021a
34.933333
120
0.705336
4.831839
false
false
false
false
d9n/intellij-rust
src/test/kotlin/org/rust/ide/surroundWith/statement/RsWithForSurrounderTest.kt
1
5002
package org.rust.ide.surroundWith.statement import org.rust.ide.surroundWith.RsSurrounderTestBase class RsWithForSurrounderTest : RsSurrounderTestBase(RsWithForSurrounder()) { fun testNotApplicable1() { doTestNotApplicable( """ fn main() { let mut server <selection>= Nickel::new(); server.get("**", hello_world); server.listen("127.0.0.1:6767").unwrap();</selection> } """ ) } fun testNotApplicable2() { doTestNotApplicable( """ fn main() { <selection>#![cfg(test)] let mut server = Nickel::new(); server.get("**", hello_world); server.listen("127.0.0.1:6767").unwrap();</selection> } """ ) } fun testNotApplicable3() { doTestNotApplicable( """ fn main() { loop<selection> { for 1 in 1..10 { println!("Hello, world!"); } }</selection> } """ ) } fun testApplicableComment() { doTest( """ fn main() { <selection>// comment let mut server = Nickel::new(); server.get("**", hello_world); server.listen("127.0.0.1:6767").unwrap(); // comment</selection> } """ , """ fn main() { for <caret> { // comment let mut server = Nickel::new(); server.get("**", hello_world); server.listen("127.0.0.1:6767").unwrap(); // comment } } """ , checkSyntaxErrors = false ) } fun testSimple1() { doTest( """ fn main() { <selection>let mut server = Nickel::new(); server.get("**", hello_world); server.listen("127.0.0.1:6767").unwrap();</selection> } """ , """ fn main() { for <caret> { let mut server = Nickel::new(); server.get("**", hello_world); server.listen("127.0.0.1:6767").unwrap(); } } """ , checkSyntaxErrors = false ) } fun testSimple2() { doTest( """ fn main() { let mut server = Nickel::new();<selection> server.get("**", hello_world); server.listen("127.0.0.1:6767").unwrap();</selection> } """ , """ fn main() { let mut server = Nickel::new(); for <caret> { server.get("**", hello_world); server.listen("127.0.0.1:6767").unwrap(); } } """ , checkSyntaxErrors = false ) } fun testSimple3() { doTest( """ fn main() { <selection>let mut server = Nickel::new(); server.get("**", hello_world);</selection> server.listen("127.0.0.1:6767").unwrap(); } """ , """ fn main() { for <caret> { let mut server = Nickel::new(); server.get("**", hello_world); } server.listen("127.0.0.1:6767").unwrap(); } """ , checkSyntaxErrors = false ) } fun testSingleLine() { doTest( """ fn main() { let mut server = Nickel::new(); server.get("**", hello_world)<caret>; server.listen("127.0.0.1:6767").unwrap(); } """ , """ fn main() { let mut server = Nickel::new(); for <caret> { server.get("**", hello_world); } server.listen("127.0.0.1:6767").unwrap(); } """ , checkSyntaxErrors = false ) } fun testNested() { doTest( """ fn main() { <selection>loop { println!("Hello"); }</selection> } """ , """ fn main() { for <caret> { loop { println!("Hello"); } } } """ , checkSyntaxErrors = false ) } }
mit
39b9ff77ffab50f48fcdcbed6f1f8220
25.326316
80
0.347261
5.338314
false
true
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/ext/gitlab/config/GitLabContext.kt
1
3158
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.ext.gitlab.config import com.google.api.client.auth.oauth.OAuthGetAccessToken import com.google.api.client.auth.oauth2.PasswordTokenRequest import com.google.api.client.auth.oauth2.TokenResponseException import com.google.api.client.http.HttpTransport import com.google.api.client.http.javanet.NetHttpTransport import com.google.api.client.json.jackson2.JacksonFactory import org.gitlab.api.GitlabAPI import org.gitlab.api.GitlabAPIException import org.gitlab.api.TokenType import org.gitlab.api.models.GitlabSession import svnserver.context.Shared import svnserver.context.SharedContext import java.io.IOException import java.net.HttpURLConnection /** * GitLab context. * * @author Artem V. Navrotskiy <[email protected]> */ class GitLabContext internal constructor(val config: GitLabConfig) : Shared { @Throws(IOException::class) fun connect(username: String, password: String): GitlabSession { val token = obtainAccessToken(gitLabUrl, username, password, false) val api = connect(gitLabUrl, token) return api.currentSession } fun connect(): GitlabAPI { return Companion.connect(gitLabUrl, token) } val gitLabUrl: String get() = config.url val token: GitLabToken get() = config.getToken() val hookPath: String get() = config.hookPath companion object { private val transport: HttpTransport = NetHttpTransport() fun sure(context: SharedContext): GitLabContext { return context.sure(GitLabContext::class.java) } @Throws(IOException::class) fun obtainAccessToken(gitlabUrl: String, username: String, password: String, sudoScope: Boolean): GitLabToken { return try { val tokenServerUrl = OAuthGetAccessToken(gitlabUrl + "/oauth/token?scope=api" + if (sudoScope) "%20sudo" else "") val oauthResponse = PasswordTokenRequest(transport, JacksonFactory.getDefaultInstance(), tokenServerUrl, username, password).execute() GitLabToken(TokenType.ACCESS_TOKEN, oauthResponse.accessToken) } catch (e: TokenResponseException) { if (sudoScope && e.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // Fallback for pre-10.2 gitlab versions val session = GitlabAPI.connect(gitlabUrl, username, password) GitLabToken(TokenType.PRIVATE_TOKEN, session.privateToken) } else { throw GitlabAPIException(e.message, e.statusCode, e) } } } fun connect(gitlabUrl: String, token: GitLabToken): GitlabAPI { return GitlabAPI.connect(gitlabUrl, token.value, token.type) } } }
gpl-2.0
16980a3fde6d2209f9f9bb58670ea1d5
40.552632
150
0.69316
4.367911
false
true
false
false
JavaProphet/JASM
src/main/java/com/protryon/jasm/MethodDescriptor.kt
1
2317
package com.protryon.jasm import com.shapesecurity.functional.Pair import java.util.ArrayList class MethodDescriptor(var returnType: JType, var parameters: ArrayList<JType>) { override fun toString(): String { val builder = StringBuilder("(") for (param in parameters) { builder.append(param.toDescriptor()) } builder.append(")") builder.append(returnType.toDescriptor()) return builder.toString() } fun niceString(methodName: String): String { val builder = StringBuilder() builder.append(returnType.niceName) builder.append(" ").append(methodName).append("(") var first = true for (param in parameters) { if (first) { first = false } else { builder.append(", ") } builder.append(param.niceName) } builder.append(")") return builder.toString() } override fun equals(o: Any?): Boolean { if (o !is MethodDescriptor) { return false } if (o.returnType != this.returnType) { return false } if (o.parameters.size != this.parameters.size) { return false } for (i in this.parameters.indices) { if (this.parameters[i] != o.parameters[i]) { return false } } return true } override fun hashCode(): Int { return this.returnType.hashCode() + this.parameters.hashCode() } companion object { fun fromString(classpath: Classpath, str: String): MethodDescriptor? { if (str[0] != '(') { return null } val end = str.indexOf(")", 1) var params = str.substring(1, end) val returnDescriptor = str.substring(end + 1) val returnType = JType.fromDescriptor(classpath, returnDescriptor) val parameters = ArrayList<JType>() while (params.length > 0) { val pair = JType.fromDescriptorWithLength(classpath, params) params = params.substring(pair.right) parameters.add(pair.left) } return MethodDescriptor(returnType, parameters) } } }
gpl-3.0
64065060a990c9e9999ed9e0f9c8d002
28.705128
81
0.546828
4.807054
false
false
false
false
edvin/tornadofx
src/test/kotlin/tornadofx/testapps/BrokenLineTest.kt
2
1889
package tornadofx.testapps import javafx.scene.layout.BorderStrokeStyle import javafx.scene.shape.StrokeLineCap import javafx.scene.shape.StrokeLineJoin import javafx.scene.shape.StrokeType import tornadofx.* class BrokenLineApp : App(BrokenLineView::class, BrokenStyles::class) class BrokenLineView : View("Broken Line Test") { override val root = stackpane { line { addClass(BrokenStyles.blue) endXProperty().bind([email protected]()) endYProperty().bind([email protected]()) } line { addClass(BrokenStyles.blue) endXProperty().bind([email protected]()) startYProperty().bind([email protected]()) } label("This is a label with a border").addClass(BrokenStyles.red) } } class BrokenStyles : Stylesheet() { companion object { val red by cssclass() val blue by cssclass() } init { root { padding = box(25.px) backgroundColor += c("white") } red { val radius = box(50.px) backgroundColor += c("white", 0.9) backgroundRadius += radius borderColor += box(c("red")) borderWidth += box(5.px) borderRadius += radius borderStyle += BorderStrokeStyle( StrokeType.CENTERED, StrokeLineJoin.MITER, StrokeLineCap.SQUARE, 10.0, 0.0, listOf(5.0, 15.0, 0.0, 15.0) ) padding = box(50.px) } blue { stroke = c("dodgerblue") strokeWidth = 5.px strokeType = StrokeType.CENTERED strokeLineCap = StrokeLineCap.SQUARE strokeDashArray = listOf(25.px, 15.px, 0.px, 15.px) } } }
apache-2.0
ab9e450bc6c1c6b64718a4a4a93d1e27
29.483871
73
0.563261
4.584951
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/DestroyUserListDialogFragment.kt
1
2991
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.support.v4.app.FragmentManager import android.support.v7.app.AlertDialog import de.vanita5.twittnuker.R import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_USER_LIST import de.vanita5.twittnuker.extension.applyOnShow import de.vanita5.twittnuker.extension.applyTheme import de.vanita5.twittnuker.model.ParcelableUserList class DestroyUserListDialogFragment : BaseDialogFragment(), DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, which: Int) { when (which) { DialogInterface.BUTTON_POSITIVE -> { val userList = userList val twitter = twitterWrapper twitter.destroyUserListAsync(userList.account_key, userList.id) } else -> { } } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = activity val builder = AlertDialog.Builder(context) val userList = userList builder.setTitle(getString(R.string.delete_user_list, userList.name)) builder.setMessage(getString(R.string.delete_user_list_confirm_message, userList.name)) builder.setPositiveButton(android.R.string.ok, this) builder.setNegativeButton(android.R.string.cancel, null) val dialog = builder.create() dialog.applyOnShow { applyTheme() } return dialog } private val userList: ParcelableUserList get() = arguments.getParcelable<ParcelableUserList>(EXTRA_USER_LIST) companion object { private const val FRAGMENT_TAG = "destroy_user_list" fun show(fm: FragmentManager, userList: ParcelableUserList): DestroyUserListDialogFragment { val args = Bundle() args.putParcelable(EXTRA_USER_LIST, userList) val f = DestroyUserListDialogFragment() f.arguments = args f.show(fm, FRAGMENT_TAG) return f } } }
gpl-3.0
60dc0248215fb19043efde7a7b08b15d
36.873418
100
0.7001
4.477545
false
false
false
false
akvo/akvo-caddisfly
caddisfly-app/app/src/androidTest/java/org/akvo/caddisfly/util/DrawableMatcher.kt
1
3951
package org.akvo.caddisfly.util import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.view.View import android.widget.ImageView import androidx.appcompat.widget.AppCompatImageView import androidx.core.content.ContextCompat import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.TypeSafeMatcher //https://medium.com/@felipegi91_89910/thanks-daniele-bottillo-b57caf823e34 class DrawableMatcher private constructor(private val expectedId: Int) : TypeSafeMatcher<View>(View::class.java) { private var resourceName: String? = null override fun matchesSafely(target: View): Boolean { var backgroundBitmap: Bitmap? = null var resourceBitmap: Bitmap? = null val clazz = target.javaClass if (clazz == AppCompatImageView::class.java) { val image = target as AppCompatImageView if (expectedId == ANY) { return image.drawable != null } if (expectedId < 0) { return image.background == null } resourceBitmap = drawableToBitmap(image.drawable) backgroundBitmap = drawableToBitmap(image.background) } if (clazz == ImageView::class.java) { val image = target as ImageView if (expectedId == ANY) { return image.drawable != null } if (expectedId < 0) { return image.background == null } resourceBitmap = drawableToBitmap(image.drawable) backgroundBitmap = drawableToBitmap(image.background) } val resources = target.context.resources val expectedDrawable = ContextCompat.getDrawable(target.context, expectedId) resourceName = resources.getResourceEntryName(expectedId) if (expectedDrawable == null) { return false } val otherBitmap = drawableToBitmap(expectedDrawable) return resourceBitmap != null && resourceBitmap.sameAs(otherBitmap) || backgroundBitmap != null && backgroundBitmap.sameAs(otherBitmap) } // private Bitmap getBitmap(Drawable drawable) { // Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(bitmap); // drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); // drawable.draw(canvas); // return bitmap; // } override fun describeTo(description: Description) { description.appendText("with drawable from resource id: ") description.appendValue(expectedId) if (resourceName != null) { description.appendText("[") description.appendText(resourceName) description.appendText("]") } } companion object { // private static final int EMPTY = -1; private const val ANY = -2 fun hasDrawable(): Matcher<View> { return DrawableMatcher(ANY) } private fun drawableToBitmap(drawable: Drawable): Bitmap { val bitmap: Bitmap = if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <= 0) { Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) // Single color bitmap will be created of 1x1 pixel } else { Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888) } if (drawable is BitmapDrawable) { if (drawable.bitmap != null) { return drawable.bitmap } } val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) return bitmap } } }
gpl-3.0
bb1d53f7d54cb2ed1bcfa04d73094ddf
34.927273
143
0.627942
5.131169
false
false
false
false
stripe/stripe-android
paymentsheet/src/test/java/com/stripe/android/paymentsheet/PaymentSheetViewModelTestInjection.kt
1
8496
package com.stripe.android.paymentsheet import android.app.Application import android.content.Context import androidx.activity.result.ActivityResultLauncher import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.SavedStateHandle import androidx.test.core.app.ApplicationProvider import com.stripe.android.ApiKeyFixtures import com.stripe.android.PaymentConfiguration import com.stripe.android.core.Logger import com.stripe.android.core.injection.Injectable import com.stripe.android.core.injection.InjectorKey import com.stripe.android.core.injection.NonFallbackInjector import com.stripe.android.core.injection.WeakMapInjectorRegistry import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncher import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncherContract import com.stripe.android.googlepaylauncher.injection.GooglePayPaymentMethodLauncherFactory import com.stripe.android.model.PaymentMethod import com.stripe.android.model.StripeIntent import com.stripe.android.payments.paymentlauncher.StripePaymentLauncherAssistedFactory import com.stripe.android.paymentsheet.analytics.EventReporter import com.stripe.android.paymentsheet.forms.FormViewModel import com.stripe.android.paymentsheet.injection.FormViewModelSubcomponent import com.stripe.android.paymentsheet.injection.PaymentSheetViewModelSubcomponent import com.stripe.android.paymentsheet.model.StripeIntentValidator import com.stripe.android.paymentsheet.paymentdatacollection.FormFragmentArguments import com.stripe.android.paymentsheet.repositories.StripeIntentRepository import com.stripe.android.paymentsheet.viewmodels.BaseSheetViewModel import com.stripe.android.ui.core.Amount import com.stripe.android.ui.core.address.AddressRepository import com.stripe.android.ui.core.forms.resources.LpmRepository import com.stripe.android.ui.core.forms.resources.StaticAddressResourceRepository import com.stripe.android.ui.core.forms.resources.StaticLpmResourceRepository import com.stripe.android.utils.FakeCustomerRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.UnconfinedTestDispatcher import org.junit.After import org.junit.Rule import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import javax.inject.Provider @ExperimentalCoroutinesApi internal open class PaymentSheetViewModelTestInjection { @get:Rule val rule = InstantTaskExecutorRule() private val testDispatcher = UnconfinedTestDispatcher() private val context = ApplicationProvider.getApplicationContext<Context>() val eventReporter = mock<EventReporter>() private val googlePayPaymentMethodLauncherFactory = createGooglePayPaymentMethodLauncherFactory() private val stripePaymentLauncherAssistedFactory = mock<StripePaymentLauncherAssistedFactory>() private lateinit var injector: NonFallbackInjector @After open fun after() { WeakMapInjectorRegistry.clear() } private fun createGooglePayPaymentMethodLauncherFactory() = object : GooglePayPaymentMethodLauncherFactory { override fun create( lifecycleScope: CoroutineScope, config: GooglePayPaymentMethodLauncher.Config, readyCallback: GooglePayPaymentMethodLauncher.ReadyCallback, activityResultLauncher: ActivityResultLauncher<GooglePayPaymentMethodLauncherContract.Args>, skipReadyCheck: Boolean ): GooglePayPaymentMethodLauncher { val googlePayPaymentMethodLauncher = mock<GooglePayPaymentMethodLauncher>() readyCallback.onReady(true) return googlePayPaymentMethodLauncher } } @ExperimentalCoroutinesApi fun createViewModel( stripeIntent: StripeIntent, customerRepositoryPMs: List<PaymentMethod> = emptyList(), @InjectorKey injectorKey: String, args: PaymentSheetContract.Args = PaymentSheetFixtures.ARGS_CUSTOMER_WITH_GOOGLEPAY ): PaymentSheetViewModel = runBlocking { PaymentSheetViewModel( ApplicationProvider.getApplicationContext(), args, eventReporter, { PaymentConfiguration(ApiKeyFixtures.FAKE_PUBLISHABLE_KEY) }, StripeIntentRepository.Static(stripeIntent), StripeIntentValidator(), FakeCustomerRepository(customerRepositoryPMs), FakePrefsRepository(), lpmResourceRepository = StaticLpmResourceRepository( LpmRepository( LpmRepository.LpmRepositoryArguments( ApplicationProvider.getApplicationContext<Application>().resources ) ).apply { this.forceUpdate( listOf( PaymentMethod.Type.Card.code, PaymentMethod.Type.USBankAccount.code ), null ) } ), mock(), stripePaymentLauncherAssistedFactory, googlePayPaymentMethodLauncherFactory, Logger.noop(), testDispatcher, injectorKey, savedStateHandle = SavedStateHandle().apply { set(BaseSheetViewModel.SAVE_RESOURCE_REPOSITORY_READY, true) }, linkLauncher = mock() ) } @FlowPreview fun registerViewModel( @InjectorKey injectorKey: String, viewModel: PaymentSheetViewModel, lpmRepository: LpmRepository, addressRepository: AddressRepository, formViewModel: FormViewModel = FormViewModel( context = context, formFragmentArguments = FormFragmentArguments( PaymentMethod.Type.Card.code, showCheckbox = true, showCheckboxControlledFields = true, merchantName = "Merchant, Inc.", amount = Amount(50, "USD"), initialPaymentMethodCreateParams = null ), lpmResourceRepository = StaticLpmResourceRepository(lpmRepository), addressResourceRepository = StaticAddressResourceRepository(addressRepository), showCheckboxFlow = mock() ) ) { injector = object : NonFallbackInjector { override fun inject(injectable: Injectable<*>) { (injectable as? PaymentSheetViewModel.Factory)?.let { val mockBuilder = mock<PaymentSheetViewModelSubcomponent.Builder>() val mockSubcomponent = mock<PaymentSheetViewModelSubcomponent>() val mockSubComponentBuilderProvider = mock<Provider<PaymentSheetViewModelSubcomponent.Builder>>() whenever(mockBuilder.build()).thenReturn(mockSubcomponent) whenever(mockBuilder.savedStateHandle(any())).thenReturn(mockBuilder) whenever(mockBuilder.paymentSheetViewModelModule(any())).thenReturn(mockBuilder) whenever(mockSubcomponent.viewModel).thenReturn(viewModel) whenever(mockSubComponentBuilderProvider.get()).thenReturn(mockBuilder) injectable.subComponentBuilderProvider = mockSubComponentBuilderProvider } (injectable as? FormViewModel.Factory)?.let { val mockBuilder = mock<FormViewModelSubcomponent.Builder>() val mockSubcomponent = mock<FormViewModelSubcomponent>() val mockSubComponentBuilderProvider = mock<Provider<FormViewModelSubcomponent.Builder>>() whenever(mockBuilder.build()).thenReturn(mockSubcomponent) whenever(mockBuilder.formFragmentArguments(any())).thenReturn(mockBuilder) whenever(mockSubcomponent.viewModel).thenReturn(formViewModel) whenever(mockSubComponentBuilderProvider.get()).thenReturn(mockBuilder) injectable.subComponentBuilderProvider = mockSubComponentBuilderProvider } } } viewModel.injector = injector WeakMapInjectorRegistry.register(injector, injectorKey) } }
mit
ed094a21de0f521e5787edf7354ec14a
46.2
108
0.703978
6.330849
false
false
false
false
paulofernando/localchat
app/src/main/kotlin/site/paulo/localchat/data/MessagesManager.kt
1
3073
/* * Copyright 2017 Paulo Fernando * * 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 site.paulo.localchat.data import site.paulo.localchat.data.model.firebase.ChatMessage import timber.log.Timber import java.util.concurrent.atomic.AtomicInteger import com.anupcowkur.reservoir.Reservoir import java.io.IOException import javax.inject.Singleton @Singleton class MessagesManager { private object HOLDER { val INSTANCE = MessagesManager() } companion object { val instance: MessagesManager by lazy { HOLDER.INSTANCE } } /** Every message is stored here */ //TODO just stored the last x messages by chat val chatMessages = mutableMapOf<String, MutableList<ChatMessage>>() val chatListeners = mutableMapOf<String, MessagesListener>() fun add(chatMessage: ChatMessage, chatId: String) { if(!chatMessages.containsKey(chatId)) { chatMessages.put(chatId, mutableListOf()) } chatMessages[chatId]?.add(chatMessage) chatListeners[chatId]?.messageReceived(chatMessage) } fun unreadMessages(chatId: String, userId: String) { try { val key = "$chatId-unread-$userId" if(!Reservoir.contains(key)) { Reservoir.put(key, AtomicInteger(0)) } val unread = Reservoir.get<AtomicInteger>(key, AtomicInteger::class.java) Reservoir.put(key, unread.incrementAndGet()) } catch (e: IOException) { Timber.e(e) } } fun readMessages(chatId: String, userId: String) { try { Reservoir.put("$chatId-unread-$userId", AtomicInteger(0)) } catch (e: IOException) { Timber.e(e) } } fun getUnreadMessages(chatId: String, userId: String): Int { try { val key = "$chatId-unread-$userId" if(!Reservoir.contains(key)) { Reservoir.put(key, AtomicInteger(0)) } return Reservoir.get<AtomicInteger>(key, AtomicInteger::class.java).get() } catch (e: Exception) { Timber.e(e) } return 0 } fun hasUnread(chatId: String, userId: String): Boolean { return getUnreadMessages(chatId, userId) > 0 } /** * Register a message listener and returns the messages already received */ fun registerListener(messageListener: MessagesListener, chatId: String): MutableList<ChatMessage>? { chatListeners.put(chatId, messageListener) return chatMessages[chatId] } }
apache-2.0
0a51a827792af5af141d0a6f8f6be917
31.020833
104
0.651806
4.539143
false
false
false
false
exponent/exponent
packages/expo-image-picker/android/src/main/java/expo/modules/imagepicker/tasks/ImageResultTask.kt
2
4947
package expo.modules.imagepicker.tasks import android.content.ContentResolver import android.net.Uri import android.os.Bundle import android.util.Base64 import android.util.Log import androidx.exifinterface.media.ExifInterface import expo.modules.core.Promise import expo.modules.core.errors.ModuleDestroyedException import expo.modules.imagepicker.ExifDataHandler import expo.modules.imagepicker.ImagePickerConstants import expo.modules.imagepicker.ImagePickerConstants.exifTags import expo.modules.imagepicker.exporters.ImageExporter import expo.modules.imagepicker.exporters.ImageExporter.Listener import expo.modules.imagepicker.fileproviders.FileProvider import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import java.io.ByteArrayOutputStream import java.io.File import java.io.IOException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException open class ImageResultTask( private val promise: Promise, private val uri: Uri, private val contentResolver: ContentResolver, private val fileProvider: FileProvider, private val isEdited: Boolean, private val withExifData: Boolean, private val imageExporter: ImageExporter, private var exifDataHandler: ExifDataHandler?, private val coroutineScope: CoroutineScope ) { /** * We need to make coroutine wait till the file is generated, while the underlying * thread is free to continue executing other coroutines. */ private suspend fun getFile(): File = suspendCancellableCoroutine { cancellableContinuation -> try { val outputFile = fileProvider.generateFile() cancellableContinuation.resume(outputFile) } catch (e: Exception) { cancellableContinuation.resumeWithException(e) } } /** * We need to make coroutine wait till the exif data is being read, while the underlying * thread is free to continue executing other coroutines. */ private suspend fun getExifData(): Bundle? = suspendCancellableCoroutine { cancellableContinuation -> try { val exif = if (withExifData) readExif() else null cancellableContinuation.resume(exif) } catch (e: Exception) { cancellableContinuation.resumeWithException(e) } } fun execute() { coroutineScope.launch { try { val outputFile = getFile() if (isEdited) { exifDataHandler?.copyExifData(uri, contentResolver) } val exif = getExifData() val imageExporterHandler = object : Listener { override fun onResult(out: ByteArrayOutputStream?, width: Int, height: Int) { val response = Bundle().apply { putString("uri", Uri.fromFile(outputFile).toString()) putInt("width", width) putInt("height", height) putBoolean("cancelled", false) putString("type", "image") out?.let { putString("base64", Base64.encodeToString(it.toByteArray(), Base64.NO_WRAP)) } exif?.let { putBundle("exif", it) } } promise.resolve(response) } override fun onFailure(cause: Throwable?) { promise.reject(ImagePickerConstants.ERR_CAN_NOT_SAVE_RESULT, ImagePickerConstants.CAN_NOT_SAVE_RESULT_MESSAGE, cause) } } imageExporter.export(uri, outputFile, imageExporterHandler) } catch (e: ModuleDestroyedException) { Log.i(ImagePickerConstants.TAG, ImagePickerConstants.COROUTINE_CANCELED, e) promise.reject(ImagePickerConstants.COROUTINE_CANCELED, e) } catch (e: IOException) { promise.reject(ImagePickerConstants.ERR_CAN_NOT_EXTRACT_METADATA, ImagePickerConstants.CAN_NOT_EXTRACT_METADATA_MESSAGE, e) } catch (e: Exception) { Log.e(ImagePickerConstants.TAG, ImagePickerConstants.UNKNOWN_EXCEPTION, e) promise.reject(ImagePickerConstants.UNKNOWN_EXCEPTION, e) } } } @Throws(IOException::class) private fun readExif() = Bundle().apply { contentResolver.openInputStream(uri)?.use { input -> val exifInterface = ExifInterface(input) exifTags.forEach { (type, name) -> if (exifInterface.getAttribute(name) != null) { when (type) { "string" -> putString(name, exifInterface.getAttribute(name)) "int" -> putInt(name, exifInterface.getAttributeInt(name, 0)) "double" -> putDouble(name, exifInterface.getAttributeDouble(name, 0.0)) } } } // Explicitly get latitude, longitude, altitude with their specific accessor functions. exifInterface.latLong?.let { latLong -> putDouble(ExifInterface.TAG_GPS_LATITUDE, latLong[0]) putDouble(ExifInterface.TAG_GPS_LONGITUDE, latLong[1]) putDouble(ExifInterface.TAG_GPS_ALTITUDE, exifInterface.getAltitude(0.0)) } } } }
bsd-3-clause
3bfdfd15c15c1740a2a4481b175aa1c7
37.348837
131
0.698201
4.80758
false
false
false
false
kittinunf/Fuel
fuel/src/main/kotlin/com/github/kittinunf/fuel/core/RequestExecutionOptions.kt
1
2297
package com.github.kittinunf.fuel.core import java.util.concurrent.Callable import java.util.concurrent.Executor import java.util.concurrent.ExecutorService import java.util.concurrent.Future import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLSocketFactory typealias RequestTransformer = (Request) -> Request typealias ResponseTransformer = (Request, Response) -> Response typealias InterruptCallback = (Request) -> Unit typealias ResponseValidator = (Response) -> Boolean data class RequestExecutionOptions( val client: Client, val socketFactory: SSLSocketFactory? = null, val hostnameVerifier: HostnameVerifier? = null, val executorService: ExecutorService, val callbackExecutor: Executor, val requestTransformer: RequestTransformer, var responseTransformer: ResponseTransformer ) { val requestProgress: Progress = Progress() val responseProgress: Progress = Progress() var timeoutInMillisecond: Int = 15_000 var timeoutReadInMillisecond: Int = 15_000 var decodeContent: Boolean? = null var allowRedirects: Boolean? = null var useHttpCache: Boolean? = null var interruptCallbacks: MutableCollection<InterruptCallback> = mutableListOf() var forceMethods: Boolean = false var responseValidator: ResponseValidator = { response -> !(response.isServerError || response.isClientError) } /** * Executes a callback [f] onto the [Executor] * * @note this can be used to handle callbacks on a different Thread than the network request is made */ fun callback(f: () -> Unit) = callbackExecutor.execute(f) /** * Submits the task to the [ExecutorService] * * @param task [Callable] the execution of [Request] that yields a [Response] * @return [Future] the future that resolves to a [Response] */ fun submit(task: Callable<Response>): Future<Response> = executorService.submit(task) val interruptCallback: InterruptCallback = { request -> interruptCallbacks.forEach { it(request) } } /** * Append a response transformer */ operator fun plusAssign(next: ResponseTransformer) { val previous = responseTransformer responseTransformer = { request, response -> next(request, previous(request, response)) } } }
mit
47f5f71fe307a4e0f84231c884959f88
35.460317
104
0.723988
4.716632
false
false
false
false
mightyfrog/S4FD
app/src/main/java/org/mightyfrog/android/s4fd/details/DetailsActivity.kt
1
8510
package org.mightyfrog.android.s4fd.details import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import com.google.android.material.appbar.AppBarLayout import com.raizlabs.android.dbflow.sql.language.Select import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_details.* import org.mightyfrog.android.s4fd.App import org.mightyfrog.android.s4fd.R import org.mightyfrog.android.s4fd.data.KHCharacter import org.mightyfrog.android.s4fd.data.KHCharacter_Table import org.mightyfrog.android.s4fd.details.tabcontents.attacks.AttacksFragment import org.mightyfrog.android.s4fd.details.tabcontents.attributes.AttributesFragment import org.mightyfrog.android.s4fd.details.tabcontents.miscs.MiscsFragment import org.mightyfrog.android.s4fd.util.Const import javax.inject.Inject /** * @author Shigehiro Soejima */ class DetailsActivity : AppCompatActivity(), DetailsContract.View, AppBarLayout.OnOffsetChangedListener { @Inject lateinit var detailsPresenter: DetailsPresenter private val id: Int by lazy { intent.getIntExtra("id", 0) } private val character: KHCharacter by lazy { Select().from(KHCharacter::class.java).where(KHCharacter_Table.id.eq(id)).querySingle() as KHCharacter } private var charToCompare: KHCharacter? = null private var isAppBarCollapsed = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (id <= 0 || id > Const.CHARACTER_COUNT) { finish() return } setTheme(resources.getIdentifier("CharTheme.$id", "style", packageName)) setContentView(R.layout.activity_details) DaggerDetailsComponent.builder() .appComponent((application as App).getAppComponent()) .detailsModule(DetailsModule(this)) .build() .inject(this) setSupportActionBar(toolbar) val titles = resources.getStringArray(R.array.detail_tabs) viewPager.adapter = TabContentAdapter(titles, supportFragmentManager, id) viewPager.offscreenPageLimit = 3 tabLayout.setupWithViewPager(viewPager) tabLayout.addOnTabSelectedListener(object : com.google.android.material.tabs.TabLayout.OnTabSelectedListener { override fun onTabReselected(tab: com.google.android.material.tabs.TabLayout.Tab?) { // no-op } override fun onTabUnselected(tab: com.google.android.material.tabs.TabLayout.Tab?) { // no-op } override fun onTabSelected(tab: com.google.android.material.tabs.TabLayout.Tab?) { invalidateOptionsMenu() } }) fab.setOnClickListener { detailsPresenter compareTo id } findViewById<AppBarLayout>(R.id.appbar).addOnOffsetChangedListener(this) Picasso.with(this) .load(character.mainImageUrl) .into(backdrop) viewPager.post { detailsPresenter.setCharToCompareIfAny(id) supportActionBar?.apply { title = character.displayName?.trim() setDisplayHomeAsUpEnabled(true) } } } override fun onStart() { super.onStart() backdrop.visibility = View.VISIBLE } override fun onStop() { backdrop.visibility = View.GONE super.onStop() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.details, menu) return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { menu?.findItem(R.id.open_in_browser)?.isVisible = tabLayout.selectedTabPosition == 3 return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.home -> supportFinishAfterTransition() R.id.open_in_browser -> openInBrowser() } return super.onOptionsItemSelected(item) } override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) { appBarLayout ?: return val maxScroll = appBarLayout.totalScrollRange val percentage = Math.abs(verticalOffset) / maxScroll.toFloat() if (percentage >= 0.7f && isAppBarCollapsed) { fab.hide() (vsThumbnail.parent as View).animate().setDuration(500L).alpha(0f).start() isAppBarCollapsed = !isAppBarCollapsed } else if (percentage < 0.7f && !isAppBarCollapsed) { fab.show() (vsThumbnail.parent as View).animate().setDuration(500L).alpha(1f).start() isAppBarCollapsed = !isAppBarCollapsed } charToCompare?.apply { if (percentage == 1f) { collapsingToolbarLayout.title = getString(R.string.attr_compare, character.displayName, displayName) } else { collapsingToolbarLayout.title = character.displayName?.trim() } } } override fun setSubtitle(resId: Int, vararg args: String?) { supportActionBar?.subtitle = getString(resId, args) } override fun clearSubtitle() { supportActionBar?.subtitle = null } override fun hideVsThumbnail() { vsThumbnail.visibility = View.GONE } override fun showVsThumbnail(charToCompare: KHCharacter?) { with(vsThumbnail) { charToCompare?.apply { Picasso.with(context) .load(thumbnailUrl) .into(this@with) (parent as androidx.cardview.widget.CardView).setCardBackgroundColor(Color.parseColor(colorTheme)) } visibility = View.VISIBLE alpha = 0f animate().setDuration(750L).alpha(1f).start() } } override fun setCharToCompare(charToCompare: KHCharacter?) { this.charToCompare = charToCompare val f0 = supportFragmentManager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 0) as AttributesFragment f0.setCharToCompare(charToCompare) val f1 = supportFragmentManager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 1) as AttacksFragment f1.setCharToCompare(charToCompare) val f2 = supportFragmentManager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 2) as MiscsFragment f2.setCharToCompare(charToCompare) } override fun showCompareDialog(list: List<KHCharacter>, displayNames: List<String>, scrollPosition: Int) { val dialog = AlertDialog.Builder(this) .setTitle(R.string.compare) .setSingleChoiceItems(displayNames.toTypedArray(), scrollPosition) { dialogInterface, which -> detailsPresenter.setCharToCompare(id, list[which]) dialogInterface.dismiss() } .setNeutralButton(R.string.clear) { _, _ -> detailsPresenter.setCharToCompare(id, null) } .setNegativeButton(R.string.cancel, null) .create() dialog.ownerActivity = this dialog.show() } override fun showActivityCircle() { activity_circle.visibility = View.VISIBLE } override fun hideActivityCircle() { activity_circle.visibility = View.GONE } override fun setPresenter(presenter: DetailsPresenter) { detailsPresenter = presenter } override fun showErrorMessage(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show() } override fun showErrorMessage(resId: Int) { showErrorMessage(getString(resId)) } private fun openInBrowser() { Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(character.fullUrl) when (resolveActivity(packageManager)) { null -> { Toast.makeText(this@DetailsActivity, "No browser found :(", Toast.LENGTH_LONG).show() } else -> { startActivity(this) } } } } }
apache-2.0
76fe7ba8870bb8197b05d80935cb4913
33.734694
127
0.643713
4.896433
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/input/GapBuffer.kt
3
11562
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.input import androidx.compose.ui.text.InternalTextApi /** * Like [toCharArray] but copies the entire source string. * Workaround for compiler error when giving [toCharArray] above default parameters. */ private fun String.toCharArray( destination: CharArray, destinationOffset: Int ) = toCharArray(destination, destinationOffset, startIndex = 0, endIndex = this.length) /** * Copies characters from this [String] into [destination]. * * Platform-specific implementations should use native functions for performing this operation if * they exist, since they will likely be more efficient than copying each character individually. * * @param destination The [CharArray] to copy into. * @param destinationOffset The index in [destination] to start copying to. * @param startIndex The index in `this` of the first character to copy from (inclusive). * @param endIndex The index in `this` of the last character to copy from (exclusive). */ internal expect fun String.toCharArray( destination: CharArray, destinationOffset: Int, startIndex: Int, endIndex: Int ) /** * The gap buffer implementation * * @param initBuffer An initial buffer. This class takes ownership of this object, so do not modify * array after passing to this constructor * @param initGapStart An initial inclusive gap start offset of the buffer * @param initGapEnd An initial exclusive gap end offset of the buffer */ private class GapBuffer(initBuffer: CharArray, initGapStart: Int, initGapEnd: Int) { /** * The current capacity of the buffer */ private var capacity = initBuffer.size /** * The buffer */ private var buffer = initBuffer /** * The inclusive start offset of the gap */ private var gapStart = initGapStart /** * The exclusive end offset of the gap */ private var gapEnd = initGapEnd /** * The length of the gap. */ private fun gapLength(): Int = gapEnd - gapStart /** * [] operator for the character at the index. */ operator fun get(index: Int): Char { if (index < gapStart) { return buffer[index] } else { return buffer[index - gapStart + gapEnd] } } /** * Check if the gap has a requested size, and allocate new buffer if there is enough space. */ private fun makeSureAvailableSpace(requestSize: Int) { if (requestSize <= gapLength()) { return } // Allocating necessary memory space by doubling the array size. val necessarySpace = requestSize - gapLength() var newCapacity = capacity * 2 while ((newCapacity - capacity) < necessarySpace) { newCapacity *= 2 } val newBuffer = CharArray(newCapacity) buffer.copyInto(newBuffer, 0, 0, gapStart) val tailLength = capacity - gapEnd val newEnd = newCapacity - tailLength buffer.copyInto(newBuffer, newEnd, gapEnd, gapEnd + tailLength) buffer = newBuffer capacity = newCapacity gapEnd = newEnd } /** * Delete the given range of the text. */ private fun delete(start: Int, end: Int) { if (start < gapStart && end <= gapStart) { // The remove happens in the head buffer. Copy the tail part of the head buffer to the // tail buffer. // // Example: // Input: // buffer: ABCDEFGHIJKLMNOPQ*************RSTUVWXYZ // del region: |-----| // // First, move the remaining part of the head buffer to the tail buffer. // buffer: ABCDEFGHIJKLMNOPQ*****KLKMNOPQRSTUVWXYZ // move data: ^^^^^^^ => ^^^^^^^^ // // Then, delete the given range. (just updating gap positions) // buffer: ABCD******************KLKMNOPQRSTUVWXYZ // del region: |-----| // // Output: ABCD******************KLKMNOPQRSTUVWXYZ val copyLen = gapStart - end buffer.copyInto(buffer, gapEnd - copyLen, end, gapStart) gapStart = start gapEnd -= copyLen } else if (start < gapStart && end >= gapStart) { // The remove happens with accrossing the gap region. Just update the gap position // // Example: // Input: // buffer: ABCDEFGHIJKLMNOPQ************RSTUVWXYZ // del region: |-------------------| // // Output: ABCDEFGHIJKL********************UVWXYZ gapEnd = end + gapLength() gapStart = start } else { // start > gapStart && end > gapStart // The remove happens in the tail buffer. Copy the head part of the tail buffer to the // head buffer. // // Example: // Input: // buffer: ABCDEFGHIJKL************MNOPQRSTUVWXYZ // del region: |-----| // // First, move the remaining part in the tail buffer to the head buffer. // buffer: ABCDEFGHIJKLMNO*********MNOPQRSTUVWXYZ // move dat: ^^^ <= ^^^ // // Then, delete the given range. (just updating gap positions) // buffer: ABCDEFGHIJKLMNO******************VWXYZ // del region: |-----| // // Output: ABCDEFGHIJKLMNO******************VWXYZ val startInBuffer = start + gapLength() val endInBuffer = end + gapLength() val copyLen = startInBuffer - gapEnd buffer.copyInto(buffer, gapStart, gapEnd, startInBuffer) gapStart += copyLen gapEnd = endInBuffer } } /** * Replace the certain region of text with given text * * @param start an inclusive start offset for replacement. * @param end an exclusive end offset for replacement * @param text a text to replace */ fun replace(start: Int, end: Int, text: String) { makeSureAvailableSpace(text.length - (end - start)) delete(start, end) text.toCharArray(buffer, gapStart) gapStart += text.length } /** * Write the current text into outBuf. * @param builder The output string builder */ fun append(builder: StringBuilder) { builder.append(buffer, 0, gapStart) builder.append(buffer, gapEnd, capacity - gapEnd) } /** * The lengh of this gap buffer. * * This doesn't include internal hidden gap length. */ fun length() = capacity - gapLength() override fun toString(): String = StringBuilder().apply { append(this) }.toString() } /** * An editing buffer that uses Gap Buffer only around the cursor location. * * Different from the original gap buffer, this gap buffer doesn't convert all given text into * mutable buffer. Instead, this gap buffer converts cursor around text into mutable gap buffer * for saving construction time and memory space. If text modification outside of the gap buffer * is requested, this class flush the buffer and create new String, then start new gap buffer. * * @param text The initial text * @suppress */ @InternalTextApi // "Used by benchmarks" class PartialGapBuffer(var text: String) { internal companion object { const val BUF_SIZE = 255 const val SURROUNDING_SIZE = 64 const val NOWHERE = -1 } private var buffer: GapBuffer? = null private var bufStart = NOWHERE private var bufEnd = NOWHERE /** * The text length */ val length: Int get() { val buffer = buffer ?: return text.length return text.length - (bufEnd - bufStart) + buffer.length() } /** * Replace the certain region of text with given text * * @param start an inclusive start offset for replacement. * @param end an exclusive end offset for replacement * @param text a text to replace */ fun replace(start: Int, end: Int, text: String) { require(start <= end) { "start index must be less than or equal to end index: $start > $end" } require(start >= 0) { "start must be non-negative, but was $start" } val buffer = buffer if (buffer == null) { // First time to create gap buffer val charArray = CharArray(maxOf(BUF_SIZE, text.length + 2 * SURROUNDING_SIZE)) // Convert surrounding text into buffer. val leftCopyCount = minOf(start, SURROUNDING_SIZE) val rightCopyCount = minOf(this.text.length - end, SURROUNDING_SIZE) // Copy left surrounding this.text.toCharArray(charArray, 0, start - leftCopyCount, start) // Copy right surrounding this.text.toCharArray( charArray, charArray.size - rightCopyCount, end, end + rightCopyCount ) // Copy given text into buffer text.toCharArray(charArray, leftCopyCount) this.buffer = GapBuffer( charArray, initGapStart = leftCopyCount + text.length, initGapEnd = charArray.size - rightCopyCount ) bufStart = start - leftCopyCount bufEnd = end + rightCopyCount return } // Convert user space offset into buffer space offset val bufferStart = start - bufStart val bufferEnd = end - bufStart if (bufferStart < 0 || bufferEnd > buffer.length()) { // Text modification outside of gap buffer has requested. Flush the buffer and try it // again. this.text = toString() this.buffer = null bufStart = NOWHERE bufEnd = NOWHERE return replace(start, end, text) } buffer.replace(bufferStart, bufferEnd, text) } /** * [] operator for the character at the index. */ operator fun get(index: Int): Char { val buffer = buffer ?: return text[index] if (index < bufStart) { return text[index] } val gapBufLength = buffer.length() if (index < gapBufLength + bufStart) { return buffer[index - bufStart] } return text[index - (gapBufLength - bufEnd + bufStart)] } override fun toString(): String { val b = buffer ?: return text val sb = StringBuilder() sb.append(text, 0, bufStart) b.append(sb) sb.append(text, bufEnd, text.length) return sb.toString() } }
apache-2.0
b142757355b687eb3d2b1ad8f4b85ada
33.308605
99
0.58182
4.829574
false
false
false
false
mkoslacz/Moviper
sample-super-rx-ai-kotlin/src/main/java/com/mateuszkoslacz/moviper/rxsample/viper/view/activity/UserDetailsActivity.kt
1
2710
package com.mateuszkoslacz.moviper.rxsample.viper.view.activity import android.content.Context import android.content.Intent import android.view.View import android.widget.LinearLayout import com.bumptech.glide.Glide import com.mateuszkoslacz.moviper.base.view.activity.autoinject.passive.ViperLceAiPassiveActivity import com.mateuszkoslacz.moviper.iface.interactor.CommonViperInteractor import com.mateuszkoslacz.moviper.iface.presenter.ViperPresenter import com.mateuszkoslacz.moviper.iface.routing.CommonViperRouting import com.mateuszkoslacz.moviper.rxsample.R import com.mateuszkoslacz.moviper.rxsample.viper.contract.UserDetailsContract import com.mateuszkoslacz.moviper.rxsample.viper.entity.User import com.mateuszkoslacz.moviper.presentersdispatcher.MoviperPresentersDispatcher import kotlinx.android.synthetic.main.activity_user_details.* import io.reactivex.Observable import io.reactivex.subjects.PublishSubject class UserDetailsActivity : ViperLceAiPassiveActivity<LinearLayout, User, UserDetailsContract.View>(), UserDetailsContract.View, UserDetailsContract.ViewHelper { override val avatarClicks: Observable<String> get() = mAvatarClicks override val avatarImageView: View get() = avatar internal var mAvatarClicks = PublishSubject.create<String>() override fun bindDataToViews(user: User) { login?.text = user.login url?.text = user.url name?.text = user.name company?.text = user.company blog?.text = user.blog location?.text = user.location email?.text = user.email Glide.with(this) .load(user.avatarUrl) .into(avatar) avatar?.setOnClickListener { mAvatarClicks.onNext(user.avatarUrl) } } override fun setData(user: User) = bindDataToViews(user) override fun getErrorMessage(e: Throwable, pullToRefresh: Boolean): String = e.message!! override fun loadData(pullToRefresh: Boolean) {} override fun createPresenter(): ViperPresenter<UserDetailsContract.View> = MoviperPresentersDispatcher.getInstance().getPresenterForView(this) as ViperPresenter<UserDetailsContract.View> override fun getLayoutId(): Int = R.layout.activity_user_details companion object { val USER_EXTRA = "USER_EXTRA" fun start(context: Context, user: User) { context.startActivity(getStartingIntent(context, user)) } fun getStartingIntent(context: Context, user: User): Intent { val starter = Intent(context, UserDetailsActivity::class.java) starter.putExtra(USER_EXTRA, user.login) return starter } } }
apache-2.0
6ceb729174157c916a85037933e477a0
36.638889
97
0.732841
4.664372
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/camera/TextOrientationActionSheet.kt
1
2842
package at.ac.tuwien.caa.docscan.camera import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.annotation.Nullable import androidx.recyclerview.widget.GridLayoutManager import at.ac.tuwien.caa.docscan.R import at.ac.tuwien.caa.docscan.databinding.TextDirSheetDialogBinding class TextOrientationActionSheet( sheetActions: ArrayList<SheetAction>, selectionListener: SheetSelection, dialogListener: DialogStatus, var confirmListener: DialogConfirm, private val opaque: Boolean = true ) : ActionSheet(sheetActions, selectionListener, dialogListener) { private lateinit var binding: TextDirSheetDialogBinding override fun onCreate(@Nullable savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val style: Int = if (opaque) R.style.BottomSheetDialogDarkTheme else R.style.TransparentBottomSheetDialogDarkTheme setStyle(STYLE_NORMAL, style) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { // Lambda for RecyclerView clicks. Got this from: // https://www.andreasjakl.com/recyclerview-kotlin-style-click-listener-android/ val sheetAdapter = SheetAdapter(sheetActions) { sheetAction: SheetAction -> sheetClicked(sheetAction) } binding.sheetDialogRecyclerview.apply { adapter = sheetAdapter layoutManager = GridLayoutManager([email protected], 2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = TextDirSheetDialogBinding.inflate(layoutInflater, container, false) binding.apply { textOrientationSheetOkButton.setOnClickListener { dismiss() } textOrientationSheetCancelButton.setOnClickListener { dismiss() confirmListener.onCancel() } } return binding.root } override fun sheetClicked(sheetAction: SheetAction) { // Just tell the listener, but do not close the dialog. So do not call super.sheetClicked listener?.onSheetSelected(sheetAction) } override fun onStart() { // Don't dim the background, because we need to see what is happening there: super.onStart() val window = dialog?.window val windowParams = window!!.attributes windowParams.dimAmount = 0f windowParams.flags = windowParams.flags or WindowManager.LayoutParams.FLAG_DIM_BEHIND window.attributes = windowParams } interface DialogConfirm { fun onOk() fun onCancel() } }
lgpl-3.0
0bc26725a969145f9fa0e772cc633ec9
34.525
96
0.688248
5.05694
false
false
false
false
JackWHLiu/jackknife
bugskiller/src/main/java/com/lwh/jackknife/crash/filter/CrashFilterChain.kt
1
1101
package com.lwh.jackknife.crash.filter import java.util.* /** * It is used to combine the superposition of two or more filters. * 通过它来组合两种或两种以上的过滤器的叠加。 */ class CrashFilterChain { private val filters: MutableList<CrashFilter> fun addFirst(filter: CrashFilter): CrashFilterChain { filters.add(0, filter) return this } fun addLast(filter: CrashFilter): CrashFilterChain { filters.add(filter) return this } /** * The whole filter chain. * 一条完整的过滤器链。 */ val filter: CrashFilter? get() { var first: CrashFilter? = null var last: CrashFilter? = null //上次的 for (i in filters.indices) { val filter = filters[i] if (i == 0) { first = filter } else { last!!.setNextFilter(filter) } last = filter } return first } init { filters = LinkedList() } }
gpl-3.0
7ead9897f9c9582ad13e7b3a7ca0e400
21.478261
66
0.520813
4.340336
false
false
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/viewmodel/ContentItemModel.kt
1
2008
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.viewmodel import android.content.Context import android.graphics.drawable.Drawable import androidx.annotation.DrawableRes import androidx.core.graphics.drawable.DrawableCompat import net.mm2d.android.util.DrawableUtils import net.mm2d.android.util.toDisplayableString import net.mm2d.dmsexplorer.R import net.mm2d.dmsexplorer.domain.entity.ContentEntity import net.mm2d.dmsexplorer.domain.entity.ContentType import net.mm2d.dmsexplorer.settings.Settings /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class ContentItemModel( context: Context, entity: ContentEntity, val selected: Boolean ) { val accentBackground: Drawable val accentText: String val title: String val description: String val hasDescription: Boolean @DrawableRes val imageResource: Int val isProtected: Boolean init { val name = entity.name accentText = if (name.isEmpty()) "" else name.substring(0, 1).toDisplayableString() val generator = Settings.get() .themeParams .themeColorGenerator accentBackground = DrawableUtils.get(context, R.drawable.ic_circle)!!.also { it.mutate() DrawableCompat.setTint(it, generator.getIconColor(name)) } title = name.toDisplayableString() description = entity.description hasDescription = description.isNotEmpty() imageResource = getImageResource(entity) isProtected = entity.isProtected } @DrawableRes private fun getImageResource(entity: ContentEntity): Int = when (entity.type) { ContentType.CONTAINER -> R.drawable.ic_folder ContentType.MOVIE -> R.drawable.ic_movie ContentType.MUSIC -> R.drawable.ic_music ContentType.PHOTO -> R.drawable.ic_image else -> 0 } }
mit
1bd13914a4789af4b1f0c46e97f29c8d
30.125
91
0.703313
4.247335
false
false
false
false
ZieIony/Carbon
carbon/src/main/java/carbon/widget/ViewPagerAdapter.kt
1
1055
package carbon.widget import android.view.View import android.view.ViewGroup import androidx.viewpager.widget.PagerAdapter class ViewPagerAdapter : PagerAdapter { class Item(val view: View, val title: String?) val items: Array<Item> constructor(views: Array<View>) : super() { this.items = (views.map { Item(it, null) }).toTypedArray() } constructor(items: Array<Item>) : super() { this.items = items } override fun getPageTitle(position: Int): CharSequence? { return items[position].title } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view === `object` } override fun getCount() = items.size override fun instantiateItem(container: ViewGroup, position: Int): Any { val pager = container as ViewPager val view = items[position].view pager.addView(view) return view } override fun destroyItem(container: ViewGroup, position: Int, view: Any) { container.removeView(view as View) } }
apache-2.0
70104ddf49f612a9b8b034057be70127
24.142857
78
0.655924
4.377593
false
false
false
false
vimeo/stag-java
stag-library-compiler/src/test/java/com/vimeo/stag/processor/functional/JavaIntegrationFunctionalTests.kt
1
6789
package com.vimeo.stag.processor.functional import com.google.testing.compile.Compilation import com.vimeo.sample_java_model.* import com.vimeo.stag.processor.ProcessorTester import com.vimeo.stag.processor.StagProcessor import com.vimeo.stag.processor.isSuccessful import org.assertj.core.api.Assertions.assertThat import org.junit.Test import kotlin.reflect.KClass /** * Functional tests for the integrations in the `integration-test-java` module. */ class JavaIntegrationFunctionalTests { private val processorTester = ProcessorTester({ StagProcessor() }, "-AstagAssumeHungarianNotation=true") private val module = "integration-test-java" @Test fun `AlternateNameModel compiles successfully`() { assertThatClassCompilationIsSuccessful(AlternateNameModel::class) } @Test fun `AlternateNameModel1 compiles successfully`() { assertThatClassCompilationIsSuccessful(AlternateNameModel1::class) } @Test fun `BaseExternalModel compiles successfully`() { assertThatClassCompilationIsSuccessful(BaseExternalModel::class) } @Test fun `BooleanFields compiles successfully`() { assertThatClassCompilationIsSuccessful(BooleanFields::class) } @Test fun `EnumWithFieldsModel compiles successfully`() { assertThatClassCompilationIsSuccessful(EnumWithFieldsModel::class) } @Test fun `ExternalAbstractClass compiles successfully`() { assertThatClassCompilationIsSuccessful(ExternalAbstractClass::class) } @Test fun `ExternalModel1 compiles successfully`() { assertThatClassCompilationIsSuccessful(ExternalModel1::class) } @Test fun `ExternalModel2 compiles successfully`() { assertThatClassCompilationIsSuccessful(ExternalModel2::class) } @Test fun `ExternalModelGeneric compiles successfully`() { assertThatClassCompilationIsSuccessful(ExternalModelGeneric::class) } @Test fun `ExternalModelGeneric1 compiles successfully`() { assertThatClassCompilationIsSuccessful(ExternalModelGeneric1::class) } @Test fun `ModelWithNestedInterface compiles successfully`() { assertThatClassCompilationIsSuccessful(ModelWithNestedInterface::class) } @Test fun `NativeJavaModel compiles successfully`() { assertThatClassCompilationIsSuccessful(NativeJavaModel::class) } @Test fun `NativeJavaModelExtension compiles successfully`() { assertThatClassCompilationIsSuccessful(NativeJavaModelExtension::class) } @Test fun `NativeJavaModelExtensionWithoutAnnotation compiles successfully`() { assertThatClassCompilationIsSuccessful(NativeJavaModelExtensionWithoutAnnotation::class) } @Test fun `RawGenericField compiles successfully`() { assertThatClassCompilationIsSuccessful(RawGenericField::class) } @Test fun `NullFields compiles successfully`() { assertThatClassCompilationIsSuccessful(NullFields::class) } @Test fun `PrivateMembers compiles successfully`() { assertThatClassCompilationIsSuccessful(PrivateMembers::class) } @Test fun `WildcardModel compiles successfully`() { assertThatClassCompilationIsSuccessful(WildcardModel::class) } @Test fun `DynamicallyTypedModel compiles successfully`() { assertThatClassCompilationIsSuccessful(DynamicallyTypedModel::class) } @Test fun `DynamicallyTypedWildcard compiles successfully`() { assertThatClassCompilationIsSuccessful(DynamicallyTypedWildcard::class) } @Test fun `AbstractDataList compiles successfully`() { assertThatClassCompilationIsSuccessful(AbstractDataList::class) } @Test fun `SuperAbstractDataList compiles successfully`() { assertThatClassCompilationIsSuccessful(SuperAbstractDataList::class) } @Test fun `ConcreteDataList compiles successfully`() { assertThatClassCompilationIsSuccessful(ConcreteDataList::class) } @Test fun `PublicFieldsNoHungarian compiles successfully`() { val processorTesterWithNoHungarian = ProcessorTester({ StagProcessor() }, "-AstagAssumeHungarianNotation=false") assertThat(processorTesterWithNoHungarian.compileClassesInModule(module, PublicFieldsNoHungarian::class).isSuccessful()).isTrue() val processorTesterWithHungarian = ProcessorTester({ StagProcessor() }, "-AstagAssumeHungarianNotation=true") assertThat(processorTesterWithHungarian.compileClassesInModule(module, PublicFieldsNoHungarian::class).isSuccessful()).isTrue() } @Test fun `SwappableParserExampleModel compiles successfully`() { assertThatClassCompilationIsSuccessful(SwappableParserExampleModel::class) } @Test fun `WrapperTypeAdapterModel compiles successfully`() { assertThatClassCompilationIsSuccessful(WrapperTypeAdapterModel::class) } @Test fun `Verify that compilation is deterministic`() { val classes = arrayOf( AlternateNameModel::class, AlternateNameModel1::class, BaseExternalModel::class, BooleanFields::class, EnumWithFieldsModel::class, ExternalAbstractClass::class, ExternalModel1::class, ExternalModel2::class, ExternalModelGeneric::class, ExternalModelGeneric1::class, ModelWithNestedInterface::class, NativeJavaModel::class, NativeJavaModelExtension::class, NativeJavaModelExtensionWithoutAnnotation::class, RawGenericField::class, NullFields::class, PrivateMembers::class, WildcardModel::class, DynamicallyTypedModel::class, DynamicallyTypedWildcard::class, AbstractDataList::class, SuperAbstractDataList::class, ConcreteDataList::class ) val compilation1Hash = processorTester.compileClassesInModule(module, *classes).hashOutput() val compilation2Hash = processorTester.compileClassesInModule(module, *classes).hashOutput() assertThat(compilation1Hash).isEqualTo(compilation2Hash) } /** * Returns the concatenation of the hash of each file generated by the [Compilation]. */ private fun Compilation.hashOutput(): String = generatedFiles() .joinToString { it.getCharContent(false).hashCode().toString() } private fun <T : Any> assertThatClassCompilationIsSuccessful(kClass: KClass<T>) { assertThat(processorTester.compileClassesInModule(module, kClass).isSuccessful()).isTrue() } }
mit
06a5977ecf93e3e46796e3399a1ede83
33.287879
137
0.710856
5.883016
false
true
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/specialBuiltins/maps.kt
3
1012
// IGNORE_BACKEND: NATIVE class A : Map<String, String> { override val size: Int get() = 56 override fun isEmpty(): Boolean { throw UnsupportedOperationException() } override fun containsKey(key: String): Boolean { throw UnsupportedOperationException() } override fun containsValue(value: String): Boolean { throw UnsupportedOperationException() } override fun get(key: String): String? { throw UnsupportedOperationException() } override val keys: Set<String> get() { throw UnsupportedOperationException() } override val values: Collection<String> get() { throw UnsupportedOperationException() } override val entries: Set<Map.Entry<String, String>> get() { throw UnsupportedOperationException() } } fun box(): String { val a = A() if (a.size != 56) return "fail 1: ${a.size}" val x: Map<String, String> = a if (x.size != 56) return "fail 2: ${x.size}" return "OK" }
apache-2.0
dd1b0dd954b94c46b82fc1bd107d6102
22.55814
64
0.629447
4.497778
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/data/download/Downloader.kt
1
16889
package eu.kanade.tachiyomi.data.download import android.content.Context import android.webkit.MimeTypeMap import com.elvishew.xlog.XLog import com.hippo.unifile.UniFile import com.jakewharton.rxrelay.BehaviorRelay import com.jakewharton.rxrelay.PublishRelay import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.data.download.model.DownloadQueue import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.source.online.fetchAllImageUrlsFromPageList import eu.kanade.tachiyomi.util.* import kotlinx.coroutines.async import okhttp3.Response import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subscriptions.CompositeSubscription import timber.log.Timber /** * This class is the one in charge of downloading chapters. * * Its [queue] contains the list of chapters to download. In order to download them, the downloader * subscriptions must be running and the list of chapters must be sent to them by [downloadsRelay]. * * The queue manipulation must be done in one thread (currently the main thread) to avoid unexpected * behavior, but it's safe to read it from multiple threads. * * @param context the application context. * @param provider the downloads directory provider. * @param cache the downloads cache, used to add the downloads to the cache after their completion. * @param sourceManager the source manager. */ class Downloader( private val context: Context, private val provider: DownloadProvider, private val cache: DownloadCache, private val sourceManager: SourceManager ) { /** * Store for persisting downloads across restarts. */ private val store = DownloadStore(context, sourceManager) /** * Queue where active downloads are kept. */ val queue = DownloadQueue(store) /** * Notifier for the downloader state and progress. */ private val notifier by lazy { DownloadNotifier(context) } /** * Downloader subscriptions. */ private val subscriptions = CompositeSubscription() /** * Relay to send a list of downloads to the downloader. */ private val downloadsRelay = PublishRelay.create<List<Download>>() /** * Relay to subscribe to the downloader status. */ val runningRelay: BehaviorRelay<Boolean> = BehaviorRelay.create(false) /** * Whether the downloader is running. */ @Volatile private var isRunning: Boolean = false init { launchNow { val chapters = async { store.restore() } queue.addAll(chapters.await()) } } /** * Starts the downloader. It doesn't do anything if it's already running or there isn't anything * to download. * * @return true if the downloader is started, false otherwise. */ fun start(): Boolean { if (isRunning || queue.isEmpty()) return false if (!subscriptions.hasSubscriptions()) initializeSubscriptions() val pending = queue.filter { it.status != Download.DOWNLOADED } pending.forEach { if (it.status != Download.QUEUE) it.status = Download.QUEUE } downloadsRelay.call(pending) return !pending.isEmpty() } /** * Stops the downloader. */ fun stop(reason: String? = null) { destroySubscriptions() queue .filter { it.status == Download.DOWNLOADING } .forEach { it.status = Download.ERROR } if (reason != null) { notifier.onWarning(reason) } else { if (notifier.paused) { notifier.paused = false notifier.onDownloadPaused() } else if (notifier.isSingleChapter && !notifier.errorThrown) { notifier.isSingleChapter = false } else { notifier.dismiss() } } } /** * Pauses the downloader */ fun pause() { destroySubscriptions() queue .filter { it.status == Download.DOWNLOADING } .forEach { it.status = Download.QUEUE } notifier.paused = true } /** * Removes everything from the queue. * * @param isNotification value that determines if status is set (needed for view updates) */ fun clearQueue(isNotification: Boolean = false) { destroySubscriptions() //Needed to update the chapter view if (isNotification) { queue .filter { it.status == Download.QUEUE } .forEach { it.status = Download.NOT_DOWNLOADED } } queue.clear() notifier.dismiss() } /** * Prepares the subscriptions to start downloading. */ private fun initializeSubscriptions() { if (isRunning) return isRunning = true runningRelay.call(true) subscriptions.clear() subscriptions += downloadsRelay.concatMapIterable { it } .concatMap { downloadChapter(it).subscribeOn(Schedulers.io()) } .onBackpressureBuffer() .observeOn(AndroidSchedulers.mainThread()) .subscribe({ completeDownload(it) }, { error -> DownloadService.stop(context) Timber.e(error) notifier.onError(error.message) }) } /** * Destroys the downloader subscriptions. */ private fun destroySubscriptions() { if (!isRunning) return isRunning = false runningRelay.call(false) subscriptions.clear() } /** * Creates a download object for every chapter and adds them to the downloads queue. * * @param manga the manga of the chapters to download. * @param chapters the list of chapters to download. * @param autoStart whether to start the downloader after enqueing the chapters. */ fun queueChapters(manga: Manga, chapters: List<Chapter>, autoStart: Boolean) = launchUI { val source = sourceManager.get(manga.source) as? HttpSource ?: return@launchUI // Called in background thread, the operation can be slow with SAF. val chaptersWithoutDir = async { val mangaDir = provider.findMangaDir(manga, source) chapters // Avoid downloading chapters with the same name. .distinctBy { it.name } // Filter out those already downloaded. .filter { mangaDir?.findFile(provider.getChapterDirName(it)) == null } // Add chapters to queue from the start. .sortedByDescending { it.source_order } } // Runs in main thread (synchronization needed). val chaptersToQueue = chaptersWithoutDir.await() // Filter out those already enqueued. .filter { chapter -> queue.none { it.chapter.id == chapter.id } } // Create a download for each one. .map { Download(source, manga, it) } if (chaptersToQueue.isNotEmpty()) { queue.addAll(chaptersToQueue) // Initialize queue size. notifier.initialQueueSize = queue.size if (isRunning) { // Send the list of downloads to the downloader. downloadsRelay.call(chaptersToQueue) } // Start downloader if needed if (autoStart) { DownloadService.start([email protected]) } } } /** * Returns the observable which downloads a chapter. * * @param download the chapter to be downloaded. */ private fun downloadChapter(download: Download): Observable<Download> = Observable.defer { val chapterDirname = provider.getChapterDirName(download.chapter) val mangaDir = provider.getMangaDir(download.manga, download.source) val tmpDir = mangaDir.createDirectory("${chapterDirname}_tmp") val pageListObservable = if (download.pages == null) { // Pull page list from network and add them to download object download.source.fetchPageList(download.chapter) .doOnNext { pages -> if (pages.isEmpty()) { throw Exception("Page list is empty") } download.pages = pages } } else { // Or if the page list already exists, start from the file Observable.just(download.pages!!) } pageListObservable .doOnNext { _ -> // Delete all temporary (unfinished) files tmpDir.listFiles() ?.filter { it.name!!.endsWith(".tmp") } ?.forEach { it.delete() } download.downloadedImages = 0 download.status = Download.DOWNLOADING } // Get all the URLs to the source images, fetch pages if necessary .flatMap { download.source.fetchAllImageUrlsFromPageList(it) } // Start downloading images, consider we can have downloaded images already .concatMap { page -> getOrDownloadImage(page, download, tmpDir) } // Do when page is downloaded. .doOnNext { notifier.onProgressChange(download) } .toList() .map { _ -> download } // Do after download completes .doOnNext { ensureSuccessfulDownload(download, mangaDir, tmpDir, chapterDirname) } // If the page list threw, it will resume here .onErrorReturn { error -> // [EXH] XLog.w("> Download error!", error) XLog.w("> (source.id: %s, source.name: %s, manga.id: %s, manga.url: %s, chapter.id: %s, chapter.url: %s)", download.source.id, download.source.name, download.manga.id, download.manga.url, download.chapter.id, download.chapter.url) download.status = Download.ERROR notifier.onError(error.message, download.chapter.name) download } } /** * Returns the observable which gets the image from the filesystem if it exists or downloads it * otherwise. * * @param page the page to download. * @param download the download of the page. * @param tmpDir the temporary directory of the download. */ private fun getOrDownloadImage(page: Page, download: Download, tmpDir: UniFile): Observable<Page> { // If the image URL is empty, do nothing if (page.imageUrl == null) return Observable.just(page) val filename = String.format("%03d", page.number) val tmpFile = tmpDir.findFile("$filename.tmp") // Delete temp file if it exists. tmpFile?.delete() // Try to find the image file. val imageFile = tmpDir.listFiles()!!.find { it.name!!.startsWith("$filename.") } // If the image is already downloaded, do nothing. Otherwise download from network val pageObservable = if (imageFile != null) Observable.just(imageFile) else downloadImage(page, download.source, tmpDir, filename) return pageObservable // When the image is ready, set image path, progress (just in case) and status .doOnNext { file -> page.uri = file.uri page.progress = 100 download.downloadedImages++ page.status = Page.READY } .map { page } // Mark this page as error and allow to download the remaining .onErrorReturn { page.progress = 0 page.status = Page.ERROR page } } /** * Returns the observable which downloads the image from network. * * @param page the page to download. * @param source the source of the page. * @param tmpDir the temporary directory of the download. * @param filename the filename of the image. */ private fun downloadImage(page: Page, source: HttpSource, tmpDir: UniFile, filename: String): Observable<UniFile> { page.status = Page.DOWNLOAD_IMAGE page.progress = 0 return source.fetchImage(page) .map { response -> val file = tmpDir.createFile("$filename.tmp") try { response.body()!!.source().saveTo(file.openOutputStream()) val extension = getImageExtension(response, file) file.renameTo("$filename.$extension") } catch (e: Exception) { // [EXH] XLog.w("> Failed to fetch image!", e) XLog.w("> (source.id: %s, source.name: %s, page.index: %s, page.url: %s, page.imageUrl: %s)", source.id, source.name, page.index, page.url, page.imageUrl) response.close() file.delete() throw e } file } // Retry 3 times, waiting 2, 4 and 8 seconds between attempts. .retryWhen(RetryWithDelay(3, { (2 shl it - 1) * 1000 }, Schedulers.trampoline())) } /** * Returns the extension of the downloaded image from the network response, or if it's null, * analyze the file. If everything fails, assume it's a jpg. * * @param response the network response of the image. * @param file the file where the image is already downloaded. */ private fun getImageExtension(response: Response, file: UniFile): String { // Read content type if available. val mime = response.body()?.contentType()?.let { ct -> "${ct.type()}/${ct.subtype()}" } // Else guess from the uri. ?: context.contentResolver.getType(file.uri) // Else read magic numbers. ?: ImageUtil.findImageType { file.openInputStream() }?.mime return MimeTypeMap.getSingleton().getExtensionFromMimeType(mime) ?: "jpg" } /** * Checks if the download was successful. * * @param download the download to check. * @param mangaDir the manga directory of the download. * @param tmpDir the directory where the download is currently stored. * @param dirname the real (non temporary) directory name of the download. */ private fun ensureSuccessfulDownload(download: Download, mangaDir: UniFile, tmpDir: UniFile, dirname: String) { // Ensure that the chapter folder has all the images. val downloadedImages = tmpDir.listFiles().orEmpty().filterNot { it.name!!.endsWith(".tmp") } download.status = if (downloadedImages.size == download.pages!!.size) { Download.DOWNLOADED } else { Download.ERROR } // Only rename the directory if it's downloaded. if (download.status == Download.DOWNLOADED) { tmpDir.renameTo(dirname) cache.addChapter(dirname, mangaDir, download.manga) } } /** * Completes a download. This method is called in the main thread. */ private fun completeDownload(download: Download) { // Delete successful downloads from queue if (download.status == Download.DOWNLOADED) { // remove downloaded chapter from queue queue.remove(download) } if (areAllDownloadsFinished()) { if (notifier.isSingleChapter && !notifier.errorThrown) { notifier.onDownloadCompleted(download, queue) } DownloadService.stop(context) } } /** * Returns true if all the queued downloads are in DOWNLOADED or ERROR state. */ private fun areAllDownloadsFinished(): Boolean { return queue.none { it.status <= Download.DOWNLOADING } } }
apache-2.0
a4b2b0d24a7ea8bf23f441e2d0be352a
35.956236
126
0.578542
5.117879
false
false
false
false
robovm/robovm-studio
plugins/settings-repository/src/git/gitCredential.kt
17
1909
package org.jetbrains.settingsRepository.git import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.ProcessNotCreatedException import com.intellij.openapi.util.text.StringUtil import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.transport.URIish import org.jetbrains.keychain.Credentials import org.jetbrains.settingsRepository.LOG private var canUseGitExe = true // https://www.kernel.org/pub/software/scm/git/docs/git-credential.html fun getCredentialsUsingGit(uri: URIish, repository: Repository): Credentials? { if (!canUseGitExe || repository.getConfig().getSubsections("credential").isEmpty()) { return null } val commandLine = GeneralCommandLine() commandLine.setExePath("git") commandLine.addParameter("credential") commandLine.addParameter("fill") commandLine.setPassParentEnvironment(true) val process: Process try { process = commandLine.createProcess() } catch (e: ProcessNotCreatedException) { canUseGitExe = false return null } val writer = process.getOutputStream().writer() writer.write("url=") writer.write(uri.toPrivateString()) writer.write("\n\n") writer.close(); val reader = process.getInputStream().reader().buffered() var username: String? = null var password: String? = null while (true) { val line = reader.readLine()?.trim() if (line == null || line.isEmpty()) { break } fun readValue() = line.substring(line.indexOf('=') + 1).trim() if (line.startsWith("username=")) { username = readValue() } else if (line.startsWith("password=")) { password = readValue() } } reader.close() val errorText = process.getErrorStream().reader().readText() if (!StringUtil.isEmpty(errorText)) { LOG.warn(errorText) } return if (username == null && password == null) null else Credentials(username, password) }
apache-2.0
194417b24ade0f700867898e652eb1de
28.828125
92
0.719749
4.177243
false
false
false
false
andrewoma/kwery
mapper/src/test/kotlin/com/github/andrewoma/kwery/mappertest/example/test/AbstractFilmDaoTest.kt
1
4333
/* * Copyright (c) 2015 Andrew O'Malley * * 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 com.github.andrewoma.kwery.mappertest.example.test import com.github.andrewoma.kwery.core.Session import com.github.andrewoma.kwery.mapper.AbstractDao import com.github.andrewoma.kwery.mappertest.example.* import java.time.Duration import java.time.LocalDateTime import kotlin.properties.Delegates abstract class AbstractFilmDaoTest<T : Any, ID : Any, D : AbstractDao<T, ID>> : AbstractDaoTest<T, ID, D>() { var sd: FilmData by Delegates.notNull() var staticId = -500 override fun afterSessionSetup() { sd = initialise("filmSchema") { initialiseFilmSchema(it) } super.afterSessionSetup() } } //language=SQL val filmSchema = """ create sequence actor_seq; create table actor ( actor_id integer generated by default as sequence actor_seq primary key, first_name character varying(255) not null, last_name character varying(255) null, last_update timestamp not null ); create table film ( film_id integer identity, title character varying(255) not null, release_year integer, language_id integer not null , original_language_id integer, length integer, rating character varying (255), last_update timestamp not null, special_features varchar(255) array ); create table language ( language_id integer identity, name character varying(255) not null, last_update timestamp not null ); create table film_actor ( film_id integer not null, actor_id integer not null, last_update timestamp not null, primary key(film_id, actor_id) ) """ class FilmData { fun <T : Any> notNull() = Delegates.notNull<T>() var actorBrad: Actor by notNull() var actorKate: Actor by notNull() var languageEnglish: Language by notNull() var languageSpanish: Language by notNull() var filmUnderworld: Film by notNull() var filmUnderworld2: Film by notNull() } fun initialiseFilmSchema(session: Session): FilmData { for (statement in filmSchema.split(";".toRegex())) { session.update(statement) } // Use negative ids for static content var id = -1000 val d = FilmData() val actorDao = ActorDao(session, FilmActorDao(session)) d.actorBrad = actorDao.insert(Actor(Name("Brad", "Pitt"), --id, LocalDateTime.now())) d.actorKate = actorDao.insert(Actor(Name("Kate", "Beckinsale"), --id, LocalDateTime.now())) val languageDao = LanguageDao(session) d.languageEnglish = languageDao.insert(Language(--id, "English", LocalDateTime.now())) d.languageSpanish = languageDao.insert(Language(--id, "Spanish", LocalDateTime.now())) val filmDao = FilmDao(session) d.filmUnderworld = filmDao.insert(Film(--id, "Static Underworld", 2003, d.languageEnglish, null, Duration.ofMinutes(121), FilmRating.NC_17, LocalDateTime.now(), listOf("Commentaries", "Behind the Scenes"))) d.filmUnderworld2 = filmDao.insert(Film(--id, "Static Underworld: Evolution", 2006, d.languageEnglish, null, Duration.ofMinutes(106), FilmRating.R, LocalDateTime.now(), listOf("Behind the Scenes"))) return d }
mit
747585dd1dc062d2107e3177e851c07c
36.353448
125
0.700669
4.307157
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt
1
9398
package info.nightscout.androidaps.plugins.general.maintenance import android.content.Context import android.content.Intent import android.net.Uri import androidx.core.content.FileProvider import dagger.android.HasAndroidInjector import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.io.* import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream import javax.inject.Inject import javax.inject.Singleton @Singleton class MaintenancePlugin @Inject constructor( injector: HasAndroidInjector, private val context: Context, rh: ResourceHelper, private val sp: SP, private val nsSettingsStatus: NSSettingsStatus, aapsLogger: AAPSLogger, private val buildHelper: BuildHelper, private val config: Config, private val fileListProvider: PrefFileListProvider, private val loggerUtils: LoggerUtils ) : PluginBase( PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(MaintenanceFragment::class.java.name) .alwaysVisible(false) .alwaysEnabled(true) .pluginIcon(R.drawable.ic_maintenance) .pluginName(R.string.maintenance) .shortName(R.string.maintenance_shortname) .preferencesId(R.xml.pref_maintenance) .description(R.string.description_maintenance), aapsLogger, rh, injector ) { fun sendLogs() { val recipient = sp.getString(R.string.key_maintenance_logs_email, "[email protected]") val amount = sp.getInt(R.string.key_maintenance_logs_amount, 2) val logs = getLogFiles(amount) val zipDir = fileListProvider.ensureTempDirExists() val zipFile = File(zipDir, constructName()) aapsLogger.debug("zipFile: ${zipFile.absolutePath}") val zip = zipLogs(zipFile, logs) val attachmentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", zip) val emailIntent: Intent = this.sendMail(attachmentUri, recipient, "Log Export") aapsLogger.debug("sending emailIntent") context.startActivity(emailIntent) } fun deleteLogs(keep: Int) { val logDir = File(loggerUtils.logDirectory) val files = logDir.listFiles { _: File?, name: String -> (name.startsWith("AndroidAPS") && name.endsWith(".zip")) } val autotunefiles = logDir.listFiles { _: File?, name: String -> (name.startsWith("autotune") && name.endsWith(".zip")) } val amount = sp.getInt(R.string.key_logshipper_amount, keep) val keepIndex = amount - 1 if (autotunefiles != null && autotunefiles.isNotEmpty()) { Arrays.sort(autotunefiles) { f1: File, f2: File -> f2.name.compareTo(f1.name) } var delAutotuneFiles = listOf(*autotunefiles) if (keepIndex < delAutotuneFiles.size) { delAutotuneFiles = delAutotuneFiles.subList(keepIndex, delAutotuneFiles.size) for (file in delAutotuneFiles) { file.delete() } } } if (files == null || files.isEmpty()) return Arrays.sort(files) { f1: File, f2: File -> f2.name.compareTo(f1.name) } var delFiles = listOf(*files) if (keepIndex < delFiles.size) { delFiles = delFiles.subList(keepIndex, delFiles.size) for (file in delFiles) { file.delete() } } val exportDir = fileListProvider.ensureTempDirExists() if (exportDir.exists()) { exportDir.listFiles()?.let { expFiles -> for (file in expFiles) file.delete() } exportDir.delete() } } /** * returns a list of log files. The number of returned logs is given via the amount * parameter. * * The log files are sorted by the name descending. * * @param amount * @return */ fun getLogFiles(amount: Int): List<File> { aapsLogger.debug("getting $amount logs from directory ${loggerUtils.logDirectory}") val logDir = File(loggerUtils.logDirectory) val files = logDir.listFiles { _: File?, name: String -> (name.startsWith("AndroidAPS") && (name.endsWith(".log") || name.endsWith(".zip") && !name.endsWith(loggerUtils.suffix))) } ?: emptyArray() Arrays.sort(files) { f1: File, f2: File -> f2.name.compareTo(f1.name) } val result = listOf(*files) var toIndex = amount if (toIndex > result.size) { toIndex = result.size } aapsLogger.debug("returning sublist 0 to $toIndex") return result.subList(0, toIndex) } fun zipLogs(zipFile: File, files: List<File>): File { aapsLogger.debug("creating zip ${zipFile.absolutePath}") try { zip(zipFile, files) } catch (e: IOException) { aapsLogger.error("Cannot retrieve zip", e) } return zipFile } /** * construct the name of zip file which is used to export logs. * * The name is constructed using the following scheme: * AndroidAPS_LOG_ + Long Time + .log.zip * * @return */ private fun constructName(): String { return "AndroidAPS_LOG_" + System.currentTimeMillis() + loggerUtils.suffix } private fun zip(zipFile: File?, files: List<File>) { val bufferSize = 2048 val out = ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))) for (file in files) { val data = ByteArray(bufferSize) FileInputStream(file).use { fileInputStream -> BufferedInputStream(fileInputStream, bufferSize).use { origin -> val entry = ZipEntry(file.name) out.putNextEntry(entry) var count: Int while (origin.read(data, 0, bufferSize).also { count = it } != -1) { out.write(data, 0, count) } } } } out.close() } @Suppress("SameParameterValue") private fun sendMail(attachmentUri: Uri, recipient: String, subject: String): Intent { val builder = StringBuilder() builder.append("ADD TIME OF EVENT HERE: " + System.lineSeparator()) builder.append("ADD ISSUE DESCRIPTION OR GITHUB ISSUE REFERENCE NUMBER: " + System.lineSeparator()) builder.append("-------------------------------------------------------" + System.lineSeparator()) builder.append("(Please remember this will send only very recent logs." + System.lineSeparator()) builder.append("If you want to provide logs for event older than a few hours," + System.lineSeparator()) builder.append("you have to do it manually)" + System.lineSeparator()) builder.append("-------------------------------------------------------" + System.lineSeparator()) builder.append(rh.gs(R.string.app_name) + " " + BuildConfig.VERSION + System.lineSeparator()) if (config.NSCLIENT) builder.append("NSCLIENT" + System.lineSeparator()) builder.append("Build: " + BuildConfig.BUILDVERSION + System.lineSeparator()) builder.append("Remote: " + BuildConfig.REMOTE + System.lineSeparator()) builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator()) builder.append(rh.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.getVersion() + System.lineSeparator()) if (buildHelper.isEngineeringMode()) builder.append(rh.gs(R.string.engineering_mode_enabled)) return sendMail(attachmentUri, recipient, subject, builder.toString()) } /** * send a mail with the given file to the recipients with the given subject. * * the returned intent should be used to really send the mail using * * startActivity(Intent.createChooser(emailIntent , "Send email...")); * * @param attachmentUri * @param recipient * @param subject * @param body * * @return */ private fun sendMail( attachmentUri: Uri, recipient: String, subject: String, body: String ): Intent { aapsLogger.debug("sending email to $recipient with subject $subject") val emailIntent = Intent(Intent.ACTION_SEND) emailIntent.type = "text/plain" emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(recipient)) emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject) emailIntent.putExtra(Intent.EXTRA_TEXT, body) aapsLogger.debug("put path $attachmentUri") emailIntent.putExtra(Intent.EXTRA_STREAM, attachmentUri) emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) return emailIntent } }
agpl-3.0
3b41a8e8214c70c8f986e41101573f6c
40.959821
140
0.638327
4.58439
false
true
false
false
trevorhalvorson/ping-android
app/src/main/kotlin/com/trevorhalvorson/ping/sendMessage/SendMessageActivity.kt
1
23770
package com.trevorhalvorson.ping.sendMessage import android.app.AlertDialog import android.app.ProgressDialog import android.content.Intent import android.graphics.drawable.ColorDrawable import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.design.widget.TextInputEditText import android.telephony.PhoneNumberUtils import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.util.Patterns import android.util.TypedValue.COMPLEX_UNIT_PX import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.widget.Button import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions.* import com.google.android.libraries.remixer.annotation.* import com.google.android.libraries.remixer.ui.view.RemixerFragment import com.google.gson.Gson import com.trevorhalvorson.ping.BuildConfig import com.trevorhalvorson.ping.R import com.trevorhalvorson.ping.builder.BuilderActivity import com.trevorhalvorson.ping.builder.BuilderConfig import dagger.android.AndroidInjection import kotlinx.android.synthetic.main.activity_send_message.* import kotlinx.android.synthetic.main.layout_number_pad.* import javax.inject.Inject class SendMessageActivity : AppCompatActivity(), SendMessageContract.View, View.OnClickListener { @Inject lateinit var sendMessagePresenter: SendMessageContract.Presenter override fun setPresenter(presenter: SendMessageContract.Presenter) { sendMessagePresenter = presenter } override fun showProgress() { progressDialog = ProgressDialog.show(this, getString(R.string.message_progress_dialog_title_text), getString(R.string.message_progress_dialog_message_text), true, false) } override fun hideProgress() { progressDialog?.dismiss() } override fun showError(error: String?) { if (error != null) { errorDialog = AlertDialog.Builder(this) .setTitle(getString(R.string.error_dialog_title_text)) .setMessage(error) .create() errorDialog?.show() } } override fun hideError() { errorDialog?.dismiss() } override fun clearInput() { number_edit_text.text.clear() } override fun showPinError() { pinEditText?.error = getString(R.string.pin_error_message) } override fun showAdminView() { val view = layoutInflater.inflate(R.layout.dialog_admin, send_message_layout, false) val dialog = AlertDialog.Builder(this).setView(view) .setTitle(getString(R.string.dialog_admin_title)) .setNegativeButton(getString(R.string.dialog_admin_negative_button), { dialogInterface, _ -> dialogInterface.cancel() hideConfigButton() adminMode = false }) .create() dialog.show() view.findViewById<Button>(R.id.edit_configs_button).setOnClickListener { showConfigView() dialog.cancel() } view.findViewById<Button>(R.id.show_builder_view_button).setOnClickListener { val builderIntent = Intent(this, BuilderActivity::class.java) builderIntent.putExtra("config", Gson().toJson( BuilderConfig( title_text.text.toString(), title_text.textSize.toString(), title_text.currentTextColor.toHex(), imageUrl, main_image.width.toString(), main_image.height.toString(), main_image.scaleType.toString(), copy_text.text.toString(), copy_text.textSize.toString(), copy_text.currentTextColor.toHex(), send_button.text.toString(), send_button.currentTextColor.toHex(), (send_button.background as ColorDrawable).color.toHex(), number_edit_text.currentTextColor.toHex(), (number_text_input_layout.background as ColorDrawable).color .toHex(), num_pad_0.currentTextColor.toHex(), (layout_number_pad.background as ColorDrawable).color.toHex(), (container_linear_layout.background as ColorDrawable).color .toHex(), pin, message, BuildConfig.MESSAGING_URL_BASE, BuildConfig.MESSAGING_URL_PATH, BuildConfig.BUILDER_URL_BASE, BuildConfig.BUILDER_URL_PATH, BuildConfig.EMAIL ))) startActivity(builderIntent) } } override fun showConfigView() { RemixerFragment.newInstance().showRemixer(supportFragmentManager, RemixerFragment.REMIXER_TAG) } private var progressDialog: ProgressDialog? = null private var errorDialog: AlertDialog? = null private var message = BuildConfig.MESSAGE private var imageUrl = BuildConfig.IMAGE_URL private var pin = BuildConfig.PIN private var phoneNumber: String? = null private var adminMode: Boolean = false private var pinEditText: TextInputEditText? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_send_message) AndroidInjection.inject(this) hideSystemUI() send_button.setOnClickListener { sendMessagePresenter.sendMessage(phoneNumber!!, message) } number_edit_text.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(editable: Editable?) { } override fun beforeTextChanged(number: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(number: CharSequence, p1: Int, p2: Int, p3: Int) { val isValid = Patterns.PHONE.matcher(number).matches() && !PhoneNumberUtils.isEmergencyNumber(number.toString()); send_button.isEnabled = isValid if (isValid) phoneNumber = number.toString() } }) num_pad_1.setOnClickListener(this) num_pad_2.setOnClickListener(this) num_pad_3.setOnClickListener(this) num_pad_4.setOnClickListener(this) num_pad_5.setOnClickListener(this) num_pad_6.setOnClickListener(this) num_pad_7.setOnClickListener(this) num_pad_8.setOnClickListener(this) num_pad_9.setOnClickListener(this) num_pad_0.setOnClickListener(this) num_pad_del.setOnClickListener { if (number_edit_text.text.isNotEmpty()) { number_edit_text.text.delete(number_edit_text.text.length - 1, number_edit_text.text.length) } } num_pad_del.setOnLongClickListener { clearInput() true } var blankClickCount = 0 num_pad_blank.setOnClickListener { if (++blankClickCount == 7) { showConfigButton() blankClickCount = 0 } } config_button.setOnClickListener { if (adminMode) { showAdminView() } else { val view = layoutInflater.inflate(R.layout.dialog_pin, send_message_layout, false) pinEditText = view.findViewById(R.id.pin_edit_text) val dialog = AlertDialog.Builder(this).setView(view) .setTitle(getString(R.string.dialog_pin_title)) .setNegativeButton(getString(R.string.dialog_pin_negative_button), { dialogInterface, _ -> dialogInterface.cancel() hideConfigButton() }) .create() dialog.show() view.findViewById<Button>(R.id.submit_pin_button).setOnClickListener { if (sendMessagePresenter.submitPin(pinEditText?.text.toString())) { adminMode = true dialog.cancel() } } } } RemixerBinder.bind(this) } private fun showConfigButton() { num_pad_blank.visibility = GONE config_button.visibility = VISIBLE } private fun hideConfigButton() { config_button.visibility = GONE num_pad_blank.visibility = VISIBLE } override fun onClick(view: View?) { number_edit_text.text.append((view as TextView).text) } override fun onBackPressed() { // prevent user from exiting app via the back button } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) hideSystemUI() } private fun hideSystemUI() { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE .or(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) .or(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) .or(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) .or(View.SYSTEM_UI_FLAG_FULLSCREEN) .or(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) } // Remixer UI controls @StringVariableMethod(title = "Title Text", initialValue = BuildConfig.TITLE_TEXT) fun setTitleText(text: String?) { if (text != null) { title_text.text = text } } @RangeVariableMethod(title = "Title Text Size", initialValue = BuildConfig.TITLE_TEXT_SIZE, minValue = 12F, maxValue = 120F) fun setTitleTextSize(textSize: Float?) { if (textSize != null) { title_text.setTextSize(COMPLEX_UNIT_PX, textSize) } } @ColorListVariableMethod(title = "Title Text Color", initialValue = BuildConfig.TITLE_TEXT_COLOR, limitedToValues = intArrayOf( 0xFF000000.toInt(), 0xFFE91E63.toInt(), 0xFF9C27B0.toInt(), 0xFF673AB7.toInt(), 0xFF3F51B5.toInt(), 0xFF2196F3.toInt(), 0xFF03A9F4.toInt(), 0xFF00BCD4.toInt(), 0xFF009688.toInt(), 0xFF4CAF50.toInt(), 0xFF8BC34A.toInt(), 0xFFFFEB3B.toInt(), 0xFFFFC107.toInt(), 0xFF8BC34A.toInt(), 0xFFFF9800.toInt(), 0xFFFF5722.toInt(), 0xFF9E9E9E.toInt(), 0xFF607D8B.toInt(), 0xFF424242.toInt(), 0xFF37474F.toInt(), 0xFF212121.toInt(), 0xFF263238.toInt(), 0xFFFFFFFF.toInt() )) fun setTitleTextColor(color: Int?) { if (color != null) { title_text.setTextColor(color) } } @StringVariableMethod(title = "Image URL", initialValue = BuildConfig.IMAGE_URL) fun setMainImageUrl(url: String?) { if (!TextUtils.isEmpty(url)) { imageUrl = url!! Glide.with(this).load(imageUrl).apply(centerCropTransform()).into(main_image) } } @RangeVariableMethod(title = "Image Width", initialValue = BuildConfig.IMAGE_WIDTH, minValue = 0F, maxValue = 1200F) fun setMainImageWidth(width: Float?) { if (width != null) { main_image.layoutParams.width = width.toInt() main_image.requestLayout() Glide.with(this).clear(main_image) Glide.with(this).load(imageUrl).into(main_image) } } @RangeVariableMethod(title = "Image Height", initialValue = BuildConfig.IMAGE_HEIGHT, minValue = 0F, maxValue = 1200F) fun setMainImageHeight(height: Float?) { if (height != null) { main_image.layoutParams.height = height.toInt() main_image.requestLayout() Glide.with(this).clear(main_image) Glide.with(this).load(imageUrl).into(main_image) } } @StringListVariableMethod(title = "Image Scale Type", initialValue = BuildConfig.IMAGE_SCALE_TYPE, limitedToValues = arrayOf( "CENTER", "CENTER_CROP", "CENTER_INSIDE", "FIT_CENTER", "FIT_XY" )) fun setMainImageScaleType(type: String?) { val scaleType: ImageView.ScaleType? = when (type) { "CENTER" -> ImageView.ScaleType.CENTER "CENTER_CROP" -> ImageView.ScaleType.CENTER_CROP "CENTER_INSIDE" -> ImageView.ScaleType.CENTER_INSIDE "FIT_CENTER" -> ImageView.ScaleType.FIT_CENTER "FIT_XY" -> ImageView.ScaleType.FIT_XY else -> { ImageView.ScaleType.CENTER } } main_image.scaleType = scaleType main_image.requestLayout() Glide.with(this).clear(main_image) Glide.with(this).load(imageUrl).into(main_image) } @StringVariableMethod(title = "Copy Text", initialValue = BuildConfig.COPY_TEXT) fun setCopyText(text: String?) { if (text != null) { copy_text.text = text } } @RangeVariableMethod(title = "Copy Text Size", initialValue = BuildConfig.COPY_TEXT_SIZE, minValue = 12F, maxValue = 120F) fun setCopyTextSize(textSize: Float?) { if (textSize != null) { copy_text.setTextSize(COMPLEX_UNIT_PX, textSize) } } @ColorListVariableMethod(title = "Copy Text Color", initialValue = BuildConfig.COPY_TEXT_COLOR, limitedToValues = intArrayOf( 0xFF000000.toInt(), 0xFFE91E63.toInt(), 0xFF9C27B0.toInt(), 0xFF673AB7.toInt(), 0xFF3F51B5.toInt(), 0xFF2196F3.toInt(), 0xFF03A9F4.toInt(), 0xFF00BCD4.toInt(), 0xFF009688.toInt(), 0xFF4CAF50.toInt(), 0xFF8BC34A.toInt(), 0xFFFFEB3B.toInt(), 0xFFFFC107.toInt(), 0xFF8BC34A.toInt(), 0xFFFF9800.toInt(), 0xFFFF5722.toInt(), 0xFF9E9E9E.toInt(), 0xFF607D8B.toInt(), 0xFF424242.toInt(), 0xFF37474F.toInt(), 0xFF212121.toInt(), 0xFF263238.toInt(), 0xFFFFFFFF.toInt() )) fun setCopyTextColor(color: Int?) { if (color != null) { copy_text.setTextColor(color) } } @StringVariableMethod(title = "Send Button Text", initialValue = BuildConfig.SEND_BUTTON_TEXT) fun setSendButtonText(text: String?) { if (text != null) { send_button.text = text } } @ColorListVariableMethod(title = "Send Button Text Color", initialValue = BuildConfig.SEND_BUTTON_TEXT_COLOR, limitedToValues = intArrayOf( 0xFF000000.toInt(), 0xFFE91E63.toInt(), 0xFF9C27B0.toInt(), 0xFF673AB7.toInt(), 0xFF3F51B5.toInt(), 0xFF2196F3.toInt(), 0xFF03A9F4.toInt(), 0xFF00BCD4.toInt(), 0xFF009688.toInt(), 0xFF4CAF50.toInt(), 0xFF8BC34A.toInt(), 0xFFFFEB3B.toInt(), 0xFFFFC107.toInt(), 0xFF8BC34A.toInt(), 0xFFFF9800.toInt(), 0xFFFF5722.toInt(), 0xFF9E9E9E.toInt(), 0xFF607D8B.toInt(), 0xFF424242.toInt(), 0xFF37474F.toInt(), 0xFF212121.toInt(), 0xFF263238.toInt(), 0xFFFFFFFF.toInt() )) fun setSendButtonTextColor(color: Int?) { if (color != null) { send_button.setTextColor(color) } } @ColorListVariableMethod(title = "Send Message Button Color", initialValue = BuildConfig.SEND_BUTTON_BACKGROUND_COLOR, limitedToValues = intArrayOf( 0xFFCCCCCC.toInt(), 0xFF000000.toInt(), 0xFFE91E63.toInt(), 0xFF9C27B0.toInt(), 0xFF673AB7.toInt(), 0xFF3F51B5.toInt(), 0xFF2196F3.toInt(), 0xFF03A9F4.toInt(), 0xFF00BCD4.toInt(), 0xFF009688.toInt(), 0xFF4CAF50.toInt(), 0xFF8BC34A.toInt(), 0xFFFFEB3B.toInt(), 0xFFFFC107.toInt(), 0xFF8BC34A.toInt(), 0xFFFF9800.toInt(), 0xFFFF5722.toInt(), 0xFF9E9E9E.toInt(), 0xFF607D8B.toInt(), 0xFF424242.toInt(), 0xFF37474F.toInt(), 0xFF212121.toInt(), 0xFF263238.toInt(), 0xFFFFFFFF.toInt() )) fun setSendButtonBackgroundColor(color: Int?) { if (color != null) { send_button.setBackgroundColor(color) } } @ColorListVariableMethod(title = "Phone Number Background Color", initialValue = BuildConfig.PHONE_INPUT_BACKGROUND_COLOR, limitedToValues = intArrayOf( 0xFF000000.toInt(), 0xFFE91E63.toInt(), 0xFF9C27B0.toInt(), 0xFF673AB7.toInt(), 0xFF3F51B5.toInt(), 0xFF2196F3.toInt(), 0xFF03A9F4.toInt(), 0xFF00BCD4.toInt(), 0xFF009688.toInt(), 0xFF4CAF50.toInt(), 0xFF8BC34A.toInt(), 0xFFFFEB3B.toInt(), 0xFFFFC107.toInt(), 0xFF8BC34A.toInt(), 0xFFFF9800.toInt(), 0xFFFF5722.toInt(), 0xFF9E9E9E.toInt(), 0xFF607D8B.toInt(), 0xFF424242.toInt(), 0xFF37474F.toInt(), 0xFF212121.toInt(), 0xFF263238.toInt(), 0xFFFFFFFF.toInt() )) fun setPhoneNumberBackgroundTextColor(color: Int?) { if (color != null) { number_text_input_layout.setBackgroundColor(color) } } @ColorListVariableMethod(title = "Phone Number Input Text Color", initialValue = BuildConfig.PHONE_INPUT_TEXT_COLOR, limitedToValues = intArrayOf( 0xFF000000.toInt(), 0xFFE91E63.toInt(), 0xFF9C27B0.toInt(), 0xFF673AB7.toInt(), 0xFF3F51B5.toInt(), 0xFF2196F3.toInt(), 0xFF03A9F4.toInt(), 0xFF00BCD4.toInt(), 0xFF009688.toInt(), 0xFF4CAF50.toInt(), 0xFF8BC34A.toInt(), 0xFFFFEB3B.toInt(), 0xFFFFC107.toInt(), 0xFF8BC34A.toInt(), 0xFFFF9800.toInt(), 0xFFFF5722.toInt(), 0xFF9E9E9E.toInt(), 0xFF607D8B.toInt(), 0xFF424242.toInt(), 0xFF37474F.toInt(), 0xFF212121.toInt(), 0xFF263238.toInt(), 0xFFFFFFFF.toInt() )) fun setPhoneNumberInputTextColor(color: Int?) { if (color != null) { number_edit_text.setTextColor(color) } } @ColorListVariableMethod(title = "Number Pad Text Color", initialValue = BuildConfig.NUM_PAD_TEXT_COLOR, limitedToValues = intArrayOf( 0xFF000000.toInt(), 0xFFE91E63.toInt(), 0xFF9C27B0.toInt(), 0xFF673AB7.toInt(), 0xFF3F51B5.toInt(), 0xFF2196F3.toInt(), 0xFF03A9F4.toInt(), 0xFF00BCD4.toInt(), 0xFF009688.toInt(), 0xFF4CAF50.toInt(), 0xFF8BC34A.toInt(), 0xFFFFEB3B.toInt(), 0xFFFFC107.toInt(), 0xFF8BC34A.toInt(), 0xFFFF9800.toInt(), 0xFFFF5722.toInt(), 0xFF9E9E9E.toInt(), 0xFF607D8B.toInt(), 0xFF424242.toInt(), 0xFF37474F.toInt(), 0xFF212121.toInt(), 0xFF263238.toInt(), 0xFFFFFFFF.toInt() )) fun setPhoneNumberPadTextColor(color: Int?) { if (color != null) { num_pad_1.setTextColor(color) num_pad_2.setTextColor(color) num_pad_3.setTextColor(color) num_pad_4.setTextColor(color) num_pad_5.setTextColor(color) num_pad_6.setTextColor(color) num_pad_7.setTextColor(color) num_pad_8.setTextColor(color) num_pad_9.setTextColor(color) num_pad_0.setTextColor(color) num_pad_del.setTextColor(color) } } @ColorListVariableMethod(title = "Number Pad Background Color", initialValue = BuildConfig.NUM_PAD_BACKGROUND_COLOR, limitedToValues = intArrayOf( 0xFFFFFFFF.toInt(), 0xFFE91E63.toInt(), 0xFF9C27B0.toInt(), 0xFF673AB7.toInt(), 0xFF3F51B5.toInt(), 0xFF2196F3.toInt(), 0xFF03A9F4.toInt(), 0xFF00BCD4.toInt(), 0xFF009688.toInt(), 0xFF4CAF50.toInt(), 0xFF8BC34A.toInt(), 0xFFFFEB3B.toInt(), 0xFFFFC107.toInt(), 0xFF8BC34A.toInt(), 0xFFFF9800.toInt(), 0xFFFF5722.toInt(), 0xFF9E9E9E.toInt(), 0xFF607D8B.toInt(), 0xFF424242.toInt(), 0xFF37474F.toInt(), 0xFF212121.toInt(), 0xFF263238.toInt(), 0xFF000000.toInt() )) fun setPhoneNumberPadBackgroundColor(color: Int?) { if (color != null && layout_number_pad != null) { layout_number_pad.setBackgroundColor(color) } } @ColorListVariableMethod(title = "Main Background Color", initialValue = BuildConfig.BACKGROUND_COLOR, limitedToValues = intArrayOf( 0xFFFFFFFF.toInt(), 0xFFE91E63.toInt(), 0xFF9C27B0.toInt(), 0xFF673AB7.toInt(), 0xFF3F51B5.toInt(), 0xFF2196F3.toInt(), 0xFF03A9F4.toInt(), 0xFF00BCD4.toInt(), 0xFF009688.toInt(), 0xFF4CAF50.toInt(), 0xFF8BC34A.toInt(), 0xFFFFEB3B.toInt(), 0xFFFFC107.toInt(), 0xFF8BC34A.toInt(), 0xFFFF9800.toInt(), 0xFFFF5722.toInt(), 0xFF9E9E9E.toInt(), 0xFF607D8B.toInt(), 0xFF424242.toInt(), 0xFF37474F.toInt(), 0xFF212121.toInt(), 0xFF263238.toInt(), 0xFF000000.toInt() )) fun setBackgroundColor(color: Int?) { if (color != null) { container_linear_layout.setBackgroundColor(color) } } @StringVariableMethod(title = "Message", initialValue = BuildConfig.MESSAGE) fun setMessageText(s: String?) { if (s != null) { message = s } } @StringVariableMethod(title = "PIN", initialValue = BuildConfig.PIN) fun setPin(s: String?) { if (s != null) { pin = s } } } fun Int.toHex(): String { return "0xFF" + String.format("%06X", 0xFFFFFF and this) }
mit
59f27cded9b536c245e2123c7489d5aa
34.060472
99
0.555322
4.464688
false
true
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt
1
1120
package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.database.entities.TemporaryBasal import info.nightscout.androidaps.extensions.convertedToAbsolute import info.nightscout.androidaps.utils.DateUtil import java.util.* class BasalElement(tbr: TemporaryBasal, private val profile: Profile, dateUtil: DateUtil) : BaseElement(tbr.timestamp, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.timestamp).toByteArray()).toString(), dateUtil) { internal var timestamp: Long = 0 // not exposed @Expose internal var deliveryType = "automated" @Expose internal var duration: Long = 0 @Expose internal var rate = -1.0 @Expose internal var scheduleName = "AAPS" @Expose internal var clockDriftOffset: Long = 0 @Expose internal var conversionOffset: Long = 0 init { type = "basal" timestamp = tbr.timestamp rate = tbr.convertedToAbsolute(tbr.timestamp, profile) duration = tbr.duration } }
agpl-3.0
76f94f82915092c771f8bdc279bcc537
27.74359
125
0.73125
4.48
false
false
false
false
Adventech/sabbath-school-android-2
features/media/src/main/kotlin/app/ss/media/playback/PlaybackConnection.kt
1
9072
/* * Copyright (c) 2021. Adventech <[email protected]> * * 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 app.ss.media.playback import android.content.ComponentName import android.content.Context import android.os.Bundle import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaControllerCompat import android.support.v4.media.session.PlaybackStateCompat import androidx.core.os.bundleOf import androidx.lifecycle.ProcessLifecycleOwner import androidx.lifecycle.lifecycleScope import app.ss.media.playback.extensions.NONE_PLAYBACK_STATE import app.ss.media.playback.extensions.NONE_PLAYING import app.ss.media.playback.extensions.duration import app.ss.media.playback.extensions.isBuffering import app.ss.media.playback.extensions.isPlaying import app.ss.media.playback.model.MEDIA_TYPE_AUDIO import app.ss.media.playback.model.MediaId import app.ss.media.playback.model.PlaybackModeState import app.ss.media.playback.model.PlaybackProgressState import app.ss.media.playback.model.PlaybackQueue import app.ss.media.playback.model.PlaybackSpeed import app.ss.media.playback.players.AudioPlayer import app.ss.media.playback.players.QUEUE_LIST_KEY import app.ss.models.media.AudioFile import com.cryart.sabbathschool.core.extensions.coroutines.flow.flowInterval import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch const val PLAYBACK_PROGRESS_INTERVAL = 1000L interface PlaybackConnection { val isConnected: StateFlow<Boolean> val playbackState: StateFlow<PlaybackStateCompat> val nowPlaying: StateFlow<MediaMetadataCompat> val playbackQueue: StateFlow<PlaybackQueue> val playbackProgress: StateFlow<PlaybackProgressState> val playbackMode: StateFlow<PlaybackModeState> val playbackSpeed: StateFlow<PlaybackSpeed> var mediaController: MediaControllerCompat? val transportControls: MediaControllerCompat.TransportControls? fun playAudio(audio: AudioFile) fun playAudios(audios: List<AudioFile>, index: Int = 0) fun toggleSpeed(playbackSpeed: PlaybackSpeed) fun setQueue(audios: List<AudioFile>, index: Int = 0) } internal class PlaybackConnectionImpl( context: Context, serviceComponent: ComponentName, private val audioPlayer: AudioPlayer, coroutineScope: CoroutineScope = ProcessLifecycleOwner.get().lifecycleScope ) : PlaybackConnection, CoroutineScope by coroutineScope { override val isConnected = MutableStateFlow(false) override val playbackState = MutableStateFlow(NONE_PLAYBACK_STATE) override val nowPlaying = MutableStateFlow(NONE_PLAYING) private val playbackQueueState = MutableStateFlow(PlaybackQueue()) override val playbackQueue = playbackQueueState private var playbackProgressInterval: Job = Job() override val playbackProgress = MutableStateFlow(PlaybackProgressState()) override val playbackMode = MutableStateFlow(PlaybackModeState()) override val playbackSpeed = MutableStateFlow(PlaybackSpeed.NORMAL) override var mediaController: MediaControllerCompat? = null override val transportControls get() = mediaController?.transportControls private val mediaBrowserConnectionCallback = MediaBrowserConnectionCallback(context) private val mediaBrowser = MediaBrowserCompat( context, serviceComponent, mediaBrowserConnectionCallback, null ).apply { connect() } private var currentProgressInterval: Long = PLAYBACK_PROGRESS_INTERVAL init { startPlaybackProgress() } override fun playAudio(audio: AudioFile) = playAudios(audios = listOf(audio), index = 0) override fun playAudios(audios: List<AudioFile>, index: Int) { val audiosIds = audios.map { it.id }.toTypedArray() val audio = audios[index] transportControls?.playFromMediaId( MediaId(MEDIA_TYPE_AUDIO, audio.id).toString(), Bundle().apply { putStringArray(QUEUE_LIST_KEY, audiosIds) } ) transportControls?.sendCustomAction(UPDATE_QUEUE, bundleOf()) } override fun toggleSpeed(playbackSpeed: PlaybackSpeed) { val nextSpeed = when (playbackSpeed) { PlaybackSpeed.SLOW -> PlaybackSpeed.NORMAL PlaybackSpeed.NORMAL -> PlaybackSpeed.FAST PlaybackSpeed.FAST -> PlaybackSpeed.FASTEST PlaybackSpeed.FASTEST -> PlaybackSpeed.SLOW } audioPlayer.setPlaybackSpeed(nextSpeed.speed) this.playbackSpeed.value = nextSpeed resetPlaybackProgressInterval() } override fun setQueue(audios: List<AudioFile>, index: Int) { val audiosIds = audios.map { it.id } val initialId = audios.getOrNull(index)?.id ?: "" val playbackQueue = PlaybackQueue( list = audiosIds, audiosList = audios, initialMediaId = initialId, currentIndex = index ) this.playbackQueueState.value = playbackQueue } private fun startPlaybackProgress() = launch { combine(playbackState, nowPlaying, ::Pair).collect { (state, current) -> playbackProgressInterval.cancel() val duration = current.duration val position = state.position if (state == NONE_PLAYBACK_STATE || current == NONE_PLAYING || duration < 1) { return@collect } val initial = PlaybackProgressState(duration, position, buffered = audioPlayer.bufferedPosition()) playbackProgress.value = initial if (state.isPlaying && !state.isBuffering) { startPlaybackProgressInterval(initial) } } } private fun startPlaybackProgressInterval(initial: PlaybackProgressState) { playbackProgressInterval = launch { flowInterval(currentProgressInterval).collect { val current = playbackProgress.value.elapsed val elapsed = current + PLAYBACK_PROGRESS_INTERVAL playbackProgress.value = initial.copy(elapsed = elapsed, buffered = audioPlayer.bufferedPosition()) } } } private fun resetPlaybackProgressInterval() { val speed = playbackSpeed.value.speed currentProgressInterval = (PLAYBACK_PROGRESS_INTERVAL.toDouble() / speed).toLong() playbackProgressInterval.cancel() startPlaybackProgressInterval(playbackProgress.value) } private inner class MediaBrowserConnectionCallback(private val context: Context) : MediaBrowserCompat.ConnectionCallback() { override fun onConnected() { mediaController = MediaControllerCompat(context, mediaBrowser.sessionToken).apply { registerCallback(MediaControllerCallback()) } isConnected.value = true } override fun onConnectionSuspended() { isConnected.value = false } override fun onConnectionFailed() { isConnected.value = false } } private inner class MediaControllerCallback : MediaControllerCompat.Callback() { override fun onPlaybackStateChanged(state: PlaybackStateCompat?) { playbackState.value = state ?: return } override fun onMetadataChanged(metadata: MediaMetadataCompat?) { nowPlaying.value = metadata ?: return } override fun onRepeatModeChanged(repeatMode: Int) { playbackMode.value = playbackMode.value.copy(repeatMode = repeatMode) } override fun onShuffleModeChanged(shuffleMode: Int) { playbackMode.value = playbackMode.value.copy(shuffleMode = shuffleMode) } override fun onSessionDestroyed() { mediaBrowserConnectionCallback.onConnectionSuspended() } } }
mit
4f81febd013347fe0ae562e154c788ab
37.935622
115
0.720348
5.213793
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertUnsafeCastToUnsafeCastCallIntention.kt
2
1966
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.TypeUtils class ConvertUnsafeCastToUnsafeCastCallIntention : SelfTargetingIntention<KtBinaryExpressionWithTypeRHS>( KtBinaryExpressionWithTypeRHS::class.java, KotlinBundle.lazyMessage("convert.to.unsafecast.call"), ) { override fun isApplicableTo(element: KtBinaryExpressionWithTypeRHS, caretOffset: Int): Boolean { if (!element.platform.isJs()) return false if (element.operationReference.getReferencedNameElementType() != KtTokens.AS_KEYWORD) return false val right = element.right ?: return false val context = right.analyze(BodyResolveMode.PARTIAL) val type = context[BindingContext.TYPE, right] ?: return false if (TypeUtils.isNullableType(type)) return false setTextGetter(KotlinBundle.lazyMessage("convert.to.0.unsafecast.1", element.left.text, right.text)) return true } override fun applyTo(element: KtBinaryExpressionWithTypeRHS, editor: Editor?) { val right = element.right ?: return val newExpression = KtPsiFactory(element).createExpressionByPattern("$0.unsafeCast<$1>()", element.left, right) element.replace(newExpression) } }
apache-2.0
e5210fef715c271b6d23f45b50d57062
45.833333
158
0.780264
4.692124
false
false
false
false
abigpotostew/easypolitics
ui/src/main/kotlin/bz/stew/bracken/ui/common/bill/status/BillStatusData.kt
1
1657
package bz.stew.bracken.ui.common.bill.status import bz.stew.bracken.ui.extension.html.emptyDate import bz.stew.bracken.ui.common.bill.MajorAction import bz.stew.bracken.ui.common.bill.emptyMajorAction import bz.stewart.bracken.shared.data.FixedStatus import bz.stewart.bracken.shared.data.MajorStatus import kotlin.js.Date /** * Created by stew on 3/4/17. */ class BillStatusData(private val fixedStatus: FixedStatus = FixedStatus.NONE, private val date: Date = emptyDate(), private val description: String = "", private val label: String = "", private val majorActions: Collection<MajorAction> = emptyList()) : BillStatus { private val lastMajorActionCached: MajorAction = this.majorActions.maxBy { val dt = it.date() dt.getTime() } ?: emptyMajorAction() override fun lastMajorAction(): MajorAction { return this.lastMajorActionCached } override fun lastMajorStatus(): MajorStatus { return this.fixedStatus.lastMajorCompletedStatus } override fun fixedStatus(): FixedStatus { return this.fixedStatus } override fun date(): Date { return this.date } override fun description(): String { return this.description } override fun label(): String { return this.label } override fun majorActions(): Collection<MajorAction> { return this.majorActions } } private val emptyBillStatusData: BillStatus = BillStatusData( majorActions = listOf(emptyMajorAction())) fun emptyBillStatus(): BillStatus { return emptyBillStatusData }
apache-2.0
b1b310e2c893cd0604bb8c6ff55ba3d4
26.163934
100
0.678334
4.418667
false
false
false
false
k9mail/k-9
app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo5.kt
2
1321
package com.fsck.k9.preferences.migrations import android.database.sqlite.SQLiteDatabase /** * Rewrite frequencies lower than LOWEST_FREQUENCY_SUPPORTED */ class StorageMigrationTo5( private val db: SQLiteDatabase, private val migrationsHelper: StorageMigrationsHelper ) { fun fixMailCheckFrequencies() { val accountUuidsListValue = migrationsHelper.readValue(db, "accountUuids") if (accountUuidsListValue == null || accountUuidsListValue.isEmpty()) { return } val accountUuids = accountUuidsListValue.split(",") for (accountUuid in accountUuids) { fixFrequencyForAccount(accountUuid) } } private fun fixFrequencyForAccount(accountUuid: String) { val key = "$accountUuid.automaticCheckIntervalMinutes" val frequencyValue = migrationsHelper.readValue(db, key)?.toIntOrNull() if (frequencyValue != null && frequencyValue > -1 && frequencyValue < LOWEST_FREQUENCY_SUPPORTED) { migrationsHelper.writeValue(db, key, LOWEST_FREQUENCY_SUPPORTED.toString()) } } companion object { // see: https://github.com/evernote/android-job/wiki/FAQ#why-cant-an-interval-be-smaller-than-15-minutes-for-periodic-jobs private const val LOWEST_FREQUENCY_SUPPORTED = 15 } }
apache-2.0
0343d6a0c0fb2ed045708f35e2435534
35.694444
130
0.697199
4.821168
false
false
false
false
JohnnyShieh/Gank
app/src/main/kotlin/com/johnny/gank/model/ui/GankItem.kt
1
1840
package com.johnny.gank.model.ui import com.johnny.gank.model.entity.Gank import java.util.* /* * Copyright (C) 2015 Johnny Shieh 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. */ /** * Unified data model for all sorts of gank items * @author Johnny Shieh * * * @version 1.0 */ interface GankItem data class GankHeaderItem(var name: String = "") : GankItem data class GankNormalItem( var page: Int = -1, var gank: Gank = Gank() ) : GankItem { companion object { fun newGankList(gankList: List<Gank>?): List<GankNormalItem> { if (null == gankList || gankList.isEmpty()) { return arrayListOf() } return gankList.map { GankNormalItem(gank = it) } } fun newGankList(gankList: List<Gank>?, pageIndex: Int): List<GankNormalItem> { if (null == gankList || gankList.isEmpty()) { return arrayListOf() } return gankList.map { GankNormalItem(page = pageIndex, gank = it) } } } } data class GankGirlImageItem( var imgUrl: String = "", var publishedAt: Date = Date() ) : GankItem { companion object { fun newImageItem(gank: Gank): GankGirlImageItem { return GankGirlImageItem(gank.url, gank.publishedAt) } } }
apache-2.0
41f63327a5523532e99a692a9bfc50dc
28.206349
86
0.645652
4.097996
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/optimizer/ParamsOptimizer.kt
1
2518
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.optimizer import com.kotlinnlp.simplednn.core.functionalities.gradientclipping.GradientClipping import com.kotlinnlp.simplednn.core.functionalities.updatemethods.UpdateMethod import com.kotlinnlp.simplednn.utils.scheduling.BatchScheduling import com.kotlinnlp.simplednn.utils.scheduling.EpochScheduling import com.kotlinnlp.simplednn.utils.scheduling.ExampleScheduling /** * The optimizer of neural parameters. * * @param updateMethod the update method helper (Learning Rate, ADAM, AdaGrad, ...) * @param gradientClipping the gradient clipper (default null) */ class ParamsOptimizer( private val updateMethod: UpdateMethod<*>, private val gradientClipping: GradientClipping? = null ) : ParamsErrorsAccumulator(), ScheduledUpdater { /** * Calculate the errors average, update the parameters. */ override fun update() { if (this.isNotEmpty) { this.clipGradients() this.updateParams() this.clear() } } /** * Method to call every new epoch. * In turn it calls the same method into the `updateMethod` */ override fun newEpoch() { if (this.updateMethod is EpochScheduling) { this.updateMethod.newEpoch() } } /** * Method to call every new batch. * In turn it calls the same method into the `updateMethod` */ override fun newBatch() { if (this.updateMethod is BatchScheduling) { this.updateMethod.newBatch() } } /** * Method to call every new example. * In turn it calls the same method into the `updateMethod` */ override fun newExample() { if (this.updateMethod is ExampleScheduling) { this.updateMethod.newExample() } } /** * Update the parameters in respect of the errors using the update method helper (Learning Rate, ADAM, AdaGrad, ...). */ private fun updateParams() { this.getParamsErrors(copy = false).forEach { errors -> this.updateMethod.update(array = errors.refParams, errors = errors.values) } } /** * Perform the gradient clipping. */ private fun clipGradients() { this.gradientClipping?.clip(this.getParamsErrors(copy = false)) } }
mpl-2.0
2e4eef9693b9cd79162c0bfe58138c7a
26.67033
119
0.685862
4.356401
false
false
false
false
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/codeVision/CodeVisionProviderBase.kt
2
3614
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.hints.codeVision import com.intellij.codeInsight.codeVision.* import com.intellij.codeInsight.codeVision.ui.model.ClickableTextCodeVisionEntry import com.intellij.codeInsight.hints.InlayHintsUtils import com.intellij.codeInsight.hints.settings.language.isInlaySettingsEditor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.SmartPointerManager import com.intellij.psi.SyntaxTraverser import java.awt.event.MouseEvent abstract class CodeVisionProviderBase : DaemonBoundCodeVisionProvider { /** * WARNING! This method is executed also before the file is open. It must be fast! During it users see no editor. * @return true iff this provider may provide lenses for this file. */ abstract fun acceptsFile(file: PsiFile): Boolean /** * WARNING! This method is executed also before the file is open. It must be fast! During it users see no editor. * @return true iff this provider may provide lenses for this element. */ abstract fun acceptsElement(element: PsiElement): Boolean /** * @return text that user sees for a given element as a code lens */ abstract fun getHint(element: PsiElement, file: PsiFile): String? open fun logClickToFUS(element: PsiElement) {} override fun computeForEditor(editor: Editor, file: PsiFile): List<Pair<TextRange, CodeVisionEntry>> { if (!acceptsFile(file)) return emptyList() // we want to let this provider work only in tests dedicated for code vision, otherwise they harm performance if (ApplicationManager.getApplication().isUnitTestMode && !CodeVisionHost.isCodeLensTest(editor)) return emptyList() val lenses = ArrayList<Pair<TextRange, CodeVisionEntry>>() val traverser = SyntaxTraverser.psiTraverser(file) for (element in traverser) { if (!acceptsElement(element)) continue if (!InlayHintsUtils.isFirstInLine(element)) continue val hint = getHint(element, file) if (hint == null) continue val handler = ClickHandler(element) val range = InlayHintsUtils.getTextRangeWithoutLeadingCommentsAndWhitespaces(element) lenses.add(range to ClickableTextCodeVisionEntry(hint, id, handler)) } return lenses } private inner class ClickHandler( element: PsiElement ) : (MouseEvent?, Editor) -> Unit { private val elementPointer = SmartPointerManager.createPointer(element) override fun invoke(event: MouseEvent?, editor: Editor) { if (isInlaySettingsEditor(editor)) return val element = elementPointer.element ?: return logClickToFUS(element) handleClick(editor, element, event) } } abstract fun handleClick(editor: Editor, element: PsiElement, event: MouseEvent?) override fun getPlaceholderCollector(editor: Editor, psiFile: PsiFile?): CodeVisionPlaceholderCollector? { if (psiFile == null || !acceptsFile(psiFile)) return null return object: BypassBasedPlaceholderCollector { override fun collectPlaceholders(element: PsiElement, editor: Editor): List<TextRange> { if (!acceptsElement(element)) return emptyList() val range = InlayHintsUtils.getTextRangeWithoutLeadingCommentsAndWhitespaces(element) return listOf(range) } } } override val defaultAnchor: CodeVisionAnchorKind get() = CodeVisionAnchorKind.Default }
apache-2.0
c3bde58e88c5c209338c076f1f33a3cb
41.529412
120
0.757609
4.718016
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/base/fir/analysis-api-providers/src/org/jetbrains/kotlin/idea/base/fir/analysisApiProviders/FirIdeModificationTrackerService.kt
2
7287
// 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.base.fir.analysisApiProviders import com.intellij.lang.ASTNode import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.Disposable import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.pom.PomManager import com.intellij.pom.PomModelAspect import com.intellij.pom.event.PomModelEvent import com.intellij.pom.event.PomModelListener import com.intellij.pom.tree.TreeAspect import com.intellij.pom.tree.events.TreeChangeEvent import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.FileElement import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.analysis.low.level.api.fir.element.builder.getNonLocalContainingInBodyDeclarationWith import org.jetbrains.kotlin.analysis.low.level.api.fir.file.structure.isReanalyzableContainer import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.base.util.module import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicLong internal class FirIdeModificationTrackerService(project: Project) : Disposable { init { PomManager.getModel(project).addModelListener(Listener()) } private val _projectGlobalOutOfBlockInKotlinFilesModificationCount = AtomicLong() val projectGlobalOutOfBlockInKotlinFilesModificationCount: Long get() = _projectGlobalOutOfBlockInKotlinFilesModificationCount.get() fun getOutOfBlockModificationCountForModules(module: Module): Long = moduleModificationsState.getModificationsCountForModule(module) private val moduleModificationsState = ModuleModificationsState() private val treeAspect = TreeAspect.getInstance(project) override fun dispose() {} fun increaseModificationCountForAllModules() { _projectGlobalOutOfBlockInKotlinFilesModificationCount.incrementAndGet() moduleModificationsState.increaseModificationCountForAllModules() } @TestOnly fun increaseModificationCountForModule(module: Module) { moduleModificationsState.increaseModificationCountForModule(module) } private inner class Listener : PomModelListener { override fun isAspectChangeInteresting(aspect: PomModelAspect): Boolean = treeAspect == aspect override fun modelChanged(event: PomModelEvent) { val changeSet = event.getChangeSet(treeAspect) as TreeChangeEvent? ?: return val psi = changeSet.rootElement.psi val changedElements = changeSet.changedElements handleChangedElementsInAllModules(changedElements, changeSet, psi) } private fun handleChangedElementsInAllModules( changedElements: Array<out ASTNode>, changeSet: TreeChangeEvent, changeSetRootElementPsi: PsiElement ) { if (!changeSetRootElementPsi.isPhysical) { /** * Element which do not belong to a project should not cause OOBM */ return } if (changedElements.isEmpty()) { incrementModificationCountForFileChange(changeSet) } else { incrementModificationCountForSpecificElements(changedElements, changeSet, changeSetRootElementPsi) } } private fun incrementModificationCountForSpecificElements( changedElements: Array<out ASTNode>, changeSet: TreeChangeEvent, changeSetRootElementPsi: PsiElement ) { require(changedElements.isNotEmpty()) var isOutOfBlockChangeInAnyModule = false changedElements.forEach { element -> val isOutOfBlock = element.isOutOfBlockChange(changeSet, changeSetRootElementPsi) isOutOfBlockChangeInAnyModule = isOutOfBlockChangeInAnyModule || isOutOfBlock if (isOutOfBlock) { incrementModificationTrackerForContainingModule(element) } } if (isOutOfBlockChangeInAnyModule) { _projectGlobalOutOfBlockInKotlinFilesModificationCount.incrementAndGet() } } private fun incrementModificationCountForFileChange(changeSet: TreeChangeEvent) { val fileElement = changeSet.rootElement as FileElement ?: return incrementModificationTrackerForContainingModule(fileElement) _projectGlobalOutOfBlockInKotlinFilesModificationCount.incrementAndGet() } private fun incrementModificationTrackerForContainingModule(element: ASTNode) { element.psi.module?.let { module -> moduleModificationsState.increaseModificationCountForModule(module) } } private fun ASTNode.isOutOfBlockChange(changeSet: TreeChangeEvent, changeSetRootElementPsi: PsiElement): Boolean { return when (changeSetRootElementPsi.language) { KotlinLanguage.INSTANCE -> { val nodes = changeSet.getChangesByElement(this).affectedChildren nodes.any(::isOutOfBlockChange) } JavaLanguage.INSTANCE -> { true // TODO improve for Java KTIJ-21684 } else -> { // Any other language may cause OOBM in Kotlin too true } } } private fun isOutOfBlockChange(node: ASTNode): Boolean { val psi = node.psi ?: return true if (!psi.isValid) { /** * If PSI is not valid, well something bad happened, OOBM won't hurt */ return true } val container = psi.getNonLocalContainingInBodyDeclarationWith() ?: return true return !isReanalyzableContainer(container) } } } private class ModuleModificationsState { private val modificationCountForModule = ConcurrentHashMap<Module, ModuleModifications>() private val state = AtomicLong() fun getModificationsCountForModule(module: Module) = modificationCountForModule.compute(module) { _, modifications -> val currentState = state.get() when { modifications == null -> ModuleModifications(0, currentState) modifications.state == currentState -> modifications else -> ModuleModifications(modificationsCount = modifications.modificationsCount + 1, state = currentState) } }!!.modificationsCount fun increaseModificationCountForAllModules() { state.incrementAndGet() } fun increaseModificationCountForModule(module: Module) { modificationCountForModule.compute(module) { _, modifications -> val currentState = state.get() when (modifications) { null -> ModuleModifications(0, currentState) else -> ModuleModifications(modifications.modificationsCount + 1, currentState) } } } private data class ModuleModifications(val modificationsCount: Long, val state: Long) }
apache-2.0
542f6dd6c0c5e59c958ee76cdd8e29a0
40.645714
122
0.684507
5.914773
false
false
false
false
hsson/card-balance-app
app/src/main/java/se/creotec/chscardbalance2/controller/AppBarStateChangeListener.kt
1
1264
// Copyright (c) 2017 Alexander Håkansson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT package se.creotec.chscardbalance2.controller import android.support.design.widget.AppBarLayout abstract class AppBarStateChangeListener : AppBarLayout.OnOffsetChangedListener { enum class State { EXPANDED, COLLAPSED, IDLE } private var currentState = State.IDLE override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) { appBarLayout?.let { if (verticalOffset == 0) { if (currentState != State.EXPANDED) { onStateChanged(it, State.EXPANDED) } currentState = State.EXPANDED; } else if (Math.abs(verticalOffset) >= it.totalScrollRange) { if (currentState != State.COLLAPSED) { onStateChanged(it, State.COLLAPSED) } currentState = State.COLLAPSED } else { if (currentState != State.IDLE) { onStateChanged(it, State.IDLE) } } } } abstract fun onStateChanged(appBarLayout: AppBarLayout, state: State) }
mit
b941a6c4c8e764ac5b991611f339f515
29.829268
84
0.589865
5.329114
false
false
false
false
android/nowinandroid
core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/model/Topic.kt
1
1026
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.data.model import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic fun NetworkTopic.asEntity() = TopicEntity( id = id, name = name, shortDescription = shortDescription, longDescription = longDescription, url = url, imageUrl = imageUrl )
apache-2.0
598a1f75dc92dcc30d98d34f627af149
34.37931
75
0.751462
4.170732
false
false
false
false
InsideZhou/Instep
dao/src/test/kotlin/instep/dao/sql/InstepSQLTest.kt
1
5174
@file:Suppress("MemberVisibilityCanBePrivate") package instep.dao.sql import com.alibaba.druid.pool.DruidDataSource import instep.Instep import instep.InstepLogger import instep.InstepLoggerFactory import instep.dao.sql.dialect.HSQLDialect import instep.dao.sql.dialect.MySQLDialect import instep.dao.sql.dialect.SQLServerDialect import instep.dao.sql.impl.DefaultConnectionProvider import net.moznion.random.string.RandomStringGenerator import org.testng.Assert import org.testng.annotations.AfterClass import org.testng.annotations.BeforeClass import org.testng.annotations.Test import java.time.LocalDateTime import java.time.format.DateTimeFormatter object InstepSQLTest { val stringGenerator = RandomStringGenerator() val datasourceUrl: String = System.getenv("instep.test.jdbc_url") val dialect = Dialect.of(datasourceUrl) val datasource = DruidDataSource() object TransactionTable : Table("transaction_" + stringGenerator.generateByRegex("[a-z]{8}"), "transaction test", dialect) { val id = autoIncrementLong("id").primary() val name = varchar("name", 256).notnull() } init { datasource.url = datasourceUrl datasource.initialSize = 1 datasource.minIdle = 1 datasource.maxActive = 2 datasource.timeBetweenEvictionRunsMillis = 60000 datasource.minEvictableIdleTimeMillis = 300000 datasource.isTestWhileIdle = true datasource.maxPoolPreparedStatementPerConnectionSize = 16 Instep.bind(ConnectionProvider::class.java, DefaultConnectionProvider(datasource, dialect)) val factory = object : InstepLoggerFactory { override fun getLogger(cls: Class<*>): InstepLogger { return object : InstepLogger { var msg = "" var context = mutableMapOf<String, Any>() var t: Throwable? = null override fun message(message: String): InstepLogger { msg = message return this } override fun exception(e: Throwable): InstepLogger { t = e return this } override fun context(key: String, value: Any): InstepLogger { context[key] = value return this } override fun context(key: String, lazy: () -> String): InstepLogger { context[key] = lazy.invoke() return this } override fun trace() { println(msg) println(context) } override fun debug() { println(msg) println(context) } override fun info() { println(msg) println(context) } override fun warn() { System.err.println(msg) System.err.println(context) } override fun error() { System.err.println(msg) System.err.println(context) } } } } Instep.bind(InstepLoggerFactory::class.java, factory) InstepLogger.factory = factory } @BeforeClass fun init() { TransactionTable.create().debug().execute() } @AfterClass fun cleanUp() { TransactionTable.drop().execute() } @Test fun executeScalar() { val scalar = when (dialect) { is HSQLDialect -> InstepSQL.plan("""VALUES(to_char(current_timestamp, 'YYYY-MM-DD HH24\:MI\:SS'))""").executeString() is MySQLDialect -> InstepSQL.plan("""SELECT date_format(current_timestamp, '%Y-%m-%d %k\:%i\:%S')""").executeString() is SQLServerDialect -> InstepSQL.plan("""SELECT format(current_timestamp, 'yyyy-MM-dd HH:mm:ss')""").executeString() else -> InstepSQL.plan("""SELECT to_char(current_timestamp, 'YYYY-MM-DD HH24:MI:SS')""").executeString() } LocalDateTime.parse(scalar, DateTimeFormatter.ofPattern("""yyyy-MM-dd HH:mm:ss""")) Assert.assertEquals(InstepSQL.plan("""SELECT NULL""").executeLong(), 0) } @Test fun transaction() { InstepSQL.transaction().committed { val row = TableRow() row[TransactionTable.name] = stringGenerator.generateByRegex("\\w{8,64}") TransactionTable[1] = row } assert(TransactionTable[1] != null) InstepSQL.transaction().serializable { val row = TableRow() row[TransactionTable.name] = stringGenerator.generateByRegex("\\w{8,64}") TransactionTable[2] = row abort() } assert(TransactionTable[2] == null) Assert.assertEquals(TransactionTable.selectExpression(TransactionTable.id.count()).distinct().executeLong(), 1) } }
bsd-2-clause
bd1056f26a84e405a8e916e9fba11a2b
35.188811
129
0.568999
5.122772
false
true
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/visitors/CreateAuxiliaryFilesVisitor.kt
12
7386
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.visitors import com.intellij.diagnostic.hprof.classstore.ClassDefinition import com.intellij.diagnostic.hprof.classstore.ClassStore import com.intellij.diagnostic.hprof.parser.* import com.intellij.diagnostic.hprof.util.FileChannelBackedWriteBuffer import com.intellij.openapi.diagnostic.Logger import java.nio.ByteBuffer import java.nio.channels.FileChannel internal class CreateAuxiliaryFilesVisitor( private val auxOffsetsChannel: FileChannel, private val auxChannel: FileChannel, private val classStore: ClassStore, private val parser: HProfEventBasedParser ) : HProfVisitor() { private lateinit var offsets: FileChannelBackedWriteBuffer private lateinit var aux: FileChannelBackedWriteBuffer private var directByteBufferClass: ClassDefinition? = null private var directByteBufferCapacityOffset: Int = 0 private var directByteBufferFdOffset: Int = 0 private var stringClass: ClassDefinition? = null private var stringCoderOffset: Int = -1 companion object { private val LOG = Logger.getInstance(CreateAuxiliaryFilesVisitor::class.java) } override fun preVisit() { disableAll() enable(HeapDumpRecordType.ClassDump) enable(HeapDumpRecordType.InstanceDump) enable(HeapDumpRecordType.ObjectArrayDump) enable(HeapDumpRecordType.PrimitiveArrayDump) offsets = FileChannelBackedWriteBuffer(auxOffsetsChannel) aux = FileChannelBackedWriteBuffer(auxChannel) directByteBufferClass = null val dbbClass = classStore.getClassIfExists("java.nio.DirectByteBuffer") if (dbbClass != null) { directByteBufferClass = dbbClass directByteBufferCapacityOffset = dbbClass.computeOffsetOfField("capacity", classStore) directByteBufferFdOffset = dbbClass.computeOffsetOfField("fd", classStore) if (directByteBufferCapacityOffset == -1 || directByteBufferFdOffset == -1) { LOG.error("DirectByteBuffer.capacity and/or .fd field is missing.") } } stringClass = classStore.getClassIfExists("java.lang.String") stringClass?.let { stringCoderOffset = it.computeOffsetOfField("coder", classStore) } // Map id=0 to 0 offsets.writeInt(0) } override fun postVisit() { aux.close() offsets.close() } override fun visitPrimitiveArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, numberOfElements: Long, elementType: Type, primitiveArrayData: ByteBuffer) { assert(arrayObjectId <= Int.MAX_VALUE) assert(offsets.position() / 4 == arrayObjectId.toInt()) offsets.writeInt(aux.position()) aux.writeId(classStore.getClassForPrimitiveArray(elementType)!!.id.toInt()) assert(numberOfElements <= Int.MAX_VALUE) // arrays in java don't support more than Int.MAX_VALUE elements aux.writeNonNegativeLEB128Int(numberOfElements.toInt()) primitiveArrayData.mark() aux.writeBytes(primitiveArrayData) primitiveArrayData.reset() } override fun visitClassDump(classId: Long, stackTraceSerialNumber: Long, superClassId: Long, classloaderClassId: Long, instanceSize: Long, constants: Array<ConstantPoolEntry>, staticFields: Array<StaticFieldEntry>, instanceFields: Array<InstanceFieldEntry>) { assert(classId <= Int.MAX_VALUE) assert(offsets.position() / 4 == classId.toInt()) offsets.writeInt(aux.position()) aux.writeId(0) // Special value for class definitions, to differentiate from regular java.lang.Class instances } override fun visitObjectArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, arrayClassObjectId: Long, objects: LongArray) { assert(arrayObjectId <= Int.MAX_VALUE) assert(arrayClassObjectId <= Int.MAX_VALUE) assert(offsets.position() / 4 == arrayObjectId.toInt()) offsets.writeInt(aux.position()) aux.writeId(arrayClassObjectId.toInt()) val nonNullElementsCount = objects.count { it != 0L } val nullElementsCount = objects.count() - nonNullElementsCount // To minimize serialized size, store (nullElementsCount, nonNullElementsCount) pair instead of // (objects.count, nonNullElementsCount) pair. aux.writeNonNegativeLEB128Int(nullElementsCount) aux.writeNonNegativeLEB128Int(nonNullElementsCount) objects.forEach { if (it == 0L) return@forEach assert(it <= Int.MAX_VALUE) aux.writeId(it.toInt()) } } override fun visitInstanceDump(objectId: Long, stackTraceSerialNumber: Long, classObjectId: Long, bytes: ByteBuffer) { assert(objectId <= Int.MAX_VALUE) assert(classObjectId <= Int.MAX_VALUE) assert(offsets.position() / 4 == objectId.toInt()) offsets.writeInt(aux.position()) aux.writeId(classObjectId.toInt()) var classOffset = 0 val objectClass = classStore[classObjectId] run { var classDef: ClassDefinition = objectClass do { classDef.refInstanceFields.forEach { val offset = classOffset + it.offset val value = bytes.getLong(offset) if (value == 0L) { aux.writeId(0) } else { // bytes are just raw data. IDs have to be mapped manually. val reference = parser.remap(value) assert(reference != 0L) aux.writeId(reference.toInt()) } } classOffset += classDef.superClassOffset if (classDef.superClassId == 0L) { break } classDef = classStore[classDef.superClassId] } while (true) } // DirectByteBuffer class contains additional field with buffer capacity. if (objectClass == directByteBufferClass) { if (directByteBufferCapacityOffset == -1 || directByteBufferFdOffset == -1) { aux.writeNonNegativeLEB128Int(1) } else { val directByteBufferCapacity = bytes.getInt(directByteBufferCapacityOffset) val directByteBufferFd = bytes.getLong(directByteBufferFdOffset) if (directByteBufferFd == 0L) { // When fd == 0, the buffer is directly allocated in memory. aux.writeNonNegativeLEB128Int(directByteBufferCapacity) } else { // File-mapped buffer aux.writeNonNegativeLEB128Int(1) } } } else if (objectClass == stringClass) { if (stringCoderOffset == -1) { aux.writeByte(-1) } else { aux.writeByte(bytes.get(stringCoderOffset)) } } } private fun FileChannelBackedWriteBuffer.writeId(id: Int) { // Use variable-length Int for IDs to save space this.writeNonNegativeLEB128Int(id) } }
apache-2.0
fda7fed080c627f6d02f0677d1af4f4f
34.339713
166
0.69361
4.713465
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/ModalityConversion.kt
2
2873
// 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 com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.psi import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.tree.JKClass.ClassKind.* import org.jetbrains.kotlin.nj2k.tree.Modality.* import org.jetbrains.kotlin.nj2k.tree.Visibility.PRIVATE class ModalityConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { when (element) { is JKClass -> element.process() is JKMethod -> element.process() is JKField -> element.process() } return recurse(element) } private fun JKClass.process() { modality = when { classKind == ENUM || classKind == RECORD -> FINAL classKind == INTERFACE -> OPEN modality == OPEN && context.converter.settings.openByDefault -> OPEN modality == OPEN && !hasInheritors(psi as PsiClass) -> FINAL else -> modality } } private fun hasInheritors(psiClass: PsiClass): Boolean = context.converter.converterServices.oldServices.referenceSearcher.hasInheritors(psiClass) private fun JKMethod.process() { val psiMethod = psi<PsiMethod>() ?: return val containingClass = parentOfType<JKClass>() ?: return when { visibility == PRIVATE -> modality = FINAL modality != ABSTRACT && psiMethod.findSuperMethods().isNotEmpty() -> { modality = FINAL if (!hasOtherModifier(OtherModifier.OVERRIDE)) { otherModifierElements += JKOtherModifierElement(OtherModifier.OVERRIDE) } } modality == OPEN && context.converter.settings.openByDefault && containingClass.modality == OPEN && visibility != PRIVATE -> { modality = OPEN } modality == OPEN && containingClass.classKind != INTERFACE && !hasOverrides(psiMethod) -> { modality = FINAL } else -> modality = modality } } private fun hasOverrides(psiMethod: PsiMethod): Boolean = context.converter.converterServices.oldServices.referenceSearcher.hasOverrides(psiMethod) private fun JKField.process() { val containingClass = parentOfType<JKClass>() ?: return if (containingClass.classKind == INTERFACE) modality = FINAL } }
apache-2.0
61cc58a1489d7025c1e32c4944b16975
37.32
120
0.635573
5.195298
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurableUI.kt
2
2404
// 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.vfs.encoding import com.intellij.ide.IdeBundle import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.vfs.encoding.EncodingProjectManagerImpl.BOMForNewUTF8Files import com.intellij.ui.EnumComboBoxModel import com.intellij.ui.components.JBCheckBox import com.intellij.ui.dsl.builder.* import java.awt.event.ItemListener import javax.swing.JComponent class FileEncodingConfigurableUI { lateinit var transparentNativeToAsciiCheckBox: JBCheckBox lateinit var bomForUTF8Combo: ComboBox<BOMForNewUTF8Files> private lateinit var bomForUTF8ComboCell: Cell<ComboBox<BOMForNewUTF8Files>> fun createContent(tablePanel: JComponent, filesEncodingCombo: JComponent): DialogPanel { return panel { row { cell(tablePanel).align(Align.FILL) }.resizableRow() .bottomGap(BottomGap.SMALL) row(IdeBundle.message("editbox.default.encoding.for.properties.files")) { cell(filesEncodingCombo) } indent { row { transparentNativeToAsciiCheckBox = checkBox(IdeBundle.message("checkbox.transparent.native.to.ascii.conversion")).component }.bottomGap(BottomGap.SMALL) } row(IdeBundle.message("file.encoding.option.create.utf8.files")) { bomForUTF8ComboCell = comboBox(EnumComboBoxModel(BOMForNewUTF8Files::class.java)).applyToComponent { addItemListener(ItemListener { updateExplanationLabelText() }) }.comment("") bomForUTF8Combo = bomForUTF8ComboCell.component }.layout(RowLayout.INDEPENDENT) } } private fun updateExplanationLabelText() { val item = bomForUTF8ComboCell.component.selectedItem as BOMForNewUTF8Files val productName = ApplicationNamesInfo.getInstance().productName val comment = when (item) { BOMForNewUTF8Files.ALWAYS -> IdeBundle.message("file.encoding.option.warning.always", productName) BOMForNewUTF8Files.NEVER -> IdeBundle.message("file.encoding.option.warning.never", productName) BOMForNewUTF8Files.WINDOWS_ONLY -> IdeBundle.message("file.encoding.option.warning.windows.only", productName) } bomForUTF8ComboCell.comment?.text = comment } }
apache-2.0
827b3b1e083994d89bab66451913f156
40.465517
133
0.762895
4.605364
false
false
false
false
GunoH/intellij-community
platform/analysis-impl/src/com/intellij/codeInsight/completion/OffsetsInFile.kt
2
2857
// 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.codeInsight.completion import com.intellij.injected.editor.VirtualFileWindow import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.pom.PomManager import com.intellij.pom.core.impl.PomModelImpl import com.intellij.psi.PsiFile import com.intellij.psi.impl.source.tree.FileElement import java.util.function.Supplier class OffsetsInFile(val file: PsiFile, val offsets: OffsetMap) { constructor(file: PsiFile) : this(file, OffsetMap(file.viewProvider.document!!)) fun toTopLevelFile(): OffsetsInFile { val manager = InjectedLanguageManager.getInstance(file.project) val hostFile = manager.getTopLevelFile(file) if (hostFile == file) return this return OffsetsInFile(hostFile, offsets.mapOffsets(hostFile.viewProvider.document!!) { manager.injectedToHost(file, it) }) } fun toInjectedIfAny(offset: Int): OffsetsInFile { val manager = InjectedLanguageManager.getInstance(file.project) val injected = manager.findInjectedElementAt(file, offset)?.containingFile ?: return this val virtualFile = injected.virtualFile if (virtualFile is VirtualFileWindow) { val documentWindow = virtualFile.documentWindow return OffsetsInFile(injected, offsets.mapOffsets( documentWindow) { documentWindow.hostToInjected(it) }) } else { return this } } fun copyWithReplacement(startOffset: Int, endOffset: Int, replacement: String): OffsetsInFile { return replaceInCopy(file.copy() as PsiFile, startOffset, endOffset, replacement).get() } fun replaceInCopy(fileCopy: PsiFile, startOffset: Int, endOffset: Int, replacement: String): Supplier<OffsetsInFile> { val originalText = offsets.document.immutableCharSequence val tempDocument = DocumentImpl(originalText, originalText.contains('\r') || replacement.contains('\r'), true) val tempMap = offsets.copyOffsets(tempDocument) tempDocument.replaceString(startOffset, endOffset, replacement) val copyDocument = fileCopy.viewProvider.document!! val node = fileCopy.node as? FileElement ?: throw IllegalStateException("Node is not a FileElement ${fileCopy.javaClass.name} / ${fileCopy.fileType} / ${fileCopy.node}") val applyPsiChange = (PomManager.getModel(file.project) as PomModelImpl).reparseFile(fileCopy, node, tempDocument.immutableCharSequence) return Supplier { applyPsiChange?.run() OffsetsInFile(fileCopy, tempMap.copyOffsets(copyDocument)) } } }
apache-2.0
d6cf30d7cb457bc9e4ab953a61c57770
47.423729
143
0.715786
4.908935
false
false
false
false
GunoH/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/ReplOutputHandler.kt
2
5595
// 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.console import com.intellij.execution.process.OSProcessHandler import com.intellij.execution.process.ProcessOutputTypes import com.intellij.openapi.util.Key import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.KotlinIdeaReplBundle import org.jetbrains.kotlin.cli.common.repl.replNormalizeLineBreaks import org.jetbrains.kotlin.cli.common.repl.replUnescapeLineBreaks import org.jetbrains.kotlin.console.actions.logError import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.utils.repl.ReplEscapeType import org.jetbrains.kotlin.utils.repl.ReplEscapeType.* import org.w3c.dom.Element import org.xml.sax.InputSource import java.io.ByteArrayInputStream import java.nio.charset.Charset import javax.xml.parsers.DocumentBuilderFactory data class SeverityDetails(val severity: Severity, val description: String, val range: TextRange) class ReplOutputHandler( private val runner: KotlinConsoleRunner, process: Process, commandLine: String ) : OSProcessHandler(process, commandLine) { private var isBuildInfoChecked = false private val factory = DocumentBuilderFactory.newInstance() private val outputProcessor = ReplOutputProcessor(runner) private val inputBuffer = StringBuilder() override fun isSilentlyDestroyOnClose() = true override fun notifyTextAvailable(text: String, key: Key<*>) { // hide warning about adding test folder to classpath if (text.startsWith("warning: classpath entry points to a non-existent location")) return if (key == ProcessOutputTypes.STDOUT) { inputBuffer.append(text) val resultingText = inputBuffer.toString() if (resultingText.endsWith("\n")) { handleReplMessage(resultingText) inputBuffer.setLength(0) } } else { super.notifyTextAvailable(text, key) } } private fun handleReplMessage(text: String) { if (text.isBlank()) return val output = try { factory.newDocumentBuilder().parse(strToSource(text)) } catch (e: Exception) { logError(ReplOutputHandler::class.java, "Couldn't parse REPL output: $text", e) return } val root = output.firstChild as Element val outputType = ReplEscapeType.valueOfOrNull(root.getAttribute("type")) val content = root.textContent.replUnescapeLineBreaks().replNormalizeLineBreaks() when (outputType) { INITIAL_PROMPT -> buildWarningIfNeededBeforeInit(content) HELP_PROMPT -> outputProcessor.printHelp(content) USER_OUTPUT -> outputProcessor.printUserOutput(content) REPL_RESULT -> outputProcessor.printResultWithGutterIcon(content) READLINE_START -> runner.isReadLineMode = true READLINE_END -> runner.isReadLineMode = false REPL_INCOMPLETE -> outputProcessor.highlightCompilerErrors(createCompilerMessages(content)) COMPILE_ERROR, RUNTIME_ERROR -> outputProcessor.printRuntimeError("${content.trim()}\n") INTERNAL_ERROR -> outputProcessor.printInternalErrorMessage(content) ERRORS_REPORTED -> {} SUCCESS -> runner.commandHistory.lastUnprocessedEntry()?.entryText?.let { runner.successfulLine(it) } else -> logError(ReplOutputHandler::class.java, "Unexpected output type:\n$outputType") } if (outputType in setOf(SUCCESS, ERRORS_REPORTED, READLINE_END)) { runner.commandHistory.entryProcessed() } } private fun buildWarningIfNeededBeforeInit(content: String) { if (!isBuildInfoChecked) { outputProcessor.printBuildInfoWarningIfNeeded() isBuildInfoChecked = true } // there are several INITIAL_PROMPT messages, the 1st starts with `Welcome to Kotlin version ...` if (content.startsWith("Welcome")) { outputProcessor.printUserOutput(KotlinIdeaReplBundle.message("repl.is.in.experimental.stage") + "\n") } outputProcessor.printInitialPrompt(content) } private fun strToSource(s: String, encoding: Charset = Charsets.UTF_8) = InputSource(ByteArrayInputStream(s.toByteArray(encoding))) private fun createCompilerMessages(runtimeErrorsReport: String): List<SeverityDetails> { val compilerMessages = arrayListOf<SeverityDetails>() val report = factory.newDocumentBuilder().parse(strToSource(runtimeErrorsReport, Charsets.UTF_16)) val entries = report.getElementsByTagName("reportEntry") for (i in 0 until entries.length) { val reportEntry = entries.item(i) as Element val severityLevel = reportEntry.getAttribute("severity").toSeverity() val rangeStart = reportEntry.getAttribute("rangeStart").toInt() val rangeEnd = reportEntry.getAttribute("rangeEnd").toInt() val description = reportEntry.textContent compilerMessages.add(SeverityDetails(severityLevel, description, TextRange(rangeStart, rangeEnd))) } return compilerMessages } private fun String.toSeverity() = when (this) { "ERROR" -> Severity.ERROR "WARNING" -> Severity.WARNING "INFO" -> Severity.INFO else -> throw IllegalArgumentException("Unsupported Severity: '$this'") // this case shouldn't occur } }
apache-2.0
ad76cf92d9c6daed6f781eec69be2389
43.412698
158
0.700983
4.856771
false
false
false
false
eyneill777/SpacePirates
core/src/rustyice/screens/ScreenManager.kt
1
3378
package rustyice.screens import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.scenes.scene2d.Stage import rustyengine.RustyEngine import rustyice.graphics.PerformanceTracker import java.util.* /** * Manages which screens are currently active and displays them. */ class ScreenManager(val tracker: PerformanceTracker? = null){ val stage: Stage private val screens: HashMap<String, LazyScreen> private val screenHistory: Stack<Screen> private var currentScreen: Screen? init { stage = Stage(RustyEngine.viewport, RustyEngine.batch) currentScreen = null screens = HashMap() screenHistory = Stack() } /** * adds a screen with a given name * * @param name the name the screen will be referenced to by * @param screen a screen object */ fun addScreen(name: String, screen: () -> Screen) { screens.put(name, LazyScreen(screen)) } /** * displays a screen, the last screen will be added to a stack. * * @param name see add screen */ fun showScreen(name: String) { val screen = screens[name] var currentScreen = currentScreen if(screen != null) { if(currentScreen != null) { currentScreen.hide() screenHistory.push(currentScreen) } currentScreen = screen.get() currentScreen.show() currentScreen.resize(Gdx.graphics.width, Gdx.graphics.height) this.currentScreen = currentScreen showTracker() } else { throw IllegalArgumentException("No screen is registered with the name") } } private fun showTracker() { if (tracker != null) { stage.actors.removeValue(tracker, true) stage.addActor(tracker) tracker.setFillParent(true) tracker.validate() } } /** * sets a screen to the screen before the last activation */ fun popScreen() { val popScreen: Screen? currentScreen?.hide() popScreen = screenHistory.pop() currentScreen = popScreen if(popScreen != null) { popScreen.show() showTracker() } } /** * NEEDS to be called whenever the window resizes for screens to behave properly. * * @param width in pixels * @param height in pixels */ fun resize(width: Int, height: Int) { stage.viewport.update(width, height, true) currentScreen?.resize(width, height) tracker?.validate() } /** * NEEDS to be called every frame * * @param delta in seconds */ fun render(batch: Batch, delta: Float) { currentScreen?.render(batch, delta) stage.act(delta) stage.draw() } fun dispose() { stage.dispose() } private inner class LazyScreen(private val builder: () -> Screen){ private var screen: Screen? = null fun get(): Screen { val screen = screen if(screen == null){ val out = builder() out.screenManager = this@ScreenManager this.screen = out return out } else { return screen } } } }
mit
847e78347928de90e47ccf08f1301ea9
24.022222
85
0.575784
4.691667
false
false
false
false
marius-m/wt4
components/src/main/java/lt/markmerkk/utils/ConfigSetSettingsImpl.kt
1
3433
package lt.markmerkk.utils import lt.markmerkk.ConfigPathProvider import org.slf4j.LoggerFactory import java.io.File import java.util.* class ConfigSetSettingsImpl( private val configPathProvider: ConfigPathProvider ) : BaseSettings(), ConfigSetSettings { private var configSetName: String = "" set(value) { field = sanitizeConfigName(value) } private var configs: List<String> = emptyList() override fun changeActiveConfig(configSelection: String) { configSetName = configSelection } override fun configs(): List<String> { return configs .plus(DEFAULT_ROOT_CONFIG_NAME) } override fun currentConfig(): String { return configSetName } override fun currentConfigOrDefault(): String { if (configSetName.isEmpty()) { return DEFAULT_ROOT_CONFIG_NAME } return configSetName } override fun propertyPath(): String { return File(configPathProvider.fullAppDir, "${File.separator}${PROPERTIES_FILENAME}") .absolutePath } override fun onLoad(properties: Properties) { configs = configsFromProperty(properties.getOrDefault(KEY_CONFIGS, "").toString()) configSetName = properties.getOrDefault(KEY_CONFIG_NAME, "").toString() } override fun onSave(properties: Properties) { properties.put(KEY_CONFIG_NAME, configSetName) properties.put(KEY_CONFIGS, configsToProperty(configs)) } //region Convenience /** * Sanitizes input value to be valid for a validation name * If no such config exist, will create a new one in the [configs] * * Note: "default" value will be reserved and interpreted as an empty string. */ fun sanitizeConfigName(inputValue: String): String { if (inputValue.isEmpty()) return "" if (inputValue == DEFAULT_ROOT_CONFIG_NAME) return "" if (!configs.contains(inputValue)) { configs += inputValue } return inputValue.replace(",", "").trim() } /** * Transforms a list of configs from property */ fun configsFromProperty(property: String): List<String> { if (property.isEmpty()) return emptyList() return property.split(",") .filter { it != "\n" } .filter { it != "\r\n" } .map(String::trim) .filter { !it.isEmpty() } .toList() } /** * Transforms list of configs to property to be saved. * Will take care of invalid items. */ fun configsToProperty(configs: List<String>): String { val sb = StringBuilder() for (config in configs) { if (config.isNullOrEmpty()) continue sb.append( config.toString() .trim() .replace(",", "") ) sb.append(",") } if (sb.length > 0) { sb.deleteCharAt(sb.length - 1) } return sb.toString() } //endregion companion object { const val KEY_CONFIG_NAME = "config_set_name" const val KEY_CONFIGS = "configs" const val DEFAULT_ROOT_CONFIG_NAME = "default" const val PROPERTIES_FILENAME = "config_set.properties" val logger = LoggerFactory.getLogger(ConfigSetSettingsImpl::class.java)!! } }
apache-2.0
6748558bb9628af0966704bbac253a87
29.122807
93
0.592776
4.801399
false
true
false
false
evanchooly/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/JarUtils.kt
1
7738
package com.beust.kobalt.misc import com.beust.kobalt.Glob import com.beust.kobalt.IFileSpec import com.google.common.io.CharStreams import java.io.* import java.nio.file.Paths import java.util.jar.JarEntry import java.util.jar.JarFile import java.util.jar.JarInputStream import java.util.zip.ZipEntry import java.util.zip.ZipException import java.util.zip.ZipFile import java.util.zip.ZipOutputStream public class JarUtils { companion object { val DEFAULT_HANDLER: (Exception) -> Unit = { ex: Exception -> // Ignore duplicate entry exceptions if (! ex.message?.contains("duplicate")!!) { throw ex } } fun addFiles(directory: String, files: List<IncludedFile>, target: ZipOutputStream, expandJarFiles: Boolean, onError: (Exception) -> Unit = DEFAULT_HANDLER) { files.forEach { addSingleFile(directory, it, target, expandJarFiles, onError) } } private val DEFAULT_JAR_EXCLUDES = Glob("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA") fun addSingleFile(directory: String, file: IncludedFile, outputStream: ZipOutputStream, expandJarFiles: Boolean, onError: (Exception) -> Unit = DEFAULT_HANDLER) { val foundFiles = file.allFromFiles(directory) foundFiles.forEach { foundFile -> // Turn the found file into the local physical file that will be put in the jar file val fromFile = file.from(foundFile.path) val localFile = if (fromFile.isAbsolute) fromFile else File(directory, fromFile.path) if (!localFile.exists()) { throw AssertionError("File should exist: $localFile") } if (foundFile.isDirectory) { log(2, "Writing contents of directory $foundFile") // Directory var name = foundFile.name if (!name.isEmpty()) { if (!name.endsWith("/")) name += "/" val entry = JarEntry(name) entry.time = localFile.lastModified() try { outputStream.putNextEntry(entry) } catch(ex: ZipException) { log(2, "Can't add $name: ${ex.message}") } finally { outputStream.closeEntry() } } val includedFile = IncludedFile(From(foundFile.path), To(""), listOf(IFileSpec.GlobSpec("**"))) addSingleFile(".", includedFile, outputStream, expandJarFiles) } else { if (file.expandJarFiles && foundFile.name.endsWith(".jar") && ! file.from.contains("resources")) { log(2, "Writing contents of jar file $foundFile") val stream = JarInputStream(FileInputStream(localFile)) var entry = stream.nextEntry while (entry != null) { if (!entry.isDirectory && !KFiles.isExcluded(entry.name, DEFAULT_JAR_EXCLUDES)) { val ins = JarFile(localFile).getInputStream(entry) addEntry(ins, JarEntry(entry), outputStream, onError) } entry = stream.nextEntry } } else { val entryFileName = file.to(foundFile.path).path.replace("\\", "/") val entry = JarEntry(entryFileName) entry.time = localFile.lastModified() addEntry(FileInputStream(localFile), entry, outputStream, onError) } } } } private fun addEntry(inputStream: InputStream, entry: ZipEntry, outputStream: ZipOutputStream, onError: (Exception) -> Unit = DEFAULT_HANDLER) { var bis: BufferedInputStream? = null try { outputStream.putNextEntry(entry) bis = BufferedInputStream(inputStream) val buffer = ByteArray(50 * 1024) while (true) { val count = bis.read(buffer) if (count == -1) break outputStream.write(buffer, 0, count) } outputStream.closeEntry() } catch(ex: Exception) { onError(ex) } finally { bis?.close() } } fun extractTextFile(zip : ZipFile, fileName: String) : String? { val enumEntries = zip.entries() while (enumEntries.hasMoreElements()) { val file = enumEntries.nextElement() if (file.name == fileName) { log(2, "Found $fileName in ${zip.name}") zip.getInputStream(file).use { ins -> return CharStreams.toString(InputStreamReader(ins, "UTF-8")) } } } return null } fun extractJarFile(file: File, destDir: File) = extractZipFile(JarFile(file), destDir) fun extractZipFile(zipFile: ZipFile, destDir: File) { val enumEntries = zipFile.entries() while (enumEntries.hasMoreElements()) { val file = enumEntries.nextElement() val f = File(destDir.path + File.separator + file.name) if (file.isDirectory) { f.mkdir() continue } zipFile.getInputStream(file).use { ins -> f.parentFile.mkdirs() FileOutputStream(f).use { fos -> while (ins.available() > 0) { fos.write(ins.read()) } } } } } } } open class Direction(open val p: String) { override fun toString() = path fun isCurrentDir() = path == "./" val path: String get() = if (p.isEmpty()) "./" else if (p.startsWith("/") || p.endsWith("/")) p else p + "/" } class IncludedFile(val fromOriginal: From, val toOriginal: To, val specs: List<IFileSpec>, val expandJarFiles: Boolean = false) { constructor(specs: List<IFileSpec>, expandJarFiles: Boolean = false) : this(From(""), To(""), specs, expandJarFiles) fun from(s: String) = File(if (fromOriginal.isCurrentDir()) s else KFiles.joinDir(from, s)) val from: String get() = fromOriginal.path.replace("\\", "/") fun to(s: String) = File(if (toOriginal.isCurrentDir()) s else KFiles.joinDir(to, s)) val to: String get() = toOriginal.path.replace("\\", "/") override public fun toString() = toString("IncludedFile", "files - ", specs.map { it.toString() }, "from", from, "to", to) fun allFromFiles(directory: String? = null): List<File> { val result = arrayListOf<File>() specs.forEach { spec -> // val fullDir = if (directory == null) from else KFiles.joinDir(directory, from) spec.toFiles(directory, from).forEach { source -> result.add(if (source.isAbsolute) source else File(source.path)) } } return result.map { Paths.get(it.path).normalize().toFile()} } } class From(override val p: String) : Direction(p) class To(override val p: String) : Direction(p)
apache-2.0
fcb691e5f41d7ffac3954c5afa1bdf28
40.602151
120
0.517705
5.044329
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/i18n/lang/colors/I18nSyntaxHighlighter.kt
1
1675
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.i18n.lang.colors import com.demonwav.mcdev.i18n.lang.gen.psi.I18nTypes import com.intellij.lexer.Lexer import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.psi.tree.IElementType class I18nSyntaxHighlighter(private val lexer: Lexer) : SyntaxHighlighterBase() { override fun getHighlightingLexer() = lexer override fun getTokenHighlights(tokenType: IElementType?) = when (tokenType) { I18nTypes.KEY, I18nTypes.DUMMY -> KEY_KEYS I18nTypes.EQUALS -> EQUALS_KEYS I18nTypes.VALUE -> VALUE_KEYS I18nTypes.COMMENT -> COMMENT_KEYS else -> EMPTY_KEYS } companion object { val KEY = TextAttributesKey.createTextAttributesKey("I18N_KEY", DefaultLanguageHighlighterColors.KEYWORD) val EQUALS = TextAttributesKey.createTextAttributesKey("I18N_EQUALS", DefaultLanguageHighlighterColors.OPERATION_SIGN) val VALUE = TextAttributesKey.createTextAttributesKey("I18N_VALUE", DefaultLanguageHighlighterColors.STRING) val COMMENT = TextAttributesKey.createTextAttributesKey("I18N_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT) val KEY_KEYS = arrayOf(KEY) val EQUALS_KEYS = arrayOf(EQUALS) val VALUE_KEYS = arrayOf(VALUE) val COMMENT_KEYS = arrayOf(COMMENT) val EMPTY_KEYS = emptyArray<TextAttributesKey>() } }
mit
1e2b670f64b1204f7173455373cd0171
37.068182
126
0.732537
4.665738
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/cuda/src/templates/kotlin/cuda/templates/NVRTC.kt
4
9465
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package cuda.templates import cuda.* import org.lwjgl.generator.* val NVRTC = "NVRTC".nativeClass(Module.CUDA, prefix = "NVRTC", binding = NVRTC_BINDING) { documentation = "Contains bindings to <a href=\"https://docs.nvidia.com/cuda/nvrtc/index.html\">NVRTC</a>, a runtime compilation library for CUDA C++." EnumConstant( """ The enumerated type {@code nvrtcResult} defines API call result codes. NVRTC API functions return {@code nvrtcResult} to indicate the call result. """, "SUCCESS".enum("", "0"), "ERROR_OUT_OF_MEMORY".enum, "ERROR_PROGRAM_CREATION_FAILURE".enum, "ERROR_INVALID_INPUT".enum, "ERROR_INVALID_PROGRAM".enum, "ERROR_INVALID_OPTION".enum, "ERROR_COMPILATION".enum, "ERROR_BUILTIN_OPERATION_FAILURE".enum, "ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION".enum, "ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION".enum, "ERROR_NAME_EXPRESSION_NOT_VALID".enum, "ERROR_INTERNAL_ERROR".enum ) charASCII.const.p( "GetErrorString", """ A helper function that returns a string describing the given {@code nvrtcResult} code, e.g., #SUCCESS to {@code "NVRTC_SUCCESS"}. For unrecognized enumeration values, it returns {@code "NVRTC_ERROR unknown"}. """, nvrtcResult("result", "CUDA Runtime Compilation API result code"), returnDoc = "message string for the given {@code nvrtcResult} code" ) nvrtcResult( "Version", "Sets the output parameters {@code major} and {@code minor} with the CUDA Runtime Compilation version number.", Check(1)..int.p("major", "CUDA Runtime Compilation major version number"), Check(1)..int.p("minor", "CUDA Runtime Compilation minor version number") ) IgnoreMissing..nvrtcResult( "GetNumSupportedArchs", """ Sets the output parameter {@code numArchs} with the number of architectures supported by NVRTC. This can then be used to pass an array to #GetSupportedArchs() to get the supported architectures. """, Check(1)..int.p("numArchs", "number of supported architectures") ) IgnoreMissing..nvrtcResult( "GetSupportedArchs", """ Populates the array passed via the output parameter {@code supportedArchs} with the architectures supported by NVRTC. The array is sorted in the ascending order. The size of the array to be passed can be determined using #GetNumSupportedArchs(). """, Unsafe..int.p("supportedArchs", "sorted array of supported architectures") ) nvrtcResult( "CreateProgram", "Creates an instance of {@code nvrtcProgram} with the given input parameters, and sets the output parameter {@code prog} with it.", Check(1)..nvrtcProgram.p("prog", "CUDA Runtime Compilation program"), charUTF8.const.p("src", "CUDA program source"), nullable..charUTF8.const.p("name", "CUDA program name. {@code name} can be #NULL; {@code \"default_program\"} is used when {@code name} is #NULL or \"\"."), AutoSize("headers", "includeNames")..int("numHeaders", "number of headers used. {@code numHeaders} must be greater than or equal to 0."), nullable..charUTF8.const.p.const.p("headers", "sources of the headers. {@code headers} can be #NULL when {@code numHeaders} is 0."), nullable..char.const.p.const.p( "includeNames", "name of each header by which they can be included in the CUDA program source. {@code includeNames} can be #NULL when {@code numHeaders} is 0." ) ) nvrtcResult( "DestroyProgram", "Destroys the given program.", Check(1)..nvrtcProgram.p("prog", "CUDA Runtime Compilation program") ) nvrtcResult( "CompileProgram", """ Compiles the given program. It supports compile options listed in {@code options}. """, nvrtcProgram("prog", "CUDA Runtime Compilation program"), AutoSize("options")..int("numOptions", "number of compiler options passed"), nullable..charASCII.const.p.const.p("options", "compiler options in the form of C string array. {@code options} can be #NULL when {@code numOptions} is 0.") ) nvrtcResult( "GetPTXSize", "Sets {@code ptxSizeRet} with the size of the PTX generated by the previous compilation of {@code prog} (including the trailing #NULL).", nvrtcProgram("prog", "CUDA Runtime Compilation program"), Check(1)..size_t.p("ptxSizeRet", "size of the generated PTX (including the trailing #NULL)") ) nvrtcResult( "GetPTX", "Stores the PTX generated by the previous compilation of {@code prog} in the memory pointed by {@code ptx}.", nvrtcProgram("prog", "CUDA Runtime Compilation program"), Unsafe..char.p("ptx", "compiled result") ) IgnoreMissing..nvrtcResult( "GetCUBINSize", """ Sets {@code cubinSizeRet} with the size of the {@code cubin} generated by the previous compilation of {@code prog}. The value of {@code cubinSizeRet} is set to 0 if the value specified to {@code -arch} is a virtual architecture instead of an actual architecture. """, nvrtcProgram("prog", "CUDA Runtime Compilation program"), Check(1)..size_t.p("cubinSizeRet", "size of the generated cubin") ) IgnoreMissing..nvrtcResult( "GetCUBIN", """ Stores the {@code cubin} generated by the previous compilation of {@code prog} in the memory pointed by {@code cubin}. No {@code cubin} is available if the value specified to {@code -arch} is a virtual architecture instead of an actual architecture. """, nvrtcProgram("prog", "CUDA Runtime Compilation program"), Unsafe..char.p("cubin", "compiled and assembled result") ) IgnoreMissing..nvrtcResult( "GetNVVMSize", """ Sets {@code nvvmSizeRet} with the size of the NVVM generated by the previous compilation of {@code prog}. The value of {@code nvvmSizeRet} is set to 0 if the program was not compiled with {@code -dlto}. """, nvrtcProgram("prog", "CUDA Runtime Compilation program"), Check(1)..size_t.p("nvvmSizeRet", "size of the generated NVVM"), returnDoc = "" ) IgnoreMissing..nvrtcResult( "GetNVVM", """ Stores the NVVM generated by the previous compilation of {@code prog} in the memory pointed by {@code nvvm}. The program must have been compiled with {@code -dlto}, otherwise will return an error. """, nvrtcProgram("prog", "CUDA Runtime Compilation program"), Unsafe..char.p("nvvm", "compiled result") ) nvrtcResult( "GetProgramLogSize", """ Sets {@code logSizeRet} with the size of the log generated by the previous compilation of {@code prog} (including the trailing #NULL). Note that compilation log may be generated with warnings and informative messages, even when the compilation of {@code prog} succeeds. """, nvrtcProgram("prog", "CUDA Runtime Compilation program"), Check(1)..size_t.p("logSizeRet", "size of the compilation log (including the trailing #NULL)") ) nvrtcResult( "GetProgramLog", "Stores the log generated by the previous compilation of {@code prog} in the memory pointed by {@code log}.", nvrtcProgram("prog", "CUDA Runtime Compilation program"), Unsafe..char.p("log", "compilation log") ) nvrtcResult( "AddNameExpression", """ Notes the given name expression denoting the address of a {@code __global__} function or {@code __device__}/{@code __constant__} variable. The identical name expression string must be provided on a subsequent call to #GetLoweredName() to extract the lowered name. """, nvrtcProgram("prog", "CUDA Runtime Compilation program"), charUTF8.const.p.const( "name_expression", "constant expression denoting the address of a {@code __global__} function or {@code __device__}/{@code __constant__} variable" ), returnDoc = "" ) nvrtcResult( "GetLoweredName", """ Extracts the lowered (mangled) name for a {@code __global__} function or {@code __device__}/{@code __constant__} variable, and updates {@code *lowered_name} to point to it. The memory containing the name is released when the NVRTC program is destroyed by #DestroyProgram(). The identical name expression must have been previously provided to #AddNameExpression(). """, nvrtcProgram("prog", "CUDA Runtime Compilation program"), charUTF8.const.p.const( "name_expression", "constant expression denoting the address of a {@code __global__} function or {@code __device__}/{@code __constant__} variable"), Check(1)..charUTF8.const.p.p( "lowered_name", "initialized by the function to point to a C string containing the lowered (mangled) name corresponding to the provided name expression" ) ) }
bsd-3-clause
cd6889754cb2ceae13659cc2919939e7
39.280851
164
0.63402
4.617073
false
false
false
false
fabianonline/telegram_backup
src/main/kotlin/de/fabianonline/telegram_backup/CommandLineRunner.kt
1
3483
/* Telegram_Backup * Copyright (C) 2016 Fabian Schlenz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.fabianonline.telegram_backup import de.fabianonline.telegram_backup.CommandLineController import de.fabianonline.telegram_backup.Utils import de.fabianonline.telegram_backup.Version import java.util.concurrent.TimeUnit import org.slf4j.LoggerFactory import ch.qos.logback.classic.Logger import ch.qos.logback.classic.LoggerContext import ch.qos.logback.classic.encoder.PatternLayoutEncoder import ch.qos.logback.classic.spi.ILoggingEvent import ch.qos.logback.core.ConsoleAppender import ch.qos.logback.classic.Level fun main(args: Array<String>) { val clr = CommandLineRunner(args) clr.setupLogging() clr.checkVersion() clr.run() } class CommandLineRunner(args: Array<String>) { val logger = LoggerFactory.getLogger(CommandLineRunner::class.java) as Logger val options = CommandLineOptions(args) fun run() { // Always use the console for now. try { CommandLineController(options) } catch (e: Throwable) { println("An error occured!") e.printStackTrace() logger.error("Exception caught!", e) System.exit(1) } } fun setupLogging() { if (options.isSet("anonymize")) { Utils.anonymize = true } logger.trace("Setting up Loggers...") val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger val rootContext = rootLogger.getLoggerContext() rootContext.reset() val encoder = PatternLayoutEncoder() encoder.setContext(rootContext) encoder.setPattern("%d{HH:mm:ss.SSS} %-5level %-35.-35(%logger{0}.%method): %message%n") encoder.start() val appender = ConsoleAppender<ILoggingEvent>() appender.setContext(rootContext) appender.setEncoder(encoder) appender.start() rootLogger.addAppender(appender) rootLogger.setLevel(Level.OFF) if (options.isSet("trace")) { (LoggerFactory.getLogger("de.fabianonline.telegram_backup") as Logger).setLevel(Level.TRACE) } else if (options.isSet("debug")) { (LoggerFactory.getLogger("de.fabianonline.telegram_backup") as Logger).setLevel(Level.DEBUG) } if (options.isSet("trace_telegram")) { (LoggerFactory.getLogger("com.github.badoualy") as Logger).setLevel(Level.TRACE) } } fun checkVersion() { if (Config.APP_APPVER.contains("-")) { println("Your version ${Config.APP_APPVER} seems to be a development version. Version check is disabled.") return } val v = Utils.getNewestVersion() if (v != null && v.isNewer) { println() println() println() println("A newer version is vailable!") println("You are using: " + Config.APP_APPVER) println("Available: " + v.version) println("Get it here: " + v.url) println() println() println("Changes in this version:") println(v.body) println() println() println() TimeUnit.SECONDS.sleep(5) } } }
gpl-3.0
173293e0c1c3573a0a31b29d47c21c3a
29.552632
109
0.727247
3.601861
false
false
false
false
programmerr47/ganalytics
ganalytics-core/src/test/java/com/github/programmerr47/ganalytics/core/test_classes.kt
1
428
package com.github.programmerr47.ganalytics.core open class DummyClass(val id: Int, val name: String) { override fun toString() = "DummyClass(id=$id, name=$name)" } data class DummyDataClass(val id: Int, val name: String) class DummyReversedClass(id: Int, name: String) : DummyClass(id, name.reversed()) { override fun toString() = "DummyReversedClass(id=$id, name=$name)" } enum class DummyEnum { ONE, TWO, THREE }
mit
ce123f5eaf580f0b3024a9c076da0645
31.923077
83
0.719626
3.317829
false
false
false
false
Kennyc1012/DashWeatherExtension
app/src/main/java/com/kennyc/dashweather/SettingsFragment.kt
1
4784
package com.kennyc.dashweather import android.Manifest import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.os.Bundle import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.preference.ListPreference import androidx.preference.MultiSelectListPreference import androidx.preference.PreferenceFragmentCompat import com.kennyc.dashweather.data.Logger import com.kennyc.dashweather.data.WeatherRepository import com.kennyc.dashweather.data.model.LocalPreferences import javax.inject.Inject /** * Created by kcampagna on 10/6/17. */ class SettingsFragment : PreferenceFragmentCompat() { companion object { const val UPDATE_FREQUENCY_NO_LIMIT = "0" const val UPDATE_FREQUENCY_1_HOUR = "1" const val UPDATE_FREQUENCY_3_HOURS = "2" const val UPDATE_FREQUENCY_4_HOURS = "3" const val WEATHER_DETAILS_HIGH_LOW = "0" const val WEATHER_DETAILS_HUMIDITY = "1" const val WEATHER_DETAILS_LOCATION = "2" } @Inject lateinit var preferences: LocalPreferences @Inject lateinit var logger: Logger @Inject lateinit var repo: WeatherRepository override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { (context!!.applicationContext as WeatherApp).component.inject(this) addPreferencesFromResource(R.xml.settings) val frequencyKey = SettingsActivity.KEY_UPDATE_FREQUENCY val listPreference: ListPreference = findPreference(frequencyKey) as ListPreference listPreference.summary = listPreference.entries[preferences.getString(frequencyKey, UPDATE_FREQUENCY_1_HOUR)!!.toInt()] listPreference.setOnPreferenceChangeListener { preference, newValue -> val listPreference: ListPreference = preference as ListPreference listPreference.summary = listPreference.entries[newValue.toString().toInt()] true } val detailsKey = SettingsActivity.KEY_SHOW_WEATHER_DETAILS val weatherDetails: MultiSelectListPreference = findPreference(detailsKey) as MultiSelectListPreference preferences.getStringSet(detailsKey, setOf(SettingsFragment.WEATHER_DETAILS_HIGH_LOW, SettingsFragment.WEATHER_DETAILS_LOCATION))?.let { setWeatherDetails(weatherDetails, it) } weatherDetails.setOnPreferenceChangeListener { preference, newValue -> setWeatherDetails(preference as MultiSelectListPreference, newValue as Set<String>) true } val version = findPreference(getString(R.string.pref_key_version)) try { val act = activity as Activity val pInfo = act.packageManager.getPackageInfo(act.packageName, 0) version.summary = pInfo.versionName } catch (e: PackageManager.NameNotFoundException) { logger.e("Settings", "Unable to get version number") } checkPermissions() findPreference(getString(R.string.pref_key_powered_by)).summary = repo.getWeatherProviderName() } private fun checkPermissions() { val context = activity as Context val coarsePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED val finePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED val hasPermission = coarsePermission || finePermission if (!hasPermission) { findPreference(getString(R.string.pref_key_permission)).setOnPreferenceClickListener { ActivityCompat.requestPermissions(context as Activity, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), SettingsActivity.PERMISSION_REQUEST_CODE) true } } onPermissionUpdated(hasPermission) } private fun setWeatherDetails(weatherDetails: MultiSelectListPreference, uiPreferences: Set<String>) { val summary = StringBuilder() val size = uiPreferences.size uiPreferences.withIndex().forEach { summary.append(weatherDetails.entries[weatherDetails.findIndexOfValue(it.value)]) if (it.index < size - 1) summary.append("\n") } weatherDetails.summary = summary.toString() } fun onPermissionUpdated(available: Boolean) { val stringRes = if (available) R.string.preference_permission_granted else R.string.preference_permission_declined findPreference(getString(R.string.pref_key_permission)).setSummary(stringRes) } }
apache-2.0
c525013c3ab6d33e65db084896ddb99a
39.550847
154
0.712584
5.234136
false
false
false
false
cy6erGn0m/github-release-plugin
github-release-shared/src/main/kotlin/github-api.kt
1
5866
package cy.github import cy.rfc6570.* import org.json.simple.* import java.io.* import java.net.* import javax.net.ssl.* data class Repo(val serverEndpoint: String, val user: String, val repoName: String) data class Release(val tagName: String, val releaseId: Long, val releasesFormat: String, val uploadFormat: String, val htmlPage: String) fun endpointOf(protoSpec: String?, hostSpec: String) = "${protoSpec ?: "https://"}api.$hostSpec" fun connectionOf(url: String, method: String = "GET", token: String? = null): HttpURLConnection { val connection = URL(url).openConnection() as HttpURLConnection connection.setRequestProperty("User-Agent", "Kotlin") connection.setRequestProperty("Accept", "application/vnd.github.v3+json") connection.instanceFollowRedirects = false connection.allowUserInteraction = false connection.defaultUseCaches = false connection.useCaches = false connection.doInput = true connection.requestMethod = method connection.connectTimeout = 15000 connection.readTimeout = 30000 if (token != null) { connection.setRequestProperty("Authorization", "token " + token) } if (connection is HttpsURLConnection) { // connection.setHostnameVerifier { host, sslsession -> // if (host in unsafeHosts) { // } else DefaultHostVerifier... // } } return connection } fun jsonOf(url: String, method: String = "GET", token: String? = null, body: JSONObject? = null): JSONObject? { val connection = connectionOf(url, method, token) try { if (body != null) { connection.setRequestProperty("Content-Type", "application/json") connection.doOutput = true connection.outputStream.bufferedWriter(Charsets.UTF_8).use { writer -> body.writeJSONString(writer) } } return connection.withReader { JSONValue.parse(it) as JSONObject } } catch (ffn: FileNotFoundException) { return null } catch (e: IOException) { throw IOException("Failed due to ${connection.errorStream?.bufferedReader()?.readText()}", e) } finally { connection.disconnect() } } fun createRelease(token: String, releasesFormat: String, tagName: String, releaseTitle: String, description: String, preRelease: Boolean): Release? { val request = JSONObject() request["tag_name"] = tagName request["name"] = releaseTitle request["body"] = description request["draft"] = false request["prerelease"] = preRelease return jsonOf(releasesFormat.expandURLFormat(emptyMap<String, String>()), "POST", token, body = request)?.parseRelease(releasesFormat) } fun findRelease(releasesFormat: String, tagName: String, token: String? = null): Release? = jsonOf("${releasesFormat.expandURLFormat(emptyMap<String, String>())}/tags/${tagName.encodeURLComponent()}", token = token).parseRelease(releasesFormat) fun JSONObject?.parseRelease(releasesFormat: String): Release? { val id = this?.getAsLong("id") return if (this == null || id == null) { null } else { Release(this["tag_name"]!!.toString(), this.getAsLong("id")!!, releasesFormat, this["upload_url"]!!.toString(), this["html_url"]!!.toString()) } } fun upload(token: String, uploadFormat: String, source: File, name: String = source.name) { val connection = connectionOf(uploadFormat.expandURLFormat(mapOf("name" to name)), "POST", token) connection.setRequestProperty("Content-Type", when (source.extension.toLowerCase()) { "txt" -> "text/plain" "html", "htm", "xhtml" -> "text/html" "md" -> "text/x-markdown" "adoc", "asciidoc" -> "text/x-asciidoc" "zip", "war" -> "application/x-zip" "rar" -> "application/x-rar-compressed" "js" -> "application/javascript" "gzip", "gz", "tgz" -> "application/x-gzip" "bzip2", "bz2", "tbz", "tbz2" -> "application/bzip2" "xz", "txz" -> "application/x-xz" "jar", "ear", "aar" -> "application/java-archive" "tar" -> "application/x-tar" "svg", "pom", "xml" -> "text/xml" "jpg", "jpeg" -> "image/jpeg" "png" -> "image/png" "gif" -> "image/gif" "md5", "sha", "sha1", "sha256", "asc" -> "text/plain" else -> "binary/octet-stream" }) connection.doOutput = true connection.outputStream.use { out -> source.inputStream().use { ins -> ins.copyTo(out) } } connection.errorStream?.let { error -> error.use { it.copyTo(System.out) } throw IOException("${connection.responseCode} ${connection.responseMessage}") } connection.withReader { it.toJSONObject() } } fun probeGitHubRepositoryFormat(base: String = "https://api.github.com", token: String? = null): String = connectionOf(base, token = token).withReader { it.toJSONObject()?.get("repository_url")?.toString() ?: throw IllegalArgumentException("No repository_url endpoint found for $base") } data class RepositoryUrlFormats(val releasesFormat: String, val tagsFormat: String) fun probeGitHubReleasesFormat(repositoryFormat: String, repo: Repo, token: String? = null): RepositoryUrlFormats = connectionOf(repositoryFormat.expandURLFormat(mapOf("owner" to repo.user, "repo" to repo.repoName)), token = token).withReader { it.toJSONObject()?.let { json -> RepositoryUrlFormats( releasesFormat = json.required("releases_url"), tagsFormat = json.required("tags_url") ) } ?: throw IllegalArgumentException("No response found") } fun JSONObject.required(name: String) = get(name)?.toString() ?: throw IllegalArgumentException("No $name found")
apache-2.0
23bb33edddd841452a18c4afa52c3208
38.113333
160
0.641152
4.19
false
false
false
false
nadraliev/DsrWeatherApp
app/src/main/java/soutvoid/com/DsrWeatherApp/interactor/common/network/ServerConstants.kt
1
519
package soutvoid.com.DsrWeatherApp.interactor.common.network object ServerConstants { const val API_KEY_PARAMETER = "appid" const val API_KEY = "c0c7d349be8cec8728ea408d0e6acfe7" const val UNITS_PARAMETER = "units" const val QUERY_PARAMETER = "q" const val CITY_ID_PARAMETER = "id" const val LATITUDE_PARAMETER = "lat" const val LONGITUDE_PARAMETER = "lon" const val ZIP_CODE_PARAMETER = "zip" const val ACCURACY_PARAMETER = "type" const val LANG_PARAMETER = "lang" }
apache-2.0
e2c645bfd28afc4b586d9f2255d1fe9f
19.8
60
0.697495
3.414474
false
false
false
false
intellij-solidity/intellij-solidity
src/main/kotlin/me/serce/solidity/ide/colors/SolColorSettingsPage.kt
1
1233
package me.serce.solidity.ide.colors import com.intellij.openapi.options.colors.AttributesDescriptor import com.intellij.openapi.options.colors.ColorDescriptor import com.intellij.openapi.options.colors.ColorSettingsPage import me.serce.solidity.ide.SolHighlighter import me.serce.solidity.ide.SolidityIcons import me.serce.solidity.lang.SolidityLanguage import me.serce.solidity.loadCodeSampleResource class SolColorSettingsPage : ColorSettingsPage { private val ATTRIBUTES: Array<AttributesDescriptor> = SolColor.values().map { it.attributesDescriptor }.toTypedArray() private val ANNOTATOR_TAGS = SolColor.values().associateBy({ it.name }, { it.textAttributesKey }) private val DEMO_TEXT by lazy { loadCodeSampleResource(this, "me/serce/solidity/ide/colors/highlighter_example.sol") } override fun getDisplayName() = SolidityLanguage.displayName override fun getIcon() = SolidityIcons.FILE_ICON override fun getAttributeDescriptors() = ATTRIBUTES override fun getColorDescriptors(): Array<ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY override fun getHighlighter() = SolHighlighter override fun getAdditionalHighlightingTagToDescriptorMap() = ANNOTATOR_TAGS override fun getDemoText() = DEMO_TEXT }
mit
dd426aede18f5067aeafc18163b6f6bd
46.423077
120
0.815085
4.635338
false
false
false
false
paplorinc/intellij-community
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ObsoleteLibraryFilesRemover.kt
9
1810
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots.ui.configuration import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.ui.Messages import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import java.util.* /** * @author nik */ class ObsoleteLibraryFilesRemover(private val project: Project) { private val oldRoots = LinkedHashSet<VirtualFile>() fun registerObsoleteLibraryRoots(roots: Collection<VirtualFile>) { oldRoots += roots } fun deleteFiles() { val index = ProjectFileIndex.getInstance(project) //do not suggest to delete library files located outside project roots: they may be used in other projects or aren't stored in VCS val toDelete = oldRoots.filter { it.isValid && !index.isInLibrary(it) && index.isInContent(VfsUtil.getLocalFile(it)) } oldRoots.clear() if (toDelete.isNotEmpty()) { val many = toDelete.size > 1 if (Messages.showYesNoDialog(project, "The following ${if (many) "files aren't" else "file isn't"} used anymore:\n" + "${toDelete.joinToString("\n") { it.presentableUrl }}\n" + "Do you want to delete ${if (many) "them" else "it"}?\n" + "You might not be able to fully undo this operation!", "Delete Unused Files", null) == Messages.YES) { runWriteAction { toDelete.forEach { VfsUtil.getLocalFile(it).delete(this) } } } } } }
apache-2.0
424fc820e3a7d65823f1a8dc1e62a223
40.159091
140
0.648066
4.536341
false
false
false
false