repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/settings/SettingsFragment.kt | 1 | 8888 | package net.simonvt.cathode.settings
import android.Manifest.permission
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build.VERSION_CODES
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreference
import net.simonvt.android.colorpicker.ColorPickerDialog
import net.simonvt.android.colorpicker.ColorPickerSwatch.OnColorSelectedListener
import net.simonvt.cathode.R
import net.simonvt.cathode.common.ui.FragmentsUtils
import net.simonvt.cathode.common.ui.adapter.Adapters
import net.simonvt.cathode.common.util.Intents
import net.simonvt.cathode.common.util.VersionCodes
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns
import net.simonvt.cathode.provider.ProviderSchematic.Episodes
import net.simonvt.cathode.settings.ShowOffsetDialog.ShowOffsetSelectedListener
import net.simonvt.cathode.settings.UpcomingTime.WEEKS_1
import net.simonvt.cathode.settings.UpcomingTimeDialog.UpcomingTimeSelectedListener
import net.simonvt.cathode.settings.hidden.HiddenItems
import net.simonvt.cathode.settings.login.LoginActivity
import timber.log.Timber
import javax.inject.Inject
class SettingsFragment @Inject constructor(private val upcomingTimePreference: UpcomingTimePreference) :
PreferenceFragmentCompat(), UpcomingTimeSelectedListener, OnColorSelectedListener,
ShowOffsetSelectedListener {
private lateinit var syncCalendar: SwitchPreference
private var isTablet: Boolean = false
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
isTablet = resources.getBoolean(R.bool.isTablet)
}
override fun onCreatePreferences(inState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.settings_general)
syncCalendar = findPreference<Preference>(Settings.CALENDAR_SYNC) as SwitchPreference
syncCalendar.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { preference, newValue ->
val checked = newValue as Boolean
syncCalendar.isChecked = checked
if (VersionCodes.isAtLeastM()) {
if (checked && !Permissions.hasCalendarPermission(activity)) {
requestPermission()
}
} else {
Accounts.requestCalendarSync(activity)
}
true
}
findPreference<Preference>("calendarColor")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
val calendarColor =
Settings.get(activity).getInt(Settings.CALENDAR_COLOR, Settings.CALENDAR_COLOR_DEFAULT)
val size = if (isTablet) ColorPickerDialog.SIZE_LARGE else ColorPickerDialog.SIZE_SMALL
val dialog = ColorPickerDialog.newInstance(
R.string.preference_calendar_color,
Settings.CALENDAR_COLORS,
calendarColor,
5,
size
)
dialog.setTargetFragment(this@SettingsFragment, 0)
dialog.show(requireFragmentManager(), DIALOG_COLOR_PICKER)
if (Settings.get(activity).getBoolean(Settings.CALENDAR_SYNC, false)) {
Accounts.requestCalendarSync(activity)
}
true
}
findPreference<Preference>("notifications")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
startActivity(
Intent(
activity,
NotificationSettingsActivity::class.java
)
)
true
}
findPreference<Preference>("hiddenItems")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
startActivity(Intent(activity, HiddenItems::class.java))
true
}
findPreference<Preference>("upcomingTime")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
val upcomingTime = UpcomingTime.fromValue(
Settings.get(activity).getLong(
Settings.UPCOMING_TIME,
WEEKS_1.cacheTime
)
)
val dialog = FragmentsUtils.instantiate(
requireFragmentManager(),
UpcomingTimeDialog::class.java,
UpcomingTimeDialog.getArgs(upcomingTime)
)
dialog.setTargetFragment(this@SettingsFragment, 0)
dialog.show(requireFragmentManager(), DIALOG_UPCOMING_TIME)
true
}
findPreference<Preference>(Settings.SHOWS_AVOID_SPOILERS)!!.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { preference, newValue ->
Adapters.notifyAdapters()
if (Settings.get(activity).getBoolean(Settings.CALENDAR_SYNC, false)) {
Accounts.requestCalendarSync(activity)
}
true
}
findPreference<Preference>(Settings.SHOWS_OFFSET)!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
val offset = FirstAiredOffsetPreference.getInstance().offsetHours
val dialog = FragmentsUtils.instantiate(
requireFragmentManager(),
ShowOffsetDialog::class.java,
ShowOffsetDialog.getArgs(offset)
)
dialog.setTargetFragment(this@SettingsFragment, 0)
dialog.show(requireFragmentManager(), DIALOG_SHOW_OFFSET)
true
}
val traktLink = findPreference<Preference>("traktLink")
val traktUnlink = findPreference<Preference>("traktUnlink")
traktLink!!.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val i = Intent(activity, LoginActivity::class.java)
i.putExtra(LoginActivity.EXTRA_TASK, LoginActivity.TASK_LINK)
startActivity(i)
true
}
traktUnlink!!.onPreferenceClickListener = Preference.OnPreferenceClickListener {
FragmentsUtils.instantiate(requireFragmentManager(), LogoutDialog::class.java)
.show(requireFragmentManager(), DIALOG_LOGOUT)
true
}
if (TraktLinkSettings.isLinked(activity)) {
preferenceScreen.removePreference(traktLink)
} else {
preferenceScreen.removePreference(traktUnlink)
}
findPreference<Preference>("about")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
AboutDialog().show(requireFragmentManager(), DIALOG_ABOUT)
true
}
findPreference<Preference>("privacy")!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
Intents.openUrl(requireActivity(), getString(R.string.privacy_policy_url))
true
}
}
@RequiresApi(VERSION_CODES.M)
private fun requestPermission() {
requestPermissions(
arrayOf(permission.READ_CALENDAR, permission.WRITE_CALENDAR),
PERMISSION_REQUEST_CALENDAR
)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == PERMISSION_REQUEST_CALENDAR) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Timber.d("Calendar permission granted")
Accounts.requestCalendarSync(activity)
} else {
Timber.d("Calendar permission not granted")
}
}
}
override fun onUpcomingTimeSelected(value: UpcomingTime) {
upcomingTimePreference.set(value)
}
override fun onColorSelected(color: Int) {
val calendarColor =
Settings.get(activity).getInt(Settings.CALENDAR_COLOR, Settings.CALENDAR_COLOR_DEFAULT)
if (color != calendarColor) {
Settings.get(activity)
.edit()
.putInt(Settings.CALENDAR_COLOR, color)
.putBoolean(Settings.CALENDAR_COLOR_NEEDS_UPDATE, true)
.apply()
if (Permissions.hasCalendarPermission(activity)) {
Accounts.requestCalendarSync(activity)
}
}
}
override fun onShowOffsetSelected(offset: Int) {
val showOffset = FirstAiredOffsetPreference.getInstance().offsetHours
if (offset != showOffset) {
FirstAiredOffsetPreference.getInstance().set(offset)
val context = requireContext()
Thread(Runnable {
val values = ContentValues()
values.put(EpisodeColumns.LAST_MODIFIED, System.currentTimeMillis())
context.contentResolver.update(Episodes.EPISODES, values, null, null)
Accounts.requestCalendarSync(context)
}).start()
}
}
companion object {
private const val DIALOG_UPCOMING_TIME =
"net.simonvt.cathode.settings.SettingsFragment.upcomingTime"
private const val DIALOG_SHOW_OFFSET =
"net.simonvt.cathode.settings.SettingsFragment.showOffset"
private const val DIALOG_COLOR_PICKER =
"net.simonvt.cathode.settings.SettingsFragment.ColorPicker"
private const val DIALOG_LOGOUT = "net.simonvt.cathode.settings.SettingsFragment.logoutDialog"
private const val DIALOG_ABOUT = "net.simonvt.cathode.settings.SettingsFragment.aboutDialog"
private const val PERMISSION_REQUEST_CALENDAR = 11
}
}
| apache-2.0 |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/retry/AsyncRetryExecutor.kt | 1 | 5134 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.core.retry
import debop4k.core.loggerOf
import debop4k.core.retry.backoff.*
import debop4k.core.utils.Systems
import nl.komponents.kovenant.Promise
import java.lang.Exception
import java.util.concurrent.*
/**
* AsyncRetryExecutor
* @author debop [email protected]
*/
open class AsyncRetryExecutor
@JvmOverloads constructor(val scheduler: ScheduledExecutorService = DefaultExecutorService,
val retryPolicy: RetryPolicy = RetryPolicy.DEFAULT,
val backoff: Backoff = DEFAULT_BACKOFF,
val fixedDelay: Boolean = false) : RetryExecutor {
companion object {
@JvmField val DefaultExecutorService: ScheduledExecutorService
= Executors.newScheduledThreadPool(Systems.ProcessCount)
}
private val log = loggerOf(javaClass)
override fun doWithRetry(action: (RetryContext) -> Unit): Promise<Unit, Throwable> {
return getWithRetry { action(it) }
}
override fun <V> getWithRetry(callable: Callable<V>): Promise<V, Throwable> {
return getWithRetry { callable.call() }
}
override fun <V> getWithRetry(func: (RetryContext) -> V): Promise<V, Throwable> {
return scheduleImmediately(createTask(func))
}
override fun <V> getFutureWithRetry(func: (RetryContext) -> Promise<V, Throwable>): Promise<V, Throwable> {
return scheduleImmediately(createFutureTask(func))
}
/**
* 작업을 수행합니다.
*/
protected fun <V> scheduleImmediately(job: RetryJob<V>): Promise<V, Throwable> {
scheduler.schedule(job, 0, TimeUnit.MILLISECONDS)
return job.promise
}
private fun <V> createTask(func: (RetryContext) -> V): RetryJob<V>
= SyncRetryJob(func, this)
private fun <V> createFutureTask(func: (RetryContext) -> Promise<V, Throwable>): RetryJob<V>
= AsyncRetryJob<V>(func, this)
fun withScheduler(scheduler: ScheduledExecutorService): AsyncRetryExecutor
= AsyncRetryExecutor(scheduler, retryPolicy, backoff, fixedDelay)
fun withRetryPolicy(policy: RetryPolicy): AsyncRetryExecutor
= AsyncRetryExecutor(scheduler, policy, backoff, fixedDelay)
fun withBackoff(backoff: Backoff): AsyncRetryExecutor
= AsyncRetryExecutor(scheduler, retryPolicy, backoff, fixedDelay)
@JvmOverloads
fun withExponentialBackoff(initialDelayMillis: Long, multiplier: Double = DEFAULT_MULTIPLIER): AsyncRetryExecutor {
return withBackoff(ExponentialDelayBackoff(initialDelayMillis, multiplier))
}
@JvmOverloads
fun withFixedBackoff(delayMillis: Long = DEFAULT_PERIOD_MILLIS): AsyncRetryExecutor {
return withBackoff(FixedIntervalBackoff(delayMillis))
}
@JvmOverloads
fun withFixedRate(fixedDelay: Boolean = true): AsyncRetryExecutor {
return AsyncRetryExecutor(scheduler, retryPolicy, backoff, fixedDelay)
}
@JvmOverloads
fun withUniformJitter(range: Long = DEFAULT_RANDOM_RANGE_MILLIS): AsyncRetryExecutor
= withBackoff(backoff.withUniformJitter(range))
@JvmOverloads
fun withProportionalJitter(multiplier: Double = DEFAULT_MULTIPLIER): AsyncRetryExecutor
= withBackoff(backoff.withProportionalJitter(multiplier))
@JvmOverloads
fun withMinDelay(minDelayMillis: Long = DEFAULT_MIN_DELAY_MILLIS): AsyncRetryExecutor
= withBackoff(backoff.withMinDelay(minDelayMillis))
@JvmOverloads
fun withMaxDelay(maxDelayMillis: Long = DEFAULT_MAX_DELAY_MILLIS): AsyncRetryExecutor
= withBackoff(backoff.withMaxDelay(maxDelayMillis))
fun withMaxRetry(times: Int): AsyncRetryExecutor
= withRetryPolicy(retryPolicy.withMaxRetry(times))
fun dontRetry(): AsyncRetryExecutor
= withRetryPolicy(retryPolicy.dontRetry())
fun retryInfinitely(): AsyncRetryExecutor
= withMaxRetry(Int.MAX_VALUE)
fun withNoDelay(): AsyncRetryExecutor
= withBackoff(FixedIntervalBackoff(0L))
fun firstRetryNoDelay(): AsyncRetryExecutor
= withBackoff(backoff.withFirstRetryNoDelay())
fun retryOn(vararg retryOnExceptions: Class<out Exception>): AsyncRetryExecutor
= this.withRetryPolicy(retryPolicy.retryOn(*retryOnExceptions))
fun abortOn(vararg abortOnExceptions: Class<out Exception>): AsyncRetryExecutor
= this.withRetryPolicy(retryPolicy.abortOn(*abortOnExceptions))
fun retryIf(predicate: (Throwable?) -> Boolean): AsyncRetryExecutor
= this.withRetryPolicy(retryPolicy.retryIf(predicate))
fun abortIf(predicate: (Throwable?) -> Boolean): AsyncRetryExecutor
= this.withRetryPolicy(retryPolicy.abortIf(predicate))
} | apache-2.0 |
andreyfomenkov/green-cat | plugin/src/test/ru/fomenkov/plugin/repository/parser/JetifiedResourceParserTest.kt | 1 | 4999 | package ru.fomenkov.plugin.repository.parser
import org.junit.jupiter.api.Test
import ru.fomenkov.plugin.repository.JetifiedJarRepository
import kotlin.test.assertEquals
class JetifiedResourceParserTest {
private val parser = JetifiedResourceParser()
@Test
fun `Test JAR resources inside transformed directory`() {
// jetified, api
assertEquals(
JetifiedJarRepository.Entry("play-services-ads-identifier", "18.0.1"),
parser.parse("~/.gradle/caches/transforms-3/ee61fea61f93c586b4a5c9757532036a/transformed/jetified-play-services-ads-identifier-18.0.1-api.jar"),
)
// jetified
assertEquals(
JetifiedJarRepository.Entry("kotlin-stdlib", "1.5.31"),
parser.parse("~/.gradle/caches/transforms-3/624ba37502a20fb5cf6bcbefb0eca46d/transformed/jetified-kotlin-stdlib-1.5.31.jar"),
)
// api
assertEquals(
JetifiedJarRepository.Entry("ads-identifier", "1.0.0-alpha03"),
parser.parse("~/.gradle/caches/transforms-3/1665e7f6142dc066b4a4db113e2e8cdc/transformed/ads-identifier-1.0.0-alpha03-api.jar"),
)
// plain
assertEquals(
JetifiedJarRepository.Entry("media", "1.4.1"),
parser.parse("~/.gradle/caches/transforms-3/674bb7a92157d9ee02bd120f5791f911/transformed/media-1.4.1.jar"),
)
}
@Test
fun `Test AAR resources inside transformed directory`() {
// jetified, api
assertEquals(
JetifiedJarRepository.Entry("play-services-ads-identifier", "18.0.1"),
parser.parse("~/.gradle/caches/transforms-3/ee61fea61f93c586b4a5c9757532036a/transformed/jetified-play-services-ads-identifier-18.0.1-api.aar"),
)
// jetified
assertEquals(
JetifiedJarRepository.Entry("kotlin-stdlib", "1.5.31"),
parser.parse("~/.gradle/caches/transforms-3/624ba37502a20fb5cf6bcbefb0eca46d/transformed/jetified-kotlin-stdlib-1.5.31.aar"),
)
// api
assertEquals(
JetifiedJarRepository.Entry("ads-identifier", "1.0.0-alpha03"),
parser.parse("~/.gradle/caches/transforms-3/1665e7f6142dc066b4a4db113e2e8cdc/transformed/ads-identifier-1.0.0-alpha03-api.aar"),
)
// plain
assertEquals(
JetifiedJarRepository.Entry("media", "1.4.1"),
parser.parse("~/.gradle/caches/transforms-3/674bb7a92157d9ee02bd120f5791f911/transformed/media-1.4.1.aar"),
)
}
@Test
fun `Test JARS resources inside jars directory`() {
// jetified, api
assertEquals(
JetifiedJarRepository.Entry("core-icons-generated-25", "1.54.4-oldlibverify-SNAPSHOT"),
parser.parse("~/.gradle/caches/transforms-3/cf8cbc4e53bf5a40c0ed6af5c89d54ec/transformed/jetified-core-icons-generated-25-1.54.4-oldlibverify-SNAPSHOT-api/jars/classes.jar"),
)
// jetified
assertEquals(
JetifiedJarRepository.Entry("core-icons-generated-25", "1.54.4-oldlibverify-SNAPSHOT"),
parser.parse("~/.gradle/caches/transforms-3/cf8cbc4e53bf5a40c0ed6af5c89d54ec/transformed/jetified-core-icons-generated-25-1.54.4-oldlibverify-SNAPSHOT/jars/classes.jar"),
)
// api
assertEquals(
JetifiedJarRepository.Entry("core-icons-generated-25", "1.54.4-oldlibverify-SNAPSHOT"),
parser.parse("~/.gradle/caches/transforms-3/cf8cbc4e53bf5a40c0ed6af5c89d54ec/transformed/core-icons-generated-25-1.54.4-oldlibverify-SNAPSHOT-api/jars/classes.jar"),
)
// plain
assertEquals(
JetifiedJarRepository.Entry("core-icons-generated-25", "1.54.4-oldlibverify-SNAPSHOT"),
parser.parse("~/.gradle/caches/transforms-3/cf8cbc4e53bf5a40c0ed6af5c89d54ec/transformed/core-icons-generated-25-1.54.4-oldlibverify-SNAPSHOT/jars/classes.jar"),
)
}
@Test
fun `Test strange artifact version`() {
// jetified, api
assertEquals(
JetifiedJarRepository.Entry("cameraview", "5b2f0fff93"),
parser.parse("~/.gradle/caches/transforms-3/1c66649054b85a1e4c2801d896eca713/transformed/jetified-cameraview-5b2f0fff93-api.aar"),
)
// jetified
assertEquals(
JetifiedJarRepository.Entry("cameraview", "5b2f0fff93"),
parser.parse("~/.gradle/caches/transforms-3/1c66649054b85a1e4c2801d896eca713/transformed/jetified-cameraview-5b2f0fff93.aar"),
)
// api
assertEquals(
JetifiedJarRepository.Entry("cameraview", "5b2f0fff93"),
parser.parse("~/.gradle/caches/transforms-3/1c66649054b85a1e4c2801d896eca713/transformed/cameraview-5b2f0fff93-api.aar"),
)
// plain
assertEquals(
JetifiedJarRepository.Entry("cameraview", "5b2f0fff93"),
parser.parse("~/.gradle/caches/transforms-3/1c66649054b85a1e4c2801d896eca713/transformed/cameraview-5b2f0fff93.aar"),
)
}
} | apache-2.0 |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/common/gui/FluidDisplayPiece.kt | 1 | 1746 | package net.ndrei.teslapoweredthingies.common.gui
import net.minecraft.client.renderer.GlStateManager
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraftforge.fluids.Fluid
import net.minecraftforge.fluids.FluidStack
import net.ndrei.teslacorelib.gui.BasicContainerGuiPiece
import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer
import org.lwjgl.opengl.GL11
/**
* Created by CF on 2017-06-30.
*/
class FluidDisplayPiece(left: Int, top: Int, width: Int, height: Int, private val fluidGetter: () -> FluidStack?)
: BasicContainerGuiPiece(left, top, width, height) {
override fun drawBackgroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, partialTicks: Float, mouseX: Int, mouseY: Int) {
val fluid = this.fluidGetter() ?: return
this.drawFluid(container, fluid.fluid, guiX + this.left + 1, guiY + this.top + 1 , this.width - 2, this.height - 2)
}
private fun drawFluid(container: BasicTeslaGuiContainer<*>, fluid: Fluid?, x: Int, y: Int, w: Int, h: Int) {
if (fluid == null) {
return
}
val color = fluid.color
val still = fluid.flowing //.getStill(stack);
if (still != null) {
val sprite = container.mc.textureMapBlocks.getTextureExtry(still.toString()) ?: container.mc.textureMapBlocks.missingSprite
container.mc.textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE)
GL11.glColor3ub((color shr 16 and 0xFF).toByte(), (color shr 8 and 0xFF).toByte(), (color and 0xFF).toByte())
GlStateManager.enableBlend()
container.drawTexturedModalRect(
x, y, sprite!!, w, h)
GlStateManager.disableBlend()
}
}
}
| mit |
FHannes/intellij-community | platform/projectModel-api/src/com/intellij/openapi/project/ProjectUtilCore.kt | 2 | 2188 | /*
* 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.
*/
@file:JvmName("ProjectUtilCore")
package com.intellij.openapi.project
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.LocalFileProvider
import com.intellij.openapi.vfs.VirtualFile
fun displayUrlRelativeToProject(file: VirtualFile, url: String, project: Project, includeFilePath: Boolean, keepModuleAlwaysOnTheLeft: Boolean): String {
var result = url
val baseDir = project.baseDir
if (baseDir != null && includeFilePath) {
val projectHomeUrl = baseDir.presentableUrl
if (result.startsWith(projectHomeUrl)) {
result = "...${result.substring(projectHomeUrl.length)}"
}
}
if (SystemInfo.isMac && file.fileSystem is LocalFileProvider) {
val fileForJar = (file.fileSystem as LocalFileProvider).getLocalVirtualFileFor(file)
if (fileForJar != null) {
val libraryEntry = LibraryUtil.findLibraryEntry(file, project)
if (libraryEntry != null) {
if (libraryEntry is JdkOrderEntry) {
result = "$result - [${libraryEntry.jdkName}]"
}
else {
result = "$result - [${libraryEntry.presentableName}]"
}
}
else {
result = "$result - [${fileForJar.name}]"
}
}
}
val module = ModuleUtilCore.findModuleForFile(file, project) ?: return result
return if (!keepModuleAlwaysOnTheLeft && SystemInfo.isMac) {
"$result - [${module.name}]"
}
else {
"[${module.name}] - $result"
}
} | apache-2.0 |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/view/activity/GrassrootActivity.kt | 1 | 13438 | package za.org.grassroot2.view.activity
import android.accounts.AccountAuthenticatorResponse
import android.accounts.AccountManager
import android.accounts.AuthenticatorException
import android.accounts.OperationCanceledException
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.annotation.LayoutRes
import android.support.design.widget.Snackbar
import android.support.v4.app.DialogFragment
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.AppCompatDelegate
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import android.widget.Toast
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.gcm.GoogleCloudMessaging
import dagger.Lazy
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.include_progress_bar.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import timber.log.Timber
import za.org.grassroot.messaging.dto.MessageDTO
import za.org.grassroot2.GrassrootApplication
import za.org.grassroot2.R
import za.org.grassroot2.dagger.AppComponent
import za.org.grassroot2.dagger.activity.ActivityComponent
import za.org.grassroot2.dagger.activity.ActivityModule
import za.org.grassroot2.model.task.Meeting
import za.org.grassroot2.service.GCMPreferences
import za.org.grassroot2.services.OfflineReceiver
import za.org.grassroot2.services.SyncOfflineDataService
import za.org.grassroot2.services.account.AuthConstants
import za.org.grassroot2.services.rest.AddTokenInterceptor
import za.org.grassroot2.util.AlarmManagerHelper
import za.org.grassroot2.util.UserPreference
import za.org.grassroot2.util.ViewAnimation
import za.org.grassroot2.view.GrassrootView
import za.org.grassroot2.view.dialog.GenericErrorDialog
import za.org.grassroot2.view.dialog.GenericMessageDialog
import za.org.grassroot2.view.dialog.GenericSuccessDialog
import za.org.grassroot2.view.dialog.NoConnectionDialog
import java.io.IOException
import java.util.*
import javax.inject.Inject
abstract class GrassrootActivity : AppCompatActivity(), GrassrootView {
@Inject lateinit var accountManagerProvider: Lazy<AccountManager>
@Inject lateinit var userPreference: UserPreference
@Inject lateinit var jsonMaper: ObjectMapper
@get:LayoutRes protected abstract val layoutResourceId: Int
protected abstract fun onInject(component: ActivityComponent)
private var mRegistrationBroadcastReceiver: BroadcastReceiver? = null
private var isReceiverRegistered: Boolean = false
private var authResponse: AccountAuthenticatorResponse? = null
private var authResultBundle: Bundle? = null
protected var disposables = CompositeDisposable()
private var component: ActivityComponent? = null
override val activity: Activity
get() = this
val activityModule: ActivityModule
get() = ActivityModule(this)
val componenet: ActivityComponent
get() {
if (component == null) {
component = appComponent.plus(activityModule)
}
return component!!
}
val appComponent: AppComponent
get() = (application as GrassrootApplication).appComponent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
setContentView(R.layout.base_progress_container)
setContentLayout(layoutResourceId)
componenet.inject(this)
onInject(componenet)
authResponse = intent.getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)
if (authResponse != null) {
authResponse!!.onRequestContinued()
}
mRegistrationBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val currentToken = sharedPreferences.getString(GCMPreferences.CURRENT_GCM_TOKEN, null)
Timber.i("GCM token check finished. Current token: %s", currentToken)
closeProgressBar()
}
}
}
private fun registerReceiver() {
if (!isReceiverRegistered) {
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver!!,
IntentFilter(GCMPreferences.GCM_REGISTRATION_COMPLETE))
isReceiverRegistered = true
}
}
private fun setContentLayout(resId: Int) {
val parent = findViewById<View>(R.id.main_layout) as RelativeLayout
val v = LayoutInflater.from(this).inflate(resId, parent, false)
parent.addView(v)
}
protected fun loggedIn(): Boolean {
val accounts = accountManagerProvider.get().getAccountsByType(AuthConstants.ACCOUNT_TYPE)
return accounts.size != 0 && !TextUtils.isEmpty(accountManagerProvider.get().getUserData(accounts[0], AuthConstants.USER_DATA_LOGGED_IN))
}
override fun showMessageDialog(text: String) {
val dialog = GenericMessageDialog.newInstance(text)
dialog.show(supportFragmentManager, DIALOG_TAG)
}
override fun handleNoConnection() {
if (!userPreference.connectionInfoDisplayed()) {
val dialog: DialogFragment
if (loggedIn()) {
dialog = NoConnectionDialog.newInstance(NoConnectionDialog.TYPE_AUTHORIZED)
} else {
dialog = NoConnectionDialog.newInstance(NoConnectionDialog.TYPE_NOT_AUTHORIZED)
}
dialog.show(supportFragmentManager, DIALOG_TAG)
userPreference.setNoConnectionInfoDisplayed(true)
AlarmManagerHelper.scheduleAlarmForBroadcastReceiver(this, OfflineReceiver::class.java)
}
}
override fun handleNoConnectionUpload() {
if (userPreference.connectionInfoDisplayed()) {
showNoConnectionMessage()
} else {
handleNoConnection()
}
}
override fun showSuccessSnackbar(successMsg: Int) {
Snackbar.make(findViewById(android.R.id.content), successMsg, Toast.LENGTH_SHORT).show()
}
override fun showErrorDialog(errorMsg: Int) {
val dialog = GenericErrorDialog.newInstance(errorMsg)
dialog.show(supportFragmentManager, DIALOG_TAG)
}
override fun showErrorSnackbar(errorTextRes: Int) {
Snackbar.make(findViewById(android.R.id.content), errorTextRes, Toast.LENGTH_SHORT).show()
}
override fun showSuccessDialog(textRes: Int, okayListener: View.OnClickListener) {
val dialog = GenericSuccessDialog.newInstance(textRes, null, okayListener)
dialog.show(supportFragmentManager, DIALOG_TAG)
}
override fun launchActivity(cls: Class<*>, args: Bundle) {
val i = Intent(this, cls)
i.putExtras(args)
startActivity(i)
}
/**
* Set the result that is to be sent as the result of the request that caused this
* Activity to be launched. If result is null or this method is never called then
* the request will be canceled.
*
* @param result this is returned as the result of the AbstractAccountAuthenticator request
*/
fun setAccountAuthenticatorResult(result: Bundle) {
authResultBundle = result
}
/**
* Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present.
*/
override fun finish() {
if (authResponse != null) {
// send the result bundle back if set, otherwise send an error.
if (authResultBundle != null) {
authResponse!!.onResult(authResultBundle)
} else {
authResponse!!.onError(AccountManager.ERROR_CODE_CANCELED,
"canceled")
}
authResponse = null
}
super.finish()
}
override fun closeKeyboard() {
val view = currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
override fun showProgressBar() {
Timber.d("showing progress bar 1 in activity: %s", activity.toString())
progress?.let { ViewAnimation.fadeIn(progress!!) }
}
override fun closeProgressBar() {
Timber.d("showing progress bar 2 inside activity")
progress?.let { ViewAnimation.fadeOut(progress!!) }
}
override fun onPause() {
super.onPause()
EventBus.getDefault().unregister(this)
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver!!)
isReceiverRegistered = false
}
override fun onDestroy() {
super.onDestroy()
dismissDialogs()
if (!disposables.isDisposed) {
disposables.clear()
}
}
private fun dismissDialogs() {
val fragmentByTag = supportFragmentManager.findFragmentByTag(DIALOG_TAG)
if (fragmentByTag != null) {
(fragmentByTag as DialogFragment).dismiss()
}
}
override fun onResume() {
super.onResume()
EventBus.getDefault().register(this)
// if (loggedIn()) {
//
// if (checkPlayServices()) {
// Timber.e("Showing progress bar 3 in activity: %s", getActivity().toString());
// // start registration service in order to check token and register if not already registered
// showProgressBar();
// registerReceiver();
// Intent intent = new Intent(this, GCMRegistrationService.class);
// startService(intent);
// }
// }
}
@Subscribe(sticky = true)
fun tokenRefreshEvent(e: AddTokenInterceptor.TokenRefreshEvent) {
EventBus.getDefault().removeStickyEvent(e)
val accountManager = accountManagerProvider!!.get()
val accounts = accountManager.getAccountsByType(AuthConstants.ACCOUNT_TYPE)
accountManager.getAuthToken(accounts[0], AuthConstants.AUTH_TOKENTYPE, null, this, { future ->
try {
if (future.result.containsKey(AccountManager.KEY_AUTHTOKEN)) {
accountManager.setAuthToken(accounts[0], AuthConstants.AUTH_TOKENTYPE, future.result.getString(AccountManager.KEY_AUTHTOKEN))
accountManager.setUserData(accounts[0], AuthConstants.USER_DATA_CURRENT_TOKEN, future.result.getString(AccountManager.KEY_AUTHTOKEN))
}
} catch (e1: OperationCanceledException) {
e1.printStackTrace()
} catch (e1: IOException) {
e1.printStackTrace()
} catch (e1: AuthenticatorException) {
e1.printStackTrace()
}
}, null)
}
@Subscribe
fun notifyItemOutOfSync(e: SyncOfflineDataService.ObjectOutOfSyncEvent) {
if (e.syncable is Meeting) {
Snackbar.make(findViewById(android.R.id.content), e.msg!!, Snackbar.LENGTH_LONG).show()
}
}
override fun showNoConnectionMessage() {
Snackbar.make(findViewById(android.R.id.content), R.string.snackbar_offline, Snackbar.LENGTH_SHORT).show()
}
override fun hideKeyboard() {
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
private fun checkPlayServices(): Boolean {
val apiAvailability = GoogleApiAvailability.getInstance()
val resultCode = apiAvailability.isGooglePlayServicesAvailable(this)
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show()
} else {
Timber.i("This device is not supported.")
finish()
}
return false
}
return true
}
override fun sendCGMMessage(messageDTO: MessageDTO) {
try {
val gcm = GoogleCloudMessaging.getInstance(this)
val data = Bundle()
val msgJson = jsonMaper!!.writeValueAsString(messageDTO)
data.putString("body", msgJson)
val id = UUID.randomUUID().toString()
val senderId = getString(R.string.gcm_sender_id)
gcm.send("[email protected]", id, data)
} catch (ex: Exception) {
Timber.e(ex)
}
}
companion object {
const val DIALOG_TAG = "dialog"
const val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
}
}
| bsd-3-clause |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAHaltedPlaylistEngine/WhenSettingEngineToComplete.kt | 1 | 3833 | package com.lasthopesoftware.bluewater.client.playback.engine.GivenAHaltedPlaylistEngine
import com.lasthopesoftware.EmptyUrl
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListUtilities
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.KnownFileProperties
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.FilePropertiesContainer
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.IFilePropertiesContainerRepository
import com.lasthopesoftware.bluewater.client.browsing.library.access.ISpecificLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.access.PassThroughLibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine
import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement
import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CyclicalFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlaying
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository
import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager
import com.lasthopesoftware.bluewater.shared.UrlKeyHolder
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
class WhenSettingEngineToComplete {
companion object {
private val library = Library()
private var nowPlaying: NowPlaying? = null
@BeforeClass
@JvmStatic
fun before() {
val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider()
library.setId(1)
library.setSavedTracksString(
FileStringListUtilities.promiseSerializedFileStringList(
listOf(
ServiceFile(1),
ServiceFile(2),
ServiceFile(3),
ServiceFile(4),
ServiceFile(5)
)
).toFuture().get()
)
library.setNowPlayingId(0)
library.setRepeating(true)
val libraryProvider = mockk<ISpecificLibraryProvider>()
every { libraryProvider.library } returns Promise(library)
val libraryStorage = PassThroughLibraryStorage()
val filePropertiesContainerRepository = mockk<IFilePropertiesContainerRepository>()
every {
filePropertiesContainerRepository.getFilePropertiesContainer(UrlKeyHolder(EmptyUrl.url, ServiceFile(4)))
} returns FilePropertiesContainer(1, mapOf(Pair(KnownFileProperties.DURATION, "100")))
val repository = NowPlayingRepository(libraryProvider, libraryStorage)
val playbackEngine =
PlaybackEngine(
PreparedPlaybackQueueResourceManagement(
fakePlaybackPreparerProvider
) { 1 },
listOf(CompletingFileQueueProvider(), CyclicalFileQueueProvider()),
repository,
PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f))
)
playbackEngine.playToCompletion().toFuture().get()
nowPlaying = repository.nowPlaying.toFuture().get()
}
}
@Test
fun thenNowPlayingIsSetToNotRepeating() {
assertThat(nowPlaying!!.isRepeating).isFalse
}
}
| lgpl-3.0 |
ansman/okhttp | okhttp/src/test/java/okhttp3/internal/io/FileSystemTest.kt | 1 | 5220 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.io
import okhttp3.SimpleProvider
import okhttp3.TestUtil
import okio.buffer
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.io.TempDir
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource
import java.io.File
import java.io.IOException
class FileSystemParamProvider: SimpleProvider() {
override fun arguments() = listOf(
FileSystem.SYSTEM to TestUtil.windows,
InMemoryFileSystem() to false,
WindowsFileSystem(FileSystem.SYSTEM) to true,
WindowsFileSystem(InMemoryFileSystem()) to true
)
}
/**
* Test that our file system abstraction is consistent and sufficient for OkHttp's needs. We're
* particularly interested in what happens when open files are moved or deleted on Windows.
*/
class FileSystemTest {
@TempDir lateinit var temporaryFolder: File
private lateinit var fileSystem: FileSystem
private var windows: Boolean = false
internal fun setUp(fileSystem: FileSystem, windows: Boolean) {
this.fileSystem = fileSystem
this.windows = windows
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `delete open for writing fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val file = File(temporaryFolder, "file.txt")
expectIOExceptionOnWindows {
fileSystem.sink(file).use {
fileSystem.delete(file)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `delete open for appending fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val file = File(temporaryFolder, "file.txt")
file.write("abc")
expectIOExceptionOnWindows {
fileSystem.appendingSink(file).use {
fileSystem.delete(file)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `delete open for reading fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val file = File(temporaryFolder, "file.txt")
file.write("abc")
expectIOExceptionOnWindows {
fileSystem.source(file).use {
fileSystem.delete(file)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `rename target exists succeeds on all platforms`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val from = File(temporaryFolder, "from.txt")
val to = File(temporaryFolder, "to.txt")
from.write("source file")
to.write("target file")
fileSystem.rename(from, to)
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `rename source is open fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val from = File(temporaryFolder, "from.txt")
val to = File(temporaryFolder, "to.txt")
from.write("source file")
to.write("target file")
expectIOExceptionOnWindows {
fileSystem.source(from).use {
fileSystem.rename(from, to)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `rename target is open fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val from = File(temporaryFolder, "from.txt")
val to = File(temporaryFolder, "to.txt")
from.write("source file")
to.write("target file")
expectIOExceptionOnWindows {
fileSystem.source(to).use {
fileSystem.rename(from, to)
}
}
}
@ParameterizedTest
@ArgumentsSource(FileSystemParamProvider::class)
fun `delete contents of parent of file open for reading fails on Windows`(
parameters: Pair<FileSystem, Boolean>
) {
setUp(parameters.first, parameters.second)
val parentA = File(temporaryFolder, "a").also { it.mkdirs() }
val parentAB = File(parentA, "b")
val parentABC = File(parentAB, "c")
val file = File(parentABC, "file.txt")
file.write("child file")
expectIOExceptionOnWindows {
fileSystem.source(file).use {
fileSystem.deleteContents(parentA)
}
}
}
private fun File.write(content: String) {
fileSystem.sink(this).buffer().use {
it.writeUtf8(content)
}
}
private fun expectIOExceptionOnWindows(block: () -> Unit) {
try {
block()
assertThat(windows).isFalse()
} catch (_: IOException) {
assertThat(windows).isTrue()
}
}
}
| apache-2.0 |
AoEiuV020/PaNovel | pager/src/main/java/cc/aoeiuv020/pager/Size.kt | 1 | 139 | package cc.aoeiuv020.pager
/**
*
* Created by AoEiuV020 on 2017.12.08-00:22:05.
*/
data class Size(var width: Int, var height: Int) {
} | gpl-3.0 |
tasks/tasks | app/src/main/java/org/tasks/data/Filter.kt | 1 | 2679 | package org.tasks.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.todoroo.andlib.utility.AndroidUtilities
import com.todoroo.astrid.api.FilterListItem.NO_ORDER
import org.tasks.Strings
import org.tasks.themes.CustomIcons.FILTER
@Entity(tableName = "filters")
class Filter {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "_id")
@Transient
var id: Long = 0
@ColumnInfo(name = "title")
var title: String? = null
@ColumnInfo(name = "sql")
private var sql: String? = null
@ColumnInfo(name = "values")
var values: String? = null
@ColumnInfo(name = "criterion")
var criterion: String? = null
@ColumnInfo(name = "f_color")
private var color: Int? = 0
@ColumnInfo(name = "f_icon")
private var icon: Int? = -1
@ColumnInfo(name = "f_order")
var order = NO_ORDER
// TODO: replace dirty hack for missing column
fun getSql(): String = sql!!.replace("tasks.userId=0", "1")
fun setSql(sql: String?) {
this.sql = sql
}
val valuesAsMap: Map<String, Any>?
get() = if (Strings.isNullOrEmpty(values)) null else AndroidUtilities.mapFromSerializedString(values)
@Suppress("RedundantNullableReturnType")
fun getColor(): Int? = color ?: 0
fun setColor(color: Int?) {
this.color = color
}
@Suppress("RedundantNullableReturnType")
fun getIcon(): Int? = icon ?: FILTER
fun setIcon(icon: Int?) {
this.icon = icon
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Filter) return false
if (id != other.id) return false
if (title != other.title) return false
if (sql != other.sql) return false
if (values != other.values) return false
if (criterion != other.criterion) return false
if (color != other.color) return false
if (icon != other.icon) return false
if (order != other.order) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + (title?.hashCode() ?: 0)
result = 31 * result + (sql?.hashCode() ?: 0)
result = 31 * result + (values?.hashCode() ?: 0)
result = 31 * result + (criterion?.hashCode() ?: 0)
result = 31 * result + (color ?: 0)
result = 31 * result + (icon ?: 0)
result = 31 * result + order
return result
}
override fun toString(): String =
"Filter(id=$id, title=$title, sql=$sql, values=$values, criterion=$criterion, color=$color, icon=$icon, order=$order)"
} | gpl-3.0 |
dafi/photoshelf | core/src/main/java/com/ternaryop/photoshelf/util/menu/MenuExt.kt | 1 | 192 | package com.ternaryop.photoshelf.util.menu
import android.view.Menu
fun Menu.enableAll(isEnabled: Boolean) {
for (i in 0 until size()) {
getItem(i).isEnabled = isEnabled
}
}
| mit |
Light-Team/ModPE-IDE-Source | editorkit/src/main/kotlin/com/brackeys/ui/editorkit/utils/LinesCollection.kt | 1 | 2617 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* 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.brackeys.ui.editorkit.utils
class LinesCollection : Iterable<LinesCollection.Line> {
val lineCount: Int
get() = lines.size
private val lines = mutableListOf(Line(0))
fun add(line: Int, index: Int) {
lines.add(line, Line(index))
}
fun remove(line: Int) {
if (line != 0) {
lines.removeAt(line)
}
}
fun clear() {
lines.clear()
lines.add(Line(0))
}
fun shiftIndexes(fromLine: Int, shiftBy: Int) {
if (fromLine <= 0) {
return
}
if (fromLine < lineCount) {
var i = fromLine
while (i < lineCount) {
val newIndex = getIndexForLine(i) + shiftBy
if (i <= 0 || newIndex > 0) {
lines[i].start = newIndex
} else {
remove(i)
i--
}
i++
}
}
}
fun getIndexForLine(line: Int): Int {
return if (line >= lineCount) {
-1
} else {
lines[line].start
}
}
fun getLineForIndex(index: Int): Int {
var first = 0
var last = lineCount - 1
while (first < last) {
val mid = (first + last) / 2
if (index < getIndexForLine(mid)) {
last = mid
} else if (index <= getIndexForLine(mid) || index < getIndexForLine(mid + 1)) {
return mid
} else {
first = mid + 1
}
}
return lineCount - 1
}
fun getLine(line: Int): Line {
if (line > -1 && line < lineCount) {
return lines[line]
}
return Line(0)
}
override fun iterator(): Iterator<Line> {
return lines.iterator()
}
data class Line(var start: Int) : Comparable<Line> {
override fun compareTo(other: Line): Int {
return start - other.start
}
}
} | apache-2.0 |
michaelgallacher/intellij-community | plugins/settings-repository/src/copyAppSettingsToRepository.kt | 3 | 3632 | /*
* 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 org.jetbrains.settingsRepository
import com.intellij.configurationStore.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.stateStore
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.io.directoryStreamIfExists
import com.intellij.util.io.isFile
import com.intellij.util.io.readBytes
import com.intellij.util.io.systemIndependentPath
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
fun copyLocalConfig(storageManager: StateStorageManagerImpl = ApplicationManager.getApplication()!!.stateStore.stateStorageManager as StateStorageManagerImpl) {
val streamProvider = StreamProviderWrapper.getOriginalProvider(storageManager.streamProvider)!! as IcsManager.IcsStreamProvider
val fileToComponents = getExportableComponentsMap(true, false, storageManager)
fileToComponents.keys.forEachGuaranteed { file ->
var fileSpec: String
try {
val absolutePath = file.toAbsolutePath().systemIndependentPath
fileSpec = removeMacroIfStartsWith(storageManager.collapseMacros(absolutePath), ROOT_CONFIG)
if (fileSpec == absolutePath) {
// we have not experienced such problem yet, but we are just aware
val canonicalPath = file.toRealPath().systemIndependentPath
if (canonicalPath != absolutePath) {
fileSpec = removeMacroIfStartsWith(storageManager.collapseMacros(canonicalPath), ROOT_CONFIG)
}
}
}
catch (e: NoSuchFileException) {
return@forEachGuaranteed
}
val roamingType = getRoamingType(fileToComponents.get(file)!!)
if (file.isFile()) {
val fileBytes = file.readBytes()
streamProvider.doSave(fileSpec, fileBytes, fileBytes.size, roamingType)
}
else {
saveDirectory(file, fileSpec, roamingType, streamProvider)
}
}
}
private fun saveDirectory(parent: Path, parentFileSpec: String, roamingType: RoamingType, streamProvider: IcsManager.IcsStreamProvider) {
parent.directoryStreamIfExists {
for (file in it) {
val childFileSpec = "$parentFileSpec/${file.fileName}"
if (file.isFile()) {
val fileBytes = Files.readAllBytes(file)
streamProvider.doSave(childFileSpec, fileBytes, fileBytes.size, roamingType)
}
else {
saveDirectory(file, childFileSpec, roamingType, streamProvider)
}
}
}
}
private fun getRoamingType(components: Collection<ExportableItem>): RoamingType {
for (component in components) {
if (component is ExportableItem) {
return component.roamingType
}
// else if (component is PersistentStateComponent<*>) {
// val stateAnnotation = component.javaClass.getAnnotation(State::class.java)
// if (stateAnnotation != null) {
// val storages = stateAnnotation.storages
// if (!storages.isEmpty()) {
// return storages[0].roamingType
// }
// }
// }
}
return RoamingType.DEFAULT
} | apache-2.0 |
pedroSG94/rtmp-streamer-java | rtsp/src/main/java/com/pedro/rtsp/rtsp/commands/CommandsManager.kt | 1 | 9760 | /*
* Copyright (C) 2021 pedroSG94.
*
* 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.pedro.rtsp.rtsp.commands
import android.util.Base64
import android.util.Log
import com.pedro.rtsp.BuildConfig
import com.pedro.rtsp.rtsp.Protocol
import com.pedro.rtsp.rtsp.commands.SdpBody.createAacBody
import com.pedro.rtsp.rtsp.commands.SdpBody.createH264Body
import com.pedro.rtsp.rtsp.commands.SdpBody.createH265Body
import com.pedro.rtsp.utils.AuthUtil.getMd5Hash
import com.pedro.rtsp.utils.RtpConstants
import com.pedro.rtsp.utils.getVideoStartCodeSize
import java.io.BufferedReader
import java.io.IOException
import java.nio.ByteBuffer
import java.util.regex.Pattern
/**
* Created by pedro on 12/02/19.
*
* Class to create request to server and parse response from server.
*/
open class CommandsManager {
var host: String? = null
private set
var port = 0
private set
var path: String? = null
private set
var sps: ByteArray? = null
private set
var pps: ByteArray? = null
private set
private var cSeq = 0
private var sessionId: String? = null
private val timeStamp: Long
var sampleRate = 32000
var isStereo = true
var protocol: Protocol = Protocol.TCP
var videoDisabled = false
var audioDisabled = false
//For udp
val audioClientPorts = intArrayOf(5000, 5001)
val videoClientPorts = intArrayOf(5002, 5003)
val audioServerPorts = intArrayOf(5004, 5005)
val videoServerPorts = intArrayOf(5006, 5007)
//For H265
var vps: ByteArray? = null
private set
//For auth
var user: String? = null
private set
var password: String? = null
private set
companion object {
private const val TAG = "CommandsManager"
private var authorization: String? = null
}
init {
val uptime = System.currentTimeMillis()
timeStamp = uptime / 1000 shl 32 and ((uptime - uptime / 1000 * 1000 shr 32)
/ 1000) // NTP timestamp
}
private fun getData(byteBuffer: ByteBuffer?): ByteArray? {
return if (byteBuffer != null) {
val startCodeSize = byteBuffer.getVideoStartCodeSize()
val bytes = ByteArray(byteBuffer.capacity() - startCodeSize)
byteBuffer.position(startCodeSize)
byteBuffer[bytes, 0, bytes.size]
bytes
} else {
null
}
}
private fun encodeToString(bytes: ByteArray?): String {
bytes?.let {
return Base64.encodeToString(it, 0, it.size, Base64.NO_WRAP)
}
return ""
}
fun setVideoInfo(sps: ByteBuffer?, pps: ByteBuffer?, vps: ByteBuffer?) {
this.sps = getData(sps)
this.pps = getData(pps)
this.vps = getData(vps) //H264 has no vps so if not null assume H265
}
fun setAudioInfo(sampleRate: Int, isStereo: Boolean) {
this.isStereo = isStereo
this.sampleRate = sampleRate
}
fun setAuth(user: String?, password: String?) {
this.user = user
this.password = password
}
fun setUrl(host: String?, port: Int, path: String?) {
this.host = host
this.port = port
this.path = path
}
fun clear() {
sps = null
pps = null
vps = null
retryClear()
}
fun retryClear() {
cSeq = 0
sessionId = null
}
private val spsString: String
get() = encodeToString(sps)
private val ppsString: String
get() = encodeToString(pps)
private val vpsString: String
get() = encodeToString(vps)
private fun addHeaders(): String {
return "CSeq: ${++cSeq}\r\n" +
"User-Agent: ${BuildConfig.LIBRARY_PACKAGE_NAME} ${BuildConfig.VERSION_NAME}\r\n" +
(if (sessionId == null) "" else "Session: $sessionId\r\n") +
(if (authorization == null) "" else "Authorization: $authorization\r\n")
}
private fun createBody(): String {
var videoBody = ""
if (!videoDisabled) {
videoBody = if (vps == null) {
createH264Body(RtpConstants.trackVideo, spsString, ppsString)
} else {
createH265Body(RtpConstants.trackVideo, spsString, ppsString, vpsString)
}
}
var audioBody = ""
if (!audioDisabled) {
audioBody = createAacBody(RtpConstants.trackAudio, sampleRate, isStereo)
}
return "v=0\r\n" +
"o=- $timeStamp $timeStamp IN IP4 127.0.0.1\r\n" +
"s=Unnamed\r\n" +
"i=N/A\r\n" +
"c=IN IP4 $host\r\n" +
"t=0 0\r\n" +
"a=recvonly\r\n" +
videoBody + audioBody
}
private fun createAuth(authResponse: String): String {
val authPattern = Pattern.compile("realm=\"(.+)\",\\s+nonce=\"(\\w+)\"", Pattern.CASE_INSENSITIVE)
val matcher = authPattern.matcher(authResponse)
//digest auth
return if (matcher.find()) {
Log.i(TAG, "using digest auth")
val realm = matcher.group(1)
val nonce = matcher.group(2)
val hash1 = getMd5Hash("$user:$realm:$password")
val hash2 = getMd5Hash("ANNOUNCE:rtsp://$host:$port$path")
val hash3 = getMd5Hash("$hash1:$nonce:$hash2")
"Digest username=\"$user\", realm=\"$realm\", nonce=\"$nonce\", uri=\"rtsp://$host:$port$path\", response=\"$hash3\""
//basic auth
} else {
Log.i(TAG, "using basic auth")
val data = "$user:$password"
val base64Data = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT)
"Basic $base64Data"
}
}
//Commands
fun createOptions(): String {
val options = "OPTIONS rtsp://$host:$port$path RTSP/1.0\r\n" + addHeaders() + "\r\n"
Log.i(TAG, options)
return options
}
open fun createSetup(track: Int): String {
val udpPorts = if (track == RtpConstants.trackVideo) videoClientPorts else audioClientPorts
val params = if (protocol === Protocol.UDP) {
"UDP;unicast;client_port=${udpPorts[0]}-${udpPorts[1]};mode=record"
} else {
"TCP;unicast;interleaved=${2 * track}-${2 * track + 1};mode=record"
}
val setup = "SETUP rtsp://$host:$port$path/streamid=$track RTSP/1.0\r\n" +
"Transport: RTP/AVP/$params\r\n" +
addHeaders() + "\r\n"
Log.i(TAG, setup)
return setup
}
fun createRecord(): String {
val record = "RECORD rtsp://$host:$port$path RTSP/1.0\r\n" +
"Range: npt=0.000-\r\n" + addHeaders() + "\r\n"
Log.i(TAG, record)
return record
}
fun createAnnounce(): String {
val body = createBody()
val announce = "ANNOUNCE rtsp://$host:$port$path RTSP/1.0\r\n" +
"Content-Type: application/sdp\r\n" +
addHeaders() +
"Content-Length: ${body.length}\r\n\r\n" +
body
Log.i(TAG, announce)
return announce
}
fun createAnnounceWithAuth(authResponse: String): String {
authorization = createAuth(authResponse)
Log.i("Auth", "$authorization")
return createAnnounce()
}
fun createTeardown(): String {
val teardown = "TEARDOWN rtsp://$host:$port$path RTSP/1.0\r\n" + addHeaders() + "\r\n"
Log.i(TAG, teardown)
return teardown
}
//Response parser
fun getResponse(reader: BufferedReader?, method: Method = Method.UNKNOWN): Command {
reader?.let { br ->
return try {
var response = ""
var line: String?
while (br.readLine().also { line = it } != null) {
response += "${line ?: ""}\n"
//end of response
if (line?.length ?: 0 < 3) break
}
Log.i(TAG, response)
if (method == Method.UNKNOWN) {
Command.parseCommand(response)
} else {
val command = Command.parseResponse(method, response)
getSession(command.text)
if (command.method == Method.SETUP && protocol == Protocol.UDP) {
getServerPorts(command.text)
}
command
}
} catch (e: IOException) {
Log.e(TAG, "read error", e)
Command(method, cSeq, -1, "")
}
}
return Command(method, cSeq, -1, "")
}
private fun getSession(response: String) {
val rtspPattern = Pattern.compile("Session:(\\s?\\w+)")
val matcher = rtspPattern.matcher(response)
if (matcher.find()) {
sessionId = matcher.group(1) ?: ""
sessionId?.let {
val temp = it.split(";")[0]
sessionId = temp.trim()
}
}
}
private fun getServerPorts(response: String) {
var isAudio = true
val clientPattern = Pattern.compile("client_port=([0-9]+)-([0-9]+)")
val clientMatcher = clientPattern.matcher(response)
if (clientMatcher.find()) {
val port = (clientMatcher.group(1) ?: "-1").toInt()
isAudio = port == audioClientPorts[0]
}
val rtspPattern = Pattern.compile("server_port=([0-9]+)-([0-9]+)")
val matcher = rtspPattern.matcher(response)
if (matcher.find()) {
if (isAudio) {
audioServerPorts[0] = (matcher.group(1) ?: "${audioClientPorts[0]}").toInt()
audioServerPorts[1] = (matcher.group(2) ?: "${audioClientPorts[1]}").toInt()
} else {
videoServerPorts[0] = (matcher.group(1) ?: "${videoClientPorts[0]}").toInt()
videoServerPorts[1] = (matcher.group(2) ?: "${videoClientPorts[1]}").toInt()
}
}
}
//Unused commands
fun createPause(): String {
return ""
}
fun createPlay(): String {
return ""
}
fun createGetParameter(): String {
return ""
}
fun createSetParameter(): String {
return ""
}
fun createRedirect(): String {
return ""
}
} | apache-2.0 |
robertwb/incubator-beam | learning/katas/kotlin/Common Transforms/Aggregation/Max/test/org/apache/beam/learning/katas/commontransforms/aggregation/max/TaskTest.kt | 9 | 1559 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.learning.katas.commontransforms.aggregation.max
import org.apache.beam.learning.katas.commontransforms.aggregation.max.Task.applyTransform
import org.apache.beam.sdk.testing.PAssert
import org.apache.beam.sdk.testing.TestPipeline
import org.apache.beam.sdk.transforms.Create
import org.junit.Rule
import org.junit.Test
class TaskTest {
@get:Rule
@Transient
val testPipeline: TestPipeline = TestPipeline.create()
@Test
fun common_transforms_aggregation_max() {
val values = Create.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val numbers = testPipeline.apply(values)
val results = applyTransform(numbers)
PAssert.that(results).containsInAnyOrder(10)
testPipeline.run().waitUntilFinish()
}
} | apache-2.0 |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/RootParameter.kt | 1 | 1661 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.parameters
import uk.co.nickthecoder.paratask.TaskDescription
class RootParameter(val taskD: TaskDescription, description: String)
: SimpleGroupParameter("root", description = description) {
override fun findTaskD(): TaskDescription = taskD
override fun findRoot(): RootParameter? = this
fun valueParameters(): List<ValueParameter<*>> {
val result = mutableListOf<ValueParameter<*>>()
fun addAll(group: GroupParameter) {
group.children.forEach { child ->
if (child is ValueParameter<*>) {
result.add(child)
}
if (child is GroupParameter) {
addAll(child)
}
}
}
addAll(this)
return result
}
override fun copy() :RootParameter {
val result =RootParameter(taskD = taskD, description = description)
copyChildren(result)
return result
}
}
| gpl-3.0 |
arturbosch/detekt | detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/KtLintLineColCalculator.kt | 1 | 2751 | package io.gitlab.arturbosch.detekt.formatting
/**
* This object provides helper methods for calculation line and column number based on provided offset.
*
* This code duplicates [KtLint.normalizeText] and [KtLint.calculateLineColByOffset] methods,
* since they are deprecated and probably will be removed in next releases.
*/
object KtLintLineColCalculator {
private const val UTF8_BOM = "\uFEFF"
fun normalizeText(text: String): String {
return text
.replace("\r\n", "\n")
.replace("\r", "\n")
.replaceFirst(UTF8_BOM, "")
}
fun calculateLineColByOffset(
text: String
): (offset: Int) -> Pair<Int, Int> {
return buildPositionInTextLocator(text)
}
private fun buildPositionInTextLocator(
text: String
): (offset: Int) -> Pair<Int, Int> {
val textLength = text.length
val arr = ArrayList<Int>()
var endOfLineIndex = -1
do {
arr.add(endOfLineIndex + 1)
endOfLineIndex = text.indexOf('\n', endOfLineIndex + 1)
} while (endOfLineIndex != -1)
arr.add(textLength + if (arr.last() == textLength) 1 else 0)
val segmentTree = SegmentTree(arr.toIntArray())
return { offset ->
val line = segmentTree.indexOf(offset)
if (line != -1) {
val col = offset - segmentTree.get(line).left
line + 1 to col + 1
} else {
1 to 1
}
}
}
private class SegmentTree(
sortedArray: IntArray
) {
init {
require(sortedArray.size > 1) { "At least two data points are required" }
sortedArray.reduce { current, next ->
require(current <= next) { "Data points are not sorted (ASC)" }
next
}
}
private val segments: List<Segment> = sortedArray
.dropLast(1)
.mapIndexed { index: Int, element: Int ->
Segment(element, sortedArray[index + 1] - 1)
}
fun get(i: Int): Segment = segments[i]
fun indexOf(v: Int): Int = binarySearch(v, 0, segments.size - 1)
private fun binarySearch(
v: Int,
l: Int,
r: Int
): Int = when {
l > r -> -1
else -> {
val i = l + (r - l) / 2
val s = segments[i]
if (v < s.left) {
binarySearch(v, l, i - 1)
} else {
if (s.right < v) binarySearch(v, i + 1, r) else i
}
}
}
}
private data class Segment(
val left: Int,
val right: Int
)
}
| apache-2.0 |
gladed/kotlin-late | src/main/java/com/gladed/late/package.kt | 1 | 515 | package com.gladed.late
import com.gladed.util.Runner
/** Begin background work on the specified [Runner] */
fun <Result> work(runner: Runner, block: () -> Result) = Late(runner, block)
/** Begin background work on [Late.defaultRunner] */
fun <Result> work(block: () -> Result) = Late(block)
/** Return a [Late] containing a successful result value */
fun <Result> pass(value: Result) = Late.pass(value)
/** Return a [Late] containing an error */
fun <Result> fail(error: Exception) = Late.fail<Result>(error)
| apache-2.0 |
chimbori/crux | src/main/kotlin/com/chimbori/crux/api/Fields.kt | 1 | 1885 | package com.chimbori.crux.api
/** Well-known keys to use in [Resource.metadata]. */
public object Fields {
public const val TITLE: String = "title"
public const val DESCRIPTION: String = "description"
public const val SITE_NAME: String = "site-name"
public const val LANGUAGE: String = "language"
public const val DISPLAY: String = "display"
public const val ORIENTATION: String = "orientation"
public const val PUBLISHED_AT: String = "published_at"
public const val MODIFIED_AT: String = "modified_at"
public const val THEME_COLOR_HEX: String = "theme-color-hex"
public const val THEME_COLOR_HTML: String = "theme-color-html" // Named colors like "aliceblue"
public const val BACKGROUND_COLOR_HEX: String = "background-color-hex"
public const val BACKGROUND_COLOR_HTML: String = "background-color-html" // Named colors like "aliceblue"
public const val CANONICAL_URL: String = "canonical-url"
public const val AMP_URL: String = "amp-url"
public const val FAVICON_URL: String = "favicon-url"
public const val BANNER_IMAGE_URL: String = "banner-image-url"
public const val FEED_URL: String = "feed-url"
public const val VIDEO_URL: String = "video-url"
public const val WEB_APP_MANIFEST_URL: String = "web-app-manifest-url" // https://www.w3.org/TR/appmanifest/
public const val NEXT_PAGE_URL: String = "next-page-url"
public const val PREVIOUS_PAGE_URL: String = "previous-page-url"
// For image or video resources only.
public const val ALT_TEXT: String = "alt-text"
public const val WIDTH_PX: String = "width-px"
public const val HEIGHT_PX: String = "height-px"
// For articles (estimated reading time) and audio/video content (playback duration).
public const val DURATION_MS: String = "duration-ms"
public const val TWITTER_HANDLE: String = "twitter-handle"
public const val KEYWORDS_CSV: String = "keywords-csv"
}
| apache-2.0 |
d9n/intellij-rust | src/test/kotlin/org/rust/ide/surroundWith/expression/RsWithNotSurrounderTest.kt | 1 | 1329 | package org.rust.ide.surroundWith.expression
import org.rust.ide.surroundWith.RsSurrounderTestBase
class RsWithNotSurrounderTest : RsSurrounderTestBase(RsWithNotSurrounder()) {
fun testSimple() {
doTest(
"""
fn main() {
<selection>true</selection>
}
"""
,
"""
fn main() {
!(true)<caret>
}
"""
)
}
fun testCall() {
doTest(
"""
fn func() -> bool {
false
}
fn main() {
<selection>func()</selection>
}
"""
,
"""
fn func() -> bool {
false
}
fn main() {
!(func())<caret>
}
"""
)
}
fun testNumber() {
doTestNotApplicable(
"""
fn main() {
<selection>1234</selection>
}
"""
)
}
fun testNumberCall() {
doTestNotApplicable(
"""
fn func() -> i32 {
1234
}
fn main() {
<selection>func()</selection>
}
"""
)
}
}
| mit |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/validation/rules/NoFragmentCycles.kt | 1 | 3126 | package graphql.validation.rules
import graphql.language.FragmentDefinition
import graphql.language.FragmentSpread
import graphql.language.Node
import graphql.validation.IValidationContext
import graphql.validation.LanguageTraversal
import graphql.validation.QueryLanguageVisitor
import graphql.validation.ValidationErrorType
import graphql.validation.*
import java.util.*
class NoFragmentCycles(validationContext: IValidationContext,
validationErrorCollector: ValidationErrorCollector)
: AbstractRule(validationContext, validationErrorCollector) {
private val fragmentSpreads = LinkedHashMap<String, List<FragmentSpread>>()
init {
prepareFragmentMap()
}
private fun prepareFragmentMap() {
val definitions = validationContext.document.definitions
for (definition in definitions) {
if (definition is FragmentDefinition) {
val fragmentDefinition = definition
fragmentSpreads.put(fragmentDefinition.name, gatherSpreads(fragmentDefinition))
}
}
}
private fun gatherSpreads(fragmentDefinition: FragmentDefinition): List<FragmentSpread> {
val fragmentSpreads = ArrayList<FragmentSpread>()
val visitor = object : QueryLanguageVisitor {
override fun enter(node: Node, path: List<Node>) {
if (node is FragmentSpread) {
fragmentSpreads.add(node)
}
}
override fun leave(node: Node, path: List<Node>) {
}
}
LanguageTraversal().traverse(fragmentDefinition, visitor)
return fragmentSpreads
}
override fun checkFragmentDefinition(fragmentDefinition: FragmentDefinition) {
val spreadPath = ArrayList<FragmentSpread>()
detectCycleRecursive(fragmentDefinition.name, fragmentDefinition.name, spreadPath)
}
private fun detectCycleRecursive(fragmentName: String,
initialName: String,
spreadPath: MutableList<FragmentSpread>) {
val fragmentSpreads = this.fragmentSpreads[fragmentName]
if (fragmentSpreads != null) {
outer@ for (fragmentSpread in fragmentSpreads) {
if (fragmentSpread.name == initialName) {
val message = "Fragment cycles not allowed"
addError(ErrorFactory().newError(ValidationErrorType.FragmentCycle, spreadPath, message))
continue
}
for (spread in spreadPath) {
if (spread == fragmentSpread) {
continue@outer
}
}
spreadPath.add(fragmentSpread)
detectCycleRecursive(fragmentSpread.name, initialName, spreadPath)
spreadPath.removeAt(spreadPath.size - 1)
}
} else {
val message = "Fragment $fragmentName not found"
addError(ErrorFactory().newError(ValidationErrorType.FragmentCycle, spreadPath, message))
}
}
}
| mit |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/creator/buildsystem/BuildSystemTemplate.kt | 1 | 2385 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.creator.buildsystem
import com.demonwav.mcdev.creator.buildsystem.maven.BasicMavenStep
import com.demonwav.mcdev.platform.BaseTemplate
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.GRADLE_GITIGNORE_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.MAVEN_GITIGNORE_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.MULTI_MODULE_BUILD_GRADLE_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.MULTI_MODULE_COMMON_POM_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.MULTI_MODULE_GRADLE_PROPERTIES_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.MULTI_MODULE_POM_TEMPLATE
import com.demonwav.mcdev.util.MinecraftTemplates.Companion.MULTI_MODULE_SETTINGS_GRADLE_TEMPLATE
import com.intellij.openapi.project.Project
object BuildSystemTemplate : BaseTemplate() {
fun applyPom(project: Project): String {
return project.applyTemplate(MULTI_MODULE_POM_TEMPLATE, BasicMavenStep.pluginVersions)
}
fun applyCommonPom(project: Project): String {
return project.applyTemplate(MULTI_MODULE_COMMON_POM_TEMPLATE, BasicMavenStep.pluginVersions)
}
fun applyBuildGradle(project: Project, buildSystem: BuildSystem): String {
val props = mapOf(
"GROUP_ID" to buildSystem.groupId,
"PLUGIN_VERSION" to buildSystem.version
)
return project.applyTemplate(MULTI_MODULE_BUILD_GRADLE_TEMPLATE, props)
}
fun applyGradleProp(project: Project): String {
return project.applyTemplate(MULTI_MODULE_GRADLE_PROPERTIES_TEMPLATE)
}
fun applySettingsGradle(project: Project, buildSystem: BuildSystem, subProjects: List<String>): String {
val props = mapOf(
"ARTIFACT_ID" to buildSystem.artifactId,
"INCLUDES" to subProjects.joinToString(", ") { "'$it'" }
)
return project.applyTemplate(MULTI_MODULE_SETTINGS_GRADLE_TEMPLATE, props)
}
fun applyGradleGitignore(project: Project): String {
return project.applyTemplate(GRADLE_GITIGNORE_TEMPLATE)
}
fun applyMavenGitignore(project: Project): String {
return project.applyTemplate(MAVEN_GITIGNORE_TEMPLATE)
}
}
| mit |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/fabric/creator/FabricProjectCreator.kt | 1 | 18019 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.fabric.creator
import com.demonwav.mcdev.asset.MCDevBundle
import com.demonwav.mcdev.creator.BaseProjectCreator
import com.demonwav.mcdev.creator.CreatorStep
import com.demonwav.mcdev.creator.LicenseStep
import com.demonwav.mcdev.creator.PostMultiModuleAware
import com.demonwav.mcdev.creator.buildsystem.BuildSystem
import com.demonwav.mcdev.creator.buildsystem.gradle.BasicGradleFinalizerStep
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleBuildSystem
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleFiles
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleGitignoreStep
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleWrapperStep
import com.demonwav.mcdev.creator.buildsystem.gradle.SimpleGradleSetupStep
import com.demonwav.mcdev.platform.fabric.EntryPoint
import com.demonwav.mcdev.platform.fabric.util.FabricConstants
import com.demonwav.mcdev.util.addAnnotation
import com.demonwav.mcdev.util.addImplements
import com.demonwav.mcdev.util.addMethod
import com.demonwav.mcdev.util.invokeLater
import com.demonwav.mcdev.util.runGradleTaskAndWait
import com.demonwav.mcdev.util.runWriteAction
import com.demonwav.mcdev.util.runWriteTask
import com.demonwav.mcdev.util.runWriteTaskInSmartMode
import com.demonwav.mcdev.util.virtualFile
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.generation.PsiMethodMember
import com.intellij.ide.util.EditorHelper
import com.intellij.json.JsonLanguage
import com.intellij.json.psi.JsonArray
import com.intellij.json.psi.JsonElementGenerator
import com.intellij.json.psi.JsonFile
import com.intellij.json.psi.JsonObject
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.PsiManager
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiModifierListOwner
import com.intellij.util.IncorrectOperationException
import java.nio.file.Files
import java.nio.file.Path
import java.util.Locale
class FabricProjectCreator(
private val rootDirectory: Path,
private val rootModule: Module,
private val buildSystem: GradleBuildSystem,
private val config: FabricProjectConfig
) : BaseProjectCreator(rootModule, buildSystem), PostMultiModuleAware {
override fun getSingleModuleSteps(): Iterable<CreatorStep> {
val buildText = FabricTemplate.applyBuildGradle(project, buildSystem, config)
val propText = FabricTemplate.applyGradleProp(project, buildSystem, config)
val settingsText = FabricTemplate.applySettingsGradle(project, buildSystem, config)
val files = GradleFiles(buildText, propText, settingsText)
val steps = mutableListOf(
SimpleGradleSetupStep(project, rootDirectory, buildSystem, files),
GradleWrapperStep(project, rootDirectory, buildSystem)
)
if (config.genSources) {
steps += GenSourcesStep(project, rootDirectory)
}
steps += GradleGitignoreStep(project, rootDirectory)
config.license?.let {
steps += LicenseStep(project, rootDirectory, it, config.authors.joinToString(", "))
}
steps += BasicGradleFinalizerStep(rootModule, rootDirectory, buildSystem)
if (config.mixins) {
steps += MixinConfigStep(project, buildSystem, config)
}
createPostSteps(steps)
steps += FabricModJsonStep(project, buildSystem, config)
return steps
}
override fun getMultiModuleSteps(projectBaseDir: Path): Iterable<CreatorStep> {
val buildText = FabricTemplate.applyMultiModuleBuildGradle(project, buildSystem, config)
val propText = FabricTemplate.applyMultiModuleGradleProp(project, buildSystem, config)
val settingsText = FabricTemplate.applySettingsGradle(project, buildSystem, config)
val files = GradleFiles(buildText, propText, settingsText)
val steps = mutableListOf<CreatorStep>(
SimpleGradleSetupStep(project, rootDirectory, buildSystem, files)
)
if (config.genSources) {
steps += GenSourcesStep(project, rootDirectory)
}
config.license?.let {
steps += LicenseStep(project, rootDirectory, it, config.authors.joinToString(", "))
}
if (config.mixins) {
steps += MixinConfigStep(project, buildSystem, config)
}
return steps
}
override fun getPostMultiModuleSteps(projectBaseDir: Path): Iterable<CreatorStep> {
val steps = mutableListOf<CreatorStep>()
createPostSteps(steps)
steps += FabricModJsonStep(project, buildSystem, config)
return steps
}
private fun createPostSteps(steps: MutableList<CreatorStep>) {
for (entry in config.entryPoints.groupBy { it.className }.entries.sortedBy { it.key }) {
steps += CreateEntryPointStep(project, buildSystem, entry.key, entry.value)
}
}
}
class GenSourcesStep(
private val project: Project,
private val rootDirectory: Path
) : CreatorStep {
override fun runStep(indicator: ProgressIndicator) {
indicator.text = "Setting up project"
indicator.text2 = "Running Gradle task: 'genSources'"
runGradleTaskAndWait(project, rootDirectory) { settings ->
settings.taskNames = listOf("genSources")
settings.vmOptions = "-Xmx1G"
}
indicator.text2 = null
}
}
class FabricModJsonStep(
private val project: Project,
private val buildSystem: BuildSystem,
private val config: FabricProjectConfig
) : CreatorStep {
override fun runStep(indicator: ProgressIndicator) {
val text = FabricTemplate.applyFabricModJsonTemplate(project, buildSystem, config)
val dir = buildSystem.dirsOrError.resourceDirectory
indicator.text = "Indexing"
project.runWriteTaskInSmartMode {
indicator.text = "Creating 'fabric.mod.json'"
val file = PsiFileFactory.getInstance(project).createFileFromText(JsonLanguage.INSTANCE, text)
file.runWriteAction {
val jsonFile = file as JsonFile
val json = jsonFile.topLevelValue as? JsonObject ?: return@runWriteAction
val generator = JsonElementGenerator(project)
(json.findProperty("authors")?.value as? JsonArray)?.let { authorsArray ->
for (i in config.authors.indices) {
if (i != 0) {
authorsArray.addBefore(generator.createComma(), authorsArray.lastChild)
}
authorsArray.addBefore(generator.createStringLiteral(config.authors[i]), authorsArray.lastChild)
}
}
(json.findProperty("contact")?.value as? JsonObject)?.let { contactObject ->
val properties = mutableListOf<Pair<String, String>>()
val website = config.website
if (!website.isNullOrBlank()) {
properties += "website" to website
}
val repo = config.modRepo
if (!repo.isNullOrBlank()) {
properties += "repo" to repo
}
for (i in properties.indices) {
if (i != 0) {
contactObject.addBefore(generator.createComma(), contactObject.lastChild)
}
val key = StringUtil.escapeStringCharacters(properties[i].first)
val value = "\"" + StringUtil.escapeStringCharacters(properties[i].second) + "\""
contactObject.addBefore(generator.createProperty(key, value), contactObject.lastChild)
}
}
(json.findProperty("entrypoints")?.value as? JsonObject)?.let { entryPointsObject ->
val entryPointsByCategory = config.entryPoints
.groupBy { it.category }
.asSequence()
.sortedBy { it.key }
.toList()
for (i in entryPointsByCategory.indices) {
val entryPointCategory = entryPointsByCategory[i]
if (i != 0) {
entryPointsObject.addBefore(generator.createComma(), entryPointsObject.lastChild)
}
val values = generator.createValue<JsonArray>("[]")
for (j in entryPointCategory.value.indices) {
if (j != 0) {
values.addBefore(generator.createComma(), values.lastChild)
}
val entryPointReference = entryPointCategory.value[j].computeReference(project)
val value = generator.createStringLiteral(entryPointReference)
values.addBefore(value, values.lastChild)
}
val key = StringUtil.escapeStringCharacters(entryPointCategory.key)
val prop = generator.createProperty(key, "[]")
prop.value?.replace(values)
entryPointsObject.addBefore(prop, entryPointsObject.lastChild)
}
}
}
CreatorStep.writeTextToFile(project, dir, FabricConstants.FABRIC_MOD_JSON, file.text)
}
}
}
class MixinConfigStep(
private val project: Project,
private val buildSystem: BuildSystem,
private val config: FabricProjectConfig
) : CreatorStep {
override fun runStep(indicator: ProgressIndicator) {
val text = FabricTemplate.applyMixinConfigTemplate(project, buildSystem, config)
val dir = buildSystem.dirsOrError.resourceDirectory
runWriteTask {
CreatorStep.writeTextToFile(project, dir, "${buildSystem.artifactId}.mixins.json", text)
}
}
}
class CreateEntryPointStep(
private val project: Project,
private val buildSystem: BuildSystem,
private val qualifiedClassName: String,
private val entryPoints: List<EntryPoint>
) : CreatorStep {
override fun runStep(indicator: ProgressIndicator) {
val dirs = buildSystem.dirsOrError
indicator.text = "Indexing"
val dotIndex = qualifiedClassName.lastIndexOf('.')
val packageName = if (dotIndex == -1) {
""
} else {
qualifiedClassName.substring(0, dotIndex)
}
val className = qualifiedClassName.substring(dotIndex + 1)
var directory = dirs.sourceDirectory
for (part in packageName.split(".")) {
directory = directory.resolve(part)
}
if (Files.notExists(directory)) {
Files.createDirectories(directory)
}
val virtualDir = directory.virtualFile ?: return
project.runWriteTaskInSmartMode {
indicator.text = "Writing class: $className"
val psiDir = PsiManager.getInstance(project).findDirectory(virtualDir) ?: return@runWriteTaskInSmartMode
val clazz = try {
JavaDirectoryService.getInstance().createClass(psiDir, className)
} catch (e: IncorrectOperationException) {
invokeLater {
val message = MCDevBundle.message(
"intention.error.cannot.create.class.message",
className,
e.localizedMessage
)
Messages.showErrorDialog(
project,
message,
MCDevBundle.message("intention.error.cannot.create.class.title")
)
}
return@runWriteTaskInSmartMode
}
val editor = EditorHelper.openInEditor(clazz)
clazz.containingFile.runWriteAction {
val clientEntryPoints = entryPoints.filter { it.category == "client" }
val serverEntryPoints = entryPoints.filter { it.category == "server" }
val otherEntryPoints = entryPoints.filter { it.category != "client" && it.category != "server" }
val entryPointsByInterface = entryPoints
.filter { it.type == EntryPoint.Type.CLASS }
.groupBy { it.interfaceName }
.entries
.sortedBy { it.key }
val entryPointsByMethodNameAndSig = entryPoints
.filter { it.type == EntryPoint.Type.METHOD }
.groupBy { entryPoint ->
val functionalMethod = entryPoint.findFunctionalMethod(project) ?: return@groupBy null
val paramTypes = functionalMethod.parameterList.parameters.map { it.type.canonicalText }
(entryPoint.methodName ?: functionalMethod.name) to paramTypes
}
.entries
.mapNotNull { it.key?.let { k -> k to it.value } }
.sortedBy { it.first.first }
val elementFactory = JavaPsiFacade.getElementFactory(project)
var isClientClass = false
var isServerClass = false
if (clientEntryPoints.isNotEmpty()) {
if (serverEntryPoints.isEmpty() && otherEntryPoints.isEmpty()) {
addEnvironmentAnnotation(clazz, "CLIENT")
isClientClass = true
} else {
addSidedInterfaceEntryPoints(entryPointsByInterface, clazz, editor, "client")
}
} else if (serverEntryPoints.isNotEmpty()) {
if (clientEntryPoints.isEmpty() && otherEntryPoints.isEmpty()) {
addEnvironmentAnnotation(clazz, "SERVER")
isServerClass = true
} else {
addSidedInterfaceEntryPoints(entryPointsByInterface, clazz, editor, "server")
}
}
for (eps in entryPointsByInterface) {
clazz.addImplements(eps.key)
}
implementAll(clazz, editor)
for (eps in entryPointsByMethodNameAndSig) {
val functionalMethod = eps.second.first().findFunctionalMethod(project) ?: continue
val newMethod = clazz.addMethod(functionalMethod) ?: continue
val methodName = eps.first.first
newMethod.nameIdentifier?.replace(elementFactory.createIdentifier(methodName))
newMethod.modifierList.setModifierProperty(PsiModifier.PUBLIC, true)
newMethod.modifierList.setModifierProperty(PsiModifier.STATIC, true)
newMethod.modifierList.setModifierProperty(PsiModifier.ABSTRACT, false)
CreateFromUsageUtils.setupMethodBody(newMethod)
if (!isClientClass && eps.second.all { it.category == "client" }) {
addEnvironmentAnnotation(newMethod, "CLIENT")
} else if (!isServerClass && eps.second.all { it.category == "server" }) {
addEnvironmentAnnotation(newMethod, "SERVER")
}
}
}
}
}
private fun addSidedInterfaceEntryPoints(
entryPointsByInterface: List<Map.Entry<String, List<EntryPoint>>>,
clazz: PsiClass,
editor: Editor,
side: String
) {
val capsSide = side.toUpperCase(Locale.ROOT)
var needsInterfaceFix = false
for (eps in entryPointsByInterface) {
if (eps.value.all { it.category == side }) {
addEnvironmentInterfaceAnnotation(clazz, capsSide, eps.key)
clazz.addImplements(eps.key)
needsInterfaceFix = true
}
}
if (needsInterfaceFix) {
implementAll(clazz, editor)
for (method in clazz.methods) {
if (!method.hasAnnotation(FabricConstants.ENVIRONMENT_ANNOTATION)) {
addEnvironmentAnnotation(method, capsSide)
}
}
}
}
private fun addEnvironmentAnnotation(owner: PsiModifierListOwner, envType: String) {
owner.addAnnotation("@${FabricConstants.ENVIRONMENT_ANNOTATION}(${FabricConstants.ENV_TYPE}.$envType)")
}
private fun addEnvironmentInterfaceAnnotation(
owner: PsiModifierListOwner,
envType: String,
interfaceQualifiedName: String
) {
val annotationText = "@${FabricConstants.ENVIRONMENT_INTERFACE_ANNOTATION}(" +
"value=${FabricConstants.ENV_TYPE}.$envType," +
"itf=$interfaceQualifiedName.class" +
")"
owner.addAnnotation(annotationText)
}
private fun implementAll(clazz: PsiClass, editor: Editor) {
val methodsToImplement = OverrideImplementUtil.getMethodsToOverrideImplement(clazz, true)
.map { PsiMethodMember(it) }
OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(
editor,
clazz,
methodsToImplement,
false,
true
)
}
}
| mit |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/login/SsoLoginActivity.kt | 1 | 2131 | package de.xikolo.controllers.login
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.yatatsu.autobundle.AutoBundleField
import de.xikolo.App
import de.xikolo.R
import de.xikolo.controllers.base.BaseActivity
import de.xikolo.controllers.dialogs.CreateTicketDialog
import de.xikolo.controllers.dialogs.CreateTicketDialogAutoBundle
import de.xikolo.controllers.webview.WebViewFragmentAutoBundle
import de.xikolo.extensions.observe
class SsoLoginActivity : BaseActivity() {
companion object {
val TAG = SsoLoginActivity::class.java.simpleName
}
@AutoBundleField
lateinit var url: String
@AutoBundleField
lateinit var title: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_blank)
setupActionBar()
setTitle(title)
val tag = "content"
val fragment = WebViewFragmentAutoBundle.builder(url)
.inAppLinksEnabled(true)
.externalLinksEnabled(true)
.build()
val fragmentManager = supportFragmentManager
if (fragmentManager.findFragmentByTag(tag) == null) {
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.content, fragment, tag)
transaction.commit()
}
App.instance.state.login
.observe(this) { isLoggedIn ->
if (isLoggedIn) {
finish()
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.helpdesk, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_helpdesk -> {
val dialog = CreateTicketDialogAutoBundle.builder().build()
dialog.show(supportFragmentManager, CreateTicketDialog.TAG)
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| bsd-3-clause |
arturbosch/TiNBo | tinbo-ascii/src/main/kotlin/io/gitlab/arturbosch/tinbo/ascii/Ascii.kt | 1 | 2934 | package io.gitlab.arturbosch.tinbo.ascii
import io.gitlab.arturbosch.tinbo.api.marker.Command
import org.springframework.shell.core.annotation.CliCommand
import org.springframework.shell.core.annotation.CliOption
import java.awt.Color
import java.awt.Image
import java.awt.image.BufferedImage
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import javax.imageio.ImageIO
/**
* @author Artur Bosch
*/
class Ascii : Command {
override val id: String = "plugins"
@CliCommand("plugin ascii", help = "Converts an given image to ascii art.")
fun run(@CliOption(key = ["", "path"]) path: String?,
@CliOption(key = ["invert"], unspecifiedDefaultValue = "false",
specifiedDefaultValue = "true") invert: Boolean): String {
return path?.let {
val path1 = Paths.get(path)
if (Files.notExists(path1)) return "Specified path does not exist!"
if (!isImage(path1)) return "Given path points not to an image (jpg or png)."
val image = ImageIO.read(path1.toFile())
val resizeImage = resizeImage(image, 76, 0)
return ASCII(invert).convert(resizeImage)
} ?: "Provided path does not exist"
}
private fun isImage(path: Path): Boolean {
val stringPath = path.toString().toLowerCase()
fun endsWith(sub: String): Boolean = stringPath.endsWith(sub)
return endsWith("jpg") || endsWith("jpeg") || endsWith("png")
}
private fun resizeImage(image: BufferedImage, width: Int, height: Int): BufferedImage {
var cWidth = width
var cHeight = height
if (cWidth < 1) {
cWidth = 1
}
if (cHeight <= 0) {
val aspectRatio = cWidth.toDouble() / image.width * 0.5
cHeight = Math.ceil(image.height * aspectRatio).toInt()
}
val resized = BufferedImage(cWidth, cHeight, BufferedImage.TYPE_INT_RGB)
val scaled = image.getScaledInstance(cWidth, cHeight, Image.SCALE_DEFAULT)
resized.graphics.drawImage(scaled, 0, 0, null)
return resized
}
class ASCII(private val negative: Boolean = false) {
fun convert(image: BufferedImage): String {
val sb = StringBuilder((image.width + 1) * image.height)
for (y in 0 until image.height) {
if (sb.isNotEmpty()) sb.append("\n")
(0 until image.width)
.asSequence()
.map { Color(image.getRGB(it, y)) }
.map { it.red.toDouble() * 0.30 + it.blue.toDouble() * 0.59 + it.green.toDouble() * 0.11 }
.map { if (negative) returnStrNeg(it) else returnStrPos(it) }
.forEach { sb.append(it) }
}
return sb.toString()
}
private fun returnStrPos(g: Double) = when {
g >= 230.0 -> ' '
g >= 200.0 -> '.'
g >= 180.0 -> '*'
g >= 160.0 -> ':'
g >= 130.0 -> 'o'
g >= 100.0 -> '&'
g >= 70.0 -> '8'
g >= 50.0 -> '#'
else -> '@'
}
private fun returnStrNeg(g: Double) = when {
g >= 230.0 -> '@'
g >= 200.0 -> '#'
g >= 180.0 -> '8'
g >= 160.0 -> '&'
g >= 130.0 -> 'o'
g >= 100.0 -> ':'
g >= 70.0 -> '*'
g >= 50.0 -> '.'
else -> ' '
}
}
}
| apache-2.0 |
jeksor/Language-Detector | app/src/main/java/com/esorokin/lantector/di/module/AndroidApplicationModule.kt | 1 | 627 | package com.esorokin.lantector.di.module
import android.content.Context
import com.esorokin.lantector.app.StringProvider
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class AndroidApplicationModule(private val context: Context) {
@Provides
@Singleton
fun provideContext(): Context {
return context
}
@Provides
@Singleton
fun provideStringProvider(): StringProvider {
return object : StringProvider {
override fun getString(stringRes: Int, vararg formatArgs: Any): String = context.getString(stringRes, formatArgs)
}
}
}
| mit |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/med/PZN.kt | 1 | 5127 | /*
* Copyright (c) 2020 by Oliver Boehm
*
* 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.
*
* (c)reated 25.05.2020 by oboehm
*/
package de.jfachwert.med
import de.jfachwert.AbstractFachwert
import de.jfachwert.PruefzifferVerfahren
import de.jfachwert.KSimpleValidator
import de.jfachwert.pruefung.LengthValidator
import java.util.*
/**
* Die Klasse PZN.
*
* @author oboehm
* @since 4.0 (25.05.2020)
*/
open class PZN
/**
* Erzeugt ein neues PZN-Objekt.
*
* @param code achtstellige Zahl
* @param validator Validator zur Pruefung der Zahl
*/
@JvmOverloads constructor(code: Int, validator: KSimpleValidator<Int> = VALIDATOR) : AbstractFachwert<Int, PZN>(code, validator) {
/**
* Erzeugt ein neues PZN-Objekt.
*
* @param code achtstellige Zahl
*/
constructor(code: String) : this(toInt(code)) {}
/**
* Die PZN ist 8-stellig und wird auch achtstellig ausgegeben.
*
* @return 8-stellige Zeichenkette mit PZN-Prefix
*/
override fun toString(): String {
return String.format("PZN-%08d", code)
}
companion object {
private val VALIDATOR = Validator()
private val WEAK_CACHE = WeakHashMap<Int, PZN>()
/**
* Liefert eine PZN zurueck.
*
* @param code 8-stellige Nummer
* @return die PZN
*/
@JvmStatic
fun of(code: Int): PZN {
return WEAK_CACHE.computeIfAbsent(code) { n: Int -> PZN(n) }
}
/**
* Liefert eine PZN zurueck.
*
* @param code 8-stellige Nummer
* @return die PZN
*/
@JvmStatic
fun of(code: String): PZN {
return of(toInt(code))
}
private fun toInt(s: String): Int {
return s.replace("PZN-", "", true).toInt()
}
}
/**
* Die Pruefziffer der PZN wird nach dem Modulo 11 berechnet. Dabei wird
* jede Ziffer der PZN mit einem unterschiedlichen Faktor von eins bis neun
* gewichtet. Ueber die Produkte wird die Summe gebildet und durch 11
* dividiert. Der verbleibende ganzzahlige Rest bildet die Pruefziffer.
* Bleibt als Rest die Zahl 10, dann wird diese Ziffernfolge nicht als PZN verwendet
*/
class Validator : KSimpleValidator<Int> {
/**
* Wenn der uebergebene Wert gueltig ist, soll er unveraendert
* zurueckgegeben werden, damit er anschliessend von der aufrufenden
* Methode weiterverarbeitet werden kann. Ist der Wert nicht gueltig,
* soll eine [javax.validation.ValidationException] geworfen
* werden.
*
* @param value Wert, der validiert werden soll
* @return Wert selber, wenn er gueltig ist
*/
override fun validate(value: Int): Int {
val n = VALIDATOR8.validate(value)
MOD11.validate(Integer.toString(n))
return n
}
companion object {
private val MOD11: PruefzifferVerfahren<String> = Mod11Verfahren()
private val VALIDATOR8 = LengthValidator<Int>(2, 8)
}
}
/**
* Die Pruefziffer der PZN wird nach dem Modulo 11 berechnet. Dabei wird
* jede Ziffer der PZN mit einem unterschiedlichen Faktor von 1 bis 9
* gewichtet. Ueber die Produkte wird die Summe gebildet und durch 11
* dividiert. Der verbleibende ganzzahlige Rest bildet die Pruefziffer.
* Bleibt als Rest die Zahl 10, dann wird diese Ziffernfolge nicht als PZN
* verwendet
*/
class Mod11Verfahren : PruefzifferVerfahren<String> {
/**
* Die Pruefziffer ist die letzte Ziffer.
*
* @param wert eine PZN
* @return ein Wert zwischen 0 und 9
*/
override fun getPruefziffer(wert: String): String {
return wert.last().toString()
}
/**
* Berechnet die Pruefziffer des uebergebenen Wertes.
*
* @param wert Wert
* @return errechnete Pruefziffer
*/
override fun berechnePruefziffer(wert: String): String {
val sum = getQuersumme(wert)
return Integer.toString((sum % 11) % 10)
}
private fun getQuersumme(wert: String): Int {
val digits = wert.toCharArray()
var sum = 0
val length = digits.size-1
val anfangsWichtung = 8 - length
for (i in 0 until length) {
val digit = Character.digit(digits[i], 10)
sum += digit * (anfangsWichtung + i)
}
return sum
}
}
}
| apache-2.0 |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/net/TwidereDns.kt | 1 | 12104 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.net
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import android.util.TimingLogger
import okhttp3.Dns
import org.mariotaku.ktextension.toIntOr
import de.vanita5.twittnuker.BuildConfig
import de.vanita5.twittnuker.TwittnukerConstants.HOST_MAPPING_PREFERENCES_NAME
import de.vanita5.twittnuker.constant.SharedPreferenceConstants.*
import org.xbill.DNS.*
import java.io.IOException
import java.net.InetAddress
import java.net.UnknownHostException
import java.util.*
import javax.inject.Singleton
@Singleton
class TwidereDns(val context: Context, private val preferences: SharedPreferences) : Dns {
private val hostMapping = context.getSharedPreferences(HOST_MAPPING_PREFERENCES_NAME,
Context.MODE_PRIVATE)
private val systemHosts = SystemHosts()
private var resolver: Resolver? = null
private var useResolver: Boolean = false
init {
reloadDnsSettings()
}
@Throws(UnknownHostException::class)
override fun lookup(hostname: String): List<InetAddress> {
try {
return resolveInternal(hostname, hostname, 0, useResolver)
} catch (e: IOException) {
if (e is UnknownHostException) throw e
throw UnknownHostException("Unable to resolve address " + e.message)
} catch (e: SecurityException) {
throw UnknownHostException("Security exception" + e.message)
}
}
@Throws(UnknownHostException::class)
fun lookupResolver(hostname: String): List<InetAddress> {
try {
return resolveInternal(hostname, hostname, 0, true)
} catch (e: IOException) {
if (e is UnknownHostException) throw e
throw UnknownHostException("Unable to resolve address " + e.message)
} catch (e: SecurityException) {
throw UnknownHostException("Security exception" + e.message)
}
}
fun reloadDnsSettings() {
this.resolver = null
useResolver = preferences.getBoolean(KEY_BUILTIN_DNS_RESOLVER, false)
}
fun putMapping(host: String, address: String) {
beginMappingTransaction {
this[host] = address
}
}
fun beginMappingTransaction(action: MappingTransaction.() -> Unit) {
hostMapping.edit().apply { action(MappingTransaction(this)) }.apply()
}
@Throws(IOException::class, SecurityException::class)
private fun resolveInternal(originalHost: String, host: String, depth: Int,
useResolver: Boolean): List<InetAddress> {
val logger = TimingLogger(RESOLVER_LOGTAG, "resolve")
// Return if host is an address
val fromAddressString = fromAddressString(originalHost, host)
if (fromAddressString != null) {
addLogSplit(logger, host, "valid ip address", depth)
dumpLog(logger, fromAddressString)
return fromAddressString
}
// Load from custom mapping
addLogSplit(logger, host, "start custom mapping resolve", depth)
val fromMapping = getFromMapping(host)
addLogSplit(logger, host, "end custom mapping resolve", depth)
if (fromMapping != null) {
dumpLog(logger, fromMapping)
return fromMapping
}
if (useResolver) {
// Load from /etc/hosts, since Dnsjava doesn't support hosts entry lookup
addLogSplit(logger, host, "start /etc/hosts resolve", depth)
val fromSystemHosts = fromSystemHosts(host)
addLogSplit(logger, host, "end /etc/hosts resolve", depth)
if (fromSystemHosts != null) {
dumpLog(logger, fromSystemHosts)
return fromSystemHosts
}
// Use DNS resolver
addLogSplit(logger, host, "start resolver resolve", depth)
val fromResolver = fromResolver(originalHost, host)
addLogSplit(logger, host, "end resolver resolve", depth)
if (fromResolver != null) {
dumpLog(logger, fromResolver)
return fromResolver
}
}
addLogSplit(logger, host, "start system default resolve", depth)
val fromDefault = Arrays.asList(*InetAddress.getAllByName(host))
addLogSplit(logger, host, "end system default resolve", depth)
dumpLog(logger, fromDefault)
return fromDefault
}
private fun dumpLog(logger: TimingLogger, addresses: List<InetAddress>) {
if (BuildConfig.DEBUG) return
Log.v(RESOLVER_LOGTAG, "Resolved " + addresses)
logger.dumpToLog()
}
private fun addLogSplit(logger: TimingLogger, host: String, message: String, depth: Int) {
if (BuildConfig.DEBUG) return
val sb = StringBuilder()
for (i in 0 until depth) {
sb.append(">")
}
sb.append(" ")
sb.append(host)
sb.append(": ")
sb.append(message)
logger.addSplit(sb.toString())
}
private fun fromSystemHosts(host: String): List<InetAddress>? {
try {
return systemHosts.resolve(host)
} catch (e: IOException) {
return null
}
}
@Throws(IOException::class)
private fun fromResolver(originalHost: String, host: String): List<InetAddress>? {
val resolver = this.getResolver()
val records = lookupHostName(resolver, host, true)
val addrs = ArrayList<InetAddress>(records.size)
for (record in records) {
addrs.add(addrFromRecord(originalHost, record))
}
if (addrs.isEmpty()) return null
return addrs
}
@Throws(UnknownHostException::class)
private fun getFromMapping(host: String): List<InetAddress>? {
return getFromMappingInternal(host, host, false)
}
@Throws(UnknownHostException::class)
private fun getFromMappingInternal(host: String, origHost: String, checkRecursive: Boolean): List<InetAddress>? {
if (checkRecursive && hostMatches(host, origHost)) {
// Recursive resolution, stop this call
return null
}
for ((key, value1) in hostMapping.all) {
if (hostMatches(host, key)) {
val value = value1 as String
val resolved = getResolvedIPAddress(origHost, value) ?: // Maybe another hostname
return getFromMappingInternal(value, origHost, true)
return listOf(resolved)
}
}
return null
}
private fun getResolver(): Resolver {
return this.resolver ?: run {
val tcp = preferences.getBoolean(KEY_TCP_DNS_QUERY, false)
val servers = preferences.getString(KEY_DNS_SERVER, null)?.split(';', ',', ' ') ?:
SystemDnsFetcher.get(context)
val resolvers = servers?.mapNotNull {
val segs = it.split("#", limit = 2)
if (segs.isEmpty()) return@mapNotNull null
if (!isValidIpAddress(segs[0])) return@mapNotNull null
return@mapNotNull SimpleResolver(segs[0]).apply {
if (segs.size == 2) {
val port = segs[1].toIntOr(-1)
if (port in 0..65535) {
setPort(port)
}
}
}
}
val resolver: Resolver
resolver = if (resolvers != null && resolvers.isNotEmpty()) {
ExtendedResolver(resolvers.toTypedArray())
} else {
SimpleResolver()
}
resolver.setTCP(tcp)
this.resolver = resolver
return@run resolver
}
}
@Throws(UnknownHostException::class)
private fun fromAddressString(host: String, address: String): List<InetAddress>? {
val resolved = getResolvedIPAddress(host, address) ?: return null
return listOf(resolved)
}
companion object {
private val RESOLVER_LOGTAG = "TwittnukerDns"
private fun hostMatches(host: String?, rule: String?): Boolean {
if (rule == null || host == null) return false
if (rule.startsWith(".")) return host.endsWith(rule, ignoreCase = true)
return host.equals(rule, ignoreCase = true)
}
@Throws(UnknownHostException::class)
fun getResolvedIPAddress(host: String,
address: String): InetAddress? {
var bytes = Address.toByteArray(address, Address.IPv4)
if (bytes != null)
return InetAddress.getByAddress(host, bytes)
bytes = Address.toByteArray(address, Address.IPv6)
if (bytes != null)
return InetAddress.getByAddress(host, bytes)
return null
}
private fun getInetAddressType(address: String): Int {
var bytes = Address.toByteArray(address, Address.IPv4)
if (bytes != null)
return Address.IPv4
bytes = Address.toByteArray(address, Address.IPv6)
if (bytes != null)
return Address.IPv6
return 0
}
fun isValidIpAddress(address: String): Boolean {
return getInetAddressType(address) != 0
}
@Throws(UnknownHostException::class)
private fun lookupHostName(resolver: Resolver, name: String, all: Boolean): Array<Record> {
try {
val lookup = newLookup(resolver, name, Type.A)
val a = lookup.run()
if (a == null) {
if (lookup.result == Lookup.TYPE_NOT_FOUND) {
// val aaaa = newLookup(resolver, name, Type.AAAA).run()
// if (aaaa != null) return aaaa
}
throw UnknownHostException("unknown host")
}
if (!all)
return a
// val aaaa = newLookup(resolver, name, Type.AAAA).run() ?: return a
// return a + aaaa
return a
} catch (e: TextParseException) {
throw UnknownHostException("invalid name")
}
}
@Throws(TextParseException::class)
private fun newLookup(resolver: Resolver, name: String, type: Int): Lookup {
val lookup = Lookup(name, type)
lookup.setResolver(resolver)
return lookup
}
@Throws(UnknownHostException::class)
private fun addrFromRecord(name: String, r: Record): InetAddress {
val addr: InetAddress
if (r is ARecord) {
addr = r.address
} else {
addr = (r as AAAARecord).address
}
return InetAddress.getByAddress(name, addr.address)
}
}
class MappingTransaction(private val editor: SharedPreferences.Editor) {
operator fun set(host: String, address: String) {
editor.putString(host, address)
}
fun remove(host: String) {
editor.remove(host)
}
}
} | gpl-3.0 |
ejeinc/VR-MultiView-UDP | player/src/main/java/com/eje_c/player/MediaPlayerImpl.kt | 1 | 2808 | package com.eje_c.player
import android.content.Context
import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.net.Uri
import android.view.Surface
class MediaPlayerImpl(
private val context: Context,
private val mp: MediaPlayer) : Player, MediaPlayer.OnInfoListener, MediaPlayer.OnCompletionListener {
private var surface: Surface? = null
init {
// Add event listeners
mp.setOnInfoListener(this)
mp.setOnCompletionListener(this)
}
override val duration: Long
get() = mp.duration.toLong()
override var currentPosition: Long
set(value) = mp.seekTo(value.toInt())
get() = mp.currentPosition.toLong()
override val isPlaying: Boolean
get() = mp.isPlaying
override var volume: Float = 1.0f
set(value) {
field = value
mp.setVolume(value, value)
}
override var onRenderFirstFrame: (() -> Unit)? = null
set(value) {
field = value
if (value != null) {
mp.setOnInfoListener { mediaPlayer, what, extra ->
when (what) {
MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START -> {
value()
return@setOnInfoListener true
}
else -> {
return@setOnInfoListener false
}
}
}
} else {
mp.setOnInfoListener(null)
}
}
override var onCompletion: (() -> Unit)? = null
override val videoWidth: Int
get() = mp.videoWidth
override val videoHeight: Int
get() = mp.videoHeight
override fun pause() = mp.pause()
override fun start() = mp.start()
override fun stop() = mp.stop()
override fun load(uri: Uri) {
mp.reset()
mp.setDataSource(context, uri)
mp.prepare()
}
override fun release() {
surface?.release()
mp.release()
}
override fun setOutput(surfaceTexture: SurfaceTexture) {
surface?.release()
surface = Surface(surfaceTexture)
mp.setSurface(surface)
}
override fun setOutput(surface: Surface) {
this.surface?.release()
this.surface = surface
mp.setSurface(surface)
}
override fun onCompletion(p0: MediaPlayer?) {
onCompletion?.invoke()
}
override fun onInfo(mediaPlayer: MediaPlayer, what: Int, extra: Int): Boolean {
when (what) {
MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START -> {
onRenderFirstFrame?.invoke()
return true
}
}
return false
}
}
| apache-2.0 |
mswift42/apg | Stopwatch/app/src/main/java/mswift42/com/github/stopwatch/StopwatchActivity.kt | 1 | 2101 | package mswift42.com.github.stopwatch
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import kotlinx.android.synthetic.main.activity_stopwatch.*
class StopwatchActivity : AppCompatActivity() {
private var seconds: Int = 0
private var running: Boolean = false
private var wasRunning: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_stopwatch)
if (savedInstanceState != null) {
seconds = savedInstanceState.getInt("seconds")
running = savedInstanceState.getBoolean("running")
wasRunning = savedInstanceState.getBoolean("wasRunning")
}
runTimer()
}
override fun onSaveInstanceState(savedInstanceState: Bundle?) {
savedInstanceState?.putInt("seconds", seconds)
savedInstanceState?.putBoolean("running", running)
savedInstanceState?.putBoolean("wasRunning", wasRunning)
}
fun onClickStart(view: View) {
running = true
}
fun onClickStop(view: View) {
running = false
}
fun onClickReset(view: View) {
running = false
seconds = 0
}
private fun runTimer(): Unit {
val handler = Handler()
val settimer = object : Runnable {
override fun run() {
val hours = seconds / 3600
val minutes = (seconds % 3600) / 60
val sec = seconds % 60
val time = String.format("%d:%02d:%02d", hours, minutes, seconds)
watchtimer.text = time
if (running) {
seconds++
}
handler.postDelayed(this, 1000)
}
}
handler.post(settimer)
}
override fun onStop() {
super.onStop()
wasRunning = running
running = false
}
override fun onStart() {
super.onStart()
if (wasRunning) {
running = true
}
}
} | gpl-3.0 |
mayank408/susi_android | app/src/main/java/org/fossasia/susi/ai/rest/responses/susi/LoginResponse.kt | 1 | 462 | package org.fossasia.susi.ai.rest.responses.susi
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* <h1>Kotlin Data class to parse retrofit response from login endpoint susi client.</h1>
* Created by saurabh on 12/10/16.
*/
class LoginResponse {
val message: String? = null
val session: Session? = null
val valid_seconds: Long = 0
var access_token: String? = null
internal set
}
| apache-2.0 |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/PayWithGoogleUtils.kt | 1 | 2291 | package com.stripe.android
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Currency
import java.util.Locale
import kotlin.math.pow
/**
* Public utility class for common Pay with Google-related tasks.
*/
object PayWithGoogleUtils {
/**
* Converts an integer price in the lowest currency denomination to a Google string value.
* For instance: (100L, USD) -> "1.00", but (100L, JPY) -> "100".
* @param price the price in the lowest available currency denomination
* @param currency the [Currency] used to determine how many digits after the decimal
* @return a String that can be used as a Pay with Google price string
*/
@JvmStatic
fun getPriceString(price: Int, currency: Currency): String {
val fractionDigits = currency.defaultFractionDigits
val totalLength = price.toString().length
val builder = StringBuilder()
if (fractionDigits == 0) {
for (i in 0 until totalLength) {
builder.append('#')
}
val noDecimalCurrencyFormat =
DecimalFormat(builder.toString(), DecimalFormatSymbols.getInstance(Locale.ROOT))
noDecimalCurrencyFormat.currency = currency
noDecimalCurrencyFormat.isGroupingUsed = false
return noDecimalCurrencyFormat.format(price)
}
val beforeDecimal = totalLength - fractionDigits
for (i in 0 until beforeDecimal) {
builder.append('#')
}
// So we display "0.55" instead of ".55"
if (totalLength <= fractionDigits) {
builder.append('0')
}
builder.append('.')
for (i in 0 until fractionDigits) {
builder.append('0')
}
val modBreak = 10.0.pow(fractionDigits.toDouble())
val decimalPrice = price / modBreak
// No matter the Locale, Android Pay requires a dot for the decimal separator, and Arabic
// numbers.
val symbolOverride = DecimalFormatSymbols.getInstance(Locale.ROOT)
val decimalFormat = DecimalFormat(builder.toString(), symbolOverride)
decimalFormat.currency = currency
decimalFormat.isGroupingUsed = false
return decimalFormat.format(decimalPrice)
}
}
| mit |
sksamuel/scrimage | scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/nio/GifSequenceWriterTest.kt | 1 | 797 | @file:Suppress("BlockingMethodInNonBlockingContext")
package com.sksamuel.scrimage.core.nio
import com.sksamuel.scrimage.ImmutableImage
import com.sksamuel.scrimage.nio.GifSequenceWriter
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe
import org.apache.commons.io.IOUtils
class GifSequenceWriterTest : WordSpec({
val bird = ImmutableImage.loader().fromResource("/bird_small.png")
"gif sequence writer" should {
"write all frames" {
val frames = listOf(bird, bird.flipX(), bird.flipY(), bird.flipX().flipY())
val actual = GifSequenceWriter().withFrameDelay(500).bytes(frames.toTypedArray())
actual shouldBe IOUtils.toByteArray(javaClass.getResourceAsStream("/com/sksamuel/scrimage/nio/animated_birds.gif"))
}
}
})
| apache-2.0 |
peervalhoegen/SudoQ | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/solution/Solution.kt | 1 | 1240 | package de.sudoq.model.solverGenerator.solution
import de.sudoq.model.actionTree.Action
import java.util.*
/**
* A Solution step for the [Sudoku]. Comprises
* - a concrete [Action] that if applied to a [Sudoku] solves a [Cell]
* - [Derivation]s that lead to the solution (see [SolveDerivation] und [Action]).
*/
class Solution {
/**
* The [Action] that solves the [Cell] that belongs to the [Solution]
* or null if the Action doesn't solve a [Cell].
*/
var action: Action? = null
set(action) {
if (action != null) field = action
}
/**
* A list of [SolveDerivation]s that derive the [Action].
*/
private val derivations: MutableList<SolveDerivation> = ArrayList()
/**
* Adds a [SolveDerivation]
*
* @param derivation A SolveDerivation to add
*/
fun addDerivation(derivation: SolveDerivation) {
derivations.add(derivation)
}
/**
* Iterator over the SolveDerivations.
*
* @return An Iterator over the SolveDerivations
*/
val derivationIterator: Iterator<SolveDerivation>
get() = derivations.iterator()
fun getDerivations(): List<SolveDerivation> {
return derivations
}
} | gpl-3.0 |
codeka/wwmmo | planet-render/src/main/kotlin/au/com/codeka/warworlds/planetrender/TemplatedPointCloud.kt | 1 | 1812 | package au.com.codeka.warworlds.planetrender
import au.com.codeka.warworlds.common.PointCloud
import au.com.codeka.warworlds.common.Vector2
import au.com.codeka.warworlds.planetrender.Template.PointCloudTemplate
import java.util.*
/** A [PointCloud] that takes it's parameters from a [Template]. */
class TemplatedPointCloud(tmpl: PointCloudTemplate, rand: Random) : PointCloud(ArrayList()) {
/**
* This is the base class for implementations that generate point clouds. We contain the
* various properties the control how many points to generate, "randomness" etc.
*/
interface Generator {
fun generate(tmpl: PointCloudTemplate, rand: Random): ArrayList<Vector2>
}
/**
* Generates points by simply generating random (x,y) coordinates. This isn't usually
* very useful, because the points tend to clump up and look unrealistic.
*/
class TemplatedRandomGenerator : RandomGenerator(), Generator {
override fun generate(tmpl: PointCloudTemplate, rand: Random): ArrayList<Vector2> {
return generate(tmpl.density, rand)
}
}
/**
* Uses a poisson generator to generate more "natural" looking random points than the
* basic [RandomGenerator] does.
*/
class TemplatedPoissonGenerator : PoissonGenerator(), Generator {
override fun generate(tmpl: PointCloudTemplate, rand: Random): ArrayList<Vector2> {
return generate(tmpl.density, tmpl.randomness, rand)
}
}
init {
val g = when (tmpl.generator) {
PointCloudTemplate.Generator.Random -> {
TemplatedRandomGenerator()
}
PointCloudTemplate.Generator.Poisson -> {
TemplatedPoissonGenerator()
}
else -> {
throw RuntimeException("Unknown PointCloudGenerator: " + tmpl.generator)
}
}
points_ = g.generate(tmpl, rand)
}
} | mit |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/VimeoAccount.kt | 1 | 1156 | @file:JvmName("VimeoAccountUtils")
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.util.Date
/**
* This class represents an authenticated user of Vimeo, either logged in or logged out.
*
* @param expiresOn The date and time that the token expires.
* @param refreshToken The refresh token string.
* @param scope The scope or scopes that the token supports.
* @param user The authenticated and logged in user.
* @param tokenType The token type.
*/
@JsonClass(generateAdapter = true)
data class VimeoAccount(
@Json(name = "access_token")
override val accessToken: String,
@Json(name = "expires_on")
val expiresOn: Date? = null,
@Json(name = "refresh_token")
val refreshToken: String? = null,
@Json(name = "scope")
val scope: String? = null,
@Json(name = "user")
val user: User? = null,
@Json(name = "token_type")
val tokenType: String? = null
) : AccessTokenProvider
/**
* True if the account represents a logged in user, false if it represents a logged out user.
*/
val VimeoAccount.isLoggedIn: Boolean
get() = user != null
| mit |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsStructItem.kt | 3 | 1917 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.search.SearchScope
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.macros.RsExpandedElement
import org.rust.lang.core.psi.RsElementTypes.UNION
import org.rust.lang.core.psi.RsPsiImplUtil
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.stubs.RsStructItemStub
import org.rust.lang.core.types.RsPsiTypeImplUtil
import org.rust.lang.core.types.ty.Ty
import javax.swing.Icon
val RsStructItem.union: PsiElement?
get() = node.findChildByType(UNION)?.psi
enum class RsStructKind {
STRUCT,
UNION
}
val RsStructItem.kind: RsStructKind get() {
val hasUnion = greenStub?.isUnion ?: (union != null)
return if (hasUnion) RsStructKind.UNION else RsStructKind.STRUCT
}
val RsStructItem.isTupleStruct get() = tupleFields != null
abstract class RsStructItemImplMixin : RsStubbedNamedElementImpl<RsStructItemStub>, RsStructItem {
constructor(node: ASTNode) : super(node)
constructor(stub: RsStructItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int): Icon {
val baseIcon = when (kind) {
RsStructKind.STRUCT -> RsIcons.STRUCT
RsStructKind.UNION -> RsIcons.UNION
}
return iconWithVisibility(flags, baseIcon)
}
override val crateRelativePath: String? get() = RsPsiImplUtil.crateRelativePath(this)
override val declaredType: Ty get() = RsPsiTypeImplUtil.declaredType(this)
override fun getContext(): PsiElement? = RsExpandedElement.getContextImpl(this)
override fun getUseScope(): SearchScope = RsPsiImplUtil.getDeclarationUseScope(this) ?: super.getUseScope()
}
| mit |
TeamWizardry/LibrarianLib | modules/courier/src/test/kotlin/com/teamwizardry/librarianlib/courier/test/LibLibCourierTest.kt | 1 | 2566 | package com.teamwizardry.librarianlib.courier.test
import com.teamwizardry.librarianlib.core.util.ModLogManager
import com.teamwizardry.librarianlib.courier.CourierClientPlayNetworking
import com.teamwizardry.librarianlib.courier.CourierServerPlayNetworking
import com.teamwizardry.librarianlib.testcore.TestModContentManager
import com.teamwizardry.librarianlib.testcore.content.TestItem
import net.fabricmc.api.ClientModInitializer
import net.fabricmc.api.DedicatedServerModInitializer
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.networking.v1.PacketSender
import net.minecraft.block.Blocks
import net.minecraft.client.MinecraftClient
import net.minecraft.client.network.ClientPlayNetworkHandler
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.LiteralText
internal object LibLibCourierTest {
val logManager: ModLogManager = ModLogManager("liblib-courier-test", "LibrarianLib Courier Test")
val manager: TestModContentManager = TestModContentManager("liblib-courier-test", "Courier", logManager)
object CommonInitializer : ModInitializer {
private val logger = logManager.makeLogger<CommonInitializer>()
override fun onInitialize() {
manager.create<TestItem>("server_to_client") {
name = "Server to client packet"
rightClick.server {
val packet = TestPacket(Blocks.DIRT, 42)
packet.manual = 100
player.sendMessage(LiteralText("Server sending: $packet (manual = ${packet.manual})"), false)
CourierServerPlayNetworking.send(player as ServerPlayerEntity, TestPacketTypes.testPacket, packet)
}
}
manager.registerCommon()
}
}
object ClientInitializer : ClientModInitializer {
private val logger = logManager.makeLogger<ClientInitializer>()
override fun onInitializeClient() {
CourierClientPlayNetworking.registerGlobalReceiver(TestPacketTypes.testPacket) { packet, context ->
context.execute {
context.client.player?.sendMessage(LiteralText("CourierPacket handler: $packet (manual = ${packet.manual})"), false)
}
}
manager.registerClient()
}
}
object ServerInitializer : DedicatedServerModInitializer {
private val logger = logManager.makeLogger<ServerInitializer>()
override fun onInitializeServer() {
manager.registerServer()
}
}
}
| lgpl-3.0 |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/tasks/IssueTask.kt | 1 | 1080 | package com.github.jk1.ytplugin.tasks
import com.github.jk1.ytplugin.issues.model.Issue
import com.intellij.tasks.Task
import com.intellij.tasks.TaskRepository
import com.intellij.tasks.TaskType
import com.intellij.tasks.impl.LocalTaskImpl
import javax.swing.Icon
/**
* Adapter class to use YouTrack issues as Task Management plugin tasks
*/
class IssueTask(val issue: Issue, val repo: TaskRepository): Task() {
override fun getId(): String = issue.id
override fun getSummary(): String = issue.summary
override fun getDescription(): String = issue.description
override fun getCreated() = issue.createDate
override fun getUpdated() = issue.updateDate
override fun isClosed() = issue.resolved
override fun getComments() = issue.comments.map { it.asTaskManagerComment() }.toTypedArray()
override fun getIcon(): Icon = LocalTaskImpl.getIconFromType(type, isIssue)
override fun getType(): TaskType = TaskType.OTHER
override fun isIssue() = true
override fun getIssueUrl() = issue.url
override fun getRepository() = repo
} | apache-2.0 |
TeamWizardry/LibrarianLib | modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/controllers/SingleSlotView.kt | 1 | 1032 | package com.teamwizardry.librarianlib.facade.test.controllers
import com.teamwizardry.librarianlib.core.util.vec
import com.teamwizardry.librarianlib.facade.container.FacadeView
import com.teamwizardry.librarianlib.facade.container.layers.SlotGridLayer
import com.teamwizardry.librarianlib.facade.layers.StackLayout
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.text.Text
class SingleSlotView(
container: SingleSlotController,
inventory: PlayerInventory,
title: Text
): FacadeView<SingleSlotController>(container, inventory, title) {
init {
val stack = StackLayout.build(5, 5)
.vertical()
.alignCenterX()
.spacing(4)
.add(SlotGridLayer(0, 0, container.contentsSlots.all, 1))
.add(SlotGridLayer(0, 0, container.playerSlots.main, 9))
.add(SlotGridLayer(0, 0, container.playerSlots.hotbar, 9))
.fit()
.build()
main.size = stack.size + vec(10, 10)
main.add(stack)
}
} | lgpl-3.0 |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/application/activities/MainActivity.kt | 1 | 12918 | package nl.rsdt.japp.application.activities
import android.app.AlertDialog
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.application.fragments.CarFragment
import nl.rsdt.japp.application.fragments.HomeFragment
import nl.rsdt.japp.application.fragments.JappMapFragment
import nl.rsdt.japp.application.navigation.FragmentNavigationManager
import nl.rsdt.japp.application.navigation.NavigationManager
import nl.rsdt.japp.jotial.auth.Authentication
import nl.rsdt.japp.jotial.data.nav.Join
import nl.rsdt.japp.jotial.data.nav.Location
import nl.rsdt.japp.jotial.data.nav.Resend
import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo
import nl.rsdt.japp.jotial.maps.MapManager
import nl.rsdt.japp.jotial.maps.window.CustomInfoWindowAdapter
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap
import nl.rsdt.japp.jotial.maps.wrapper.google.GoogleJotiMap
import nl.rsdt.japp.jotial.net.apis.AutoApi
import nl.rsdt.japp.service.AutoSocketHandler
import nl.rsdt.japp.service.LocationService
import nl.rsdt.japp.service.cloud.data.NoticeInfo
import nl.rsdt.japp.service.cloud.data.UpdateInfo
import nl.rsdt.japp.service.cloud.messaging.MessageManager
import org.acra.ACRA
import org.acra.ktx.sendWithAcra
import org.acra.log.ACRALog
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity(), IJotiMap.OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener, SharedPreferences.OnSharedPreferenceChangeListener, MessageManager.UpdateMessageListener {
/**
* Manages the GoogleMap.
*/
private var mapManager: MapManager = MapManager.instance
/**
* Manages the navigation between the fragments.
*/
private var navigationManager: NavigationManager = NavigationManager()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
JappPreferences.isFirstRun = false
/**
* Set a interceptor so that requests that give a 401 will result in a login activity.
*/
/*
Japp.setInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if(response.code() == 401) {
Authentication.startLoginActivity(MainActivity.this);
}
return response;
}
});
*/
/**
* Add this as a listener for UpdateMessages.
*/
Japp.updateManager?.add(this)
/**
* Register a on changed listener to the visible release_preferences.
*/
JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
/**
* Setup the MapManager.
*/
mapManager.onIntentCreate(intent)
mapManager.onCreate(savedInstanceState)
/**
* Setup the NavigationDrawer.
*/
val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer.addDrawerListener(toggle)
toggle.syncState()
/**
* Setup the NavigationView.
*/
val navigationView = findViewById<NavigationView>(R.id.nav_view)
navigationView.setNavigationItemSelectedListener(this)
/**
* Initialize the NavigationManager.
*/
navigationManager.initialize(this)
navigationManager.onSavedInstance(savedInstanceState)
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
navigationManager.onSaveInstanceState(savedInstanceState)
mapManager.onSaveInstanceState(savedInstanceState)
val id = JappPreferences.accountId
if (id >= 0) {
val autoApi = Japp.getApi(AutoApi::class.java)
autoApi.getInfoById(JappPreferences.accountKey, id).enqueue(object :
Callback<AutoInzittendeInfo> {
override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) {
if (response.code() == 200) {
val autoInfo = response.body()
if (autoInfo != null) {
val auto = autoInfo.autoEigenaar!!
AutoSocketHandler.join(Join(JappPreferences.accountUsername, auto))
}
}
}
override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) {
t.sendWithAcra()
Log.e(TAG, t.toString())
}
})
}
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState)
}
override fun onMapReady(map: IJotiMap) {
/**
* First set the custom InfoWindowAdapter and then invoke the onMapReady on the MapManager.
*/
if (map is GoogleJotiMap) {
map.setInfoWindowAdapter(CustomInfoWindowAdapter(layoutInflater, map.googleMap!!)) //// TODO: 07/08/17 change the GoogleMap to a JotiMap
} else {
//// TODO: 09/08/17 do stuff
}
mapManager.onMapReady(map)
mapManager.update()
}
/**
* TODO: don't use final here
*/
override fun onUpdateMessageReceived(info: UpdateInfo?) {
if (JappPreferences.isAutoUpdateEnabled) {
Snackbar.make(findViewById(R.id.container), getString(R.string.updating_type, info?.type), Snackbar.LENGTH_LONG).show()
mapManager.onUpdateMessageReceived(info)
} else {
Snackbar.make(findViewById(R.id.container), getString(R.string.update_available, info?.type), Snackbar.LENGTH_LONG)
.setAction(getString(R.string.update)) { mapManager.onUpdateMessageReceived(info) }
.show()
}
}
/**
* TODO: don't use final here
*/
override fun onNoticeMessageReceived(info: NoticeInfo?) {
this.runOnUiThread {
AlertDialog.Builder(this@MainActivity)
.setTitle(info?.title)
.setMessage(info?.body)
.setIcon(info?.drawable?:0)
.create()
.show()
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (JappPreferences.USE_OSM == key) {
recreate()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the options menu from XML
val inflater = menuInflater
inflater.inflate(R.menu.options_menu, menu)
/**
* TODO: fix search system
*/
//searchManager.onCreateOptionsMenu(menu);
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.refresh) {
mapManager.update()
/**
* Update the vos status on the home fragment.
*/
val fragment = navigationManager.getFragment(FragmentNavigationManager.FRAGMENT_HOME) as HomeFragment?
if (fragment?.isAdded==true) {
fragment.refresh()
}
val carfragment = navigationManager.getFragment(FragmentNavigationManager.FRAGMENT_CAR) as CarFragment?
carfragment?.refresh()
val id = JappPreferences.accountId
if (id >= 0) {
val autoApi = Japp.getApi(AutoApi::class.java)
autoApi.getInfoById(JappPreferences.accountKey, id).enqueue(object :
Callback<AutoInzittendeInfo> {
override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) {
if (response.code() == 200) {
val autoInfo = response.body()
if (autoInfo != null) {
val auto = autoInfo.autoEigenaar!!
AutoSocketHandler.join(Join(JappPreferences.accountUsername, auto))
AutoSocketHandler.resend(Resend(auto))
}
}
}
override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) {
Log.e(TAG, t.message?:"error")
t.sendWithAcra()
}
})
}
return true
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
if (navigationManager.hasBackStack()) {
navigationManager.onBackPressed()
} else {
super.onBackPressed()
}
}
}
public override fun onStart() {
super.onStart()
}
public override fun onResume() {
super.onResume()
navigationManager.setupMap(this)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
val action = intent.action
if (action != null && action == LocationService.ACTION_REQUEST_LOCATION_SETTING) {
val mapFragment = navigationManager.getFragment(FragmentNavigationManager.FRAGMENT_MAP) as JappMapFragment?
mapFragment?.movementManager?.requestLocationSettingRequest()
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == JappMapFragment.REQUEST_CHECK_SETTINGS) {
val mapFragment = navigationManager.getFragment(FragmentNavigationManager.FRAGMENT_MAP) as JappMapFragment?
mapFragment?.movementManager?.postResolutionResultToService(resultCode)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
val id = item.itemId
if (id == R.id.nav_home) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_HOME)
} else if (id == R.id.nav_map) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_MAP)
} else if (id == R.id.nav_settings) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_SETTINGS)
} else if (id == R.id.nav_car) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_CAR)
} else if (id == R.id.nav_about) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_ABOUT)
} else if (id == R.id.nav_help) {
navigationManager.switchTo(FragmentNavigationManager.FRAGMENT_HELP)
} else if (id == R.id.nav_log_out) {
Authentication.startLoginActivity(this)
}
val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
drawer.closeDrawer(GravityCompat.START)
return true
}
public override fun onStop() {
super.onStop()
}
public override fun onDestroy() {
super.onDestroy()
Japp.setInterceptor(null)
/**
* Remove this as UpdateMessageListener.
*/
Japp.updateManager?.remove(this)
/**
* Unregister this as OnSharedPreferenceChangeListener.
*/
JappPreferences.visiblePreferences.unregisterOnSharedPreferenceChangeListener(this)
mapManager.onDestroy()
navigationManager.onDestroy()
}
companion object {
/**
* Defines a tag for this class.
*/
val TAG = "MainActivity"
}
}
| apache-2.0 |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/service/GeofencingRegistrationService.kt | 1 | 3414 | package de.tum.`in`.tumcampusapp.service
import android.Manifest
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.support.v4.app.JobIntentService
import android.support.v4.content.ContextCompat
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingClient
import com.google.android.gms.location.GeofencingRequest
import com.google.android.gms.location.LocationServices
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Const.ADD_GEOFENCE_EXTRA
import de.tum.`in`.tumcampusapp.utils.Const.GEOFENCING_SERVICE_JOB_ID
import de.tum.`in`.tumcampusapp.utils.Utils
/**
* Service that receives Geofencing requests and registers them.
*/
class GeofencingRegistrationService : JobIntentService() {
private lateinit var locationClient: GeofencingClient
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return Service.START_STICKY
}
override fun onCreate() {
super.onCreate()
locationClient = LocationServices.getGeofencingClient(baseContext)
Utils.log("Service started")
}
@SuppressLint("MissingPermission")
override fun onHandleWork(intent: Intent) {
if (!isLocationPermissionGranted()) {
return
}
val request = intent.getParcelableExtra<GeofencingRequest>(Const.ADD_GEOFENCE_EXTRA) ?: return
val geofenceIntent = Intent(this, GeofencingUpdateReceiver::class.java)
val geofencePendingIntent = PendingIntent.getBroadcast(
this, 0, geofenceIntent, PendingIntent.FLAG_UPDATE_CURRENT)
locationClient.addGeofences(request, geofencePendingIntent)
Utils.log("Registered new Geofence")
}
private fun isLocationPermissionGranted(): Boolean {
return ContextCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
}
companion object {
@JvmStatic fun startGeofencing(context: Context, work: Intent) {
enqueueWork(context, GeofencingRegistrationService::class.java, GEOFENCING_SERVICE_JOB_ID, work)
}
/**
* Helper method for creating an intent containing a geofencing request
*/
fun buildGeofence(context: Context, id: String, latitude: Double, longitude: Double, range: Float): Intent {
val intent = Intent(context, GeofencingRegistrationService::class.java)
val geofence = Geofence.Builder()
.setRequestId(id)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(latitude, longitude, range)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build()
val geofencingRequest = GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER or GeofencingRequest.INITIAL_TRIGGER_EXIT)
.addGeofences(arrayListOf(geofence))
.build()
return intent.putExtra(ADD_GEOFENCE_EXTRA, geofencingRequest)
}
}
} | gpl-3.0 |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/AppTestingLevel.kt | 1 | 185 | package com.habitrpg.android.habitica.helpers
enum class AppTestingLevel(identifier: String) {
STAFF("staff"),
ALPHA("alpha"),
BETA("beta"),
PRODUCTION("production")
}
| gpl-3.0 |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/social/UserStyles.kt | 1 | 1258 | package com.habitrpg.android.habitica.models.social
import com.habitrpg.android.habitica.models.Avatar
import com.habitrpg.android.habitica.models.AvatarFlags
import com.habitrpg.android.habitica.models.user.Items
import com.habitrpg.android.habitica.models.user.Outfit
import com.habitrpg.android.habitica.models.user.Preferences
import com.habitrpg.android.habitica.models.user.Stats
import io.realm.RealmObject
import io.realm.annotations.RealmClass
@RealmClass(embedded = true)
open class UserStyles : RealmObject(), Avatar {
override val currentMount: String?
get() = items?.currentMount
override val currentPet: String?
get() = items?.currentPet
override val sleep: Boolean
get() = false
override val gemCount: Int
get() = 0
override val hourglassCount: Int
get() = 0
override val costume: Outfit?
get() = items?.gear?.costume
override val equipped: Outfit?
get() = items?.gear?.equipped
override val hasClass: Boolean
get() {
return false
}
override var stats: Stats? = null
override var preferences: Preferences? = null
override val flags: AvatarFlags?
get() = null
private var items: Items? = null
}
| gpl-3.0 |
androidx/androidx | compose/ui/ui-graphics/src/commonMain/kotlin/androidx/compose/ui/graphics/colorspace/WhitePoint.kt | 3 | 1537 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.graphics.colorspace
/**
* Class for constructing white points used in [RGB][Rgb] color space. The value is
* stored in the CIE xyY color space. The Y component of the white point is assumed
* to be 1.
*
* @see Illuminant
*/
data class WhitePoint(val x: Float, val y: Float) {
/**
* Illuminant for CIE XYZ white point
*/
constructor(x: Float, y: Float, z: Float) : this(x, y, z, x + y + z)
@Suppress("UNUSED_PARAMETER")
private constructor(x: Float, y: Float, z: Float, sum: Float) : this(x / sum, y / sum)
/**
* Converts a value from CIE xyY to CIE XYZ. Y is assumed to be 1 so the
* input xyY array only contains the x and y components.
*
* @return A new float array of length 3 containing XYZ values
*/
/*@Size(3)*/
internal fun toXyz(): FloatArray {
return floatArrayOf(x / y, 1.0f, (1f - x - y) / y)
}
}
| apache-2.0 |
androidx/androidx | navigation/navigation-safe-args-gradle-plugin/src/test/kotlin/androidx/navigation/safeargs/gradle/KotlinPluginTest.kt | 3 | 2392 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.safeargs.gradle
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
// Does not work in the Android Studio
@RunWith(JUnit4::class)
class KotlinPluginTest : BasePluginTest() {
@Test
fun runGenerateTaskForKotlin() {
setupSimpleKotlinBuildGradle()
runGradle("assembleDebug").assertSuccessfulTask("assembleDebug")
assertGenerated("debug/$NEXT_DIRECTIONS.kt")
assertGenerated("debug/$NEXT_ARGUMENTS.kt")
assertGenerated("debug/$MAIN_DIRECTIONS.kt")
}
@Test
fun runGenerateTaskForKotlinWithSuffix() {
testData("app-project-kotlin").copyRecursively(projectRoot())
projectSetup.writeDefaultBuildGradle(
prefix = """
plugins {
id('com.android.application')
id('kotlin-android')
id('androidx.navigation.safeargs.kotlin')
}
""".trimIndent(),
suffix = """
android {
namespace 'androidx.navigation.testapp'
buildTypes {
debug {
applicationIdSuffix ".foo"
}
}
}
dependencies {
implementation "${projectSetup.props.kotlinStblib}"
implementation "${projectSetup.props.navigationRuntime}"
}
""".trimIndent()
)
runGradle("assembleDebug").assertSuccessfulTask("assembleDebug")
assertGenerated("debug/$FOO_NEXT_DIRECTIONS.kt")
assertGenerated("debug/$FOO_NEXT_ARGUMENTS.kt")
assertGenerated("debug/$FOO_MAIN_DIRECTIONS.kt")
}
} | apache-2.0 |
taigua/exercism | kotlin/phone-number/src/test/kotlin/PhoneNumberTest.kt | 1 | 1801 | import org.junit.Test
import kotlin.test.assertEquals
class PhoneNumberTest {
@Test
fun cleansNumber() {
val expectedNumber = "1234567890"
val actualNumber = PhoneNumber("(123) 456-7890").number
assertEquals(expectedNumber, actualNumber)
}
@Test
fun cleansNumberWithDots() {
val expectedNumber = "1234567890"
val actualNumber = PhoneNumber("123.456.7890").number
assertEquals(expectedNumber, actualNumber)
}
@Test
fun validWhen11DigitsAndFirstIs1() {
val expectedNumber = "1234567890"
val actualNumber = PhoneNumber("11234567890").number
assertEquals(expectedNumber, actualNumber)
}
@Test
fun invalidWhenOnly11Digits() {
val expectedNumber = "0000000000"
val actualNumber = PhoneNumber("21234567890").number
assertEquals(expectedNumber, actualNumber)
}
@Test
fun invalidWhen9Digits() {
val expectedNumber = "0000000000"
val actualNumber = PhoneNumber("123456789").number
assertEquals(expectedNumber, actualNumber)
}
@Test
fun areaCode() {
val expectedAreaCode = "123"
val actualAreaCode = PhoneNumber("1234567890").areaCode
assertEquals(expectedAreaCode, actualAreaCode)
}
@Test
fun toStringPrint() {
val expectedtoStringNumber = "(123) 456-7890"
val actualtoStringNumber = PhoneNumber("1234567890").toString()
assertEquals(expectedtoStringNumber, actualtoStringNumber)
}
@Test
fun toStringPrintWithFullUSPhoneNumber() {
val expectedtoStringNumber = "(123) 456-7890"
val actualtoStringNumber = PhoneNumber("11234567890").toString()
assertEquals(expectedtoStringNumber, actualtoStringNumber)
}
}
| mit |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/blacklist/adapter/BlacklistAdapter.kt | 1 | 2221 | package com.sedsoftware.yaptalker.presentation.feature.blacklist.adapter
import androidx.collection.SparseArrayCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.domain.device.Settings
import com.sedsoftware.yaptalker.presentation.base.adapter.YapEntityDelegateAdapter
import com.sedsoftware.yaptalker.presentation.model.DisplayedItemType
import com.sedsoftware.yaptalker.presentation.model.base.BlacklistedTopicModel
import javax.inject.Inject
class BlacklistAdapter @Inject constructor(
clickListener: BlacklistElementsClickListener,
settings: Settings
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items: ArrayList<BlacklistedTopicModel>
private var delegateAdapters = SparseArrayCompat<YapEntityDelegateAdapter>()
init {
delegateAdapters.put(
DisplayedItemType.BLACKLISTED_TOPIC, BlacklistDelegateAdapter(clickListener, settings)
)
items = ArrayList()
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
delegateAdapters.get(viewType)!!.onCreateViewHolder(parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
delegateAdapters.get(getItemViewType(position))?.onBindViewHolder(holder, items[position])
with(holder.itemView) {
AnimationUtils.loadAnimation(context, R.anim.recyclerview_fade_in).apply {
startAnimation(this)
}
}
}
override fun onViewDetachedFromWindow(holder: ViewHolder) {
super.onViewDetachedFromWindow(holder)
holder.itemView.clearAnimation()
}
override fun getItemViewType(position: Int): Int =
items[position].getEntityType()
override fun getItemCount() =
items.size
override fun getItemId(position: Int) =
position.toLong()
fun setTopics(topics: List<BlacklistedTopicModel>) {
items.clear()
items.addAll(topics)
notifyDataSetChanged()
}
}
| apache-2.0 |
stoyicker/dinger | app/src/main/kotlin/app/settings/SettingsPreferenceFragmentCompat.kt | 1 | 2428 | package app.settings
import android.annotation.SuppressLint
import android.content.Intent
import android.content.startIntent
import android.net.Uri
import android.os.Bundle
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import domain.autoswipe.ImmediatePostAutoSwipeUseCase
import io.reactivex.observers.DisposableCompletableObserver
import io.reactivex.schedulers.Schedulers
import org.stoyicker.dinger.R
internal class SettingsPreferenceFragmentCompat : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.prefs_settings, rootKey)
addTriggerToAutoswipeEnabledPreference()
initializeSharePreference()
initializeAboutTheAppPreference()
}
private fun addTriggerToAutoswipeEnabledPreference() {
findPreference(context?.getString(R.string.preference_key_autoswipe_enabled))
?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, value ->
if (value is Boolean && value) {
ImmediatePostAutoSwipeUseCase(context!!, Schedulers.trampoline()).execute(
object : DisposableCompletableObserver() {
override fun onComplete() {
}
override fun onError(error: Throwable) {
}
})
}
true
}
}
private fun initializeSharePreference() {
findPreference(context?.getString(R.string.preference_key_share))
.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
@SuppressLint("InlinedApi")
flags += Intent.FLAG_ACTIVITY_NEW_DOCUMENT
putExtra(Intent.EXTRA_TEXT, context?.getString(
R.string.dinger_website_download))
}
context?.startIntent(Intent.createChooser(
intent, getString(R.string.action_share_title)))
true
}
}
private fun initializeAboutTheAppPreference() {
findPreference(context?.getString(R.string.preference_key_about_the_app))
.onPreferenceClickListener = Preference.OnPreferenceClickListener {
context?.startIntent(Intent(
Intent.ACTION_VIEW, Uri.parse(getString(R.string.dinger_website))))
true
}
}
companion object {
const val FRAGMENT_TAG = "SettingsPreferenceFragmentCompat"
}
}
| mit |
outlying/card-check | app/src/main/kotlin/com/antyzero/cardcheck/ui/screen/main/MainPresenter.kt | 1 | 1369 | package com.antyzero.cardcheck.ui.screen.main
import com.antyzero.cardcheck.CardCheck
import com.antyzero.cardcheck.card.Card
import com.antyzero.cardcheck.data.CardTransformer
import com.antyzero.cardcheck.job.Jobs
import com.antyzero.cardcheck.logger.Logger
import com.antyzero.cardcheck.mvp.Presenter
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class MainPresenter(val cardCheck: CardCheck, val jobs: Jobs, val logger: Logger) : Presenter<MainView> {
lateinit var view: MainView
override fun attachView(view: MainView) {
this.view = view
}
fun loadCardList() {
Observable.fromIterable(cardCheck.getCards())
.compose(CardTransformer.status(cardCheck))
.toList()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe {
view.showLoading()
}
.doAfterTerminate {
view.hideLoading()
}
.subscribe(
{ cards -> view.showCards(cards) },
{ view.hideLoading() })
jobs.scheduleCardCheck()
}
fun removeCard(card: Card) {
cardCheck.removeCard(card)
}
}
| gpl-3.0 |
codehz/container | app/src/main/java/one/codehz/container/SpaceManagerActivity.kt | 1 | 3080 | package one.codehz.container
import android.app.ActivityManager
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuItem
import one.codehz.container.adapters.SpaceManagerAdapter
import one.codehz.container.base.BaseActivity
import one.codehz.container.ext.MakeLoaderCallbacks
import one.codehz.container.ext.get
import one.codehz.container.ext.systemService
import one.codehz.container.models.SpaceManagerModel
import org.apache.commons.io.FileUtils
import java.io.File
class SpaceManagerActivity : BaseActivity(R.layout.space_manager) {
val contentList by lazy<RecyclerView> { this[R.id.content_list] }
val contentAdapter by lazy { SpaceManagerAdapter() }
val linearLayoutManager by lazy { LinearLayoutManager(this) }
companion object {
val APP_DATA = 0
val APP_OPT = 1
}
val appDataLoader by MakeLoaderCallbacks({ this }, { dataList[APP_DATA].amount = it; syncList() }) {
val data = filesDir.parent
FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectoryAsBigInteger(File("$data/virtual/data")))
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.space_manager, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.clear_data -> {
systemService<ActivityManager>(Context.ACTIVITY_SERVICE).clearApplicationUserData()
true
}
android.R.id.home -> {
finish()
true
}
else -> false
}
val appOptLoader by MakeLoaderCallbacks({ this }, { dataList[APP_OPT].amount = it; syncList() }) {
val data = filesDir.parent
FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectoryAsBigInteger(File("$data/virtual/opt")))
}
val dataList by lazy {
mutableListOf(
SpaceManagerModel(getString(R.string.space_application_in_container), ManageContainerApplicationStorageActivity::class),
SpaceManagerModel(getString(R.string.container_application_optimization_data), ManageContainerApplicationStorageActivity::class)
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
with(contentList) {
adapter = contentAdapter
layoutManager = linearLayoutManager
itemAnimator = DefaultItemAnimator()
}
syncList()
supportLoaderManager.restartLoader(APP_DATA, null, appDataLoader)
supportLoaderManager.restartLoader(APP_OPT, null, appOptLoader)
}
val syncList: () -> Unit
get() = contentAdapter.updateModels(dataList.map { it.clone() })
} | gpl-3.0 |
EventFahrplan/EventFahrplan | app/src/main/java/nerd/tuxmobil/fahrplan/congress/repositories/SessionsTransformer.kt | 1 | 3193 | package nerd.tuxmobil.fahrplan.congress.repositories
import androidx.annotation.VisibleForTesting
import nerd.tuxmobil.fahrplan.congress.models.RoomData
import nerd.tuxmobil.fahrplan.congress.models.ScheduleData
import nerd.tuxmobil.fahrplan.congress.models.Session
class SessionsTransformer @VisibleForTesting constructor(
private val roomProvider: RoomProvider
) {
companion object {
fun createSessionsTransformer(): SessionsTransformer {
val roomProvider = object : RoomProvider {
override val prioritizedRooms: List<String> = listOf(
"Saal 1",
"Saal 2",
"Saal G",
"Saal 6",
"Saal 17",
"Lounge"
)
override val deprioritizedRooms: List<String> = emptyList()
}
return SessionsTransformer(roomProvider)
}
}
/**
* Transforms the given [sessions] for the given [dayIndex] into a [ScheduleData] object.
*
* Apart from the [dayIndex] it contains a list of room names and their associated sessions
* (sorted by [Session.dateUTC]). Rooms names are added in a defined order: room names of
* prioritized rooms first, then all other room names in the order defined by the given session.
* After adding room names the original order [Session.roomIndex] is no longer of interest.
*/
fun transformSessions(dayIndex: Int, sessions: List<Session>): ScheduleData {
// Pre-populate the map with prioritized rooms
val roomMap = roomProvider.prioritizedRooms
.associateWith { mutableListOf<Session>() }
.toMutableMap()
val sortedSessions = sessions.sortedBy { it.roomIndex }
for (session in sortedSessions) {
val sessionsInRoom = roomMap.getOrPut(session.room) { mutableListOf() }
sessionsInRoom.add(session)
}
val roomDataList = roomMap.mapNotNull { (roomName, sessions) ->
if (sessions.isEmpty()) {
// Drop prioritized rooms without sessions
null
} else {
RoomData(
roomName = roomName,
sessions = sessions.sortedBy { it.dateUTC }.toList()
)
}
}.sortWithDeprioritizedRooms(roomProvider.deprioritizedRooms)
return ScheduleData(dayIndex, roomDataList)
}
}
interface RoomProvider {
val prioritizedRooms: List<String>
val deprioritizedRooms: List<String>
}
/**
* Moves all [RoomData] items with a room name contained in [deprioritizedRooms] to the end of the list.
* The order of room names in the [deprioritizedRooms] list is applied to the receiving list.
*/
private fun List<RoomData>.sortWithDeprioritizedRooms(deprioritizedRooms: List<String>): List<RoomData> {
if (deprioritizedRooms.isEmpty()) {
return this
}
val (tail, head) = partition { deprioritizedRooms.contains(it.roomName) }
val sortedTail = deprioritizedRooms.mapNotNull { room ->
tail.firstOrNull { room == it.roomName }
}
return head + sortedTail
}
| apache-2.0 |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mcp/srg/StandardSrgParser.kt | 1 | 1750 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.srg
import com.demonwav.mcdev.util.MemberReference
import com.google.common.collect.ImmutableBiMap
import java.nio.file.Files
import java.nio.file.Path
object StandardSrgParser : SrgParser {
override fun parseSrg(path: Path): McpSrgMap {
val classMapBuilder = ImmutableBiMap.builder<String, String>()
val fieldMapBuilder = ImmutableBiMap.builder<MemberReference, MemberReference>()
val methodMapBuilder = ImmutableBiMap.builder<MemberReference, MemberReference>()
val srgNames = hashMapOf<String, String>()
Files.lines(path).forEach { line ->
val parts = line.split(' ')
when (parts[0]) {
"CL:" -> {
val srg = parts[1].replace('/', '.')
val mcp = parts[2].replace('/', '.')
classMapBuilder.put(mcp, srg)
}
"FD:" -> {
val mcp = SrgMemberReference.parse(parts[1])
val srg = SrgMemberReference.parse(parts[2])
fieldMapBuilder.put(mcp, srg)
srgNames[srg.name] = mcp.name
}
"MD:" -> {
val mcp = SrgMemberReference.parse(parts[1], parts[2])
val srg = SrgMemberReference.parse(parts[3], parts[4])
methodMapBuilder.put(mcp, srg)
srgNames[srg.name] = mcp.name
}
}
}
return McpSrgMap(classMapBuilder.build(), fieldMapBuilder.build(), methodMapBuilder.build(), srgNames)
}
}
| mit |
RobotPajamas/Blueteeth | blueteeth-sample/src/main/kotlin/com/robotpajamas/android/blueteeth/ui/widgets/recyclers/SingleLayoutAdapter.kt | 1 | 228 | package com.robotpajamas.android.blueteeth.ui.widgets.recyclers
abstract class SingleLayoutAdapter(private val layoutId: Int) : ViewAdapter() {
override fun getLayoutId(position: Int): Int {
return layoutId
}
}
| apache-2.0 |
RobotPajamas/Blueteeth | blueteeth/src/main/kotlin/com/robotpajamas/blueteeth/BlueteethDevice.kt | 1 | 14804 | package com.robotpajamas.blueteeth
import android.bluetooth.*
import android.content.Context
import android.os.Handler
import android.os.Looper
import com.robotpajamas.blueteeth.extensions.compositeId
import com.robotpajamas.blueteeth.extensions.getCharacteristic
import com.robotpajamas.blueteeth.models.*
import com.robotpajamas.dispatcher.Dispatch
import com.robotpajamas.dispatcher.Result
import com.robotpajamas.dispatcher.RetryPolicy
import com.robotpajamas.dispatcher.SerialDispatcher
import java.util.*
// TODO: Make this object threadsafe and async-safe (called twice in a row, should return a failure?)
class BlueteethDevice private constructor() : Device {
// TODO: The handler posts would be better if abstracted away - Does this need to be dependency injected for testing?
private var context: Context? = null
private val handler = Handler(Looper.getMainLooper())
private var bluetoothDevice: BluetoothDevice? = null
private var bluetoothGatt: BluetoothGatt? = null
private val subscriptionDescriptor = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
private var dispatcher = SerialDispatcher()
val name: String
get() = bluetoothDevice?.name ?: ""
val id: String
get() = bluetoothDevice?.address ?: ""
/** Connectable **/
private var autoReconnect = false
private var connectionHandler: ConnectionHandler? = null
var isConnected = false
private set
// Autoreconnect == true is a slow connection, false is fast
// https://stackoverflow.com/questions/22214254/android-ble-connect-slowly
override fun connect(timeout: Int?, autoReconnect: Boolean, block: ConnectionHandler?) {
BLog.d("connect: Attempting to connect: Timeout=$timeout, autoReconnect=$autoReconnect")
this.autoReconnect = autoReconnect
connectionHandler = block
// if (bluetoothGatt != null) {
// bluetoothGatt?.close()
// bluetoothGatt = null
// }
// TODO: Passing in a null context seems to work, but what are the consequences?
// TODO: Should I grab the application context from the BlueteethManager? Seems odd...
handler.post {
if (isConnected) {
BLog.d("connect: Already connected, returning - disregarding autoReconnect")
connected()
return@post
}
if (bluetoothGatt != null) {
bluetoothGatt?.connect()
} else {
bluetoothGatt = bluetoothDevice?.connectGatt(null, autoReconnect, mGattCallback)
}
}
}
override fun disconnect(autoReconnect: Boolean) {
BLog.d("disconnect: Disconnecting... autoReconnect=$autoReconnect")
this.autoReconnect = autoReconnect
handler.post {
bluetoothGatt?.disconnect() ?: BLog.d("disconnect: Cannot disconnect - GATT is null")
}
}
private fun connected() {
isConnected = true
connectionHandler?.invoke(isConnected)
}
// private fun connecting() {
//
// }
private fun disconnected() {
isConnected = false
// Clear all pending queue items
dispatcher.clear()
// Clear all subscriptions
notifications.clear()
// Call appropriate callbacks
connectionHandler?.invoke(isConnected)
}
/** Discoverable **/
override fun discoverServices(block: ServiceDiscovery?) {
BLog.d("discoverServices: Attempting to discover services")
val item = Dispatch<Boolean>(
id = "discoverServices", // TODO: Need something better than hardcoded string
timeout = 60, // Discovery can take a helluva long time depending on phone
retryPolicy = RetryPolicy.RETRY,
execution = { cb ->
if (!isConnected || bluetoothGatt == null) {
// TODO: Need proper exceptions/errors
cb(Result.Failure(RuntimeException("discoverServices: Device is not connected, or GATT is null")))
return@Dispatch
}
bluetoothGatt?.discoverServices()
},
completion = { result ->
result.onFailure {
BLog.e("Service discovery failed with $it")
}
block?.invoke(result)
})
dispatcher.enqueue(item)
}
/** Readable **/
override fun read(characteristic: UUID, service: UUID, block: ReadHandler) {
BLog.d("read: Attempting to read $characteristic")
val compositeId = service.toString() + characteristic.toString()
val item = Dispatch<ByteArray>(
id = compositeId,
timeout = 3,
retryPolicy = RetryPolicy.RETRY,
execution = { cb ->
if (!isConnected) {
cb(Result.Failure(RuntimeException("read: Device is not connected")))
return@Dispatch
}
val gattCharacteristic = bluetoothGatt?.getCharacteristic(characteristic, service)
?: run {
val error = "read: Failed to get Gatt Char: $characteristic in $service from $bluetoothGatt"
cb(Result.Failure(RuntimeException(error)))
return@Dispatch
}
bluetoothGatt?.readCharacteristic(gattCharacteristic)
}) { result ->
result.onFailure {
BLog.e("Read completion failed with $it")
}
block(result)
}
dispatcher.enqueue(item)
}
private val notifications = HashMap<String, ReadHandler>()
override fun subscribeTo(characteristic: UUID, service: UUID, block: ReadHandler) {
BLog.d("subscribeTo: Adding Notification listener to %s", characteristic.toString())
val compositeId = service.toString() + characteristic.toString()
val item = Dispatch<Boolean>(
id = subscriptionDescriptor.toString(),
timeout = 3,
retryPolicy = RetryPolicy.RETRY,
execution = { cb ->
if (!isConnected) {
cb(Result.Failure(RuntimeException("subscribe: Device is not connected")))
return@Dispatch
}
val gattCharacteristic = bluetoothGatt?.getCharacteristic(characteristic, service)
?: run {
val error = "subscribe: Failed to get Gatt Char: $characteristic in $service from $bluetoothGatt"
cb(Result.Failure(RuntimeException(error)))
return@Dispatch
}
val gattDescriptor = gattCharacteristic.getDescriptor(subscriptionDescriptor)
?: run {
val error = "subscribe: Descriptor not available - $compositeId"
cb(Result.Failure(RuntimeException(error)))
return@Dispatch
}
notifications[compositeId] = block
bluetoothGatt?.setCharacteristicNotification(gattCharacteristic, true)
gattDescriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
bluetoothGatt?.writeDescriptor(gattDescriptor)
}) { result ->
result.onFailure {
BLog.e("Read completion failed with $it")
}
}
dispatcher.enqueue(item)
}
/** Writable **/
override fun write(data: ByteArray, characteristic: UUID, service: UUID, type: Writable.Type, block: WriteHandler?) {
BLog.d("write: Attempting to write ${Arrays.toString(data)} to $characteristic")
val compositeId = service.toString() + characteristic.toString()
val item = Dispatch<Boolean>(
id = compositeId,
timeout = 3,
retryPolicy = RetryPolicy.RETRY,
execution = { cb ->
if (!isConnected) {
cb(Result.Failure(RuntimeException("write: Device is not connected, or GATT is null")))
return@Dispatch
}
val gattCharacteristic = bluetoothGatt?.getCharacteristic(characteristic, service)
?: run {
val error = "write: Failed to get Gatt Char: $characteristic in $service from $bluetoothGatt"
cb(Result.Failure(RuntimeException(error)))
return@Dispatch
}
gattCharacteristic.value = data
gattCharacteristic.writeType = when (type) {
Writable.Type.WITH_RESPONSE -> BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
Writable.Type.WITHOUT_RESPONSE -> BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
}
bluetoothGatt?.writeCharacteristic(gattCharacteristic)
}) { result ->
result.onFailure {
BLog.e("Write completion failed with $it")
}
block?.invoke(result)
}
dispatcher.enqueue(item)
}
internal constructor(context: Context, device: BluetoothDevice) : this() {
bluetoothDevice = device
// TODO: Need this for registering to the bonding process - ugly...
this.context = context
}
internal constructor(context: Context,
device: BluetoothDevice,
rssi: Int,
scanRecord: ByteArray) : this(context, device) {
// this.rssi = rssi
// mScanRecord = scanRecord
}
fun close() {
bluetoothGatt?.disconnect()
handler.post {
bluetoothGatt?.close()
bluetoothGatt = null
}
}
/***
* Should never really get here, only if someone forgets to call close() explicitly
* @throws Throwable
*/
@Throws(Throwable::class)
private fun finalize() {
try {
close()
} finally {
BLog.e("Could not close the BlueteethDevice")
}
}
private val mGattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
super.onConnectionStateChange(gatt, status, newState)
BLog.d("onConnectionStateChange - gatt: $gatt, status: $status, newState: $newState")
// Removed check for GATT_SUCCESS - do we care? I think the current state is all that matters...
// TODO: When changing isConnected to a ConnectionState - account for STATE_CONNECTING as well
when (newState) {
BluetoothProfile.STATE_CONNECTED -> {
BLog.d("onConnectionStateChange - Connected")
connected()
}
BluetoothProfile.STATE_CONNECTING -> {
BLog.d("onConnectionStateChange - Connecting")
// connecting()
}
BluetoothProfile.STATE_DISCONNECTING -> {
BLog.d("onConnectionStateChange - Disconnecting")
}
BluetoothProfile.STATE_DISCONNECTED -> {
BLog.d("onConnectionStateChange - Disconnected")
disconnected()
}
}
}
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
super.onServicesDiscovered(gatt, status)
BLog.d("onServicesDiscovered - gatt: $gatt, status: $status")
val result: Result<Boolean> = when (status) {
BluetoothGatt.GATT_SUCCESS -> Result.Success(true)
else -> Result.Failure(RuntimeException("onServicesDiscovered - Failed with status: $status"))
}
dispatcher.dispatched<Boolean>("discoverServices")?.complete(result)
}
override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
super.onCharacteristicRead(gatt, characteristic, status)
BLog.d("onCharacteristicRead - gatt: $gatt, status: $status, characteristic: ${characteristic.compositeId}")
val result: Result<ByteArray> = when (status) {
BluetoothGatt.GATT_SUCCESS -> Result.Success(characteristic.value)
else -> Result.Failure(RuntimeException("onCharacteristicRead - Failed with status: $status"))
}
dispatcher.dispatched<ByteArray>(characteristic.compositeId)?.complete(result)
}
override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
super.onCharacteristicWrite(gatt, characteristic, status)
BLog.d("onCharacteristicWrite - gatt: $gatt, status: $status, characteristic: $characteristic")
val result: Result<Boolean> = when (status) {
BluetoothGatt.GATT_SUCCESS -> Result.Success(true)
else -> Result.Failure(RuntimeException("onCharacteristicWrite - Failed with status: $status"))
}
dispatcher.dispatched<Boolean>(characteristic.compositeId)?.complete(result)
}
override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
super.onCharacteristicChanged(gatt, characteristic)
BLog.d("OnCharacteristicChanged - gatt: $gatt, characteristic: ${characteristic.compositeId}")
notifications[characteristic.compositeId]?.invoke(Result.Success(characteristic.value))
}
override fun onDescriptorWrite(gatt: BluetoothGatt?, descriptor: BluetoothGattDescriptor?, status: Int) {
super.onDescriptorWrite(gatt, descriptor, status)
BLog.d("onDescriptorWrite - gatt: $gatt, descriptor: ${descriptor?.uuid?.toString()}, status: $status")
val result: Result<Boolean> = when (status) {
BluetoothGatt.GATT_SUCCESS -> Result.Success(true)
else -> Result.Failure(RuntimeException("onDescriptorWrite - Failed with status: $status"))
}
dispatcher.dispatched<Boolean>(descriptor?.uuid.toString())?.complete(result)
}
}
}
| apache-2.0 |
wordpress-mobile/AztecEditor-Android | aztec/src/main/kotlin/org/wordpress/aztec/ITextFormat.kt | 1 | 390 | package org.wordpress.aztec
/**
* Defines the text formatting type.
*
* It is used instead of an enumeration, so that additional plugins can define their own format types.
* The basic format types are defined in [AztecTextFormat]. A plugin should provide its own *enum class* implementation.
*
* @property name the enum member name.
*/
interface ITextFormat {
val name: String
} | mpl-2.0 |
handstandsam/ShoppingApp | shopping-cart-room/src/androidTest/java/com/handstandsam/shoppingapp/cart/RoomShoppingCartTestDelegate.kt | 1 | 2247 | package com.handstandsam.shoppingapp.cart
import androidx.room.Room
import androidx.test.platform.app.InstrumentationRegistry
import com.handstandsam.shoppingapp.models.Item
import org.junit.Assert.assertEquals
/**
* A TestDelegate is meant to abstract away the test details to make the tests more readable.
*/
class RoomShoppingCartTestDelegate {
/**
* InMemory Instance of the [Room] Database
*/
private val shoppingCart: ShoppingCart = ShoppingCart(
RoomShoppingCartDao(
Room.inMemoryDatabaseBuilder(
InstrumentationRegistry.getInstrumentation().targetContext,
RoomItemInCartDatabase::class.java
).build()
)
)
suspend fun incrementItemInCart(item: Item) = apply {
println("adding item: $item")
shoppingCart.incrementItemInCart(item)
println("after adding item: ${shoppingCart.latestItemsInCart()}")
}
suspend fun assertPersisted(item: Item, quantity: Long) = apply {
println("asserting there is $quantity of $item")
val matchingItemsInCart = shoppingCart.latestItemsInCart()
.filter { it.item.label == item.label }
assertEquals(matchingItemsInCart.size, 1)
val matchingItemInCart = matchingItemsInCart[0]
assertEquals(matchingItemInCart.item, item)
assertEquals(matchingItemInCart.quantity, quantity)
}
suspend fun assertTotalItemsInCart(typeCount: Int, totalCount: Int) = apply {
println("asserting there are $typeCount types of items with a total of $totalCount items")
val itemsInCart = shoppingCart.latestItemsInCart()
val itemTypeCount = itemsInCart.size
assertEquals(itemTypeCount, typeCount)
val totalItems = itemsInCart.sumOf { it.quantity.toInt() }
assertEquals(totalItems, totalCount)
}
suspend fun decrementItemInCart(item: Item) = apply {
println("decrementItemInCart $item")
shoppingCart.decrementItemInCart(item)
println("decrementItemInCart finished: ${shoppingCart.latestItemsInCart()}")
}
suspend fun clearDb() = apply {
shoppingCart.empty()
println("empty finished: ${shoppingCart.latestItemsInCart()}")
}
} | apache-2.0 |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/settings/category/SettingsCategoryPresenter.kt | 2 | 227 | package ru.fantlab.android.ui.modules.settings.category
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class SettingsCategoryPresenter : BasePresenter<SettingsCategoryMvp.View>(), SettingsCategoryMvp.Presenter | gpl-3.0 |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/controller/rest/ProductCategoryRestController.kt | 1 | 5024 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* Rest controller responsible for handling product scans.
*/
package dk.etiktak.backend.controller.rest
import dk.etiktak.backend.controller.rest.json.add
import dk.etiktak.backend.model.contribution.TrustVote
import dk.etiktak.backend.model.user.Client
import dk.etiktak.backend.security.CurrentlyLoggedClient
import dk.etiktak.backend.service.client.ClientService
import dk.etiktak.backend.service.product.ProductCategoryService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.util.*
@RestController
@RequestMapping("/service/product/category")
class ProductCategoryRestController @Autowired constructor(
private val productCategoryService: ProductCategoryService,
private val clientService: ClientService) : BaseRestController() {
@RequestMapping(value = "/", method = arrayOf(RequestMethod.GET))
fun getProductCategory(
@CurrentlyLoggedClient loggedClient: Client?,
@RequestParam uuid: String): HashMap<String, Any> {
val client = if (loggedClient != null) clientService.getByUuid(loggedClient.uuid) else null
val productCategory = productCategoryService.getProductCategoryByUuid(uuid) ?: return notFoundMap("Product category")
return okMap().add(productCategory, client, productCategoryService)
}
@RequestMapping(value = "/create/", method = arrayOf(RequestMethod.POST))
fun createProductCategory(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam name: String): HashMap<String, Any> {
val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
val productCategory = productCategoryService.createProductCategory(client, name)
return okMap().add(productCategory, client, productCategoryService)
}
@RequestMapping(value = "/edit/", method = arrayOf(RequestMethod.POST))
fun editProductLabel(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam productCategoryUuid: String,
@RequestParam(required = false) name: String?): HashMap<String, Any> {
var client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
var productCategory = productCategoryService.getProductCategoryByUuid(productCategoryUuid) ?: return notFoundMap("Product category")
name?.let {
productCategoryService.editProductCategoryName(client, productCategory, name,
modifyValues = {modifiedClient, modifiedProductCategory -> client = modifiedClient; productCategory = modifiedProductCategory})
}
return okMap().add(productCategory, client, productCategoryService)
}
@RequestMapping(value = "/trust/name/", method = arrayOf(RequestMethod.POST))
fun trustVoteProductCategoryName(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam productCategoryUuid: String,
@RequestParam vote: TrustVote.TrustVoteType): HashMap<String, Any> {
val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
val productCategory = productCategoryService.getProductCategoryByUuid(productCategoryUuid) ?: return notFoundMap("Product category")
productCategoryService.trustVoteProductCategoryName(client, productCategory, vote)
return okMap().add(productCategory, client, productCategoryService)
}
}
| bsd-3-clause |
y2k/JoyReactor | core/src/main/kotlin/y2k/joyreactor/services/requests/LoginRequestFactory.kt | 1 | 1256 | package y2k.joyreactor.services.requests
import org.jsoup.nodes.Document
import rx.Completable
import rx.Single
import y2k.joyreactor.common.getDocumentAsync
import y2k.joyreactor.common.http.HttpClient
import y2k.joyreactor.common.postAsync
/**
* Created by y2k on 9/30/15.
*/
class LoginRequestFactory(private val httpClient: HttpClient) {
fun request(username: String, password: String): Completable {
return getSiteToken()
.flatMap {
httpClient
.buildRequest()
.addField("signin[username]", username)
.addField("signin[password]", password)
.addField("signin[_csrf_token]", it)
.postAsync("http://joyreactor.cc/login")
}
.doOnSuccess { validateIsSuccessLogin(it) }
.toCompletable()
}
private fun getSiteToken(): Single<String> {
return httpClient
.getDocumentAsync("http://joyreactor.cc/login")
.map { it.getElementById("signin__csrf_token").attr("value") }
}
private fun validateIsSuccessLogin(mainPage: Document) {
if (mainPage.getElementById("logout") == null)
throw IllegalStateException()
}
} | gpl-2.0 |
ZieIony/Carbon | samples/src/main/java/tk/zielony/carbonsamples/ThemedActivity.kt | 1 | 823 | package tk.zielony.carbonsamples
import android.content.Context
import android.os.Bundle
abstract class ThemedActivity : SamplesActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
applyTheme()
super.onCreate(savedInstanceState)
}
open protected fun applyTheme() {
val preferences = getSharedPreferences(ColorsActivity.THEME, Context.MODE_PRIVATE)
setTheme(ColorsActivity.styles[preferences.getInt(ColorsActivity.STYLE, 2)].value)
theme.applyStyle(ColorsActivity.primary[preferences.getInt(ColorsActivity.PRIMARY, 8)].value, true)
theme.applyStyle(ColorsActivity.secondary[preferences.getInt(ColorsActivity.SECONDARY, 14)].value, true)
theme.applyStyle(ColorsActivity.fonts[preferences.getInt(ColorsActivity.FONT, 0)].value, true)
}
}
| apache-2.0 |
DemonWav/StatCraftGradle | statcraft-common/src/main/kotlin/com/demonwav/statcraft/AbstractStatCraft.kt | 1 | 5868 | /*
* StatCraft Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft
import com.demonwav.statcraft.api.StatCraftApi
import com.demonwav.statcraft.api.exceptions.StatCraftNamespaceAlreadyDefinedException
import com.demonwav.statcraft.config.Config
import com.demonwav.statcraft.stats.AnimalsBred
import com.demonwav.statcraft.stats.Blocks
import com.demonwav.statcraft.stats.Buckets
import com.demonwav.statcraft.stats.Damage
import com.demonwav.statcraft.stats.Deaths
import com.demonwav.statcraft.stats.Eating
import com.demonwav.statcraft.stats.FiresStarted
import com.demonwav.statcraft.stats.FishCaught
import com.demonwav.statcraft.stats.HighestLevel
import com.demonwav.statcraft.stats.Items
import com.demonwav.statcraft.stats.Joins
import com.demonwav.statcraft.stats.Jumps
import com.demonwav.statcraft.stats.Kicks
import com.demonwav.statcraft.stats.Kills
import com.demonwav.statcraft.stats.MessagesSpoken
import com.demonwav.statcraft.stats.Movement
import com.demonwav.statcraft.stats.OnFire
import com.demonwav.statcraft.stats.PlayTime
import com.demonwav.statcraft.stats.Projectiles
import com.demonwav.statcraft.stats.Seen
import com.demonwav.statcraft.stats.SheepSheared
import com.demonwav.statcraft.stats.SleepTime
import com.demonwav.statcraft.stats.TabCompletions
import com.demonwav.statcraft.stats.TntDetonated
import com.demonwav.statcraft.stats.ToolsBroken
import com.demonwav.statcraft.stats.WordsSpoken
import com.demonwav.statcraft.stats.WorldChanges
import com.demonwav.statcraft.stats.XpGained
import ninja.leaping.configurate.hocon.HoconConfigurationLoader
import ninja.leaping.configurate.objectmapping.ObjectMapper
import java.util.Calendar
import java.util.Collections
import java.util.HashMap
import java.util.TimeZone
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
abstract class AbstractStatCraft : StatCraft {
// Config
private lateinit var statConfig: Config
private var timeZone: String = Calendar.getInstance().timeZone.getDisplayName(false, TimeZone.SHORT)
private val players = ConcurrentHashMap<String, UUID>()
// API Map
protected val apiMap = HashMap<Any, StatCraftApi>()
// StatCraft's API instance
protected lateinit var api: StatCraftApi
override fun preInit() {
val loader = HoconConfigurationLoader.builder().setPath(configFile).build()
val configMapper = ObjectMapper.forClass(Config::class.java).bindToNew()
// Load config
val root = loader.load()
statConfig = configMapper.populate(root)
// Save config
if (!configFile.parent.toFile().exists()) {
configFile.parent.toFile().mkdir()
}
configMapper.serialize(root)
loader.save(root)
// Init database
databaseManager.initialize()
// Register this plugin with the StatCraft API, done here, so we are always first
api = getApi(this)
registerStats()
}
override fun postInit() {
databaseManager.setupDatabase()
if (!isEnabled) {
return
}
if (!statConfig.timezone.equals("auto", true)) {
timeZone = statConfig.timezone
}
createListeners()
createCommands()
}
override fun shutdown() {
threadManager.close()
threadManager.shutdown()
}
protected fun registerStats() {
api.registerStatistic(AnimalsBred.getInstance())
api.registerStatistic(Blocks.getInstance())
api.registerStatistic(Buckets.getInstance())
api.registerStatistic(Damage.getInstance())
api.registerStatistic(Deaths.getInstance())
api.registerStatistic(Eating.getInstance())
api.registerStatistic(FiresStarted.getInstance())
api.registerStatistic(FishCaught.getInstance())
api.registerStatistic(HighestLevel.getInstance())
api.registerStatistic(Items.getInstance())
api.registerStatistic(Joins.getInstance())
api.registerStatistic(Jumps.getInstance())
api.registerStatistic(Kicks.getInstance())
api.registerStatistic(Kills.getInstance())
api.registerStatistic(MessagesSpoken.getInstance())
api.registerStatistic(Movement.getInstance())
api.registerStatistic(OnFire.getInstance())
api.registerStatistic(PlayTime.getInstance())
api.registerStatistic(Projectiles.getInstance())
api.registerStatistic(Seen.getInstance())
api.registerStatistic(SheepSheared.getInstance())
api.registerStatistic(SleepTime.getInstance())
api.registerStatistic(TabCompletions.getInstance())
api.registerStatistic(TntDetonated.getInstance())
api.registerStatistic(ToolsBroken.getInstance())
api.registerStatistic(WordsSpoken.getInstance())
api.registerStatistic(WorldChanges.getInstance())
api.registerStatistic(XpGained.getInstance())
}
abstract fun createListeners()
abstract fun createCommands()
override fun getStatConfig(): Config = statConfig
override fun setStatConfig(config: Config) {
statConfig = config
}
override fun getTimeZone() = timeZone
override fun getPlayers(): Map<String, UUID> = Collections.unmodifiableMap(players)!!
override fun getApi(plugin: Any): StatCraftApi {
var api = apiMap[plugin]
if (api != null) {
return api
}
api = StatCraftApi(plugin)
for ((key, value) in apiMap) {
if (value.namespace == api.namespace) {
throw StatCraftNamespaceAlreadyDefinedException()
}
}
apiMap[plugin] = api
return api
}
companion object {
@JvmStatic
lateinit var instance: AbstractStatCraft
}
}
| mit |
rhdunn/xquery-intellij-plugin | src/plugin-basex/main/uk/co/reecedunn/intellij/plugin/basex/resources/BaseXIcons.kt | 1 | 893 | /*
* Copyright (C) 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.basex.resources
import com.intellij.openapi.util.IconLoader
import javax.swing.Icon
object BaseXIcons {
private fun getIcon(path: String): Icon = IconLoader.getIcon(path, BaseXIcons::class.java)
val Product: Icon = getIcon("/icons/basex.png")
}
| apache-2.0 |
rhdunn/xquery-intellij-plugin | src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/SaxonErrorListener.kt | 1 | 1407 | /*
* Copyright (C) 2018-2019 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.saxon.query.s9api
import com.intellij.openapi.vfs.VirtualFile
import uk.co.reecedunn.intellij.plugin.processor.query.QueryError
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.trans.toXPathException
import javax.xml.transform.ErrorListener
import javax.xml.transform.TransformerException
internal class SaxonErrorListener(private var queryFile: VirtualFile, var classLoader: ClassLoader) : ErrorListener {
var fatalError: QueryError? = null
override fun warning(exception: TransformerException?) {
}
override fun error(exception: TransformerException?) {
}
override fun fatalError(exception: TransformerException?) {
fatalError = exception!!.toXPathException(classLoader)!!.toSaxonQueryError(queryFile)
}
}
| apache-2.0 |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/ArmoireActivity.kt | 1 | 8766 | package com.habitrpg.android.habitica.ui.activities
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.widget.FrameLayout
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.databinding.ActivityArmoireBinding
import com.habitrpg.android.habitica.helpers.AdHandler
import com.habitrpg.android.habitica.helpers.AdType
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.common.habitica.extensions.loadImage
import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel
import com.habitrpg.android.habitica.ui.views.ads.AdButton
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaBottomSheetDialog
import com.habitrpg.common.habitica.extensions.dpToPx
import com.habitrpg.common.habitica.extensions.loadImage
import com.habitrpg.common.habitica.helpers.Animations
import com.plattysoft.leonids.ParticleSystem
import java.util.Locale
import javax.inject.Inject
class ArmoireActivity : BaseActivity() {
private var equipmentKey: String? = null
private var gold: Double? = null
private var hasAnimatedChanges: Boolean = false
private lateinit var binding: ActivityArmoireBinding
@Inject
internal lateinit var inventoryRepository: InventoryRepository
@Inject
internal lateinit var appConfigManager: AppConfigManager
@Inject
lateinit var userViewModel: MainUserViewModel
override fun getLayoutResId(): Int = R.layout.activity_armoire
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun getContentView(): View {
binding = ActivityArmoireBinding.inflate(layoutInflater)
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.goldView.currency = "gold"
binding.goldView.animationDuration = 1000
binding.goldView.animationDelay = 500
binding.goldView.minForAbbrevation = 1000000
binding.goldView.decimals = 0
userViewModel.user.observe(this) { user ->
if (gold == null) {
gold = user?.stats?.gp
}
val remaining = inventoryRepository.getArmoireRemainingCount()
binding.equipmentCountView.text = getString(R.string.equipment_remaining, remaining)
binding.noEquipmentView.visibility = if (remaining > 0) View.GONE else View.VISIBLE
}
if (appConfigManager.enableArmoireAds()) {
val handler = AdHandler(this, AdType.ARMOIRE) {
if (!it) {
return@AdHandler
}
Log.d("AdHandler", "Giving Armoire")
val user = userViewModel.user.value ?: return@AdHandler
val currentGold = user.stats?.gp ?: return@AdHandler
compositeSubscription.add(
userRepository.updateUser("stats.gp", currentGold + 100)
.flatMap { inventoryRepository.buyItem(user, "armoire", 100.0, 1) }
.subscribe({
configure(
it.armoire["type"] ?: "",
it.armoire["dropKey"] ?: "",
it.armoire["dropText"] ?: "",
it.armoire["value"] ?: ""
)
binding.adButton.state = AdButton.State.UNAVAILABLE
binding.adButton.visibility = View.INVISIBLE
hasAnimatedChanges = false
gold = null
}, ExceptionHandler.rx())
)
}
handler.prepare {
if (it && binding.adButton.state == AdButton.State.LOADING) {
binding.adButton.state = AdButton.State.READY
} else if (!it) {
binding.adButton.visibility = View.INVISIBLE
}
}
binding.adButton.updateForAdType(AdType.ARMOIRE, lifecycleScope)
binding.adButton.setOnClickListener {
binding.adButton.state = AdButton.State.LOADING
handler.show()
}
} else {
binding.adButton.visibility = View.GONE
}
binding.closeButton.setOnClickListener {
finish()
}
binding.equipButton.setOnClickListener {
equipmentKey?.let { it1 -> inventoryRepository.equip("equipped", it1).subscribe({}, ExceptionHandler.rx()) }
finish()
}
binding.dropRateButton.setOnClickListener {
showDropRateDialog()
}
intent.extras?.let {
val args = ArmoireActivityArgs.fromBundle(it)
equipmentKey = args.key
configure(args.type, args.key, args.text, args.value)
}
}
override fun onResume() {
super.onResume()
startAnimation()
}
private fun startAnimation() {
val gold = gold?.toInt()
if (hasAnimatedChanges) return
if (gold != null) {
binding.goldView.value = (gold).toDouble()
binding.goldView.value = (gold - 100).toDouble()
}
val container = binding.confettiAnchor
container.postDelayed(
{
createParticles(container, R.drawable.confetti_blue)
createParticles(container, R.drawable.confetti_red)
createParticles(container, R.drawable.confetti_yellow)
createParticles(container, R.drawable.confetti_purple)
}, 500
)
binding.iconView.startAnimation(Animations.bobbingAnimation())
binding.titleView.alpha = 0f
binding.subtitleView.alpha = 0f
binding.iconWrapper.post {
Animations.circularReveal(binding.iconWrapper, 300)
}
binding.leftSparkView.startAnimating()
binding.rightSparkView.startAnimating()
binding.titleView.animate().apply {
alpha(1f)
duration = 300
startDelay = 600
start()
}
binding.subtitleView.animate().apply {
alpha(1f)
duration = 300
startDelay = 900
start()
}
hasAnimatedChanges = true
}
private fun createParticles(container: FrameLayout, resource: Int) {
ParticleSystem(
container,
30,
ContextCompat.getDrawable(this, resource),
6000
)
.setRotationSpeed(144f)
.setScaleRange(1.0f, 1.6f)
.setSpeedByComponentsRange(-0.15f, 0.15f, 0.15f, 0.45f)
.setFadeOut(200, AccelerateInterpolator())
.emitWithGravity(binding.confettiAnchor, Gravity.TOP, 15, 2000)
}
fun configure(type: String, key: String, text: String, value: String? = "") {
binding.titleView.text = text.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
binding.equipButton.visibility = if (type == "gear") View.VISIBLE else View.GONE
when (type) {
"gear" -> {
binding.subtitleView.text = getString(R.string.armoireEquipment_new)
binding.iconView.loadImage("shop_$key")
}
"food" -> {
binding.subtitleView.text = getString(R.string.armoireFood_new)
binding.iconView.loadImage("Pet_Food_$key")
}
else -> {
@SuppressLint("SetTextI18n")
binding.titleView.text = "+${value} ${binding.titleView.text}"
binding.subtitleView.text = getString(R.string.armoireExp)
binding.iconView.setImageResource(R.drawable.armoire_experience)
val layoutParams = RelativeLayout.LayoutParams(108.dpToPx(this), 122.dpToPx(this))
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
binding.iconView.layoutParams = layoutParams
}
}
}
private fun showDropRateDialog() {
val dialog = HabiticaBottomSheetDialog(this)
dialog.setContentView(R.layout.armoire_drop_rate_dialog)
dialog.show()
}
}
| gpl-3.0 |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryGroupingSpecPsiImpl.kt | 1 | 2184 | /*
* Copyright (C) 2016-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmSequenceType
import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyUriValue
import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathEQName
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryGroupingSpec
class XQueryGroupingSpecPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryGroupingSpec {
// region PsiElement
override fun getUseScope(): SearchScope = LocalSearchScope(parent.parent)
// endregion
// region XQueryGroupingSpec
override val collation: XsAnyUriValue?
get() = children().filterIsInstance<XsAnyUriValue>().firstOrNull()
// endregion
// region XpmVariableBinding
override val variableName: XsQNameValue?
get() = children().filterIsInstance<XPathEQName>().firstOrNull()
// endregion
// region XpmAssignableVariable
override val variableType: XdmSequenceType?
get() = children().filterIsInstance<XdmSequenceType>().firstOrNull()
override val variableExpression: XpmExpression?
get() = children().filterIsInstance<XpmExpression>().firstOrNull()
// endregion
}
| apache-2.0 |
rhdunn/xquery-intellij-plugin | src/plugin-basex/main/uk/co/reecedunn/intellij/plugin/basex/query/session/BaseXQueryInfo.kt | 1 | 2671 | /*
* Copyright (C) 2019-2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.basex.query.session
import uk.co.reecedunn.intellij.plugin.xdm.types.impl.values.XsDuration
@Suppress("RegExpAnonymousGroup")
private val RE_TOTAL_TIME = "([0-9.]+) ms[ .]".toRegex()
private fun String.toBaseXInfoBlocks(): Sequence<String> {
return replace("\r\n", "\n").replace('\r', '\n').split("\n\n").asSequence().map {
when {
it.startsWith('\n') -> it.substring(1)
it.endsWith('\n') -> it.substring(0, it.length - 1)
else -> it
}
}
}
private fun String.parseBaseXInfoBlock(info: HashMap<String, Any>) {
@Suppress("UNCHECKED_CAST")
var profile = info["Profile"] as? HashMap<String, XsDuration>
split('\n').forEach { row ->
val data = row.split(": ")
if (data[1].endsWith(" ms")) {
if (profile == null) {
profile = HashMap()
info["Profile"] = profile!!
}
profile?.put(data[0], XsDuration.ms(data[1].substringBefore(" ms")))
if (data[0] == "Total Time") {
info[data[0]] = XsDuration.ms(data[1].substringBefore(" ms"))
}
} else {
info[data[0]] = data[1]
}
}
}
fun String.toBaseXInfo(): Map<String, Any> {
val info = HashMap<String, Any>()
toBaseXInfoBlocks().forEach { block ->
val part = block.substringBefore('\n')
when {
part.contains(": ") -> block.parseBaseXInfoBlock(info)
part == "Query Plan:" -> {
info["Query Plan"] = block.substringAfter('\n')
}
part == "Compiling:" -> {
info["Compilation"] = block.substringAfter('\n').split('\n').map { it.substring(2) }
}
part == "Optimized Query:" -> {
info["Optimized Query"] = block.substringAfter('\n')
}
else -> RE_TOTAL_TIME.find(block)?.let { total ->
info["Total Time"] = XsDuration.ms(total.groupValues[1])
}
}
}
return info
}
| apache-2.0 |
google/private-compute-services | src/com/google/android/as/oss/policies/api/proto/AnnotationProto.kt | 1 | 2412 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package com.google.android.`as`.oss.policies.api.proto
import arcs.core.data.proto.AnnotationParamProto
import arcs.core.data.proto.AnnotationProto
import com.google.android.`as`.oss.policies.api.annotation.Annotation
import com.google.android.`as`.oss.policies.api.annotation.AnnotationParam
private fun AnnotationParamProto.decode(): AnnotationParam {
return when (valueCase) {
AnnotationParamProto.ValueCase.STR_VALUE -> AnnotationParam.Str(strValue)
AnnotationParamProto.ValueCase.NUM_VALUE -> AnnotationParam.Num(numValue)
AnnotationParamProto.ValueCase.BOOL_VALUE -> AnnotationParam.Bool(boolValue)
else -> throw UnsupportedOperationException("Invalid [AnnotationParam] type $valueCase.")
}
}
private fun AnnotationParam.encode(paramName: String): AnnotationParamProto {
val proto = AnnotationParamProto.newBuilder().setName(paramName)
when (this) {
is AnnotationParam.Bool -> proto.boolValue = value
is AnnotationParam.Str -> proto.strValue = value
is AnnotationParam.Num -> proto.numValue = value
}
return proto.build()
}
/** Converts a [AnnotationProto] into a [Annotation]. */
fun AnnotationProto.decode(): Annotation {
return Annotation(name = name, params = paramsList.associate { it.name to it.decode() })
}
/** Converts a [Annotation] into a [AnnotationProto]. */
fun Annotation.encode(): AnnotationProto {
return AnnotationProto.newBuilder()
.setName(name)
.addAllParams(params.map { (name, param) -> param.encode(name) })
.build()
}
| apache-2.0 |
dhleong/ideavim | src/com/maddyhome/idea/vim/action/motion/select/SelectEscapeAction.kt | 1 | 1889 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.action.motion.select
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.VimCommandAction
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.helper.inBlockSubMode
import javax.swing.KeyStroke
class SelectEscapeAction : VimCommandAction() {
override fun makeActionHandler(): VimActionHandler = object : VimActionHandler.SingleExecution() {
override fun execute(editor: Editor, context: DataContext, cmd: Command): Boolean {
val blockMode = editor.inBlockSubMode
VimPlugin.getVisualMotion().exitSelectMode(editor, true)
if (blockMode) editor.caretModel.removeSecondaryCarets()
return true
}
}
override val mappingModes: MutableSet<MappingMode> = MappingMode.S
override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("<esc>")
override val type: Command.Type = Command.Type.OTHER_READONLY
} | gpl-2.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/storage/migration/MigrationFrom43To44.kt | 2 | 365 | package org.stepic.droid.storage.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.stepik.android.cache.submission.structure.DbStructureSubmission
object MigrationFrom43To44 : Migration(43, 44) {
override fun migrate(db: SupportSQLiteDatabase) {
DbStructureSubmission.createTable(db)
}
} | apache-2.0 |
rabsouza/bgscore | app/src/androidTest/java/br/com/battista/bgscore/helper/HomeActivityHelper.kt | 1 | 530 | package br.com.battista.bgscore.helper
import br.com.battista.bgscore.helper.TestConstant.DATA_USER_TEST_MAIL
import br.com.battista.bgscore.helper.TestConstant.DATA_USER_TEST_USERNAME
import br.com.battista.bgscore.model.User
object HomeActivityHelper {
fun createNewUser(): User {
val user = User()
.username(DATA_USER_TEST_USERNAME)
.mail(DATA_USER_TEST_MAIL)
.lastBuildVersion(0)
user.initEntity()
user.welcome(true)
return user
}
}
| gpl-3.0 |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/browse/components/BaseSourceItem.kt | 1 | 2363 | package eu.kanade.presentation.browse.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import eu.kanade.domain.source.model.Source
import eu.kanade.presentation.util.horizontalPadding
import eu.kanade.presentation.util.secondaryItemAlpha
import eu.kanade.tachiyomi.util.system.LocaleHelper
@Composable
fun BaseSourceItem(
modifier: Modifier = Modifier,
source: Source,
showLanguageInContent: Boolean = true,
onClickItem: () -> Unit = {},
onLongClickItem: () -> Unit = {},
icon: @Composable RowScope.(Source) -> Unit = defaultIcon,
action: @Composable RowScope.(Source) -> Unit = {},
content: @Composable RowScope.(Source, String?) -> Unit = defaultContent,
) {
val sourceLangString = LocaleHelper.getSourceDisplayName(source.lang, LocalContext.current).takeIf { showLanguageInContent }
BaseBrowseItem(
modifier = modifier,
onClickItem = onClickItem,
onLongClickItem = onLongClickItem,
icon = { icon.invoke(this, source) },
action = { action.invoke(this, source) },
content = { content.invoke(this, source, sourceLangString) },
)
}
private val defaultIcon: @Composable RowScope.(Source) -> Unit = { source ->
SourceIcon(source = source)
}
private val defaultContent: @Composable RowScope.(Source, String?) -> Unit = { source, sourceLangString ->
Column(
modifier = Modifier
.padding(horizontal = horizontalPadding)
.weight(1f),
) {
Text(
text = source.name,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyMedium,
)
if (sourceLangString != null) {
Text(
modifier = Modifier.secondaryItemAlpha(),
text = sourceLangString,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
| apache-2.0 |
sn3d/nomic | nomic-hdfs/src/main/kotlin/nomic/hdfs/adapter/HdfsAdapter.kt | 1 | 717 | package nomic.hdfs.adapter
import org.apache.hadoop.fs.Path
import java.io.InputStream
import java.io.OutputStream
/**
* The whole Nomic is accessing to HDFS through this adapter. That allows me
* to create [HdfsSimulator] for testing and we don't need real
* HDFS system.
*
* @author [email protected]
*/
interface HdfsAdapter {
fun create(path: String): OutputStream
fun open(path: String): InputStream
fun mkdirs(path: String): Boolean
fun delete(path: String): Boolean
fun exist(path: String): Boolean
fun isDirectory(path: String): Boolean
fun listFiles(path: String, recursive: Boolean): Sequence<String>
val homeDirectory: String;
val nameNode: String;
} | apache-2.0 |
suchaHassle/kotNES | src/Controller.kt | 1 | 738 | package kotNES
import asInt
class Controller {
enum class Buttons(val value: Int) {
A(0), B(1), Select(2), Start(3), Up(4), Down(5), Left(6), Right(7)
}
private var strobe: Boolean = false
private var buttonState = BooleanArray(8)
private var currButtonIndex: Int = 0
fun setButtonState(button: Buttons, state: Boolean) {
buttonState[button.value] = state
}
fun writeControllerInput(input: Int) {
strobe = (input and 1) == 1
if (strobe) currButtonIndex = 0
}
fun readControllerOutput(): Int {
if (currButtonIndex > 7) return 1
val state = buttonState[currButtonIndex]
if (!strobe) currButtonIndex++
return state.asInt()
}
} | mit |
taehwandev/BlogExample | app/src/main/java/tech/thdev/app/ui/first/FirstFragment.kt | 2 | 1055 | package tech.thdev.app.ui.first
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import tech.thdev.app.R
import tech.thdev.app.databinding.FirstFragmentBinding
class FirstFragment : Fragment() {
private lateinit var binding: FirstFragmentBinding
private val viewModel: FirstViewModel by viewModels<FirstViewModel>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return FirstFragmentBinding.inflate(inflater).also {
binding = it
}.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonFirst.setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
}
| apache-2.0 |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt | 1 | 7460 | package info.nightscout.androidaps.plugins.source
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.interfaces.BgSource
import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSgv
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.XDripBroadcast
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NSClientSourcePlugin @Inject constructor(
injector: HasAndroidInjector,
rh: ResourceHelper,
aapsLogger: AAPSLogger,
config: Config
) : PluginBase(PluginDescription()
.mainType(PluginType.BGSOURCE)
.fragmentClass(BGSourceFragment::class.java.name)
.pluginIcon(R.drawable.ic_nsclient_bg)
.pluginName(R.string.nsclientbg)
.shortName(R.string.nsclientbgshort)
.description(R.string.description_source_ns_client),
aapsLogger, rh, injector
), BgSource {
private var lastBGTimeStamp: Long = 0
private var isAdvancedFilteringEnabled = false
init {
if (config.NSCLIENT) {
pluginDescription
.alwaysEnabled(true)
.setDefault()
}
}
override fun advancedFilteringSupported(): Boolean {
return isAdvancedFilteringEnabled
}
override fun shouldUploadToNs(glucoseValue: GlucoseValue): Boolean = false
private fun detectSource(glucoseValue: GlucoseValue) {
if (glucoseValue.timestamp > lastBGTimeStamp) {
isAdvancedFilteringEnabled = arrayOf(
GlucoseValue.SourceSensor.DEXCOM_NATIVE_UNKNOWN,
GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE,
GlucoseValue.SourceSensor.DEXCOM_G5_NATIVE,
GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE_XDRIP,
GlucoseValue.SourceSensor.DEXCOM_G5_NATIVE_XDRIP
).any { it == glucoseValue.sourceSensor }
lastBGTimeStamp = glucoseValue.timestamp
}
}
// cannot be inner class because of needed injection
class NSClientSourceWorker(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
@Inject lateinit var nsClientSourcePlugin: NSClientSourcePlugin
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBus
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var dataWorker: DataWorker
@Inject lateinit var repository: AppRepository
@Inject lateinit var xDripBroadcast: XDripBroadcast
@Inject lateinit var dexcomPlugin: DexcomPlugin
@Inject lateinit var nsClientPlugin: NSClientPlugin
init {
(context.applicationContext as HasAndroidInjector).androidInjector().inject(this)
}
private fun toGv(jsonObject: JSONObject): CgmSourceTransaction.TransactionGlucoseValue? {
val sgv = NSSgv(jsonObject)
return CgmSourceTransaction.TransactionGlucoseValue(
timestamp = sgv.mills ?: return null,
value = sgv.mgdl?.toDouble() ?: return null,
noise = null,
raw = sgv.filtered?.toDouble() ?: sgv.mgdl?.toDouble(),
trendArrow = GlucoseValue.TrendArrow.fromString(sgv.direction),
nightscoutId = sgv.id,
sourceSensor = GlucoseValue.SourceSensor.fromString(sgv.device)
)
}
@Suppress("SpellCheckingInspection")
override fun doWork(): Result {
var ret = Result.success()
val sgvs = dataWorker.pickupJSONArray(inputData.getLong(DataWorker.STORE_KEY, -1))
?: return Result.failure(workDataOf("Error" to "missing input data"))
xDripBroadcast.sendSgvs(sgvs)
if (!nsClientSourcePlugin.isEnabled() && !sp.getBoolean(R.string.key_ns_receive_cgm, false))
return Result.success(workDataOf("Result" to "Sync not enabled"))
try {
var latestDateInReceivedData: Long = 0
aapsLogger.debug(LTag.BGSOURCE, "Received NS Data: $sgvs")
val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>()
for (i in 0 until sgvs.length()) {
val sgv = toGv(sgvs.getJSONObject(i)) ?: continue
if (sgv.timestamp < dateUtil.now() && sgv.timestamp > latestDateInReceivedData) latestDateInReceivedData = sgv.timestamp
glucoseValues += sgv
}
// Was that sgv more less 5 mins ago ?
if (T.msecs(dateUtil.now() - latestDateInReceivedData).mins() < 5L) {
rxBus.send(EventDismissNotification(Notification.NS_ALARM))
rxBus.send(EventDismissNotification(Notification.NS_URGENT_ALARM))
}
nsClientPlugin.updateLatestDateReceivedIfNewer(latestDateInReceivedData)
repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null, !nsClientSourcePlugin.isEnabled()))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while saving values from NSClient App", it)
ret = Result.failure(workDataOf("Error" to it.toString()))
}
.blockingGet()
.also { result ->
result.updated.forEach {
xDripBroadcast.send(it)
nsClientSourcePlugin.detectSource(it)
aapsLogger.debug(LTag.DATABASE, "Updated bg $it")
}
result.inserted.forEach {
xDripBroadcast.send(it)
nsClientSourcePlugin.detectSource(it)
aapsLogger.debug(LTag.DATABASE, "Inserted bg $it")
}
}
} catch (e: Exception) {
aapsLogger.error("Unhandled exception", e)
ret = Result.failure(workDataOf("Error" to e.toString()))
}
return ret
}
}
} | agpl-3.0 |
exponentjs/exponent | packages/expo-updates/android/src/main/java/expo/modules/updates/loader/Crypto.kt | 2 | 8658 | package expo.modules.updates.loader
import android.annotation.SuppressLint
import android.security.keystore.KeyProperties
import android.util.Base64
import android.util.Log
import expo.modules.structuredheaders.BooleanItem
import expo.modules.structuredheaders.Dictionary
import okhttp3.*
import java.io.IOException
import java.security.*
import java.security.cert.CertificateException
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import java.security.spec.InvalidKeySpecException
import java.security.spec.X509EncodedKeySpec
import expo.modules.structuredheaders.Parser
import expo.modules.structuredheaders.StringItem
object Crypto {
private val TAG = Crypto::class.java.simpleName
const val CODE_SIGNING_METADATA_ALGORITHM_KEY = "alg"
const val CODE_SIGNING_METADATA_KEY_ID_KEY = "keyid"
const val CODE_SIGNING_METADATA_DEFAULT_KEY_ID = "root"
const val CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_SIGNATURE = "sig"
const val CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_KEY_ID = "keyid"
const val CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_ALGORITHM = "alg"
private const val EXPO_PUBLIC_KEY_URL = "https://exp.host/--/manifest-public-key"
// ASN.1 path to the extended key usage info within a CERT
private const val CODE_SIGNING_OID = "1.3.6.1.5.5.7.3.3"
fun verifyExpoPublicRSASignature(
fileDownloader: FileDownloader,
data: String,
signature: String,
listener: RSASignatureListener
) {
fetchExpoPublicKeyAndVerifyPublicRSASignature(true, data, signature, fileDownloader, listener)
}
// On first attempt use cache. If verification fails try a second attempt without
// cache in case the keys were actually rotated.
// On second attempt reject promise if it fails.
private fun fetchExpoPublicKeyAndVerifyPublicRSASignature(
isFirstAttempt: Boolean,
plainText: String,
cipherText: String,
fileDownloader: FileDownloader,
listener: RSASignatureListener
) {
val cacheControl = if (isFirstAttempt) CacheControl.FORCE_CACHE else CacheControl.FORCE_NETWORK
val request = Request.Builder()
.url(EXPO_PUBLIC_KEY_URL)
.cacheControl(cacheControl)
.build()
fileDownloader.downloadData(
request,
object : Callback {
override fun onFailure(call: Call, e: IOException) {
listener.onError(e, true)
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val exception: Exception = try {
val isValid = verifyPublicRSASignature(response.body()!!.string(), plainText, cipherText)
listener.onCompleted(isValid)
return
} catch (e: Exception) {
e
}
if (isFirstAttempt) {
fetchExpoPublicKeyAndVerifyPublicRSASignature(
false,
plainText,
cipherText,
fileDownloader,
listener
)
} else {
listener.onError(exception, false)
}
}
}
)
}
@Throws(
NoSuchAlgorithmException::class,
InvalidKeySpecException::class,
InvalidKeyException::class,
SignatureException::class
)
private fun verifyPublicRSASignature(
publicKey: String,
plainText: String,
cipherText: String
): Boolean {
// remove comments from public key
val publicKeySplit = publicKey.split("\\r?\\n".toRegex()).toTypedArray()
var publicKeyNoComments = ""
for (line in publicKeySplit) {
if (!line.contains("PUBLIC KEY-----")) {
publicKeyNoComments += line + "\n"
}
}
val signature = Signature.getInstance("SHA256withRSA")
val decodedPublicKey = Base64.decode(publicKeyNoComments, Base64.DEFAULT)
val publicKeySpec = X509EncodedKeySpec(decodedPublicKey)
@SuppressLint("InlinedApi") val keyFactory = KeyFactory.getInstance(KeyProperties.KEY_ALGORITHM_RSA)
val key = keyFactory.generatePublic(publicKeySpec)
signature.initVerify(key)
signature.update(plainText.toByteArray())
return signature.verify(Base64.decode(cipherText, Base64.DEFAULT))
}
interface RSASignatureListener {
fun onError(exception: Exception, isNetworkError: Boolean)
fun onCompleted(isValid: Boolean)
}
enum class CodeSigningAlgorithm(val algorithmName: String) {
RSA_SHA256("rsa-v1_5-sha256");
companion object {
fun parseFromString(str: String?): CodeSigningAlgorithm {
return when (str) {
RSA_SHA256.algorithmName -> RSA_SHA256
null -> RSA_SHA256
else -> throw Exception("Invalid code signing algorithm name: $str")
}
}
}
}
data class CodeSigningConfiguration(private val certificateString: String, private val metadata: Map<String, String>?) {
val embeddedCertificate: X509Certificate by lazy {
val certificateFactory = CertificateFactory.getInstance("X.509")
val certificate = certificateFactory.generateCertificate(certificateString.byteInputStream()) as X509Certificate
certificate.checkValidity()
val keyUsage: BooleanArray? = certificate.keyUsage
if (keyUsage == null || keyUsage.isEmpty() || !keyUsage[0]) {
throw CertificateException("X509v3 Key Usage: Digital Signature not present")
}
val extendedKeyUsage = certificate.extendedKeyUsage
if (!extendedKeyUsage.contains(CODE_SIGNING_OID)) {
throw CertificateException("X509v3 Extended Key Usage: Code Signing not present")
}
certificate
}
val algorithm: CodeSigningAlgorithm by lazy {
CodeSigningAlgorithm.parseFromString(metadata?.get(CODE_SIGNING_METADATA_ALGORITHM_KEY))
}
val keyId: String by lazy {
metadata?.get(CODE_SIGNING_METADATA_KEY_ID_KEY) ?: CODE_SIGNING_METADATA_DEFAULT_KEY_ID
}
}
fun createAcceptSignatureHeader(codeSigningConfiguration: CodeSigningConfiguration): String {
return Dictionary.valueOf(
mapOf(
CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_SIGNATURE to BooleanItem.valueOf(true),
CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_KEY_ID to StringItem.valueOf(codeSigningConfiguration.keyId),
CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_ALGORITHM to StringItem.valueOf(codeSigningConfiguration.algorithm.algorithmName)
)
).serialize()
}
data class SignatureHeaderInfo(val signature: String, val keyId: String, val algorithm: CodeSigningAlgorithm)
fun parseSignatureHeader(signatureHeader: String?): SignatureHeaderInfo {
if (signatureHeader == null) {
throw Exception("No expo-signature header specified")
}
val signatureMap = Parser(signatureHeader).parseDictionary().get()
val sigFieldValue = signatureMap[CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_SIGNATURE]
val keyIdFieldValue = signatureMap[CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_KEY_ID]
val algFieldValue = signatureMap[CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_ALGORITHM]
val signature = if (sigFieldValue is StringItem) {
sigFieldValue.get()
} else throw Exception("Structured field $CODE_SIGNING_SIGNATURE_STRUCTURED_FIELD_KEY_SIGNATURE not found in expo-signature header")
val keyId = if (keyIdFieldValue is StringItem) {
keyIdFieldValue.get()
} else CODE_SIGNING_METADATA_DEFAULT_KEY_ID
val alg = if (algFieldValue is StringItem) {
algFieldValue.get()
} else null
return SignatureHeaderInfo(signature, keyId, CodeSigningAlgorithm.parseFromString(alg))
}
fun isSignatureValid(configuration: CodeSigningConfiguration, info: SignatureHeaderInfo, bytes: ByteArray): Boolean {
// check that the key used to sign the response is the same as the key embedded in the configuration
// TODO(wschurman): this may change for child certificates and development certificates
if (info.keyId != configuration.keyId) {
throw Exception("Key with keyid=${info.keyId} from signature not found in client configuration")
}
// note that a mismatched algorithm doesn't fail early. it still tries to verify the signature with the
// algorithm specified in the configuration
if (info.algorithm != configuration.algorithm) {
Log.i(TAG, "Key with alg=${info.algorithm} from signature does not match client configuration algorithm, continuing")
}
return Signature.getInstance(
when (configuration.algorithm) {
CodeSigningAlgorithm.RSA_SHA256 -> "SHA256withRSA"
}
).apply {
initVerify(configuration.embeddedCertificate.publicKey)
update(bytes)
}.verify(Base64.decode(info.signature, Base64.DEFAULT))
}
}
| bsd-3-clause |
realm/realm-java | realm/realm-library/src/androidTest/kotlin/io/realm/realmany/RealmAnyBulkInsertsTests.kt | 1 | 22082 | /*
* Copyright 2020 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.realmany
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import io.realm.*
import io.realm.entities.*
import io.realm.kotlin.createObject
import io.realm.kotlin.where
import org.bson.types.Decimal128
import org.bson.types.ObjectId
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import java.util.*
import kotlin.test.*
@RunWith(AndroidJUnit4::class)
class RealmAnyBulkInsertsTests {
private lateinit var realmConfiguration: RealmConfiguration
private lateinit var realm: Realm
companion object {
const val TEST_VALUE_1 = "hello world 1"
const val TEST_VALUE_2 = "hello world 2"
const val TEST_VALUE_3 = "hello world 3"
const val TEST_VALUE_4 = "hello world 4"
}
@get:Rule
val configFactory = TestRealmConfigurationFactory()
init {
Realm.init(InstrumentationRegistry.getInstrumentation().targetContext)
}
@Before
fun setUp() {
realmConfiguration = configFactory.createSchemaConfiguration(
false,
RealmAnyNotIndexed::class.java,
RealmAnyIndexed::class.java,
AllJavaTypes::class.java,
RealmAnyRealmListWithPK::class.java,
RealmAnyNotIndexedWithPK::class.java,
PrimaryKeyAsString::class.java)
realm = Realm.getInstance(realmConfiguration)
}
@After
fun tearDown() {
realm.close()
}
private val testList1 = arrayOf(
RealmAny.valueOf(10.toByte()),
RealmAny.valueOf(20.toShort()),
RealmAny.valueOf(30.toInt()),
RealmAny.valueOf(40.toLong()),
RealmAny.valueOf(true),
RealmAny.valueOf(TEST_VALUE_1),
RealmAny.valueOf(byteArrayOf(0, 1, 1)),
RealmAny.valueOf(Date(10)),
RealmAny.valueOf(50.toFloat()),
RealmAny.valueOf(60.toDouble()),
RealmAny.valueOf(Decimal128(10)),
RealmAny.valueOf(ObjectId(Date(100))),
RealmAny.valueOf(UUID.randomUUID())
)
private val testList2 = arrayOf(
RealmAny.valueOf(1.toByte()),
RealmAny.valueOf(2.toShort()),
RealmAny.valueOf(3.toInt()),
RealmAny.valueOf(4.toLong()),
RealmAny.valueOf(false),
RealmAny.valueOf(TEST_VALUE_2),
RealmAny.valueOf(byteArrayOf(0, 1, 0)),
RealmAny.valueOf(Date(0)),
RealmAny.valueOf(5.toFloat()),
RealmAny.valueOf(6.toDouble()),
RealmAny.valueOf(Decimal128(1)),
RealmAny.valueOf(ObjectId(Date(10))),
RealmAny.valueOf(UUID.randomUUID())
)
/**
* RealmAny tests for Realm objects
*/
@Test
fun copyFromRealm_realmModel() {
realm.beginTransaction()
val value = realm.createObject<RealmAnyNotIndexedWithPK>(0)
val inner = RealmAnyNotIndexedWithPK(1)
val allTypes = AllJavaTypes(0)
allTypes.fieldString = TEST_VALUE_1
val innerAllJavaTypes = AllJavaTypes(1)
innerAllJavaTypes.fieldString = TEST_VALUE_2
allTypes.fieldObject = innerAllJavaTypes
inner.realmAny = RealmAny.valueOf(allTypes)
value.realmAny = RealmAny.valueOf(inner)
realm.commitTransaction()
val copy0 = realm.copyFromRealm(value, 0)
val copy1 = realm.copyFromRealm(value, 1)
val copy2 = realm.copyFromRealm(value, 2)
val copy3 = realm.copyFromRealm(value, 3)
assertFalse(copy0.isManaged)
assertFalse(copy1.isManaged)
assertFalse(copy2.isManaged)
assertFalse(copy3.isManaged)
assertEquals(RealmAny.nullValue(), copy0.realmAny)
assertEquals(RealmAny.nullValue(), copy1.realmAny!!.asRealmModel(RealmAnyNotIndexedWithPK::class.java).realmAny)
assertEquals(TEST_VALUE_1, copy2.realmAny!!.asRealmModel(RealmAnyNotIndexedWithPK::class.java).realmAny!!.asRealmModel(AllJavaTypes::class.java).fieldString)
assertNull(copy2.realmAny!!.asRealmModel(RealmAnyNotIndexedWithPK::class.java).realmAny!!.asRealmModel(AllJavaTypes::class.java).fieldObject)
assertEquals(TEST_VALUE_1, copy3.realmAny!!.asRealmModel(RealmAnyNotIndexedWithPK::class.java).realmAny!!.asRealmModel(AllJavaTypes::class.java).fieldString)
assertNotNull(copy3.realmAny!!.asRealmModel(RealmAnyNotIndexedWithPK::class.java).realmAny!!.asRealmModel(AllJavaTypes::class.java).fieldObject)
assertEquals(TEST_VALUE_2, copy3.realmAny!!.asRealmModel(RealmAnyNotIndexedWithPK::class.java).realmAny!!.asRealmModel(AllJavaTypes::class.java).fieldObject.fieldString)
}
@Test
fun copyToRealm_realmModel() {
val value = RealmAnyNotIndexedWithPK()
value.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1))
realm.beginTransaction()
val managedValue = realm.copyToRealm(value)
realm.commitTransaction()
val managedInnerObject = managedValue.realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)!!
assertTrue(managedInnerObject.isManaged)
assertEquals(TEST_VALUE_1, managedInnerObject.name)
}
@Test
fun copyToRealmOrUpdate_realmModel() {
realm.executeTransaction { realm ->
val obj = realm.createObject<RealmAnyNotIndexedWithPK>(0)
obj.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1))
}
val value = RealmAnyNotIndexedWithPK()
value.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2))
realm.beginTransaction()
val managedValue = realm.copyToRealmOrUpdate(value)
realm.commitTransaction()
val managedInnerObject = managedValue.realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject.isManaged)
assertEquals(TEST_VALUE_2, managedInnerObject.name)
}
@Test
fun insert_realmModel() {
realm.executeTransaction { realm ->
val value = RealmAnyNotIndexedWithPK()
value.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1))
realm.insert(value)
}
val managedValue = realm.where<RealmAnyNotIndexedWithPK>().findFirst()!!
val managedInnerObject = managedValue.realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject.isManaged)
assertEquals(TEST_VALUE_1, managedInnerObject.name)
}
@Test
fun insertOrUpdate_realmModel() {
realm.executeTransaction { realm ->
val value = realm.createObject<RealmAnyNotIndexedWithPK>(0)
value.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1))
}
realm.executeTransaction { realm ->
val value = RealmAnyNotIndexedWithPK()
value.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2))
realm.insertOrUpdate(value)
}
val all = realm.where<RealmAnyNotIndexedWithPK>().findAll()
assertEquals(1, all.size)
val managedInnerObject = all.first()!!.realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject.isManaged)
assertEquals(TEST_VALUE_2, managedInnerObject.name)
}
/**
* Tests for RealmAny RealmLists
*/
@Test
fun copyFromRealm_list() {
val list = RealmList(*testList1)
val inner = RealmAnyNotIndexedWithPK(1)
inner.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1))
list.add(RealmAny.valueOf(inner))
realm.beginTransaction()
val value = realm.createObject<RealmAnyRealmListWithPK>(0)
value.realmAnyList = list
realm.commitTransaction()
val copy0 = realm.copyFromRealm(value, 0)
val copy1 = realm.copyFromRealm(value, 1)
val copy2 = realm.copyFromRealm(value, 2)
assertFalse(copy0.isManaged)
assertFalse(copy1.isManaged)
assertFalse(copy2.isManaged)
assertNull(copy0.realmAnyList)
assertTrue(copy1.realmAnyList.containsAll(testList1.asList()))
assertEquals(RealmAny.nullValue(), copy1.realmAnyList.last()!!.asRealmModel(RealmAnyNotIndexedWithPK::class.java).realmAny)
assertEquals(TEST_VALUE_1, copy2.realmAnyList.last()!!.asRealmModel(RealmAnyNotIndexedWithPK::class.java).realmAny!!.asRealmModel(PrimaryKeyAsString::class.java).name)
}
@Test
fun copyToRealmOrUpdate_list() {
realm.executeTransaction { realm ->
val value = realm.createObject<RealmAnyRealmListWithPK>(0)
value.realmAnyList = RealmList(*testList1)
value.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1)))
}
val update = RealmAnyRealmListWithPK(0)
update.realmAnyList = RealmList(*testList2)
update.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2)))
realm.beginTransaction()
val managedValue = realm.copyToRealmOrUpdate(update)
realm.commitTransaction()
assertTrue(managedValue.realmAnyList.containsAll(testList2.asList()))
val managedInnerObject = managedValue.realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject.isManaged)
assertEquals(TEST_VALUE_2, managedInnerObject.name)
}
@Test
fun insert_realmModelList() {
realm.executeTransaction { realm ->
val value = RealmAnyRealmListWithPK()
value.realmAnyList = RealmList(*testList1)
value.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1)))
realm.insert(value)
}
val managedValue = realm.where<RealmAnyRealmListWithPK>().findFirst()!!
val managedInnerObject = managedValue.realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject.isManaged)
assertTrue(managedValue.realmAnyList.containsAll(testList1.asList()))
assertEquals(TEST_VALUE_1, managedInnerObject.name)
}
@Test
fun insertOrUpdate_realmModelList() {
realm.executeTransaction { realm ->
val value = realm.createObject<RealmAnyRealmListWithPK>(0)
value.realmAnyList = RealmList(*testList1)
value.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1)))
}
realm.executeTransaction { realm ->
val value = RealmAnyRealmListWithPK(0)
value.realmAnyList = RealmList(*testList2)
value.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2)))
realm.insertOrUpdate(value)
}
val all = realm.where<RealmAnyRealmListWithPK>().findAll()
assertEquals(1, all.size)
assertTrue(all.first()!!.realmAnyList.containsAll(testList2.asList()))
val managedInnerObject = all.first()!!.realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject.isManaged)
assertEquals(TEST_VALUE_2, managedInnerObject.name)
}
@Test
fun bulk_copyToRealm_realmModel() {
val value1 = RealmAnyNotIndexedWithPK(0)
value1.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1))
val value2 = RealmAnyNotIndexedWithPK(1)
value2.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2))
realm.beginTransaction()
val objects = realm.copyToRealm(arrayListOf(value1, value2))
realm.commitTransaction()
val managedInnerObject1 = objects[0].realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
val managedInnerObject2 = objects[1].realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject1.isManaged)
assertTrue(managedInnerObject2.isManaged)
assertEquals(TEST_VALUE_1, managedInnerObject1.name)
assertEquals(TEST_VALUE_2, managedInnerObject2.name)
}
@Test
fun bulk_copyToRealm_realmModelList() {
val value1 = RealmAnyRealmListWithPK(0)
value1.realmAnyList = RealmList(*testList1)
value1.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1)))
val value2 = RealmAnyRealmListWithPK(1)
value2.realmAnyList = RealmList(*testList2)
value2.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2)))
realm.beginTransaction()
val objects = realm.copyToRealm(arrayListOf(value1, value2))
realm.commitTransaction()
assertTrue(objects[0].realmAnyList.containsAll(testList1.asList()))
assertTrue(objects[1].realmAnyList.containsAll(testList2.asList()))
val managedInnerObject1 = objects[0].realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
val managedInnerObject2 = objects[1].realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject1.isManaged)
assertEquals(TEST_VALUE_1, managedInnerObject1.name)
assertTrue(managedInnerObject2.isManaged)
assertEquals(TEST_VALUE_2, managedInnerObject2.name)
}
@Test
fun bulk_copyToRealmOrUpdate_realmModel() {
realm.executeTransaction { realm ->
val obj1 = realm.createObject<RealmAnyNotIndexedWithPK>(0)
obj1.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1))
val obj2 = realm.createObject<RealmAnyNotIndexedWithPK>(1)
obj2.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2))
}
val value1 = RealmAnyNotIndexedWithPK(0)
value1.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_3))
val value2 = RealmAnyNotIndexedWithPK(1)
value2.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_4))
realm.beginTransaction()
val objects = realm.copyToRealmOrUpdate(arrayListOf(value1, value2))
realm.commitTransaction()
val managedInnerObject1 = objects[0].realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
val managedInnerObject2 = objects[1].realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject1.isManaged)
assertEquals(TEST_VALUE_3, managedInnerObject1.name)
assertTrue(managedInnerObject2.isManaged)
assertEquals(TEST_VALUE_4, managedInnerObject2.name)
}
@Test
fun bulk_copyToRealmOrUpdate_realmModelList() {
realm.executeTransaction { realm ->
val value1 = realm.createObject<RealmAnyRealmListWithPK>(0)
value1.realmAnyList = RealmList(*testList1)
value1.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1)))
val value2 = realm.createObject<RealmAnyRealmListWithPK>(1)
value2.realmAnyList = RealmList(*testList1)
value2.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1)))
}
val value1 = RealmAnyRealmListWithPK(0)
value1.realmAnyList = RealmList(*testList2)
value1.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_3)))
val value2 = RealmAnyRealmListWithPK(1)
value2.realmAnyList = RealmList(*testList2)
value2.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_4)))
realm.beginTransaction()
val objects = realm.copyToRealmOrUpdate(arrayListOf(value1, value2))
realm.commitTransaction()
assertTrue(objects[0].realmAnyList.containsAll(testList2.asList()))
assertTrue(objects[1].realmAnyList.containsAll(testList2.asList()))
val managedInnerObject1 = objects[0].realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
val managedInnerObject2 = objects[1].realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject1.isManaged)
assertEquals(TEST_VALUE_3, managedInnerObject1.name)
assertTrue(managedInnerObject2.isManaged)
assertEquals(TEST_VALUE_4, managedInnerObject2.name)
}
@Test
fun bulk_insert_realmModel() {
realm.executeTransaction { realm ->
val value1 = RealmAnyNotIndexedWithPK(0)
value1.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1))
val value2 = RealmAnyNotIndexedWithPK(1)
value2.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2))
realm.insert(arrayListOf(value1, value2))
}
val objects = realm.where<RealmAnyNotIndexedWithPK>().findAll()
val managedInnerObject1 = objects[0]!!.realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
val managedInnerObject2 = objects[1]!!.realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject1.isManaged)
assertEquals(TEST_VALUE_1, managedInnerObject1.name)
assertTrue(managedInnerObject2.isManaged)
assertEquals(TEST_VALUE_2, managedInnerObject2.name)
}
@Test
fun bulk_insert_realmModelList() {
realm.executeTransaction { realm ->
val value1 = RealmAnyRealmListWithPK(0)
value1.realmAnyList = RealmList(*testList1)
value1.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1)))
val value2 = RealmAnyRealmListWithPK(1)
value2.realmAnyList = RealmList(*testList1)
value2.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2)))
realm.insert(arrayListOf(value1, value2))
}
val objects = realm.where<RealmAnyRealmListWithPK>().findAll()
assertTrue(objects[0]!!.realmAnyList.containsAll(testList1.asList()))
assertTrue(objects[1]!!.realmAnyList.containsAll(testList1.asList()))
val managedInnerObject1 = objects[0]!!.realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
val managedInnerObject2 = objects[1]!!.realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject1.isManaged)
assertEquals(TEST_VALUE_1, managedInnerObject1.name)
assertTrue(managedInnerObject2.isManaged)
assertEquals(TEST_VALUE_2, managedInnerObject2.name)
}
@Test
fun bulk_insertOrUpdate_realmModel() {
realm.executeTransaction { realm ->
val value1 = realm.createObject<RealmAnyNotIndexedWithPK>(0)
value1.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_1))
val value2 = realm.createObject<RealmAnyNotIndexedWithPK>(1)
value2.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2))
}
realm.executeTransaction { realm ->
val value1 = RealmAnyNotIndexedWithPK(0)
value1.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_3))
val value2 = RealmAnyNotIndexedWithPK(1)
value2.realmAny = RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_4))
realm.insertOrUpdate(arrayListOf(value1, value2))
}
val all = realm.where<RealmAnyNotIndexedWithPK>().findAll()
assertEquals(2, all.size)
val managedInnerObject1 = all[0]!!.realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
val managedInnerObject2 = all[1]!!.realmAny!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject1.isManaged)
assertEquals(TEST_VALUE_3, managedInnerObject1.name)
assertTrue(managedInnerObject2.isManaged)
assertEquals(TEST_VALUE_4, managedInnerObject2.name)
}
@Test
fun bulk_insertOrUpdate_realmModelList() {
realm.executeTransaction { realm ->
val value1 = realm.createObject<RealmAnyRealmListWithPK>(0)
value1.realmAnyList = RealmList(*testList1)
value1.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString("hello world1")))
val value2 = realm.createObject<RealmAnyRealmListWithPK>(1)
value2.realmAnyList = RealmList(*testList1)
value2.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_2)))
}
realm.executeTransaction { realm ->
val value1 = RealmAnyRealmListWithPK(0)
value1.realmAnyList = RealmList(*testList2)
value1.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_3)))
val value2 = RealmAnyRealmListWithPK(1)
value2.realmAnyList = RealmList(*testList2)
value2.realmAnyList.add(RealmAny.valueOf(PrimaryKeyAsString(TEST_VALUE_4)))
realm.insertOrUpdate(arrayListOf(value1, value2))
}
val all = realm.where<RealmAnyRealmListWithPK>().findAll()
assertEquals(2, all.size)
assertTrue(all[0]!!.realmAnyList.containsAll(testList2.asList()))
assertTrue(all[1]!!.realmAnyList.containsAll(testList2.asList()))
val managedInnerObject1 = all[0]!!.realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject1.isManaged)
assertEquals(TEST_VALUE_3, managedInnerObject1.name)
val managedInnerObject2 = all[1]!!.realmAnyList.last()!!.asRealmModel(PrimaryKeyAsString::class.java)
assertTrue(managedInnerObject2.isManaged)
assertEquals(TEST_VALUE_4, managedInnerObject2.name)
}
}
| apache-2.0 |
auth0/Auth0.Android | auth0/src/test/java/com/auth0/android/provider/AuthenticationActivityMock.kt | 1 | 638 | package com.auth0.android.provider
import android.content.Context
import android.content.Intent
public class AuthenticationActivityMock : AuthenticationActivity() {
internal var customTabsController: CustomTabsController? = null
public var deliveredIntent: Intent? = null
private set
override fun createCustomTabsController(
context: Context,
options: CustomTabsOptions
): CustomTabsController {
return customTabsController!!
}
override fun deliverAuthenticationResult(result: Intent?) {
deliveredIntent = result
super.deliverAuthenticationResult(result)
}
} | mit |
kevinhinterlong/archwiki-viewer | app/src/main/java/com/jtmcn/archwiki/viewer/SearchResultsAdapter.kt | 2 | 1639 | package com.jtmcn.archwiki.viewer
import android.app.SearchManager
import android.content.Context
import android.database.MatrixCursor
import android.provider.BaseColumns
import androidx.cursoradapter.widget.CursorAdapter
import androidx.cursoradapter.widget.SimpleCursorAdapter
import com.jtmcn.archwiki.viewer.data.SearchResult
/**
* Helper for creating a [SimpleCursorAdapter] which will
* list the search results for a [android.widget.SearchView]
*/
object SearchResultsAdapter {
private val columnNames = arrayOf(BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1)
private val from = arrayOf(SearchManager.SUGGEST_COLUMN_TEXT_1)
private val to = intArrayOf(R.id.url)
/**
* Creates a cursor adapter given a [<].
* https://stackoverflow.com/questions/11628172/converting-an-arrayadapter-to-cursoradapter-for-use-in-a-searchview/11628527#11628527
*
* @param results the results to be placed in the adapter.
* @return the adapter.
*/
fun getCursorAdapter(context: Context, results: List<SearchResult>): CursorAdapter {
var id = 0
val cursor = MatrixCursor(columnNames)
for ((pageName) in results) {
val temp = arrayOfNulls<String>(2)
temp[0] = id.toString() // "_id"
temp[1] = pageName // "title"
cursor.addRow(temp)
id++
}
return SimpleCursorAdapter(
context,
R.layout.search_suggestions_list_item,
cursor,
from,
to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER
)
}
}
| apache-2.0 |
k9mail/k-9 | app/k9mail/src/debug/java/app/k9mail/dev/DemoBackendFactory.kt | 2 | 525 | package app.k9mail.dev
import app.k9mail.backend.demo.DemoBackend
import com.fsck.k9.Account
import com.fsck.k9.backend.BackendFactory
import com.fsck.k9.backend.api.Backend
import com.fsck.k9.mailstore.K9BackendStorageFactory
class DemoBackendFactory(private val backendStorageFactory: K9BackendStorageFactory) : BackendFactory {
override fun createBackend(account: Account): Backend {
val backendStorage = backendStorageFactory.createBackendStorage(account)
return DemoBackend(backendStorage)
}
}
| apache-2.0 |
laminr/aeroknow | app/src/main/java/biz/eventually/atpl/ui/source/SourceRepository.kt | 1 | 3084 | package biz.eventually.atpl.ui.source
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import biz.eventually.atpl.R
import biz.eventually.atpl.common.RxBaseManager
import biz.eventually.atpl.data.DataProvider
import biz.eventually.atpl.data.NetworkStatus
import biz.eventually.atpl.data.dao.LastCallDao
import biz.eventually.atpl.data.dao.SourceDao
import biz.eventually.atpl.data.db.LastCall
import biz.eventually.atpl.data.db.Source
import biz.eventually.atpl.utils.hasInternetConnection
import com.google.firebase.perf.metrics.AddTrace
import io.reactivex.Maybe
import io.reactivex.rxkotlin.plusAssign
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import timber.log.Timber
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by Thibault de Lambilly on 20/03/17.
*
*/
@Singleton
class SourceRepository @Inject constructor(private val dataProvider: DataProvider, private val dao: SourceDao, private val lastCallDao: LastCallDao) : RxBaseManager() {
private var status: MutableLiveData<NetworkStatus> = MutableLiveData()
@AddTrace(name = "getSources", enabled = true)
fun getSources(): LiveData<List<Source>> {
return dao.getAll()
}
fun updateData() {
if (hasInternetConnection()) getWebData()
}
fun networkStatus(): LiveData<NetworkStatus> {
return status
}
private fun getWebData() {
doAsync {
val lastCall = lastCallDao.findByType(LastCall.TYPE_SOURCE)?.updatedAt ?: 0L
uiThread {
status.postValue(NetworkStatus.LOADING)
disposables += dataProvider
.dataGetSources(lastCall)
.subscribeOn(scheduler.network)
.observeOn(scheduler.main)
.subscribe({ sWeb ->
analyseData(sWeb)
status.postValue(NetworkStatus.SUCCESS)
}, { e ->
Timber.d("getSources: " + e)
status.postValue(NetworkStatus.ERROR)
})
}
}
}
private fun analyseData(sWeb: List<Source>) {
doAsync {
val sourceIds = dao.getIds()
sWeb.forEach { s ->
// Update
if (s.idWeb in sourceIds) {
s.idWeb?.let {
Maybe.just(it).observeOn(scheduler.disk).map {
val sourceDb = dao.findById(it)
sourceDb?.let {
it.name = s.name
dao.update(it)
}
}
}
}
// New
else {
dao.insert(s)
}
}
// update time reference
lastCallDao.updateOrInsert(LastCall(LastCall.TYPE_SOURCE, Date().time))
}
}
}
| mit |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceWithEnumMapInspection.kt | 2 | 3353 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.types.typeUtil.isEnum
private val hashMapCreationFqNames = setOf(
"java.util.HashMap.<init>",
"kotlin.collections.HashMap.<init>",
"kotlin.collections.hashMapOf"
)
class ReplaceWithEnumMapInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return callExpressionVisitor(fun(element: KtCallExpression) {
if (!element.platform.isJvm()) return
val context = element.safeAnalyzeNonSourceRootCode()
val fqName = element.getResolvedCall(context)?.resultingDescriptor?.fqNameUnsafe?.asString() ?: return
if (!hashMapCreationFqNames.contains(fqName)) return
if (element.valueArguments.isNotEmpty()) return
val expectedType = context[BindingContext.EXPECTED_EXPRESSION_TYPE, element] ?: return
val firstArgType = expectedType.arguments.firstOrNull()?.type ?: return
if (!firstArgType.isEnum()) return
val enumClassName = firstArgType.constructor.declarationDescriptor?.fqNameUnsafe?.asString() ?: return
holder.registerProblem(element, KotlinBundle.message("replaceable.with.enummap"), ReplaceWithEnumMapFix(enumClassName))
})
}
private class ReplaceWithEnumMapFix(
private val enumClassName: String
) : LocalQuickFix {
override fun getFamilyName() = name
override fun getName() = KotlinBundle.message("replace.with.enum.map.fix.text")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val call = descriptor.psiElement as? KtCallExpression ?: return
val factory = KtPsiFactory(call)
val file = call.containingKtFile
val enumMapDescriptor = file.resolveImportReference(FqName("java.util.EnumMap")).firstOrNull() ?: return
ImportInsertHelper.getInstance(project).importDescriptor(call.containingKtFile, enumMapDescriptor)
call.replace(factory.createExpressionByPattern("EnumMap($0::class.java)", enumClassName))
}
}
} | apache-2.0 |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/data/repositories/jpa/ActivityReportSettingsRepository.kt | 1 | 938 | /*
* Copyright 2018 Duncan Casteleyn
*
* 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 be.duncanc.discordmodbot.data.repositories.jpa
import be.duncanc.discordmodbot.data.entities.ActivityReportSettings
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface ActivityReportSettingsRepository : JpaRepository<ActivityReportSettings, Long>
| apache-2.0 |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/data/tree/RemovableTreeNode.kt | 1 | 187 | package org.hexworks.zircon.internal.data.tree
interface RemovableTreeNode<D : Any?> : TreeNode<D> {
/**
* Removes this [TreeNode] from its parent.
*/
fun remove()
}
| apache-2.0 |
JStege1206/AdventOfCode | aoc-archetype/src/main/resources/archetype-resources/src/main/kotlin/days/Day19.kt | 1 | 285 | package ${package}.days
import nl.jstege.adventofcode.aoccommon.days.Day
class Day19 : Day(title = "") {
override fun first(input: Sequence<String>): Any {
TODO("Implement")
}
override fun second(input: Sequence<String>): Any {
TODO("Implement")
}
}
| mit |
fashare2015/MVVM-JueJin | app/src/main/kotlin/com/fashare/mvvm_juejin/model/user/UserBean.kt | 1 | 3618 | package com.fashare.mvvm_juejin.model.user
import java.io.Serializable
/**
* role : editor
* username : 梁山boy
* selfDescription : 擅长面向基佬编程
* email :
* mobilePhoneNumber : 18818276018
* jobTitle : Android
* company : 上海
* avatarHd : https://avatars.githubusercontent.com/u/15076541?v=3
* avatarLarge : https://avatars.githubusercontent.com/u/15076541?v=3
* blogAddress : http://blog.csdn.net/a153614131
* deviceType : android
* editorType : markdown
* allowNotification : false
* emailVerified : false
* mobilePhoneVerified : false
* isAuthor : true
* isUnitedAuthor : false
* blacklist : false
* followeesCount : 116
* followersCount : 39
* postedPostsCount : 5
* postedEntriesCount : 5
* collectedEntriesCount : 238
* viewedEntriesCount : 1832
* subscribedTagsCount : 18
* totalCollectionsCount : 1349
* totalViewsCount : 35326
* totalCommentsCount : 73
* latestLoginedInAt : 2017-09-12T10:55:48.674Z
* createdAt : 2016-08-24T04:43:32.001Z
* updatedAt : 2017-09-12T12:10:05.860Z
* collectionSetCount : 28
* useLeancloudPwd : false
* objectId : 57bd25f4a34131005b211b84
* uid : 57bd25f4a34131005b211b84
*/
/**
* 用户信息
*/
class UserBean : Serializable {
var role: String? = null
var username: String? = null
var selfDescription: String? = null
var email: String? = null
var mobilePhoneNumber: String? = null
var jobTitle: String? = null
var company: String? = null
var avatarHd: String? = null
var avatarLarge: String? = null
var blogAddress: String? = null
var deviceType: String? = null
var editorType: String? = null
var allowNotification: Boolean = false
var emailVerified: Boolean = false
var mobilePhoneVerified: Boolean = false
var isAuthor: Boolean = false
var isUnitedAuthor: Boolean = false
var blacklist: Boolean = false
var followeesCount: Int = 0
var followersCount: Int = 0
var postedPostsCount: Int = 0
var postedEntriesCount: Int = 0
var collectedEntriesCount: Int = 0
var viewedEntriesCount: Int = 0
var subscribedTagsCount: Int = 0
var totalCollectionsCount: Int = 0
var totalViewsCount: Int = 0
var totalCommentsCount: Int = 0
var latestLoginedInAt: String? = null
var createdAt: String? = null
var updatedAt: String? = null
var collectionSetCount: Int = 0
var useLeancloudPwd: Boolean = false
var objectId: String? = null
var uid: String? = null
class CommunityBean: Serializable {
/**
* uid : 5885816355
* nickname : 墨镜猫jacky
*/
var weibo: WeiboBean? = null
/**
* nickname : Android王世昌
* uid : oDv1Eww5c17raaESRVI8l9M6zsuE
* expires_at : 1468246472191
*/
var wechat: WechatBean? = null
/**
* nickname : Jacky Wang
* uid : 17797018
* expires_at : 1468239341180
*/
var github: GithubBean? = null
class WeiboBean : Serializable{
var uid: String? = null
var nickname: String? = null
}
class WechatBean : Serializable{
var nickname: String? = null
var uid: String? = null
var expires_at: String? = null
}
class GithubBean : Serializable{
var nickname: String? = null
var uid: String? = null
var expires_at: String? = null
}
}
class TokenBean: Serializable{
var token: String? = null
var user_id: String? = null
var state: String? = null
}
}
| mit |
jasonmfehr/kotlin-koans | src/iii_conventions/_31_Invoke_.kt | 1 | 571 | package iii_conventions
import util.TODO
class Invokable {
var num = 0
operator fun invoke(): Invokable {
this.num++
return this
}
fun getNumberOfInvocations(): Int = this.num
}
fun todoTask31(): Nothing = TODO(
"""
Task 31.
Change class Invokable to count the number of invocations (round brackets).
Uncomment the commented code - it should return 4.
""",
references = { invokable: Invokable -> })
fun task31(invokable: Invokable): Int {
return invokable()()()().getNumberOfInvocations()
}
| mit |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/ui/posts/editor/media/OptimizeMediaUseCaseTest.kt | 1 | 7078 | package org.wordpress.android.ui.posts.editor.media
import android.net.Uri
import kotlinx.coroutines.InternalCoroutinesApi
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.TEST_DISPATCHER
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.test
import org.wordpress.android.ui.posts.editor.EditorTracker
import org.wordpress.android.util.MediaUtilsWrapper
@RunWith(MockitoJUnitRunner::class)
@InternalCoroutinesApi
class OptimizeMediaUseCaseTest : BaseUnitTest() {
@Test
fun `Uri filtered out when getRealPathFromURI returns null`() = test {
// Arrange
val uris = listOf<Uri>(mock(), mock(), mock())
val mediaUtilsWrapper = createMediaUtilsWrapper(resultForGetRealPath = uris[1] to null)
// Act
val optimizeMediaResult = createOptimizeMediaUseCase(mediaUtilsWrapper = mediaUtilsWrapper)
.optimizeMediaIfSupportedAsync(SiteModel(), FRESHLY_TAKEN, uris)
// Assert
assertThat(optimizeMediaResult.optimizedMediaUris.size).isEqualTo(uris.size - 1)
}
@Test
fun `LoadingSomeMediaFailed set to true when getRealPathFromURI returns null`() = test {
// Arrange
val uris = listOf<Uri>(mock(), mock(), mock())
val mediaUtilsWrapper = createMediaUtilsWrapper(resultForGetRealPath = uris[1] to null)
// Act
val optimizeMediaResult = createOptimizeMediaUseCase(mediaUtilsWrapper = mediaUtilsWrapper)
.optimizeMediaIfSupportedAsync(SiteModel(), FRESHLY_TAKEN, uris)
// Assert
assertThat(optimizeMediaResult.loadingSomeMediaFailed).isTrue()
}
@Test
fun `LoadingSomeMediaFailed set to false on success`() = test {
// Arrange
val uris = listOf<Uri>(mock(), mock(), mock())
// Act
val optimizeMediaResult = createOptimizeMediaUseCase()
.optimizeMediaIfSupportedAsync(SiteModel(), FRESHLY_TAKEN, uris)
// Assert
assertThat(optimizeMediaResult.loadingSomeMediaFailed).isFalse()
}
@Test
fun `Optimization enabled, result contains optimized uris`() = test {
// Arrange
val uris = listOf<Uri>(mock())
val optimizedUri = mock<Uri>()
// OptimizeMediaResult is not null => optimization supported
val mediaUtilsWrapper = createMediaUtilsWrapper(resultForGetOptimizeMedia = optimizedUri)
// Act
val optimizeMediaResult = createOptimizeMediaUseCase(mediaUtilsWrapper = mediaUtilsWrapper)
.optimizeMediaIfSupportedAsync(SiteModel(), FRESHLY_TAKEN, uris)
// Assert
assertThat(optimizeMediaResult.optimizedMediaUris).isEqualTo(listOf(optimizedUri))
assertThat(optimizeMediaResult.optimizedMediaUris).isNotEqualTo(uris)
}
@Test
fun `Optimization disabled, is WPCom, result contains original uris`() = test {
// Arrange
val uris = listOf<Uri>(mock(), mock(), mock())
val siteModel = SiteModel().apply { setIsWPCom(true) }
// OptimizeMediaResult is null => optimization disabled
val mediaUtilsWrapper = createMediaUtilsWrapper(resultForGetOptimizeMedia = null)
// Act
val optimizeMediaResult = createOptimizeMediaUseCase(mediaUtilsWrapper = mediaUtilsWrapper)
.optimizeMediaIfSupportedAsync(siteModel, FRESHLY_TAKEN, uris)
// Assert
assertThat(optimizeMediaResult.optimizedMediaUris).isEqualTo(uris)
}
@Test
fun `Optimization disabled, self-hosted, result contains uris with fixed orientation`() =
test {
// Arrange
val uris = listOf<Uri>(mock())
val fixedOrientationUri = mock<Uri>()
// Is self-hosted
val siteModel = SiteModel().apply { setIsWPCom(false) }
// OptimizeMediaResult is null => optimization disabled
val mediaUtilsWrapper = createMediaUtilsWrapper(
resultForGetOptimizeMedia = null,
resultForFixOrientation = fixedOrientationUri
)
// Act
val optimizeMediaResult = createOptimizeMediaUseCase(mediaUtilsWrapper = mediaUtilsWrapper)
.optimizeMediaIfSupportedAsync(siteModel, FRESHLY_TAKEN, uris)
// Assert
assertThat(optimizeMediaResult.optimizedMediaUris).isEqualTo(
listOf(
fixedOrientationUri
)
)
assertThat(optimizeMediaResult.optimizedMediaUris).isNotEqualTo(uris)
}
@Test
fun `Optimization disabled, self-hosted, fixOrientationIssue returns null, result contains original uris`() =
test {
// Arrange
val uris = listOf<Uri>(mock())
val fixedOrientationUri = null
// Is self-hosted
val siteModel = SiteModel().apply { setIsWPCom(false) }
// OptimizeMediaResult is null => optimization disabled
val mediaUtilsWrapper = createMediaUtilsWrapper(
resultForGetOptimizeMedia = null,
resultForFixOrientation = fixedOrientationUri
)
// Act
val optimizeMediaResult = createOptimizeMediaUseCase(mediaUtilsWrapper = mediaUtilsWrapper)
.optimizeMediaIfSupportedAsync(siteModel, FRESHLY_TAKEN, uris)
// Assert
assertThat(optimizeMediaResult.optimizedMediaUris).isEqualTo(uris)
}
private companion object Fixtures {
private const val FRESHLY_TAKEN = false
private fun createOptimizeMediaUseCase(
editorTracker: EditorTracker = mock(),
mediaUtilsWrapper: MediaUtilsWrapper = createMediaUtilsWrapper()
): OptimizeMediaUseCase {
return OptimizeMediaUseCase(editorTracker, mediaUtilsWrapper, TEST_DISPATCHER)
}
private fun createMediaUtilsWrapper(
resultForGetRealPath: Pair<Uri, String?>? = null,
resultForGetOptimizeMedia: Uri? = mock(),
resultForFixOrientation: Uri? = mock()
) =
mock<MediaUtilsWrapper> {
on { getOptimizedMedia(any(), any()) }.thenReturn(resultForGetOptimizeMedia)
on { fixOrientationIssue(any(), any()) }.thenReturn(resultForFixOrientation)
on { getRealPathFromURI(any()) }.thenReturn("")
resultForGetRealPath?.let {
on { getRealPathFromURI(resultForGetRealPath.first) }.thenReturn(
resultForGetRealPath.second
)
}
}
}
}
| gpl-2.0 |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/viewholders/ReferredItemViewHolder.kt | 1 | 830 | package org.wordpress.android.ui.stats.refresh.lists.sections.viewholders
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import org.wordpress.android.R
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ReferredItem
class ReferredItemViewHolder(parent: ViewGroup) : BlockListItemViewHolder(
parent,
R.layout.stats_block_referred_item
) {
private val container = itemView.findViewById<LinearLayout>(R.id.container)
private val label = itemView.findViewById<TextView>(R.id.label)
private val title = itemView.findViewById<TextView>(R.id.title)
fun bind(item: ReferredItem) {
container.setOnClickListener { item.navigationAction?.click() }
label.setText(item.label)
title.text = item.itemTitle
}
}
| gpl-2.0 |
mbrlabs/Mundus | editor/src/main/com/mbrlabs/mundus/editor/ui/widgets/ScrollPaneSlider.kt | 1 | 1310 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.ui.widgets
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.kotcrab.vis.ui.widget.VisSlider
/**
* Makes it possible to use a slider inside a scroll pane.
*
* @author Marcus Brummer
* @version 04-02-2016
*/
class ScrollPaneSlider(min: Float, max: Float, stepSize: Float, vertical: Boolean) : VisSlider(min, max, stepSize, vertical) {
init {
addListener(object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
event?.stop()
return true
}
})
}
}
| apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/multiModuleHighlighting/multiplatform/headerWithoutImplForBoth/common/common.kt | 15 | 269 | expect class <error descr="[NO_ACTUAL_FOR_EXPECT] Expected class 'My' has no actual declaration in module testModule_JS for JS"><error descr="[NO_ACTUAL_FOR_EXPECT] Expected class 'My' has no actual declaration in module testModule_JVM for JVM">My</error></error> {
}
| apache-2.0 |
johnjohndoe/Umweltzone | Umweltzone/src/main/java/de/avpptr/umweltzone/models/extensions/ChildZoneExtensions.kt | 1 | 2634 | /*
* Copyright (C) 2020 Tobias Preuss
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@file:JvmName("ChildZoneExtensions")
package de.avpptr.umweltzone.models.extensions
import de.avpptr.umweltzone.contract.LowEmissionZoneNumbers
import de.avpptr.umweltzone.models.ChildZone
import info.metadude.kotlin.library.roadsigns.RoadSign
val ChildZone.roadSignType: RoadSign.Type
get() = when {
zoneNumber == LowEmissionZoneNumbers.NONE -> RoadSign.Type.None
zoneNumber == LowEmissionZoneNumbers.RED -> RoadSign.Type.EnvironmentalBadge.RedYellowGreen
zoneNumber == LowEmissionZoneNumbers.YELLOW -> RoadSign.Type.EnvironmentalBadge.YellowGreen
zoneNumber == LowEmissionZoneNumbers.GREEN -> RoadSign.Type.EnvironmentalBadge.Green
zoneNumber == LowEmissionZoneNumbers.LIGHT_BLUE && fileName == "lez_stuttgart" ->
RoadSign.Type.DieselProhibition.FreeAsOfEuro5VExceptDeliveryVehiclesStuttgart
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_hamburg_max_brauer_allee" ->
RoadSign.Type.DieselProhibition.CarsFreeUntilEuro5VOpenForResidentsHamburg
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_hamburg_stresemannstrasse" ->
RoadSign.Type.DieselProhibition.HgvsFreeUntilEuroVOpenForResidentsHamburg
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_berlin" ->
RoadSign.Type.DieselProhibition.CarsFreeUntilEuro5VOpenForResidentsBerlin
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_darmstadt_huegelstrasse" ->
RoadSign.Type.DieselProhibition.CarsFreeUntilEuro5PetrolUntilEuro2Darmstadt
zoneNumber == LowEmissionZoneNumbers.DARK_BLUE && fileName == "dpz_darmstadt_heinrichstrasse" ->
RoadSign.Type.DieselProhibition.HgvsCarsFreeUntilEuro5VPetrolUntilEuro2Darmstadt
else -> throw IllegalStateException("Unknown combination of zone number: '$zoneNumber' and file name: '$fileName'.")
}
| gpl-3.0 |
mdaniel/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/replace/KotlinSSRClassReplaceTest.kt | 1 | 4826 | // 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.structuralsearch.replace
import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralReplaceTest
class KotlinSSRClassReplaceTest : KotlinStructuralReplaceTest() {
fun testClassModifierReplacement() {
doTest(
searchPattern = "public class '_ID('_PARAM : '_TYPE)",
replacePattern = "internal class '_ID('_PARAM : '_TYPE)",
match = "public class Foo(bar : Int = 0) {}",
result = "internal class Foo(bar : Int = 0) {}"
)
}
fun testConstructorFormatCopy() {
doTest(
searchPattern = "class '_ID('_PARAM : '_TYPE = '_INIT)",
replacePattern = "class '_ID('_PARAM : '_TYPE = '_INIT)",
match = "class Foo(bar : Int = 0) {}",
result = "class Foo(bar : Int = 0) {}"
)
}
fun testConstructorModifier() {
doTest(
searchPattern = "class '_ID('_PARAM : '_TYPE = '_INIT)",
replacePattern = "class '_ID('_PARAM : '_TYPE = '_INIT)",
match = "class Foo private constructor(bar : Int = 0) {}",
result = "class Foo private constructor(bar : Int = 0) {}"
)
}
fun testConstructorModifierReplace() {
doTest(
searchPattern = "class '_ID private constructor('_PARAM : '_TYPE = '_INIT)",
replacePattern = "class '_ID public constructor('_PARAM : '_TYPE = '_INIT)",
match = "class Foo private constructor(bar : Int = 0) {}",
result = "class Foo public constructor(bar : Int = 0) {}"
)
}
fun testConstructorNamedParameter() {
doTest(
searchPattern = "class '_ID('_PARAM : '_TYPE = '_INIT)",
replacePattern = "class '_ID('_PARAM : '_TYPE = '_INIT)",
match = "class Foo(bar : Int = 0) {}",
result = "class Foo(bar : Int = 0) {}"
)
}
fun testConstructorParameterFormatCopy() {
doTest(
searchPattern = "class '_ID('_PARAM : '_TYPE)",
replacePattern = "class '_ID('_PARAM : '_TYPE)",
match = "class Foo(bar : Int = 0) {}",
result = "class Foo(bar : Int = 0) {}"
)
}
fun testClassSuperTypesFormatCopy() {
doTest(
searchPattern = "class '_ID()",
replacePattern = "class '_ID()",
match = "class Foo() : Cloneable , Any() {}",
result = "class Foo() : Cloneable , Any() {}"
)
}
fun testClassSuperTypesFormatNoBodyCopy() {
doTest(
searchPattern = "class '_ID",
replacePattern = "class '_ID",
match = """
interface Foo
interface Bar
class FooBar : Foo , Bar
""".trimIndent(),
result = """
interface Foo
interface Bar
class FooBar : Foo , Bar
""".trimIndent()
)
}
fun testAnnotatedClassCountFilter() {
doTest(
searchPattern = "@'_ANN* class '_ID('_PARAM : '_TYPE)",
replacePattern = "@'_ANN class '_ID('_PARAM : '_TYPE)",
match = "class Foo(bar : Int) {}",
result = "class Foo(bar : Int) {}"
)
}
fun testClassExtensionCountFilter() {
doTest(
searchPattern = "class '_ID() : '_INTFACE*",
replacePattern = "class '_ID() : '_INTFACE",
match = "class Foo() {}",
result = "class Foo() {}"
)
}
fun testClassTypeParamCountFilter() {
doTest(
searchPattern = "class '_ID<'_TYPE*>()",
replacePattern = "class '_ID<'_TYPE>()",
match = "class Foo() {}",
result = "class Foo() {}"
)
}
fun testSimpleClassReplacement() {
doTest(
searchPattern = "class '_ID",
replacePattern = "class '_ID",
match = """
class Foo(bar: Int) {
val a = "prop"
}
""".trimIndent(),
result = """
class Foo(bar: Int) {
val a = "prop"
}
""".trimIndent()
)
}
fun testSimpleClassConstructorReplacement() {
doTest(
searchPattern = "class '_ID('_PAR : '_TYPE)",
replacePattern = "class '_ID('_PAR : '_TYPE)",
match = """
class Foo(val bar : Int)
""".trimIndent(),
result = """
class Foo(val bar : Int)
""".trimIndent()
)
}
} | apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/caches/project/VfsCodeBlockModificationListener.kt | 3 | 2460 | // 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.caches.project
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.vfs.AsyncVfsEventsListener
import com.intellij.vfs.AsyncVfsEventsPostProcessor
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.util.runInReadActionWithWriteActionPriority
import org.jetbrains.kotlin.idea.util.application.isDispatchThread
class VfsCodeBlockModificationListener: StartupActivity.Background {
override fun runActivity(project: Project) {
val disposable = KotlinPluginDisposable.getInstance(project)
val ocbModificationListener = KotlinCodeBlockModificationListener.getInstance(project)
val vfsEventsListener = AsyncVfsEventsListener { events: List<VFileEvent> ->
val projectRelatedVfsFileChange = events.any { event ->
val file = event.takeIf { it.isFromRefresh || it is VFileContentChangeEvent }?.file ?: return@any false
return@any runInReadActionWithWriteActionPriority { RootKindFilter.projectSources.matches(project, file) } ?: true
}
if (projectRelatedVfsFileChange) {
if (isDispatchThread()) {
ocbModificationListener.incModificationCount()
} else {
// it is not fully correct - OCB has to be triggered ASAP as we detect VFS-change out of IJ that
// can affect Kotlin resolve, we can't do that properly before Kotlin 1.6.0
// see [org.jetbrains.kotlin.descriptors.InvalidModuleNotifier]
invokeLater {
ocbModificationListener.incModificationCount()
}
}
}
}
AsyncVfsEventsPostProcessor.getInstance().addListener(vfsEventsListener, disposable)
}
} | apache-2.0 |
ingokegel/intellij-community | platform/elevation/common/src/com/intellij/execution/process/mediator/daemon/DaemonLaunchOptions.kt | 12 | 4670 | // 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.execution.process.mediator.daemon
import com.intellij.execution.process.mediator.util.parseArgs
import java.nio.file.Path
import java.security.KeyFactory
import java.security.PublicKey
import java.security.spec.X509EncodedKeySpec
import java.util.*
import kotlin.system.exitProcess
data class DaemonLaunchOptions(
val trampoline: Boolean = false,
val daemonize: Boolean = false,
val leaderPid: Long? = null,
val machNamespaceUid: Int? = null,
val handshakeOption: HandshakeOption? = null,
val tokenEncryptionOption: TokenEncryptionOption? = null,
) {
interface CmdlineOption {
override fun toString(): String
}
// handling multiple handshake writers is too complicated w.r.t. resource management, and we never need it anyway
sealed class HandshakeOption(private val arg: String) : CmdlineOption {
override fun toString(): String = arg
object Stdout : HandshakeOption("--handshake-file=-")
class File(val path: Path) : HandshakeOption("--handshake-file=$path") {
constructor(s: String) : this(Path.of(s))
}
class Port(val port: Int) : HandshakeOption("--handshake-port=$port") {
constructor(s: String) : this(s.toInt())
}
}
class TokenEncryptionOption(val publicKey: PublicKey) {
constructor(s: String) : this(rsaPublicKeyFromBytes(Base64.getDecoder().decode(s)))
override fun toString(): String = "--token-encrypt-rsa=${Base64.getEncoder().encodeToString(publicKey.encoded)}"
companion object {
private fun rsaPublicKeyFromBytes(bytes: ByteArray) =
KeyFactory.getInstance("RSA").generatePublic(X509EncodedKeySpec(bytes))
}
}
fun asCmdlineArgs(): List<String> {
return listOf(
"--trampoline".takeIf { trampoline },
"--daemonize".takeIf { daemonize },
leaderPid?.let { "--leader-pid=$it" },
machNamespaceUid?.let { "--mach-namespace-uid=$it" },
handshakeOption,
tokenEncryptionOption,
).mapNotNull { it?.toString() }
}
override fun toString(): String {
return asCmdlineArgs().joinToString(" ")
}
companion object {
private fun printUsage(programName: String) {
System.err.println(
"Usage: $programName" +
" [ --trampoline ]" +
" [ --daemonize ]" +
" [ --leader-pid=pid ]" +
" [ --mach-namespace-uid=uid ]" +
" [ --handshake-file=file|- | --handshake-port=port ]" +
" [ --token-encrypt-rsa=public-key ]"
)
}
fun parseFromArgsOrDie(programName: String, args: Array<String>): DaemonLaunchOptions {
return try {
parseFromArgs(args)
}
catch (e: Exception) {
System.err.println(e.message)
printUsage(programName)
exitProcess(1)
}
}
private fun parseFromArgs(args: Array<String>): DaemonLaunchOptions {
var trampoline = false
var daemonize = false
var leaderPid: Long? = null
var machNamespaceUid: Int? = null
var handshakeOption: HandshakeOption? = null
var tokenEncryptionOption: TokenEncryptionOption? = null
for ((option, value) in parseArgs(args)) {
when (option) {
"--trampoline" -> trampoline = true
"--no-trampoline" -> trampoline = false
"--daemonize" -> daemonize = true
"--no-daemonize" -> daemonize = false
else -> requireNotNull(value) { "Missing '$option' value" }
}
value ?: continue
when (option) {
"--leader-pid" -> {
leaderPid = value.toLong()
}
"--mach-namespace-uid" -> {
machNamespaceUid = value.toInt()
}
"--handshake-file" -> {
handshakeOption =
if (value == "-") HandshakeOption.Stdout
else HandshakeOption.File(value)
}
"--handshake-port" -> {
handshakeOption = HandshakeOption.Port(value)
}
"--token-encrypt-rsa" -> {
tokenEncryptionOption = TokenEncryptionOption(value)
}
null -> throw IllegalArgumentException("Unrecognized positional argument '$value'")
else -> throw IllegalArgumentException("Unrecognized option '$option'")
}
}
return DaemonLaunchOptions(
trampoline = trampoline,
daemonize = daemonize,
leaderPid = leaderPid,
machNamespaceUid = machNamespaceUid,
handshakeOption = handshakeOption,
tokenEncryptionOption = tokenEncryptionOption,
)
}
}
}
| apache-2.0 |
androidstarters/androidstarters.com | templates/androidstarters-kotlin/app/src/main/java/io/mvpstarter/sample/features/detail/DetailMvpView.kt | 1 | 372 | package <%= appPackage %>.features.detail
import <%= appPackage %>.data.model.Pokemon
import <%= appPackage %>.data.model.Statistic
import <%= appPackage %>.features.base.MvpView
interface DetailMvpView : MvpView {
fun showPokemon(pokemon: Pokemon)
fun showStat(statistic: Statistic)
fun showProgress(show: Boolean)
fun showError(error: Throwable)
} | mit |
JavaEden/Orchid-Core | OrchidTest/src/test/kotlin/com/eden/orchid/impl/compilers/pebble/ContentTagTest.kt | 2 | 5386 | package com.eden.orchid.impl.compilers.pebble
import com.eden.orchid.api.compilers.TemplateTag
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.registration.IgnoreModule
import com.eden.orchid.api.registration.OrchidModule
import com.eden.orchid.impl.generators.HomepageGenerator
import com.eden.orchid.strikt.htmlBodyMatches
import com.eden.orchid.strikt.pageWasRendered
import com.eden.orchid.testhelpers.OrchidIntegrationTest
import com.eden.orchid.testhelpers.withGenerator
import com.eden.orchid.utilities.addToSet
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import strikt.api.expectThat
class ContentTagTest : OrchidIntegrationTest(ContentTagModule(), withGenerator<HomepageGenerator>()) {
@ParameterizedTest
@MethodSource("params")
fun testContentTags(input: String, expected: String) {
resource("homepage.peb", input.trim())
resource("templates/tags/hello.peb", "hello {{ tag.greeting }} {{ tag.content }} {{ tag.closing }}")
resource("templates/tags/althello.peb", "alt {{ tag.greeting }} {{ tag.content }} {{ tag.closing }}")
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
+expected.trim()
}
}
}
companion object {
@JvmStatic
fun params() = sequence<Arguments> {
// simple tag, no content
yield(Arguments.of(
"{% hello %}{% endhello %}",
"hello world"
))
yield(Arguments.of(
"{% hello 'sir' %}{% endhello %}",
"hello sir"
))
yield(Arguments.of(
"{% hello 'sir' 'and goodbye!' %}{% endhello %}",
"hello sir and goodbye!"
))
yield(Arguments.of(
"{% hello 'sir' closing='and goodbye!' %}{% endhello %}",
"hello sir and goodbye!"
))
yield(Arguments.of(
"{% hello greeting='sir' %}{% endhello %}",
"hello sir"
))
yield(Arguments.of(
"{% hello greeting='sir' closing=' and goodbye!' %}{% endhello %}",
"hello sir and goodbye!"
))
// simple tag, content with no filters
yield(Arguments.of(
"{% hello %}from all of us{% endhello %}",
"hello world from all of us"
))
yield(Arguments.of(
"{% hello 'sir' %}from all of us{% endhello %}",
"hello sir from all of us"
))
yield(Arguments.of(
"{% hello 'sir' 'and goodbye!' %}from all of us{% endhello %}",
"hello sir from all of us and goodbye!"
))
yield(Arguments.of(
"{% hello 'sir' closing='and goodbye!' %}from all of us{% endhello %}",
"hello sir from all of us and goodbye!"
))
yield(Arguments.of(
"{% hello greeting='sir' %}from all of us{% endhello %}",
"hello sir from all of us"
))
yield(Arguments.of(
"{% hello greeting='sir' closing='and goodbye!' %}from all of us{% endhello %}",
"hello sir from all of us and goodbye!"
))
// simple tag, content with filters
yield(Arguments.of(
"{% hello :: upper %}from all of us{% endhello %}",
"hello world FROM ALL OF US"
))
yield(Arguments.of(
"{% hello 'sir' :: upper %}from all of us{% endhello %}",
"hello sir FROM ALL OF US"
))
yield(Arguments.of(
"{% hello 'sir' 'and goodbye!' :: upper %}from all of us{% endhello %}",
"hello sir FROM ALL OF US and goodbye!"
))
yield(Arguments.of(
"{% hello 'sir' closing='and goodbye!' :: upper %}from all of us{% endhello %}",
"hello sir FROM ALL OF US and goodbye!"
))
yield(Arguments.of(
"{% hello greeting='sir' :: upper %}from all of us{% endhello %}",
"hello sir FROM ALL OF US"
))
yield(Arguments.of(
"{% hello greeting='sir' closing='and goodbye!' :: upper %}from all of us{% endhello %}",
"hello sir FROM ALL OF US and goodbye!"
))
yield(Arguments.of(
"{% hello greeting='sir' closing='and goodbye!' template='althello' :: upper %}from all of us{% endhello %}",
"alt sir FROM ALL OF US and goodbye!"
))
}.asIterable()
}
}
class ContentHelloTag : TemplateTag("hello", Type.Content, true) {
@Option
@StringDefault("world")
lateinit var greeting: String
@Option
lateinit var closing: String
override fun parameters() = arrayOf(::greeting.name, ::closing.name)
}
@IgnoreModule
private class ContentTagModule : OrchidModule() {
override fun configure() {
addToSet<TemplateTag, ContentHelloTag>()
}
}
| mit |
icela/FriceEngine | src/org/frice/platform/Platforms.kt | 1 | 698 | /**
* Run your codes under a specific platform
* @author ice1000
* @since v1.7.12
*/
@file:JvmName("Platforms")
package org.frice.platform
/** for Windowses */
var onWindows: Runnable? = null
/** for Mac OS X */
var onMac: Runnable? = null
/** for Linuxes */
var onLinux: Runnable? = null
/** for SunOS and Solaris */
var onSolaris: Runnable? = null
/** for FreeBSD */
var onBSD: Runnable? = null
var isOnWindows = false @JvmName(" ### windows") internal set
var isOnMac = false @JvmName(" ### mac") internal set
var isOnLinux = false @JvmName(" ### linux") internal set
var isOnSolaris = false @JvmName(" ### solaris") internal set
var isOnBSD = false @JvmName(" ### bsd") internal set
| agpl-3.0 |
nonylene/MackerelAgentAndroid | app/src/main/java/net/nonylene/mackerelagent/viewmodel/LogRecyclerItemViewModel.kt | 1 | 758 | package net.nonylene.mackerelagent.viewmodel
import android.databinding.ObservableField
import net.nonylene.mackerelagent.AgentLog
import net.nonylene.mackerelagent.R
import java.text.SimpleDateFormat
import java.util.*
private val DATE_FORMAT = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault())
class LogRecyclerItemViewModel {
val text: ObservableField<String> = ObservableField()
val dateText: ObservableField<String> = ObservableField()
val colorRes: ObservableField<Int> = ObservableField()
fun setAgentLog(agentLog: AgentLog) {
text.set(agentLog.text)
colorRes.set(if (agentLog.error) R.color.status_error else R.color.status_running)
dateText.set(DATE_FORMAT.format(agentLog.timeStamp))
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.