repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Ribesg/anko | dsl/static/src/supportV4/SupportIntents.kt | 1 | 1850 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.anko.support.v4
import android.app.Activity
import android.app.Service
import android.content.Intent
import android.support.v4.app.Fragment
import org.jetbrains.anko.internals.AnkoInternals
import org.jetbrains.anko.*
fun Fragment.browse(url: String): Boolean = activity.browse(url)
fun Fragment.share(text: String, subject: String = ""): Boolean = activity.share(text, subject)
fun Fragment.email(email: String, subject: String = "", text: String = ""): Boolean =
activity.email(email, subject, text)
fun Fragment.makeCall(number: String): Boolean = activity.makeCall(number)
inline fun <reified T: Activity> Fragment.startActivity(vararg params: Pair<String, Any>) {
AnkoInternals.internalStartActivity(activity, T::class.java, params)
}
inline fun <reified T: Activity> Fragment.startActivityForResult(requestCode: Int, vararg params: Pair<String, Any>) {
AnkoInternals.internalStartActivityForResult(activity, T::class.java, requestCode, params)
}
inline fun <reified T: Service> Fragment.startService(vararg params: Pair<String, Any>) {
AnkoInternals.internalStartService(activity, T::class.java, params)
}
inline fun <reified T: Any> Fragment.intentFor(): Intent = Intent(activity, T::class.java) | apache-2.0 | 2c70392ddf4c28751fa58705cbacab34 | 38.382979 | 118 | 0.759459 | 3.952991 | false | false | false | false |
matejdro/WearMusicCenter | common/src/main/java/com/matejdro/wearmusiccenter/common/MiscPreferences.kt | 1 | 2557 | package com.matejdro.wearmusiccenter.common
import android.content.SharedPreferences
import com.matejdro.wearmusiccenter.common.model.AutoStartMode
import com.matejdro.wearutils.preferences.definition.EnumPreferenceDefinition
import com.matejdro.wearutils.preferences.definition.PreferenceDefinition
import com.matejdro.wearutils.preferences.definition.Preferences
import com.matejdro.wearutils.preferences.definition.SimplePreferenceDefinition
object MiscPreferences {
val ALWAYS_SHOW_TIME: PreferenceDefinition<Boolean>
= SimplePreferenceDefinition("always_show_time", false)
val PAUSE_ON_SWIPE_EXIT: PreferenceDefinition<Boolean> = SimplePreferenceDefinition("pause_on_swipe_exit", false)
val ROTATING_CROWN_OFF_PERIOD: PreferenceDefinition<Int> = SimplePreferenceDefinition("rotating_crown_off_period", 300)
val ROTATING_CROWN_SENSITIVITY: PreferenceDefinition<Int> = SimplePreferenceDefinition("rotating_crown_sensitivity", 100)
val HAPTIC_FEEDBACK: PreferenceDefinition<Boolean> = SimplePreferenceDefinition("haptic_feedback", true)
val DISABLE_PHYSICAL_DOUBLE_CLICK_IN_AMBIENT: PreferenceDefinition<Boolean> = SimplePreferenceDefinition("disable_ambient_physical_double_click", false)
val AUTO_START: PreferenceDefinition<Boolean> = SimplePreferenceDefinition("auto_start", false)
val AUTO_START_MODE: EnumPreferenceDefinition<AutoStartMode> = EnumPreferenceDefinition("auto_start_mode", AutoStartMode.OFF)
val AUTO_START_APP_BLACKLIST: PreferenceDefinition<Set<String>> = SimplePreferenceDefinition("auto_start_apps_blacklist", emptySet())
val CLOSE_TIMEOUT: PreferenceDefinition<Int> = SimplePreferenceDefinition("close_timeout", 0)
val ENABLE_NOTIFICATION_POPUP: PreferenceDefinition<Boolean> = SimplePreferenceDefinition("enable_notification_popup", false)
val NOTIFICATION_TIMEOUT: PreferenceDefinition<Int> = SimplePreferenceDefinition("notification_timeout", 10)
val ALWAYS_SELECT_CENTER_ACTION: PreferenceDefinition<Boolean> = SimplePreferenceDefinition("always_select_center_action", false)
val LAST_MENU_DISPLAYED: PreferenceDefinition<String> = SimplePreferenceDefinition("last_menu_displayed", "-1")
val OPEN_PLAYBACK_QUEUE_ON_SWIPE_UP: PreferenceDefinition<Boolean> = SimplePreferenceDefinition("swipe_up_for_queue", false)
fun isAnyKindOfAutoStartEnabled(preferences: SharedPreferences): Boolean {
return Preferences.getBoolean(preferences, AUTO_START) || Preferences.getEnum(preferences, AUTO_START_MODE) != AutoStartMode.OFF
}
}
| gpl-3.0 | fc37842565bbf6d42f3db253a2371e4a | 55.822222 | 156 | 0.807196 | 4.501761 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/api/webauthn/Types.kt | 1 | 4063 | package pl.wendigo.chrome.api.webauthn
/**
*
*
* @link [WebAuthn#AuthenticatorId](https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-AuthenticatorId) type documentation.
*/
typealias AuthenticatorId = String
/**
*
*
* @link [WebAuthn#AuthenticatorProtocol](https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-AuthenticatorProtocol) type documentation.
*/
@kotlinx.serialization.Serializable
enum class AuthenticatorProtocol {
@kotlinx.serialization.SerialName("u2f")
U2F,
@kotlinx.serialization.SerialName("ctap2")
CTAP2;
}
/**
*
*
* @link [WebAuthn#Ctap2Version](https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-Ctap2Version) type documentation.
*/
@kotlinx.serialization.Serializable
enum class Ctap2Version {
@kotlinx.serialization.SerialName("ctap2_0")
CTAP2_0,
@kotlinx.serialization.SerialName("ctap2_1")
CTAP2_1;
}
/**
*
*
* @link [WebAuthn#AuthenticatorTransport](https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-AuthenticatorTransport) type documentation.
*/
@kotlinx.serialization.Serializable
enum class AuthenticatorTransport {
@kotlinx.serialization.SerialName("usb")
USB,
@kotlinx.serialization.SerialName("nfc")
NFC,
@kotlinx.serialization.SerialName("ble")
BLE,
@kotlinx.serialization.SerialName("cable")
CABLE,
@kotlinx.serialization.SerialName("internal")
INTERNAL;
}
/**
*
*
* @link [WebAuthn#VirtualAuthenticatorOptions](https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-VirtualAuthenticatorOptions) type documentation.
*/
@kotlinx.serialization.Serializable
data class VirtualAuthenticatorOptions(
/**
*
*/
val protocol: AuthenticatorProtocol,
/**
* Defaults to ctap2_0. Ignored if |protocol| == u2f.
*/
val ctap2Version: Ctap2Version? = null,
/**
*
*/
val transport: AuthenticatorTransport,
/**
* Defaults to false.
*/
val hasResidentKey: Boolean? = null,
/**
* Defaults to false.
*/
val hasUserVerification: Boolean? = null,
/**
* If set to true, the authenticator will support the largeBlob extension.
https://w3c.github.io/webauthn#largeBlob
Defaults to false.
*/
val hasLargeBlob: Boolean? = null,
/**
* If set to true, tests of user presence will succeed immediately.
Otherwise, they will not be resolved. Defaults to true.
*/
val automaticPresenceSimulation: Boolean? = null,
/**
* Sets whether User Verification succeeds or fails for an authenticator.
Defaults to false.
*/
val isUserVerified: Boolean? = null
)
/**
*
*
* @link [WebAuthn#Credential](https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-Credential) type documentation.
*/
@kotlinx.serialization.Serializable
data class Credential(
/**
*
*/
val credentialId: String,
/**
*
*/
val isResidentCredential: Boolean,
/**
* Relying Party ID the credential is scoped to. Must be set when adding a
credential.
*/
val rpId: String? = null,
/**
* The ECDSA P-256 private key in PKCS#8 format. (Encoded as a base64 string when passed over JSON)
*/
val privateKey: String,
/**
* An opaque byte sequence with a maximum size of 64 bytes mapping the
credential to a specific user. (Encoded as a base64 string when passed over JSON)
*/
val userHandle: String? = null,
/**
* Signature counter. This is incremented by one for each successful
assertion.
See https://w3c.github.io/webauthn/#signature-counter
*/
val signCount: Int,
/**
* The large blob associated with the credential.
See https://w3c.github.io/webauthn/#sctn-large-blob-extension (Encoded as a base64 string when passed over JSON)
*/
val largeBlob: String? = null
)
| apache-2.0 | 57dcc072e8562b7ee9c6dcf308133669 | 24.080247 | 165 | 0.662318 | 3.995084 | false | false | false | false |
slartus/4pdaClient-plus | app/src/main/java/org/softeg/slartus/forpdaplus/prefs/PreferencesActivity.kt | 1 | 52129 | package org.softeg.slartus.forpdaplus.prefs
import android.app.TimePickerDialog
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.Color
import android.media.RingtoneManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.preference.Preference
import android.preference.PreferenceFragment
import android.text.*
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import kotlinx.android.synthetic.main.device_edit.*
import org.softeg.slartus.forpdacommon.FileUtils
import org.softeg.slartus.forpdacommon.NotReportException
import org.softeg.slartus.forpdacommon.loadAssetsText
import org.softeg.slartus.forpdaplus.App
import org.softeg.slartus.forpdaplus.AppTheme.currentTheme
import org.softeg.slartus.forpdaplus.AppTheme.getThemeCssFileName
import org.softeg.slartus.forpdaplus.IntentActivity
import org.softeg.slartus.forpdaplus.R
import org.softeg.slartus.forpdacommon.FilePath
import org.softeg.slartus.forpdaplus.classes.InputFilterMinMax
import org.softeg.slartus.forpdaplus.common.AppLog
import org.softeg.slartus.forpdaplus.controls.OpenFileDialog
import org.softeg.slartus.forpdaplus.core.AppPreferences
import org.softeg.slartus.forpdaplus.db.NotesDbHelper
import org.softeg.slartus.forpdaplus.db.NotesTable
import org.softeg.slartus.forpdaplus.fragments.base.ProgressDialog
import org.softeg.slartus.forpdaplus.fragments.topic.ThemeFragment
import org.softeg.slartus.forpdaplus.listtemplates.ListCore
import org.softeg.slartus.forpdaplus.mainnotifiers.ForPdaVersionNotifier
import org.softeg.slartus.forpdaplus.mainnotifiers.NotifiersManager
import org.softeg.slartus.forpdaplus.repositories.NotesRepository
import org.softeg.slartus.forpdaplus.styles.CssStyle
import org.softeg.slartus.forpdaplus.styles.StyleInfoActivity
import org.softeg.slartus.hosthelper.HostHelper
import ru.slartus.http.PersistentCookieStore.Companion.getInstance
import timber.log.Timber
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
/**
* User: slinkin
* Date: 03.10.11
* Time: 10:47
*/
class PreferencesActivity : BasePreferencesActivity() {
//private EditText red, green, blue;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
fragmentManager.beginTransaction().replace(
android.R.id.content,
PrefsFragment()
).commitAllowingStateLoss()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
if (resultCode == RESULT_OK)
when (requestCode) {
NOTIFIERS_SERVICE_SOUND_REQUEST_CODE -> {
val uri =
intent?.getParcelableExtra<Uri>(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
Preferences.Notifications.sound = uri
}
PreferencesNotes.BACKUP_REQUEST_CODE -> {
PreferencesNotes.showBackupNotesBackupDialog(this)
}
PreferencesNotes.RESTORE_REQUEST_CODE -> {
PreferencesNotes.restoreNotes(this)
}
}
}
class PrefsFragment : PreferenceFragment(), Preference.OnPreferenceClickListener {
/* @Override
public void onActivityCreated(android.os.Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
PreferenceManager.setDefaultValues(getActivity(), R.xml.news_list_prefs, false);
}*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences)
// ((PreferenceScreen)findPreference("common")).addPreference(new CheckBoxPreference(getContext()));
findPreference("path.system_path").onPreferenceClickListener = this
findPreference("appstyle").onPreferenceClickListener = this
findPreference("accentColor").onPreferenceClickListener = this
findPreference("mainAccentColor").onPreferenceClickListener = this
findPreference("webViewFont").onPreferenceClickListener = this
findPreference("userBackground").onPreferenceClickListener = this
findPreference("About.AppVersion").onPreferenceClickListener = this
findPreference("cookies.delete").onPreferenceClickListener = this
findPreference("About.History").onPreferenceClickListener = this
findPreference("About.ShareIt").onPreferenceClickListener = this
findPreference("About.ShowTheme").onPreferenceClickListener = this
findPreference("About.CheckNewVersion").onPreferenceClickListener = this
findPreference("notifiers.silent_mode.start_time")?.let { preference ->
preference.onPreferenceClickListener = this
val clndr = Preferences.Notifications.SilentMode.startTime
preference.summary = String.format(
Locale.getDefault(),
"%02d:%02d",
clndr[Calendar.HOUR_OF_DAY],
clndr[Calendar.MINUTE]
)
}
findPreference("notifiers.silent_mode.end_time")?.let { preference ->
preference.onPreferenceClickListener = this
val clndr = Preferences.Notifications.SilentMode.endTime
preference.summary = String.format(
Locale.getDefault(),
"%02d:%02d",
clndr[Calendar.HOUR_OF_DAY],
clndr[Calendar.MINUTE]
)
}
findPreference("notifiers.service.use_sound")?.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _: Preference?, o: Any? ->
val useSound = o as Boolean?
findPreference("notifiers.service.is_default_sound").isEnabled = useSound!!
findPreference("notifiers.service.sound").isEnabled = useSound
true
}
findPreference("notifiers.service.is_default_sound")?.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _: Preference?, o: Any? ->
val isDefault = o as Boolean?
findPreference("notifiers.service.sound").isEnabled = !isDefault!!
true
}
findPreference("notifiers.service.sound").onPreferenceClickListener = this
findPreference("notes.backup").onPreferenceClickListener =
Preference.OnPreferenceClickListener {
PreferencesNotes.showBackupNotesBackupDialog(activity)
true
}
findPreference("notes.restore").onPreferenceClickListener =
Preference.OnPreferenceClickListener {
PreferencesNotes.restoreNotes(activity)
true
}
DonateActivity.setDonateClickListeners(this)
findPreference("showExitButton").onPreferenceClickListener = this
notesCategory()
}
private fun notesCategory() {
findPreference("notes.placement")?.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _, value ->
if (value == "remote") {
showNotesRemoteServerDialog()
}
true
}
findPreference("notes.remote.url")?.let { p ->
p.summary = Preferences.Notes.remoteUrl
p.onPreferenceClickListener = Preference.OnPreferenceClickListener {
showNotesRemoteServerDialog()
true
}
}
findPreference("notes.remote.help")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
IntentActivity.showInDefaultBrowser(
activity,
"https://github.com/slartus/4pdaClient-plus/wiki/Notes"
)
true
}
refreshNotesEnabled()
}
private fun refreshNotesEnabled() {
// findPreference("notes.remote.settings").isEnabled = !Preferences.Notes.isLocal()
// findPreference("notes.backup.category").isEnabled = Preferences.Notes.isLocal()
}
private fun setLoading(progress: Boolean) {
if (!isAdded) return
val PROGRESS_TAG = "PROGRESS_TAG"
val fragment = fragmentManager.findFragmentByTag(PROGRESS_TAG)
if (fragment != null && !progress) {
(fragment as ProgressDialog).dismissAllowingStateLoss()
fragmentManager.executePendingTransactions()
} else if (fragment == null && progress) {
ProgressDialog().show(fragmentManager, PROGRESS_TAG)
fragmentManager.executePendingTransactions()
}
}
private fun showNotesRemoteServerDialog() {
val inflater = (activity.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater)
val view = inflater.inflate(R.layout.input_notes_remote_url_layout, null as ViewGroup?)
val editText = view.findViewById<EditText>(R.id.edit_text)
editText.setText(Preferences.Notes.remoteUrl ?: "")
MaterialDialog.Builder(activity)
.title(R.string.notes_remote_url)
.customView(view, true)
.cancelable(true)
.positiveText(R.string.ok)
.negativeText(R.string.cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
try {
val baseUrl = editText?.text.toString()
setLoading(true)
NotesRepository.checUrlAsync(baseUrl, {
setLoading(false)
Preferences.Notes.setPlacement("remote")
Preferences.Notes.remoteUrl = baseUrl
findPreference("notes.remote.url")?.summary = baseUrl
refreshNotesEnabled()
}, {
setLoading(false)
Preferences.Notes.setPlacement("local")
findPreference("notes.placement")?.summary = resources
.getStringArray(R.array.NotesStoragePlacements)
.firstOrNull()
refreshNotesEnabled()
AppLog.e(
activity, NotReportException(
it.localizedMessage
?: it.message, it
)
)
})
} catch (ex: Throwable) {
AppLog.e(activity, ex)
}
}
.show()
}
override fun onPreferenceClick(preference: Preference): Boolean {
when (val key = preference.key) {
"path.system_path" -> {
showSelectDirDialog()
return true
}
"About.AppVersion" -> {
showAbout()
return true
}
"cookies.delete" -> {
showCookiesDeleteDialog()
return true
}
"About.History" -> {
showAboutHistory()
return true
}
"About.ShareIt" -> {
showShareIt()
return true
}
"About.ShowTheme" -> {
showTheme("271502")
return true
}
"appstyle" -> {
showStylesDialog()
return true
}
"accentColor" -> {
showAccentColorDialog()
return true
}
"mainAccentColor" -> {
showMainAccentColorDialog()
return true
}
"webViewFont" -> {
webViewFontDialog()
return true
}
"userBackground" -> {
pickUserBackground()
return true
}
"notifiers.service.sound" -> {
Preferences.Notifications.sound?.let {
pickRingtone(it)
}
return true
}
"notifiers.silent_mode.start_time" -> {
val calendar = Preferences.Notifications.SilentMode.startTime
TimePickerDialog(activity, { _: TimePicker?, hourOfDay: Int, minute: Int ->
Preferences.Notifications.SilentMode.setStartTime(hourOfDay, minute)
findPreference(key).summary =
String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute)
}, calendar[Calendar.HOUR_OF_DAY], calendar[Calendar.MINUTE], true).show()
return true
}
"notifiers.silent_mode.end_time" -> {
val endcalendar = Preferences.Notifications.SilentMode.endTime
TimePickerDialog(activity, { _: TimePicker?, hourOfDay: Int, minute: Int ->
Preferences.Notifications.SilentMode.setEndTime(hourOfDay, minute)
findPreference(key).summary =
String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute)
}, endcalendar[Calendar.HOUR_OF_DAY], endcalendar[Calendar.MINUTE], true).show()
return true
}
"About.CheckNewVersion" -> {
checkUpdates()
return true
}
}
return false
}
private fun checkUpdates() {
val notifiersManager = NotifiersManager()
ForPdaVersionNotifier(notifiersManager, 0, true).start(activity)
}
private fun setMenuItems() {
val preferences = preferenceManager.sharedPreferences
var items = (preferences.getString("selectedMenuItems", ListCore.DEFAULT_MENU_ITEMS)
?: ListCore.DEFAULT_MENU_ITEMS).split(",".toRegex()).toTypedArray()
val allItems = ListCore.getAllMenuBricks()
if (ListCore.checkIndex(items, allItems.size)) {
items = ListCore.DEFAULT_MENU_ITEMS.split(",".toRegex()).toTypedArray()
}
val selectedItems = arrayOfNulls<Int>(items.size)
for (i in items.indices) selectedItems[i] = items[i].toInt()
val namesArray = ArrayList<String>()
for (item in allItems) namesArray.add(item.title)
val finalItems = Array<Array<Int?>?>(1) { arrayOfNulls(1) }
finalItems[0] = selectedItems
MaterialDialog.Builder(activity)
.title(R.string.select_items)
.items(*namesArray.toTypedArray<CharSequence>())
.itemsCallbackMultiChoice(selectedItems) { _: MaterialDialog?, integers: Array<Int?>?, _: Array<CharSequence?>? ->
finalItems[0] = integers
true
}
.alwaysCallMultiChoiceCallback()
.positiveText(R.string.accept)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
if (finalItems.first()?.size ?: 0 == 0) return@onPositive
preferences.edit().putString(
"selectedMenuItems",
Arrays.toString(finalItems[0]).replace(" ", "").replace("[", "")
.replace("]", "")
).apply()
}
.neutralText(R.string.reset)
.onNeutral { _: MaterialDialog?, _: DialogAction? ->
preferences.edit().putString("selectedMenuItems", ListCore.DEFAULT_MENU_ITEMS)
.apply()
}
.show()
}
private fun pickUserBackground() {
MaterialDialog.Builder(activity)
.content(R.string.pick_image)
.positiveText(R.string.choose)
.negativeText(R.string.cancel)
.neutralText(R.string.reset)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
try {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
startActivityForResult(intent, MY_INTENT_CLICK)
} catch (ex: ActivityNotFoundException) {
Toast.makeText(
activity,
R.string.no_app_for_get_image_file,
Toast.LENGTH_LONG
).show()
} catch (ex: Exception) {
AppLog.e(activity, ex)
}
}
.onNeutral { _: MaterialDialog?, _: DialogAction? ->
App.getInstance().preferences
.edit()
.putString("userInfoBg", "")
.putBoolean("isUserBackground", false)
.apply()
}
.show()
}
private fun createImageFile(): File {
val timeStamp: String =
SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
return File.createTempFile(
"PHOTO_${timeStamp}_",
".jpg",
App.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
)
}
private fun copyFileToTemp(uri: Uri): String {
val context = App.getContext()
val fileName = FilePath.getFileName(context, uri)
val tempFile = createImageFile()
context.contentResolver.openInputStream(uri)?.buffered()?.use { inputStream ->
FileOutputStream(tempFile, false).use { outputStream ->
FileUtils.CopyStream(inputStream, outputStream)
}
}
return tempFile.absolutePath
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == RESULT_OK) {
if (requestCode == MY_INTENT_CLICK) {
data?.data?.let { selectedImageUri ->
val selectedImagePath =
FilePath.getPath(App.getContext(), selectedImageUri) ?: copyFileToTemp(
selectedImageUri
)
App.getInstance().preferences
.edit()
.putString("userInfoBg", selectedImagePath)
.putBoolean("isUserBackground", true)
.apply()
}
}
}
}
private fun webViewFontDialog() {
try {
val prefs = App.getInstance().preferences
val selected = intArrayOf(prefs.getInt("webViewFont", 0))
val name = arrayOf<CharSequence>("")
val dialogShowed = booleanArrayOf(false)
MaterialDialog.Builder(activity)
.title(R.string.choose_font)
.items(
App.getContext().getString(R.string.font_from_style),
App.getContext().getString(R.string.system_font),
App.getContext().getString(R.string.enter_font_name)
)
.itemsCallbackSingleChoice(selected[0]) { _: MaterialDialog?, _: View?, which: Int, _: CharSequence? ->
selected[0] = which
when (which) {
0 -> name[0] = ""
1 -> name[0] = "inherit"
2 -> {
if (dialogShowed[0]) return@itemsCallbackSingleChoice true
dialogShowed[0] = true
MaterialDialog.Builder(activity)
.inputType(InputType.TYPE_CLASS_TEXT)
.input(
App.getContext().getString(R.string.font_name),
prefs.getString("webViewFontName", "")
) { _: MaterialDialog?, input: CharSequence -> name[0] = input }
.positiveText(R.string.ok)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
prefs.edit()
.putString("webViewFontName", name[0].toString())
.apply()
}
.show()
}
}
true
}
.alwaysCallSingleChoiceCallback()
.positiveText(R.string.accept)
.negativeText(R.string.cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
prefs.edit().putString("webViewFontName", name[0].toString())
.putInt("webViewFont", selected[0]).apply()
}
.show()
} catch (ex: Exception) {
AppLog.e(activity, ex)
}
}
private fun showMainAccentColorDialog() {
try {
val prefs = App.getInstance().preferences
val string = prefs.getString("mainAccentColor", "pink")
var position = -1
when (string) {
AppPreferences.ACCENT_COLOR_PINK_NAME -> position = 0
AppPreferences.ACCENT_COLOR_BLUE_NAME -> position = 1
AppPreferences.ACCENT_COLOR_GRAY_NAME -> position = 2
}
val selected = intArrayOf(0)
MaterialDialog.Builder(activity)
.title(R.string.pick_accent_color)
.items(
App.getContext().getString(R.string.blue),
App.getContext().getString(R.string.pink),
App.getContext().getString(R.string.gray)
)
.itemsCallbackSingleChoice(position) { _: MaterialDialog?, _: View?, which: Int, _: CharSequence? ->
selected[0] = which
true
}
.alwaysCallSingleChoiceCallback()
.positiveText(R.string.accept)
.negativeText(R.string.cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
when (selected[0]) {
0 -> {
prefs.edit().putString("mainAccentColor", AppPreferences.ACCENT_COLOR_PINK_NAME).apply()
if (!prefs.getBoolean("accentColorEdited", false)) {
prefs.edit()
.putInt("accentColor", Color.rgb(2, 119, 189))
.putInt("accentColorPressed", Color.rgb(0, 89, 159))
.apply()
}
}
1 -> {
prefs.edit().putString("mainAccentColor", AppPreferences.ACCENT_COLOR_BLUE_NAME).apply()
if (!prefs.getBoolean("accentColorEdited", false)) {
prefs.edit()
.putInt("accentColor", Color.rgb(233, 30, 99))
.putInt("accentColorPressed", Color.rgb(203, 0, 69))
.apply()
}
}
2 -> {
prefs.edit().putString("mainAccentColor", AppPreferences.ACCENT_COLOR_GRAY_NAME).apply()
if (!prefs.getBoolean("accentColorEdited", false)) {
prefs.edit()
.putInt("accentColor", Color.rgb(117, 117, 117))
.putInt("accentColorPressed", Color.rgb(87, 87, 87))
.apply()
}
}
}
}
.show()
} catch (ex: Exception) {
AppLog.e(activity, ex)
}
}
private fun showAccentColorDialog() {
try {
val prefs = App.getInstance().preferences
val prefColor =
prefs.getInt("accentColor", Color.rgb(2, 119, 189)).toString().toLong(10)
.toInt()
//int prefColor = (int) Long.parseLong(String.valueOf(prefs.getInt("accentColor", Color.rgb(96, 125, 139))), 10);
val colors = intArrayOf(
prefColor shr 16 and 0xFF,
prefColor shr 8 and 0xFF,
prefColor and 0xFF
)
val inflater =
(activity.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater)
val view = inflater.inflate(R.layout.color_editor, null as ViewGroup?)
val redTxt = view.findViewById<EditText>(R.id.redText)
val greenTxt = view.findViewById<EditText>(R.id.greenText)
val blueTxt = view.findViewById<EditText>(R.id.blueText)
val preview = view.findViewById<View>(R.id.preview)
val red = view.findViewById<SeekBar>(R.id.red)
val green = view.findViewById<SeekBar>(R.id.green)
val blue = view.findViewById<SeekBar>(R.id.blue)
redTxt.filters = arrayOf<InputFilter>(InputFilterMinMax("0", "255"))
greenTxt.filters = arrayOf<InputFilter>(InputFilterMinMax("0", "255"))
blueTxt.filters = arrayOf<InputFilter>(InputFilterMinMax("0", "255"))
redTxt.setText(colors[0].toString())
greenTxt.setText(colors[1].toString())
blueTxt.setText(colors[2].toString())
red.progress = colors[0]
green.progress = colors[1]
blue.progress = colors[2]
preview.setBackgroundColor(Color.rgb(colors[0], colors[1], colors[2]))
redTxt.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
if (redTxt.text.toString() == "") {
colors[0] = 0
} else {
colors[0] = redTxt.text.toString().toInt()
}
preview.setBackgroundColor(Color.rgb(colors[0], colors[1], colors[2]))
red.progress = colors[0]
redTxt.setSelection(redTxt.text.length)
}
})
greenTxt.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
if (greenTxt.text.toString() == "") {
colors[1] = 0
} else {
colors[1] = greenTxt.text.toString().toInt()
}
preview.setBackgroundColor(Color.rgb(colors[0], colors[1], colors[2]))
green.progress = colors[1]
greenTxt.setSelection(greenTxt.text.length)
}
})
blueTxt.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
if (blueTxt.text.toString() == "") {
colors[2] = 0
} else {
colors[2] = blueTxt.text.toString().toInt()
}
preview.setBackgroundColor(Color.rgb(colors[0], colors[1], colors[2]))
blue.progress = colors[2]
blueTxt.setSelection(blueTxt.text.length)
}
})
red.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar,
progress: Int,
fromUser: Boolean
) {
redTxt.setText(progress.toString())
preview.setBackgroundColor(Color.rgb(progress, colors[1], colors[2]))
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {
colors[0] = seekBar.progress
}
})
green.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar,
progress: Int,
fromUser: Boolean
) {
greenTxt.setText(progress.toString())
preview.setBackgroundColor(Color.rgb(colors[0], progress, colors[2]))
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {
colors[1] = seekBar.progress
}
})
blue.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar,
progress: Int,
fromUser: Boolean
) {
blueTxt.setText(progress.toString())
preview.setBackgroundColor(Color.rgb(colors[0], colors[1], progress))
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {
colors[2] = seekBar.progress
}
})
MaterialDialog.Builder(activity)
.title(R.string.color)
.customView(view, true)
.positiveText(R.string.accept)
.negativeText(R.string.cancel)
.neutralText(R.string.reset)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
val colorPressed =
intArrayOf(colors[0] - 30, colors[1] - 30, colors[2] - 30)
if (colorPressed[0] < 0) colorPressed[0] = 0
if (colorPressed[1] < 0) colorPressed[1] = 0
if (colorPressed[2] < 0) colorPressed[2] = 0
if (Color.rgb(
colors[0],
colors[1],
colors[2]
) != prefs.getInt("accentColor", Color.rgb(2, 119, 189))
) {
prefs.edit().putBoolean("accentColorEdited", true).apply()
}
prefs.edit()
.putInt("accentColor", Color.rgb(colors[0], colors[1], colors[2]))
.putInt(
"accentColorPressed",
Color.rgb(colorPressed[0], colorPressed[1], colorPressed[2])
)
.apply()
}
.onNeutral { _: MaterialDialog?, _: DialogAction? ->
prefs.edit()
.putInt("accentColor", Color.rgb(2, 119, 189))
.putInt("accentColorPressed", Color.rgb(0, 89, 159))
.putBoolean(
"accentColorEdited",
false
) //.putInt("accentColor", Color.rgb(96, 125, 139))
//.putInt("accentColorPressed", Color.rgb(76, 95, 109))
.apply()
}
.show()
} catch (ex: Exception) {
AppLog.e(activity, ex)
}
}
/*private int PICK_IMAGE_REQUEST = 1;
private void pickUserBackground() {
try {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/ *");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
} catch (Exception ex) {
AppLog.e(getActivity(), ex);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
App.getInstance().getPreferences()
.edit()
.putString("userBackground", uri.toString())
.commit();
}
}*/
private fun showStylesDialog() {
try {
val currentValue = currentTheme
val newStyleNames = ArrayList<CharSequence>()
val newstyleValues = ArrayList<CharSequence>()
getStylesList(activity, newStyleNames, newstyleValues)
val selected = intArrayOf(newstyleValues.indexOf(currentValue))
MaterialDialog.Builder(activity)
.title(R.string.app_theme)
.cancelable(true)
.items(*newStyleNames.toTypedArray())
.itemsCallbackSingleChoice(newstyleValues.indexOf(currentValue)) { _: MaterialDialog?, _: View?, i: Int, _: CharSequence? ->
selected[0] = i
true // allow selection
}
.alwaysCallSingleChoiceCallback()
.positiveText(getString(R.string.AcceptStyle))
.neutralText(getString(R.string.Information))
.onPositive { _: MaterialDialog?, _: DialogAction? ->
if (selected[0] == -1) {
Toast.makeText(
activity,
getString(R.string.ChooseStyle),
Toast.LENGTH_LONG
).show()
return@onPositive
}
App.getInstance().preferences
.edit()
.putString("appstyle", newstyleValues[selected[0]].toString())
.apply()
}
.onNeutral { _: MaterialDialog?, _: DialogAction? ->
if (selected[0] == -1) {
Toast.makeText(
activity,
getString(R.string.ChooseStyle),
Toast.LENGTH_LONG
).show()
return@onNeutral
}
var stylePath = newstyleValues[selected[0]].toString()
stylePath = getThemeCssFileName(stylePath)
val xmlPath = stylePath.replace(".css", ".xml")
val cssStyle = CssStyle.parseStyle(activity, xmlPath)
if (!cssStyle.ExistsInfo) {
Toast.makeText(
activity,
getString(R.string.StyleDoesNotContainDesc),
Toast.LENGTH_SHORT
).show()
return@onNeutral
}
//dialogInterface.dismiss();
StyleInfoActivity.showStyleInfo(
activity,
newstyleValues[selected[0]].toString()
)
}
.show()
} catch (ex: Exception) {
AppLog.e(activity, ex)
}
}
private fun showAbout() {
val text = """
<b>Неофициальный клиент для сайта <a href="https://www.4pda.ru">4pda.ru</a></b><br/><br/>
<b>Автор: </b> Артём Слинкин aka <a href="https://4pda.ru/forum/index.php?showuser=236113">slartus</a><br/>
<b>E-mail:</b> <a href="mailto:[email protected]">[email protected]</a><br/><br/>
<b>Разработчик(v3.x): </b> Евгений Низамиев aka <a href="https://4pda.ru/forum/index.php?showuser=2556269">Radiation15</a><br/>
<b>E-mail:</b> <a href="mailto:[email protected]">[email protected]</a><br/><br/>
<b>Разработчик(v3.x):</b> Александр Тайнюк aka <a href="https://4pda.ru/forum/index.php?showuser=1726458">iSanechek</a><br/>
<b>E-mail:</b> <a href="mailto:[email protected]">[email protected]</a><br/><br/>
<b>Помощник разработчиков: </b> Алексей Шолохов aka <a href="https://4pda.ru/forum/index.php?showuser=96664">Морфий</a>
<b>E-mail:</b> <a href="mailto:[email protected]">[email protected]</a><br/><br/>
<b>Благодарности: </b> <br/>
* <b><a href="https://4pda.ru/forum/index.php?showuser=1657987">__KoSyAk__</a></b> Иконка программы<br/>
* <b>Пользователям 4pda</b> (тестирование, идеи, поддержка)
<br/><br/>Copyright 2011-2016 Artem Slinkin <[email protected]>
""".trimIndent().replace("4pda.ru", HostHelper.host)
@Suppress("DEPRECATION")
MaterialDialog.Builder(activity)
.title(programFullName)
.content(Html.fromHtml(text))
.positiveText(R.string.ok)
.show()
//TextView textView = (TextView) dialog.findViewById(android.R.id.message);
//textView.setTextSize(12);
//textView.setMovementMethod(LinkMovementMethod.getInstance());
}
private fun pickRingtone(defaultSound: Uri) {
val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION)
intent.putExtra(
RingtoneManager.EXTRA_RINGTONE_TITLE,
App.getContext().getString(R.string.pick_audio)
)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, defaultSound)
if (activity != null) activity.startActivityForResult(
intent,
NOTIFIERS_SERVICE_SOUND_REQUEST_CODE
)
}
private fun showTheme(themeId: String) {
activity.finish()
ThemeFragment.showTopicById(themeId)
}
private fun showShareIt() {
val sendMailIntent = Intent(Intent.ACTION_SEND)
sendMailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.Recomend))
sendMailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.RecommendText))
sendMailIntent.type = "text/plain"
startActivity(Intent.createChooser(sendMailIntent, getString(R.string.SendBy_)))
}
private fun showAboutHistory() {
val content = kotlin.runCatching {
App.getInstance().loadAssetsText("history.txt")
}.onFailure {
Timber.e(it)
}.getOrNull() ?: "Ошибка загрузки ресурса"
MaterialDialog.Builder(activity)
.title(getString(R.string.ChangesHistory))
.content(content)
.positiveText(R.string.ok)
.show()
//TextView textView = (TextView) dialog.findViewById(android.R.id.message);
//textView.setTextSize(12);
}
private fun showCookiesDeleteDialog() {
MaterialDialog.Builder(activity)
.title(getString(R.string.ConfirmTheAction))
.content(getString(R.string.SureDeleteFile))
.cancelable(true)
.positiveText(getString(R.string.Delete))
.negativeText(getString(R.string.no))
.onPositive { _: MaterialDialog?, _: DialogAction? ->
try {
val f = File(cookieFilePath)
if (!f.exists()) {
Toast.makeText(
activity, getString(R.string.CookiesFileNotFound) +
": " + cookieFilePath, Toast.LENGTH_LONG
).show()
}
if (f.delete()) Toast.makeText(
activity, getString(R.string.CookiesFileDeleted) +
": " + cookieFilePath, Toast.LENGTH_LONG
).show() else Toast.makeText(
activity, getString(R.string.FailedDeleteCookies) +
": " + cookieFilePath, Toast.LENGTH_LONG
).show()
} catch (ex: Exception) {
AppLog.e(activity, ex)
}
}
.show()
}
private fun showSelectDirDialog() {
val inflater = (activity.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater)
val view = inflater.inflate(R.layout.dir_select_dialog, null as ViewGroup?)
val rbInternal = view.findViewById<RadioButton>(R.id.rbInternal)
val rbExternal = view.findViewById<RadioButton>(R.id.rbExternal)
val rbCustom = view.findViewById<RadioButton>(R.id.rbCustom)
val txtPath = view.findViewById<EditText>(R.id.txtPath)
txtPath.setText(Preferences.System.systemDir)
val checkedChangeListener =
CompoundButton.OnCheckedChangeListener { compoundButton: CompoundButton, b: Boolean ->
if (b) {
when (compoundButton.id) {
rbInternal.id -> {
txtPath.setText(App.getInstance().filesDir.path)
txtPath.isEnabled = false
}
rbExternal.id -> {
try {
txtPath.setText(
App.getInstance().getExternalFilesDir(null)?.path
?: ""
)
txtPath.isEnabled = false
} catch (ex: Throwable) {
AppLog.e(activity, ex)
}
}
rbCustom.id -> {
txtPath.isEnabled = true
}
}
}
}
rbInternal.setOnCheckedChangeListener(checkedChangeListener)
rbExternal.setOnCheckedChangeListener(checkedChangeListener)
rbCustom.setOnCheckedChangeListener(checkedChangeListener)
MaterialDialog.Builder(activity)
.title(R.string.path_to_data)
.customView(view, true)
.cancelable(true)
.positiveText(R.string.ok)
.negativeText(R.string.cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
try {
var dir = txtPath.text.toString()
dir = dir.replace("/", File.separator)
FileUtils.checkDirPath(dir)
Preferences.System.systemDir = dir
} catch (ex: Throwable) {
AppLog.e(activity, ex)
}
}
.show()
}
companion object {
private const val MY_INTENT_CLICK = 302
}
}
public override fun onStop() {
super.onStop()
App.resStartNotifierServices()
getInstance(App.getInstance()).reload()
}
companion object {
private val NOTIFIERS_SERVICE_SOUND_REQUEST_CODE = App.getInstance().uniqueIntValue
private val appCookiesPath: String
get() = Preferences.System.systemDir + "4pda_cookies"
@JvmStatic
val cookieFilePath: String
get() {
var res = App.getInstance().preferences.getString("cookies.path", "") ?: ""
if (TextUtils.isEmpty(res)) res = appCookiesPath
return res.replace("/", File.separator)
}
@JvmStatic
fun getStylesList(
context: Context,
newStyleNames: ArrayList<CharSequence>,
newstyleValues: ArrayList<CharSequence>
) {
var xmlPath: String
var cssStyle: CssStyle
val styleNames = context.resources.getStringArray(R.array.appthemesArray)
val styleValues = context.resources.getStringArray(R.array.appthemesValues)
for (i in styleNames.indices) {
var styleName: CharSequence = styleNames[i]
val styleValue: CharSequence = styleValues[i]
xmlPath = getThemeCssFileName(styleValue.toString()).replace(".css", ".xml")
.replace("/android_asset/", "")
cssStyle = CssStyle.parseStyleFromAssets(context, xmlPath)
if (cssStyle.ExistsInfo) styleName = cssStyle.Title
newStyleNames.add(styleName)
newstyleValues.add(styleValue)
}
val file = File(Preferences.System.systemDir + "styles/")
getStylesList(newStyleNames, newstyleValues, file)
}
private fun getStylesList(
newStyleNames: ArrayList<CharSequence>,
newstyleValues: ArrayList<CharSequence>, file: File
) {
var cssPath: String
var xmlPath: String
var cssStyle: CssStyle
if (file.exists()) {
val cssFiles = file.listFiles() ?: return
for (cssFile in cssFiles) {
if (cssFile.isDirectory) {
getStylesList(newStyleNames, newstyleValues, cssFile)
continue
}
cssPath = cssFile.path
if (!cssPath.toLowerCase(Locale.getDefault()).endsWith(".css")) continue
xmlPath = cssPath.replace(".css", ".xml")
cssStyle = CssStyle.parseStyleFromFile(xmlPath)
val title = cssStyle.Title
newStyleNames.add(title)
newstyleValues.add(cssPath)
}
}
}
@JvmStatic
val packageInfo: PackageInfo
get() {
val packageName = App.getInstance().packageName
try {
return App.getInstance().packageManager.getPackageInfo(
packageName, PackageManager.GET_META_DATA
)
} catch (e1: PackageManager.NameNotFoundException) {
AppLog.e(App.getInstance(), e1)
}
val packageInfo = PackageInfo()
packageInfo.packageName = packageName
packageInfo.versionName = "unknown"
packageInfo.versionCode = 1
return packageInfo
}
val programFullName: String
get() {
var programName = App.getInstance().getString(R.string.app_name)
val pInfo = packageInfo
programName += " v" + pInfo.versionName + " c" + pInfo.versionCode
return programName
}
}
} | apache-2.0 | 561fe9d7ee7a3a69632dbf3930fae72f | 45.804328 | 144 | 0.490858 | 5.636946 | false | false | false | false |
UnsignedInt8/d.Wallet-Core | android/lib/src/main/java/dWallet/core/bitcoin/application/bip32/ExtendedKey.kt | 1 | 10372 | package dwallet.core.bitcoin.application.bip32
import dwallet.core.bitcoin.application.wallet.Address
import dwallet.core.extensions.toHexString
import org.spongycastle.util.Arrays
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import java.io.ByteArrayOutputStream
import kotlin.experimental.and
import kotlin.experimental.or
/**
* Created by Jesion on 2015-01-14.
*
* ExtendedKey class represents BIP32 key, which is able to provide derived keys according to the spec.
* It composes ECKey class which is responsible for providing Elliptic Curve transformations required to support key derivation.
*/
class ExtendedKey {
var chainCode: ByteArray? = null
private set
var ecKey: ECKey? = null
private set
private var sequence: Int = 0
private var depth: Int = 0
private var parentFingerprint: Int = 0
/**
* Constructing a derived key
*
* @param keyHash - Derived key hash
* @param compressed - Indicates if public key is compressed for EC calculations
* @param sequence - Derivation sequence
* @param depth - Derivation depth
* @param parentFingerprint - Parent key fingerprint
* @param ecKey - Parent ECKey
*/
constructor(keyHash: ByteArray, compressed: Boolean = true, sequence: Int = 0, depth: Int = 0, parentFingerprint: Int = 0, ecKey: ECKey? = null) {
//key hash left side, private key base
val l = Arrays.copyOfRange(keyHash, 0, 32)
//key hash right side, chaincode
val r = Arrays.copyOfRange(keyHash, 32, 64)
//r is chainCode bytes
this.chainCode = r
this.sequence = sequence
this.depth = depth
this.parentFingerprint = parentFingerprint
if (ecKey != null) {
this.ecKey = ECKey(l, ecKey)
} else {
this.ecKey = ECKey(l, compressed)
}
}
/**
* Constructing a parsed key
*
* @param chainCode
* @param sequence
* @param depth
* @param parentFingerprint
* @param ecKey
*/
constructor(chainCode: ByteArray, sequence: Int, depth: Int, parentFingerprint: Int, ecKey: ECKey) {
this.chainCode = chainCode
this.sequence = sequence
this.depth = depth
this.parentFingerprint = parentFingerprint
this.ecKey = ecKey
}
@Throws(Exception::class)
fun serializePublic(): String {
return ExtendedKeySerializer().serialize(xpub,
this.depth,
this.parentFingerprint,
this.sequence,
this.chainCode,
this.ecKey!!.public!!
)
}
@Throws(Exception::class)
fun serializePrivate(): String {
if (ecKey?.hasPrivate() == true) {
return ExtendedKeySerializer().serialize(xprv,
this.depth,
this.parentFingerprint,
this.sequence,
this.chainCode,
this.ecKey!!.private!!
)
}
throw Exception("This is a public key only. Can't serialize a private key")
}
/**
* Derives a child key from a valid instance of key
* Currently only supports simple derivation (m/i', where m is master and i is level-1 derivation of master)
* Key derivation spec is much richer and includes accounts with internal/external key chains as well, due to be implemented
* @return
*/
@Throws(Exception::class)
fun derive(i: Int): ExtendedKey {
return getChild(i)
}
@Throws(Exception::class)
private fun getChild(i: Int): ExtendedKey {
//Hmac hashing algo, which is using parents chainCode as its key
val mac = Mac.getInstance("HmacSHA512", "SC")
val key = SecretKeySpec(chainCode, "HmacSHA512")
mac.init(key)
//treating master's pub key as base... not sure why but simple m/i derivation goes by pub only but has to be tested a lot
val pub = this.ecKey!!.public!!
val child = ByteArray(pub.size + 4)
System.arraycopy(pub, 0, child, 0, pub.size)
//now some byte shifting
child[pub.size] = (i.ushr(24) and 0xff).toByte()
child[pub.size + 1] = (i.ushr(16) and 0xff).toByte()
child[pub.size + 2] = (i.ushr(8) and 0xff).toByte()
child[pub.size + 3] = (i and 0xff).toByte()
val keyHash = mac.doFinal(child)
return ExtendedKey(keyHash, this.ecKey!!.isCompressed, i, this.depth + 1, fingerPrint, this.ecKey)
}
/**
* Gets an Integer representation of master public key hash
* @return
*/
val fingerPrint: Int
get() {
var fingerprint = 0
for (i in 0..3) {
fingerprint = fingerprint shl 8
fingerprint = fingerprint or ((this.ecKey!!.publicKeyHash!![i] and 0xff.toByte()).toInt())
}
return fingerprint
}
/**
* Gets a Wallet Import Format - a Base58 String representation of private key that can be imported to
* - Electrum Wallet : if we are working with compressed public keys
* - Armory Wallet : if we are working with uncompressed public keys
* allowing to sweep funds sent to a corresponding address.
* There is no easy way to support both, I would rather expect Armory to upgrade and support compressed keys
* By default we are working with compressed keys, supporting Electrum wallet (see constructor of this class)
* @throws Exception
*/
val wif: String
@Throws(Exception::class)
get() = this.ecKey!!.wif
/**
* Gets an Address
*/
fun toAddress(netId: ByteArray) = Address(public, netId)
/**
* Gets public key bytes
*/
val public: ByteArray
get() = this.ecKey!!.public!!
/**
* Gets public key hexadecimal string
*/
val publicHex: String
get() = public.toHexString()
override fun equals(obj: Any?): Boolean {
return if (obj is ExtendedKey) {
ecKey!!.equals(obj.ecKey)
&& Arrays.areEqual(chainCode, obj.chainCode)
&& depth == obj.depth
&& parentFingerprint == obj.parentFingerprint
&& sequence == obj.sequence
} else false
}
private inner class ExtendedKeySerializer {
/**
*
* @param version
* @param depth
* @param parentFingerprint
* @param sequence - Key derivation sequence
* @param chainCode
* @param keyBytes - Actual key bytes coming from the Elliptic Curve
* @return
* @throws Exception
*/
@Throws(Exception::class)
fun serialize(version: ByteArray,
depth: Int,
parentFingerprint: Int,
sequence: Int,
chainCode: ByteArray?,
keyBytes: ByteArray): String {
val out = ByteArrayOutputStream()
out.write(version)
out.write(depth and 0xff)
out.write(parentFingerprint.ushr(24) and 0xff)
out.write(parentFingerprint.ushr(16) and 0xff)
out.write(parentFingerprint.ushr(8) and 0xff)
out.write(parentFingerprint and 0xff)
out.write(sequence.ushr(24) and 0xff)
out.write(sequence.ushr(16) and 0xff)
out.write(sequence.ushr(8) and 0xff)
out.write(sequence and 0xff)
out.write(chainCode)
if (version == xprv) {
out.write(0x00)
}
out.write(keyBytes)
return ByteUtil.toBase58WithChecksum(out.toByteArray());
}
}
object ExtendedKeyParser {
@Throws(Exception::class)
fun parse(serialized: String, compressed: Boolean): ExtendedKey {
val data = ByteUtil.fromBase58WithChecksum(serialized)
if (data.size != 78) {
throw Exception("Invalid extended key")
}
val type = Arrays.copyOf(data, 4)
val hasPrivate: Boolean
if (Arrays.areEqual(type, xprv)) {
hasPrivate = true
} else if (Arrays.areEqual(type, xpub)) {
hasPrivate = false
} else {
throw Exception("Invalid or unsupported key type")
}
val depth = data[4] and 0xff.toByte()
var parentFingerprint = data[5] and 0xff.toByte()
parentFingerprint = (parentFingerprint.toInt() shl 8).toByte()
parentFingerprint = parentFingerprint or (data[6] and 0xff.toByte())
parentFingerprint = (parentFingerprint.toInt() shl 8).toByte()
parentFingerprint = parentFingerprint or (data[7] and 0xff.toByte())
parentFingerprint = (parentFingerprint.toInt() shl 8).toByte()
parentFingerprint = parentFingerprint or (data[8] and 0xff.toByte())
var sequence = data[9] and 0xff.toByte()
sequence = (sequence.toInt() shl 8).toByte()
sequence = sequence or (data[10] and 0xff.toByte())
sequence = (sequence.toInt() shl 8).toByte()
sequence = sequence or (data[11] and 0xff.toByte())
sequence = (sequence.toInt() shl 8).toByte()
sequence = sequence or (data[12] and 0xff.toByte())
val chainCode = Arrays.copyOfRange(data, 13, 13 + 32)
val keyBytes = Arrays.copyOfRange(data, 13 + 32, data.size)
val ecKey = ECKey(keyBytes, compressed, hasPrivate)
return ExtendedKey(chainCode, sequence.toInt(), depth.toInt(), parentFingerprint.toInt(), ecKey)
}
}
companion object {
private val xpub = byteArrayOf(0x04, 0x88.toByte(), 0xB2.toByte(), 0x1E.toByte())
private val xprv = byteArrayOf(0x04, 0x88.toByte(), 0xAD.toByte(), 0xE4.toByte())
/**
* Takes a serialized key (public or private) and constructs an instance of ExtendedKey
*
* @param serialized
* @param compressed
* @return
* @throws Exception
*/
@Throws(Exception::class)
fun parse(serialized: String, compressed: Boolean): ExtendedKey {
return ExtendedKeyParser.parse(serialized, compressed)
}
}
} | gpl-3.0 | ff76ff1fa00d02623c7c08512f89bbd4 | 35.269231 | 150 | 0.59381 | 4.417376 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/layer/supporting/FlatLayerRenderBuffer.kt | 1 | 3401 | package com.teamwizardry.librarianlib.facade.layer.supporting
import com.teamwizardry.librarianlib.albedo.base.buffer.BaseRenderBuffer
import com.teamwizardry.librarianlib.albedo.buffer.VertexBuffer
import com.teamwizardry.librarianlib.albedo.shader.Shader
import com.teamwizardry.librarianlib.albedo.shader.attribute.VertexLayoutElement
import com.teamwizardry.librarianlib.albedo.shader.uniform.SamplerUniform
import com.teamwizardry.librarianlib.albedo.shader.uniform.Uniform
import com.teamwizardry.librarianlib.core.util.Client
import net.minecraft.util.Identifier
internal class FlatLayerRenderBuffer(vbo: VertexBuffer) : BaseRenderBuffer<FlatLayerRenderBuffer>(vbo) {
val layerImage = +Uniform.sampler2D.create("LayerImage")
val maskImage = +Uniform.sampler2D.create("MaskImage")
val alphaMultiply = +Uniform.float.create("AlphaMultiply")
val maskMode = +Uniform.int.create("MaskMode")
val renderMode = +Uniform.int.create("RenderMode")
private val texelCoordAttribute = +VertexLayoutElement("TexelCoord", VertexLayoutElement.FloatFormat.FLOAT, 2, false)
init {
bind(shader)
}
fun texel(x: Float, y: Float): FlatLayerRenderBuffer {
start(texelCoordAttribute)
putFloat(x)
putFloat(y)
return this
}
override fun setupState() {
super.setupState()
}
companion object {
val shader = Shader.build("flat_layer")
.vertex(Identifier("liblib-facade:flat_layer.vert"))
.fragment(Identifier("liblib-facade:flat_layer.frag"))
.build()
val SHARED = FlatLayerRenderBuffer(VertexBuffer.SHARED)
}
}
public enum class MaskMode {
/**
* No masking will occur
*/
NONE,
/**
* The layer's alpha is multiplied by the mask's alpha. i.e. transparent mask = transparent layer.
*/
ALPHA,
/**
* The layer's alpha is multiplied by the mask's luma (brightness), blended with a white background.
* i.e. dark mask = transparent layer, transparent mask = white background = opaque layer.
*/
LUMA_ON_WHITE,
/**
* The layer's alpha is multiplied by the mask's luma (brightness), blended with a black background.
* i.e. dark mask = transparent layer, transparent mask = black background = transparent layer.
*/
LUMA_ON_BLACK,
/**
* The inverse of [ALPHA]. i.e. transparent mask = opaque layer.
*/
INV_ALPHA,
/**
* The inverse of [LUMA_ON_WHITE]. i.e. dark mask = opaque layer,
* transparent mask = white background = transparent layer.
*/
INV_LUMA_ON_WHITE,
/**
* The inverse of [LUMA_ON_BLACK]. i.e. dark mask = opaque layer,
* transparent mask = black background = opaque layer.
*/
INV_LUMA_ON_BLACK;
}
public enum class RenderMode {
/**
* The default, this renders directly to the current FBO
*/
DIRECT,
/**
* The default when rendering to a texture, this renders onto an FBO which is then rendered onto the screen. This
* mode uses a technique that avoids issues of lost resolution due to scale.
*/
RENDER_TO_FBO,
/**
* Draws the layer to a texture at a native resolution multiple (one unit = N texture pixels) and draws that to a
* quad. This mode can lead to lost resolution, however sometimes this is the desired effect.
*/
RENDER_TO_QUAD
}
| lgpl-3.0 | a8267da3f3f7346d23d89104c46d3eac | 32.019417 | 121 | 0.684211 | 4.152625 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/StoryViewerFragment.kt | 1 | 7270 | package org.thoughtcrime.securesms.stories.viewer
import android.graphics.RenderEffect
import android.graphics.Shader
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.stories.StoryViewerArgs
import org.thoughtcrime.securesms.stories.viewer.first.StoryFirstTimeNavigationFragment
import org.thoughtcrime.securesms.stories.viewer.page.StoryViewerPageArgs
import org.thoughtcrime.securesms.stories.viewer.page.StoryViewerPageFragment
import org.thoughtcrime.securesms.stories.viewer.reply.StoriesSharedElementCrossFaderView
import org.thoughtcrime.securesms.util.LifecycleDisposable
/**
* Fragment which manages a vertical pager fragment of stories.
*/
class StoryViewerFragment :
Fragment(R.layout.stories_viewer_fragment),
StoryViewerPageFragment.Callback,
StoriesSharedElementCrossFaderView.Callback {
private val onPageChanged = OnPageChanged()
private lateinit var storyPager: ViewPager2
private val viewModel: StoryViewerViewModel by viewModels(
factoryProducer = {
StoryViewerViewModel.Factory(storyViewerArgs, StoryViewerRepository())
}
)
private val lifecycleDisposable = LifecycleDisposable()
private val storyViewerArgs: StoryViewerArgs by lazy { requireArguments().getParcelable(ARGS)!! }
private lateinit var storyCrossfader: StoriesSharedElementCrossFaderView
private var pagerOnPageSelectedLock: Boolean = false
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
storyCrossfader = view.findViewById(R.id.story_content_crossfader)
storyPager = view.findViewById(R.id.story_item_pager)
ViewCompat.setTransitionName(storyCrossfader, "story")
storyCrossfader.callback = this
val adapter = StoryViewerPagerAdapter(
this,
StoryViewerPageArgs(
recipientId = Recipient.UNKNOWN.id,
initialStoryId = storyViewerArgs.storyId,
isJumpForwardToUnviewed = storyViewerArgs.isJumpToUnviewed,
isOutgoingOnly = storyViewerArgs.isFromMyStories,
source = when {
storyViewerArgs.isFromInfoContextMenuAction -> StoryViewerPageArgs.Source.INFO_CONTEXT
storyViewerArgs.isFromNotification -> StoryViewerPageArgs.Source.NOTIFICATION
else -> StoryViewerPageArgs.Source.UNKNOWN
},
groupReplyStartPosition = storyViewerArgs.groupReplyStartPosition
)
)
storyPager.adapter = adapter
storyPager.overScrollMode = ViewPager2.OVER_SCROLL_NEVER
lifecycleDisposable += viewModel.allowParentScrolling.observeOn(AndroidSchedulers.mainThread()).subscribe {
storyPager.isUserInputEnabled = it
}
storyPager.offscreenPageLimit = 1
lifecycleDisposable.bindTo(viewLifecycleOwner)
lifecycleDisposable += viewModel.state.observeOn(AndroidSchedulers.mainThread()).subscribe { state ->
if (state.noPosts) {
ActivityCompat.finishAfterTransition(requireActivity())
}
adapter.setPages(state.pages)
if (state.pages.isNotEmpty() && storyPager.currentItem != state.page) {
pagerOnPageSelectedLock = true
storyPager.isUserInputEnabled = false
storyPager.setCurrentItem(state.page, state.previousPage > -1)
pagerOnPageSelectedLock = false
if (state.page >= state.pages.size) {
ActivityCompat.finishAfterTransition(requireActivity())
lifecycleDisposable.clear()
}
}
when (state.crossfadeSource) {
is StoryViewerState.CrossfadeSource.TextModel -> storyCrossfader.setSourceView(state.crossfadeSource.storyTextPostModel)
is StoryViewerState.CrossfadeSource.ImageUri -> storyCrossfader.setSourceView(state.crossfadeSource.imageUri, state.crossfadeSource.imageBlur)
}
if (state.crossfadeTarget is StoryViewerState.CrossfadeTarget.Record) {
storyCrossfader.setTargetView(state.crossfadeTarget.messageRecord)
requireActivity().supportStartPostponedEnterTransition()
}
if (state.skipCrossfade) {
viewModel.setCrossfaderIsReady(true)
}
if (state.loadState.isReady()) {
storyCrossfader.alpha = 0f
}
}
if (savedInstanceState != null && savedInstanceState.containsKey(HIDDEN)) {
val ids: List<RecipientId> = savedInstanceState.getParcelableArrayList(HIDDEN)!!
viewModel.addHiddenAndRefresh(ids.toSet())
} else {
viewModel.refresh()
if (!SignalStore.storyValues().userHasSeenFirstNavView) {
StoryFirstTimeNavigationFragment().show(childFragmentManager, null)
}
}
if (Build.VERSION.SDK_INT >= 31) {
lifecycleDisposable += viewModel.isFirstTimeNavigationShowing.subscribe {
if (it) {
requireView().rootView.setRenderEffect(RenderEffect.createBlurEffect(100f, 100f, Shader.TileMode.CLAMP))
} else {
requireView().rootView.setRenderEffect(null)
}
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putParcelableArrayList(HIDDEN, ArrayList(viewModel.getHidden()))
}
override fun onResume() {
super.onResume()
viewModel.setIsScrolling(false)
storyPager.registerOnPageChangeCallback(onPageChanged)
}
override fun onPause() {
super.onPause()
viewModel.setIsScrolling(false)
storyPager.unregisterOnPageChangeCallback(onPageChanged)
}
override fun onGoToPreviousStory(recipientId: RecipientId) {
viewModel.onGoToPrevious(recipientId)
}
override fun onFinishedPosts(recipientId: RecipientId) {
viewModel.onGoToNext(recipientId)
}
override fun onStoryHidden(recipientId: RecipientId) {
viewModel.addHiddenAndRefresh(setOf(recipientId))
}
override fun onContentTranslation(x: Float, y: Float) {
storyCrossfader.translationX = x
storyCrossfader.translationY = y
}
override fun onReadyToAnimate() {
}
override fun onAnimationStarted() {
viewModel.setCrossfaderIsReady(false)
}
override fun onAnimationFinished() {
viewModel.setCrossfaderIsReady(true)
}
inner class OnPageChanged : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
if (!pagerOnPageSelectedLock) {
viewModel.setSelectedPage(position)
}
}
override fun onPageScrollStateChanged(state: Int) {
viewModel.setIsScrolling(state == ViewPager2.SCROLL_STATE_DRAGGING)
if (state == ViewPager2.SCROLL_STATE_IDLE) {
storyPager.isUserInputEnabled = true
}
}
}
companion object {
private const val ARGS = "args"
private const val HIDDEN = "hidden"
fun create(storyViewerArgs: StoryViewerArgs): Fragment {
return StoryViewerFragment().apply {
arguments = Bundle().apply {
putParcelable(ARGS, storyViewerArgs)
}
}
}
}
}
| gpl-3.0 | 4e7084804a11402c80598f8d341c470f | 32.971963 | 150 | 0.74553 | 4.717716 | false | false | false | false |
androidx/androidx | compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/ComposeErrors.kt | 3 | 5194 | /*
* Copyright 2020 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.compiler.plugins.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory0
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory2
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory3
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.PositioningStrategies.DECLARATION_SIGNATURE_OR_DEFAULT
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.types.KotlinType
object ComposeErrors {
// error goes on the composable call in a non-composable function
@JvmField
val COMPOSABLE_INVOCATION =
DiagnosticFactory0.create<PsiElement>(
Severity.ERROR
)
// error goes on the non-composable function with composable calls
@JvmField
val COMPOSABLE_EXPECTED =
DiagnosticFactory0.create<PsiElement>(
Severity.ERROR
)
@JvmField
val COMPOSABLE_FUNCTION_REFERENCE =
DiagnosticFactory0.create<KtCallableReferenceExpression>(
Severity.ERROR
)
@JvmField
val COMPOSABLE_PROPERTY_BACKING_FIELD =
DiagnosticFactory0.create<PsiElement>(
Severity.ERROR
)
@JvmField
val COMPOSABLE_VAR =
DiagnosticFactory0.create<PsiElement>(
Severity.ERROR
)
@JvmField
val COMPOSABLE_SUSPEND_FUN =
DiagnosticFactory0.create<PsiElement>(
Severity.ERROR
)
@JvmField
val ABSTRACT_COMPOSABLE_DEFAULT_PARAMETER_VALUE =
DiagnosticFactory0.create<PsiElement>(
Severity.ERROR
)
@JvmField
val COMPOSABLE_FUN_MAIN =
DiagnosticFactory0.create<PsiElement>(
Severity.ERROR
)
@JvmField
val CAPTURED_COMPOSABLE_INVOCATION =
DiagnosticFactory2.create<PsiElement, DeclarationDescriptor, DeclarationDescriptor>(
Severity.ERROR
)
@JvmField
val CALLED_IN_INCORRECT_CONTEXT =
DiagnosticFactory1.create<PsiElement, String>(
Severity.ERROR
)
@JvmField
val MISSING_DISALLOW_COMPOSABLE_CALLS_ANNOTATION =
DiagnosticFactory3.create<
PsiElement,
ValueParameterDescriptor, // unmarked
ValueParameterDescriptor, // marked
CallableDescriptor
>(
Severity.ERROR
)
@JvmField
val NONREADONLY_CALL_IN_READONLY_COMPOSABLE = DiagnosticFactory0.create<PsiElement>(
Severity.ERROR
)
// This error matches Kotlin's CONFLICTING_OVERLOADS error, except that it renders the
// annotations with the descriptor. This is important to use for errors where the
// only difference is whether or not it is annotated with @Composable or not.
@JvmField
var CONFLICTING_OVERLOADS: DiagnosticFactory1<PsiElement, Collection<DeclarationDescriptor>> =
DiagnosticFactory1.create(
Severity.ERROR,
DECLARATION_SIGNATURE_OR_DEFAULT
)
@JvmField
val ILLEGAL_TRY_CATCH_AROUND_COMPOSABLE =
DiagnosticFactory0.create<PsiElement>(
Severity.ERROR
)
// This error matches Kotlin's TYPE_MISMATCH error, except that it renders the annotations
// with the types. This is important to use for type mismatch errors where the only
// difference is whether or not it is annotated with @Composable or not.
@JvmField
val TYPE_MISMATCH =
DiagnosticFactory2.create<KtExpression, KotlinType, KotlinType>(
Severity.ERROR
)
@JvmField
val COMPOSE_APPLIER_CALL_MISMATCH =
DiagnosticFactory2.create<PsiElement, String, String>(
Severity.WARNING
)
@JvmField
val COMPOSE_APPLIER_PARAMETER_MISMATCH =
DiagnosticFactory2.create<PsiElement, String, String>(
Severity.WARNING
)
@JvmField
val COMPOSE_APPLIER_DECLARATION_MISMATCH =
DiagnosticFactory0.create<PsiElement>(
Severity.WARNING
)
init {
Errors.Initializer.initializeFactoryNamesAndDefaultErrorMessages(
ComposeErrors::class.java,
ComposeErrorMessages()
)
}
} | apache-2.0 | 2c23786725801f926f24b1b38e701524 | 30.871166 | 98 | 0.696765 | 4.999038 | false | false | false | false |
CarrotCodes/Kale | src/test/kotlin/chat/willow/kale/irc/message/extension/batch/BatchStartMessageTests.kt | 2 | 2584 | package chat.willow.kale.irc.message.extension.batch
import chat.willow.kale.core.message.IrcMessage
import chat.willow.kale.irc.prefix.prefix
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
class BatchStartMessageTests {
private lateinit var messageParser: BatchMessage.Start.Message.Parser
private lateinit var messageSerialiser: BatchMessage.Start.Message.Serialiser
@Before fun setUp() {
messageParser = BatchMessage.Start.Message.Parser
messageSerialiser = BatchMessage.Start.Message.Serialiser
}
@Test fun test_parse_NoBatchParameters() {
val message = messageParser.parse(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("+batch1", "type")))
assertEquals(BatchMessage.Start.Message(source = prefix("someone"), reference = "batch1", type = "type"), message)
}
@Test fun test_parse_MultipleBatchParameters() {
val message = messageParser.parse(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("+batch1", "type", "param1", "param2")))
assertEquals(BatchMessage.Start.Message(source = prefix("someone"), reference = "batch1", type = "type", parameters = listOf("param1", "param2")), message)
}
@Test fun test_parse_MissingPlusCharacter_ReturnsNull() {
val message = messageParser.parse(IrcMessage(command = "BATCH", parameters = listOf("batch1", "type")))
assertNull(message)
}
@Test fun test_parse_TooFewParameters_ReturnsNull() {
val messageOne = messageParser.parse(IrcMessage(command = "BATCH", parameters = listOf("batch1")))
val messageTwo = messageParser.parse(IrcMessage(command = "BATCH", parameters = listOf()))
assertNull(messageOne)
assertNull(messageTwo)
}
@Test fun test_serialise_NoBatchParameters() {
val message = messageSerialiser.serialise(BatchMessage.Start.Message(source = prefix("someone"), reference = "reference", type = "type"))
assertEquals(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("+reference", "type")), message)
}
@Test fun test_serialise_MultipleBatchParameters() {
val message = messageSerialiser.serialise(BatchMessage.Start.Message(source = prefix("someone"), reference = "reference", type = "type", parameters = listOf("parameter1", "parameter2")))
assertEquals(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("+reference", "type", "parameter1", "parameter2")), message)
}
} | isc | 2fb1303957bb2d2925658892e151f7a2 | 43.568966 | 194 | 0.706269 | 4.387097 | false | true | false | false |
codehz/container | app/src/main/java/one/codehz/container/delegate/MyComponentDelegate.kt | 1 | 2266 | package one.codehz.container.delegate
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import com.lody.virtual.client.hook.delegate.ComponentDelegate
import com.lody.virtual.helper.utils.VLog
import one.codehz.container.ext.vClientImpl
import one.codehz.container.provider.MainProvider
class MyComponentDelegate(val context: Context) : ComponentDelegate {
override fun beforeActivityCreate(activity: Activity?) {
}
override fun beforeActivityResume(activity: Activity?) {
}
override fun beforeActivityPause(activity: Activity?) {
}
override fun beforeActivityDestroy(activity: Activity?) {
}
override fun afterActivityCreate(activity: Activity?) {
}
override fun afterActivityResume(activity: Activity?) {
}
override fun afterActivityPause(activity: Activity?) {
}
override fun afterActivityDestroy(activity: Activity?) {
}
fun checkComponent(type: String, action: String): Boolean {
context.contentResolver.query(MainProvider.COMPONENT_URI, arrayOf("action"), "`type`=\"$type\" AND package=\"${vClientImpl.currentPackage}\"", null, null).use {
generateSequence { if (it.moveToNext()) it else null }.map { it.getString(0) }.forEach {
VLog.d("MCD", "%s == %s", it, action)
if (it == action)
return false
}
}
return true
}
fun logComponent(type: String, action: String) = checkComponent(type, action).apply {
val result = if (this) 1 else 0
context.contentResolver.insert(MainProvider.COMPONENT_LOG_URI, ContentValues().apply {
put("package", vClientImpl.currentPackage)
put("type", type)
put("action", action)
put("result", result)
})
}
override fun onStartService(intent: Intent?): Boolean {
if (intent?.component != null)
return logComponent("service", intent?.component?.className!!)
return true
}
override fun onSendBroadcast(intent: Intent?): Boolean {
if (intent?.action != null)
return logComponent("broadcast", intent?.action!!)
return true
}
} | gpl-3.0 | 695dc57ebf404fdc28eec8ba48b37995 | 31.385714 | 168 | 0.658429 | 4.550201 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/note/KeywordsFilter.kt | 1 | 6085 | /*
* Copyright (C) 2015 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.note
import org.andstatus.app.util.IsEmpty
import org.andstatus.app.util.MyHtml
import org.andstatus.app.util.StringUtil
import java.util.*
class KeywordsFilter(keywordsIn: String?) : IsEmpty {
internal class Keyword @JvmOverloads constructor(val value: String, val contains: Boolean = false) {
val nonEmpty: Boolean
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val keyword = other as Keyword
return contains == keyword.contains && value == keyword.value
}
override fun hashCode(): Int {
return Objects.hash(value, contains)
}
override fun toString(): String {
return "{" + (if (contains) CONTAINS_PREFIX else "") + value + "}"
}
init {
nonEmpty = value.isNotEmpty()
}
}
internal val keywordsToFilter: MutableList<Keyword>
private val keywordsRaw: MutableList<String>
private fun parseFilterString(text: String?): MutableList<String> {
val keywords: MutableList<String> = ArrayList()
if (text.isNullOrEmpty()) {
return keywords
}
var inQuote = false
var atPos = 0
while (atPos < text.length) {
val separatorInd = if (inQuote) nextQuote(text, atPos) else nextSeparatorInd(text, atPos)
if (atPos > separatorInd) {
break
}
val item = text.substring(atPos, separatorInd)
if (item.isNotEmpty() && !keywords.contains(item)) {
keywords.add(item)
}
if (separatorInd < text.length && text[separatorInd] == '"') {
inQuote = !inQuote
}
atPos = separatorInd + 1
}
return keywords
}
private fun nextQuote(text: String, atPos: Int): Int {
for (ind in atPos until text.length) {
if (DOUBLE_QUOTE == text[ind]) {
return ind
}
}
return text.length
}
private fun nextSeparatorInd(text: String, atPos: Int): Int {
val SEPARATORS = ", $DOUBLE_QUOTE"
for (ind in atPos until text.length) {
if (SEPARATORS.indexOf(text[ind]) >= 0) {
return ind
}
}
return text.length
}
private fun rawToActual(keywordsRaw: MutableList<String>): MutableList<Keyword> {
val keywords: MutableList<Keyword> = ArrayList()
for (itemRaw in keywordsRaw) {
val contains = itemRaw.startsWith(CONTAINS_PREFIX)
val contentToSearch = MyHtml.getContentToSearch(if (contains) itemRaw.substring(CONTAINS_PREFIX.length) else itemRaw)
val withContains = if (contains && contentToSearch.length > 2) contentToSearch.substring(1, contentToSearch.length - 1) else contentToSearch
val item = Keyword(withContains, contains)
if (item.nonEmpty && !keywords.contains(item)) {
keywords.add(item)
}
}
return keywords
}
fun matchedAny(s: String?): Boolean {
if (keywordsToFilter.isEmpty() || s.isNullOrEmpty()) {
return false
}
for (keyword in keywordsToFilter) {
if (s.contains(keyword.value)) {
return true
}
}
return false
}
fun matchedAll(s: String?): Boolean {
if (keywordsToFilter.isEmpty() || s.isNullOrEmpty()) {
return false
}
for (keyword in keywordsToFilter) {
if (!s.contains(keyword.value)) {
return false
}
}
return true
}
fun getSqlSelection(fieldName: String?): String {
if (isEmpty) {
return ""
}
val selection = StringBuilder()
for (ind in keywordsToFilter.indices) {
if (ind > 0) {
selection.append(" AND ")
}
selection.append("$fieldName LIKE ?")
}
return if (selection.isEmpty()) "" else "($selection)"
}
fun prependSqlSelectionArgs(selectionArgs: Array<String>): Array<String> {
var selectionArgsOut = selectionArgs
for (keyword in keywordsToFilter) {
selectionArgsOut = StringUtil.addBeforeArray(selectionArgsOut, "%" + keyword.value + "%")
}
return selectionArgsOut
}
fun getFirstTagOrFirstKeyword(): String {
for (keyword in keywordsRaw) {
if (keyword.startsWith("#")) {
return keyword.substring(1)
}
}
return if (keywordsRaw.isEmpty()) "" else keywordsRaw[0]
}
override val isEmpty: Boolean
get() {
return keywordsToFilter.isEmpty()
}
override fun toString(): String {
val builder = StringBuilder()
for (keyword in keywordsRaw) {
if (builder.isNotEmpty()) {
builder.append(", ")
}
builder.append("\"" + keyword + "\"")
}
return builder.toString()
}
companion object {
val CONTAINS_PREFIX: String = "contains:"
private const val DOUBLE_QUOTE = '"'
}
init {
keywordsRaw = parseFilterString(keywordsIn)
keywordsToFilter = rawToActual(keywordsRaw)
}
}
| apache-2.0 | 7537a78a9057bfbac43b3bd1a8d7e9dd | 31.715054 | 152 | 0.577814 | 4.616844 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/database/table/ActorTable.kt | 1 | 6265 | /*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.database.table
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import org.andstatus.app.account.MyAccount
import org.andstatus.app.data.DbUtils
/**
* Actors table (they are both senders AND recipients in the [NoteTable] table)
* Some of these Users are Accounts (connected to accounts in AndStatus),
* see [MyAccount.getActorId]
*/
object ActorTable : BaseColumns {
val TABLE_NAME: String = "actor"
// Table columns
/* {@link BaseColumns#_ID} is primary key in this database */
val USER_ID: String = UserTable.USER_ID
/**
* ID of the originating (source) system (twitter.com, identi.ca, ... ) where the row was created
*/
val ORIGIN_ID: String = OriginTable.ORIGIN_ID
/**
* ID in the originating system
* The id is not unique for this table, because we have IDs from different systems in one column.
*/
val ACTOR_OID: String = "actor_oid"
/** [org.andstatus.app.actor.GroupType] */
val GROUP_TYPE: String = "group_type"
/** See [org.andstatus.app.actor.GroupType.hasParentActor]
* denotes the Actor, whose the Group is */
val PARENT_ACTOR_ID: String = "parent_actor_id"
/** This is called "screen_name" in Twitter API, "login" or "username" in others, "preferredUsername" in ActivityPub */
val USERNAME: String = "username"
/** It looks like an email address with your nickname then "@" then your server */
val WEBFINGER_ID: String = "webfinger_id"
/** This is called "name" in Twitter API and in ActivityPub */
val REAL_NAME: String = "real_name"
/** Actor's description / "About myself" "bio" "summary" */
val SUMMARY: String = "actor_description" // TODO: Rename
/** Location string */
val LOCATION: String = "location"
/** URL of Actor's Profile web page */
val PROFILE_PAGE: String = "profile_url" // TODO: Rename
/** URL of Actor's Home web page */
val HOMEPAGE: String = "homepage"
/** The latest url of the avatar */
val AVATAR_URL: String = "avatar_url"
val NOTES_COUNT: String = "notes_count"
val FAVORITES_COUNT: String = "favorited_count"
val FOLLOWING_COUNT: String = "following_count"
val FOLLOWERS_COUNT: String = "followers_count"
/**
* Date and time when the row was created in the originating system.
* We store it as long returned by [Connection.dateFromJson].
* NULL means the row was not retrieved from the Internet yet
* (And maybe there is no such an Actor in the originating system...)
*/
val CREATED_DATE: String = "actor_created_date"
val UPDATED_DATE: String = "actor_updated_date"
/** Date and time the row was inserted into this database */
val INS_DATE: String = "actor_ins_date"
/**
* Id of the latest activity where this actor was an Actor or an Author
*/
val ACTOR_ACTIVITY_ID: String = "actor_activity_id"
/**
* Date of the latest activity of this Actor (were he was an Actor)
*/
val ACTOR_ACTIVITY_DATE: String = "actor_activity_date"
/*
* Derived columns (they are not stored in this table but are result of joins)
*/
/** Alias for the primary key */
val ACTOR_ID: String = "actor_id"
/** Alias for the primary key used for accounts */
val ACCOUNT_ID: String = "account_id"
/**
* Derived from [ActivityTable.ACTOR_ID]
* Whether this (and other similar...) is [.USERNAME] or [.REAL_NAME], depends on settings
*
* Derived from [ActivityTable.ACTOR_ID] */
val ACTIVITY_ACTOR_NAME: String = "activity_actor_name"
/** Derived from [NoteTable.AUTHOR_ID] */
val AUTHOR_NAME: String = "author_name"
val DEFAULT_SORT_ORDER: String = USERNAME + " ASC"
fun create(db: SQLiteDatabase) {
DbUtils.execSQL(db, "CREATE TABLE " + TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ USER_ID + " INTEGER NOT NULL,"
+ ORIGIN_ID + " INTEGER NOT NULL,"
+ ACTOR_OID + " TEXT NOT NULL,"
+ GROUP_TYPE + " INTEGER NOT NULL DEFAULT 0,"
+ PARENT_ACTOR_ID + " INTEGER NOT NULL DEFAULT 0,"
+ USERNAME + " TEXT NOT NULL,"
+ WEBFINGER_ID + " TEXT NOT NULL,"
+ REAL_NAME + " TEXT,"
+ SUMMARY + " TEXT,"
+ LOCATION + " TEXT,"
+ PROFILE_PAGE + " TEXT,"
+ HOMEPAGE + " TEXT,"
+ AVATAR_URL + " TEXT,"
+ NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ FAVORITES_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ FOLLOWING_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ FOLLOWERS_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ CREATED_DATE + " INTEGER NOT NULL DEFAULT 0,"
+ UPDATED_DATE + " INTEGER NOT NULL DEFAULT 0,"
+ INS_DATE + " INTEGER NOT NULL,"
+ ACTOR_ACTIVITY_ID + " INTEGER NOT NULL DEFAULT 0,"
+ ACTOR_ACTIVITY_DATE + " INTEGER NOT NULL DEFAULT 0"
+ ")")
DbUtils.execSQL(db, "CREATE UNIQUE INDEX idx_actor_origin ON " + TABLE_NAME + " ("
+ ORIGIN_ID + ", "
+ ACTOR_OID
+ ")")
DbUtils.execSQL(db, "CREATE INDEX idx_actor_user ON " + TABLE_NAME + " ("
+ USER_ID
+ ")")
DbUtils.execSQL(db, "CREATE INDEX idx_actor_webfinger ON " + TABLE_NAME + " ("
+ WEBFINGER_ID
+ ")")
}
}
| apache-2.0 | 29ca6a6e293fe029316a7738477bb810 | 38.651899 | 124 | 0.607342 | 4.086758 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/data/ActorActivity.kt | 1 | 4867 | /*
* Copyright (C) 2013 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.data
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.database.table.ActivityTable
import org.andstatus.app.database.table.ActorTable
import org.andstatus.app.util.MyLog
import java.util.*
/**
* Manages minimal information about the latest downloaded note by one Actor (or a User represented by the Actor).
* We count notes where the Actor is either a Actor or an Author
*
* All information is supplied in this constructor, so it doesn't lookup anything in the database
*/
class ActorActivity(actorIdIn: Long, activityId: Long, activityDate: Long) {
private var actorId: Long = 0
/**
* The id of the latest downloaded Note by this Actor
* 0 - none were downloaded
*/
private var lastActivityId: Long = 0
/**
* 0 - none were downloaded
*/
private var lastActivityDate: Long = 0
/**
* We will update only what really changed
*/
private var changed = false
init {
if (actorIdIn != 0L && activityId != 0L) {
actorId = actorIdIn
onNewActivity(activityId, activityDate)
}
}
fun getActorId(): Long {
return actorId
}
/**
* @return Id of the last downloaded note by this Actor
*/
fun getLastActivityId(): Long {
return lastActivityId
}
/**
* @return Sent Date of the last downloaded note by this Actor
*/
fun getLastActivityDate(): Long {
return lastActivityDate
}
/** If this note is newer than any we got earlier, remember it
* @param updatedDateIn may be 0 (will be retrieved here)
*/
fun onNewActivity(activityId: Long, updatedDateIn: Long) {
if (actorId == 0L || activityId == 0L) {
return
}
var activityDate = updatedDateIn
if (activityDate == 0L) {
activityDate = MyQuery.activityIdToLongColumnValue(ActivityTable.UPDATED_DATE, activityId)
}
if (activityDate > lastActivityDate) {
lastActivityDate = activityDate
lastActivityId = activityId
changed = true
}
}
/**
* Persist the info into the Database
* @return true if succeeded
*/
fun save(): Boolean {
MyLog.v(this
) {
("actorId " + actorId + ": " +
MyQuery.actorIdToWebfingerId( MyContextHolder.myContextHolder.getNow(), actorId)
+ " Latest activity update at " + Date(getLastActivityDate()).toString()
+ if (changed) "" else " not changed")
}
if (!changed) {
return true
}
// As a precaution compare with stored values ones again
val activityDate = MyQuery.actorIdToLongColumnValue(ActorTable.ACTOR_ACTIVITY_DATE, actorId)
if (activityDate > lastActivityDate) {
lastActivityDate = activityDate
lastActivityId = MyQuery.actorIdToLongColumnValue(ActorTable.ACTOR_ACTIVITY_ID, actorId)
MyLog.v(this) {
("There is newer information in the database. Actor " + actorId + ": "
+ MyQuery.actorIdToWebfingerId( MyContextHolder.myContextHolder.getNow(), actorId)
+ " Latest activity at " + Date(getLastActivityDate()).toString())
}
changed = false
return true
}
var sql = ""
try {
sql += ActorTable.ACTOR_ACTIVITY_ID + "=" + lastActivityId
sql += ", " + ActorTable.ACTOR_ACTIVITY_DATE + "=" + lastActivityDate
sql = ("UPDATE " + ActorTable.TABLE_NAME + " SET " + sql
+ " WHERE " + BaseColumns._ID + "=" + actorId)
val db: SQLiteDatabase? = MyContextHolder.myContextHolder.getNow().database
if (db == null) {
MyLog.databaseIsNull { "Save $this" }
return false
}
db.execSQL(sql)
changed = false
} catch (e: Exception) {
MyLog.w(this, "save: sql='$sql'", e)
return false
}
return true
}
}
| apache-2.0 | 6b1cfd09c8c0924705953255df9f006a | 33.274648 | 114 | 0.608999 | 4.635238 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/provider/storage/WorkTypesProvider.kt | 2 | 2320 | package ru.fantlab.android.provider.storage
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.disposables.Disposable
import ru.fantlab.android.App
import ru.fantlab.android.data.dao.model.WorkType
import ru.fantlab.android.data.dao.response.WorkTypesResponse
import ru.fantlab.android.helper.observe
import ru.fantlab.android.helper.single
import ru.fantlab.android.provider.rest.DataManager
import timber.log.Timber
import java.io.File
import java.io.InputStream
object WorkTypesProvider {
private const val FILENAME = "worktypes.json"
private var WORKTYPES: List<WorkType.WorkTypeItem> = listOf()
fun init(): Disposable = loadWorkTypesLocal().single()
.subscribe({
deserializeWorkTypes(it)
loadWorkTypesExternal()
}, { Timber.d(it) }
)
private fun loadWorkTypesExternal(): Disposable = DataManager.getWorkTypes().single()
.subscribe({ deserializeWorkTypes(it) }, { Timber.d(it) })
private fun loadWorkTypesAssets(): String {
return inputStreamToString(App.instance.assets.open(FILENAME))
}
private fun loadWorkTypesLocal(): Single<String> {
val file = File(App.instance.filesDir.toString() + FILENAME)
return Single.just(if (file.exists() && file.length() > 0) (inputStreamToString(file.inputStream())) else loadWorkTypesAssets())
}
private fun saveWorkTypesLocal(workTypes: String) = File(App.instance.filesDir.toString() + FILENAME).bufferedWriter().use { out -> out.write(workTypes) }
private fun deserializeWorkTypes(workTypesData: String): Disposable =
Observable.just(WorkTypesResponse.Deserializer().deserialize(workTypesData)).observe()
.subscribe({
if (it.types.isEmpty()) {
loadWorkTypesLocal()
} else {
setWorkTypes(it.types)
saveWorkTypesLocal(workTypesData)
}
}, { Timber.d(it) })
private fun inputStreamToString(stream: InputStream): String = stream.bufferedReader().use { it.readText() }
fun getWorkTypes(): List<WorkType.WorkTypeItem> = WORKTYPES
fun getCoverByTypeId(typeId: Int) = WORKTYPES.find { it.id == typeId }?.image ?: ""
fun getCoverByTypeName(typeName: String, isRussian: Boolean = true) = WORKTYPES.find { it.title.rus == typeName }?.image ?: ""
private fun setWorkTypes(workTypeItems: ArrayList<WorkType.WorkTypeItem>) {
WORKTYPES = workTypeItems
}
}
| gpl-3.0 | 4c3049b1bfc4762e2ed2520d3a73c487 | 35.25 | 155 | 0.748276 | 3.647799 | false | false | false | false |
0x1bad1d3a/Kaku | app/src/main/java/ca/fuwafuwa/kaku/TutorialActivity.kt | 1 | 1471 | package ca.fuwafuwa.kaku
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import kotlinx.android.synthetic.main.activity_tutorial.*
class TutorialActivity : AppCompatActivity()
{
inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm)
{
override fun getItem(position: Int): Fragment
{
if (position == 0){
return TutorialWelcomeFragment.newInstance()
}
if (position in 1..9)
{
return TutorialFragment.newInstance(position)
}
return TutorialEndFragment.newInstance()
}
override fun getCount(): Int
{
return 11
}
}
private lateinit var mSectionsPagerAdapter: FragmentStatePagerAdapter
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
supportActionBar?.hide()
setContentView(R.layout.activity_tutorial)
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
container.adapter = mSectionsPagerAdapter
container.offscreenPageLimit = 1
tab_indicator.setupWithViewPager(container)
}
companion object
{
private val TAG = TutorialActivity::class.java.name
}
} | bsd-3-clause | e0b2a9a16b1b782e9b6af12d516969e9 | 27.307692 | 89 | 0.67777 | 5.679537 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/config/HaskellConfigurable.kt | 1 | 5564 | package org.jetbrains.haskell.config
import com.intellij.openapi.options.Configurable
import org.jetbrains.haskell.icons.HaskellIcons
import javax.swing.*
import com.intellij.ui.DocumentAdapter
import javax.swing.event.DocumentEvent
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import org.jetbrains.haskell.util.setConstraints
import java.awt.GridBagConstraints
import org.jetbrains.haskell.util.gridBagConstraints
import java.awt.Insets
import java.awt.GridBagLayout
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.fileTypes.FileType
import com.intellij.ui.components.JBCheckBox
import javax.swing.event.ChangeListener
import javax.swing.event.ChangeEvent
public class HaskellConfigurable() : Configurable {
private var isModified = false
private val cabalPathField = TextFieldWithBrowseButton()
private val cabalDataPathField = TextFieldWithBrowseButton()
private val ghcMod = TextFieldWithBrowseButton()
private val ghcModi = TextFieldWithBrowseButton()
private val useGhcMod = JBCheckBox("Use ghc-mod automatic check (turn off if you have problems with ghc-mod)")
private val usePty = JBCheckBox("Use pseudo terminal for project running")
override fun getDisplayName(): String {
return "Haskell"
}
override fun isModified(): Boolean = isModified
override fun createComponent(): JComponent {
cabalPathField.addBrowseFolderListener(
"Select cabal execurtable",
null,
null,
FileChooserDescriptorFactory.createSingleLocalFileDescriptor())
cabalDataPathField.addBrowseFolderListener(
"Select data cabal directory",
null,
null,
FileChooserDescriptorFactory.createSingleFolderDescriptor())
ghcMod.addBrowseFolderListener(
"Select ghc-mod executable",
null,
null,
FileChooserDescriptorFactory.createSingleLocalFileDescriptor())
val result = JPanel(GridBagLayout())
val listener : DocumentAdapter = object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent?) {
isModified = true;
}
};
cabalPathField.getTextField()!!.getDocument()!!.addDocumentListener(listener)
cabalDataPathField.getTextField()!!.getDocument()!!.addDocumentListener(listener)
ghcMod.getTextField()!!.getDocument()!!.addDocumentListener(listener)
val base = gridBagConstraints {
insets = Insets(2, 0, 2, 3)
}
fun addLabeledControl(row : Int, label : String, component : JComponent) {
result.add(JLabel(label), base.setConstraints {
anchor = GridBagConstraints.LINE_START
gridx = 0;
gridy = row;
})
result.add(component, base.setConstraints {
gridx = 1;
gridy = row;
fill = GridBagConstraints.HORIZONTAL
weightx = 1.0
})
result.add(Box.createHorizontalStrut(1), base.setConstraints {
gridx = 2;
gridy = row;
weightx = 0.1
})
}
addLabeledControl(0, "cabal executable", cabalPathField)
addLabeledControl(1, "cabal data path", cabalDataPathField)
addLabeledControl(2, "ghc-mod executable", ghcMod)
addLabeledControl(3, "ghc-modi executable", ghcModi)
val defaultChangeListener = object : ChangeListener {
override fun stateChanged(p0: ChangeEvent) {
isModified = true;
}
}
useGhcMod.addChangeListener(defaultChangeListener)
usePty.addChangeListener(defaultChangeListener)
result.add(useGhcMod, base.setConstraints {
anchor = GridBagConstraints.LINE_START
gridx = 0;
gridwidth = 2;
gridy = 4;
})
result.add(usePty, base.setConstraints {
anchor = GridBagConstraints.LINE_START
gridx = 0;
gridwidth = 2;
gridy = 5;
})
result.add(Box.createVerticalStrut(1), base.setConstraints {
gridy = 6;
weighty = 2.0;
})
return result
}
public fun getIcon(): Icon {
return HaskellIcons.HASKELL
}
override fun apply() {
val state = HaskellSettings.getInstance().getState()
state.cabalPath = cabalPathField.getTextField()!!.getText()
state.cabalDataPath = cabalDataPathField.getTextField()!!.getText()
state.ghcModPath = ghcMod.getTextField()!!.getText()
state.ghcModiPath = ghcModi.getTextField()!!.getText()
state.useGhcMod = useGhcMod.isSelected()
state.usePtyProcess = usePty.isSelected()
isModified = false
}
override fun disposeUIResources() {
}
override fun getHelpTopic(): String? = null
override fun reset() {
val state = HaskellSettings.getInstance().getState()
cabalPathField.getTextField()!!.setText(state.cabalPath ?: "")
cabalDataPathField.getTextField()!!.setText(state.cabalDataPath ?: "")
ghcMod.getTextField()!!.setText(state.ghcModPath ?: "")
ghcModi.getTextField()!!.setText(state.ghcModiPath ?: "")
useGhcMod.setSelected(state.useGhcMod!!)
usePty.setSelected(state.usePtyProcess!!)
isModified = false
}
}
| apache-2.0 | df2c057c89d9092c6350633898ea6793 | 32.518072 | 114 | 0.638749 | 5.156627 | false | false | false | false |
sybila/ode-generator | src/main/java/com/github/sybila/ode/generator/rect/Rectangle.kt | 1 | 7784 | package com.github.sybila.ode.generator.rect
import com.github.sybila.ode.generator.det.IntervalSet
import com.github.sybila.ode.generator.det.RectangleSet
import java.nio.ByteBuffer
import java.util.*
private val PRECISION = 0.00001
/**
* Shortcut for creating rectangles
*/
fun rectangleOf(vararg values: Double): Rectangle = Rectangle(values)
/**
* Create rectangle defined by two n-dimensional points, not variable intervals
*/
fun rectangleFromPoints(vararg values: Double): Rectangle {
val dimensions = values.size/2
val newCoordinates = DoubleArray(values.size) { i ->
if (i%2 == 0) {
values[i/2]
} else {
values[dimensions+i/2]
}
}
return Rectangle(newCoordinates)
}
fun rectangleFromBuffer(buffer: ByteBuffer): Rectangle {
val size = buffer.int
val coordinates = DoubleArray(size)
for (i in 0 until size) {
coordinates[i] = buffer.double
}
return Rectangle(coordinates)
}
/**
* Non empty rectangle represented by it's coordinates in the parameter space.
* Coordinates should contain intervals for each variable, not direct coordinates of corner vertices.
*/
class Rectangle(
private val coordinates: DoubleArray
) {
/**
* Intersect these two rectangles.
* If result is empty, return null.
*/
operator fun times(other: Rectangle): Rectangle? {
val newCoordinates = DoubleArray(coordinates.size) { i ->
if (i % 2 == 0) {
Math.max(coordinates[i], other.coordinates[i]) //new lower bound
} else {
Math.min(coordinates[i], other.coordinates[i]) //new higher bound
}
}
//check integrity
for (dim in 0 until (newCoordinates.size/2)) {
if (newCoordinates[2*dim] >= newCoordinates[2*dim+1]) return null
}
return Rectangle(newCoordinates)
}
fun intersect(other: Rectangle, into: DoubleArray): Rectangle? {
for (i in 0 until (this.coordinates.size / 2)) {
val iL = 2*i
val iH = 2*i+1
val low = Math.max(coordinates[iL], other.coordinates[iL])
val high = Math.min(coordinates[iH], other.coordinates[iH])
if (low >= high) return null
else {
into[iL] = low
into[iH] = high
}
}
return Rectangle(into)
}
fun newArray(): DoubleArray = DoubleArray(coordinates.size)
private fun encloses(other: Rectangle): Boolean {
for (i in coordinates.indices) {
if (i % 2 == 0 && coordinates[i] > other.coordinates[i]) return false
if (i % 2 == 1 && coordinates[i] < other.coordinates[i]) return false
}
return true
}
/**
* If possible, merge these two rectangles. If not possible, return null.
*/
operator fun plus(other: Rectangle): Rectangle? {
if (this.encloses(other)) return this
if (other.encloses(this)) return other
var mergeDimension = -1
var mergeLow = Double.NEGATIVE_INFINITY
var mergeHigh = Double.POSITIVE_INFINITY
for (dim in 0 until (coordinates.size/2)) {
val l1 = coordinates[2*dim]
val l2 = other.coordinates[2*dim]
val h1 = coordinates[2*dim+1]
val h2 = other.coordinates[2*dim+1]
if (l1 == l2 && h1 == h2) {
//this dimension won't change
continue
} else if (h2 < l1 || h1 < l2) {
// l1..h1 ... l2..h2 || l2..h2 ... l1..h1 - we can't merge them, they are completely separate
return null
} else {
//we have a possible merge dimension
if (mergeDimension != -1) {
//more than one merge dimension, abort
return null
} else {
mergeDimension = dim
mergeLow = Math.min(l1, l2)
mergeHigh = Math.max(h1, h2)
}
}
}
//if rectangles are equal, they are processed in encloses section - if we reach this point, merge must be valid
val newCoordinates = coordinates.copyOf()
newCoordinates[2*mergeDimension] = mergeLow
newCoordinates[2*mergeDimension+1] = mergeHigh
return Rectangle(newCoordinates)
}
/**
* Create a set of smaller rectangles that together form a result of subtraction of given rectangle.
*/
operator fun minus(other: Rectangle): MutableSet<Rectangle> {
val workingCoordinates = coordinates.copyOf()
val results = HashSet<Rectangle>()
for (dim in 0 until (coordinates.size/2)) {
val l1 = coordinates[2*dim]
val l2 = other.coordinates[2*dim]
val h1 = coordinates[2*dim+1]
val h2 = other.coordinates[2*dim+1]
if (l1 >= l2 && h1 <= h2) {
//this dimension has a clean cut, no rectangles are created
continue
} else if (h2 <= l1 || h1 <= l2) {
// l1..h1 ... l2..h2 || l2..h2 ... l1..h1 - these rectangles are completely separate, nothing should be cut
return mutableSetOf(this)
} else {
if (l1 < l2) {
//there is an overlap on the lower side, create cut-rectangle and subtract it from working coordinates
val newCoordinates = workingCoordinates.copyOf()
newCoordinates[2*dim] = l1
newCoordinates[2*dim+1] = l2
results.add(Rectangle(newCoordinates))
workingCoordinates[2*dim] = l2
}
if (h1 > h2) {
//there is an overlap on the upper side, create cut-rectangle and subtract it from working coordinates
val newCoordinates = workingCoordinates.copyOf()
newCoordinates[2*dim] = h2
newCoordinates[2*dim+1] = h1
results.add(Rectangle(newCoordinates))
workingCoordinates[2*dim+1] = h2
}
}
}
return results
}
override fun equals(other: Any?): Boolean = other is Rectangle && Arrays.equals(coordinates, other.coordinates)
override fun hashCode(): Int = Arrays.hashCode(coordinates)
override fun toString(): String = Arrays.toString(coordinates)
fun byteSize(): Int = 4 + 8 * coordinates.size
fun writeToBuffer(buffer: ByteBuffer) {
buffer.putInt(coordinates.size)
coordinates.forEach { buffer.putDouble(it) }
}
fun asParams(): MutableSet<Rectangle> = mutableSetOf(this)
fun volume(): Double {
var vol = 1.0
for (dim in 0 until coordinates.size/2) {
vol *= coordinates[2*dim + 1] - coordinates[2*dim]
}
return vol
}
fun asIntervals(): Array<DoubleArray> {
return Array(coordinates.size / 2) { i ->
doubleArrayOf(coordinates[2*i], coordinates[2*i + 1])
}
}
fun toRectangleSet(): RectangleSet {
if (this.coordinates.size != 4) throw IllegalStateException("Wrong rectangle dimension")
return RectangleSet(
thresholdsX = doubleArrayOf(coordinates[0], coordinates[1]),
thresholdsY = doubleArrayOf(coordinates[2], coordinates[3]),
values = BitSet().apply { set(0) }
)
}
fun toIntervalSet(): IntervalSet {
if (this.coordinates.size != 2) throw IllegalStateException("Wrong rectangle dimension")
return IntervalSet(
thresholds = coordinates,
values = BitSet().apply { set(0) }
)
}
} | gpl-3.0 | f743e4e27b1829a5367f674f70ccf224 | 35.209302 | 123 | 0.572585 | 4.346175 | false | false | false | false |
JavaEden/Orchid | plugins/OrchidNetlifyCMS/src/main/kotlin/com/eden/orchid/netlifycms/util/NetlifyCmsHelpers.kt | 2 | 7416 | package com.eden.orchid.netlifycms.util
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.OptionHolderDescription
import com.eden.orchid.api.options.OptionsDescription
import com.eden.orchid.api.options.OptionsExtractor
import com.eden.orchid.api.options.OptionsHolder
import com.eden.orchid.api.theme.components.ModularList
import com.eden.orchid.api.theme.components.ModularListItem
import com.eden.orchid.impl.relations.AssetRelation
import com.eden.orchid.utilities.camelCase
import com.eden.orchid.utilities.from
import com.eden.orchid.utilities.titleCase
import com.eden.orchid.utilities.to
import org.json.JSONArray
import org.json.JSONObject
import java.lang.reflect.ParameterizedType
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
fun OptionsDescription.toNetlifyCmsField(context: OrchidContext, recursionDepth: Int): JSONObject {
val extractor = context.resolve(OptionsExtractor::class.java)
val field = JSONObject()
field.put("label", this.key from { camelCase() } to { titleCase() })
field.put("name", this.key)
field.put("description", this.description)
field.put("required", false)
field.put("widget", getWidgetType())
if (ModularList::class.java.isAssignableFrom(this.optionType)) {
val itemTypesListClass = getModularListItemClass(this.optionType)
if (itemTypesListClass != null) {
val itemTypes = context.resolveSet(itemTypesListClass)
val typeField = JSONObject()
typeField.put("label", this.javaClass.simpleName)
typeField.put("name", this.key)
typeField.put("description", this.description)
field.put("typeKey", "type")
field.put(
"types",
itemTypes
.map {
val options = extractor.describeAllOptions(it::class.java)
val itemType = JSONObject()
itemType.put("label", options.descriptiveName)
itemType.put("name", (it as ModularListItem<*, *>).getType())
itemType.put("description", options.classDescription)
itemType.put("widget", "object")
val fields = JSONArray()
options.optionsDescriptions.forEach { option ->
if (recursionDepth > 0) {
fields.put(option.toNetlifyCmsField(context, recursionDepth - 1))
}
}
itemType.put("fields", fields)
itemType
}
)
}
}
else if (OptionsHolder::class.java.isAssignableFrom(this.optionType)) {
val options = extractor.describeAllOptions(this.optionType)
val fields = JSONArray()
options.optionsDescriptions.forEach { option ->
if (recursionDepth > 0) {
fields.put(option.toNetlifyCmsField(context, recursionDepth - 1))
}
}
field.put("fields", fields)
}
else if (List::class.java.isAssignableFrom(this.optionType) && this.optionTypeParameters.first() != String::class.java) {
val options = extractor.describeAllOptions(this.optionTypeParameters.first())
val fields = JSONArray()
options.optionsDescriptions.forEach { option ->
if (recursionDepth > 0) {
fields.put(option.toNetlifyCmsField(context, recursionDepth - 1))
}
}
field.put("fields", fields)
}
else if (this.optionType.isArray && this.optionType.componentType != String::class.java) {
val options = extractor.describeAllOptions(this.optionType.componentType)
val fields = JSONArray()
options.optionsDescriptions.forEach { option ->
if (recursionDepth > 0) {
fields.put(option.toNetlifyCmsField(context, recursionDepth - 1))
}
}
field.put("fields", fields)
}
return field
}
fun OptionHolderDescription.getNetlifyCmsFields(context: OrchidContext, recursionDepth: Int): JSONArray {
val fields = JSONArray()
this.optionsDescriptions.forEach {
if (recursionDepth > 0) {
fields.put(it.toNetlifyCmsField(context, recursionDepth - 1))
}
}
val requiredFields = arrayOf("title", "body")
requiredFields.forEach { fieldName ->
var hasRequiredField = false
for (i in 0 until fields.length()) {
if (fields.getJSONObject(i).getString("name") == fieldName) {
hasRequiredField = true
break
}
}
if (!hasRequiredField) {
fields.put(getRequiredField(fieldName))
}
}
return fields
}
fun String.toNetlifyCmsSlug(): String {
return this.replace("\\{(.*?)\\}".toRegex(), "{{$1}}")
}
private fun getRequiredField(fieldName: String): JSONObject {
val field = JSONObject()
field.put("name", fieldName)
field.put("widget", "string")
if (fieldName == "body") {
field.put("label", "Page Content")
field.put("widget", "markdown")
}
else if (fieldName == "title") {
field.put("label", "Title")
field.put("widget", "string")
}
return field;
}
private fun OptionsDescription.getWidgetType(): String {
return when {
Number::class.java.isAssignableFrom(this.optionType) -> "number"
Boolean::class.java.isAssignableFrom(this.optionType) -> "boolean"
ModularList::class.java.isAssignableFrom(this.optionType) -> "list"
OptionsHolder::class.java.isAssignableFrom(this.optionType) -> "object"
List::class.java.isAssignableFrom(this.optionType) -> "list"
this.optionType.isArray -> "list"
this.optionType == LocalDate::class.java -> "date"
this.optionType == LocalTime::class.java -> "datetime"
this.optionType == LocalDateTime::class.java -> "datetime"
this.optionType == AssetRelation::class.java -> "image"
this.optionType == String::class.java -> "string"
else -> "string"
}
}
fun getModularListItemClass(modularListClass: Class<*>): Class<*>? {
var currentSuperclass: Class<*>? = modularListClass
var genericSuperclass: ParameterizedType? = null
while(currentSuperclass != null) {
if(currentSuperclass.genericSuperclass is ParameterizedType) {
genericSuperclass = currentSuperclass.genericSuperclass as ParameterizedType
break
}
else {
currentSuperclass = currentSuperclass.superclass
}
}
if(genericSuperclass != null) {
for (typeArg in genericSuperclass.actualTypeArguments) {
val className = typeArg.typeName
val clazz = Class.forName(className)
if (ModularListItem::class.java.isAssignableFrom(clazz)) {
return clazz
}
}
}
return null
}
| lgpl-3.0 | 52ec944136bf6fbbfd10e117f03e93bf | 35.712871 | 125 | 0.593312 | 4.747759 | false | false | false | false |
elect86/jAssimp | src/test/kotlin/assimp/collada/animFullRot.kt | 2 | 11408 | package assimp.collada
import assimp.*
import glm_.mat4x4.Mat4
import glm_.quat.Quat
import glm_.vec3.Vec3
import io.kotest.matchers.shouldBe
import java.net.URL
object animFullRot {
operator fun invoke(url: URL) {
Importer().testFile(url) {
flags shouldBe 0
with(rootNode) {
name shouldBe "Array Test 001"
transformation shouldBe Mat4(
1f, 0f, 0f, 0f,
0f, 0f, -1f, 0f,
0f, 1f, 0f, 0f,
0f, 0f, 0f, 1f)
parent shouldBe null
numChildren shouldBe 1
with(children[0]) {
name shouldBe "Box001"
transformation shouldBe Mat4(
1f, 5.235988e-08f, 0f, 0f,
-5.235988e-08f, 1f, 0f, 0f,
0f, 0f, 1f, 0f,
0f, 0f, 0f, 1f)
(parent === rootNode) shouldBe true
numChildren shouldBe 2
with(children[0]) {
name shouldBe "Box001-Pivot"
transformation shouldBe Mat4(
1f, 0f, 0f, 0f,
0f, 1f, 0f, 0f,
0f, 0f, 1f, 0f,
0.185947001f, 0f, 0f, 1f)
(parent === rootNode.children[0]) shouldBe true
numChildren shouldBe 0
numMeshes shouldBe 1
meshes[0] shouldBe 0
metaData.isEmpty() shouldBe true
}
with(children[1]) {
name shouldBe "Box002"
transformation shouldBe Mat4(
1f, 5.235988e-08f, 0f, 0f,
-5.235988e-08f, 1f, 0f, 0f,
0f, 0f, 1f, 0f,
0f, 0f, 0f, 1f)
(parent === rootNode.children[0]) shouldBe true
numChildren shouldBe 2
with(children[0]) {
name shouldBe "Box002-Pivot"
transformation shouldBe Mat4(
1f, 0f, 0f, 0f,
0f, 1f, 0f, 0f,
0f, 0f, 1f, 0f,
0.185947001f, 1.89182305f, 0f, 1f)
(parent === rootNode.children[0].children[1]) shouldBe true
numChildren shouldBe 0
numMeshes shouldBe 1
meshes[0] shouldBe 1
metaData.isEmpty() shouldBe true
}
with(children[1]) {
name shouldBe "Box003"
transformation shouldBe Mat4(
1f, 5.235988e-08f, 0f, 0f,
-5.235988e-08f, 1f, 0f, 0f,
0f, 0f, 1f, 0f,
0f, 0f, 0f, 1f)
(parent === rootNode.children[0].children[1]) shouldBe true
numChildren shouldBe 2
// TODO continue?
numMeshes shouldBe 0
meshes.isEmpty() shouldBe true
metaData.isEmpty() shouldBe true
}
numMeshes shouldBe 0
meshes.isEmpty() shouldBe true
metaData.isEmpty() shouldBe true
}
numMeshes shouldBe 0
meshes.isEmpty() shouldBe true
metaData.isEmpty() shouldBe true
}
}
numMeshes shouldBe 64
with(meshes[0]) {
primitiveTypes shouldBe 8
numVertices shouldBe 24
numFaces shouldBe 6
vertices[0] shouldBe Vec3(-0.5f, -0.5f, 0f)
vertices[11] shouldBe Vec3(-0.5f, -0.5f, 1f)
vertices[23] shouldBe Vec3(-0.5f, 0.5f, 1f)
normals[0] shouldBe Vec3(0f, 0f, -1f)
normals[11] shouldBe Vec3(0f, -1f, 0f)
normals[23] shouldBe Vec3(-1f, 0f, 0f)
textureCoords[0][0][0] shouldBe 1f
textureCoords[0][0][1] shouldBe 0f
textureCoords[0][11][0] shouldBe 0f
textureCoords[0][11][1] shouldBe 1f
textureCoords[0][23][0] shouldBe 0f
textureCoords[0][23][1] shouldBe 1f
for (i in 0..23 step 4) faces[i / 4] shouldBe mutableListOf(i, i + 1, i + 2, i + 3)
name shouldBe "Box001Mesh"
}
// for further mesh test, follow this issue, https://github.com/assimp/assimp/issues/1561
numMaterials shouldBe 1
with(materials[0]) {
color!!.diffuse shouldBe Vec3(0.600000024f)
name shouldBe "DefaultMaterial"
}
numAnimations shouldBe 1
with(animations[0]) {
name shouldBe ""
duration shouldBe 11.966667175292969
ticksPerSecond shouldBe 1.0
numChannels shouldBe 64
with(channels[0]!!) {
nodeName shouldBe "Box001"
numPositionKeys shouldBe 5
with(positionKeys[0]) {
time shouldBe 0.033332999795675278
value shouldBe Vec3()
}
with(positionKeys[2]) {
time shouldBe 6.0
value shouldBe Vec3()
}
with(positionKeys[4]) {
time shouldBe 11.966667175292969
value shouldBe Vec3()
}
numRotationKeys shouldBe 5
with(rotationKeys[0]) {
time shouldBe 0.033332999795675278
value shouldBe Quat(1f, 0f, 0f, 2.38497613e-08f)
}
with(rotationKeys[2]) {
time shouldBe 6.0
value shouldBe Quat(2.90066708e-07f, 0f, 0f, 1f)
}
with(rotationKeys[4]) {
time shouldBe 11.966667175292969
value shouldBe Quat(1f, 0f, 0f, 3.49691106e-07f)
}
numScalingKeys shouldBe 5
with(scalingKeys[0]) {
time shouldBe 0.033332999795675278
value shouldBe Vec3(1f)
}
with(scalingKeys[2]) {
time shouldBe 6.0
value shouldBe Vec3(1f)
}
with(scalingKeys[4]) {
time shouldBe 11.966667175292969
value shouldBe Vec3(1f)
}
preState shouldBe AiAnimBehaviour.DEFAULT
postState shouldBe AiAnimBehaviour.DEFAULT
}
with(channels[31]!!) {
nodeName shouldBe "Box032"
numPositionKeys shouldBe 5
with(positionKeys[0]) {
time shouldBe 0.033332999795675278
value shouldBe Vec3()
}
with(positionKeys[2]) {
time shouldBe 6.0
value shouldBe Vec3()
}
with(positionKeys[4]) {
time shouldBe 11.966667175292969
value shouldBe Vec3()
}
numRotationKeys shouldBe 5
with(rotationKeys[0]) {
time shouldBe 0.033332999795675278
value shouldBe Quat(1f, 0f, 0f, 2.38497613e-08f)
}
with(rotationKeys[2]) {
time shouldBe 6.0
value shouldBe Quat(2.90066708e-07f, 0f, 0f, 1f)
}
with(rotationKeys[4]) {
time shouldBe 11.966667175292969
value shouldBe Quat(1f, 0f, 0f, 3.49691106e-07f)
}
numScalingKeys shouldBe 5
with(scalingKeys[0]) {
time shouldBe 0.033332999795675278
value shouldBe Vec3(1f)
}
with(scalingKeys[2]) {
time shouldBe 6.0
value shouldBe Vec3(1f)
}
with(scalingKeys[4]) {
time shouldBe 11.966667175292969
value shouldBe Vec3(1f)
}
preState shouldBe AiAnimBehaviour.DEFAULT
postState shouldBe AiAnimBehaviour.DEFAULT
}
with(channels[63]!!) {
nodeName shouldBe "Box064"
numPositionKeys shouldBe 5
with(positionKeys[0]) {
time shouldBe 0.033332999795675278
value shouldBe Vec3()
}
with(positionKeys[2]) {
time shouldBe 6.0
value shouldBe Vec3()
}
with(positionKeys[4]) {
time shouldBe 11.966667175292969
value shouldBe Vec3()
}
numRotationKeys shouldBe 5
with(rotationKeys[0]) {
time shouldBe 0.033332999795675278
value shouldBe Quat(1f, 0f, 0f, 2.38497613e-08f)
}
with(rotationKeys[2]) {
time shouldBe 6.0
value shouldBe Quat(2.90066708e-07f, 0f, 0f, 1f)
}
with(rotationKeys[4]) {
time shouldBe 11.966667175292969
value shouldBe Quat(1f, 0f, 0f, 3.49691106e-07f)
}
numScalingKeys shouldBe 5
with(scalingKeys[0]) {
time shouldBe 0.033332999795675278
value shouldBe Vec3(1f)
}
with(scalingKeys[2]) {
time shouldBe 6.0
value shouldBe Vec3(1f)
}
with(scalingKeys[4]) {
time shouldBe 11.966667175292969
value shouldBe Vec3(1f)
}
preState shouldBe AiAnimBehaviour.DEFAULT
postState shouldBe AiAnimBehaviour.DEFAULT
}
}
}
}
} | mit | 5ccb481590533b36322109e6abdb90b5 | 38.477509 | 101 | 0.40305 | 5.054497 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/primitiveTypes/kt684.kt | 2 | 1951 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
fun escapeChar(c : Char) : String? = when (c) {
'\\' -> "\\\\"
'\n' -> "\\n"
'"' -> "\\\""
else -> "" + c
}
fun String.escape(i : Int = 0, result : String = "") : String =
if (i == length) result
else escape(i + 1, result + escapeChar(get(i)))
fun box() : String {
val s = " System.out?.println(\"fun escapeChar(c : Char) : String? = when (c) {\");\n System.out?.println(\" '\\\\\\\\' => \\\"\\\\\\\\\\\\\\\\\\\"\");\n System.out?.println(\" '\\\\n' => \\\"\\\\\\\\n\\\"\");\n System.out?.println(\" '\\\"' => \\\"\\\\\\\\\\\\\\\"\\\"\");\n System.out?.println(\" else => String.valueOf(c)\");\n System.out?.println(\"}\");\n System.out?.println();\n System.out?.println(\"fun String.escape(i : Int = 0, result : String = \\\"\\\") : String =\");\n System.out?.println(\" if (i == length) result\");\n System.out?.println(\" else escape(i + 1, result + escapeChar(this.get(i)))\");\n System.out?.println();\n System.out?.println(\"fun main(args : Array<String>) {\");\n System.out?.println(\" val s = \\\"\" + s.escape() + \"\\\";\");\n System.out?.println(s);\n}\n";
System.out?.println("fun escapeChar(c : Char) : String? = when (c) {");
System.out?.println(" '\\\\' => \"\\\\\\\\\"");
System.out?.println(" '\\n' => \"\\\\n\"");
System.out?.println(" '\"' => \"\\\\\\\"\"");
System.out?.println(" else => String.valueOf(c)");
System.out?.println("}");
System.out?.println();
System.out?.println("fun String.escape(i : Int = 0, result : String = \"\") : String =");
System.out?.println(" if (i == length) result");
System.out?.println(" else escape(i + 1, result + escapeChar(this.get(i)))");
System.out?.println();
System.out?.println("fun main(args : Array<String>) {");
System.out?.println(" val s = \"" + s.escape() + "\";");
System.out?.println(s);
return "OK"
}
| apache-2.0 | 402a8657b9c2752b76176456aab2d281 | 59.96875 | 826 | 0.527422 | 3.087025 | false | false | false | false |
soulnothing/HarmonyGen | src/main/kotlin/HarmonyGen/MusicAbstractor/Artist.kt | 1 | 3570 | package HarmonyGen.MusicAbstractor
import HarmonyGen.DB.*
import HarmonyGen.HarmonyGenConfig
import HarmonyGen.Util.ArtistQuery
import HarmonyGen.Util.getGenre
import HarmonyGen.Util.getQueryBase
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.collections.emptyList
import kotlin.collections.listOf
import kotlin.collections.map
import de.umass.lastfm.Artist as LastFMArtist
import de.umass.lastfm.Caller as Caller
import HarmonyGen.Util.Artist as HArtist
import HarmonyGen.Util.Track as Track
import HarmonyGen.Util.getUnusedIndice
import animus.design.KMusicBrainz.musicbrainz.Musicbrainz
import co.paralleluniverse.kotlin.select
import com.rethinkdb.RethinkDB
import com.rethinkdb.net.Cursor
import com.sun.org.apache.xpath.internal.operations.Bool
import com.wrapper.spotify.Api as SpotifyAPI
import animus.design.KMusicBrainz.musicbrainz.Tables.ARTIST as MusicBrainzArtist
import org.jooq.Record2;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
/**
* Created by sobrien on 1/9/16.
*/
val logger: Logger = LoggerFactory.getLogger("HarmonyGen")
val r = RethinkDB.r
fun getArtistMBID(artist: String) : String {
val conn = getConnection()
val dsl = getDSL(conn)
val mbid = dsl.select(MusicBrainzArtist.GID)
.from(MusicBrainzArtist)
.where(MusicBrainzArtist.NAME.equalIgnoreCase(artist)).fetch().firstOrNull()
conn.close()
return mbid?.getValue(MusicBrainzArtist.GID).toString()
}
fun getArtistName(mbid: String) : String {
val conn = getConnection()
val dsl = getDSL(conn)
val name = dsl.select(MusicBrainzArtist.NAME)
.from(MusicBrainzArtist)
.where(MusicBrainzArtist.GID.equalIgnoreCase(mbid)).fetch().firstOrNull()
conn.close()
return name?.getValue(MusicBrainzArtist.NAME).toString()
}
fun de.umass.lastfm.Artist.toArtistRecord(genre:List<String>, similar:List<String>) : DBArtist {
var rsp = DBArtist()
rsp.id=this.mbid
rsp.name=this.name
rsp.uris=listOf(ArtistURI(platform="LastFM", uri = this.url))
rsp.genres = genre
rsp.similar = similar
return rsp
}
fun getSimilarArtists(artist_name: String, api_key: String, return_count: Int = 15, tree_depth: Int = 1): List<HArtist> {
val caller = Caller.getInstance().setDebugMode(true)
var SimilarArtists = emptyList<HArtist>()
var Artists = emptyList<HArtist>()
var iteration = 0
for (artist in LastFMArtist.getSimilar(artist_name, api_key)) {
SimilarArtists += HArtist(
Name = artist.name,
Tracks = emptyList<Track>(),
Genres = emptyList<String>()
)
iteration += 1
if (iteration < tree_depth) {
logger.debug("Iteration $iteration of $tree_depth for artist $artist")
val SubSimilar = getSimilarArtists(artist.name, api_key, tree_depth = (tree_depth - 1))
SimilarArtists += SubSimilar
}
}
var usedIndice = listOf<Int>(-1)
for (i in IntRange(0, return_count)) {
val indice = getUnusedIndice(ceiling = SimilarArtists.size, unusedIndice = usedIndice)
val artst = SimilarArtists[indice]
val artist_tracks = LastFMArtist.getTopTracks(artst.Name, api_key).map { x ->
println(x)
Track(
Name = x.name,
Artist = x.artist,
Album = x.album
)
}
Artists += HArtist(
Name = artst.Name,
Tracks = artist_tracks,
Genres = emptyList<String>()
)
}
return Artists
} | bsd-3-clause | 040247911abe3b573374880d55680332 | 32.688679 | 121 | 0.691597 | 3.661538 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/eh/EHentaiUpdateWorker.kt | 1 | 15674 | package exh.eh
import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import android.content.Context
import android.os.Build
import android.support.annotation.RequiresApi
import com.elvishew.xlog.XLog
import com.google.gson.Gson
import com.kizitonwose.time.days
import com.kizitonwose.time.hours
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.library.LibraryUpdateNotifier
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.online.all.EHentai
import eu.kanade.tachiyomi.util.jobScheduler
import eu.kanade.tachiyomi.util.syncChaptersWithSource
import exh.EH_SOURCE_ID
import exh.EXH_SOURCE_ID
import exh.debug.DebugToggles
import exh.eh.EHentaiUpdateWorkerConstants.UPDATES_PER_ITERATION
import exh.metadata.metadata.EHentaiSearchMetadata
import exh.metadata.metadata.base.*
import exh.util.await
import exh.util.cancellable
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import rx.schedulers.Schedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
import kotlin.coroutines.CoroutineContext
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class EHentaiUpdateWorker: JobService(), CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + Job()
private val db: DatabaseHelper by injectLazy()
private val prefs: PreferencesHelper by injectLazy()
private val gson: Gson by injectLazy()
private val sourceManager: SourceManager by injectLazy()
private val updateHelper: EHentaiUpdateHelper by injectLazy()
private val logger = XLog.tag("EHUpdater")
private val updateNotifier by lazy { LibraryUpdateNotifier(this) }
/**
* This method is called if the system has determined that you must stop execution of your job
* even before you've had a chance to call [.jobFinished].
*
*
* This will happen if the requirements specified at schedule time are no longer met. For
* example you may have requested WiFi with
* [android.app.job.JobInfo.Builder.setRequiredNetworkType], yet while your
* job was executing the user toggled WiFi. Another example is if you had specified
* [android.app.job.JobInfo.Builder.setRequiresDeviceIdle], and the phone left its
* idle maintenance window. You are solely responsible for the behavior of your application
* upon receipt of this message; your app will likely start to misbehave if you ignore it.
*
*
* Once this method returns, the system releases the wakelock that it is holding on
* behalf of the job.
*
* @param params The parameters identifying this job, as supplied to
* the job in the [.onStartJob] callback.
* @return `true` to indicate to the JobManager whether you'd like to reschedule
* this job based on the retry criteria provided at job creation-time; or `false`
* to end the job entirely. Regardless of the value returned, your job must stop executing.
*/
override fun onStopJob(params: JobParameters?): Boolean {
runBlocking { [email protected][Job]?.cancelAndJoin() }
return false
}
/**
* Called to indicate that the job has begun executing. Override this method with the
* logic for your job. Like all other component lifecycle callbacks, this method executes
* on your application's main thread.
*
*
* Return `true` from this method if your job needs to continue running. If you
* do this, the job remains active until you call
* [.jobFinished] to tell the system that it has completed
* its work, or until the job's required constraints are no longer satisfied. For
* example, if the job was scheduled using
* [setRequiresCharging(true)][JobInfo.Builder.setRequiresCharging],
* it will be immediately halted by the system if the user unplugs the device from power,
* the job's [.onStopJob] callback will be invoked, and the app
* will be expected to shut down all ongoing work connected with that job.
*
*
* The system holds a wakelock on behalf of your app as long as your job is executing.
* This wakelock is acquired before this method is invoked, and is not released until either
* you call [.jobFinished], or after the system invokes
* [.onStopJob] to notify your job that it is being shut down
* prematurely.
*
*
* Returning `false` from this method means your job is already finished. The
* system's wakelock for the job will be released, and [.onStopJob]
* will not be invoked.
*
* @param params Parameters specifying info about this job, including the optional
* extras configured with [ This object serves to identify this specific running job instance when calling][JobInfo.Builder.setExtras]
*/
override fun onStartJob(params: JobParameters): Boolean {
launch {
startUpdating()
logger.d("Update job completed!")
jobFinished(params, false)
}
return true
}
suspend fun startUpdating() {
logger.d("Update job started!")
val startTime = System.currentTimeMillis()
logger.d("Finding manga with metadata...")
val metadataManga = db.getFavoriteMangaWithMetadata().await()
logger.d("Filtering manga and raising metadata...")
val curTime = System.currentTimeMillis()
val allMeta = metadataManga.asFlow().cancellable().mapNotNull { manga ->
if (manga.source != EH_SOURCE_ID && manga.source != EXH_SOURCE_ID)
return@mapNotNull null
val meta = db.getFlatMetadataForManga(manga.id!!).asRxSingle().await()
?: return@mapNotNull null
val raisedMeta = meta.raise<EHentaiSearchMetadata>()
// Don't update galleries too frequently
if (raisedMeta.aged || (curTime - raisedMeta.lastUpdateCheck < MIN_BACKGROUND_UPDATE_FREQ && DebugToggles.RESTRICT_EXH_GALLERY_UPDATE_CHECK_FREQUENCY.enabled))
return@mapNotNull null
val chapter = db.getChaptersByMangaId(manga.id!!).asRxSingle().await().minBy {
it.date_upload
}
UpdateEntry(manga, raisedMeta, chapter)
}.toList().sortedBy { it.meta.lastUpdateCheck }
logger.d("Found %s manga to update, starting updates!", allMeta.size)
val mangaMetaToUpdateThisIter = allMeta.take(UPDATES_PER_ITERATION)
var failuresThisIteration = 0
var updatedThisIteration = 0
val updatedManga = mutableListOf<Manga>()
val modifiedThisIteration = mutableSetOf<Long>()
try {
for ((index, entry) in mangaMetaToUpdateThisIter.withIndex()) {
val (manga, meta) = entry
if (failuresThisIteration > MAX_UPDATE_FAILURES) {
logger.w("Too many update failures, aborting...")
break
}
logger.d("Updating gallery (index: %s, manga.id: %s, meta.gId: %s, meta.gToken: %s, failures-so-far: %s, modifiedThisIteration.size: %s)...",
index,
manga.id,
meta.gId,
meta.gToken,
failuresThisIteration,
modifiedThisIteration.size)
if (manga.id in modifiedThisIteration) {
// We already processed this manga!
logger.w("Gallery already updated this iteration, skipping...")
updatedThisIteration++
continue
}
val (new, chapters) = try {
updateEntryAndGetChapters(manga)
} catch (e: GalleryNotUpdatedException) {
if (e.network) {
failuresThisIteration++
logger.e("> Network error while updating gallery!", e)
logger.e("> (manga.id: %s, meta.gId: %s, meta.gToken: %s, failures-so-far: %s)",
manga.id,
meta.gId,
meta.gToken,
failuresThisIteration)
}
continue
}
if (chapters.isEmpty()) {
logger.e("No chapters found for gallery (manga.id: %s, meta.gId: %s, meta.gToken: %s, failures-so-far: %s)!",
manga.id,
meta.gId,
meta.gToken,
failuresThisIteration)
continue
}
// Find accepted root and discard others
val (acceptedRoot, discardedRoots, hasNew) =
updateHelper.findAcceptedRootAndDiscardOthers(manga.source, chapters).await()
if((new.isNotEmpty() && manga.id == acceptedRoot.manga.id)
|| (hasNew && updatedManga.none { it.id == acceptedRoot.manga.id })) {
updatedManga += acceptedRoot.manga
}
modifiedThisIteration += acceptedRoot.manga.id!!
modifiedThisIteration += discardedRoots.map { it.manga.id!! }
updatedThisIteration++
}
} finally {
prefs.eh_autoUpdateStats().set(
gson.toJson(
EHentaiUpdaterStats(
startTime,
allMeta.size,
updatedThisIteration
)
)
)
if(updatedManga.isNotEmpty()) {
updateNotifier.showResultNotification(updatedManga)
}
}
}
// New, current
suspend fun updateEntryAndGetChapters(manga: Manga): Pair<List<Chapter>, List<Chapter>> {
val source = sourceManager.get(manga.source) as? EHentai
?: throw GalleryNotUpdatedException(false, IllegalStateException("Missing EH-based source (${manga.source})!"))
try {
val updatedManga = source.fetchMangaDetails(manga).toSingle().await(Schedulers.io())
manga.copyFrom(updatedManga)
db.insertManga(manga).asRxSingle().await()
val newChapters = source.fetchChapterList(manga).toSingle().await(Schedulers.io())
val (new, _) = syncChaptersWithSource(db, newChapters, manga, source) // Not suspending, but does block, maybe fix this?
return new to db.getChapters(manga).await()
} catch(t: Throwable) {
if(t is EHentai.GalleryNotFoundException) {
val meta = db.getFlatMetadataForManga(manga.id!!).await()?.raise<EHentaiSearchMetadata>()
if(meta != null) {
// Age dead galleries
meta.aged = true
db.insertFlatMetadata(meta.flatten()).await()
}
throw GalleryNotUpdatedException(false, t)
}
throw GalleryNotUpdatedException(true, t)
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
companion object {
private const val MAX_UPDATE_FAILURES = 5
private val MIN_BACKGROUND_UPDATE_FREQ = 1.days.inMilliseconds.longValue
private const val JOB_ID_UPDATE_BACKGROUND = 700000
private const val JOB_ID_UPDATE_BACKGROUND_TEST = 700001
private val logger by lazy { XLog.tag("EHUpdaterScheduler") }
private fun Context.componentName(): ComponentName {
return ComponentName(this, EHentaiUpdateWorker::class.java)
}
private fun Context.baseBackgroundJobInfo(isTest: Boolean): JobInfo.Builder {
return JobInfo.Builder(
if(isTest) JOB_ID_UPDATE_BACKGROUND_TEST
else JOB_ID_UPDATE_BACKGROUND, componentName())
}
private fun Context.periodicBackgroundJobInfo(period: Long,
requireCharging: Boolean,
requireUnmetered: Boolean): JobInfo {
return baseBackgroundJobInfo(false)
.setPeriodic(period)
.setPersisted(true)
.setRequiredNetworkType(
if(requireUnmetered) JobInfo.NETWORK_TYPE_UNMETERED
else JobInfo.NETWORK_TYPE_ANY)
.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setRequiresBatteryNotLow(true)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
setEstimatedNetworkBytes(15000L * UPDATES_PER_ITERATION,
1000L * UPDATES_PER_ITERATION)
}
}
.setRequiresCharging(requireCharging)
// .setRequiresDeviceIdle(true) Job never seems to run with this
.build()
}
private fun Context.testBackgroundJobInfo(): JobInfo {
return baseBackgroundJobInfo(true)
.setOverrideDeadline(1)
.build()
}
fun launchBackgroundTest(context: Context) {
val jobScheduler = context.jobScheduler
if(jobScheduler.schedule(context.testBackgroundJobInfo()) == JobScheduler.RESULT_FAILURE) {
logger.e("Failed to schedule background test job!")
} else {
logger.d("Successfully scheduled background test job!")
}
}
fun scheduleBackground(context: Context, prefInterval: Int? = null) {
cancelBackground(context)
val preferences = Injekt.get<PreferencesHelper>()
val interval = prefInterval ?: preferences.eh_autoUpdateFrequency().getOrDefault()
if (interval > 0) {
val restrictions = preferences.eh_autoUpdateRequirements()!!
val acRestriction = "ac" in restrictions
val wifiRestriction = "wifi" in restrictions
val jobInfo = context.periodicBackgroundJobInfo(
interval.hours.inMilliseconds.longValue,
acRestriction,
wifiRestriction
)
if(context.jobScheduler.schedule(jobInfo) == JobScheduler.RESULT_FAILURE) {
logger.e("Failed to schedule background update job!")
} else {
logger.d("Successfully scheduled background update job!")
}
}
}
fun cancelBackground(context: Context) {
context.jobScheduler.cancel(JOB_ID_UPDATE_BACKGROUND)
}
}
}
data class UpdateEntry(val manga: Manga, val meta: EHentaiSearchMetadata, val rootChapter: Chapter?)
object EHentaiUpdateWorkerConstants {
const val UPDATES_PER_ITERATION = 50
val GALLERY_AGE_TIME = 365.days.inMilliseconds.longValue
}
| apache-2.0 | 8a343eb2fad7c22c96cd7d14fcf7390b | 42.298343 | 171 | 0.606801 | 4.907326 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/components/Tabs.kt | 1 | 1664 | package eu.kanade.presentation.components
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.TabPosition
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun TabIndicator(currentTabPosition: TabPosition) {
TabRowDefaults.Indicator(
Modifier
.tabIndicatorOffset(currentTabPosition)
.padding(horizontal = 8.dp)
.clip(RoundedCornerShape(topStart = 3.dp, topEnd = 3.dp)),
)
}
@Composable
fun TabText(
text: String,
badgeCount: Int? = null,
isCurrentPage: Boolean,
) {
val pillAlpha = if (isSystemInDarkTheme()) 0.12f else 0.08f
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = text,
color = if (isCurrentPage) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onBackground,
)
if (badgeCount != null) {
Pill(
text = "$badgeCount",
color = MaterialTheme.colorScheme.onBackground.copy(alpha = pillAlpha),
fontSize = 10.sp,
)
}
}
}
| apache-2.0 | b117680c04b4f6231bf3f705d9b98b14 | 31 | 117 | 0.713341 | 4.402116 | false | false | false | false |
da1z/intellij-community | python/src/com/jetbrains/python/debugger/PySetNextStatementAction.kt | 2 | 3596 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.debugger
import com.intellij.codeInsight.hint.HintManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pair
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.impl.DebuggerSupport
import com.intellij.xdebugger.impl.XDebuggerUtilImpl
import com.intellij.xdebugger.impl.actions.XDebuggerActionBase
import com.intellij.xdebugger.impl.actions.XDebuggerSuspendedActionHandler
import com.jetbrains.python.debugger.pydev.PyDebugCallback
class PySetNextStatementAction : XDebuggerActionBase(true) {
private val setNextStatementActionHandler: XDebuggerSuspendedActionHandler
init {
setNextStatementActionHandler = object : XDebuggerSuspendedActionHandler() {
override fun perform(session: XDebugSession, dataContext: DataContext) {
val debugProcess = session.debugProcess as? PyDebugProcess ?: return
val position = XDebuggerUtilImpl.getCaretPosition(session.project, dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(dataContext) ?: FileEditorManager.getInstance(session.project).selectedTextEditor
val suspendContext = debugProcess.session.suspendContext
ApplicationManager.getApplication().executeOnPooledThread(Runnable {
debugProcess.startSetNextStatement(suspendContext, position, object : PyDebugCallback<Pair<Boolean, String>> {
override fun ok(response: Pair<Boolean, String>) {
if (!response.first && editor != null) {
ApplicationManager.getApplication().invokeLater(Runnable {
if (!editor.isDisposed) {
editor.caretModel.moveToOffset(position.offset)
HintManager.getInstance().showErrorHint(editor, response.second)
}
}, ModalityState.defaultModalityState())
}
}
override fun error(e: PyDebuggerException) {
LOG.error(e)
}
})
})
}
override fun isEnabled(project: Project, event: AnActionEvent): Boolean {
return super.isEnabled(project, event) && PyDebugSupportUtils.isPythonConfigurationSelected(project)
}
}
}
override fun getHandler(debuggerSupport: DebuggerSupport) = setNextStatementActionHandler
override fun isHidden(event: AnActionEvent): Boolean {
return !PyDebugSupportUtils.isPythonConfigurationSelected(event.getData(CommonDataKeys.PROJECT))
}
companion object {
private val LOG = Logger.getInstance("#com.jetbrains.python.debugger.PySetNextStatementAction")
}
}
| apache-2.0 | 6bb11306c55ecd24320cb860721082cf | 43.95 | 132 | 0.747775 | 5.001391 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/mark/VimMarkGroupBase.kt | 1 | 14608 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.mark
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.getLineEndOffset
import com.maddyhome.idea.vim.api.getOffset
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.normalizeOffset
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.diagnostic.debug
import com.maddyhome.idea.vim.diagnostic.vimLogger
import com.maddyhome.idea.vim.helper.vimStateMachine
import java.util.*
abstract class VimMarkGroupBase : VimMarkGroup {
@JvmField
protected val fileMarks = HashMap<String, FileMarks<Char, Mark>>()
@JvmField
protected val globalMarks = HashMap<Char, Mark>()
@JvmField
// COMPATIBILITY-LAYER: Changed to public
// Please see: https://jb.gg/zo8n0r
// Use dropLastJump method instead of direct access
/*protected*/ val jumps: MutableList<Jump> = ArrayList<Jump>()
@JvmField
protected var jumpSpot = -1
protected class FileMarks<K, V> : HashMap<K, V>() {
var myTimestamp = Date()
fun setTimestamp(timestamp: Date) {
this.myTimestamp = timestamp
}
override fun put(key: K, value: V): V? {
myTimestamp = Date()
return super.put(key, value)
}
}
/**
* This updates all the marks for a file whenever text is deleted from the file. If the line that contains a mark
* is completely deleted then the mark is deleted too. If the deleted text is before the marked line, the mark is
* moved up by the number of deleted lines.
*
* @param editor The modified editor
* @param marks The editor's marks to update
* @param delStartOff The offset within the editor where the deletion occurred
* @param delLength The length of the deleted text
*/
override fun updateMarkFromDelete(editor: VimEditor?, marks: HashMap<Char, Mark>?, delStartOff: Int, delLength: Int) {
// Skip all this work if there are no marks
if (marks != null && marks.size > 0 && editor != null) {
// Calculate the buffer position of the start and end of the deleted text
val delEndOff = delStartOff + delLength - 1
val delStart = editor.offsetToBufferPosition(delStartOff)
val delEnd = editor.offsetToBufferPosition(delEndOff + 1)
logger.debug { "mark delete. delStart = $delStart, delEnd = $delEnd" }
// Now analyze each mark to determine if it needs to be updated or removed
for (ch in marks.keys) {
val myMark = marks[ch]
if (myMark !is VimMark) continue
logger.debug { "mark = $myMark" }
// If the end of the deleted text is prior to the marked line, simply shift the mark up by the
// proper number of lines.
if (delEnd.line < myMark.line) {
val lines = delEnd.line - delStart.line
logger.debug { "Shifting mark by $lines lines" }
myMark.line = myMark.line - lines
} else if (delStart.line <= myMark.line/* && delEnd.line >= mark.line*/) {
// Regarding the commented out condition in if: This additional condition was here before moving to kotlin
// But now it's highlighted as "always true", so I commented it out for case of it's a bug
val markLineStartOff = editor.getLineStartOffset(myMark.line)
val markLineEndOff = editor.getLineEndOffset(myMark.line, true)
val command = editor.vimStateMachine.executingCommand
// If text is being changed from the start of the mark line (a special case for mark deletion)
val changeFromMarkLineStart = (command != null && command.type === Command.Type.CHANGE && delStartOff == markLineStartOff)
// If the marked line is completely within the deleted text, remove the mark (except the special case)
if (delStartOff <= markLineStartOff && delEndOff >= markLineEndOff && !changeFromMarkLineStart) {
injector.markGroup.removeMark(ch, myMark)
logger.debug("Removed mark")
} else if (delStart.line < myMark.line) {
// shift mark
myMark.line = delStart.line
logger.debug { "Shifting mark to line " + delStart.line }
} // The deletion only covers part of the marked line so shift the mark only if the deletion begins
// on a line prior to the marked line (which means the deletion must end on the marked line).
} // If the deleted text begins before the mark and ends after the mark then it may be shifted or deleted
}
}
}
/**
* This updates all the marks for a file whenever text is inserted into the file. If the line that contains a mark
* that is after the start of the insertion point, shift the mark by the number of new lines added.
*
* @param editor The editor that was updated
* @param marks The editor's marks
* @param insStartOff The insertion point
* @param insLength The length of the insertion
*/
override fun updateMarkFromInsert(editor: VimEditor?, marks: HashMap<Char, Mark>?, insStartOff: Int, insLength: Int) {
if (marks != null && marks.size > 0 && editor != null) {
val insEndOff = insStartOff + insLength
val insStart = editor.offsetToBufferPosition(insStartOff)
val insEnd = editor.offsetToBufferPosition(insEndOff)
logger.debug { "mark insert. insStart = $insStart, insEnd = $insEnd" }
val lines = insEnd.line - insStart.line
if (lines == 0) return
for (mark in marks.values.filterIsInstance<VimMark>()) {
logger.debug { "mark = $mark" }
// Shift the mark if the insertion began on a line prior to the marked line.
if (insStart.line < mark.line) {
mark.line = mark.line + lines
logger.debug { "Shifting mark by $lines lines" }
}
}
}
}
companion object {
private val logger = vimLogger<VimMarkGroupBase>()
const val SAVE_JUMP_COUNT = 100
}
override fun addJump(editor: VimEditor, reset: Boolean) {
addJump(editor, editor.currentCaret().offset.point, reset)
}
private fun addJump(editor: VimEditor, offset: Int, reset: Boolean) {
val path = editor.getPath() ?: return
val position = editor.offsetToBufferPosition(offset)
val jump = Jump(position.line, position.column, path)
val filename = jump.filepath
for (i in jumps.indices) {
val j = jumps[i]
if (filename == j.filepath && j.line == jump.line) {
jumps.removeAt(i)
break
}
}
jumps.add(jump)
if (reset) {
jumpSpot = -1
} else {
jumpSpot++
}
if (jumps.size > SAVE_JUMP_COUNT) {
jumps.removeAt(0)
}
}
/**
* Gets the map of marks for the specified file
*
* @param filename The file to get the marks for
* @return The map of marks. The keys are `Character`s of the mark names, the values are
* `Mark`s.
*/
protected fun getFileMarks(filename: String): FileMarks<Char, Mark> {
return fileMarks.getOrPut(filename) { FileMarks() }
}
/**
* Gets the requested mark for the editor
*
* @param editor The editor to get the mark for
* @param ch The desired mark
* @return The requested mark if set, null if not set
*/
override fun getMark(editor: VimEditor, ch: Char): Mark? {
var myCh = ch
var mark: Mark? = null
if (myCh == '`') myCh = '\''
// Make sure this is a valid mark
if (VimMarkConstants.VALID_GET_MARKS.indexOf(myCh) < 0) return null
val editorPath = editor.getPath()
if ("{}".indexOf(myCh) >= 0 && editorPath != null) {
var offset = injector.searchHelper.findNextParagraph(
editor, editor.primaryCaret(), if (myCh == '{') -1 else 1,
false
)
offset = editor.normalizeOffset(offset, false)
val position = editor.offsetToBufferPosition(offset)
mark = VimMark(myCh, position.line, position.column, editorPath, editor.extractProtocol())
} else if ("()".indexOf(myCh) >= 0 && editorPath != null) {
var offset = injector.searchHelper
.findNextSentenceStart(
editor, editor.primaryCaret(), if (myCh == '(') -1 else 1,
countCurrent = false,
requireAll = true
)
offset = editor.normalizeOffset(offset, false)
val position = editor.offsetToBufferPosition(offset)
mark = VimMark(myCh, position.line, position.column, editorPath, editor.extractProtocol())
} else if (VimMarkConstants.FILE_MARKS.indexOf(myCh) >= 0) {
var fmarks: FileMarks<Char, Mark>? = null
if (editorPath != null) {
fmarks = getFileMarks(editorPath)
}
if (fmarks != null) {
mark = fmarks[myCh]
if (mark != null && mark.isClear()) {
fmarks.remove(myCh)
mark = null
}
}
} else if (VimMarkConstants.GLOBAL_MARKS.indexOf(myCh) >= 0) {
mark = globalMarks[myCh]
if (mark != null && mark.isClear()) {
globalMarks.remove(myCh)
mark = null
}
} // This is a mark from another file
// If this is a file mark, get the mark from this file
return mark
}
/**
* Get the requested jump.
*
* @param count Postive for next jump (Ctrl-I), negative for previous jump (Ctrl-O).
* @return The jump or null if out of range.
*/
override fun getJump(count: Int): Jump? {
val index = jumps.size - 1 - (jumpSpot - count)
return if (index < 0 || index >= jumps.size) {
null
} else {
jumpSpot -= count
jumps[index]
}
}
/**
* Sets the specified mark to the specified location.
*
* @param editor The editor the mark is associated with
* @param ch The mark to set
* @param offset The offset to set the mark to
* @return true if able to set the mark, false if not
*/
override fun setMark(editor: VimEditor, ch: Char, offset: Int): Boolean {
var myCh = ch
if (myCh == '`') myCh = '\''
val position = editor.offsetToBufferPosition(offset)
val path = editor.getPath() ?: return false
// File specific marks get added to the file
if (VimMarkConstants.FILE_MARKS.indexOf(myCh) >= 0) {
val fmarks = getFileMarks(path)
val mark = VimMark(myCh, position.line, position.column, path, editor.extractProtocol())
fmarks[myCh] = mark
} else if (VimMarkConstants.GLOBAL_MARKS.indexOf(myCh) >= 0) {
val fmarks = getFileMarks(path)
var mark = createSystemMark(myCh, position.line, position.column, editor)
if (mark == null) {
mark = VimMark(myCh, position.line, position.column, path, editor.extractProtocol())
}
fmarks[myCh] = mark
val oldMark = globalMarks.put(myCh, mark)
if (oldMark is VimMark) {
oldMark.clear()
}
} // Global marks get set to both the file and the global list of marks
return true
}
/**
* Sets the specified mark to the caret position of the editor
*
* @param editor The editor to get the current position from
* @param ch The mark set set
* @return True if a valid, writable mark, false if not
*/
override fun setMark(editor: VimEditor, ch: Char): Boolean {
return VimMarkConstants.VALID_SET_MARKS.indexOf(ch) >= 0 && setMark(
editor,
ch,
editor.currentCaret().offset.point
)
}
/**
* Saves the caret location prior to doing a jump
*
* @param editor The editor the jump will occur in
*/
override fun saveJumpLocation(editor: VimEditor) {
addJump(editor, true)
setMark(editor, '\'')
includeCurrentCommandAsNavigation(editor)
}
/**
* Get's a mark from the file
*
* @param editor The editor to get the mark from
* @param ch The mark to get
* @return The mark in the current file, if set, null if no such mark
*/
override fun getFileMark(editor: VimEditor, ch: Char): Mark? {
var myCh = ch
if (myCh == '`') myCh = '\''
val path = editor.getPath() ?: return null
val fmarks = getFileMarks(path)
var mark: Mark? = fmarks[myCh]
if (mark != null && mark.isClear()) {
fmarks.remove(myCh)
mark = null
}
return mark
}
override fun setVisualSelectionMarks(editor: VimEditor, range: TextRange) {
setMark(editor, VimMarkConstants.MARK_VISUAL_START, range.startOffset)
setMark(editor, VimMarkConstants.MARK_VISUAL_END, range.endOffset)
}
override fun setChangeMarks(vimEditor: VimEditor, range: TextRange) {
setMark(vimEditor, VimMarkConstants.MARK_CHANGE_START, range.startOffset)
setMark(vimEditor, VimMarkConstants.MARK_CHANGE_END, range.endOffset - 1)
}
private fun getMarksRange(editor: VimEditor, startMark: Char, endMark: Char): TextRange? {
val start = getMark(editor, startMark)
val end = getMark(editor, endMark)
if (start != null && end != null) {
val startOffset = editor.getOffset(start.line, start.col)
val endOffset = editor.getOffset(end.line, end.col)
return TextRange(startOffset, endOffset + 1)
}
return null
}
override fun getChangeMarks(editor: VimEditor): TextRange? {
return getMarksRange(editor, VimMarkConstants.MARK_CHANGE_START, VimMarkConstants.MARK_CHANGE_END)
}
override fun getVisualSelectionMarks(editor: VimEditor): TextRange? {
return getMarksRange(editor, VimMarkConstants.MARK_VISUAL_START, VimMarkConstants.MARK_VISUAL_END)
}
override fun resetAllMarks() {
globalMarks.clear()
fileMarks.clear()
jumps.clear()
}
override fun removeMark(ch: Char, mark: Mark) {
if (VimMarkConstants.FILE_MARKS.indexOf(ch) >= 0) {
val fmarks = getFileMarks(mark.filename)
fmarks.remove(ch)
} else if (VimMarkConstants.GLOBAL_MARKS.indexOf(ch) >= 0) {
// Global marks are added to global and file marks
val fmarks = getFileMarks(mark.filename)
fmarks.remove(ch)
globalMarks.remove(ch)
}
mark.clear()
}
override fun getMarks(editor: VimEditor): List<Mark> {
val res = HashSet<Mark>()
val path = editor.getPath()
if (path != null) {
val marks = getFileMarks(path)
res.addAll(marks.values)
}
res.addAll(globalMarks.values)
val list = ArrayList(res)
list.sortWith(Mark.KeySorter)
return list
}
override fun getJumps(): List<Jump> {
return jumps
}
override fun getJumpSpot(): Int {
return jumpSpot
}
override fun dropLastJump() {
jumps.dropLast(1)
}
}
| mit | de6bb04b4f05f4fc8b2e678cf35203ab | 33.698337 | 132 | 0.654299 | 3.888209 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/reader/views/ReaderTagHeaderView.kt | 1 | 1452 | package org.wordpress.android.ui.reader.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.RelativeLayout
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.ReaderTagHeaderViewBinding
import org.wordpress.android.ui.reader.views.ReaderTagHeaderViewUiState.ReaderTagHeaderUiState
import org.wordpress.android.ui.utils.UiHelpers
import javax.inject.Inject
/**
* topmost view in post adapter when showing tag preview - displays tag name and follow button
*/
class ReaderTagHeaderView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
private val binding = ReaderTagHeaderViewBinding.inflate(LayoutInflater.from(context), this, true)
@Inject lateinit var uiHelpers: UiHelpers
private var onFollowBtnClicked: (() -> Unit)? = null
init {
(context.applicationContext as WordPress).component().inject(this)
binding.followButton.setOnClickListener { onFollowBtnClicked?.invoke() }
}
fun updateUi(uiState: ReaderTagHeaderUiState) = with(binding) {
textTag.text = uiState.title
with(uiState.followButtonUiState) {
followButton.setIsFollowed(isFollowed)
followButton.isEnabled = isEnabled
onFollowBtnClicked = onFollowButtonClicked
}
}
}
| gpl-2.0 | 14f396fb16e706c87968615481c1cf05 | 35.3 | 102 | 0.756198 | 4.714286 | false | false | false | false |
android/architecture-components-samples | GithubBrowserSample/app/src/main/java/com/android/example/github/db/RepoDao.kt | 1 | 3135 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.github.db
import android.util.SparseIntArray
import androidx.lifecycle.LiveData
import androidx.lifecycle.map
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.android.example.github.testing.OpenForTesting
import com.android.example.github.vo.Contributor
import com.android.example.github.vo.Repo
import com.android.example.github.vo.RepoSearchResult
/**
* Interface for database access on Repo related operations.
*/
@Dao
@OpenForTesting
abstract class RepoDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insert(vararg repos: Repo)
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertContributors(contributors: List<Contributor>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertRepos(repositories: List<Repo>)
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun createRepoIfNotExists(repo: Repo): Long
@Query("SELECT * FROM repo WHERE owner_login = :ownerLogin AND name = :name")
abstract fun load(ownerLogin: String, name: String): LiveData<Repo>
@Query(
"""
SELECT login, avatarUrl, repoName, repoOwner, contributions FROM contributor
WHERE repoName = :name AND repoOwner = :owner
ORDER BY contributions DESC"""
)
abstract fun loadContributors(owner: String, name: String): LiveData<List<Contributor>>
@Query(
"""
SELECT * FROM Repo
WHERE owner_login = :owner
ORDER BY stars DESC"""
)
abstract fun loadRepositories(owner: String): LiveData<List<Repo>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insert(result: RepoSearchResult)
@Query("SELECT * FROM RepoSearchResult WHERE `query` = :query")
abstract fun search(query: String): LiveData<RepoSearchResult?>
fun loadOrdered(repoIds: List<Int>): LiveData<List<Repo>> {
val order = SparseIntArray()
repoIds.withIndex().forEach {
order.put(it.value, it.index)
}
return loadById(repoIds).map { repositories ->
repositories.sortedWith(compareBy { order.get(it.id) })
}
}
@Query("SELECT * FROM Repo WHERE id in (:repoIds)")
protected abstract fun loadById(repoIds: List<Int>): LiveData<List<Repo>>
@Query("SELECT * FROM RepoSearchResult WHERE `query` = :query")
abstract fun findSearchResult(query: String): RepoSearchResult?
}
| apache-2.0 | d9e8f19302020327794205b506daac38 | 33.833333 | 91 | 0.719298 | 4.378492 | false | false | false | false |
simoneapp/S3-16-simone | app/src/main/java/app/simone/multiplayer/view/invites/InvitesFragment.kt | 2 | 4321 | package app.simone.multiplayer.view.invites
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ListView
import app.simone.multiplayer.controller.DataManager
import app.simone.multiplayer.controller.FacebookManagerActor
import app.simone.multiplayer.model.OnlineMatch
import app.simone.shared.application.App
import app.simone.shared.utils.Constants
import app.simone.shared.utils.Utilities
import com.facebook.Profile
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
/**
* This class represents the GUI where a user, after the Facebook login, can see the list of friends and send them a game request.
*
* @author Giacomo
*/
class InvitesFragment : Fragment() {
var rootView : View? = null
var listViewRequests : ListView? = null
var requestsAdapter : PendingRequestsAdapter? = null
var requestsUsers = ArrayList<OnlineMatch>()
var myStrategy = StrategyImpl()
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater?.inflate(app.simone.R.layout.activity_invites_fragment, container, false)
initRequestsList()
listenForChanges()
val actor = Utilities.getActor(Constants.FBVIEW_ACTOR_NAME, App.getInstance().actorSystem)
val btnInvites = rootView?.findViewById(app.simone.R.id.btn_invite) as FloatingActionButton
btnInvites.setOnClickListener({
actor.tell(app.simone.multiplayer.messages.FbSendGameRequestMsg(), akka.actor.ActorRef.noSender())
})
return rootView!!
}
/**
* This method initializes the list view and it hooks a click listener on each cell.
*
*/
private fun initRequestsList() {
listViewRequests = rootView?.findViewById(app.simone.R.id.list_invites) as android.widget.ListView
if(app.simone.multiplayer.controller.FacebookManagerActor.Companion.isLoggedIn()) {
requestsAdapter = PendingRequestsAdapter(requestsUsers, activity)
listViewRequests?.adapter = requestsAdapter
listViewRequests?.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
requestsUsers[position]
println("ARRAY: " + position)
}
updateRequests()
}
}
/**
* This method simply updates the match list of a given user.
*
*/
fun updateRequests() {
if (this.activity != null) {
this.activity.runOnUiThread {
if (requestsUsers.isNotEmpty() && FacebookManagerActor.Companion.isLoggedIn()) {
requestsUsers = DataManager.Companion.instance.filterRequests(requestsUsers, Profile.getCurrentProfile().id)
requestsAdapter?.clear()
requestsAdapter?.addAll(requestsUsers)
}
}
}
}
override fun onResume() {
super.onResume()
if(FacebookManagerActor.Companion.isLoggedIn() && Profile.getCurrentProfile() != null) {
updateRequests()
}
}
/**
* This method is listening for changes on the database. In case some values are updated, the list is updated consequently.
* It has been used a Strategy Pattern: the list of matches is filtered by userID. All the algorithm is encapsulated inside the class StrategyImpl.
* DataSnapshot is an object containing all the matches store into the database.
*/
fun listenForChanges() {
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
requestsUsers.clear()
requestsUsers.addAll(myStrategy.getRequestsUsers(dataSnapshot))
updateRequests()
}
override fun onCancelled(databaseError: DatabaseError) {
println("Error while retrieving data from DB")
}
}
DataManager.Companion.instance.database?.addValueEventListener(postListener)
}
}
| mit | 08f75348ca81ad059993d0ba10b70a7d | 36.573913 | 152 | 0.694978 | 4.795782 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertConcatenationToBuildStringIntention.kt | 1 | 4560 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.elementType
import com.intellij.psi.util.nextLeafs
import com.intellij.psi.util.siblings
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ConvertConcatenationToBuildStringIntention : SelfTargetingIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("convert.concatenation.to.build.string")
) {
override fun isApplicableTo(element: KtBinaryExpression, caretOffset: Int): Boolean {
return element.isConcatenation() && !element.parent.isConcatenation() && !element.mustBeConstant()
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val buildStringCall = KtPsiFactory(element).buildExpression {
appendFixedText("kotlin.text.buildString {\n")
element.allExpressions().forEach { expression ->
appendFixedText("append(")
if (expression is KtStringTemplateExpression) {
val singleEntry = expression.entries.singleOrNull()
if (singleEntry is KtStringTemplateEntryWithExpression) {
appendExpression(singleEntry.expression)
} else {
appendNonFormattedText(expression.text)
}
} else {
appendExpression(expression)
}
appendFixedText(")")
val tailComments = expression.tailComments()
if (tailComments.isNotEmpty()) {
appendFixedText(" ")
tailComments.forEach { appendNonFormattedText(it.text) }
}
appendFixedText("\n")
}
appendFixedText("}")
}
element.deleteTailComments()
val replaced = element.replaced(buildStringCall)
ShortenReferences.DEFAULT.process(replaced)
}
private fun PsiElement.isConcatenation(): Boolean {
if (this !is KtBinaryExpression) return false
if (operationToken != KtTokens.PLUS) return false
val type = getType(safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)) ?: return false
return KotlinBuiltIns.isString(type)
}
private fun KtBinaryExpression.allExpressions(): List<KtExpression> {
val expressions = mutableListOf<KtExpression>()
fun collect(expression: KtExpression?) {
when (expression) {
is KtBinaryExpression -> {
collect(expression.left)
collect(expression.right)
}
is KtExpression ->
expressions.add(expression)
}
}
collect(this)
return expressions
}
private fun KtExpression.tailComments(): List<PsiElement> {
val tailElements = this.nextLeafs
.takeWhile { it is PsiWhiteSpace || it is PsiComment || it.elementType == KtTokens.PLUS }
.dropWhile { it !is PsiComment }
return if (tailElements.any { it is PsiComment }) {
tailElements.toList().dropLastWhile { it is PsiWhiteSpace }
} else {
emptyList()
}
}
private fun KtExpression.deleteTailComments() {
siblings(withSelf = false)
.takeWhile { !it.isWhiteSpaceWithLineBreak() }
.filter { it is PsiComment }
.forEach { it.delete() }
}
private fun PsiElement.isWhiteSpaceWithLineBreak() = this is PsiWhiteSpace && this.textContains('\n')
}
internal fun KtExpression.mustBeConstant(): Boolean = this.parents.any { it is KtAnnotationEntry }
| apache-2.0 | 73d42b3dd4cf75cde526061cae2ce904 | 41.222222 | 158 | 0.662281 | 5.320887 | false | false | false | false |
micolous/metrodroid | src/commonTest/kotlin/au/id/micolous/metrodroid/test/VirtualClassic.kt | 1 | 4579 | package au.id.micolous.metrodroid.test
import au.id.micolous.metrodroid.card.classic.ClassicAccessBits
import au.id.micolous.metrodroid.card.classic.ClassicCardTech
import au.id.micolous.metrodroid.key.ClassicSectorKey
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.util.toImmutable
class VirtualClassic(private val raw: ImmutableByteArray) : ClassicCardTech {
// Currently authenticated sector, -1 if none
private var authSector: Int = -1
// Currently authenticated sector key
private var authKey: ClassicSectorKey.KeyType = ClassicSectorKey.KeyType.UNKNOWN
internal var authCounter: Int = 0
private set
internal var readCounter: Int = 0
private set
override val tagId: ImmutableByteArray
get() = raw.sliceOffLen(0, if (raw[0] == 4.toByte()) 7 else 4)
private fun getKey(sectorIndex: Int, keyType: ClassicSectorKey.KeyType): ImmutableByteArray {
val trailerBlock = sectorToBlock(sectorIndex) + getBlockCountInSector(sectorIndex) - 1
val trailerOffset = BLOCK_SIZE * trailerBlock
val keyOffset = when (keyType) {
ClassicSectorKey.KeyType.A -> 0
ClassicSectorKey.KeyType.B -> 10
else -> throw IllegalArgumentException()
}
return raw.sliceOffLen(trailerOffset + keyOffset, 6)
}
private fun getAccessBits(sectorIndex: Int): ImmutableByteArray {
val trailerBlock = sectorToBlock(sectorIndex) + getBlockCountInSector(sectorIndex) - 1
val trailerOffset = BLOCK_SIZE * trailerBlock
return raw.sliceOffLen(trailerOffset + 6, 4)
}
private fun maskOutTrailer(accBits: ImmutableByteArray, block: ImmutableByteArray): ImmutableByteArray {
val keyZero = ImmutableByteArray(6) { 0 }
if (!ClassicAccessBits(accBits).isKeyBReadable)
return keyZero + block.sliceOffLen(6, 4) + keyZero
else
return keyZero + block.sliceOffLen(6, 10)
}
override suspend fun authenticate(sectorIndex: Int, key: ClassicSectorKey): Boolean {
authCounter++
val type = key.type
val accBits = getAccessBits(sectorIndex)
Log.d(TAG, "auth ${key.key}, ${key.type} vs ${getKey(sectorIndex, type)}, accbits=$accBits")
if (key.key != getKey(sectorIndex, type)
// TODO: verify behaviour in these 2 cases on a real card
|| (key.type == ClassicSectorKey.KeyType.B && ClassicAccessBits(accBits).isKeyBReadable)
|| !ClassicAccessBits.isAccBitsValid(accBits)) {
authSector = -1
authKey = ClassicSectorKey.KeyType.UNKNOWN
return false
}
authSector = sectorIndex
authKey = type
return true
}
override val sectorCount
get() = when (raw.size) {
1024 -> 16
2048 -> 32
4096 -> 40
else -> throw IllegalArgumentException()
}
override suspend fun readBlock(block: Int): ImmutableByteArray {
readCounter++
val sectorIdx = blockToSector(block)
// TODO: verify behaviour in this case on real card
if (authSector != sectorIdx)
return byteArrayOf(4).toImmutable()
val blockOffset = block - sectorToBlock(sectorIdx)
val blockContents = raw.sliceOffLen(BLOCK_SIZE * block, BLOCK_SIZE)
val accBits = getAccessBits(sectorIdx)
val blkCnt = getBlockCountInSector(sectorIdx)
if (!ClassicAccessBits.isAccBitsValid(accBits))
return byteArrayOf(4).toImmutable()
if (blockOffset == blkCnt - 1) {
return maskOutTrailer(accBits, blockContents)
}
val slot = when(blkCnt) {
4 -> blockOffset
16 -> blockOffset / 5
else -> throw IllegalArgumentException()
}
if (!ClassicAccessBits(accBits).isDataBlockReadable(slot, authKey))
return byteArrayOf(4).toImmutable()
return blockContents
}
private fun blockToSector(block: Int): Int =
if (block < 128) block / 4 else ((block + 32*12) / 16)
override fun getBlockCountInSector(sectorIndex: Int) = if (sectorIndex >= 32) 16 else 4
override fun sectorToBlock(sectorIndex: Int) = if (sectorIndex < 32) sectorIndex * 4 else
(16 * sectorIndex - 32 * 12)
companion object {
internal const val BLOCK_SIZE = 16
private const val TAG = "VirtualClassic"
}
} | gpl-3.0 | 13565b7e1445fcf9177f4bf4bc520dc3 | 40.261261 | 108 | 0.65713 | 4.428433 | false | false | false | false |
rubengees/ktask | ktask/src/main/kotlin/com/rubengees/ktask/util/TaskBuilder.kt | 1 | 4413 | package com.rubengees.ktask.util
import com.rubengees.ktask.base.Task
import com.rubengees.ktask.operation.*
import com.rubengees.ktask.operation.CacheTask.CacheStrategy
/**
* Utility class for constructing tasks in a fluent way.
*
* @author Ruben Gees
*/
class TaskBuilder<I, O, T : Task<I, O>> private constructor(private val currentTask: T) {
companion object {
/**
* Creates a new [TaskBuilder] from the given task.
*/
fun <I, O, T : Task<I, O>> task(task: T) = TaskBuilder(task)
/**
* Creates a new [TaskBuilder] with an [AttemptTask] and given [leftTask] and [rightTask] as root.
*/
fun <I, O> attemptTask(leftTask: Task<I, O>, rightTask: Task<I, O>) = task(AttemptTask(leftTask, rightTask))
}
/**
* Caches results of the previous tasks.
*/
fun cache(strategy: CacheStrategy = CacheStrategy.FULL) = task(CacheTask(currentTask, strategy))
/**
* Modifies the result line, to also return the input of the previous task.
*/
fun inputEcho() = task(InputEchoTask(currentTask))
/**
* Maps the result to a new type.
*/
fun <M> map(function: (O) -> M) = task(MapTask(currentTask, function))
/**
* Maps the input to a new type.
*/
fun <OI> mapInput(function: (OI) -> I) = TaskBuilder.task(MapInputTask(currentTask, function))
/**
* Runs the previous task in parallel with another given task.
*
* Note that this requires both tasks, to be [AsynchronousTask]s at some point.
*/
fun <OI, OO, FO> parallelWith(
other: Task<OI, OO>, zipFunction: (O, OO) -> FO,
awaitLeftResultOnError: Boolean = false,
awaitRightResultOnError: Boolean = false
) = task(ParallelTask(AsynchronousTask(currentTask), AsynchronousTask(other), zipFunction,
awaitLeftResultOnError, awaitRightResultOnError))
/**
* Runs the previous task in parallel with another given [TaskBuilder].
*
* Note that this requires both tasks, to be [AsynchronousTask]s at some point.
*/
fun <OI, OO, T : Task<OI, OO>, FO> parallelWith(
other: TaskBuilder<OI, OO, T>, zipFunction: (O, OO) -> FO,
awaitLeftResultOnError: Boolean = false,
awaitRightResultOnError: Boolean = false
) = task(ParallelTask(AsynchronousTask(currentTask), AsynchronousTask(other.build()), zipFunction,
awaitLeftResultOnError, awaitRightResultOnError))
/**
* Runs the previous task with the given in series (the previous task first).
*/
fun <OI, OO> then(other: Task<OI, OO>, mapFunction: (O) -> OI = {
@Suppress("UNCHECKED_CAST")
it as OI
}) = task(StreamTask(currentTask, other, mapFunction))
/**
* Runs the previous task with the given [TaskBuilder] in series (the previous task first).
*/
fun <OI, OO, T : Task<OI, OO>> then(other: TaskBuilder<OI, OO, T>, mapFunction: (O) -> OI = {
@Suppress("UNCHECKED_CAST")
it as OI
}) = task(StreamTask(currentTask, other.build(), mapFunction))
/**
* Validates the input before the previous task.
*/
fun validateBefore(function: (I) -> Unit) = task(ValidatingTask(currentTask, function))
/**
* Makes the previous task run in a separate thread.
*/
fun async() = task(AsynchronousTask(build()))
/**
* Sets a new callback on the current task, called on start.
*/
fun onStart(callback: () -> Unit) = this.apply { currentTask.onStart(callback) }
/**
* Sets a new callback on the current task, called on success.
*/
fun onSuccess(callback: (O) -> Unit) = this.apply { currentTask.onSuccess(callback) }
/**
* Sets a new callback on the current task, called on error.
*/
fun onError(callback: (Throwable) -> Unit) = this.apply { currentTask.onError(callback) }
/**
* Sets a new callback on the current task, called on finish.
*/
fun onFinish(callback: () -> Unit) = this.apply { currentTask.onFinish(callback) }
/**
* Sets a new callback on the leftmost inner [com.rubengees.ktask.base.LeafTask], called on start.
*/
fun onInnerStart(callback: () -> Unit) = this.apply { currentTask.onInnerStart(callback) }
/**
* Finally constructs the usable task.
*/
fun build(): T {
return currentTask
}
}
| mit | 1f90a44d6d9e806dd7065f66c92a12e7 | 33.209302 | 116 | 0.627918 | 3.814175 | false | false | false | false |
ianhanniballake/ContractionTimer | mobile/src/main/java/com/ianhanniballake/contractiontimer/appwidget/DetailAppWidgetRemoteViewsService.kt | 1 | 6034 | package com.ianhanniballake.contractiontimer.appwidget
import android.annotation.TargetApi
import android.content.ContentUris
import android.content.Intent
import android.database.Cursor
import android.os.Binder
import android.os.Build
import android.preference.PreferenceManager
import android.provider.BaseColumns
import android.text.format.DateFormat
import android.text.format.DateUtils
import android.widget.AdapterView
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import com.ianhanniballake.contractiontimer.R
import com.ianhanniballake.contractiontimer.provider.ContractionContract.Contractions
import com.ianhanniballake.contractiontimer.ui.Preferences
/**
* Service which creates the RemoteViews used in the ListView collection in the Detail App Widgets
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class DetailAppWidgetRemoteViewsService : RemoteViewsService() {
override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
return object : RemoteViewsFactory {
private var data: Cursor? = null
override fun getCount() = data?.count ?: 0
override fun getItemId(position: Int) = data?.run {
val idColumnIndex = getColumnIndex(BaseColumns._ID)
if (moveToPosition(position)) getLong(idColumnIndex) else position.toLong()
} ?: position.toLong()
override fun getLoadingView(): RemoteViews {
val preferences = PreferenceManager
.getDefaultSharedPreferences(this@DetailAppWidgetRemoteViewsService)
val appwidgetBackground = preferences.getString(
Preferences.APPWIDGET_BACKGROUND_PREFERENCE_KEY,
getString(R.string.pref_appwidget_background_default))
return if (appwidgetBackground == "light")
RemoteViews(packageName, R.layout.list_item_detail_appwidget_loading_light)
else
RemoteViews(packageName, R.layout.list_item_detail_appwidget_loading_dark)
}
override fun getViewAt(position: Int): RemoteViews {
val context = this@DetailAppWidgetRemoteViewsService
val preferences = PreferenceManager
.getDefaultSharedPreferences(context)
val appwidgetBackground = preferences.getString(
Preferences.APPWIDGET_BACKGROUND_PREFERENCE_KEY,
getString(R.string.pref_appwidget_background_default))
val views = if (appwidgetBackground == "light")
RemoteViews(packageName, R.layout.list_item_detail_appwidget_light)
else
RemoteViews(packageName, R.layout.list_item_detail_appwidget_dark)
val data = data
if (position == AdapterView.INVALID_POSITION || data == null || !data.moveToPosition(position))
return views
val timeFormat = if (DateFormat.is24HourFormat(context))
"kk:mm:ss"
else
"hh:mm:ssa"
val startTimeColumnIndex = data
.getColumnIndex(Contractions.COLUMN_NAME_START_TIME)
val startTime = data.getLong(startTimeColumnIndex)
views.setTextViewText(R.id.start_time, DateFormat.format(timeFormat, startTime))
val endTimeColumnIndex = data
.getColumnIndex(Contractions.COLUMN_NAME_END_TIME)
val isContractionOngoing = data.isNull(endTimeColumnIndex)
if (isContractionOngoing) {
views.setTextViewText(R.id.end_time, " ")
views.setTextViewText(R.id.duration, getString(R.string.duration_ongoing))
} else {
val endTime = data.getLong(endTimeColumnIndex)
views.setTextViewText(R.id.end_time, DateFormat.format(timeFormat, endTime))
val durationInSeconds = (endTime - startTime) / 1000
views.setTextViewText(R.id.duration, DateUtils.formatElapsedTime(durationInSeconds))
}
// If we aren't the last entry, move to the next (previous in time)
// contraction to get its start time to compute the frequency
if (!data.isLast && data.moveToNext()) {
val prevContractionStartTimeColumnIndex = data
.getColumnIndex(Contractions.COLUMN_NAME_START_TIME)
val prevContractionStartTime = data.getLong(prevContractionStartTimeColumnIndex)
val frequencyInSeconds = (startTime - prevContractionStartTime) / 1000
views.setTextViewText(R.id.frequency, DateUtils.formatElapsedTime(frequencyInSeconds))
// Go back to the previous spot
data.moveToPrevious()
}
val fillInIntent = Intent()
val idColumnIndex = data.getColumnIndex(BaseColumns._ID)
val id = data.getLong(idColumnIndex)
fillInIntent.data = ContentUris.withAppendedId(Contractions.CONTENT_ID_URI_BASE, id)
views.setOnClickFillInIntent(R.id.list_item_detail_appwidget, fillInIntent)
return views
}
override fun getViewTypeCount() = 1
override fun hasStableIds() = true
override fun onCreate() {
// Nothing to do
}
override fun onDataSetChanged() {
val token = Binder.clearCallingIdentity()
data?.close()
data = contentResolver.query(Contractions.CONTENT_URI, null, null, null, null)
Binder.restoreCallingIdentity(token)
}
override fun onDestroy() {
data?.close()?.also {
data = null
}
}
}
}
}
| bsd-3-clause | 001ea2b72519222bb18c026680f8f33a | 48.056911 | 111 | 0.617667 | 5.455696 | false | false | false | false |
csumissu/WeatherForecast | app/src/main/java/csumissu/weatherforecast/util/LocationLiveData.kt | 1 | 2794 | package csumissu.weatherforecast.util
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Transformations
import android.content.Context
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import csumissu.weatherforecast.di.ForApplication
import csumissu.weatherforecast.extensions.locationManager
import csumissu.weatherforecast.model.Coordinate
import io.reactivex.Maybe
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
import org.jetbrains.anko.info
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
/**
* @author yxsun
* @since 01/06/2017
*/
@Singleton
class LocationLiveData
@Inject constructor(@ForApplication context: Context,
private val mSchedulerProvider: BaseSchedulerProvider)
: LiveData<Coordinate>(), AnkoLogger {
private val mGeocoder = Geocoder(context)
private val mLocationManager = context.locationManager
private val mListener = object : SimpleLocationListener() {
override fun onLocationChanged(location: Location?) {
info("onLocationChanged() $location")
updateCurrentLocation(location)
}
}
private val mAddress = Transformations.switchMap(this) { coordinate ->
val result = MutableLiveData<Address>()
getFromLocation(coordinate)
.subscribeOn(mSchedulerProvider.io())
.observeOn(mSchedulerProvider.ui())
.subscribe { result.value = it }
result
}
override fun onActive() {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500F, mListener)
}
override fun onInactive() {
mLocationManager.removeUpdates(mListener)
}
fun getAddress(): LiveData<Address> {
return mAddress
}
private fun updateCurrentLocation(location: Location?) {
val coordinate = Coordinate(location?.latitude, location?.longitude)
if (value != coordinate) {
value = coordinate
}
}
private fun getFromLocation(coordinate: Coordinate?): Maybe<Address> {
info("getFromLocation() $coordinate")
return Maybe.create {
try {
val results = if (coordinate == null) null else {
mGeocoder.getFromLocation(coordinate.latitude, coordinate.longitude, 1)
}
if (results != null && results.isNotEmpty()) {
it.onSuccess(results[0])
}
} catch (e: IOException) {
error("Get address from location failed", e)
}
it.onComplete()
}
}
} | mit | 0a5f26ce83c55ac2ee2e19a09f92fa38 | 30.761364 | 101 | 0.672513 | 5.145488 | false | false | false | false |
GunoH/intellij-community | plugins/editorconfig/src/org/editorconfig/language/schema/parser/handlers/impl/EditorConfigQualifiedOptionKeyDescriptorParseHandler.kt | 16 | 2100 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.schema.parser.handlers.impl
import com.google.gson.JsonObject
import org.editorconfig.language.schema.descriptors.EditorConfigDescriptor
import org.editorconfig.language.schema.descriptors.impl.EditorConfigQualifiedKeyDescriptor
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.DEPRECATION
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.DOCUMENTATION
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.LIST
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.OPTION
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.PAIR
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.QUALIFIED
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.TYPE
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.VALUES
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaException
import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaParser
import org.editorconfig.language.schema.parser.handlers.EditorConfigDescriptorParseHandlerBase
class EditorConfigQualifiedOptionKeyDescriptorParseHandler : EditorConfigDescriptorParseHandlerBase() {
override val requiredKeys = listOf(TYPE, VALUES)
override val forbiddenChildren = listOf(PAIR, LIST, OPTION, QUALIFIED)
override fun doHandle(jsonObject: JsonObject, parser: EditorConfigJsonSchemaParser): EditorConfigDescriptor {
val rawValues = jsonObject[VALUES]
if (!rawValues.isJsonArray) {
throw EditorConfigJsonSchemaException(jsonObject)
}
val values = rawValues.asJsonArray.map(parser::parse)
val documentation = tryGetString(jsonObject, DOCUMENTATION)
val deprecation = tryGetString(jsonObject, DEPRECATION)
return EditorConfigQualifiedKeyDescriptor(values, documentation, deprecation)
}
}
| apache-2.0 | adca816888ff88ba250c3df982870041 | 60.764706 | 140 | 0.855714 | 5.276382 | false | true | false | false |
GunoH/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/LinesBuilder.kt | 4 | 1199 | package com.intellij.workspaceModel.codegen.utils
class LinesBuilder(
val result: StringBuilder,
val indentLevel: Int,
val indentSize: Int = 4
) {
var first = true
fun line(str: String = "") {
lineNoNl(str)
result.append('\n')
}
fun lineNoNl(str: String) {
if (first) {
first = false
}
result.append(" ".repeat(indentLevel * indentSize))
result.append(str)
}
fun <T> list(c: Collection<T>, f: T.() -> String = { "$this" }) {
c.forEach {
line(it.f())
}
}
fun section(s: LinesBuilder.() -> Unit) {
LinesBuilder(result, indentLevel + 1, indentSize).s()
}
fun section(head: String, s: LinesBuilder.() -> Unit) {
lineNoNl(head)
val sub = LinesBuilder(result, indentLevel+1, indentSize)
sub.result.append(" {\n")
sub.s()
line("}")
}
fun sectionNoBrackets(head: String, s: LinesBuilder.() -> Unit) {
lineNoNl(head)
val sub = LinesBuilder(result, indentLevel+1, indentSize)
sub.result.append("\n")
sub.s()
}
}
inline fun lines(level: Int = 0, lines: LinesBuilder.() -> Unit): String {
val result = StringBuilder()
LinesBuilder(result, level).lines()
return result.toString()
} | apache-2.0 | b8c7bf24c21ba4c96e971e62cc3096b8 | 21.222222 | 74 | 0.616347 | 3.485465 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/database/SignalDatabase.kt | 1 | 19464 | package org.thoughtcrime.securesms.database
import android.app.Application
import android.content.Context
import net.zetetic.database.sqlcipher.SQLiteOpenHelper
import org.signal.core.util.SqlUtil
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.crypto.AttachmentSecret
import org.thoughtcrime.securesms.crypto.DatabaseSecret
import org.thoughtcrime.securesms.crypto.MasterSecret
import org.thoughtcrime.securesms.database.helpers.ClassicOpenHelper
import org.thoughtcrime.securesms.database.helpers.PreKeyMigrationHelper
import org.thoughtcrime.securesms.database.helpers.SQLCipherMigrationHelper
import org.thoughtcrime.securesms.database.helpers.SessionStoreMigrationHelper
import org.thoughtcrime.securesms.database.helpers.SignalDatabaseMigrations
import org.thoughtcrime.securesms.database.helpers.SignalDatabaseMigrations.migrate
import org.thoughtcrime.securesms.database.helpers.SignalDatabaseMigrations.migratePostTransaction
import org.thoughtcrime.securesms.database.model.AvatarPickerDatabase
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobs.RefreshPreKeysJob
import org.thoughtcrime.securesms.migrations.LegacyMigrationJob
import org.thoughtcrime.securesms.migrations.LegacyMigrationJob.DatabaseUpgradeListener
import org.thoughtcrime.securesms.service.KeyCachingService
import org.thoughtcrime.securesms.util.TextSecurePreferences
import java.io.File
open class SignalDatabase(private val context: Application, databaseSecret: DatabaseSecret, attachmentSecret: AttachmentSecret) :
SQLiteOpenHelper(
context,
DATABASE_NAME,
databaseSecret.asString(),
null,
SignalDatabaseMigrations.DATABASE_VERSION,
0,
SqlCipherErrorHandler(DATABASE_NAME),
SqlCipherDatabaseHook()
),
SignalDatabaseOpenHelper {
val sms: SmsDatabase = SmsDatabase(context, this)
val mms: MmsDatabase = MmsDatabase(context, this)
val attachments: AttachmentDatabase = AttachmentDatabase(context, this, attachmentSecret)
val media: MediaDatabase = MediaDatabase(context, this)
val thread: ThreadDatabase = ThreadDatabase(context, this)
val mmsSmsDatabase: MmsSmsDatabase = MmsSmsDatabase(context, this)
val identityDatabase: IdentityDatabase = IdentityDatabase(context, this)
val draftDatabase: DraftDatabase = DraftDatabase(context, this)
val pushDatabase: PushDatabase = PushDatabase(context, this)
val groupDatabase: GroupDatabase = GroupDatabase(context, this)
val recipientDatabase: RecipientDatabase = RecipientDatabase(context, this)
val groupReceiptDatabase: GroupReceiptDatabase = GroupReceiptDatabase(context, this)
val preKeyDatabase: OneTimePreKeyDatabase = OneTimePreKeyDatabase(context, this)
val signedPreKeyDatabase: SignedPreKeyDatabase = SignedPreKeyDatabase(context, this)
val sessionDatabase: SessionDatabase = SessionDatabase(context, this)
val senderKeyDatabase: SenderKeyDatabase = SenderKeyDatabase(context, this)
val senderKeySharedDatabase: SenderKeySharedDatabase = SenderKeySharedDatabase(context, this)
val pendingRetryReceiptDatabase: PendingRetryReceiptDatabase = PendingRetryReceiptDatabase(context, this)
val searchDatabase: SearchDatabase = SearchDatabase(context, this)
val stickerDatabase: StickerDatabase = StickerDatabase(context, this, attachmentSecret)
val storageIdDatabase: UnknownStorageIdDatabase = UnknownStorageIdDatabase(context, this)
val remappedRecordsDatabase: RemappedRecordsDatabase = RemappedRecordsDatabase(context, this)
val mentionDatabase: MentionDatabase = MentionDatabase(context, this)
val paymentDatabase: PaymentDatabase = PaymentDatabase(context, this)
val chatColorsDatabase: ChatColorsDatabase = ChatColorsDatabase(context, this)
val emojiSearchDatabase: EmojiSearchDatabase = EmojiSearchDatabase(context, this)
val messageSendLogDatabase: MessageSendLogDatabase = MessageSendLogDatabase(context, this)
val avatarPickerDatabase: AvatarPickerDatabase = AvatarPickerDatabase(context, this)
val groupCallRingDatabase: GroupCallRingDatabase = GroupCallRingDatabase(context, this)
val reactionDatabase: ReactionDatabase = ReactionDatabase(context, this)
val notificationProfileDatabase: NotificationProfileDatabase = NotificationProfileDatabase(context, this)
val donationReceiptDatabase: DonationReceiptDatabase = DonationReceiptDatabase(context, this)
val distributionListDatabase: DistributionListDatabase = DistributionListDatabase(context, this)
val storySendsDatabase: StorySendsDatabase = StorySendsDatabase(context, this)
val cdsDatabase: CdsDatabase = CdsDatabase(context, this)
val remoteMegaphoneDatabase: RemoteMegaphoneDatabase = RemoteMegaphoneDatabase(context, this)
override fun onOpen(db: net.zetetic.database.sqlcipher.SQLiteDatabase) {
db.enableWriteAheadLogging()
db.setForeignKeyConstraintsEnabled(true)
}
override fun onCreate(db: net.zetetic.database.sqlcipher.SQLiteDatabase) {
db.execSQL(SmsDatabase.CREATE_TABLE)
db.execSQL(MmsDatabase.CREATE_TABLE)
db.execSQL(AttachmentDatabase.CREATE_TABLE)
db.execSQL(ThreadDatabase.CREATE_TABLE)
db.execSQL(IdentityDatabase.CREATE_TABLE)
db.execSQL(DraftDatabase.CREATE_TABLE)
db.execSQL(PushDatabase.CREATE_TABLE)
db.execSQL(GroupDatabase.CREATE_TABLE)
db.execSQL(RecipientDatabase.CREATE_TABLE)
db.execSQL(GroupReceiptDatabase.CREATE_TABLE)
db.execSQL(OneTimePreKeyDatabase.CREATE_TABLE)
db.execSQL(SignedPreKeyDatabase.CREATE_TABLE)
db.execSQL(SessionDatabase.CREATE_TABLE)
db.execSQL(SenderKeyDatabase.CREATE_TABLE)
db.execSQL(SenderKeySharedDatabase.CREATE_TABLE)
db.execSQL(PendingRetryReceiptDatabase.CREATE_TABLE)
db.execSQL(StickerDatabase.CREATE_TABLE)
db.execSQL(UnknownStorageIdDatabase.CREATE_TABLE)
db.execSQL(MentionDatabase.CREATE_TABLE)
db.execSQL(PaymentDatabase.CREATE_TABLE)
db.execSQL(ChatColorsDatabase.CREATE_TABLE)
db.execSQL(EmojiSearchDatabase.CREATE_TABLE)
db.execSQL(AvatarPickerDatabase.CREATE_TABLE)
db.execSQL(GroupCallRingDatabase.CREATE_TABLE)
db.execSQL(ReactionDatabase.CREATE_TABLE)
db.execSQL(DonationReceiptDatabase.CREATE_TABLE)
db.execSQL(StorySendsDatabase.CREATE_TABLE)
db.execSQL(CdsDatabase.CREATE_TABLE)
db.execSQL(RemoteMegaphoneDatabase.CREATE_TABLE)
executeStatements(db, SearchDatabase.CREATE_TABLE)
executeStatements(db, RemappedRecordsDatabase.CREATE_TABLE)
executeStatements(db, MessageSendLogDatabase.CREATE_TABLE)
executeStatements(db, NotificationProfileDatabase.CREATE_TABLE)
executeStatements(db, DistributionListDatabase.CREATE_TABLE)
executeStatements(db, RecipientDatabase.CREATE_INDEXS)
executeStatements(db, SmsDatabase.CREATE_INDEXS)
executeStatements(db, MmsDatabase.CREATE_INDEXS)
executeStatements(db, AttachmentDatabase.CREATE_INDEXS)
executeStatements(db, ThreadDatabase.CREATE_INDEXS)
executeStatements(db, DraftDatabase.CREATE_INDEXS)
executeStatements(db, GroupDatabase.CREATE_INDEXS)
executeStatements(db, GroupReceiptDatabase.CREATE_INDEXES)
executeStatements(db, StickerDatabase.CREATE_INDEXES)
executeStatements(db, UnknownStorageIdDatabase.CREATE_INDEXES)
executeStatements(db, MentionDatabase.CREATE_INDEXES)
executeStatements(db, PaymentDatabase.CREATE_INDEXES)
executeStatements(db, MessageSendLogDatabase.CREATE_INDEXES)
executeStatements(db, GroupCallRingDatabase.CREATE_INDEXES)
executeStatements(db, NotificationProfileDatabase.CREATE_INDEXES)
executeStatements(db, DonationReceiptDatabase.CREATE_INDEXS)
db.execSQL(StorySendsDatabase.CREATE_INDEX)
executeStatements(db, MessageSendLogDatabase.CREATE_TRIGGERS)
executeStatements(db, ReactionDatabase.CREATE_TRIGGERS)
DistributionListDatabase.insertInitialDistributionListAtCreationTime(db)
if (context.getDatabasePath(ClassicOpenHelper.NAME).exists()) {
val legacyHelper = ClassicOpenHelper(context)
val legacyDb = legacyHelper.writableDatabase
SQLCipherMigrationHelper.migratePlaintext(context, legacyDb, db)
val masterSecret = KeyCachingService.getMasterSecret(context)
if (masterSecret != null) SQLCipherMigrationHelper.migrateCiphertext(context, masterSecret, legacyDb, db, null) else TextSecurePreferences.setNeedsSqlCipherMigration(context, true)
if (!PreKeyMigrationHelper.migratePreKeys(context, db)) {
ApplicationDependencies.getJobManager().add(RefreshPreKeysJob())
}
SessionStoreMigrationHelper.migrateSessions(context, db)
PreKeyMigrationHelper.cleanUpPreKeys(context)
}
}
override fun onUpgrade(db: net.zetetic.database.sqlcipher.SQLiteDatabase, oldVersion: Int, newVersion: Int) {
Log.i(TAG, "Upgrading database: $oldVersion, $newVersion")
val startTime = System.currentTimeMillis()
db.beginTransaction()
try {
migrate(context, db, oldVersion, newVersion)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
migratePostTransaction(context, oldVersion)
Log.i(TAG, "Upgrade complete. Took " + (System.currentTimeMillis() - startTime) + " ms.")
}
override fun getReadableDatabase(): net.zetetic.database.sqlcipher.SQLiteDatabase {
throw UnsupportedOperationException("Call getSignalReadableDatabase() instead!")
}
override fun getWritableDatabase(): net.zetetic.database.sqlcipher.SQLiteDatabase {
throw UnsupportedOperationException("Call getSignalWritableDatabase() instead!")
}
open val rawReadableDatabase: net.zetetic.database.sqlcipher.SQLiteDatabase
get() = super.getReadableDatabase()
open val rawWritableDatabase: net.zetetic.database.sqlcipher.SQLiteDatabase
get() = super.getWritableDatabase()
open val signalReadableDatabase: SQLiteDatabase
get() = SQLiteDatabase(super.getReadableDatabase())
open val signalWritableDatabase: SQLiteDatabase
get() = SQLiteDatabase(super.getWritableDatabase())
override fun getSqlCipherDatabase(): net.zetetic.database.sqlcipher.SQLiteDatabase {
return super.getWritableDatabase()
}
open fun markCurrent(db: net.zetetic.database.sqlcipher.SQLiteDatabase) {
db.version = SignalDatabaseMigrations.DATABASE_VERSION
}
private fun executeStatements(db: net.zetetic.database.sqlcipher.SQLiteDatabase, statements: Array<String>) {
for (statement in statements) db.execSQL(statement)
}
companion object {
private val TAG = Log.tag(SignalDatabase::class.java)
private const val DATABASE_NAME = "signal.db"
@JvmStatic
@Volatile
var instance: SignalDatabase? = null
private set
@JvmStatic
fun init(application: Application, databaseSecret: DatabaseSecret, attachmentSecret: AttachmentSecret) {
if (instance == null) {
synchronized(SignalDatabase::class.java) {
if (instance == null) {
instance = SignalDatabase(application, databaseSecret, attachmentSecret)
}
}
}
}
@JvmStatic
val rawDatabase: net.zetetic.database.sqlcipher.SQLiteDatabase
get() = instance!!.rawWritableDatabase
@JvmStatic
val backupDatabase: net.zetetic.database.sqlcipher.SQLiteDatabase
get() = instance!!.rawReadableDatabase
@JvmStatic
@get:JvmName("inTransaction")
val inTransaction: Boolean
get() = instance!!.rawWritableDatabase.inTransaction()
@JvmStatic
fun runPostSuccessfulTransaction(dedupeKey: String, task: Runnable) {
instance!!.signalReadableDatabase.runPostSuccessfulTransaction(dedupeKey, task)
}
@JvmStatic
fun runPostSuccessfulTransaction(task: Runnable) {
instance!!.signalReadableDatabase.runPostSuccessfulTransaction(task)
}
@JvmStatic
fun databaseFileExists(context: Context): Boolean {
return context.getDatabasePath(DATABASE_NAME).exists()
}
@JvmStatic
fun getDatabaseFile(context: Context): File {
return context.getDatabasePath(DATABASE_NAME)
}
@JvmStatic
fun upgradeRestored(database: net.zetetic.database.sqlcipher.SQLiteDatabase) {
synchronized(SignalDatabase::class.java) {
instance!!.onUpgrade(database, database.getVersion(), -1)
instance!!.markCurrent(database)
instance!!.sms.deleteAbandonedMessages()
instance!!.mms.deleteAbandonedMessages()
instance!!.mms.trimEntriesForExpiredMessages()
instance!!.reactionDatabase.deleteAbandonedReactions()
instance!!.rawWritableDatabase.execSQL("DROP TABLE IF EXISTS key_value")
instance!!.rawWritableDatabase.execSQL("DROP TABLE IF EXISTS megaphone")
instance!!.rawWritableDatabase.execSQL("DROP TABLE IF EXISTS job_spec")
instance!!.rawWritableDatabase.execSQL("DROP TABLE IF EXISTS constraint_spec")
instance!!.rawWritableDatabase.execSQL("DROP TABLE IF EXISTS dependency_spec")
instance!!.rawWritableDatabase.close()
triggerDatabaseAccess()
}
}
@JvmStatic
fun hasTable(table: String): Boolean {
return SqlUtil.tableExists(instance!!.rawReadableDatabase, table)
}
@JvmStatic
fun triggerDatabaseAccess() {
instance!!.signalWritableDatabase
}
@Deprecated("Only used for a legacy migration.")
@JvmStatic
fun onApplicationLevelUpgrade(
context: Context,
masterSecret: MasterSecret,
fromVersion: Int,
listener: DatabaseUpgradeListener?
) {
instance!!.signalWritableDatabase
var legacyOpenHelper: ClassicOpenHelper? = null
if (fromVersion < LegacyMigrationJob.ASYMMETRIC_MASTER_SECRET_FIX_VERSION) {
legacyOpenHelper = ClassicOpenHelper(context)
legacyOpenHelper.onApplicationLevelUpgrade(context, masterSecret, fromVersion, listener)
}
if (fromVersion < LegacyMigrationJob.SQLCIPHER && TextSecurePreferences.getNeedsSqlCipherMigration(context)) {
if (legacyOpenHelper == null) {
legacyOpenHelper = ClassicOpenHelper(context)
}
SQLCipherMigrationHelper.migrateCiphertext(
context,
masterSecret,
legacyOpenHelper.writableDatabase,
instance!!.rawWritableDatabase,
listener
)
}
}
@JvmStatic
fun runInTransaction(operation: Runnable) {
instance!!.signalWritableDatabase.beginTransaction()
try {
operation.run()
instance!!.signalWritableDatabase.setTransactionSuccessful()
} finally {
instance!!.signalWritableDatabase.endTransaction()
}
}
@get:JvmStatic
@get:JvmName("attachments")
val attachments: AttachmentDatabase
get() = instance!!.attachments
@get:JvmStatic
@get:JvmName("avatarPicker")
val avatarPicker: AvatarPickerDatabase
get() = instance!!.avatarPickerDatabase
@get:JvmStatic
@get:JvmName("cds")
val cds: CdsDatabase
get() = instance!!.cdsDatabase
@get:JvmStatic
@get:JvmName("chatColors")
val chatColors: ChatColorsDatabase
get() = instance!!.chatColorsDatabase
@get:JvmStatic
@get:JvmName("distributionLists")
val distributionLists: DistributionListDatabase
get() = instance!!.distributionListDatabase
@get:JvmStatic
@get:JvmName("donationReceipts")
val donationReceipts: DonationReceiptDatabase
get() = instance!!.donationReceiptDatabase
@get:JvmStatic
@get:JvmName("drafts")
val drafts: DraftDatabase
get() = instance!!.draftDatabase
@get:JvmStatic
@get:JvmName("emojiSearch")
val emojiSearch: EmojiSearchDatabase
get() = instance!!.emojiSearchDatabase
@get:JvmStatic
@get:JvmName("groupCallRings")
val groupCallRings: GroupCallRingDatabase
get() = instance!!.groupCallRingDatabase
@get:JvmStatic
@get:JvmName("groupReceipts")
val groupReceipts: GroupReceiptDatabase
get() = instance!!.groupReceiptDatabase
@get:JvmStatic
@get:JvmName("groups")
val groups: GroupDatabase
get() = instance!!.groupDatabase
@get:JvmStatic
@get:JvmName("identities")
val identities: IdentityDatabase
get() = instance!!.identityDatabase
@get:JvmStatic
@get:JvmName("media")
val media: MediaDatabase
get() = instance!!.media
@get:JvmStatic
@get:JvmName("mentions")
val mentions: MentionDatabase
get() = instance!!.mentionDatabase
@get:JvmStatic
@get:JvmName("messageSearch")
val messageSearch: SearchDatabase
get() = instance!!.searchDatabase
@get:JvmStatic
@get:JvmName("messageLog")
val messageLog: MessageSendLogDatabase
get() = instance!!.messageSendLogDatabase
@get:JvmStatic
@get:JvmName("mms")
val mms: MmsDatabase
get() = instance!!.mms
@get:JvmStatic
@get:JvmName("mmsSms")
val mmsSms: MmsSmsDatabase
get() = instance!!.mmsSmsDatabase
@get:JvmStatic
@get:JvmName("notificationProfiles")
val notificationProfiles: NotificationProfileDatabase
get() = instance!!.notificationProfileDatabase
@get:JvmStatic
@get:JvmName("payments")
val payments: PaymentDatabase
get() = instance!!.paymentDatabase
@get:JvmStatic
@get:JvmName("pendingRetryReceipts")
val pendingRetryReceipts: PendingRetryReceiptDatabase
get() = instance!!.pendingRetryReceiptDatabase
@get:JvmStatic
@get:JvmName("oneTimePreKeys")
val oneTimePreKeys: OneTimePreKeyDatabase
get() = instance!!.preKeyDatabase
@get:Deprecated("This only exists to migrate from legacy storage. There shouldn't be any new usages.")
@get:JvmStatic
@get:JvmName("push")
val push: PushDatabase
get() = instance!!.pushDatabase
@get:JvmStatic
@get:JvmName("recipients")
val recipients: RecipientDatabase
get() = instance!!.recipientDatabase
@get:JvmStatic
@get:JvmName("signedPreKeys")
val signedPreKeys: SignedPreKeyDatabase
get() = instance!!.signedPreKeyDatabase
@get:JvmStatic
@get:JvmName("sms")
val sms: SmsDatabase
get() = instance!!.sms
@get:JvmStatic
@get:JvmName("threads")
val threads: ThreadDatabase
get() = instance!!.thread
@get:JvmStatic
@get:JvmName("reactions")
val reactions: ReactionDatabase
get() = instance!!.reactionDatabase
@get:JvmStatic
@get:JvmName("remappedRecords")
val remappedRecords: RemappedRecordsDatabase
get() = instance!!.remappedRecordsDatabase
@get:JvmStatic
@get:JvmName("senderKeys")
val senderKeys: SenderKeyDatabase
get() = instance!!.senderKeyDatabase
@get:JvmStatic
@get:JvmName("senderKeyShared")
val senderKeyShared: SenderKeySharedDatabase
get() = instance!!.senderKeySharedDatabase
@get:JvmStatic
@get:JvmName("sessions")
val sessions: SessionDatabase
get() = instance!!.sessionDatabase
@get:JvmStatic
@get:JvmName("stickers")
val stickers: StickerDatabase
get() = instance!!.stickerDatabase
@get:JvmStatic
@get:JvmName("storySends")
val storySends: StorySendsDatabase
get() = instance!!.storySendsDatabase
@get:JvmStatic
@get:JvmName("unknownStorageIds")
val unknownStorageIds: UnknownStorageIdDatabase
get() = instance!!.storageIdDatabase
@get:JvmStatic
@get:JvmName("remoteMegaphones")
val remoteMegaphones: RemoteMegaphoneDatabase
get() = instance!!.remoteMegaphoneDatabase
}
}
| gpl-3.0 | 6396f33141ec5f5589626ba38ddea19c | 37.466403 | 186 | 0.755086 | 4.540238 | false | false | false | false |
walleth/kethereum | extensions/src/main/kotlin/org/kethereum/extensions/BigInteger.kt | 1 | 1757 | package org.kethereum.extensions
import org.walleth.khex.clean0xPrefix
import org.walleth.khex.has0xPrefix
import java.math.BigInteger
fun BigInteger.toBytesPadded(length: Int): ByteArray {
val result = ByteArray(length)
val bytes = toByteArray()
val bytesLength: Int
val srcOffset: Int
if (bytes[0].toInt() == 0) {
bytesLength = bytes.size - 1
srcOffset = 1
} else {
bytesLength = bytes.size
srcOffset = 0
}
if (bytesLength > length) {
throw RuntimeException("Input is too large to put in byte array of size $length")
}
val destOffset = length - bytesLength
System.arraycopy(bytes, srcOffset, result, destOffset, bytesLength)
return result
}
fun BigInteger.toHexStringNoPrefix(): String = toString(16)
fun BigInteger.toHexString(): String = "0x" + toString(16)
fun BigInteger.toHexStringZeroPadded(size: Int, withPrefix: Boolean = true): String {
var result = toHexStringNoPrefix()
val length = result.length
if (length > size) {
throw UnsupportedOperationException("Value $result is larger then length $size")
} else if (signum() < 0) {
throw UnsupportedOperationException("Value cannot be negative")
}
if (length < size) {
result = "0".repeat(size - length) + result
}
return if (withPrefix) {
"0x$result"
} else {
result
}
}
fun String.hexToBigInteger() = BigInteger(clean0xPrefix(), 16)
fun String.maybeHexToBigInteger() = if (has0xPrefix()) {
BigInteger(clean0xPrefix(), 16)
} else {
BigInteger(this)
}
fun ByteArray.toBigInteger(offset: Int, length: Int) = BigInteger(1, copyOfRange(offset, offset + length))
fun ByteArray.toBigInteger() = BigInteger(1, this)
| mit | b37c3fd16130497894fbf1cd27542bfc | 26.453125 | 106 | 0.672738 | 3.975113 | false | false | false | false |
AoDevBlue/AnimeUltimeTv | app/src/main/java/blue/aodev/animeultimetv/presentation/screen/playback/PlaybackFragment.kt | 1 | 1909 | package blue.aodev.animeultimetv.presentation.screen.playback
import android.content.Context
import android.media.AudioManager
import android.os.Bundle
import android.support.v17.leanback.app.PlaybackFragment
import android.support.v17.leanback.app.VideoFragment
import android.support.v17.leanback.app.VideoFragmentGlueHost
import android.util.Log
import blue.aodev.animeultimetv.domain.model.Playlist
class PlaybackFragment : VideoFragment() {
companion object {
val TAG = "PlaybackFragment"
}
val playlist: Playlist by lazy {
(activity as PlaybackActivity).playlist
}
private lateinit var mediaPlayerGlue: PlaylistMediaPlayerGlue
private val host = VideoFragmentGlueHost(this)
private val onAudioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val playerAdapter = ExoPlayerAdapter(activity)
playerAdapter.audioStreamType = AudioManager.USE_DEFAULT_STREAM_TYPE
mediaPlayerGlue = PlaylistMediaPlayerGlue(activity, playerAdapter, playlist)
mediaPlayerGlue.host = host
mediaPlayerGlue.onPlaylistChanged = { playlist -> setCurrentEpisodeIndex(playlist.index) }
val audioManager = activity.getSystemService(Context.AUDIO_SERVICE) as AudioManager
if (audioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Log.w(TAG, "video player cannot obtain audio focus!")
}
backgroundType = PlaybackFragment.BG_LIGHT
}
override fun onPause() {
mediaPlayerGlue.pause()
super.onPause()
}
private fun setCurrentEpisodeIndex(index: Int) {
(activity as PlaybackActivity).setCurrentEpisodeIndex(index)
}
} | mit | 401741c9a77b39172c3cd185e4c418f4 | 34.37037 | 98 | 0.74594 | 4.958442 | false | false | false | false |
Novatec-Consulting-GmbH/testit-testutils | logrecorder/logrecorder-logback/src/main/kotlin/info/novatec/testit/logrecorder/logback/LogbackLogRecorder.kt | 1 | 1254 | /*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 info.novatec.testit.logrecorder.logback
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.Logger
internal class LogbackLogRecorder(
private val logger: Logger,
logRecord: LogbackLogRecord
) {
private val originalLevel = logger.effectiveLevel
private val appender = CallbackAppender(name(), logRecord::record)
fun start() {
logger.level = Level.ALL
logger.addAppender(appender)
}
fun stop() {
logger.detachAppender(appender)
logger.level = originalLevel
}
private fun name(): String = "temporary log appender #${System.nanoTime()}"
}
| apache-2.0 | 873dc4a1cb71b3fe571be8b03580e1f6 | 29.585366 | 79 | 0.719298 | 4.309278 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/readinglist/database/ReadingListPageTable.kt | 1 | 6365 | package org.wikipedia.readinglist.database
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.database.DatabaseTable
import org.wikipedia.database.column.Column
import org.wikipedia.database.contract.ReadingListPageContract
import org.wikipedia.dataclient.WikiSite
class ReadingListPageTable : DatabaseTable<ReadingListPage>(ReadingListPageContract.TABLE, ReadingListPageContract.URI) {
override fun fromCursor(cursor: Cursor): ReadingListPage {
val langCode = ReadingListPageContract.Col.LANG.value(cursor)
val site = ReadingListPageContract.Col.SITE.value(cursor)
val nameSpace = ReadingListPageContract.Col.NAMESPACE.value(cursor)
val displayTitle = ReadingListPageContract.Col.DISPLAY_TITLE.value(cursor)
val apiTitle = ReadingListPageContract.Col.API_TITLE.value(cursor).orEmpty().ifEmpty { displayTitle }
return ReadingListPage(langCode?.let { WikiSite(site, it) } ?: WikiSite(site),
nameSpace, displayTitle, apiTitle).apply {
listId = ReadingListPageContract.Col.LISTID.value(cursor)
id = ReadingListPageContract.Col.ID.value(cursor)
description = ReadingListPageContract.Col.DESCRIPTION.value(cursor)
thumbUrl = ReadingListPageContract.Col.THUMBNAIL_URL.value(cursor)
atime = ReadingListPageContract.Col.ATIME.value(cursor)
mtime = ReadingListPageContract.Col.MTIME.value(cursor)
revId = ReadingListPageContract.Col.REVID.value(cursor)
offline = ReadingListPageContract.Col.OFFLINE.value(cursor) != 0L
status = ReadingListPageContract.Col.STATUS.value(cursor)
sizeBytes = ReadingListPageContract.Col.SIZEBYTES.value(cursor)
remoteId = ReadingListPageContract.Col.REMOTEID.value(cursor)
lang = ReadingListPageContract.Col.LANG.value(cursor)
}
}
override fun getColumnsAdded(version: Int): Array<Column<*>> {
return when (version) {
dBVersionIntroducedAt -> arrayOf(
ReadingListPageContract.Col.ID,
ReadingListPageContract.Col.LISTID,
ReadingListPageContract.Col.SITE,
ReadingListPageContract.Col.LANG,
ReadingListPageContract.Col.NAMESPACE,
ReadingListPageContract.Col.DISPLAY_TITLE,
ReadingListPageContract.Col.MTIME,
ReadingListPageContract.Col.ATIME,
ReadingListPageContract.Col.THUMBNAIL_URL,
ReadingListPageContract.Col.DESCRIPTION,
ReadingListPageContract.Col.REVID,
ReadingListPageContract.Col.OFFLINE,
ReadingListPageContract.Col.STATUS,
ReadingListPageContract.Col.SIZEBYTES,
ReadingListPageContract.Col.REMOTEID,
)
DB_VER_API_TITLE_ADDED -> arrayOf(ReadingListPageContract.Col.API_TITLE)
else -> super.getColumnsAdded(version)
}
}
public override fun onUpgradeSchema(db: SQLiteDatabase, fromVersion: Int, toVersion: Int) {
if (toVersion == dBVersionIntroducedAt) {
val currentLists = mutableListOf<ReadingList>()
createDefaultList(db, currentLists)
renameListsWithIdenticalNameAsDefault(db, currentLists)
// TODO: add other one-time conversions here.
}
}
public override fun toContentValues(obj: ReadingListPage): ContentValues {
val contentValues = ContentValues()
contentValues.put(ReadingListPageContract.Col.LISTID.name, obj.listId)
contentValues.put(ReadingListPageContract.Col.SITE.name, obj.wiki.authority())
contentValues.put(ReadingListPageContract.Col.LANG.name, obj.wiki.languageCode())
contentValues.put(ReadingListPageContract.Col.NAMESPACE.name, obj.namespace.code())
contentValues.put(ReadingListPageContract.Col.DISPLAY_TITLE.name, obj.displayTitle)
contentValues.put(ReadingListPageContract.Col.API_TITLE.name, obj.apiTitle)
contentValues.put(ReadingListPageContract.Col.MTIME.name, obj.mtime)
contentValues.put(ReadingListPageContract.Col.ATIME.name, obj.atime)
contentValues.put(ReadingListPageContract.Col.THUMBNAIL_URL.name, obj.thumbUrl)
contentValues.put(ReadingListPageContract.Col.DESCRIPTION.name, obj.description)
contentValues.put(ReadingListPageContract.Col.REVID.name, obj.revId)
contentValues.put(ReadingListPageContract.Col.OFFLINE.name, if (obj.offline) 1 else 0)
contentValues.put(ReadingListPageContract.Col.STATUS.name, obj.status)
contentValues.put(ReadingListPageContract.Col.SIZEBYTES.name, obj.sizeBytes)
contentValues.put(ReadingListPageContract.Col.REMOTEID.name, obj.remoteId)
return contentValues
}
override fun getPrimaryKeySelection(obj: ReadingListPage, selectionArgs: Array<String>): String {
return super.getPrimaryKeySelection(obj, ReadingListPageContract.Col.SELECTION)
}
override fun getUnfilteredPrimaryKeySelectionArgs(obj: ReadingListPage): Array<String?> {
return arrayOf(obj.displayTitle)
}
private fun createDefaultList(db: SQLiteDatabase, currentLists: MutableList<ReadingList>) {
for (list in currentLists) {
if (list.isDefault) {
// Already have a default list
return
}
}
ReadingListDbHelper.run {
currentLists.add(createDefaultList(db))
}
}
private fun renameListsWithIdenticalNameAsDefault(db: SQLiteDatabase, lists: List<ReadingList>) {
ReadingListDbHelper.run {
for (list in lists) {
if (list.dbTitle.equals(WikipediaApp.getInstance().getString(R.string.default_reading_list_name), true)) {
list.dbTitle = WikipediaApp.getInstance().getString(R.string.reading_list_saved_list_rename, list.dbTitle)
updateList(db, list, false)
}
}
}
}
override val dBVersionIntroducedAt = 18
companion object {
private const val DB_VER_API_TITLE_ADDED = 19
}
}
| apache-2.0 | e8755f31eef16cb41f4ca8c03cd1e3e6 | 49.515873 | 126 | 0.690495 | 4.625727 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ImplicitNullableNothingTypeInspection.kt | 4 | 1743 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.types.typeUtil.isNullableNothing
class ImplicitNullableNothingTypeInspection : IntentionBasedInspection<KtCallableDeclaration>(
intention = SpecifyTypeExplicitlyIntention::class,
additionalChecker = { declaration -> declaration.check() },
problemText = KotlinBundle.message("inspection.implicit.nullable.nothing.type.display.name")
) {
override fun inspectionTarget(element: KtCallableDeclaration) = element.nameIdentifier
}
private fun KtCallableDeclaration.check(): Boolean {
if (!SpecifyTypeExplicitlyIntention.getTypeForDeclaration(this).isNullableNothing()) return false
return isVarOrOpen() && !isOverridingNullableNothing()
}
private fun KtCallableDeclaration.isVarOrOpen() = this is KtProperty && this.isVar || hasModifier(KtTokens.OPEN_KEYWORD)
private fun KtCallableDeclaration.isOverridingNullableNothing(): Boolean {
if (!hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false
val descriptor = resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return false
return descriptor.overriddenDescriptors.any { it.returnType?.isNullableNothing() == true }
}
| apache-2.0 | 65d9307dc1d10dbdfa8f979b6b97a7c1 | 51.818182 | 158 | 0.819277 | 5.052174 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/KotlinProjectStructureUtils.kt | 2 | 5424 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("KotlinProjectStructureUtils")
package org.jetbrains.kotlin.idea.base.projectStructure
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.FileIndex
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.concurrency.annotations.RequiresReadLock
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.analysis.project.structure.KtModule
import org.jetbrains.kotlin.analysis.project.structure.KtSourceModule
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule
import org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.*
import org.jetbrains.kotlin.idea.base.util.Frontend10ApiUsage
import org.jetbrains.kotlin.idea.base.util.runWithAlternativeResolveEnabled
import org.jetbrains.kotlin.psi.UserDataProperty
@Frontend10ApiUsage
val KtModule.moduleInfo: IdeaModuleInfo
get() {
require(this is KtModuleByModuleInfoBase)
return ideaModuleInfo
}
val KtSourceModule.ideaModule: Module
get() {
require(this is KtSourceModuleByModuleInfo)
return ideaModule
}
fun Module.getMainKtSourceModule(): KtSourceModule? {
val moduleInfo = productionSourceInfo ?: return null
return ProjectStructureProviderIdeImpl.getInstance(project).getKtModuleByModuleInfo(moduleInfo) as KtSourceModule
}
val ModuleInfo.kotlinSourceRootType: KotlinSourceRootType?
get() = when {
this is ModuleProductionSourceInfo -> SourceKotlinRootType
this is ModuleTestSourceInfo -> TestSourceKotlinRootType
else -> null
}
val Module.productionSourceInfo: ModuleProductionSourceInfo?
get() {
val hasProductionRoots = hasRootsOfType(setOf(JavaSourceRootType.SOURCE, SourceKotlinRootType))
|| (isNewMultiPlatformModule && kotlinSourceRootType == SourceKotlinRootType)
return if (hasProductionRoots) ModuleProductionSourceInfo(this) else null
}
val Module.testSourceInfo: ModuleTestSourceInfo?
get() {
val hasTestRoots = hasRootsOfType(setOf(JavaSourceRootType.TEST_SOURCE, TestSourceKotlinRootType))
|| (isNewMultiPlatformModule && kotlinSourceRootType == TestSourceKotlinRootType)
return if (hasTestRoots) ModuleTestSourceInfo(this) else null
}
val Module.sourceModuleInfos: List<ModuleSourceInfo>
get() = listOfNotNull(testSourceInfo, productionSourceInfo)
private fun Module.hasRootsOfType(rootTypes: Set<JpsModuleSourceRootType<*>>): Boolean {
return rootManager.contentEntries.any { it.getSourceFolders(rootTypes).isNotEmpty() }
}
var @Suppress("unused") PsiFile.forcedModuleInfo: ModuleInfo? by UserDataProperty(Key.create("FORCED_MODULE_INFO"))
@ApiStatus.Internal get
@ApiStatus.Internal set
private val testRootTypes: Set<JpsModuleSourceRootType<*>> = setOf(
JavaSourceRootType.TEST_SOURCE,
JavaResourceRootType.TEST_RESOURCE,
TestSourceKotlinRootType,
TestResourceKotlinRootType
)
private val sourceRootTypes = setOf<JpsModuleSourceRootType<*>>(
JavaSourceRootType.SOURCE,
JavaResourceRootType.RESOURCE,
SourceKotlinRootType,
ResourceKotlinRootType
)
val JpsModuleSourceRootType<*>.sourceRootType: KotlinSourceRootType?
get() = when (this) {
in sourceRootTypes -> SourceKotlinRootType
in testRootTypes -> TestSourceKotlinRootType
else -> null
}
fun FileIndex.getKotlinSourceRootType(virtualFile: VirtualFile): KotlinSourceRootType? {
// Ignore injected files
if (virtualFile is VirtualFileWindow) {
return null
}
return when {
isUnderSourceRootOfType(virtualFile, testRootTypes) -> TestSourceKotlinRootType
isInSourceContent(virtualFile) -> SourceKotlinRootType
else -> null
}
}
@RequiresReadLock
fun GlobalSearchScope.hasKotlinJvmRuntime(project: Project): Boolean {
return project.runWithAlternativeResolveEnabled {
try {
val markerClassName = StandardNames.FqNames.unit.asString()
JavaPsiFacade.getInstance(project).findClass(markerClassName, this@hasKotlinJvmRuntime) != null
} catch (e: IndexNotReadyException) {
false
}
}
}
fun ModuleInfo.findSdkAcrossDependencies(): SdkInfo? {
val project = (this as? IdeaModuleInfo)?.project ?: return null
return SdkInfoCache.getInstance(project).findOrGetCachedSdk(this)
}
fun IdeaModuleInfo.findJvmStdlibAcrossDependencies(): LibraryInfo? {
val project = project ?: return null
return KotlinStdlibCache.getInstance(project).findStdlibInModuleDependencies(this)
} | apache-2.0 | c19f360d27afc5a40872f0d015d27532 | 37.75 | 120 | 0.78042 | 5.078652 | false | true | false | false |
psanders/sipio | src/main/kotlin/io/routr/core/LogsHandler.kt | 1 | 1602 | package io.routr.core
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue
import org.eclipse.jetty.websocket.api.Session
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage
import org.eclipse.jetty.websocket.api.annotations.WebSocket
/**
* @author Pedro Sanders
* @since v1
*/
@WebSocket
class LogsHandler {
@OnWebSocketConnect
fun connected(session: Session) {
sessions.add(session)
}
@OnWebSocketClose
fun closed(session: Session, statusCode: Int, reason: String) {
sessions.remove(session)
}
@OnWebSocketMessage
@Throws(IOException::class, InterruptedException::class)
fun message(session: Session, message: String) {
var br: BufferedReader? = null
try {
val base = if (System.getenv("DATA") != null) System.getenv("DATA") else "."
val file = File("$base/logs/routr.log")
br = BufferedReader(FileReader(file))
while (true) {
val line = br.readLine()
if (line == null) { // end of file, start polling
Thread.sleep(5 * 1000.toLong())
} else {
session.remote.sendString(line)
}
}
} finally {
br?.close()
}
}
companion object {
// Store sessions if you want to, for example, broadcast a message to all users
private val sessions: Queue<Session> = ConcurrentLinkedQueue()
}
}
| mit | 749d008ea3ff263b8ef053e32d3a7275 | 27.607143 | 83 | 0.700999 | 3.926471 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/HomeProductRecyclerAdapter.kt | 1 | 2553 | package com.tungnui.dalatlaptop.ux.adapters
import android.graphics.Paint
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import java.util.ArrayList
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.models.Product
import com.tungnui.dalatlaptop.utils.formatPrice
import com.tungnui.dalatlaptop.utils.getFeaturedImage
import com.tungnui.dalatlaptop.utils.inflate
import com.tungnui.dalatlaptop.utils.loadImg
import kotlinx.android.synthetic.main.list_item_home.view.*
import java.text.DecimalFormat
class HomeProductRecyclerAdapter(val listener: (Product) -> Unit) : RecyclerView.Adapter<HomeProductRecyclerAdapter.ViewHolder>() {
private val products = ArrayList<Product>()
override fun getItemCount(): Int {
return products.size
}
fun addProducts(productList: List<Product>) {
products.addAll(productList)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeProductRecyclerAdapter.ViewHolder =
ViewHolder(parent.inflate(R.layout.list_item_home))
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.blind(products[position],listener)
}
fun clear() {
products.clear()
}
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
fun blind(item:Product,listener: (Product) -> Unit)=with(itemView){
home_product_item_name.text = item.name
home_product_item_image.loadImg(item.images?.getFeaturedImage()?.src)
item.averageRating?.toFloat()?.let{home_product_item_rating.rating = it }
home_product_item_rating_count.text = "(" + item.ratingCount + ")"
if(item.onSale){
home_product_item_price.visibility = View.VISIBLE
home_product_item_regular_price.visibility = View.VISIBLE
home_product_item_regular_price.text = item.regularPrice?.formatPrice()
home_product_item_regular_price.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
home_product_item_price.text = item.salePrice?.formatPrice()
}else{
home_product_item_price.visibility = View.VISIBLE
home_product_item_regular_price.visibility = View.GONE
home_product_item_price.text = item.price?.formatPrice()
}
setOnClickListener { listener(item) }
}
}
}
| mit | 373bec2f21292956faadc69096c8af1b | 37.104478 | 131 | 0.693694 | 4.327119 | false | false | false | false |
fwcd/kotlin-language-server | server/src/main/kotlin/org/javacs/kt/imports/Imports.kt | 1 | 1509 | package org.javacs.kt.imports
import org.eclipse.lsp4j.Position
import org.eclipse.lsp4j.Range
import org.eclipse.lsp4j.TextEdit
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.javacs.kt.position.location
fun getImportTextEditEntry(parsedFile: KtFile, fqName: FqName): TextEdit {
val imports = parsedFile.importDirectives
val importedNames = imports
.mapNotNull { it.importedFqName?.shortName() }
.toSet()
val pos = findImportInsertionPosition(parsedFile, fqName)
val prefix = if (importedNames.isEmpty()) "\n\n" else "\n"
return TextEdit(Range(pos, pos), "${prefix}import ${fqName}")
}
/** Finds a good insertion position for a new import of the given fully-qualified name. */
private fun findImportInsertionPosition(parsedFile: KtFile, fqName: FqName): Position =
(closestImport(parsedFile.importDirectives, fqName) as? KtElement ?: parsedFile.packageDirective as? KtElement)
?.let(::location)
?.range
?.end
?: Position(0, 0)
// TODO: Lexicographic insertion
private fun closestImport(imports: List<KtImportDirective>, fqName: FqName): KtImportDirective? =
imports
.asReversed()
.maxByOrNull { it.importedFqName?.let { matchingPrefixLength(it, fqName) } ?: 0 }
private fun matchingPrefixLength(left: FqName, right: FqName): Int =
left.pathSegments().asSequence().zip(right.pathSegments().asSequence())
.takeWhile { it.first == it.second }
.count()
| mit | bc4fd48eb5a6716c2d57af96e1484dde | 38.710526 | 115 | 0.713718 | 4.134247 | false | false | false | false |
mktiti/Battleship | src/main/java/hu/titi/battleship/activity/MapSetupActivity.kt | 1 | 4726 | package hu.titi.battleship.activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Button
import android.widget.CheckBox
import hu.titi.battleship.R
import hu.titi.battleship.model.*
import hu.titi.battleship.model.Map
import hu.titi.battleship.ui.GamePanel
import hu.titi.battleship.ui.ShipView
import org.jetbrains.anko.sdk23.coroutines.onClick
import java.io.Serializable
import kotlin.concurrent.thread
const val MAP_SETUP_OK = 1
class MapSetupActivity : AppCompatActivity() {
private lateinit var gameView: GamePanel
private lateinit var shipView: ShipView
private lateinit var rotated: CheckBox
private lateinit var randomize: Button
private lateinit var undoButton: Button
private lateinit var okButton: Button
private val ships = mutableListOf<Ship>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_setup)
gameView = findViewById(R.id.gameView) as GamePanel
shipView = findViewById(R.id.shipView) as ShipView
undoButton = findViewById(R.id.undo) as Button
randomize = findViewById(R.id.randomize) as Button
rotated = findViewById(R.id.rotate) as CheckBox
okButton = findViewById(R.id.ok) as Button
undoButton.onClick {
if (ships.isNotEmpty()) {
ships.removeAt(ships.size - 1)
shipView.undo()
gameView.clear()
gameView.showShips(true, ships)
for (ship in ships) {
gameView.unveilShip(ship)
}
}
okButton.isEnabled = false
}
randomize.onClick { randomize() }
okButton.onClick {
setResult(MAP_SETUP_OK, Intent().putExtra("map", Map(ships) as Serializable))
finish()
}
if (savedInstanceState != null) {
val saved = savedInstanceState.getSerializable("ships")
if (saved != null && saved is List<*>) {
val savedShips: List<Ship> = (saved as List<*>).filterIsInstance<Ship>()
ships.clear()
ships.addAll(savedShips)
gameView.clear()
gameView.showShips(true, ships)
for (ship in ships) {
gameView.unveilShip(ship)
}
okButton.isEnabled = ships.size == shipSizes.size
shipView.fromSaved(savedInstanceState)
}
}
}
override fun onStart() {
super.onStart()
thread {
while (true) {
val coordinate = gameView.await(ShootResult.MISS) ?: break
val selected = shipView.getSelected() ?: continue
val vertical = rotated.isChecked
val dx = if (vertical) 0 else 1
val dy = 1 - dx
val tiles = Array(selected) { i ->
Pair(coordinate.x + i * dx, coordinate.y + i * dy)
}
if (tiles.any { !validCoordinate(it) }) continue
val newShip = Ship(selected, coordinate, vertical)
if (ships.any { ship ->
val oldShipSet = mutableSetOf<Coordinate>()
oldShipSet.addAll(ship.border())
oldShipSet.addAll(ship.tiles.map(Pair<Coordinate, *>::first))
Log.i("setup", oldShipSet.toString())
Log.i("setup", newShip.tiles.toString())
oldShipSet.intersect(newShip.tiles.map(Pair<Coordinate, *>::first)).isNotEmpty()
}) continue
ships.add(newShip)
if (shipView.removeSelected()) {
runOnUiThread {
okButton.isEnabled = true
}
}
gameView.showShips(true, listOf(newShip))
gameView.unveilShip(newShip)
}
}
}
private fun randomize() {
val list = randomSetup()
ships.clear()
ships.addAll(list)
shipView.allUsed()
gameView.clear()
gameView.showShips(true, ships)
for (ship in ships) {
gameView.unveilShip(ship)
}
okButton.isEnabled = true
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putSerializable("ships", ships as Serializable)
shipView.save(outState)
super.onSaveInstanceState(outState)
}
override fun onStop() {
gameView.abort()
super.onStop()
}
}
| gpl-3.0 | c17dd0be24f9231b6dd946013b7d0d8a | 30.298013 | 100 | 0.573212 | 4.505243 | false | false | false | false |
paplorinc/intellij-community | plugins/stats-collector/src/com/intellij/stats/personalization/impl/CompletionUsageFactors.kt | 7 | 2117 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.personalization.impl
import com.intellij.stats.personalization.*
/**
* @author Vitaliy.Bibaev
*/
class CompletionUsageReader(factor: DailyAggregatedDoubleFactor) : UserFactorReaderBase(factor) {
fun getTodayCount(): Double = factor.onToday().getOrDefault("count", 0.0)
fun getTotalCount(): Double = factor.aggregateSum().getOrDefault("count", 0.0)
fun getWeekAverage(): Double = factor.aggregateAverage().getOrDefault("count", 0.0)
}
class CompletionUsageUpdater(factor: MutableDoubleFactor) : UserFactorUpdaterBase(factor) {
fun fireCompletionUsed() {
factor.incrementOnToday("count")
}
}
class TodayCompletionUsageCount : CompletionUsageFactorBase("todayCompletionCount") {
override fun compute(reader: CompletionUsageReader): Double? = reader.getTodayCount()
}
class WeekAverageUsageCount : CompletionUsageFactorBase("weekAverageDailyCompletionCount") {
override fun compute(reader: CompletionUsageReader): Double? = reader.getWeekAverage()
}
class TotalUsageCount : CompletionUsageFactorBase("totalCompletionCountInLastDays") {
override fun compute(reader: CompletionUsageReader): Double? = reader.getTotalCount()
}
abstract class CompletionUsageFactorBase(override val id: String) : UserFactor {
final override fun compute(storage: UserFactorStorage): String? =
compute(storage.getFactorReader(UserFactorDescriptions.COMPLETION_USAGE))?.toString()
abstract fun compute(reader: CompletionUsageReader): Double?
}
| apache-2.0 | b1419224595d6bf689fb8d38f1beafe6 | 37.490909 | 97 | 0.765234 | 4.320408 | false | false | false | false |
google/intellij-community | platform/built-in-server/src/org/jetbrains/ide/ToolboxUpdateActions.kt | 1 | 3609 | // 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.ide
import com.intellij.ide.actions.SettingsEntryPointAction
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.util.Disposer
import com.intellij.util.Alarm
import com.intellij.util.Consumer
import com.intellij.util.messages.Topic
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import org.jetbrains.annotations.Nls
import java.util.*
@Service(Service.Level.APP)
class ToolboxSettingsActionRegistry : Disposable {
private val readActions = Collections.synchronizedSet(HashSet<String>())
private val pendingActions = Collections.synchronizedList(LinkedList<ToolboxUpdateAction>())
private val alarm = MergingUpdateQueue("toolbox-updates", 500, true, null, this, null, Alarm.ThreadToUse.SWING_THREAD).usePassThroughInUnitTestMode()
override fun dispose() = Unit
fun isNewAction(actionId: String) = actionId !in readActions
fun markAsRead(actionId: String) {
readActions.add(actionId)
}
fun scheduleUpdate() {
alarm.queue(object: Update(this){
override fun run() {
SettingsEntryPointAction.updateState()
}
})
}
internal fun registerUpdateAction(action: ToolboxUpdateAction) {
action.registry = this
val dispose = Disposable {
pendingActions.remove(action)
scheduleUpdate()
}
pendingActions += action
ApplicationManager.getApplication().messageBus.syncPublisher(UpdateActionsListener.TOPIC).actionReceived(action)
if (!Disposer.tryRegister(action.lifetime, dispose)) {
Disposer.dispose(dispose)
return
}
scheduleUpdate()
}
fun getActions() : List<SettingsEntryPointAction.UpdateAction> = ArrayList(pendingActions).sortedBy { it.actionId }
}
class ToolboxSettingsActionRegistryActionProvider : SettingsEntryPointAction.ActionProvider {
override fun getUpdateActions(context: DataContext) = service<ToolboxSettingsActionRegistry>().getActions()
}
internal class ToolboxUpdateAction(
val actionId: String,
val lifetime: Disposable,
text: @Nls String,
description: @Nls String,
val actionHandler: Consumer<AnActionEvent>,
val restartRequired: Boolean
) : SettingsEntryPointAction.UpdateAction(text) {
lateinit var registry : ToolboxSettingsActionRegistry
init {
templatePresentation.description = description
}
override fun isIdeUpdate() = true
override fun isRestartRequired(): Boolean {
return restartRequired
}
override fun isNewAction(): Boolean {
return registry.isNewAction(actionId)
}
override fun markAsRead() {
registry.markAsRead(actionId)
}
override fun actionPerformed(e: AnActionEvent) {
actionHandler.consume(e)
}
override fun update(e: AnActionEvent) {
super.update(e)
if (Disposer.isDisposed(lifetime)) {
e.presentation.isEnabledAndVisible = false
}
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
}
interface UpdateActionsListener: EventListener {
companion object {
val TOPIC = Topic(UpdateActionsListener::class.java)
}
fun actionReceived(action: SettingsEntryPointAction.UpdateAction)
} | apache-2.0 | d9da8e68bd02441be9837e402bd0d60c | 29.59322 | 158 | 0.77279 | 4.656774 | false | false | false | false |
JetBrains/intellij-community | python/ide/impl/src/com/jetbrains/python/configuration/PySdkStatusBar.kt | 1 | 4422 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.configuration
import com.intellij.ProjectTopics
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.ui.popup.ListPopup
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.StatusBar
import com.intellij.openapi.wm.StatusBarWidget
import com.intellij.openapi.wm.StatusBarWidgetFactory
import com.intellij.openapi.wm.impl.status.EditorBasedStatusBarPopup
import com.intellij.util.PlatformUtils
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PythonIdeLanguageCustomization
import com.jetbrains.python.sdk.PySdkPopupFactory
import com.jetbrains.python.sdk.PySdkPopupFactory.Companion.descriptionInPopup
import com.jetbrains.python.sdk.PySdkPopupFactory.Companion.shortenNameInPopup
import com.jetbrains.python.sdk.PythonSdkUtil
import com.jetbrains.python.sdk.noInterpreterMarker
private const val ID: String = "pythonInterpreterWidget"
fun isDataSpellInterpreterWidgetEnabled() = PlatformUtils.isDataSpell() && Registry.`is`("dataspell.interpreter.widget")
private class PySdkStatusBarWidgetFactory : StatusBarWidgetFactory {
override fun getId(): String = ID
override fun getDisplayName(): String = PyBundle.message("configurable.PyActiveSdkModuleConfigurable.python.interpreter.display.name")
override fun isAvailable(project: Project): Boolean =
PythonIdeLanguageCustomization.isMainlyPythonIde() && !isDataSpellInterpreterWidgetEnabled()
override fun createWidget(project: Project): StatusBarWidget = PySdkStatusBar(project)
override fun canBeEnabledOn(statusBar: StatusBar): Boolean = true
}
private class PySwitchSdkAction : DumbAwareAction(PyBundle.message("switch.python.interpreter"), null, null) {
override fun update(e: AnActionEvent) {
e.presentation.isVisible = e.getData(CommonDataKeys.VIRTUAL_FILE) != null && e.project != null
}
override fun actionPerformed(e: AnActionEvent) {
val file = e.getData(CommonDataKeys.VIRTUAL_FILE) ?: return
val project = e.project ?: return
val module = ModuleUtil.findModuleForFile(file, project) ?: return
val dataContext = e.dataContext
PySdkPopupFactory(project, module).createPopup(dataContext).showInBestPositionFor(dataContext)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
}
private class PySdkStatusBar(project: Project) : EditorBasedStatusBarPopup(project, false) {
private var module: Module? = null
override fun getWidgetState(file: VirtualFile?): WidgetState {
module = findModule(file) ?: return WidgetState.HIDDEN
val sdk = PythonSdkUtil.findPythonSdk(module)
return if (sdk == null) {
WidgetState("", noInterpreterMarker, true)
}
else {
WidgetState(PyBundle.message("current.interpreter", descriptionInPopup(sdk)), shortenNameInPopup(sdk, 50), true)
}
}
override fun isEnabledForFile(file: VirtualFile?): Boolean = true
override fun registerCustomListeners() {
project
.messageBus
.connect(this)
.subscribe(
ProjectTopics.PROJECT_ROOTS,
object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) = update()
}
)
}
override fun createPopup(context: DataContext): ListPopup? = module?.let { PySdkPopupFactory(project, it).createPopup(context) }
override fun ID(): String = ID
override fun createInstance(project: Project): StatusBarWidget = PySdkStatusBar(project)
private fun findModule(file: VirtualFile?): Module? {
if (file != null) {
val module = ModuleUtil.findModuleForFile(file, project)
if (module != null) return module
}
return ModuleManager.getInstance(project).modules.singleOrNull()
}
}
| apache-2.0 | b565266b983e304ff663dbf7d572de71 | 38.837838 | 136 | 0.784713 | 4.60625 | false | false | false | false |
vhromada/Catalog | core/src/main/kotlin/com/github/vhromada/catalog/facade/impl/ShowFacadeImpl.kt | 1 | 4634 | package com.github.vhromada.catalog.facade.impl
import com.github.vhromada.catalog.common.entity.Page
import com.github.vhromada.catalog.common.exception.InputException
import com.github.vhromada.catalog.entity.ChangeShowRequest
import com.github.vhromada.catalog.entity.Show
import com.github.vhromada.catalog.entity.ShowStatistics
import com.github.vhromada.catalog.facade.ShowFacade
import com.github.vhromada.catalog.filter.MultipleNameFilter
import com.github.vhromada.catalog.mapper.ShowMapper
import com.github.vhromada.catalog.service.GenreService
import com.github.vhromada.catalog.service.PictureService
import com.github.vhromada.catalog.service.ShowService
import com.github.vhromada.catalog.validator.ShowValidator
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Component
/**
* A class represents implementation of facade for shows.
*
* @author Vladimir Hromada
*/
@Component("showFacade")
class ShowFacadeImpl(
/**
* Service for shows
*/
private val showService: ShowService,
/**
* Service for genres
*/
private val genreService: GenreService,
/**
* Service for pictures
*/
private val pictureService: PictureService,
/**
* Mapper for shows
*/
private val mapper: ShowMapper,
/**
* Validator for shows
*/
private val validator: ShowValidator
) : ShowFacade {
override fun search(filter: MultipleNameFilter): Page<Show> {
val shows = showService.search(filter = mapper.mapFilter(source = filter), pageable = filter.toPageable(sort = Sort.by("normalizedCzechName", "id")))
val data = shows.content.map {
mapper.mapShow(source = it)
.copy(picture = getPicture(show = it)?.uuid)
}
return Page(data = data, page = shows)
}
override fun get(uuid: String): Show {
val show = showService.get(uuid = uuid)
return mapper.mapShow(source = show)
.copy(picture = getPicture(show = show)?.uuid)
}
override fun add(request: ChangeShowRequest): Show {
validator.validateRequest(request = request)
val show = mapper.mapRequest(source = request)
show.picture = getPicture(request = request)?.id
show.genres.addAll(getGenres(request = request))
val addedShow = showService.store(show = show)
return mapper.mapShow(source = addedShow)
.copy(picture = getPicture(show = addedShow)?.uuid)
}
override fun update(uuid: String, request: ChangeShowRequest): Show {
validator.validateRequest(request = request)
val show = showService.get(uuid = uuid)
show.merge(show = mapper.mapRequest(source = request))
show.picture = getPicture(request = request)?.id
show.genres.clear()
show.genres.addAll(getGenres(request = request))
val updatedShow = showService.store(show = show)
return mapper.mapShow(source = updatedShow)
.copy(picture = getPicture(show = updatedShow)?.uuid)
}
override fun remove(uuid: String) {
showService.remove(show = showService.get(uuid = uuid))
}
override fun duplicate(uuid: String): Show {
val duplicatedShow = showService.duplicate(show = showService.get(uuid = uuid))
return mapper.mapShow(source = duplicatedShow)
.copy(picture = getPicture(show = duplicatedShow)?.uuid)
}
override fun getStatistics(): ShowStatistics {
return showService.getStatistics()
}
/**
* Returns picture.
*
* @param show show
* @returns picture
*/
private fun getPicture(show: com.github.vhromada.catalog.domain.Show): com.github.vhromada.catalog.domain.Picture? {
return if (show.picture == null) null else pictureService.getById(id = show.picture!!)
}
/**
* Returns picture.
*
* @param request request for changing show
* @returns picture
* @throws InputException if picture doesn't exist in data storage
*/
private fun getPicture(request: ChangeShowRequest): com.github.vhromada.catalog.domain.Picture? {
return if (request.picture == null) null else pictureService.getByUuid(uuid = request.picture)
}
/**
* Returns genres.
*
* @param request request for changing show
* @returns genres
* @throws InputException if genre doesn't exist in data storage
*/
private fun getGenres(request: ChangeShowRequest): List<com.github.vhromada.catalog.domain.Genre> {
return request.genres!!.filterNotNull().map { genreService.get(uuid = it) }
}
} | mit | 7f349a9c9b74c457a92e8e841563a89a | 34.653846 | 157 | 0.682348 | 4.235832 | false | false | false | false |
youdonghai/intellij-community | platform/projectModel-api/src/com/intellij/configurationStore/StreamProvider.kt | 1 | 2319 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import org.jetbrains.annotations.TestOnly
import java.io.InputStream
interface StreamProvider {
val enabled: Boolean
get() = true
/**
* Called only on `write`
*/
fun isApplicable(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT) = true
/**
* @param fileSpec
* @param content bytes of content, size of array is not actual size of data, you must use `size`
* @param size actual size of data
*/
fun write(fileSpec: String, content: ByteArray, size: Int = content.size, roamingType: RoamingType = RoamingType.DEFAULT)
/**
* `true` if provider is applicable for file.
*/
fun read(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT, consumer: (InputStream?) -> Unit): Boolean
/**
* `true` if provider is fully responsible and local sources must be not used.
*/
fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean): Boolean
/**
* Delete file or directory
*
* `true` if provider is fully responsible and local sources must be not used.
*/
fun delete(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): Boolean
}
@TestOnly
fun StreamProvider.write(path: String, content: String) {
write(path, content.toByteArray())
}
fun StreamProvider.write(path: String, content: BufferExposingByteArrayOutputStream, roamingType: RoamingType = RoamingType.DEFAULT) {
write(path, content.internalBuffer, content.size(), roamingType)
} | apache-2.0 | 044b608ea7f0ecd0b62031f342cff804 | 35.25 | 182 | 0.738249 | 4.342697 | false | false | false | false |
ursjoss/sipamato | buildSrc/src/main/kotlin/plugins/ApplicationPropertiesFilterPlugin.kt | 1 | 1949 | package plugins
import org.apache.tools.ant.filters.ReplaceTokens
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.kotlin.dsl.filter
import org.gradle.kotlin.dsl.named
import org.gradle.language.jvm.tasks.ProcessResources
import java.time.LocalDateTime
/**
* Gradle plugin that takes care of replacing properties of the form `@prop@`
* (e.g. `@project.version@`) during the [ProcessResources] gradle task for
* `application.properties` files located in `src/main/resources`.
*/
class ApplicationPropertiesFilterPlugin : Plugin<Project> {
override fun apply(project: Project) {
with(project) {
tasks.named<ProcessResources>("processResources") {
from("src/main/resources") {
include("**/application*.yml")
include("**/application*.yaml")
include("**/application*.properties")
val tokens: Map<String, Any> = project.collectProperties()
inputs.properties(tokens)
filter<ReplaceTokens>("tokens" to tokens)
duplicatesStrategy = DuplicatesStrategy.WARN
}
into("build/resources/main")
}
}
}
private fun Project.collectProperties(): Map<String, Any> {
val props: MutableMap<String, Any> = mutableMapOf()
props["timestamp"] = LocalDateTime.now().toString()
properties.forEach { prop ->
prop.value?.let { value ->
when (value) {
is Map<*, *> -> null
is Collection<*> -> null
else -> value.toString()
}?.let { stringValue ->
props[prop.key] = stringValue
props["project.${prop.key}"] = stringValue
}
}
}
return props
}
}
| gpl-3.0 | 83ac27b70dcc4646f24d1ebab28d2ba8 | 35.092593 | 78 | 0.574654 | 4.860349 | false | false | false | false |
code-helix/slatekit | scripts/templates/codegen/kotlin/method.kt | 1 | 929 | /**
@{methodDesc}
The tag parameter is used as a "correlation id"
*/
fun @{methodName}(
@{methodParams}
tag:String,
callback: (Outcome<@{methodReturnType}>) -> Unit
)
{
// headers
val headers = mapOf<String,String>()
// query string
val queryParams = mapOf<String,String>(
@{queryParams}
)
// data
val postData = mapOf<String, Any>(
@{postDataVars}
)
val json = Conversions.convertMapToJson(postData)
// convert
val converter = Converter@{converterClass}<@{parameterizedClassNames}>(@{parameterizedClassTypes})
// execute
http.@{verb}(
"@{route}",
headers = headers,
queryParams = queryParams,
body = HttpRPC.Body.JsonContent(json),
callback = { respond(it, converter, callback ) }
)
} | apache-2.0 | 9feb69b8d89aebc9e200bf48b5e97dec | 24.833333 | 106 | 0.531755 | 4.764103 | false | false | false | false |
zdary/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/RootsToWorkingCopies.kt | 3 | 4656 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.BackgroundTaskQueue
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ZipperUpdater
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED
import com.intellij.openapi.vcs.VcsListener
import com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import org.jetbrains.idea.svn.SvnBundle.message
import org.jetbrains.idea.svn.SvnUtil.isAncestor
import org.jetbrains.idea.svn.api.Url
import org.jetbrains.idea.svn.auth.SvnAuthenticationNotifier
// 1. listen to roots changes
// 2. - possibly - to deletion/checkouts??? what if WC roots can be
@Service
class RootsToWorkingCopies(private val project: Project) : VcsListener, Disposable {
private val myLock = Any()
private val myRootMapping = mutableMapOf<VirtualFile, WorkingCopy>()
private val myUnversioned = mutableSetOf<VirtualFile>()
private val myQueue = BackgroundTaskQueue(project, message("progress.title.svn.roots.authorization.checker"))
private val myZipperUpdater = ZipperUpdater(200, this)
private val myRechecker = Runnable {
clear()
val roots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(vcs)
for (root in roots) {
addRoot(root)
}
}
private val vcs: SvnVcs get() = SvnVcs.getInstance(project)
init {
project.messageBus.connect().subscribe(VCS_CONFIGURATION_CHANGED, this)
}
private fun addRoot(root: VirtualFile) {
myQueue.run(object : Task.Backgroundable(project, message("progress.title.looking.for.file.working.copy.root", root.path), false) {
override fun run(indicator: ProgressIndicator) {
calculateRoot(root)
}
})
}
@RequiresBackgroundThread
fun getMatchingCopy(url: Url?): WorkingCopy? {
assert(!ApplicationManager.getApplication().isDispatchThread || ApplicationManager.getApplication().isUnitTestMode)
if (url == null) return null
val roots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(vcs)
synchronized(myLock) {
for (root in roots) {
val wcRoot = getWcRoot(root)
if (wcRoot != null && (isAncestor(wcRoot.url, url) || isAncestor(url, wcRoot.url))) {
return wcRoot
}
}
}
return null
}
@RequiresBackgroundThread
fun getWcRoot(root: VirtualFile): WorkingCopy? {
assert(!ApplicationManager.getApplication().isDispatchThread || ApplicationManager.getApplication().isUnitTestMode)
synchronized(myLock) {
if (myUnversioned.contains(root)) return null
val existing = myRootMapping[root]
if (existing != null) return existing
}
return calculateRoot(root)
}
private fun calculateRoot(root: VirtualFile): WorkingCopy? {
val workingCopyRoot = SvnUtil.getWorkingCopyRoot(virtualToIoFile(root))
var workingCopy: WorkingCopy? = null
if (workingCopyRoot != null) {
val svnInfo = vcs.getInfo(workingCopyRoot)
if (svnInfo != null && svnInfo.url != null) {
workingCopy = WorkingCopy(workingCopyRoot, svnInfo.url)
}
}
return registerWorkingCopy(root, workingCopy)
}
private fun registerWorkingCopy(root: VirtualFile, resolvedWorkingCopy: WorkingCopy?): WorkingCopy? {
synchronized(myLock) {
if (resolvedWorkingCopy == null) {
myRootMapping.remove(root)
myUnversioned.add(root)
}
else {
myUnversioned.remove(root)
myRootMapping[root] = resolvedWorkingCopy
}
}
return resolvedWorkingCopy
}
override fun dispose() = clearData()
fun clear() {
clearData()
myZipperUpdater.stop()
}
private fun clearData() =
synchronized(myLock) {
myRootMapping.clear()
myUnversioned.clear()
}
override fun directoryMappingChanged() {
// todo +- here... shouldnt be
SvnAuthenticationNotifier.getInstance(project).clear()
myZipperUpdater.queue(myRechecker)
}
companion object {
@JvmStatic
fun getInstance(project: Project): RootsToWorkingCopies = project.service()
}
}
| apache-2.0 | 765b2856a9c01fb9183518fc88ec875b | 32.985401 | 140 | 0.736254 | 4.295203 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.kt | 1 | 20778 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui
import com.intellij.application.options.editor.CheckboxDescriptor
import com.intellij.application.options.editor.checkBox
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle.message
import com.intellij.ide.actions.QuickChangeLookAndFeel
import com.intellij.ide.ui.search.OptionDescription
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.PlatformEditorBundle
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager
import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl
import com.intellij.openapi.help.HelpManager
import com.intellij.openapi.keymap.KeyMapBundle
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.options.BoundSearchableConfigurable
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.IdeFrameDecorator
import com.intellij.ui.ContextHelpLabel
import com.intellij.ui.FontComboBox
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.UIBundle
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.Label
import com.intellij.ui.layout.*
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.RenderingHints
import java.awt.Window
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JList
// @formatter:off
private val settings get() = UISettings.instance
private val generalSettings get() = GeneralSettings.getInstance()
private val lafManager get() = LafManager.getInstance()
private val cdShowToolWindowBars get() = CheckboxDescriptor(message("checkbox.show.tool.window.bars"), PropertyBinding({ !settings.hideToolStripes }, { settings.hideToolStripes = !it }), groupName = windowOptionGroupName)
private val cdShowToolWindowNumbers get() = CheckboxDescriptor(message("checkbox.show.tool.window.numbers"), settings::showToolWindowsNumbers, groupName = windowOptionGroupName)
private val cdEnableMenuMnemonics get() = CheckboxDescriptor(KeyMapBundle.message("enable.mnemonic.in.menu.check.box"), PropertyBinding({ !settings.disableMnemonics }, { settings.disableMnemonics = !it }), groupName = windowOptionGroupName)
private val cdEnableControlsMnemonics get() = CheckboxDescriptor(KeyMapBundle.message("enable.mnemonic.in.controls.check.box"), PropertyBinding({ !settings.disableMnemonicsInControls }, { settings.disableMnemonicsInControls = !it }), groupName = windowOptionGroupName)
private val cdSmoothScrolling get() = CheckboxDescriptor(message("checkbox.smooth.scrolling"), settings::smoothScrolling, groupName = uiOptionGroupName)
private val cdWidescreenToolWindowLayout get() = CheckboxDescriptor(message("checkbox.widescreen.tool.window.layout"), settings::wideScreenSupport, groupName = windowOptionGroupName)
private val cdLeftToolWindowLayout get() = CheckboxDescriptor(message("checkbox.left.toolwindow.layout"), settings::leftHorizontalSplit, groupName = windowOptionGroupName)
private val cdRightToolWindowLayout get() = CheckboxDescriptor(message("checkbox.right.toolwindow.layout"), settings::rightHorizontalSplit, groupName = windowOptionGroupName)
private val cdUseCompactTreeIndents get() = CheckboxDescriptor(message("checkbox.compact.tree.indents"), settings::compactTreeIndents, groupName = uiOptionGroupName)
private val cdShowTreeIndents get() = CheckboxDescriptor(message("checkbox.show.tree.indent.guides"), settings::showTreeIndentGuides, groupName = uiOptionGroupName)
private val cdDnDWithAlt get() = CheckboxDescriptor(message("dnd.with.alt.pressed.only"), settings::dndWithPressedAltOnly, groupName = uiOptionGroupName)
private val cdUseTransparentMode get() = CheckboxDescriptor(message("checkbox.use.transparent.mode.for.floating.windows"), PropertyBinding({ settings.state.enableAlphaMode }, { settings.state.enableAlphaMode = it }))
private val cdOverrideLaFFont get() = CheckboxDescriptor(message("checkbox.override.default.laf.fonts"), settings::overrideLafFonts)
private val cdUseContrastToolbars get() = CheckboxDescriptor(message("checkbox.acessibility.contrast.scrollbars"), settings::useContrastScrollbars)
private val cdMergeMainMenuWithWindowTitle get() = CheckboxDescriptor(message("checkbox.merge.main.menu.with.window.title"), settings::mergeMainMenuWithWindowTitle, groupName = windowOptionGroupName)
private val cdFullPathsInTitleBar get() = CheckboxDescriptor(message("checkbox.full.paths.in.window.header"), settings::fullPathsInWindowHeader)
private val cdShowMenuIcons get() = CheckboxDescriptor(message("checkbox.show.icons.in.menu.items"), settings::showIconsInMenus, groupName = windowOptionGroupName)
// @formatter:on
internal val appearanceOptionDescriptors: List<OptionDescription>
get() = listOf(
cdShowToolWindowBars,
cdShowToolWindowNumbers,
cdEnableMenuMnemonics,
cdEnableControlsMnemonics,
cdSmoothScrolling,
cdWidescreenToolWindowLayout,
cdLeftToolWindowLayout,
cdRightToolWindowLayout,
cdUseCompactTreeIndents,
cdShowTreeIndents,
cdDnDWithAlt,
cdFullPathsInTitleBar
).map(CheckboxDescriptor::asUiOptionDescriptor)
internal class AppearanceConfigurable : BoundSearchableConfigurable(message("title.appearance"), "preferences.lookFeel") {
private var shouldUpdateLaF = false
private val propertyGraph = PropertyGraph()
private val lafProperty = propertyGraph.graphProperty { lafManager.lookAndFeelReference }
private val syncThemeProperty = propertyGraph.graphProperty { lafManager.autodetect }
override fun createPanel(): DialogPanel {
lafProperty.afterChange({ QuickChangeLookAndFeel.switchLafAndUpdateUI(lafManager, lafManager.findLaf(it), true) }, disposable!!)
syncThemeProperty.afterChange ({ lafManager.autodetect = it }, disposable!!)
return panel {
blockRow {
fullRow {
label(message("combobox.look.and.feel"))
val theme = comboBox(lafManager.lafComboBoxModel, lafProperty, lafManager.lookAndFeelCellRenderer)
theme.component.accessibleContext.accessibleName = message("combobox.look.and.feel")
val syncCheckBox = checkBox(message("preferred.theme.autodetect.selector"),
syncThemeProperty).withLargeLeftGap().
apply { component.isVisible = lafManager.autodetectSupported }
theme.enableIf(syncCheckBox.selected.not())
component(lafManager.settingsToolbar).visibleIf(syncCheckBox.selected).withLeftGap()
}.largeGapAfter()
fullRow {
val overrideLaF = checkBox(cdOverrideLaFFont)
.shouldUpdateLaF()
component(FontComboBox())
.withBinding(
{ it.fontName },
{ it, value -> it.fontName = value },
PropertyBinding({ if (settings.overrideLafFonts) settings.fontFace else JBFont.label().family },
{ settings.fontFace = it })
)
.shouldUpdateLaF()
.enableIf(overrideLaF.selected)
.component.accessibleContext.accessibleName = cdOverrideLaFFont.name
component(Label(message("label.font.size")))
.withLargeLeftGap()
.enableIf(overrideLaF.selected)
fontSizeComboBox({ if (settings.overrideLafFonts) settings.fontSize else JBFont.label().size },
{ settings.fontSize = it },
settings.fontSize)
.shouldUpdateLaF()
.enableIf(overrideLaF.selected)
.component.accessibleContext.accessibleName = message("label.font.size")
}
}
titledRow(message("title.accessibility")) {
fullRow {
val isOverridden = GeneralSettings.isSupportScreenReadersOverridden()
checkBox(message("checkbox.support.screen.readers"),
generalSettings::isSupportScreenReaders, generalSettings::setSupportScreenReaders,
comment = if (isOverridden) message("option.is.overridden.by.jvm.property", GeneralSettings.SUPPORT_SCREEN_READERS)
else null)
.enabled(!isOverridden)
commentNoWrap(message("support.screen.readers.comment"))
.withLargeLeftGap()
}
fullRow { checkBox(cdUseContrastToolbars) }
val supportedValues = ColorBlindness.values().filter { ColorBlindnessSupport.get(it) != null }
if (supportedValues.isNotEmpty()) {
val modelBinding = PropertyBinding({ settings.colorBlindness }, { settings.colorBlindness = it })
val onApply = {
// callback executed not when all changes are applied, but one component by one, so, reload later when everything were applied
ApplicationManager.getApplication().invokeLater(Runnable {
DefaultColorSchemesManager.getInstance().reload()
(EditorColorsManager.getInstance() as EditorColorsManagerImpl).schemeChangedOrSwitched(null)
})
}
fullRow {
if (supportedValues.size == 1) {
component(JBCheckBox(UIBundle.message("color.blindness.checkbox.text")))
.comment(UIBundle.message("color.blindness.checkbox.comment"))
.withBinding({ if (it.isSelected) supportedValues.first() else null },
{ it, value -> it.isSelected = value != null },
modelBinding)
.onApply(onApply)
}
else {
val enableColorBlindness = component(JBCheckBox(UIBundle.message("color.blindness.combobox.text")))
.applyToComponent { isSelected = modelBinding.get() != null }
component(ComboBox(supportedValues.toTypedArray()))
.enableIf(enableColorBlindness.selected)
.applyToComponent { renderer = SimpleListCellRenderer.create<ColorBlindness>("") { PlatformEditorBundle.message(it.key) } }
.comment(UIBundle.message("color.blindness.combobox.comment"))
.withBinding({ if (enableColorBlindness.component.isSelected) it.selectedItem as? ColorBlindness else null },
{ it, value -> it.selectedItem = value ?: supportedValues.first() },
modelBinding)
.onApply(onApply)
.component.accessibleContext.accessibleName = UIBundle.message("color.blindness.checkbox.text")
}
component(ActionLink(UIBundle.message("color.blindness.link.to.help"))
{ HelpManager.getInstance().invokeHelp("Colorblind_Settings") })
.withLargeLeftGap()
}
}
}
@Suppress("MoveLambdaOutsideParentheses") // this suggestion is wrong, see KT-40969
titledRow(message("group.ui.options")) {
val leftColumnControls = sequence<InnerCell.() -> Unit> {
yield({ checkBox(cdShowTreeIndents) })
yield({ checkBox(cdUseCompactTreeIndents) })
yield({ checkBox(cdEnableMenuMnemonics) })
yield({ checkBox(cdEnableControlsMnemonics) })
}
val rightColumnControls = sequence<InnerCell.() -> Unit> {
yield({
checkBox(cdSmoothScrolling)
ContextHelpLabel.create(message("checkbox.smooth.scrolling.description"))()
})
yield({ checkBox(cdDnDWithAlt) })
if (IdeFrameDecorator.isCustomDecorationAvailable()) {
yield({
val overridden = UISettings.isMergeMainMenuWithWindowTitleOverridden
checkBox(cdMergeMainMenuWithWindowTitle).enabled(!overridden)
if (overridden) {
ContextHelpLabel.create(
message("option.is.overridden.by.jvm.property", UISettings.MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY))()
}
commentNoWrap(message("checkbox.merge.main.menu.with.window.title.comment")).withLargeLeftGap()
})
}
yield({ checkBox(cdFullPathsInTitleBar) })
yield({ checkBox(cdShowMenuIcons) })
}
// Since some of the columns have variable number of items, enumerate them in a loop, while moving orphaned items from the right
// column to the left one:
val leftIt = leftColumnControls.iterator()
val rightIt = rightColumnControls.iterator()
while (leftIt.hasNext() || rightIt.hasNext()) {
when {
leftIt.hasNext() && rightIt.hasNext() -> twoColumnRow(leftIt.next(), rightIt.next())
leftIt.hasNext() -> twoColumnRow(leftIt.next()) { placeholder() }
rightIt.hasNext() -> twoColumnRow(rightIt.next()) { placeholder() } // move from right to left
}
}
val backgroundImageAction = ActionManager.getInstance().getAction("Images.SetBackgroundImage")
if (backgroundImageAction != null) {
fullRow {
buttonFromAction(message("background.image.button"), ActionPlaces.UNKNOWN, backgroundImageAction)
.applyToComponent { isEnabled = ProjectManager.getInstance().openProjects.isNotEmpty() }
}
}
}
if (Registry.`is`("ide.transparency.mode.for.windows") &&
WindowManagerEx.getInstanceEx().isAlphaModeSupported) {
val settingsState = settings.state
titledRow(message("group.transparency")) {
lateinit var checkbox: CellBuilder<JBCheckBox>
fullRow { checkbox = checkBox(cdUseTransparentMode) }
fullRow {
label(message("label.transparency.delay.ms"))
intTextField(settingsState::alphaModeDelay, columns = 4)
}.enableIf(checkbox.selected)
fullRow {
label(message("label.transparency.ratio"))
slider(0, 100, 10, 50)
.labelTable {
put(0, JLabel("0%"))
put(50, JLabel("50%"))
put(100, JLabel("100%"))
}
.withValueBinding(
PropertyBinding(
{ (settingsState.alphaModeRatio * 100f).toInt() },
{ settingsState.alphaModeRatio = it / 100f }
)
)
.applyToComponent {
addChangeListener { toolTipText = "${value}%" }
}
}.enableIf(checkbox.selected)
}
}
titledRow(message("group.antialiasing.mode")) {
twoColumnRow(
{
label(message("label.text.antialiasing.scope.ide"))
val ideAAOptions =
if (!AntialiasingType.canUseSubpixelAAForIDE())
arrayOf(AntialiasingType.GREYSCALE, AntialiasingType.OFF)
else
AntialiasingType.values()
val comboboxIde = comboBox(DefaultComboBoxModel(ideAAOptions), settings::ideAAType, renderer = AAListCellRenderer(false))
.shouldUpdateLaF()
comboboxIde.component.accessibleContext.accessibleName = message("label.text.antialiasing.scope.ide")
comboboxIde.onApply {
for (w in Window.getWindows()) {
for (c in UIUtil.uiTraverser(w).filter(JComponent::class.java)) {
GraphicsUtil.setAntialiasingType(c, AntialiasingType.getAAHintForSwingComponent())
}
}
}
},
{
label(message("label.text.antialiasing.scope.editor"))
val editorAAOptions =
if (!AntialiasingType.canUseSubpixelAAForEditor())
arrayOf(AntialiasingType.GREYSCALE, AntialiasingType.OFF)
else
AntialiasingType.values()
comboBox(DefaultComboBoxModel(editorAAOptions), settings::editorAAType, renderer = AAListCellRenderer(true))
.shouldUpdateLaF()
.component.accessibleContext.accessibleName = message("label.text.antialiasing.scope.editor")
}
)
}
titledRow(message("group.window.options")) {
twoColumnRow(
{ checkBox(cdShowToolWindowBars) },
{ checkBox(cdShowToolWindowNumbers) }
)
twoColumnRow(
{ checkBox(cdLeftToolWindowLayout) },
{ checkBox(cdRightToolWindowLayout) }
)
row {
checkBox(cdWidescreenToolWindowLayout)
ContextHelpLabel.create(message("checkbox.widescreen.tool.window.layout.description"))()
}
}
titledRow(message("group.presentation.mode")) {
fullRow {
label(message("presentation.mode.fon.size"))
fontSizeComboBox({ settings.presentationModeFontSize },
{ settings.presentationModeFontSize = it },
settings.presentationModeFontSize)
.shouldUpdateLaF()
}
}
}
}
override fun apply() {
val uiSettingsChanged = isModified
shouldUpdateLaF = false
super.apply()
if (shouldUpdateLaF) {
LafManager.getInstance().updateUI()
}
if (uiSettingsChanged) {
UISettings.instance.fireUISettingsChanged()
EditorFactory.getInstance().refreshAllEditors()
}
}
private fun <T : JComponent> CellBuilder<T>.shouldUpdateLaF(): CellBuilder<T> = onApply { shouldUpdateLaF = true }
}
fun Cell.fontSizeComboBox(getter: () -> Int, setter: (Int) -> Unit, defaultValue: Int): CellBuilder<ComboBox<String>> {
val model = DefaultComboBoxModel(UIUtil.getStandardFontSizes())
val modelBinding: PropertyBinding<String?> = PropertyBinding({ getter().toString() }, { setter(getIntValue(it, defaultValue)) })
return component(ComboBox(model))
.applyToComponent {
isEditable = true
renderer = SimpleListCellRenderer.create("") { it.toString() }
selectedItem = modelBinding.get()
accessibleContext.accessibleName = message("presentation.mode.fon.size")
}
.withBinding(
{ component -> component.editor.item as String? },
{ component, value -> component.setSelectedItem(value) },
modelBinding
)
}
fun RowBuilder.fullRow(init: InnerCell.() -> Unit): Row = row { cell(isFullWidth = true, init = init) }
private fun RowBuilder.twoColumnRow(column1: InnerCell.() -> Unit, column2: InnerCell.() -> Unit): Row = row {
cell {
column1()
}
placeholder().withLeftGap(JBUI.scale(60))
cell {
column2()
}
placeholder().constraints(growX, pushX)
}
private fun getIntValue(text: String?, defaultValue: Int): Int {
if (text != null && text.isNotBlank()) {
val value = text.toIntOrNull()
if (value != null && value > 0) return value
}
return defaultValue
}
private class AAListCellRenderer(private val myUseEditorFont: Boolean) : SimpleListCellRenderer<AntialiasingType>() {
private val SUBPIXEL_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB)
private val GREYSCALE_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
override fun customize(list: JList<out AntialiasingType>, value: AntialiasingType, index: Int, selected: Boolean, hasFocus: Boolean) {
val aaType = when (value) {
AntialiasingType.SUBPIXEL -> SUBPIXEL_HINT
AntialiasingType.GREYSCALE -> GREYSCALE_HINT
AntialiasingType.OFF -> null
}
GraphicsUtil.setAntialiasingType(this, aaType)
if (myUseEditorFont) {
val scheme = EditorColorsManager.getInstance().globalScheme
font = Font(scheme.editorFontName, Font.PLAIN, scheme.editorFontSize)
}
text = value.presentableName
}
}
| apache-2.0 | c3e5e543fdc9ec350f7c096de9a5bf94 | 50.303704 | 284 | 0.674319 | 5.010369 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/builders/builders.kt | 2 | 8856 | // IGNORE_BACKEND: NATIVE
// FILE: 1.kt
// WITH_RUNTIME
package builders
import java.util.ArrayList
import java.util.HashMap
abstract class Element {
abstract fun render(builder: StringBuilder, indent: String)
override fun toString(): String {
val builder = StringBuilder()
render(builder, "")
return builder.toString()
}
}
class TextElement(val text: String) : Element() {
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent$text\n")
}
}
abstract class Tag(val name: String) : Element() {
val children = ArrayList<Element>()
val attributes = HashMap<String, String>()
inline protected fun <T : Element> initTag(tag: T, init: T.() -> Unit): T {
tag.init()
children.add(tag)
return tag
}
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent<$name${renderAttributes()}>\n")
for (c in children) {
c.render(builder, indent + " ")
}
builder.append("$indent</$name>\n")
}
private fun renderAttributes(): String? {
val builder = StringBuilder()
for (a in attributes.keys) {
builder.append(" $a=\"${attributes[a]}\"")
}
return builder.toString()
}
}
abstract class TagWithText(name: String) : Tag(name) {
operator fun String.unaryPlus() {
children.add(TextElement(this))
}
}
class HTML() : TagWithText("html") {
inline fun head(init: Head.() -> Unit) = initTag(Head(), init)
inline fun body(init: Body.() -> Unit) = initTag(Body(), init)
fun bodyNoInline(init: Body.() -> Unit) = initTag(Body(), init)
}
class Head() : TagWithText("head") {
inline fun title(init: Title.() -> Unit) = initTag(Title(), init)
}
class Title() : TagWithText("title")
abstract class BodyTag(name: String) : TagWithText(name) {
inline fun b(init: B.() -> Unit) = initTag(B(), init)
inline fun p(init: P.() -> Unit) = initTag(P(), init)
inline fun pNoInline(init: P.() -> Unit) = initTag(P(), init)
inline fun h1(init: H1.() -> Unit) = initTag(H1(), init)
inline fun ul(init: UL.() -> Unit) = initTag(UL(), init)
inline fun a(href: String, init: A.() -> Unit) {
val a = initTag(A(), init)
a.href = href
}
}
class Body() : BodyTag("body")
class UL() : BodyTag("ul") {
inline fun li(init: LI.() -> Unit) = initTag(LI(), init)
}
class B() : BodyTag("b")
class LI() : BodyTag("li")
class P() : BodyTag("p")
class H1() : BodyTag("h1")
class A() : BodyTag("a") {
public var href: String
get() = attributes["href"]!!
set(value) {
attributes["href"] = value
}
}
inline fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}
fun htmlNoInline(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}
// FILE: 2.kt
//NO_CHECK_LAMBDA_INLINING
import builders.*
fun testAllInline() : String {
val args = arrayOf("1", "2", "3")
val result =
html {
val htmlVal = 0
head {
title { +"XML encoding with Kotlin" }
}
body {
var bodyVar = 1
h1 { +"XML encoding with Kotlin" }
p { +"this format can be used as an alternative markup to XML" }
// an element with attributes and text content
a(href = "http://jetbrains.com/kotlin") { +"Kotlin" }
// mixed content
p {
+"This is some"
b { +"mixed" }
+"text. For more see the"
a(href = "http://jetbrains.com/kotlin") { +"Kotlin" }
+"project"
}
p { +"some text" }
// content generated from command-line arguments
p {
+"Command line arguments were:"
ul {
for (arg in args)
li { +arg; +"$htmlVal"; +"$bodyVar" }
}
}
}
}
return result.toString()!!
}
fun testHtmlNoInline() : String {
val args = arrayOf("1", "2", "3")
val result =
htmlNoInline() {
val htmlVal = 0
head {
title { +"XML encoding with Kotlin" }
}
body {
var bodyVar = 1
h1 { +"XML encoding with Kotlin" }
p { +"this format can be used as an alternative markup to XML" }
// an element with attributes and text content
a(href = "http://jetbrains.com/kotlin") { +"Kotlin" }
// mixed content
p {
+"This is some"
b { +"mixed" }
+"text. For more see the"
a(href = "http://jetbrains.com/kotlin") { +"Kotlin" }
+"project"
}
p { +"some text" }
// content generated from command-line arguments
p {
+"Command line arguments were:"
ul {
for (arg in args)
li { +arg; +"$htmlVal"; +"$bodyVar" }
}
}
}
}
return result.toString()!!
}
fun testBodyNoInline() : String {
val args = arrayOf("1", "2", "3")
val result =
html {
val htmlVal = 0
head {
title { +"XML encoding with Kotlin" }
}
bodyNoInline {
var bodyVar = 1
h1 { +"XML encoding with Kotlin" }
p { +"this format can be used as an alternative markup to XML" }
// an element with attributes and text content
a(href = "http://jetbrains.com/kotlin") { +"Kotlin" }
// mixed content
p {
+"This is some"
b { +"mixed" }
+"text. For more see the"
a(href = "http://jetbrains.com/kotlin") { +"Kotlin" }
+"project"
}
p { +"some text" }
// content generated from command-line arguments
p {
+"Command line arguments were:"
ul {
for (arg in args)
li { +arg; +"$htmlVal"; +"$bodyVar" }
}
}
}
}
return result.toString()!!
}
fun testBodyHtmlNoInline() : String {
val args = arrayOf("1", "2", "3")
val result =
htmlNoInline {
val htmlVal = 0
head {
title { +"XML encoding with Kotlin" }
}
bodyNoInline {
var bodyVar = 1
h1 { +"XML encoding with Kotlin" }
p { +"this format can be used as an alternative markup to XML" }
// an element with attributes and text content
a(href = "http://jetbrains.com/kotlin") { +"Kotlin" }
// mixed content
p {
+"This is some"
b { +"mixed" }
+"text. For more see the"
a(href = "http://jetbrains.com/kotlin") { +"Kotlin" }
+"project"
}
p { +"some text" }
// content generated from command-line arguments
p {
+"Command line arguments were:"
ul {
for (arg in args)
li { +arg; +"$htmlVal"; +"$bodyVar" }
}
}
}
}
return result.toString()!!
}
fun box(): String {
var expected = testAllInline();
if (expected != testHtmlNoInline()) return "fail 1: ${testHtmlNoInline()}\nbut expected\n${expected} "
if (expected != testBodyNoInline()) return "fail 2: ${testBodyNoInline()}\nbut expected\n${expected} "
if (expected != testBodyHtmlNoInline()) return "fail 3: ${testBodyHtmlNoInline()}\nbut expected\n${expected} "
return "OK"
}
| apache-2.0 | 78ed0e9890414ab2e92e369ded62c2d7 | 29.75 | 114 | 0.442864 | 4.670886 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/text/StringNumberConversionTest/shortToStringWithRadix.kt | 2 | 484 | import kotlin.test.*
fun box() {
assertEquals("7FFF", 0x7FFF.toShort().toString(radix = 16).toUpperCase())
assertEquals("-8000", (-0x8000).toShort().toString(radix = 16))
assertEquals("-sfs", (-29180).toShort().toString(radix = 32))
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 37") { 37.toShort().toString(radix = 37) }
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 1") { 1.toShort().toString(radix = 1) }
}
| apache-2.0 | 05253f57b51c887c0cd3c4d110bce1cd | 39.333333 | 117 | 0.694215 | 4.067227 | false | true | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/vcs/VcsShowToolWindowTabAction.kt | 7 | 2030 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.SHELF
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor
import com.intellij.openapi.wm.ToolWindow
class VcsShowLocalChangesAction : VcsShowToolWindowTabAction() {
override val tabName: String get() = LOCAL_CHANGES
}
class VcsShowShelfAction : VcsShowToolWindowTabAction() {
override val tabName: String get() = SHELF
}
abstract class VcsShowToolWindowTabAction : DumbAwareAction() {
protected abstract val tabName: String
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = getToolWindow(e.project) != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val toolWindow = getToolWindow(project)!!
val contentManager = ChangesViewContentManager.getInstance(project) as ChangesViewContentManager
val isToolWindowActive = toolWindow.isActive
val isContentSelected = contentManager.isContentSelected(tabName)
val tabSelector = Runnable { contentManager.selectContent(tabName, true) }
when {
isToolWindowActive && isContentSelected -> toolWindow.hide(null)
isToolWindowActive && !isContentSelected -> tabSelector.run()
!isToolWindowActive && isContentSelected -> toolWindow.activate(null, true)
!isToolWindowActive && !isContentSelected -> toolWindow.activate(tabSelector, false)
}
}
private fun getToolWindow(project: Project?): ToolWindow? = project?.let { getToolWindowFor(it, tabName) }
} | apache-2.0 | cf0798280456bac8830285c4c9a897e1 | 43.152174 | 140 | 0.791133 | 4.833333 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt | 6 | 4062 | // 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.loopToCallChain.sequence
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.*
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.util.FuzzyType
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class FlatMapTransformation(
override val loop: KtForExpression,
val inputVariable: KtCallableDeclaration,
val transform: KtExpression
) : SequenceTransformation {
override val affectsIndex: Boolean
get() = true
override val presentation: String
get() = "flatMap{}"
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
val lambda = generateLambda(inputVariable, transform, chainedCallGenerator.reformat)
return chainedCallGenerator.generate("flatMap$0:'{}'", lambda)
}
/**
* Matches:
* for (...) {
* ...
* for (...) {
* ...
* }
* }
*/
object Matcher : TransformationMatcher {
override val indexVariableAllowed: Boolean
get() = true
override fun match(state: MatchingState): TransformationMatch.Sequence? {
val nestedLoop = state.statements.singleOrNull() as? KtForExpression ?: return null
val transform = nestedLoop.loopRange ?: return null
// check that we iterate over Iterable
val nestedSequenceType = transform.analyze(BodyResolveMode.PARTIAL).getType(transform) ?: return null
val builtIns = transform.builtIns
val iterableType = FuzzyType(builtIns.iterableType, builtIns.iterable.declaredTypeParameters)
if (iterableType.checkIsSuperTypeOf(nestedSequenceType) == null) return null
val nestedLoopBody = nestedLoop.body ?: return null
val newInputVariable = nestedLoop.loopParameter ?: return null
if (state.indexVariable != null && state.indexVariable.hasUsages(transform)) {
// if nested loop range uses index, convert to "mapIndexed {...}.flatMap { it }"
val mapIndexedTransformation =
MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, transform, mapNotNull = false)
val inputVarExpression = KtPsiFactory(nestedLoop).createExpressionByPattern(
"$0", state.inputVariable.nameAsSafeName,
reformat = state.reformat
)
val transformToUse = if (state.lazySequence) inputVarExpression.asSequence(state.reformat) else inputVarExpression
val flatMapTransformation = FlatMapTransformation(state.outerLoop, state.inputVariable, transformToUse)
val newState = state.copy(
innerLoop = nestedLoop,
statements = listOf(nestedLoopBody),
inputVariable = newInputVariable
)
return TransformationMatch.Sequence(listOf(mapIndexedTransformation, flatMapTransformation), newState)
}
val transformToUse = if (state.lazySequence) transform.asSequence(state.reformat) else transform
val transformation = FlatMapTransformation(state.outerLoop, state.inputVariable, transformToUse)
val newState = state.copy(
innerLoop = nestedLoop,
statements = listOf(nestedLoopBody),
inputVariable = newInputVariable
)
return TransformationMatch.Sequence(transformation, newState)
}
private fun KtExpression.asSequence(reformat: Boolean): KtExpression = KtPsiFactory(this).createExpressionByPattern(
"$0.asSequence()", this,
reformat = reformat
)
}
} | apache-2.0 | 28da28a94ae73bec3d11537d16bc5111 | 45.170455 | 158 | 0.660758 | 5.504065 | false | false | false | false |
vanniktech/lint-rules | lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/StringXmlDetector.kt | 1 | 1505 | @file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final.
package com.vanniktech.lintrules.android
import com.android.SdkConstants.TAG_PLURALS
import com.android.SdkConstants.TAG_STRING
import com.android.SdkConstants.TAG_STRING_ARRAY
import com.android.resources.ResourceFolderType
import com.android.resources.ResourceFolderType.VALUES
import com.android.tools.lint.detector.api.ResourceXmlDetector
import com.android.tools.lint.detector.api.XmlContext
import org.w3c.dom.Element
import org.w3c.dom.Node
import java.util.EnumSet
abstract class StringXmlDetector : ResourceXmlDetector() {
final override fun appliesTo(folderType: ResourceFolderType) = EnumSet.of(VALUES).contains(folderType)
final override fun getApplicableElements() = listOf(TAG_STRING, TAG_STRING_ARRAY, TAG_PLURALS)
final override fun visitElement(context: XmlContext, element: Element) {
element.children()
.forEach { child ->
val isStringResource = child.isTextNode() && TAG_STRING == element.localName
val isStringArrayOrPlurals = child.isElementNode() && (TAG_STRING_ARRAY == element.localName || TAG_PLURALS == element.localName)
if (isStringResource) {
checkText(context, element, child)
} else if (isStringArrayOrPlurals) {
child.children()
.filter { it.isTextNode() }
.forEach { checkText(context, child, it) }
}
}
}
abstract fun checkText(context: XmlContext, node: Node, textNode: Node)
}
| apache-2.0 | 20640fe071bd9210cf109cdb516f0a25 | 38.605263 | 137 | 0.738206 | 4.024064 | false | false | false | false |
alt236/Bluetooth-LE-Library---Android | sample_app/src/main/java/uk/co/alt236/btlescan/containers/BluetoothLeDeviceStore.kt | 1 | 1725 | package uk.co.alt236.btlescan.containers
import uk.co.alt236.bluetoothlelib.device.BluetoothLeDevice
import uk.co.alt236.easycursor.objectcursor.EasyObjectCursor
import java.util.*
class BluetoothLeDeviceStore {
private val mDeviceMap = HashMap<String, BluetoothLeDevice>()
fun addDevice(device: BluetoothLeDevice) {
if (mDeviceMap.containsKey(device.address)) {
mDeviceMap[device.address]!!.updateRssiReading(device.timestamp, device.rssi)
} else {
mDeviceMap[device.address] = device
}
}
fun clear() {
mDeviceMap.clear()
}
val size: Int
get() = mDeviceMap.size
val deviceCursor: EasyObjectCursor<BluetoothLeDevice>
get() = getDeviceCursor(DEFAULT_COMPARATOR)
fun getDeviceCursor(comparator: Comparator<BluetoothLeDevice>): EasyObjectCursor<BluetoothLeDevice> {
return EasyObjectCursor(
BluetoothLeDevice::class.java,
getDeviceList(comparator),
"address")
}
val deviceList: List<BluetoothLeDevice>
get() = getDeviceList(DEFAULT_COMPARATOR)
fun getDeviceList(comparator: Comparator<BluetoothLeDevice>): List<BluetoothLeDevice> {
val methodResult: List<BluetoothLeDevice> = ArrayList(mDeviceMap.values)
Collections.sort(methodResult, comparator)
return methodResult
}
private class BluetoothLeDeviceComparator : Comparator<BluetoothLeDevice> {
override fun compare(arg0: BluetoothLeDevice, arg1: BluetoothLeDevice): Int {
return arg0.address.compareTo(arg1.address)
}
}
companion object {
private val DEFAULT_COMPARATOR = BluetoothLeDeviceComparator()
}
} | apache-2.0 | f814fbd895a880f7f42a11a0fdb61a7d | 31.566038 | 105 | 0.691594 | 4.539474 | false | false | false | false |
JetBrains/kotlin-native | tools/benchmarks/shared/src/main/kotlin/analyzer/FieldChange.kt | 4 | 1126 | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.analyzer
// Report with changes of different fields.
class ChangeReport<T>(val entityName: String, val changes: List<FieldChange<T>>) {
fun renderAsTextReport(): String {
var content = ""
if (!changes.isEmpty()) {
content = "$content$entityName changes\n"
content = "$content====================\n"
changes.forEach {
content = "$content${it.renderAsText()}"
}
}
return content
}
}
// Change of report field.
class FieldChange<T>(val field: String, val previous: T, val current: T) {
companion object {
fun <T> getFieldChangeOrNull(field: String, previous: T, current: T): FieldChange<T>? {
if (previous != current) {
return FieldChange(field, previous, current)
}
return null
}
}
fun renderAsText(): String {
return "$field: $previous -> $current\n"
}
} | apache-2.0 | 3b88213f8d0294d962f3ed173fadfd70 | 29.459459 | 101 | 0.578153 | 4.249057 | false | false | false | false |
allotria/intellij-community | platform/testFramework/src/com/intellij/testFramework/fixtures/InjectionTestFixture.kt | 2 | 4793 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testFramework.fixtures
import com.intellij.codeInsight.intention.impl.QuickEditAction
import com.intellij.codeInsight.intention.impl.QuickEditHandler
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.UsefulTestCase
import junit.framework.TestCase
import java.util.*
import kotlin.collections.HashSet
import kotlin.test.fail
class InjectionTestFixture(private val javaFixture: CodeInsightTestFixture) {
val injectedLanguageManager: InjectedLanguageManager
get() = InjectedLanguageManager.getInstance(javaFixture.project)
val injectedElement: PsiElement?
get() {
return injectedLanguageManager.findInjectedElementAt(topLevelFile ?: return null, topLevelCaretPosition)
}
fun assertInjectedLangAtCaret(lang: String?) {
val injectedElement = injectedElement
if (lang != null) {
TestCase.assertNotNull("injection of '$lang' expected", injectedElement)
TestCase.assertEquals(lang, injectedElement!!.language.id)
}
else {
TestCase.assertNull(injectedElement)
}
}
fun getAllInjections(): List<Pair<PsiElement, PsiFile>> {
val injected = mutableListOf<Pair<PsiElement, PsiFile>>()
val hosts = PsiTreeUtil.collectElementsOfType(topLevelFile, PsiLanguageInjectionHost::class.java)
for (host in hosts) {
injectedLanguageManager.enumerate(host, PsiLanguageInjectionHost.InjectedPsiVisitor { injectedPsi, _ ->
injected.add(host to injectedPsi)
})
}
return injected
}
fun assertInjectedContent(vararg expectedInjectFileTexts: String) {
assertInjectedContent("injected content expected", expectedInjectFileTexts.toList())
}
fun assertInjectedContent(message: String, expectedFilesTexts: List<String>) {
UsefulTestCase.assertSameElements(message,
getAllInjections().mapTo(HashSet()) { it.second }.map { it.text },
expectedFilesTexts)
}
fun assertInjected(vararg expectedInjections: InjectionAssertionData) {
val expected = expectedInjections.toCollection(LinkedList())
val foundInjections = getAllInjections().toCollection(LinkedList())
while (expected.isNotEmpty()) {
val (text, injectedLanguage) = expected.pop()
val found = (foundInjections.find { (psi, file) -> psi.text == text && file.language.id == injectedLanguage }
?: fail(
"no injection '$text' -> '$injectedLanguage' were found, remains: ${foundInjections.joinToString { (psi, file) -> "'${psi.text}' -> '${file.language}'" }} "))
foundInjections.remove(found)
}
}
fun openInFragmentEditor(): EditorTestFixture {
val quickEditHandler = QuickEditAction().invokeImpl(javaFixture.project, topLevelEditor, topLevelFile)
return openInFragmentEditor(quickEditHandler)
}
fun openInFragmentEditor(quickEditHandler: QuickEditHandler): EditorTestFixture {
val injectedFile = quickEditHandler.newFile
val project = javaFixture.project
val documentWindow = InjectedLanguageUtil.getDocumentWindow(injectedElement?.containingFile!!)
val offset = topLevelEditor.caretModel.offset
val unEscapedOffset = InjectedLanguageUtil.hostToInjectedUnescaped(documentWindow, offset)
val fragmentEditor = FileEditorManagerEx.getInstanceEx(project).openTextEditor(
OpenFileDescriptor(project, injectedFile.virtualFile, unEscapedOffset), true
)
return EditorTestFixture(project, fragmentEditor, injectedFile.virtualFile)
}
val topLevelFile: PsiFile
get() = javaFixture.file!!.let { injectedLanguageManager.getTopLevelFile(it) }
val topLevelCaretPosition
get() = topLevelEditor.caretModel.offset
val topLevelEditor: Editor
get() = (FileEditorManager.getInstance(javaFixture.project).getSelectedEditor(topLevelFile!!.virtualFile) as TextEditor).editor
}
data class InjectionAssertionData(val text: String, val injectedLanguage: String? = null) {
fun hasLanguage(lang: String): InjectionAssertionData = this.copy(injectedLanguage = lang)
}
fun injectionForHost(text: String) = InjectionAssertionData(text) | apache-2.0 | 520e590acc7c936cc5c322e9a424c82d | 42.189189 | 181 | 0.760275 | 4.910861 | false | true | false | false |
androidx/androidx | compose/material/material/integration-tests/material-catalog/src/main/java/androidx/compose/material/catalog/library/ui/example/ExampleItem.kt | 3 | 3307 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.catalog.library.ui.example
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Card
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Icon
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.catalog.library.model.Example
import androidx.compose.material.catalog.library.ui.common.BorderWidth
import androidx.compose.material.catalog.library.ui.common.compositeBorderColor
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun ExampleItem(
example: Example,
onClick: (example: Example) -> Unit
) {
Card(
elevation = 0.dp,
border = BorderStroke(
width = BorderWidth,
color = compositeBorderColor()
),
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier
.clickable { onClick(example) }
.padding(ExampleItemPadding)
) {
Column(modifier = Modifier.weight(1f, fill = true)) {
Text(
text = example.name,
style = MaterialTheme.typography.subtitle2
)
Spacer(modifier = Modifier.height(ExampleItemTextPadding))
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = example.description,
style = MaterialTheme.typography.caption
)
}
}
Spacer(modifier = Modifier.width(ExampleItemPadding))
Icon(
imageVector = Icons.Default.KeyboardArrowRight,
contentDescription = null,
modifier = Modifier.align(Alignment.CenterVertically)
)
}
}
}
private val ExampleItemPadding = 16.dp
private val ExampleItemTextPadding = 8.dp
| apache-2.0 | c9f5eb5a47f67cfc90b3b05cbb23eb0c | 37.011494 | 90 | 0.701845 | 4.841874 | false | false | false | false |
androidx/androidx | compose/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/integration/macrobenchmark/target/LazyVerticalGridActivity.kt | 3 | 2599 | /*
* 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
*
* 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.integration.macrobenchmark.target
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
class LazyVerticalGridActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val itemCount = intent.getIntExtra(EXTRA_ITEM_COUNT, 12000)
val entries = List(itemCount) { Entry("$it") }
setContent {
MaterialTheme {
LazyVerticalGrid(
columns = GridCells.Fixed(4),
modifier = Modifier.fillMaxWidth().semantics { contentDescription = "IamLazy" }
) {
items(entries) {
ListCell(it)
}
}
}
}
launchIdlenessTracking()
}
companion object {
const val EXTRA_ITEM_COUNT = "ITEM_COUNT"
}
}
@Composable
private fun ListCell(entry: Entry) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Text(
text = entry.contents,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h5,
modifier = Modifier.padding(16.dp)
)
}
} | apache-2.0 | 8ae81cdcc46d7a6adde6e2f5c1c1619a | 31.911392 | 99 | 0.684494 | 4.682883 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/LazyGridSamples.kt | 3 | 6074 | /*
* 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
*
* 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.foundation.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.flow.collect
@Sampled
@Composable
fun LazyVerticalGridSample() {
val itemsList = (0..5).toList()
val itemsIndexedList = listOf("A", "B", "C")
val itemModifier = Modifier.border(1.dp, Color.Blue).height(80.dp).wrapContentSize()
LazyVerticalGrid(
columns = GridCells.Fixed(3)
) {
items(itemsList) {
Text("Item is $it", itemModifier)
}
item {
Text("Single item", itemModifier)
}
itemsIndexed(itemsIndexedList) { index, item ->
Text("Item at index $index is $item", itemModifier)
}
}
}
@Sampled
@Composable
fun LazyVerticalGridSpanSample() {
val sections = (0 until 25).toList().chunked(5)
LazyVerticalGrid(
columns = GridCells.Fixed(3),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
sections.forEachIndexed { index, items ->
item(span = { GridItemSpan(maxLineSpan) }) {
Text(
"This is section $index",
Modifier.border(1.dp, Color.Gray).height(80.dp).wrapContentSize()
)
}
items(
items,
// not required as it is the default
span = { GridItemSpan(1) }
) {
Text(
"Item $it",
Modifier.border(1.dp, Color.Blue).height(80.dp).wrapContentSize()
)
}
}
}
}
@Sampled
@Composable
fun LazyHorizontalGridSample() {
val itemsList = (0..5).toList()
val itemsIndexedList = listOf("A", "B", "C")
val itemModifier = Modifier.border(1.dp, Color.Blue).width(80.dp).wrapContentSize()
LazyHorizontalGrid(
rows = GridCells.Fixed(3),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
items(itemsList) {
Text("Item is $it", itemModifier)
}
item {
Text("Single item", itemModifier)
}
itemsIndexed(itemsIndexedList) { index, item ->
Text("Item at index $index is $item", itemModifier)
}
}
}
@Sampled
@Composable
fun LazyHorizontalGridSpanSample() {
val sections = (0 until 25).toList().chunked(5)
LazyHorizontalGrid(
rows = GridCells.Fixed(3),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
sections.forEachIndexed { index, items ->
item(span = { GridItemSpan(maxLineSpan) }) {
Text(
"This is section $index",
Modifier.border(1.dp, Color.Gray).width(80.dp).wrapContentSize()
)
}
items(
items,
// not required as it is the default
span = { GridItemSpan(1) }
) {
Text(
"Item $it",
Modifier.border(1.dp, Color.Blue).width(80.dp).wrapContentSize()
)
}
}
}
}
@Sampled
@Composable
fun UsingGridScrollPositionForSideEffectSample() {
val gridState = rememberLazyGridState()
LaunchedEffect(gridState) {
snapshotFlow { gridState.firstVisibleItemIndex }
.collect {
// use the new index
}
}
}
@Sampled
@Composable
fun UsingGridScrollPositionInCompositionSample() {
val gridState = rememberLazyGridState()
val isAtTop by remember {
derivedStateOf {
gridState.firstVisibleItemIndex == 0 && gridState.firstVisibleItemScrollOffset == 0
}
}
if (!isAtTop) {
ScrollToTopButton(gridState)
}
}
@Sampled
@Composable
fun UsingGridLayoutInfoForSideEffectSample() {
val gridState = rememberLazyGridState()
LaunchedEffect(gridState) {
snapshotFlow { gridState.layoutInfo.totalItemsCount }
.collect {
// use the new items count
}
}
}
@Composable
private fun ScrollToTopButton(@Suppress("UNUSED_PARAMETER") gridState: LazyGridState) {
}
| apache-2.0 | a705d24a31d014965c43939691e7a7bc | 30.148718 | 95 | 0.644057 | 4.505935 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/CompilationPartsUtil.kt | 2 | 19574 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "UnstableApiUsage")
package org.jetbrains.intellij.build.impl.compilation
import com.intellij.diagnostic.telemetry.forkJoinTask
import com.intellij.diagnostic.telemetry.use
import com.intellij.diagnostic.telemetry.useWithScope
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import io.opentelemetry.context.Context
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.jetbrains.annotations.VisibleForTesting
import org.jetbrains.intellij.build.BuildMessages
import org.jetbrains.intellij.build.CompilationContext
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.io.AddDirEntriesMode
import org.jetbrains.intellij.build.io.deleteDir
import org.jetbrains.intellij.build.io.zip
import java.math.BigInteger
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.FileTime
import java.security.MessageDigest
import java.util.*
import java.util.concurrent.*
import java.util.zip.GZIPOutputStream
import kotlin.math.min
class CompilationCacheUploadConfiguration(
serverUrl: String? = null,
val checkFiles: Boolean = true,
val uploadOnly: Boolean = false,
branch: String? = null,
) {
val serverUrl: String = serverUrl ?: normalizeServerUrl()
val branch: String = branch ?: System.getProperty(branchPropertyName).also {
check(!it.isNullOrBlank()) {
"Git branch is not defined. Please set $branchPropertyName system property."
}
}
companion object {
private const val branchPropertyName = "intellij.build.compiled.classes.branch"
private fun normalizeServerUrl(): String {
val serverUrlPropertyName = "intellij.build.compiled.classes.server.url"
var result = System.getProperty(serverUrlPropertyName)?.trimEnd('/')
check(!result.isNullOrBlank()) {
"Compilation cache archive server url is not defined. Please set $serverUrlPropertyName system property."
}
if (!result.startsWith("http")) {
@Suppress("HttpUrlsUsage")
result = (if (result.startsWith("localhost:")) "http://" else "https://") + result
}
return result
}
}
}
const val COMPILATION_CACHE_METADATA_JSON = "metadata.json"
fun packAndUploadToServer(context: CompilationContext, zipDir: Path, config: CompilationCacheUploadConfiguration) {
val items = if (config.uploadOnly) {
Json.decodeFromString<CompilationPartsMetadata>(Files.readString(zipDir.resolve(COMPILATION_CACHE_METADATA_JSON))).files.map {
val item = PackAndUploadItem(output = Path.of(""), name = it.key, archive = zipDir.resolve(it.key + ".jar"))
item.hash = it.value
item
}
}
else {
spanBuilder("pack classes").useWithScope {
packCompilationResult(context, zipDir)
}
}
createBufferPool().use { bufferPool ->
spanBuilder("upload packed classes").use {
upload(config = config, zipDir = zipDir, messages = context.messages, items = items, bufferPool = bufferPool)
}
}
}
private fun createBufferPool(): DirectFixedSizeByteBufferPool {
// 4MB block, x2 of FJP thread count - one buffer to source, another one for target
return DirectFixedSizeByteBufferPool(size = MAX_BUFFER_SIZE, maxPoolSize = ForkJoinPool.getCommonPoolParallelism() * 2)
}
fun packCompilationResult(context: CompilationContext, zipDir: Path, addDirEntriesMode: AddDirEntriesMode = AddDirEntriesMode.NONE): List<PackAndUploadItem> {
val incremental = context.options.incrementalCompilation
if (!incremental) {
try {
deleteDir(zipDir)
}
catch (ignore: NoSuchFileException) {
}
}
Files.createDirectories(zipDir)
val items = ArrayList<PackAndUploadItem>(2048)
spanBuilder("compute module list to pack").use { span ->
// production, test
for (subRoot in Files.newDirectoryStream(context.classesOutputDirectory).use(DirectoryStream<Path>::toList)) {
if (!Files.isDirectory(subRoot)) {
continue
}
val subRootName = subRoot.fileName.toString()
Files.createDirectories(zipDir.resolve(subRootName))
Files.newDirectoryStream(subRoot).use { subRootStream ->
for (module in subRootStream) {
val fileName = module.fileName.toString()
val name = "$subRootName/$fileName"
try {
if (isModuleOutputDirEmpty(module)) {
span.addEvent("skip empty module", Attributes.of(
AttributeKey.stringKey("name"), name,
))
continue
}
}
catch (ignore: FileSystemException) {
continue
}
if (context.findModule(fileName) == null) {
span.addEvent("skip module output from missing in project module", Attributes.of(
AttributeKey.stringKey("module"), fileName,
))
continue
}
items.add(PackAndUploadItem(output = module, name = name, archive = zipDir.resolve("$name.jar")))
}
}
}
}
spanBuilder("build zip archives").useWithScope {
val traceContext = Context.current()
ForkJoinTask.invokeAll(items.map { item ->
ForkJoinTask.adapt(Callable {
spanBuilder("pack").setParent(traceContext).setAttribute("name", item.name).use {
// we compress the whole file using ZSTD
zip(
targetFile = item.archive,
dirs = mapOf(item.output to ""),
overwrite = true,
fileFilter = { it != "classpath.index" && it != ".unmodified" && it != ".DS_Store" },
addDirEntriesMode = addDirEntriesMode
)
}
spanBuilder("compute hash").setParent(traceContext).setAttribute("name", item.name).use {
item.hash = computeHash(item.archive)
}
})
})
}
return items
}
private fun isModuleOutputDirEmpty(moduleOutDir: Path): Boolean {
Files.newDirectoryStream(moduleOutDir).use {
for (child in it) {
if (!child.endsWith("classpath.index") && !child.endsWith(".unmodified") && !child.endsWith(".DS_Store")) {
return false
}
}
}
return true
}
// TODO: Remove hardcoded constant
internal const val uploadPrefix = "intellij-compile/v2"
private fun upload(config: CompilationCacheUploadConfiguration,
zipDir: Path,
messages: BuildMessages,
items: List<PackAndUploadItem>,
bufferPool: DirectFixedSizeByteBufferPool) {
// prepare metadata for writing into file
val metadataJson = Json.encodeToString(CompilationPartsMetadata(
serverUrl = config.serverUrl,
branch = config.branch,
prefix = uploadPrefix,
files = items.associateTo(TreeMap()) { item ->
item.name to item.hash!!
},
))
// save metadata file
if (!config.uploadOnly) {
val metadataFile = zipDir.resolve(COMPILATION_CACHE_METADATA_JSON)
val gzippedMetadataFile = zipDir.resolve("$COMPILATION_CACHE_METADATA_JSON.gz")
Files.createDirectories(metadataFile.parent)
Files.writeString(metadataFile, metadataJson)
GZIPOutputStream(Files.newOutputStream(gzippedMetadataFile)).use { outputStream ->
Files.copy(metadataFile, outputStream)
}
messages.artifactBuilt(metadataFile.toString())
messages.artifactBuilt(gzippedMetadataFile.toString())
}
spanBuilder("upload archives").setAttribute(AttributeKey.stringArrayKey("items"),
items.map(PackAndUploadItem::name)).useWithScope {
uploadArchives(reportStatisticValue = messages::reportStatisticValue,
config = config,
metadataJson = metadataJson,
httpClient = httpClient,
items = items,
bufferPool = bufferPool)
}
}
@VisibleForTesting
fun fetchAndUnpackCompiledClasses(reportStatisticValue: (key: String, value: String) -> Unit,
withScope: (name: String, operation: () -> Unit) -> Unit,
classOutput: Path,
metadataFile: Path,
saveHash: Boolean) {
withScope("fetch and unpack compiled classes") {
val metadata = Json.decodeFromString<CompilationPartsMetadata>(Files.readString(metadataFile))
val tempDownloadStorage = (System.getProperty("agent.persistent.cache")?.let { Path.of(it) } ?: classOutput.parent)
.resolve("idea-compile-parts-v2")
val items = metadata.files.mapTo(ArrayList(metadata.files.size)) { entry ->
FetchAndUnpackItem(name = entry.key,
hash = entry.value,
output = classOutput.resolve(entry.key),
file = tempDownloadStorage.resolve("${entry.key}/${entry.value}.jar"))
}
items.sortBy { it.name }
var verifyTime = 0L
val upToDate = Collections.newSetFromMap<String>(ConcurrentHashMap())
spanBuilder("check previously unpacked directories").useWithScope { span ->
verifyTime += checkPreviouslyUnpackedDirectories(items = items,
span = span,
upToDate = upToDate,
metadata = metadata,
classOutput = classOutput)
}
reportStatisticValue("compile-parts:up-to-date:count", upToDate.size.toString())
val toUnpack = LinkedHashSet<FetchAndUnpackItem>(items.size)
val toDownload = spanBuilder("check previously downloaded archives").useWithScope { span ->
val start = System.nanoTime()
val result = ForkJoinTask.invokeAll(items.mapNotNull { item ->
if (upToDate.contains(item.name)) {
return@mapNotNull null
}
val file = item.file
toUnpack.add(item)
ForkJoinTask.adapt(Callable {
when {
!Files.exists(file) -> item
item.hash == computeHash(file) -> null
else -> {
span.addEvent("file has unexpected hash, will refetch", Attributes.of(
AttributeKey.stringKey("file"), "${item.name}/${item.hash}.jar",
))
Files.deleteIfExists(file)
item
}
}
})
}).mapNotNull {
it.rawResult
}
verifyTime += TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)
result
}
// toUnpack is performed as part of download
toDownload.forEach(toUnpack::remove)
withScope("cleanup outdated compiled class archives") {
val start = System.nanoTime()
var count = 0
var bytes = 0L
try {
val preserve = items.mapTo(HashSet<Path>(items.size)) { it.file }
val epoch = FileTime.fromMillis(0)
val daysAgo = FileTime.fromMillis(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(4))
Files.createDirectories(tempDownloadStorage)
// we need to traverse with depth 3 since first level is [production, test], second level is module name, third is a file
Files.walk(tempDownloadStorage, 3, FileVisitOption.FOLLOW_LINKS).use { stream ->
stream
.filter { !preserve.contains(it) }
.forEach { file ->
val attr = Files.readAttributes(file, BasicFileAttributes::class.java)
if (attr.isRegularFile) {
val lastAccessTime = attr.lastAccessTime()
if (lastAccessTime > epoch && lastAccessTime < daysAgo) {
count++
bytes += attr.size()
Files.deleteIfExists(file)
}
}
}
}
}
catch (e: Throwable) {
Span.current().addEvent("failed to cleanup outdated archives", Attributes.of(AttributeKey.stringKey("error"), e.message ?: ""))
}
reportStatisticValue("compile-parts:cleanup:time", TimeUnit.NANOSECONDS.toMillis((System.nanoTime() - start)).toString())
reportStatisticValue("compile-parts:removed:bytes", bytes.toString())
reportStatisticValue("compile-parts:removed:count", count.toString())
}
withScope("fetch compiled classes archives") {
val start = System.nanoTime()
val prefix = metadata.prefix
val serverUrl = metadata.serverUrl
val failed = if (toDownload.isEmpty()) {
emptyList()
}
else {
val httpClientWithoutFollowingRedirects = httpClient.newBuilder().followRedirects(false).build()
createBufferPool().use { bufferPool ->
downloadCompilationCache(serverUrl = serverUrl,
prefix = prefix,
toDownload = toDownload,
client = httpClientWithoutFollowingRedirects,
bufferPool = bufferPool,
saveHash = saveHash)
}
}
reportStatisticValue("compile-parts:download:time", TimeUnit.NANOSECONDS.toMillis((System.nanoTime() - start)).toString())
val downloadedBytes = toDownload.sumOf { Files.size(it.file) }
reportStatisticValue("compile-parts:downloaded:bytes", downloadedBytes.toString())
reportStatisticValue("compile-parts:downloaded:count", toDownload.size.toString())
if (!failed.isEmpty()) {
error("Failed to fetch ${failed.size} file${if (failed.size > 1) "s" else ""}, see details above or in a trace file")
}
}
withScope("unpack compiled classes archives") {
val start = System.nanoTime()
ForkJoinTask.invokeAll(toUnpack.map { item ->
forkJoinTask(spanBuilder("unpack").setAttribute("name", item.name)) {
unpackArchive(item, saveHash)
}
})
reportStatisticValue("compile-parts:unpacked:bytes", toUnpack.sumOf { Files.size(it.file) }.toString())
reportStatisticValue("compile-parts:unpacked:count", toUnpack.size.toString())
reportStatisticValue("compile-parts:unpack:time", TimeUnit.NANOSECONDS.toMillis((System.nanoTime() - start)).toString())
}
}
}
private fun checkPreviouslyUnpackedDirectories(items: List<FetchAndUnpackItem>,
span: Span,
upToDate: MutableSet<String>,
metadata: CompilationPartsMetadata,
classOutput: Path): Long {
if (!Files.exists(classOutput)) {
return 0
}
val start = System.nanoTime()
ForkJoinTask.invokeAll(items.map { item ->
ForkJoinTask.adapt {
val out = item.output
if (!Files.exists(out)) {
span.addEvent("output directory doesn't exist", Attributes.of(
AttributeKey.stringKey("name"), item.name,
AttributeKey.stringKey("outDir"), out.toString(),
))
return@adapt
}
val hashFile = out.resolve(".hash")
if (!Files.isRegularFile(hashFile)) {
span.addEvent("no .hash file in output directory", Attributes.of(
AttributeKey.stringKey("name"), item.name,
))
deleteDir(out)
return@adapt
}
try {
val actual = Files.readString(hashFile)
if (actual == item.hash) {
upToDate.add(item.name)
}
else {
span.addEvent("output directory hash mismatch", Attributes.of(
AttributeKey.stringKey("name"), item.name,
AttributeKey.stringKey("expected"), item.hash,
AttributeKey.stringKey("actual"), actual,
))
deleteDir(out)
}
}
catch (e: Throwable) {
span.addEvent("output directory hash calculation failed", Attributes.of(
AttributeKey.stringKey("name"), item.name,
))
span.recordException(e, Attributes.of(
AttributeKey.stringKey("name"), item.name,
))
deleteDir(out)
}
}
} + forkJoinTask(spanBuilder("remove stalled directories not present in metadata")
.setAttribute(AttributeKey.stringArrayKey("keys"),
java.util.List.copyOf(metadata.files.keys))) {
val expectedDirectories = HashSet(metadata.files.keys)
// we need to traverse with depth 2 since first level is [production,test]
val stalledDirs = mutableListOf<Path>()
Files.newDirectoryStream(classOutput).use { rootStream ->
for (subRoot in rootStream) {
if (!Files.isDirectory(subRoot)) {
continue
}
try {
Files.newDirectoryStream(subRoot).use { subRootStream ->
for (module in subRootStream) {
val name = "${subRoot.fileName}/${module.fileName}"
if (!expectedDirectories.contains(name)) {
stalledDirs.add(module)
}
}
}
}
catch (ignore: NoSuchFileException) {
}
}
}
ForkJoinTask.invokeAll(stalledDirs.map { dir ->
forkJoinTask(spanBuilder("delete stalled dir").setAttribute("dir", dir.toString())) { deleteDir(dir) }
})
}
)
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)
}
private val sharedDigest = MessageDigest.getInstance("SHA-256", java.security.Security.getProvider("SUN"))
internal fun sha256() = sharedDigest.clone() as MessageDigest
private fun computeHash(file: Path): String {
val messageDigest = sha256()
FileChannel.open(file, READ_OPERATION).use { channel ->
val fileSize = channel.size()
// java message digest doesn't support native buffer (copies to heap byte array in any case)
val bufferSize = 256 * 1024
val sourceBuffer = ByteBuffer.allocate(bufferSize)
var offset = 0L
while (offset < fileSize) {
sourceBuffer.limit(min((fileSize - offset).toInt(), bufferSize))
do {
offset += channel.read(sourceBuffer, offset)
}
while (sourceBuffer.hasRemaining())
messageDigest.update(sourceBuffer.array(), 0, sourceBuffer.limit())
sourceBuffer.position(0)
}
}
return digestToString(messageDigest)
}
// we cannot change file extension or prefix, so, add suffix
internal fun digestToString(digest: MessageDigest): String = BigInteger(1, digest.digest()).toString(36) + "-z"
data class PackAndUploadItem(
val output: Path,
val name: String,
val archive: Path,
) {
var hash: String? = null
}
internal data class FetchAndUnpackItem(
val name: String,
val hash: String,
val output: Path,
val file: Path
)
/**
* Configuration on which compilation parts to download and from where.
* <br/>
* URL for each part should be constructed like: <pre>${serverUrl}/${prefix}/${files.key}/${files.value}.jar</pre>
*/
@Serializable
private data class CompilationPartsMetadata(
@SerialName("server-url") val serverUrl: String,
val branch: String,
val prefix: String,
/**
* Map compilation part path to a hash, for now SHA-256 is used.
* sha256(file) == hash, though that may be changed in the future.
*/
val files: Map<String, String>,
) | apache-2.0 | d0196b2ed3aaf964327e433ee286a0a2 | 36.716763 | 158 | 0.638347 | 4.726878 | false | false | false | false |
GunoH/intellij-community | plugins/toml/json/src/main/kotlin/org/toml/ide/json/TomlJsonPsiWalker.kt | 8 | 7220 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.toml.ide.json
import com.intellij.json.pointer.JsonPointerPosition
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.parentOfType
import com.intellij.util.ThreeState
import com.intellij.util.containers.ContainerUtil
import com.jetbrains.jsonSchema.extension.JsonLikePsiWalker
import com.jetbrains.jsonSchema.extension.adapters.JsonPropertyAdapter
import com.jetbrains.jsonSchema.extension.adapters.JsonValueAdapter
import org.toml.lang.psi.*
object TomlJsonPsiWalker : JsonLikePsiWalker {
override fun isName(element: PsiElement?): ThreeState =
if (element is TomlKeySegment) ThreeState.YES else ThreeState.NO
override fun isPropertyWithValue(element: PsiElement): Boolean =
element is TomlKeyValue && element.value != null
override fun findElementToCheck(element: PsiElement): PsiElement? =
element.parentOfType<TomlElement>()
override fun findPosition(element: PsiElement, forceLastTransition: Boolean): JsonPointerPosition {
val position = JsonPointerPosition()
var current = element
val tableHeaderSegments = mutableListOf<String?>()
var nestedIndex: Int? = null
while (current !is PsiFile) {
val parent = current.parent
when {
current is TomlKeySegment && parent is TomlKey -> {
// forceLastTransition as true is used in inspections, whether as false is used in completion
// to skip the last segment as it may not have been typed completely yet
if (current != element || forceLastTransition) {
position.addPrecedingStep(current.name)
}
for (segment in parent.segments.takeWhile { it != current }.asReversed()) {
position.addPrecedingStep(segment.name)
}
}
current is TomlKeyValue && parent is TomlHeaderOwner -> {
val parentKey = parent.header.key ?: break
// add table header segments to process all the previous siblings to handle nested array tables cases
parentKey.segments.mapTo(tableHeaderSegments) { it.name }
// TODO: Workaround, should be fixed in TOML grammar
// if it is a request from inspections, it walks only properties,
// so we don't have path calculation from key or value
if (element is TomlKeyValue) {
val currentKey = current.key
for (segment in currentKey.segments.asReversed()) {
if (segment != element || forceLastTransition) {
position.addPrecedingStep(segment.name)
}
}
}
}
current is TomlValue && parent is TomlArray -> {
if (current != element || forceLastTransition) {
position.addPrecedingStep(parent.elements.indexOf(current))
}
}
current is TomlValue && parent is TomlKeyValue -> {
val parentKey = parent.key
for (segment in parentKey.segments.asReversed()) {
if (segment != element || forceLastTransition) {
position.addPrecedingStep(segment.name)
}
}
}
current is TomlHeaderOwner && parent is PsiFile -> {
val currentSegments = current.header.key?.segments?.map { it.name }.orEmpty()
// lower keys size until it is equals current header key size
while (tableHeaderSegments.size > currentSegments.size && ContainerUtil.startsWith(tableHeaderSegments, currentSegments)) {
// add index if it is present (meaning that the current segment is array one)
if (nestedIndex != null) {
position.addPrecedingStep(nestedIndex)
nestedIndex = null
}
position.addPrecedingStep(tableHeaderSegments.removeLast())
}
// increment array table index if keys are equal
if (currentSegments == tableHeaderSegments && current is TomlArrayTable) {
if (nestedIndex != null) {
nestedIndex += 1
} else {
nestedIndex = 0
}
}
}
}
// take previous sibling if it is the top-level item, otherwise use parent
if (current is TomlHeaderOwner && parent is PsiFile && current.prevSibling != null) {
// skip everything else than TomlHeaderOwner
do {
current = current.prevSibling
} while (current !is TomlHeaderOwner && current.prevSibling != null)
} else {
current = current.parent
}
}
// process the left segments after last top-element which was equal with them
while (tableHeaderSegments.isNotEmpty()) {
if (nestedIndex != null) {
position.addPrecedingStep(nestedIndex)
nestedIndex = null
}
position.addPrecedingStep(tableHeaderSegments.removeLast())
}
return position
}
override fun getPropertyNamesOfParentObject(originalPosition: PsiElement, computedPosition: PsiElement?): Set<String> {
val table = originalPosition.parentOfType<TomlTable>()
?: originalPosition.parentOfType<TomlInlineTable>()
?: originalPosition.prevSibling as? TomlTable
?: return emptySet()
return TomlJsonObjectAdapter(table).propertyList.mapNotNullTo(HashSet()) { it.name }
}
override fun getParentPropertyAdapter(element: PsiElement): JsonPropertyAdapter? {
val property = element.parentOfType<TomlKeyValue>(true) ?: return null
return TomlJsonPropertyAdapter(property)
}
override fun isTopJsonElement(element: PsiElement): Boolean = element is TomlFile
override fun createValueAdapter(element: PsiElement): JsonValueAdapter? =
if (element is TomlElement) TomlJsonValueAdapter.createAdapterByType(element) else null
override fun getRoots(file: PsiFile): List<PsiElement> {
if (file !is TomlFile) return emptyList()
return file.children.toList()
}
override fun getPropertyNameElement(property: PsiElement?): PsiElement? = (property as? TomlKeyValue)?.key
override fun hasMissingCommaAfter(element: PsiElement): Boolean = false
override fun acceptsEmptyRoot(): Boolean = true
override fun requiresNameQuotes(): Boolean = false
override fun allowsSingleQuotes(): Boolean = false
} | apache-2.0 | 6fb7ce3d4643e2e6e8a1188981c8806e | 44.13125 | 143 | 0.593213 | 5.553846 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/breakpointTypeUtils.kt | 1 | 7517 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.breakpoints
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.ui.breakpoints.JavaLineBreakpointType
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xdebugger.XDebuggerUtil
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.impl.XSourcePositionImpl
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.core.util.getLineNumber
import org.jetbrains.kotlin.idea.debugger.findElementAtLine
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.inline.INLINE_ONLY_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
import java.util.*
interface KotlinBreakpointType
class ApplicabilityResult(val isApplicable: Boolean, val shouldStop: Boolean) {
companion object {
@JvmStatic
fun definitely(result: Boolean) = ApplicabilityResult(result, shouldStop = true)
@JvmStatic
fun maybe(result: Boolean) = ApplicabilityResult(result, shouldStop = false)
@JvmField
val UNKNOWN = ApplicabilityResult(isApplicable = false, shouldStop = false)
@JvmField
val DEFINITELY_YES = ApplicabilityResult(isApplicable = true, shouldStop = true)
@JvmField
val DEFINITELY_NO = ApplicabilityResult(isApplicable = false, shouldStop = true)
@JvmField
val MAYBE_YES = ApplicabilityResult(isApplicable = true, shouldStop = false)
}
}
fun isBreakpointApplicable(file: VirtualFile, line: Int, project: Project, checker: (PsiElement) -> ApplicabilityResult): Boolean {
val psiFile = PsiManager.getInstance(project).findFile(file)
if (psiFile == null || psiFile.virtualFile?.fileType != KotlinFileType.INSTANCE) {
return false
}
val document = FileDocumentManager.getInstance().getDocument(file) ?: return false
return runReadAction {
var isApplicable = false
val checked = HashSet<PsiElement>()
XDebuggerUtil.getInstance().iterateLine(
project, document, line,
fun(element: PsiElement): Boolean {
if (element is PsiWhiteSpace || element.getParentOfType<PsiComment>(false) != null || !element.isValid) {
return true
}
val parent = getTopmostParentOnLineOrSelf(element, document, line)
if (!checked.add(parent)) {
return true
}
val result = checker(parent)
if (result.shouldStop && !result.isApplicable) {
isApplicable = false
return false
}
isApplicable = isApplicable or result.isApplicable
return !result.shouldStop
},
)
return@runReadAction isApplicable
}
}
private fun getTopmostParentOnLineOrSelf(element: PsiElement, document: Document, line: Int): PsiElement {
var current = element
var parent = current.parent
while (parent != null && parent !is PsiFile) {
val offset = parent.textOffset
if (offset > document.textLength) break
if (offset >= 0 && document.getLineNumber(offset) != line) break
current = parent
parent = current.parent
}
return current
}
fun computeLineBreakpointVariants(
project: Project,
position: XSourcePosition,
kotlinBreakpointType: KotlinLineBreakpointType,
): List<JavaLineBreakpointType.JavaBreakpointVariant> {
val file = PsiManager.getInstance(project).findFile(position.file) as? KtFile ?: return emptyList()
val pos = SourcePosition.createFromLine(file, position.line)
val lambdas = getLambdasAtLineIfAny(pos)
if (lambdas.isEmpty()) return emptyList()
val result = LinkedList<JavaLineBreakpointType.JavaBreakpointVariant>()
val elementAt = pos.elementAt.parentsWithSelf.firstIsInstance<KtElement>()
val mainMethod = PsiTreeUtil.getParentOfType(elementAt, KtFunction::class.java, false)
var mainMethodAdded = false
if (mainMethod != null) {
val bodyExpression = mainMethod.bodyExpression
val isLambdaResult = bodyExpression is KtLambdaExpression && bodyExpression.functionLiteral in lambdas
if (!isLambdaResult) {
val variantElement = CodeInsightUtils.getTopmostElementAtOffset(elementAt, pos.offset)
result.add(kotlinBreakpointType.LineKotlinBreakpointVariant(position, variantElement, -1))
mainMethodAdded = true
}
}
lambdas.forEachIndexed { ordinal, lambda ->
val positionImpl = XSourcePositionImpl.createByElement(lambda.bodyExpression)
if (positionImpl != null) {
result.add(kotlinBreakpointType.LambdaJavaBreakpointVariant(positionImpl, lambda, ordinal))
}
}
if (mainMethodAdded && result.size > 1) {
result.add(kotlinBreakpointType.KotlinBreakpointVariant(position, lambdas.size))
}
return result
}
fun getLambdasAtLineIfAny(sourcePosition: SourcePosition): List<KtFunction> {
val file = sourcePosition.file as? KtFile ?: return emptyList()
val lineNumber = sourcePosition.line
return getLambdasAtLineIfAny(file, lineNumber)
}
fun getLambdasAtLineIfAny(file: KtFile, line: Int): List<KtFunction> {
val lineElement = findElementAtLine(file, line) as? KtElement ?: return emptyList()
val start = lineElement.startOffset
val end = lineElement.endOffset
val allLiterals = CodeInsightUtils.findElementsOfClassInRange(file, start, end, KtFunction::class.java)
.filterIsInstance<KtFunction>()
// filter function literals and functional expressions
.filter { it is KtFunctionLiteral || it.name == null }
.toSet()
return allLiterals.filter {
val statement = it.bodyBlockExpression?.statements?.firstOrNull() ?: it
statement.getLineNumber() == line && statement.getLineNumber(false) == line
}
}
internal fun KtCallableDeclaration.isInlineOnly(): Boolean {
if (!hasModifier(KtTokens.INLINE_KEYWORD)) {
return false
}
val inlineOnlyAnnotation = annotationEntries
.firstOrNull { it.shortName == INLINE_ONLY_ANNOTATION_FQ_NAME.shortName() }
?: return false
return runReadAction f@{
val bindingContext = inlineOnlyAnnotation.analyze(BodyResolveMode.PARTIAL)
val annotationDescriptor = bindingContext[BindingContext.ANNOTATION, inlineOnlyAnnotation] ?: return@f false
return@f annotationDescriptor.fqName == INLINE_ONLY_ANNOTATION_FQ_NAME
}
}
| apache-2.0 | 4b958e5abe44a75ea3176f95c36a0c0e | 37.352041 | 158 | 0.718106 | 4.964993 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/util/ContextExtensions.kt | 2 | 1984 | package eu.kanade.tachiyomi.util
import android.app.AlarmManager
import android.app.Notification
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.support.annotation.StringRes
import android.support.v4.app.NotificationCompat
import android.support.v4.content.ContextCompat
import android.widget.Toast
/**
* Display a toast in this context.
* @param resource the text resource.
* @param duration the duration of the toast. Defaults to short.
*/
fun Context.toast(@StringRes resource: Int, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, resource, duration).show()
}
/**
* Display a toast in this context.
* @param text the text to display.
* @param duration the duration of the toast. Defaults to short.
*/
fun Context.toast(text: String?, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, text, duration).show()
}
/**
* Helper method to create a notification.
* @param func the function that will execute inside the builder.
* @return a notification to be displayed or updated.
*/
inline fun Context.notification(func: NotificationCompat.Builder.() -> Unit): Notification {
val builder = NotificationCompat.Builder(this)
builder.func()
return builder.build()
}
/**
* Checks if the give permission is granted.
* @param permission the permission to check.
* @return true if it has permissions.
*/
fun Context.hasPermission(permission: String)
= ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
/**
* Property to get the notification manager from the context.
*/
val Context.notificationManager: NotificationManager
get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
/**
* Property to get the alarm manager from the context.
* @return the alarm manager.
*/
val Context.alarmManager: AlarmManager
get() = getSystemService(Context.ALARM_SERVICE) as AlarmManager
| gpl-3.0 | c29c84057982804d61b572d3d4dfee36 | 31.52459 | 98 | 0.760081 | 4.285097 | false | false | false | false |
GunoH/intellij-community | xml/xml-psi-impl/src/com/intellij/lexer/HtmlDefaultEmbeddedContentSupport.kt | 7 | 3535 | // 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.lexer
import com.intellij.html.embedding.HtmlEmbeddedContentProvider
import com.intellij.html.embedding.HtmlEmbeddedContentSupport
import com.intellij.html.embedding.HtmlEmbedmentInfo
import com.intellij.html.embedding.HtmlTagEmbeddedContentProvider
import com.intellij.lang.Language
import com.intellij.lang.html.HTMLLanguage
import com.intellij.openapi.util.text.StringUtil
import com.intellij.xml.util.HtmlUtil
class HtmlDefaultEmbeddedContentSupport : HtmlEmbeddedContentSupport {
override fun createEmbeddedContentProviders(lexer: BaseHtmlLexer): List<HtmlEmbeddedContentProvider> =
listOf(HtmlRawTextTagContentProvider(lexer), HtmlScriptStyleEmbeddedContentProvider(lexer))
}
class HtmlRawTextTagContentProvider(lexer: BaseHtmlLexer) : HtmlTagEmbeddedContentProvider(lexer) {
override fun isInterestedInTag(tagName: CharSequence): Boolean =
namesEqual(tagName, HtmlUtil.TITLE_TAG_NAME)
|| namesEqual(tagName, HtmlUtil.TEXTAREA_TAG_NAME)
override fun isInterestedInAttribute(attributeName: CharSequence): Boolean = false
override fun createEmbedmentInfo(): HtmlEmbedmentInfo = HtmlEmbeddedContentProvider.RAW_TEXT_FORMATTABLE_EMBEDMENT
}
open class HtmlScriptStyleEmbeddedContentProvider(lexer: BaseHtmlLexer) : HtmlTagEmbeddedContentProvider(lexer) {
private val infoCache = HashMap<Pair<String, String?>, HtmlEmbedmentInfo?>()
override fun isInterestedInTag(tagName: CharSequence): Boolean =
namesEqual(tagName, HtmlUtil.SCRIPT_TAG_NAME)
|| namesEqual(tagName, HtmlUtil.STYLE_TAG_NAME)
override fun isInterestedInAttribute(attributeName: CharSequence): Boolean =
(namesEqual(attributeName, HtmlUtil.TYPE_ATTRIBUTE_NAME)
|| (namesEqual(attributeName, HtmlUtil.LANGUAGE_ATTRIBUTE_NAME) && namesEqual(tagName, HtmlUtil.SCRIPT_TAG_NAME)))
override fun createEmbedmentInfo(): HtmlEmbedmentInfo? {
val attributeValue = attributeValue?.trim()?.toString()
return infoCache.getOrPut(Pair(tagName!!.toString(), attributeValue)) {
when {
namesEqual(tagName, HtmlUtil.STYLE_TAG_NAME) -> styleLanguage(attributeValue)?.let {
HtmlEmbeddedContentSupport.getStyleTagEmbedmentInfo(it)
}
namesEqual(tagName, HtmlUtil.SCRIPT_TAG_NAME) -> scriptEmbedmentInfo(attributeValue)
else -> null
} ?: HtmlEmbeddedContentProvider.RAW_TEXT_EMBEDMENT
}
}
protected open fun styleLanguage(styleLang: String?): Language? {
val cssLanguage = Language.findLanguageByID("CSS")
if (styleLang != null && !styleLang.equals("text/css", ignoreCase = true)) {
cssLanguage
?.dialects
?.firstOrNull { dialect ->
dialect.mimeTypes.any { it.equals(styleLang, ignoreCase = true) }
}
?.let { return it }
}
return cssLanguage
}
protected open fun scriptEmbedmentInfo(mimeType: String?): HtmlEmbedmentInfo? =
if (mimeType != null)
Language.findInstancesByMimeType(if (lexer.isCaseInsensitive) StringUtil.toLowerCase(mimeType) else mimeType)
.asSequence()
.plus(if (StringUtil.containsIgnoreCase(mimeType, "template")) listOf(HTMLLanguage.INSTANCE) else emptyList())
.map { HtmlEmbeddedContentSupport.getScriptTagEmbedmentInfo(it) }
.firstOrNull { it != null }
else
Language.findLanguageByID("JavaScript")?.let {
HtmlEmbeddedContentSupport.getScriptTagEmbedmentInfo(it)
}
} | apache-2.0 | 32170466d85a4b27ce0fb73bcc80a935 | 43.2 | 120 | 0.760113 | 4.396766 | false | false | false | false |
hsrzq/droidBDF | chaotic/src/main/java/top/techqi/chaotic/util/LogU.kt | 1 | 1604 | package top.techqi.chaotic.util
import android.util.Log
import top.techqi.chaotic.BuildConfig
/**
* 控制台Log封装
*/
@Suppress("unused", "MemberVisibilityCanBePrivate")
object LogU {
val TAG = PluginApp.NAME
var DEBUG = BuildConfig.DEBUG
fun vv(tag: String?, msg: String?, tr: Throwable? = null) {
if (DEBUG) Log.v(tag ?: TAG, "$msg", tr)
}
fun dd(tag: String?, msg: String?, tr: Throwable? = null) {
if (DEBUG) Log.d(tag ?: TAG, "$msg", tr)
}
fun ii(tag: String?, msg: String?, tr: Throwable? = null) {
if (DEBUG) Log.i(tag ?: TAG, "$msg", tr)
}
fun ww(tag: String?, msg: String?, tr: Throwable? = null) {
if (DEBUG) Log.w(tag ?: TAG, "$msg", tr)
}
fun ee(tag: String?, msg: String?, tr: Throwable? = null) {
if (DEBUG) Log.e(tag ?: TAG, "$msg", tr)
}
fun v(tag: String?, tr: Throwable?) = vv(tag, "", tr)
fun d(tag: String?, tr: Throwable?) = dd(tag, "", tr)
fun i(tag: String?, tr: Throwable?) = ii(tag, "", tr)
fun w(tag: String?, tr: Throwable?) = ww(tag, "", tr)
fun e(tag: String?, tr: Throwable?) = ee(tag, "", tr)
fun v(tag: String?, format: String, vararg args: Any?) = vv(tag, format.format(*args))
fun d(tag: String?, format: String, vararg args: Any?) = dd(tag, format.format(*args))
fun i(tag: String?, format: String, vararg args: Any?) = ii(tag, format.format(*args))
fun w(tag: String?, format: String, vararg args: Any?) = ww(tag, format.format(*args))
fun e(tag: String?, format: String, vararg args: Any?) = ee(tag, format.format(*args))
}
| mit | abd1c587916b35a8a3a03aba7b0149f7 | 34.422222 | 90 | 0.58532 | 3.07722 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/evaluator.kt | 6 | 2762 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror
import com.sun.jdi.*
import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext
import java.lang.IllegalArgumentException
sealed class MethodEvaluator<T>(val method: Method?) {
fun value(value: ObjectReference?, context: DefaultExecutionContext, vararg values: Value): T? {
return method?.let {
return when {
method.isStatic -> {
// pass extension methods like the usual ones.
val args = if (value != null) {
listOf(value) + values.toList()
} else
values.toList()
@Suppress("UNCHECKED_CAST")
context.invokeMethod(method.declaringType() as ClassType, method, args) as T?
}
value != null ->
@Suppress("UNCHECKED_CAST")
context.invokeMethod(value, method, values.toList()) as T?
else -> throw IllegalArgumentException("Exception while calling method " + method.signature() + " with an empty value.")
}
}
}
class DefaultMethodEvaluator<T>(method: Method?) : MethodEvaluator<T>(method)
class MirrorMethodEvaluator<T, F>(method: Method?, private val mirrorProvider: MirrorProvider<T, F>): MethodEvaluator<T>(method) {
fun mirror(ref: ObjectReference, context: DefaultExecutionContext, vararg values: Value): F? {
return mirrorProvider.mirror(value(ref, context, *values), context)
}
fun isCompatible(value: T) = mirrorProvider.isCompatible(value)
}
}
sealed class FieldEvaluator<T>(val field: Field?, val thisRef: ReferenceTypeProvider) {
@Suppress("UNCHECKED_CAST")
fun value(value: ObjectReference): T? =
field?.let { value.getValue(it) as T? }
@Suppress("UNCHECKED_CAST")
fun staticValue(): T? = thisRef.getCls().let { it.getValue(field) as? T }
class DefaultFieldEvaluator<T>(field: Field?, thisRef: ReferenceTypeProvider) : FieldEvaluator<T>(field, thisRef)
class MirrorFieldEvaluator<T, F>(field: Field?, thisRef: ReferenceTypeProvider, private val mirrorProvider: MirrorProvider<T, F>) : FieldEvaluator<T>(field, thisRef) {
fun mirror(ref: ObjectReference, context: DefaultExecutionContext): F? =
mirrorProvider.mirror(value(ref), context)
fun mirrorOnly(value: T, context: DefaultExecutionContext) = mirrorProvider.mirror(value, context)
fun isCompatible(value: T) = mirrorProvider.isCompatible(value)
}
}
| apache-2.0 | f861e8c05896933dd8bed84d907ea88f | 46.62069 | 171 | 0.655322 | 4.542763 | false | false | false | false |
smmribeiro/intellij-community | java/java-tests/testSrc/com/intellij/java/formatting/commandLine/FileSetFormatterStarterTest.kt | 4 | 3414 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.formatting.commandLine
import com.intellij.formatting.commandLine.CodeStyleProcessorBuildException.ArgumentsException
import com.intellij.formatting.commandLine.CodeStyleProcessorBuildException.ShowUsageException
import com.intellij.formatting.commandLine.FileSetFormatValidator
import com.intellij.formatting.commandLine.FileSetFormatter
import com.intellij.formatting.commandLine.createFormatter
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.testFramework.LightPlatformTestCase
import java.io.File
class FileSetFormatterStarterTest : LightPlatformTestCase() {
private inline fun <reified T : Exception> expectExceptionsOnArgs(vararg args: String) {
try {
createFormatter(args.toList().toTypedArray()).use {
fail("Missing expected exception ${T::class}")
}
}
catch (e: Exception) {
assertInstanceOf(e, T::class.java)
}
}
fun testHelp_noArgs0() = expectExceptionsOnArgs<ShowUsageException>()
fun testHelp_noArgs1() = expectExceptionsOnArgs<ShowUsageException>("format")
fun testHelp_explicit_only() = expectExceptionsOnArgs<ShowUsageException>("format", "-help")
fun testHelp_explicit_withOthers() = expectExceptionsOnArgs<ShowUsageException>("format", "-r", "src", "-h")
fun testUnknownArgumentFails() = expectExceptionsOnArgs<ArgumentsException>("format", "-r", "src", "-unknown_arg")
fun testMissingParamForMasks() = expectExceptionsOnArgs<ArgumentsException>("format", "-r", "src", "-m")
fun testMissingParamForSettings() = expectExceptionsOnArgs<ArgumentsException>("format", "-r", "src", "-s")
fun testMissingSettingsFile() = expectExceptionsOnArgs<ArgumentsException>("format", "-s",
"really_hope_noone_adds_file_with_this_name_in_future", "src")
fun testDefaultArgs() {
createFormatter(arrayOf("format", ".")).use { processor ->
assertInstanceOf(processor, FileSetFormatter::class.java)
assertFalse(processor.isRecursive)
assertEmpty(processor.getFileMasks())
assertNull(processor.defaultCodeStyle)
assertEquals(1, processor.getEntries().size)
assertEquals(File(".").absolutePath, processor.getEntries()[0].absolutePath)
}
}
fun testNonDefaultArgs() {
createFormatter(arrayOf("format", "-r", "-d", "-m", "*.java, ,*.kt,", ".", "..")).use { processor ->
assertInstanceOf(processor, FileSetFormatValidator::class.java)
assertTrue(processor.isRecursive)
assertEquals(2, processor.getFileMasks().size)
assertEquals(".*\\.java", processor.getFileMasks()[0].pattern)
assertEquals(".*\\.kt", processor.getFileMasks()[1].pattern)
assertEquals(2, processor.getEntries().size)
assertEquals(File(".").absolutePath, processor.getEntries()[0].absolutePath)
assertEquals(File("..").absolutePath, processor.getEntries()[1].absolutePath)
}
}
fun testNonDefaultArgs2() {
createFormatter(arrayOf("format", "-d", "-allowDefaults", ".")).use { processor ->
assertInstanceOf(processor, FileSetFormatValidator::class.java)
assertEquals(CodeStyleSettingsManager.getInstance().createSettings(), processor.defaultCodeStyle)
}
}
}
| apache-2.0 | 24f1f7d2771fa2262cd2ffaedba667fa | 47.084507 | 158 | 0.723492 | 4.576408 | false | true | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/manager/permission/PermissionManagerImpl.kt | 1 | 3196 | package sk.styk.martin.apkanalyzer.manager.permission
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import java.lang.ref.WeakReference
import javax.inject.Inject
private const val PERMISSIONS_REQUEST_CODE = 777
class PermissionsManagerImpl @Inject constructor(application: Application) : AndroidViewModel(application), PermissionManager {
private var activityWeakReference: WeakReference<Activity>? = null
private val activity: Activity?
get() = activityWeakReference?.get()
@Volatile
private var permissionsCallback: PermissionManager.PermissionsCallback? = null
override fun hasPermissionGranted(permission: String): Boolean {
return ContextCompat.checkSelfPermission(getApplication(), permission) == PackageManager.PERMISSION_GRANTED
}
override fun shouldShowRationaleForPermission(permission: String): Boolean {
val activity = activity
return activity != null && ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
}
override fun requestPermission(permission: String, callback: PermissionManager.PermissionCallback) {
requestPermissions(arrayOf(permission), object : PermissionManager.PermissionsCallback {
override fun onPermissionsDenied(deniedPermissions: List<String>) {
callback.onPermissionDenied(deniedPermissions[0])
}
override fun onPermissionsGranted(grantedPermissions: List<String>) {
callback.onPermissionGranted(grantedPermissions[0])
}
})
}
@Synchronized
override fun requestPermissions(permissions: Array<String>, callback: PermissionManager.PermissionsCallback) {
val activity = activity
if (activity != null) {
permissionsCallback = callback
ActivityCompat.requestPermissions(activity, permissions, PERMISSIONS_REQUEST_CODE)
}
}
@Synchronized
override fun onRequestPermissionsResult(permissions: Array<String>, grantResults: IntArray) {
val granted: MutableList<String> = ArrayList()
val denied: MutableList<String> = ArrayList()
for (i in permissions.indices) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
granted.add(permissions[i])
} else {
denied.add(permissions[i])
}
}
if (granted.isNotEmpty()) {
permissionsCallback?.onPermissionsGranted(granted)
}
if (denied.isNotEmpty()) {
permissionsCallback?.onPermissionsDenied(denied)
}
permissionsCallback = null
}
fun bind(activity: AppCompatActivity) {
activityWeakReference = WeakReference(activity)
}
}
fun hasScopedStorage() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q | gpl-3.0 | cfa103344d7dc6a0ef1d1b62de885096 | 37.059524 | 127 | 0.717772 | 5.491409 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/variables/types/TimeType.kt | 1 | 3383 | package ch.rmy.android.http_shortcuts.variables.types
import android.app.TimePickerDialog
import android.content.Context
import android.text.format.DateFormat
import ch.rmy.android.framework.extensions.showOrElse
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableRepository
import ch.rmy.android.http_shortcuts.data.models.VariableModel
import ch.rmy.android.http_shortcuts.utils.ActivityProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import javax.inject.Inject
import kotlin.coroutines.resume
class TimeType : BaseVariableType() {
@Inject
lateinit var variablesRepository: VariableRepository
@Inject
lateinit var activityProvider: ActivityProvider
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override suspend fun resolveValue(context: Context, variable: VariableModel): String {
val selectedDate = withContext(Dispatchers.Main) {
suspendCancellableCoroutine<Date> { continuation ->
val calendar = getInitialTime(variable.value)
val timePicker = TimePickerDialog(
activityProvider.getActivity(),
{ _, hourOfDay, minute ->
val newDate = Calendar.getInstance()
newDate.set(Calendar.HOUR_OF_DAY, hourOfDay)
newDate.set(Calendar.MINUTE, minute)
continuation.resume(newDate.time)
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
DateFormat.is24HourFormat(context),
)
if (variable.title.isNotEmpty()) {
timePicker.setTitle(variable.title)
}
timePicker.setCancelable(true)
timePicker.setCanceledOnTouchOutside(true)
timePicker.showOrElse {
continuation.cancel()
}
timePicker.setOnDismissListener {
continuation.cancel()
}
}
}
if (variable.rememberValue) {
variablesRepository.setVariableValue(variable.id, DATE_FORMAT.format(selectedDate.time))
}
return SimpleDateFormat(getTimeFormat(variable), Locale.US)
.format(selectedDate.time)
}
private fun getInitialTime(previousValue: String?) =
Calendar.getInstance()
.also {
if (previousValue != null) {
try {
it.time = DATE_FORMAT.parse(previousValue)!!
} catch (e: ParseException) {
}
}
}
companion object {
const val KEY_FORMAT = "format"
private const val DEFAULT_FORMAT = "HH:mm"
private val DATE_FORMAT = SimpleDateFormat("HH-mm", Locale.US)
fun getTimeFormat(variable: VariableModel) =
variable.dataForType[DateType.KEY_FORMAT] ?: DEFAULT_FORMAT
}
}
| mit | 46299d3beff141125dc3bff7aca67d42 | 35.771739 | 100 | 0.627254 | 5.352848 | false | false | false | false |
intrigus/jtransc | jtransc-utils/test/collectionutilstest.kt | 2 | 1600 | /*
* Copyright 2016 Carlos Ballesteros Velasco
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.jtransc.ds.flatMapInChunks
import com.jtransc.ds.split
import org.junit.Assert
import org.junit.Test
class CollectionUtilsTest {
@Test fun test() {
var log = listOf<String>()
listOf(1, 2, 3).flatMapInChunks(2) {
log += "CHUNK($it)"
it
}
Assert.assertEquals("[CHUNK([1, 2]), CHUNK([2, 3])]", log.toString())
}
@Test fun test2() {
var log = listOf<String>()
listOf(1, 2).flatMapInChunks(2) {
log += "CHUNK($it)"
it
}
Assert.assertEquals("[CHUNK([1, 2])]", log.toString())
}
@Test fun test3() {
var log = listOf<String>()
listOf(1, 2, 3, 4, 5).flatMapInChunks(2) {
log += "CHUNK($it)"
it.map { -it }
}
Assert.assertEquals("[CHUNK([1, 2]), CHUNK([-2, 3]), CHUNK([-3, 4]), CHUNK([-4, 5])]", log.toString())
}
@Test fun split() {
val parts = listOf("a", ":", "b", "c", ":", "d").split(":")
Assert.assertEquals(listOf(listOf("a"), listOf("b", "c"), listOf("d")), parts)
}
} | apache-2.0 | a98d9d96bb0e4c88d4384d4477b7a587 | 27.666667 | 104 | 0.624375 | 3.125 | false | true | false | false |
samthor/intellij-community | platform/script-debugger/protocol/protocol-reader/src/LazyCachedMethodHandler.kt | 36 | 1754 | package org.jetbrains.protocolReader
import java.lang.reflect.Method
/**
* Basic implementation of the method that parses value on demand and store it for a future use
*/
class LazyCachedMethodHandler(private val parser: ValueReader, private val fieldBinding: VolatileFieldBinding) : MethodHandler {
protected fun writeReturnTypeJava(scope: ClassScope, m: Method, out: TextOutput) {
val objectValueParser = parser.asJsonTypeParser()
if (objectValueParser == null) {
writeJavaTypeName(m.getGenericReturnType(), out)
}
else {
out.append(scope.getTypeImplReference(objectValueParser.type.type!!))
}
}
override fun writeMethodImplementationJava(scope: ClassScope, method: Method, out: TextOutput) {
out.append("@Override").newLine().append("public ")
writeReturnTypeJava(scope, method, out)
out.append(' ')
appendMethodSignatureJava(method, listOf<String>(), out)
out.openBlock()
out.append("if (")
fieldBinding.writeGetExpression(out)
out.append(" == null)").openBlock()
run {
if (parser.isThrowsIOException()) {
out.append("try").openBlock()
}
run {
fieldBinding.writeGetExpression(out)
out.append(" = ")
parser.writeReadCode(scope, true, scope.output)
out.semi()
}
if (parser.isThrowsIOException()) {
out.closeBlock()
out.newLine().append("catch (IOException e)").openBlock()
out.append("throw new com.google.gson.JsonParseException(e);").closeBlock()
}
out.newLine().append(PENDING_INPUT_READER_NAME).append(" = null;")
}
out.closeBlock()
out.newLine().append("return ")
fieldBinding.writeGetExpression(out)
out.semi()
out.closeBlock()
}
}
| apache-2.0 | b3dc6d34f7fb1855644218488051d433 | 31.481481 | 128 | 0.673888 | 4.257282 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/PrepareItemCraftListener.kt | 1 | 3714 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.professions.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.bukkit.util.addLore
import com.rpkit.itemquality.bukkit.itemquality.RPKItemQuality
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import com.rpkit.professions.bukkit.profession.RPKCraftingAction
import com.rpkit.professions.bukkit.profession.RPKProfessionProvider
import org.bukkit.GameMode
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.PrepareItemCraftEvent
import kotlin.math.ceil
import kotlin.math.roundToInt
class PrepareItemCraftListener(private val plugin: RPKProfessionsBukkit): Listener {
@EventHandler
fun onPrepareItemCraft(event: PrepareItemCraftEvent) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val professionProvider = plugin.core.serviceManager.getServiceProvider(RPKProfessionProvider::class)
val bukkitPlayer = event.viewers.firstOrNull() as? Player
if (bukkitPlayer == null) {
event.inventory.result = null
return
}
if (bukkitPlayer.gameMode == GameMode.CREATIVE || bukkitPlayer.gameMode == GameMode.SPECTATOR) return
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer)
if (minecraftProfile == null) {
event.inventory.result = null
return
}
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character == null) {
event.inventory.result = null
return
}
val material = event.inventory.result?.type
if (material == null) {
event.inventory.result = null
return
}
val professions = professionProvider.getProfessions(character)
val professionLevels = professions
.associateWith { profession -> professionProvider.getProfessionLevel(character, profession) }
val amount = professionLevels.entries
.map { (profession, level) -> profession.getAmountFor(RPKCraftingAction.CRAFT, material, level) }
.max() ?: plugin.config.getDouble("default.crafting.$material.amount", 1.0)
val potentialQualities = professionLevels.entries
.mapNotNull { (profession, level) -> profession.getQualityFor(RPKCraftingAction.CRAFT, material, level) }
val quality = potentialQualities.maxBy(RPKItemQuality::durabilityModifier)
val item = event.inventory.result ?: return
if (quality != null) {
item.addLore(quality.lore)
}
if (amount > 1) {
item.amount = amount.roundToInt()
} else if (amount < 1) {
item.amount = ceil(amount).toInt()
}
event.inventory.result = item
}
} | apache-2.0 | 26a0171520a460f2376bbbc1335dbd5b | 43.22619 | 121 | 0.71217 | 4.919205 | false | false | false | false |
line/armeria | it/spring/boot2-kotlin/src/test/kotlin/com/linecorp/armeria/spring/kotlin/AbnormalController.kt | 4 | 1458 | /*
* Copyright 2021 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* 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.linecorp.armeria.spring.kotlin
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ResponseBody
/**
* This controller returns a JSON with an incorrect content type header.
*/
@Controller
class AbnormalController(private val objectMapper: ObjectMapper) {
@GetMapping(value = ["/abnormal"], produces = ["text/plain;charset=utf-8"])
@ResponseBody
fun abnormal(): ResponseEntity<String> {
return ResponseEntity.ok()
.body(objectMapper.writeValueAsString(Abnormal(abnormal = true, dummyText = "output")))
}
}
data class Abnormal(val abnormal: Boolean, val dummyText: String)
| apache-2.0 | 55c3882855d86061f108936d25d163e6 | 37.368421 | 99 | 0.759945 | 4.326409 | false | false | false | false |
kpspemu/kpspemu | src/nativeCommonMain/kotlin/com/soywiz/kpspemu/native/MainNative.kt | 1 | 2939 | package com.soywiz.kpspemu.native
import com.soywiz.kpspemu.*
fun main(args: Array<String>) = Main.main(args)
/*
fun main(args: Array<String>) {
Korio {
val time = measureTime {
var pspautotests: VfsFile = localCurrentDirVfs
var rootTestResources: VfsFile = localCurrentDirVfs
for (rootPath in listOf(
".",
"..",
"../..",
"../../..",
"../../../..",
"../../../../..",
"../../../../../..",
"../../../../../../.."
)) {
//println("localCurrentDirVfs=$localCurrentDirVfs")
//println("localCurrentDirVfs[rootPath]=${localCurrentDirVfs[rootPath]}")
val root = localCurrentDirVfs[rootPath].jail()
pspautotests = root["pspautotests"]
rootTestResources = root["kpspemu/common/testresources"]
if (pspautotests.exists()) {
break
}
}
//val elf = localCurrentDirVfs["game.prx"].readAsSyncStream()
val elf = pspautotests["cpu/cpu_alu/cpu_alu.prx"].readAsSyncStream()
// Run test in release mode for benchmarking
val emulator = Emulator(kotlin.coroutines.experimental.coroutineContext)
emulator.interpreted = true
emulator.display.exposeDisplay = false
emulator.registerNativeModules()
//val info = emulator.loadElfAndSetRegisters(elf, "ms0:/PSP/GAME/EBOOT.PBP")
emulator.fileManager.currentDirectory = "ms0:/PSP/GAME/virtual"
emulator.fileManager.executableFile = "ms0:/PSP/GAME/virtual/EBOOT.PBP"
emulator.deviceManager.mount(
emulator.fileManager.currentDirectory,
MemoryVfsMix("EBOOT.PBP" to elf.clone().toAsync())
)
val info = emulator.loadElfAndSetRegisters(elf, listOf("ms0:/PSP/GAME/virtual/EBOOT.PBP"))
var generatedError: Throwable? = null
try {
//println("[1]")
while (emulator.running) {
//println("[2] : ${emulator.running}")
emulator.threadManager.step() // UPDATE THIS
getCoroutineContext().eventLoop.step(10)
//println("[3]")
}
} catch (e: Throwable) {
Console.error("Partial output generated:")
Console.error("'" + emulator.output.toString() + "'")
//throw e
e.printStackTrace()
generatedError = e
}
println(emulator.output.toString())
//assertEquals(expected.normalize(), processor(emulator.output.toString().normalize()))
//generatedError?.let { throw it }
}
println("TIME: ${time.time}")
}
}
*/
| mit | 71ee8fda50d97295fb04cc47cc6c3d06 | 38.186667 | 102 | 0.515141 | 4.732689 | false | true | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/util/livedata/WrappedLiveData.kt | 2 | 1232 | package chat.rocket.android.util.livedata
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
class WrappedLiveData<Source, Output>(
private val runContext: CoroutineContext = Dispatchers.IO,
private val source: LiveData<Source>,
private val transformation: suspend (Source?, MutableLiveData<Output>) -> Unit
) : MutableLiveData<Output>() {
private var job: Job? = null
private val observer = Observer<Source> { source ->
job?.cancel()
job = GlobalScope.launch(runContext) {
transformation(source, this@WrappedLiveData)
}
}
override fun onActive() {
source.observeForever(observer)
}
override fun onInactive() {
job?.cancel()
source.removeObserver(observer)
}
}
fun <Source, Output> LiveData<Source>.wrap(
runContext: CoroutineContext = Dispatchers.IO,
transformation: suspend (Source?, MutableLiveData<Output>) -> Unit
) =
WrappedLiveData(runContext, this, transformation) | mit | c19e5740298ba0c2c47ff27a52d12228 | 29.825 | 82 | 0.729708 | 4.738462 | false | false | false | false |
xwiki-contrib/android-authenticator | app/src/main/java/org/xwiki/android/sync/contactdb/dao/AccountsDao.kt | 1 | 1030 | package org.xwiki.android.sync.contactdb.dao
import androidx.room.*
import org.xwiki.android.sync.contactdb.*
@Dao
interface AccountsDao {
@Query ("SELECT * from USER_TABLE")
fun getAllAccount() : List<UserAccount>
@Query ("SELECT * FROM USER_TABLE WHERE $UserAccountAccountNameColumn LIKE :name")
fun findByAccountName(name: String): UserAccount?
@Query ("SELECT * FROM USER_TABLE WHERE $UserAccountIdColumn=:id")
fun findById(id: UserAccountId): UserAccount?
@Insert (onConflict = OnConflictStrategy.REPLACE)
fun insertAccount(userAccount: UserAccount): UserAccountId
@Update (onConflict = OnConflictStrategy.REPLACE)
suspend fun updateUser(userAccount: UserAccount): Int
@Query ("DELETE FROM USER_TABLE WHERE $UserAccountIdColumn = :userAccountId")
fun deleteUser(userAccountId: UserAccountId)
@Query ("SELECT $UserAccountIdColumn FROM USER_TABLE WHERE $UserAccountServerAddressColumn = :serverUrl")
fun oneServerAccounts(serverUrl: String): List<UserAccountId>
} | lgpl-2.1 | 30ac41dddf541c7645f5c734fb2e9b75 | 35.821429 | 109 | 0.75534 | 4.618834 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/amazon/java/com/battlelancer/seriesguide/billing/amazon/AmazonBillingActivity.kt | 1 | 6071 | package com.battlelancer.seriesguide.billing.amazon
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.amazon.device.iap.PurchasingService
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.billing.amazon.AmazonIapManager.AmazonIapAvailabilityEvent
import com.battlelancer.seriesguide.billing.amazon.AmazonIapManager.AmazonIapMessageEvent
import com.battlelancer.seriesguide.billing.amazon.AmazonIapManager.AmazonIapProductEvent
import com.battlelancer.seriesguide.databinding.ActivityAmazonBillingBinding
import com.battlelancer.seriesguide.ui.BaseActivity
import com.battlelancer.seriesguide.util.Utils
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
/**
* Offers a single subscription and in-app purchase using the Amazon in-app purchasing library.
*
* To debug: install on device with Amazon App Store and download App Tester app, put
* `amazon.sdktester.json` onto `sdcard`.
* Run command `adb shell setprop debug.amazon.sandboxmode debug` and launch app tester, then app.
* Debug version of app works.
*
* To disable sandbox mode run `adb shell setprop debug.amazon.sandboxmode none`.
*
* 2022-05-19: subscription not recognized because sku in receipt is null, entitlement works.
* Confirmed that subscription works and is recognized with production version.
*
* https://developer.amazon.com/de/docs/in-app-purchasing/iap-app-tester-user-guide.html
*/
class AmazonBillingActivity : BaseActivity() {
private lateinit var binding: ActivityAmazonBillingBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAmazonBillingBinding.inflate(layoutInflater)
setContentView(binding.root)
setupActionBar()
setupViews()
AmazonHelper.create(this)
AmazonHelper.iapManager.register()
}
override fun setupActionBar() {
super.setupActionBar()
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_clear_24dp)
actionBar.setDisplayHomeAsUpEnabled(true)
}
}
private fun setupViews() {
binding.buttonAmazonBillingSubscribe.isEnabled = false
binding.buttonAmazonBillingSubscribe.setOnClickListener { v: View? -> subscribe() }
binding.buttonAmazonBillingGetPass.isEnabled = false
binding.buttonAmazonBillingGetPass.setOnClickListener { v: View? -> purchasePass() }
binding.textViewAmazonBillingMoreInfo.setOnClickListener { v: View ->
Utils.launchWebsite(
v.context,
getString(R.string.url_whypay)
)
}
binding.progressBarAmazonBilling.visibility = View.VISIBLE
}
override fun onStart() {
super.onStart()
// no need to get product data every time we were hidden, so do it in onStart
AmazonHelper.iapManager.requestProductData()
}
override fun onResume() {
super.onResume()
AmazonHelper.iapManager.activate()
AmazonHelper.iapManager.requestUserDataAndPurchaseUpdates()
}
override fun onPause() {
super.onPause()
AmazonHelper.iapManager.deactivate()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
super.onBackPressed()
return true
}
return false
}
private fun subscribe() {
val requestId = PurchasingService.purchase(
AmazonSku.SERIESGUIDE_SUB_YEARLY.sku
)
Timber.d("subscribe: requestId (%s)", requestId)
}
private fun purchasePass() {
val requestId = PurchasingService.purchase(
AmazonSku.SERIESGUIDE_PASS.sku
)
Timber.d("purchasePass: requestId (%s)", requestId)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(event: AmazonIapMessageEvent) {
Toast.makeText(this, event.messageResId, Toast.LENGTH_LONG).show()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(event: AmazonIapAvailabilityEvent) {
binding.progressBarAmazonBilling.visibility = View.GONE
// enable or disable purchase buttons based on what can be purchased
binding.buttonAmazonBillingSubscribe.isEnabled =
event.subscriptionAvailable && !event.userHasActivePurchase
binding.buttonAmazonBillingGetPass.isEnabled =
event.passAvailable && !event.userHasActivePurchase
// status text
if (!event.subscriptionAvailable && !event.passAvailable) {
// neither purchase available, probably not signed in
binding.textViewAmazonBillingExisting.setText(R.string.subscription_not_signed_in)
} else {
// subscription or pass available
// show message if either one is active
binding.textViewAmazonBillingExisting.text =
if (event.userHasActivePurchase) getString(R.string.upgrade_success) else null
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(event: AmazonIapProductEvent) {
val product = event.product
// display the actual price like "1.23 C"
var price = product.price
if (price == null) {
price = "--"
}
if (AmazonSku.SERIESGUIDE_SUB_YEARLY.sku == product.sku) {
val priceString = getString(R.string.billing_duration_format, price)
val trialInfo = getString(R.string.billing_sub_description)
val finalPriceString = "$priceString\n$trialInfo"
binding.textViewAmazonBillingSubPrice.text = finalPriceString
} else if (AmazonSku.SERIESGUIDE_PASS.sku == product.sku) {
binding.textViewAmazonBillingPricePass.text =
String.format("%s\n%s", price, getString(R.string.billing_price_pass))
}
}
} | apache-2.0 | 1153876a72ccc2d1a9388e0a93ed5d21 | 37.43038 | 98 | 0.695931 | 4.581887 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/ui/money/HistorySettlementTimeActivity.kt | 1 | 6988 | package com.fuyoul.sanwenseller.ui.money
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.csl.refresh.SmartRefreshLayout
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseActivity
import com.fuyoul.sanwenseller.base.BaseAdapter
import com.fuyoul.sanwenseller.base.BaseViewHolder
import com.fuyoul.sanwenseller.bean.AdapterMultiItem
import com.fuyoul.sanwenseller.bean.MultBaseBean
import com.fuyoul.sanwenseller.bean.reshttp.ResHistorySettlementTime
import com.fuyoul.sanwenseller.bean.reshttp.ResHttpResult
import com.fuyoul.sanwenseller.configs.Code
import com.fuyoul.sanwenseller.configs.TopBarOption
import com.fuyoul.sanwenseller.configs.UrlInfo
import com.fuyoul.sanwenseller.listener.HttpReqListener
import com.fuyoul.sanwenseller.structure.model.EmptyM
import com.fuyoul.sanwenseller.structure.presenter.EmptyP
import com.fuyoul.sanwenseller.structure.view.EmptyV
import com.fuyoul.sanwenseller.utils.NormalFunUtils
import com.lzy.okgo.OkGo
import kotlinx.android.synthetic.main.historysettlementtimeactivity.*
/**
* @author: chen
* @CreatDate: 2017\11\14 0014
* @Desc:提示结算的日期列表
*/
class HistorySettlementTimeActivity : BaseActivity<EmptyM, EmptyV, EmptyP>() {
private var adapter: ThisAdapter? = null
override fun setLayoutRes(): Int = R.layout.historysettlementtimeactivity
override fun initData(savedInstanceState: Bundle?) {
val manager = LinearLayoutManager(this)
manager.orientation = LinearLayoutManager.VERTICAL
adapter = ThisAdapter()
historySettlementTimeInfo.layoutManager = manager
historySettlementTimeInfo.adapter = adapter!!
OkGo.post<ResHttpResult>(UrlInfo.SETTLEMENTDATE).execute(object : HttpReqListener(this) {
override fun reqOk(result: ResHttpResult) {
val listData = ArrayList<ResHistorySettlementTime>()
val jsonArray = JSON.parseArray(result.data.toString(), ResHistorySettlementTime::class.java)
var indexYear = "0"
var indexMonth = "0"
for (index in 0 until jsonArray.size) {
val item = jsonArray[index]
var year = ""
var month = ""
if (item.ordersDate.length == 6) {
year = item.ordersDate.trim().substring(0, 4)
month = item.ordersDate.trim().substring(4, 6)
} else {
year = item.ordersDate.trim().substring(0, 4)
month = item.ordersDate.trim().substring(4, 5)
}
if (index == 0) {
indexYear = year
indexMonth = month
item.showType = Code.BOTHSHOW
listData.add(item)
} else {
if (TextUtils.equals(year, indexYear)) {
if (!TextUtils.equals(month, indexMonth)) {
item.showType = Code.SINGLEBOTTOM
indexMonth = month
listData.add(item)
}
} else {
item.showType = Code.BOTHSHOW
indexYear = year
indexMonth = month
listData.add(item)
}
}
item.year = year
item.month = month
}
when {
listData.isEmpty() -> {
adapter?.setEmptyView(R.layout.emptylayout)
}
listData.size == 1 -> {
listData[0].showType = Code.BOTHSHOW
adapter?.setData(true, listData)
}
else -> {
adapter?.setData(true, listData)
}
}
}
override fun withoutData(code: Int, msg: String) {
NormalFunUtils.showToast(this@HistorySettlementTimeActivity, msg)
}
override fun error(errorInfo: String) {
NormalFunUtils.showToast(this@HistorySettlementTimeActivity, errorInfo)
}
})
}
override fun setListener() {
}
override fun getPresenter(): EmptyP = EmptyP(initViewImpl())
override fun initViewImpl(): EmptyV = EmptyV()
override fun initTopBar(): TopBarOption {
val op = TopBarOption()
op.isShowBar = true
op.mainTitle = "历史结算"
return op
}
inner class ThisAdapter : BaseAdapter(this) {
override fun convert(holder: BaseViewHolder, position: Int, allDatas: List<MultBaseBean>) {
val item = allDatas[position] as ResHistorySettlementTime
val settlementOfYear = holder.itemView.findViewById<TextView>(R.id.settlementOfYear)
val settlementOfMonth = holder.itemView.findViewById<TextView>(R.id.settlementOfMonth)
when (item.showType) {
Code.BOTHSHOW -> {
settlementOfYear.visibility = View.VISIBLE
settlementOfMonth.visibility = View.VISIBLE
settlementOfYear.text = item.year
settlementOfMonth.text = item.month
}
Code.SINGLETOP -> {
settlementOfYear.visibility = View.VISIBLE
settlementOfMonth.visibility = View.GONE
settlementOfYear.text = item.year
}
Code.SINGLEBOTTOM -> {
settlementOfYear.visibility = View.GONE
settlementOfMonth.visibility = View.VISIBLE
settlementOfMonth.text = item.month
}
}
}
override fun addMultiType(multiItems: ArrayList<AdapterMultiItem>) {
multiItems.add(AdapterMultiItem(Code.VIEWTYPE_SETTLEMENT, R.layout.yearofsettlementlayout))
}
override fun onItemClicked(view: View, position: Int) {
val item = datas[position] as ResHistorySettlementTime
if (item.showType != Code.SINGLETOP) {
SettlementTypeActivity.start(this@HistorySettlementTimeActivity, true, item.year, item.month)
}
}
override fun onEmpryLayou(view: View, layoutResId: Int) {
}
override fun getSmartRefreshLayout(): SmartRefreshLayout = SmartRefreshLayout(this@HistorySettlementTimeActivity)
override fun getRecyclerView(): RecyclerView = historySettlementTimeInfo
}
} | apache-2.0 | 134689f568f19a4d8acdaaefec94305e | 33.641791 | 121 | 0.585033 | 5.041274 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/trans/Translation.kt | 1 | 1111 | @file:Suppress("SpellCheckingInspection")
package cn.yiiguxing.plugin.translate.trans
import cn.yiiguxing.plugin.translate.trans.text.NamedTranslationDocument
import cn.yiiguxing.plugin.translate.trans.text.TranslationDocument
import cn.yiiguxing.plugin.translate.util.ObservableValue
interface TranslationAdapter {
fun toTranslation(): Translation
}
/**
* Translation
*/
data class Translation(
override val original: String,
override val translation: String?,
override val srcLang: Lang,
override val targetLang: Lang,
private val sourceLangs: List<Lang>,
val srcTransliteration: String? = null,
val transliteration: String? = null,
val spell: String? = null,
val dictDocument: TranslationDocument? = null,
val extraDocuments: List<NamedTranslationDocument> = emptyList()
) : BaseTranslation(original, srcLang, targetLang, translation) {
val sourceLanguages: List<Lang> by lazy { sourceLangs.filter { it != Lang.UNKNOWN } }
val observableFavoriteId: ObservableValue<Long?> = ObservableValue(null)
var favoriteId: Long? by observableFavoriteId
} | mit | 2ac63333244788ca3eee82b35f19a8f9 | 31.705882 | 89 | 0.760576 | 4.356863 | false | false | false | false |
MichaelEvans/kotlin-koans | src/ii_conventions/_11_Comparison_.kt | 6 | 898 | package ii_conventions
import util.TODO
import kotlin.jvm.internal.Intrinsics
fun compareStrings(s1: String?, s2: String?) {
s1 == s2
// is compiled to
Intrinsics.areEqual(s1, s2)
}
interface B {
fun compareTo(other: B): Int
}
fun test(b1: B, b2: B) {
b1 < b2
// is compiled to
b1.compareTo(b2) < 0
b1 >= b2
// is compiled to
b1.compareTo(b2) >= 0
}
fun todoTask11() = TODO(
"""
Task 11.
Uncomment the commented line and make it compile.
Add all changes to the file MyDate.kt.
Make class MyDate implement Comparable.
For syntax details see syntax/classesObjectsInterfaces.kt.
""",
references = { date: MyDate, comparable: Comparable<MyDate>, syntax: syntax.classesObjectsInterfaces.Successor -> }
)
fun task11(date1: MyDate, date2: MyDate): Boolean {
todoTask11()
// return date1 < date2
}
| mit | 90be4b1f20db14e888de05df5247a06e | 20.902439 | 119 | 0.641425 | 3.494163 | false | false | false | false |
perenecabuto/CatchCatch | android/app/src/main/java/io/perenecabuto/catchcatch/events/EventHandler.kt | 1 | 1324 | package io.perenecabuto.catchcatch.events
import io.perenecabuto.catchcatch.drivers.WebSocketClient
internal val GAME_AROUND = "game:around"
internal val GAME_STARTED = "game:started"
internal val GAME_LOOSE = "game:loose"
internal val GAME_TARGET_NEAR = "game:target:near"
internal val GAME_TARGET_REACHED = "game:target:reached"
internal val GAME_TARGET_WIN = "game:target:win"
internal val GAME_FINISH = "game:finish"
internal val PLAYER_REGISTERED = "player:registered"
internal val PLAYER_UPDATED = "player:updated"
internal val REMOTE_PLAYER_LIST = "remote-player:list"
internal val REMOTE_PLAYER_NEW = "remote-player:new"
internal val REMOTE_PLAYER_UPDATED = "remote-player:updated"
internal val REMOTE_PLAYER_DESTROY = "remote-player:destroy"
internal val CHECKPOINT_DETECTED = "checkpoint:detected"
interface EventHandler {
val sock: WebSocketClient
var running: Boolean
fun onStart()
fun onStop() {}
fun start(): EventHandler {
if (!running) {
running = true
onStart()
}
return this
}
fun stop(): EventHandler {
if (running) {
running = false
sock.off()
onStop()
}
return this
}
fun switchTo(handler: EventHandler) {
stop()
handler.start()
}
} | gpl-3.0 | bf36b3deabdd59983ab9c0bb778412b2 | 26.604167 | 60 | 0.670695 | 4 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/fetch/ContentUriFetcher.kt | 1 | 3934 | package coil.fetch
import android.content.ContentResolver
import android.content.ContentResolver.EXTRA_SIZE
import android.content.ContentResolver.SCHEME_CONTENT
import android.graphics.Point
import android.net.Uri
import android.os.Build.VERSION.SDK_INT
import android.os.Bundle
import android.provider.ContactsContract
import android.provider.ContactsContract.Contacts
import android.provider.MediaStore
import androidx.annotation.VisibleForTesting
import coil.ImageLoader
import coil.decode.ContentMetadata
import coil.decode.DataSource
import coil.decode.ImageSource
import coil.request.Options
import coil.size.Dimension
import okio.buffer
import okio.source
internal class ContentUriFetcher(
private val data: Uri,
private val options: Options
) : Fetcher {
override suspend fun fetch(): FetchResult {
val contentResolver = options.context.contentResolver
val inputStream = if (isContactPhotoUri(data)) {
// Modified from ContactsContract.Contacts.openContactPhotoInputStream.
val stream = contentResolver
//noinspection Recycle: Automatically recycled after being decoded.
.openAssetFileDescriptor(data, "r")
?.createInputStream()
checkNotNull(stream) { "Unable to find a contact photo associated with '$data'." }
} else if (SDK_INT >= 29 && isMusicThumbnailUri(data)) {
val bundle = newMusicThumbnailSizeOptions()
val stream = contentResolver
//noinspection Recycle: Automatically recycled after being decoded.
.openTypedAssetFile(data, "image/*", bundle, null)
?.createInputStream()
checkNotNull(stream) { "Unable to find a music thumbnail associated with '$data'." }
} else {
val stream = contentResolver.openInputStream(data)
checkNotNull(stream) { "Unable to open '$data'." }
}
return SourceResult(
source = ImageSource(
source = inputStream.source().buffer(),
context = options.context,
metadata = ContentMetadata(data)
),
mimeType = contentResolver.getType(data),
dataSource = DataSource.DISK
)
}
/**
* Contact photos are a special case of content uris that must be loaded using
* [ContentResolver.openAssetFileDescriptor] or [ContentResolver.openTypedAssetFile].
*/
@VisibleForTesting
internal fun isContactPhotoUri(data: Uri): Boolean {
return data.authority == ContactsContract.AUTHORITY &&
data.lastPathSegment == Contacts.Photo.DISPLAY_PHOTO
}
/**
* Music thumbnails on API 29+ are a special case of content uris that must be loaded using
* [ContentResolver.openAssetFileDescriptor] or [ContentResolver.openTypedAssetFile].
*
* Example URI: content://media/external/audio/albums/1961323289806133467
*/
@VisibleForTesting
internal fun isMusicThumbnailUri(data: Uri): Boolean {
if (data.authority != MediaStore.AUTHORITY) return false
val segments = data.pathSegments
val size = segments.size
return size >= 3 && segments[size - 3] == "audio" && segments[size - 2] == "albums"
}
private fun newMusicThumbnailSizeOptions(): Bundle? {
val width = (options.size.width as? Dimension.Pixels)?.px ?: return null
val height = (options.size.height as? Dimension.Pixels)?.px ?: return null
return Bundle(1).apply { putParcelable(EXTRA_SIZE, Point(width, height)) }
}
class Factory : Fetcher.Factory<Uri> {
override fun create(data: Uri, options: Options, imageLoader: ImageLoader): Fetcher? {
if (!isApplicable(data)) return null
return ContentUriFetcher(data, options)
}
private fun isApplicable(data: Uri) = data.scheme == SCHEME_CONTENT
}
}
| apache-2.0 | 9647a35902fcb18267ceeb9cf44800e8 | 38.737374 | 96 | 0.674377 | 4.880893 | false | false | false | false |
JustinMullin/drifter-kotlin | src/main/kotlin/xyz/jmullin/drifter/rendering/Draw.kt | 1 | 10430 | package xyz.jmullin.drifter.rendering
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.*
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack
import com.badlogic.gdx.utils.Align
import xyz.jmullin.drifter.entity.Layer2D
import xyz.jmullin.drifter.extensions.*
import xyz.jmullin.drifter.gl.Blend
import xyz.jmullin.drifter.rendering.shader.ShaderSet
import xyz.jmullin.drifter.rendering.shader.Shaders
/**
* Convenience methods for drawing things succinctly.
*/
object Draw {
/**
* Shared GlyphLayout for calculating text display. Very not thread safe!
*/
internal var layout = GlyphLayout()
/**
* Shared PolygonSpriteBatch for rendering polygons.
*/
internal val polygonBatch = PolygonSpriteBatch(2000, Shaders.default.program)
/**
* Simple 1px white fill sprite for drawing filled regions.
*/
val fill: Sprite by lazy {
val pixmap = Pixmap(1, 1, Pixmap.Format.RGBA8888)
pixmap.setColor(Color.WHITE)
pixmap.fill()
Sprite(Texture(pixmap))
}
}
/**
* Draw a sprite at a given position and size.
*/
fun SpriteBatch.sprite(sprite: Sprite, v: Vector2, size: Vector2) {
val bounds = Rectangle(sprite.boundingRectangle)
sprite.setBounds(v.x, v.y, size.x, size.y)
sprite.draw(this)
sprite.setBounds(bounds.x, bounds.y, bounds.width, bounds.height)
}
/**
* Draw a sprite with given bounds.
*/
fun SpriteBatch.sprite(sprite: Sprite, bounds: Rectangle) {
val oldBounds = Rectangle(sprite.boundingRectangle)
sprite.setBounds(bounds.x, bounds.y, bounds.width, bounds.height)
sprite.draw(this)
sprite.setBounds(oldBounds.x, oldBounds.y, oldBounds.width, oldBounds.height)
}
/**
* Draw a nine-patch at a given position and size.
*/
fun SpriteBatch.sprite(patch: NinePatch, v: Vector2, size: Vector2) {
patch.draw(this, v.x, v.y, size.x, size.y)
}
/**
* Draw a nine-patch with given bounds.
*/
fun SpriteBatch.sprite(patch: NinePatch, bounds: Rectangle) {
patch.draw(this, bounds.x, bounds.y, bounds.width, bounds.height)
}
/**
* Draw a texture at a given position and size.
*/
fun SpriteBatch.texture(texture: Texture, v: Vector2, size: Vector2) {
draw(texture, v.x, v.y, size.x, size.y)
}
/**
* Draw a texture with given bounds.
*/
fun SpriteBatch.texture(texture: Texture, bounds: Rectangle) {
draw(texture, bounds.x, bounds.y, bounds.width, bounds.height)
}
/**
* Draw a texture at a given position and size with the specified texture coords.
*/
fun SpriteBatch.texture(texture: Texture, v: Vector2, size: Vector2, uvA: Vector2, uvB: Vector2) {
draw(texture, v.x, v.y, size.x, size.y, uvA.x, uvA.y, uvB.x, uvB.y)
}
/**
* Draw a texture with given bounds and texture coords.
*/
fun SpriteBatch.texture(texture: Texture, bounds: Rectangle, uvA: Vector2, uvB: Vector2) {
draw(texture, bounds.x, bounds.y, bounds.x, bounds.y, uvA.x, uvA.y, uvB.x, uvB.y)
}
/**
* Draws a simple filled rectangle with the specified color.
*/
fun SpriteBatch.fill(v: Vector2, size: Vector2, color: Color) {
Draw.fill.color = color
sprite(Draw.fill, v, size)
}
/**
* Draws a simple filled rectangle with the specified color.
*/
fun SpriteBatch.fill(bounds: Rectangle, color: Color) {
Draw.fill.color = color
sprite(Draw.fill, bounds)
}
/**
* Draws a textured quad with the given vertices.
*/
fun SpriteBatch.quad(sprite: Sprite, a: Vector2, b: Vector2, c: Vector2, d: Vector2, color: Color = Color.WHITE) {
val u = sprite.u
val v = sprite.v
val u2 = sprite.u2
val v2 = sprite.v2
quad(sprite.texture, a, b, c, d, V2(u, v), V2(u, v2), V2(u2, v2), V2(u2, v), color)
}
/**
* Draws a textured quad with the given vertices.
*/
fun SpriteBatch.quad(sprite: Sprite, a: Vector2, b: Vector2, c: Vector2, d: Vector2,
colA: Color, colB: Color, colC: Color, colD: Color) {
val u = sprite.u
val v = sprite.v
val u2 = sprite.u2
val v2 = sprite.v2
quad(sprite.texture, a, b, c, d, V2(u, v), V2(u, v2), V2(u2, v2), V2(u2, v), colA, colB, colC, colD)
}
/**
* Draws a thick line between two points.
*/
fun SpriteBatch.line(a: Vector2, b: Vector2, thickness: Float, color: Color) {
val dir = (b - a).nor()
quad(Draw.fill,
a + dir.cpy().rotate(90f) * thickness*0.5f,
a - dir.cpy().rotate(90f) * thickness*0.5f,
b - dir.cpy().rotate(90f) * thickness*0.5f,
b + dir.cpy().rotate(90f) * thickness*0.5f,
color)
}
/**
* Draws a textured quad with the given vertices and texture coordinates.
*/
fun SpriteBatch.quad(texture: Texture,
a: Vector2, b: Vector2, c: Vector2, d: Vector2,
uvA: Vector2, uvB: Vector2, uvC: Vector2, uvD: Vector2,
color: Color = Color.WHITE) {
val col = color.toFloatBits()
val vertices = floatArrayOf(
a.x, a.y, col, uvA.x, uvA.y,
b.x, b.y, col, uvB.x, uvB.y,
d.x, d.y, col, uvD.x, uvD.y,
a.x, a.y, col, uvA.x, uvA.y,
d.x, d.y, col, uvD.x, uvD.y,
b.x, b.y, col, uvB.x, uvB.y,
c.x, c.y, col, uvC.x, uvC.y,
d.x, d.y, col, uvD.x, uvD.y)
draw(texture, vertices, 0, vertices.size)
}
/**
* Draws a textured quad with the given vertices and texture coordinates.
*/
fun SpriteBatch.quad(texture: Texture,
a: Vector2, b: Vector2, c: Vector2, d: Vector2,
uvA: Vector2, uvB: Vector2, uvC: Vector2, uvD: Vector2,
colA: Color, colB: Color, colC: Color, colD: Color) {
val cA = colA.toFloatBits()
val cB = colB.toFloatBits()
val cC = colC.toFloatBits()
val cD = colD.toFloatBits()
val vertices = floatArrayOf(
a.x, a.y, cA, uvA.x, uvA.y,
b.x, b.y, cB, uvB.x, uvB.y,
d.x, d.y, cD, uvD.x, uvD.y,
a.x, a.y, cA, uvA.x, uvA.y,
d.x, d.y, cD, uvD.x, uvD.y,
b.x, b.y, cB, uvB.x, uvB.y,
c.x, c.y, cC, uvC.x, uvC.y,
d.x, d.y, cD, uvD.x, uvD.y)
draw(texture, vertices, 0, vertices.size)
}
/**
* Given a [[ShapeRenderer.ShapeType]] to draw and a Unit block, provides an active [[ShapeRenderer]] with
* basic parameters setup to simplify the process of drawing primitives to the screen.
*
* '''Example:'''
*
* {{{
* Draw.shapes(ShapeType.Filled) { r ->
* r.rect(0, 0, 100, 100)
* }
* }}}
*/
fun SpriteBatch.shapes(kind: ShapeRenderer.ShapeType, shader: ShaderProgram?= Shaders.default.program, f: (ShapeRenderer) -> Unit, layer: Layer2D) {
end()
Gdx.gl.glEnable(GL20.GL_BLEND)
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)
val r = ShapeRenderer(5000, shader)
r.begin(kind)
r.projectionMatrix = layer.camera.combined
f(r)
r.end()
r.dispose()
Gdx.gl.glDisable(GL20.GL_BLEND)
begin()
}
/**
* Draw a string with the given location, font and no alignment.
*/
fun SpriteBatch.string(str: String, v: Vector2, font: BitmapFont) {
Draw.layout.setText(font, str)
font.draw(this, str, v.x, v.y)
}
/**
* Draw a string with the given location, font and alignment.
*/
fun SpriteBatch.string(str: String, v: Vector2, font: BitmapFont, align: Vector2) {
Draw.layout.setText(font, str)
font.draw(this, str, v.x + (align.x - 1) * Draw.layout.width * 0.5f, v.y + (align.y + 1) * Draw.layout.height * 0.5f)
}
/**
* Draw a string with the given location, font and alignment, wrapped to the specified width.
*/
fun SpriteBatch.stringWrapped(str: String, v: Vector2, width: Float, font: BitmapFont, align: Vector2) {
Draw.layout.setText(font, str, font.color, width, Align.center, true)
font.draw(this, str, v.x + (align.x - 1) * Draw.layout.width * 0.5f, v.y + (align.y + 1) * Draw.layout.height * 0.5f, width, Align.center, true)
}
/**
* Draw a string with the given location, font and alignment, wrapped to the specified width.
*/
fun SpriteBatch.stringWrapped(str: String, v: Vector2, start: Int, end: Int, width: Float, font: BitmapFont, hAlign: Int) {
Draw.layout.setText(font, str, start, end, font.color, width, hAlign, true, null)
font.draw(this, Draw.layout, v.x, v.y)
}
/**
* Set up a polygon renderer for drawing filled polygons.
*/
fun polygons(layer: Layer2D?, f: (PolygonRenderer) -> Unit, batch: PolygonSpriteBatch = Draw.polygonBatch) {
batch.begin()
batch.projectionMatrix = layer?.camera?.projection
f(PolygonRenderer(batch))
batch.end()
}
/**
* Sets up a scissor stack for efficient rectangular clipping.
*/
fun SpriteBatch.clip(layer: Layer2D?, bounds: Rectangle, f: SpriteBatch.() -> Unit) {
flush()
val scissors = Rectangle()
ScissorStack.calculateScissors(layer?.camera, 0f, 0f, gameW().toFloat(), gameH().toFloat(), transformMatrix, bounds, scissors)
ScissorStack.pushScissors(scissors)
this.f()
flush()
ScissorStack.popScissors();
}
/**
* Switches to a new shader set, switching back to the default shader afterwards.
*/
fun SpriteBatch.inShader(shaderSet: ShaderSet, f: SpriteBatch.(ShaderProgram) -> Unit) {
Shaders.switch(shaderSet, this)
this.f(shaderSet.program!!)
Shaders.switch(Shaders.default, this)
}
/**
* Enables a custom blending mode, returning to regular alpha blending afterwards.
*/
fun SpriteBatch.blend(source: Pair<Blend, Blend>, f: SpriteBatch.() -> Unit) = blend(source.first, source.second, f)
/**
* Enables a custom blending mode, returning to regular alpha blending afterwards.
*/
fun SpriteBatch.blend(source: Blend, dest: Blend, f: SpriteBatch.() -> Unit) {
flush()
enableBlending()
setBlendFunction(source.gl, dest.gl)
this.f()
flush()
setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)
}
fun SpriteBatch.transform(rotation: Float, translation: Vector2, f: SpriteBatch.() -> Unit) {
val previousMatrix = transformMatrix.cpy()
end()
transformMatrix
.setToRotation(V3(0f, 0f, 1f), rotation)
.translate(translation.xyo)
begin()
this.f()
end()
transformMatrix.set(previousMatrix)
begin()
}
| mit | 0840b5e587bd2fef3a299c054008402c | 29.408163 | 148 | 0.657335 | 3.114362 | false | false | false | false |
mutualmobile/CardStackUI | app/src/main/java/com/mutualmobile/cardstack/sample/utils/PrefsUtil.kt | 1 | 2568 | package com.mutualmobile.cardstack.sample.utils
import android.content.Context
import com.mutualmobile.cardstack.CardStackLayout
import com.mutualmobile.cardstack.sample.R.dimen
import com.tramsun.libs.prefcompat.Pref
object PrefsUtil {
const val SHOW_INIT_ANIMATION = "showInitAnimation"
const val PARALLAX_ENABLED = "parallaxEnabled"
const val PARALLAX_SCALE = "parallaxScale"
const val CARD_GAP = "cardGap"
const val CARD_GAP_BOTTOM = "cardGapBottom"
private const val REVERSE_CLICK_ANIMATION_ENABLED = "reverseClickAnimationEnabled"
private const val REVERSE_CLICK_ANIMATION_ENABLED_DEFAULT = false
val isShowInitAnimationEnabled: Boolean
get() = Pref.getBoolean(SHOW_INIT_ANIMATION, CardStackLayout.SHOW_INIT_ANIMATION_DEFAULT)
val isParallaxEnabled: Boolean
get() = Pref.getBoolean(PARALLAX_ENABLED, CardStackLayout.PARALLAX_ENABLED_DEFAULT)
var isReverseClickAnimationEnabled: Boolean
get() = Pref.getBoolean(
REVERSE_CLICK_ANIMATION_ENABLED,
REVERSE_CLICK_ANIMATION_ENABLED_DEFAULT
)
set(b) = Pref.putBoolean(REVERSE_CLICK_ANIMATION_ENABLED, b)
fun getParallaxScale(context: Context): Int {
return Pref.getInt(PARALLAX_SCALE, context.resources.getInteger(com.mutualmobile.cardstack.R.integer.parallax_scale_default))
}
fun getCardGap(context: Context): Int {
val cardGapDimenInDp = (context.resources.getDimension(dimen.card_gap) / context.resources.displayMetrics.density).toInt()
return Pref.getInt(CARD_GAP, cardGapDimenInDp)
}
fun getCardGapBottom(context: Context): Int {
val cardGapBottomDimenInDp = (context.resources.getDimension(dimen.card_gap_bottom) / context.resources.displayMetrics.density).toInt()
return Pref.getInt(CARD_GAP_BOTTOM, cardGapBottomDimenInDp)
}
fun resetDefaults(context: Context) {
val cardGapDimenInDp = (context.resources.getDimension(dimen.card_gap) / context.resources.displayMetrics.density).toInt()
val cardGapBottomDimenInDp = (context.resources.getDimension(dimen.card_gap_bottom) / context.resources.displayMetrics.density).toInt()
Pref.putBoolean(SHOW_INIT_ANIMATION, CardStackLayout.SHOW_INIT_ANIMATION_DEFAULT)
Pref.putBoolean(PARALLAX_ENABLED, CardStackLayout.PARALLAX_ENABLED_DEFAULT)
isReverseClickAnimationEnabled =
REVERSE_CLICK_ANIMATION_ENABLED_DEFAULT
Pref.putInt(PARALLAX_SCALE, context.resources.getInteger(com.mutualmobile.cardstack.R.integer.parallax_scale_default))
Pref.putInt(CARD_GAP, cardGapDimenInDp)
Pref.putInt(CARD_GAP_BOTTOM, cardGapBottomDimenInDp)
}
} | apache-2.0 | 1d900ccea3a26087e8ecc4ce0457b93a | 43.293103 | 139 | 0.78271 | 3.737991 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/terraform/config/inspection/TFDuplicatedInspectionBase.kt | 1 | 6380 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hcl.terraform.config.inspection
import com.intellij.codeInspection.*
import com.intellij.ide.DataManager
import com.intellij.ide.projectView.PresentationData
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFile
import com.intellij.refactoring.RefactoringActionHandlerFactory
import com.intellij.refactoring.RefactoringFactory
import com.intellij.usageView.UsageInfo
import com.intellij.usages.*
import com.intellij.util.Consumer
import com.intellij.util.NullableFunction
import org.intellij.plugins.hcl.terraform.config.model.getTerraformSearchScope
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns
import org.jetbrains.annotations.NotNull
abstract class TFDuplicatedInspectionBase : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
val file = holder.file
if (!TerraformPatterns.TerraformConfigFile.accepts(file)) {
return super.buildVisitor(holder, isOnTheFly)
}
return createVisitor(holder)
}
companion object {
abstract class RenameQuickFix(name: String) : LocalQuickFixBase(name) {
protected fun invokeRenameRefactoring(project: Project, element: PsiElement) {
// TODO: Find way to remove only current element
val factory = RefactoringFactory.getInstance(project)
val renameRefactoring = factory.createRename(element, "newName")
renameRefactoring.isSearchInComments = false
renameRefactoring.isSearchInNonJavaFiles = false
renameRefactoring.run()
if (true) return
val renameHandler = RefactoringActionHandlerFactory.getInstance().createRenameHandler()
val dataManager = DataManager.getInstance()
if (ApplicationManager.getApplication().isUnitTestMode) {
@Suppress("DEPRECATION")
renameHandler.invoke(project, arrayOf(element), dataManager.dataContext)
return
}
dataManager.dataContextFromFocus.doWhenDone(Consumer { context: DataContext? ->
context?.let {
ApplicationManager.getApplication().invokeLater(Runnable {
renameHandler.invoke(project, arrayOf(element), context)
}, project.disposed)
}
})
}
}
}
abstract fun createVisitor(holder: ProblemsHolder): PsiElementVisitor
protected fun createNavigateToDupeFix(file: VirtualFile, offsetInOtherFile: Int, single: Boolean): LocalQuickFix? {
return object : LocalQuickFixBase("Navigate to ${if (!single) "first " else ""}duplicate") {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
OpenFileDescriptor(project, file, offsetInOtherFile).navigate(true)
}
}
}
protected fun createShowOtherDupesFix(file: VirtualFile, offset: Int, duplicates: NullableFunction<PsiElement, List<PsiElement>?>): LocalQuickFix? {
return object : LocalQuickFixBase("View duplicates like this") {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
@Suppress("NAME_SHADOWING")
val duplicates = duplicates.`fun`(descriptor.psiElement) ?: return
val presentation = UsageViewPresentation()
val title = buildTitle()
presentation.usagesString = title
presentation.tabName = title
presentation.tabText = title
val scope = descriptor.psiElement.getTerraformSearchScope()
presentation.scopeText = scope.displayName
UsageViewManager.getInstance(project).searchAndShowUsages(arrayOf<UsageTarget>(object : UsageTarget {
override fun findUsages() {}
override fun findUsagesInEditor(@NotNull editor: FileEditor) {}
override fun highlightUsages(@NotNull file: PsiFile, @NotNull editor: Editor, clearHighlights: Boolean) {}
override fun isValid(): Boolean {
return true
}
override fun isReadOnly(): Boolean {
return true
}
override fun getFiles(): Array<VirtualFile>? {
return null
}
override fun update() {}
@NotNull
override fun getName(): String? {
return buildTitle()
}
@NotNull
override fun getPresentation(): ItemPresentation? {
return PresentationData(name, "", null, null)
}
override fun navigate(requestFocus: Boolean) {
OpenFileDescriptor(project, file, offset).navigate(requestFocus)
}
override fun canNavigate(): Boolean {
return true
}
override fun canNavigateToSource(): Boolean {
return canNavigate()
}
}), {
UsageSearcher { processor ->
val infos = ApplicationManager.getApplication().runReadAction<List<UsageInfo>> {
duplicates.map { dup -> UsageInfo(dup.containingFile) }
}
for (info in infos) {
processor.process(UsageInfo2UsageAdapter(info))
}
}
}, false, false, presentation, null)
}
var myTitle: String? = null
private fun buildTitle(): String {
if (myTitle == null) myTitle = "Duplicate code like in " + file.name + ":" + offset
return myTitle!!
}
}
}
}
| apache-2.0 | 83e00b9b17b1634c5ac980d299995e98 | 36.529412 | 150 | 0.694984 | 5.095847 | false | false | false | false |
spaceisstrange/ToListen | ToListen/app/src/main/java/io/spaceisstrange/tolisten/ui/activities/base/BaseDrawerActivity.kt | 1 | 4376 | /*
* Made with <3 by Fran González (@spaceisstrange)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.spaceisstrange.tolisten.ui.activities.base
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import io.spaceisstrange.tolisten.R
import io.spaceisstrange.tolisten.ui.activities.settings.SettingsActivity
import io.spaceisstrange.tolisten.ui.dialogs.AboutDialog
/**
* Base class for every activity that needs the default navigation drawer
*/
abstract class BaseDrawerActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
/**
* NavigationView of the activity
*/
lateinit var navView: NavigationView
/**
* Called when onCreate is happening to setup the view of the activity
*/
abstract fun setupView()
/**
* Called whenever the user selects "Artist" from the navigation drawer
*/
abstract fun onArtistsSelected()
/**
* Called whenever the user selects "Albums" from the navigation drawer
*/
abstract fun onAlbumsSelected()
/**
* Called whenever the user selects "Songs" from the navigation drawer
*/
abstract fun onSongsSelected()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupView()
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
navView = findViewById(R.id.nav_view) as NavigationView
val drawer = findViewById(R.id.drawer) as DrawerLayout
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer.setDrawerListener(toggle)
toggle.syncState()
navView.setNavigationItemSelectedListener(this)
}
override fun onBackPressed() {
val drawer = findViewById(R.id.drawer) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when (id) {
R.id.nav_artists -> onArtistsSelected()
R.id.nav_albums -> onAlbumsSelected()
R.id.nav_songs -> onSongsSelected()
R.id.nav_about -> onAboutSelected()
R.id.nav_settings -> onSettingsSelected()
}
val drawer = findViewById(R.id.drawer) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
return true
}
/**
* Called from a subclass to set an item as selected
*/
fun setItemChecked(item: Int) {
navView.menu.getItem(item).isChecked = true
}
/**
* Called from a subclass to set an item as not selected
*/
fun setItemUnchecked(item: Int) {
navView.menu.getItem(item).isChecked = false
}
/**
* Called whenever the user selects "About" from the navigation drawer
*/
fun onAboutSelected() {
AboutDialog().show(supportFragmentManager, javaClass.canonicalName)
}
/**
* Called whenever the user selects "Settings" from the navigation drawer
*/
fun onSettingsSelected() {
val settingsIntent = Intent(this, SettingsActivity::class.java)
startActivity(settingsIntent)
}
}
| gpl-3.0 | 3aa7e12c09214324a0cd78b85862ae5f | 31.649254 | 106 | 0.692114 | 4.581152 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/CauseUserIdCause.kt | 1 | 1178 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param shortDescription
* @param userId
* @param userName
*/
data class CauseUserIdCause(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("shortDescription") val shortDescription: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("userId") val userId: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("userName") val userName: kotlin.String? = null
) {
}
| mit | 2c4125e30e04dcb4f0b60ac178d22b85 | 29.205128 | 88 | 0.755518 | 4.207143 | false | false | false | false |
edsilfer/presence-control | app/src/main/java/br/com/edsilfer/android/presence_control/user/domain/entity/User.kt | 1 | 579 | package br.com.edsilfer.android.presence_control.user.domain.entity
import br.com.edsilfer.android.presence_control.commons.utils.SUID
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
/**
* Created by ferna on 5/14/2017.
*/
open class User : RealmObject() {
@PrimaryKey
open var id: Long = SUID.id()
open var name: String = ""
open var password: String = ""
open var email: String = ""
open var gender: String = "male"
open var facebookID: String = ""
open var facebookToken: String = ""
open var thumbnail: String = ""
} | apache-2.0 | 0eb706473db9d54f2919e7008e23266d | 28 | 67 | 0.689119 | 3.664557 | false | false | false | false |
EyeSeeTea/QAApp | app/src/main/java/org/eyeseetea/malariacare/presentation/views/MonitorActionsDialogFragment.kt | 1 | 7244 | package org.eyeseetea.malariacare.presentation.views
import android.app.Activity
import android.app.AlertDialog
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Toast
import kotlinx.android.synthetic.main.dialog_actions_monitoring.view.*
import org.eyeseetea.malariacare.DashboardActivity
import org.eyeseetea.malariacare.R
import org.eyeseetea.malariacare.factories.DataFactory
import org.eyeseetea.malariacare.factories.MetadataFactory
import org.eyeseetea.malariacare.presentation.executors.WrapperExecutor
import org.eyeseetea.malariacare.presentation.presenters.monitoring.MonitorActionsDialogPresenter
import org.eyeseetea.malariacare.presentation.viewmodels.observations.ActionViewModel
import java.text.SimpleDateFormat
import java.util.Locale
class MonitorActionsDialogFragment : DialogFragment(), MonitorActionsDialogPresenter.View {
private lateinit var rootView: View
private lateinit var surveyId: String
private lateinit var presenter: MonitorActionsDialogPresenter
var onActionsSaved: (() -> Unit)? = null
override fun onStart() {
dialog?.window?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT
)
super.onStart()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
surveyId = arguments!!.getString(SURVEY_ID)!!
return inflater.inflate(R.layout.dialog_actions_monitoring, container)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rootView = view
initializeButtons(view)
initializePresenter()
}
override fun onDestroy() {
presenter.detachView()
super.onDestroy()
}
override fun showLoading() {
rootView.progress_view.visibility = View.VISIBLE
}
override fun hideLoading() {
rootView.progress_view.visibility = View.GONE
}
override fun showLoadErrorMessage() {
Toast.makeText(
activity as Activity,
getString(R.string.load_error_message),
Toast.LENGTH_LONG
).show()
}
override fun showSaveErrorMessage() {
Toast.makeText(
activity as Activity,
getString(R.string.save_error_message),
Toast.LENGTH_LONG
).show()
}
override fun showOrgUnitAndProgram(orgUnit: String, program: String) {
rootView.program_view.text = program
rootView.org_unit_view.text = orgUnit
}
override fun showSaveConfirmMessage() {
val builder = AlertDialog.Builder(activity)
builder
.setMessage(R.string.action_monitor_save_confirm_message)
.setPositiveButton(R.string.ok) { _, _ ->
presenter.confirmSave()
}
.setNegativeButton(R.string.cancel) { _, _ ->
}
// Create the AlertDialog object and return it
val dialog = builder.create()
dialog.show()
}
override fun exit() {
dismiss()
}
override fun navigateToFeedback(surveyUid: String) {
DashboardActivity.dashboardActivity.openFeedback(surveyUid, false)
}
override fun showActions(
action1: ActionViewModel,
action2: ActionViewModel,
action3: ActionViewModel
) {
if (!action1.description.isBlank()) {
rootView.action1_container.visibility = View.VISIBLE
rootView.action1_view.text = getTextToShowInAction(action1)
rootView.action1_conducted_view.isChecked = action1.isCompleted
} else {
rootView.action1_container.visibility = View.GONE
}
if (!action2.description.isBlank()) {
rootView.action2_container.visibility = View.VISIBLE
rootView.action2_view.text = getTextToShowInAction(action2)
rootView.action2_conducted_view.isChecked = action2.isCompleted
} else {
rootView.action2_container.visibility = View.GONE
}
if (!action3.description.isBlank()) {
rootView.action3_container.visibility = View.VISIBLE
rootView.action3_view.text = getTextToShowInAction(action3)
rootView.action3_conducted_view.isChecked = action3.isCompleted
} else {
rootView.action3_container.visibility = View.GONE
}
}
override fun notifyOnSave() {
onActionsSaved?.invoke()
dismiss()
}
override fun changeToReadOnlyMode() {
rootView.action1_conducted_view.isEnabled = false
rootView.action2_conducted_view.isEnabled = false
rootView.action3_conducted_view.isEnabled = false
rootView.ok_button.isEnabled = false
}
private fun initializeButtons(rootView: View) {
rootView.ok_button.setOnClickListener {
presenter.save(
rootView.action1_conducted_view.isChecked,
rootView.action2_conducted_view.isChecked,
rootView.action3_conducted_view.isChecked
)
}
rootView.cancel_button.setOnClickListener {
presenter.cancel()
}
rootView.feedback_button.setOnClickListener {
presenter.feedback()
}
}
private fun initializePresenter() {
presenter = MonitorActionsDialogPresenter(
WrapperExecutor(),
MetadataFactory.provideGetProgramByUidUseCase(),
MetadataFactory.provideGetOrgUnitByUidUseCase(),
MetadataFactory.provideServerMetadataUseCase(activity as Activity),
DataFactory.provideGetSurveyByUidUseCase(),
DataFactory.provideGetObservationBySurveyUidUseCase(),
DataFactory.provideSaveObservationUseCase()
)
presenter.attachView(this, surveyId)
}
private fun getTextToShowInAction(action: ActionViewModel): String {
val responsibleLabel =
activity?.resources?.getString(R.string.observation_action_responsible)
val dueDateLabel = activity?.resources?.getString(R.string.observation_action_due_date)
val dateFormatter = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
val date = dateFormatter.format(action.dueDate)
val maxLength = 75
val description =
if (action.description.length > maxLength)
"${action.description.substring(0, maxLength)} ..."
else action.description
return "$description \n$responsibleLabel ${action.responsible} \n$dueDateLabel $date"
}
companion object {
private const val SURVEY_ID = "surveyId"
@JvmStatic
fun newInstance(surveyIds: String): MonitorActionsDialogFragment {
val fragment = MonitorActionsDialogFragment()
val args = Bundle()
args.putString(SURVEY_ID, surveyIds)
fragment.arguments = args
return fragment
}
}
} | gpl-3.0 | 1234055f3f956153cb853d7234b01cd6 | 31.635135 | 97 | 0.665102 | 4.924541 | false | false | false | false |
lanhuaguizha/Christian | app/src/main/java/com/christian/annotation/Test.kt | 1 | 783 | package com.christian.annotation
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun main() = runBlocking {
val time = measureTimeMillis {
launch {
calThingsAsync()
}
}
println("runtime-from thread ${Thread.currentThread().name} is $time")
}
private suspend fun calThingsAsync() {
coroutineScope {
val r1 = async(Dispatchers.IO) { calThings(1) }
val r2 = async(Dispatchers.IO) { calThings(2) }
val r3 = async(Dispatchers.IO) { calThings(3) }
println("sum-from thread ${Thread.currentThread().name}, ${r1.await() + r2.await() + r3.await()}")
}
}
suspend fun calThings(i: Int): Int {
delay(1000)
println("r$i-from thread ${Thread.currentThread().name}, $i")
return i
} | gpl-3.0 | 77bb619a6c8ee86f8c2beacee6b46fab | 25.133333 | 106 | 0.632184 | 3.7109 | false | false | false | false |
thermatk/FastHub-Libre | app/src/main/java/com/fastaccess/ui/adapter/viewholder/ProjectViewHolder.kt | 7 | 1385 | package com.fastaccess.ui.adapter.viewholder
import android.view.View
import android.view.ViewGroup
import butterknife.BindView
import com.fastaccess.R
import com.fastaccess.helper.ParseDateFormat
import com.fastaccess.ui.widgets.FontTextView
import com.fastaccess.ui.widgets.recyclerview.BaseRecyclerAdapter
import com.fastaccess.ui.widgets.recyclerview.BaseViewHolder
import github.RepoProjectsOpenQuery
/**
* Created by kosh on 09/09/2017.
*/
class ProjectViewHolder(view: View, adapter: BaseRecyclerAdapter<*, *, *>) : BaseViewHolder<RepoProjectsOpenQuery.Node>(view, adapter) {
@BindView(R.id.description) lateinit var description: FontTextView
@BindView(R.id.title) lateinit var title: FontTextView
@BindView(R.id.date) lateinit var date: FontTextView
override fun bind(t: RepoProjectsOpenQuery.Node) {
title.text = t.name()
if (t.body().isNullOrBlank()) {
description.visibility = View.GONE
} else {
description.visibility = View.VISIBLE
description.text = t.body()
}
date.text = ParseDateFormat.getTimeAgo(t.createdAt().toString())
}
companion object {
fun newInstance(parent: ViewGroup, adapter: BaseRecyclerAdapter<*, *, *>): ProjectViewHolder {
return ProjectViewHolder(getView(parent, R.layout.feeds_row_no_image_item), adapter)
}
}
} | gpl-3.0 | 8c95740d439573d50473b6ca84453ebf | 35.473684 | 136 | 0.718412 | 4.287926 | false | false | false | false |
JavaEden/OrchidCore | OrchidCore/src/main/kotlin/com/eden/orchid/impl/resources/InlineResourceSource.kt | 1 | 1163 | package com.eden.orchid.impl.resources
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.resources.resource.InlineStringResource
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.api.resources.resourcesource.LocalResourceSource
import java.util.regex.Pattern
import javax.inject.Inject
class InlineResourceSource
@Inject
constructor(
private val context: OrchidContext
) : LocalResourceSource {
override val priority: Int = Integer.MAX_VALUE - 1
override fun getResourceEntry(fileName: String): OrchidResource? {
val m = inlineFilenamePattern.matcher(fileName)
if (m.find()) {
val actualFileName = m.group(2)
val fileContent = m.group(3)
return InlineStringResource(context, actualFileName, fileContent)
}
return null
}
override fun getResourceEntries(dirName: String, fileExtensions: Array<String>?, recursive: Boolean): List<OrchidResource> {
return emptyList()
}
companion object {
private val inlineFilenamePattern = Pattern.compile("^(inline:(.*?):)(.*)", Pattern.DOTALL)
}
}
| mit | f00f3c493b5f09a11f96dd67aef4bf59 | 28.820513 | 128 | 0.715391 | 4.525292 | false | false | false | false |
xfournet/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/IconsClassGenerator.kt | 1 | 10645 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.intellij.build.images
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.jps.model.JpsSimpleElement
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.util.JpsPathUtil
import java.io.File
import java.util.*
class IconsClassGenerator(val projectHome: File, val util: JpsModule, val writeChangesToDisk: Boolean = true) {
private var processedClasses = 0
private var processedIcons = 0
private var modifiedClasses = ArrayList<Pair<JpsModule, File>>()
fun processModule(module: JpsModule) {
val customLoad: Boolean
val packageName: String
val className: String
val outFile: File
if ("intellij.platform.icons" == module.name) {
customLoad = false
packageName = "com.intellij.icons"
className = "AllIcons"
val dir = util.getSourceRoots(JavaSourceRootType.SOURCE).first().file.absolutePath + "/com/intellij/icons"
outFile = File(dir, "AllIcons.java")
}
else {
customLoad = true
packageName = "icons"
val firstRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).firstOrNull()
if (firstRoot == null) return
val generatedRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).find { it.properties.isForGeneratedSources }
val targetRoot = File((generatedRoot ?: firstRoot).file, "icons")
val firstRootDir = File(firstRoot.file, "icons")
if (firstRootDir.isDirectory && firstRootDir.list().isEmpty()) {
//this is added to remove unneeded empty directories created by previous version of this script
println("deleting empty directory ${firstRootDir.absolutePath}")
firstRootDir.delete()
}
var oldClassName = findIconClass(firstRootDir)
if (generatedRoot != null && oldClassName != null) {
val oldFile = File(firstRootDir, "${oldClassName}.java")
println("deleting $oldFile from source root which isn't marked as 'generated'")
oldFile.delete()
}
if (oldClassName == null) {
oldClassName = findIconClass(targetRoot)
}
className = oldClassName ?: directoryName(module) + "Icons"
outFile = File(targetRoot, "${className}.java")
}
val copyrightComment = getCopyrightComment(outFile)
val text = generate(module, className, packageName, customLoad, copyrightComment)
if (text != null) {
processedClasses++
if (!outFile.exists() || outFile.readText().lines() != text.lines()) {
modifiedClasses.add(Pair(module, outFile))
if (writeChangesToDisk) {
outFile.parentFile.mkdirs()
outFile.writeText(text)
println("Updated icons class: ${outFile.name}")
}
}
}
}
fun printStats() {
println()
println("Generated classes: $processedClasses. Processed icons: $processedIcons")
}
fun getModifiedClasses() = modifiedClasses
private fun findIconClass(dir: File): String? {
var className: String? = null
dir.children.forEach {
if (it.name.endsWith("Icons.java")) {
className = it.name.substring(0, it.name.length - ".java".length)
}
}
return className
}
private fun getCopyrightComment(file: File): String {
if (!file.isFile) return ""
val text = file.readText()
val i = text.indexOf("package ")
if (i == -1) return ""
val comment = text.substring(0, i)
return if (comment.trim().endsWith("*/") || comment.trim().startsWith("//")) comment else ""
}
private fun generate(module: JpsModule, className: String, packageName: String, customLoad: Boolean, copyrightComment: String): String? {
val answer = StringBuilder()
answer.append(copyrightComment)
append(answer, "package $packageName;\n", 0)
append(answer, "import com.intellij.openapi.util.IconLoader;", 0)
append(answer, "", 0)
append(answer, "import javax.swing.*;", 0)
append(answer, "", 0)
// IconsGeneratedSourcesFilter depends on following comment, if you going to change the text
// please do corresponding changes in IconsGeneratedSourcesFilter as well
append(answer, "/**", 0)
append(answer, " * NOTE THIS FILE IS AUTO-GENERATED", 0)
append(answer, " * DO NOT EDIT IT BY HAND, run \"Generate icon classes\" configuration instead", 0)
append(answer, " */", 0)
append(answer, "public class $className {", 0)
if (customLoad) {
append(answer, "private static Icon load(String path) {", 1)
append(answer, "return IconLoader.getIcon(path, ${className}.class);", 2)
append(answer, "}", 1)
append(answer, "", 0)
}
val imageCollector = ImageCollector(projectHome, true)
val images = imageCollector.collect(module)
imageCollector.printUsedIconRobots()
val inners = StringBuilder()
processIcons(images, inners, customLoad, 0)
if (inners.isEmpty()) return null
answer.append(inners)
append(answer, "}", 0)
return answer.toString()
}
private fun processIcons(images: List<ImagePaths>, answer: StringBuilder, customLoad: Boolean, depth: Int) {
val level = depth + 1
val (nodes, leafs) = images.partition { getImageId(it, depth).contains('/') }
val nodeMap = nodes.groupBy { getImageId(it, depth).substringBefore('/') }
val leafMap = ContainerUtil.newMapFromValues(leafs.iterator(), { getImageId(it, depth) })
val sortedKeys = (nodeMap.keys + leafMap.keys).sortedWith(NAME_COMPARATOR)
sortedKeys.forEach { key ->
val group = nodeMap[key]
val image = leafMap[key]
if (group != null) {
val inners = StringBuilder()
processIcons(group, inners, customLoad, depth + 1)
if (inners.isNotEmpty()) {
append(answer, "", level)
append(answer, "public static class " + className(key) + " {", level)
append(answer, inners.toString(), 0)
append(answer, "}", level)
}
}
if (image != null) {
val file = image.file
if (file != null) {
val name = file.name
val used = image.used
val deprecated = image.deprecated
val deprecationComment = image.deprecationComment
if (isIcon(file)) {
processedIcons++
if (used || deprecated) {
append(answer, "", level)
if (deprecationComment != null) {
append(answer, "/** @deprecated $deprecationComment */", level)
}
append(answer, "@SuppressWarnings(\"unused\")", level)
}
if (deprecated) {
append(answer, "@Deprecated", level)
}
val sourceRoot = image.sourceRoot
var root_prefix: String = ""
if (sourceRoot.rootType == JavaSourceRootType.SOURCE) {
@Suppress("UNCHECKED_CAST")
val packagePrefix = (sourceRoot.properties as JpsSimpleElement<JavaSourceRootProperties>).data.packagePrefix
if (!packagePrefix.isEmpty()) root_prefix = "/" + packagePrefix.replace('.', '/')
}
val size = imageSize(file) ?: error("Can't get icon size: $file")
val method = if (customLoad) "load" else "IconLoader.getIcon"
val relativePath = root_prefix + "/" + FileUtil.getRelativePath(sourceRoot.file, file)!!.replace('\\', '/')
append(answer,
"public static final Icon ${iconName(name)} = $method(\"$relativePath\"); // ${size.width}x${size.height}",
level)
}
}
}
}
}
private fun append(answer: StringBuilder, text: String, level: Int) {
answer.append(" ".repeat(level))
answer.append(text).append("\n")
}
private fun getImageId(image: ImagePaths, depth: Int): String {
val path = StringUtil.trimStart(image.id, "/").split("/")
if (path.size < depth) throw IllegalArgumentException("Can't get image ID - ${image.id}, $depth")
return path.drop(depth).joinToString("/")
}
private fun directoryName(module: JpsModule): String {
return directoryNameFromConfig(module) ?: className(module.name)
}
private fun directoryNameFromConfig(module: JpsModule): String? {
val rootUrl = getFirstContentRootUrl(module) ?: return null
val rootDir = File(JpsPathUtil.urlToPath(rootUrl))
if (!rootDir.isDirectory) return null
val file = File(rootDir, ImageCollector.ROBOTS_FILE_NAME)
if (!file.exists()) return null
val prefix = "name:"
var moduleName: String? = null
file.forEachLine {
if (it.startsWith(prefix)) {
val name = it.substring(prefix.length).trim()
if (name.isNotEmpty()) moduleName = name
}
}
return moduleName
}
private fun getFirstContentRootUrl(module: JpsModule): String? {
return module.contentRootsList.urls.firstOrNull()
}
private fun className(name: String): String {
val answer = StringBuilder()
name.removePrefix("intellij.").split("-", "_", ".").forEach {
answer.append(capitalize(it))
}
return toJavaIdentifier(answer.toString())
}
private fun iconName(name: String): String {
val id = capitalize(name.substring(0, name.lastIndexOf('.')))
return toJavaIdentifier(id)
}
private fun toJavaIdentifier(id: String): String {
val sb = StringBuilder()
id.forEach {
if (Character.isJavaIdentifierPart(it)) {
sb.append(it)
}
else {
sb.append('_')
}
}
if (Character.isJavaIdentifierStart(sb.first())) {
return sb.toString()
}
else {
return "_" + sb.toString()
}
}
private fun capitalize(name: String): String {
if (name.length == 2) return name.toUpperCase()
return name.capitalize()
}
// legacy ordering
private val NAME_COMPARATOR: Comparator<String> = compareBy { it.toLowerCase() + "." }
}
| apache-2.0 | 8bf32dfb5865cb8e4eaa62671908920d | 34.365449 | 139 | 0.648943 | 4.378856 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.