repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Szewek/Minecraft-Flux
src/main/java/szewek/mcflux/fluxable/PlayerEnergy.kt
1
2206
package szewek.mcflux.fluxable import net.minecraft.entity.player.EntityPlayer import net.minecraft.nbt.NBTBase import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.DamageSource import net.minecraft.util.EnumFacing import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.capabilities.ICapabilityProvider import net.minecraftforge.common.util.INBTSerializable import szewek.fl.FL import szewek.fl.energy.IEnergy import szewek.mcflux.fluxable.FluxableCapabilities.CAP_PE @Suppress("UNCHECKED_CAST") class PlayerEnergy internal constructor(private val player: EntityPlayer?) : IEnergy, ICapabilityProvider, INBTSerializable<NBTBase> { private var venergy: Long = 0 private var maxEnergy: Long = 0 private var lvl: Byte = 0 constructor() : this(null) fun updateLevel(): Byte { if (lvl.toInt() == 30) return -1 ++lvl maxEnergy = (100000 * lvl).toLong() return lvl } override fun hasCapability(cap: Capability<*>, f: EnumFacing?) = cap === CAP_PE || maxEnergy > 0 && cap === FL.ENERGY_CAP override fun <T> getCapability(cap: Capability<T>, f: EnumFacing?) = if (cap === CAP_PE || maxEnergy > 0 && cap === FL.ENERGY_CAP) this as T else null override fun outputEnergy(amount: Long, sim: Boolean): Long { if (amount == 0L) return 0 var r = venergy if (amount < r) r = amount if (!sim) venergy -= r return r } override fun canInputEnergy() = maxEnergy > 0 override fun canOutputEnergy() = maxEnergy > 0 override fun inputEnergy(amount: Long, sim: Boolean): Long { if (amount == 0L) return 0 if (maxEnergy == 0L) { player!!.attackEntityFrom(DamageSource.GENERIC, (amount / 100).toFloat()) return 0 } var r = maxEnergy - venergy if (amount < r) r = amount if (!sim) venergy += r return r } override fun getEnergy() = venergy override fun getEnergyCapacity() = maxEnergy override fun serializeNBT(): NBTBase { val nbt = NBTTagCompound() nbt.setByte("lvl", lvl) nbt.setLong("e", venergy) return nbt } override fun deserializeNBT(nbt: NBTBase) { if (nbt is NBTTagCompound) { val nbttc = nbt lvl = nbttc.getByte("lvl") venergy = nbttc.getLong("e") } } }
mit
141924189211e5619a9f0d3478f46e9a
24.651163
134
0.707616
3.373089
false
false
false
false
VoIPGRID/vialer-android
app/src/main/java/com/voipgrid/vialer/onboarding/Onboarder.kt
1
3563
package com.voipgrid.vialer.onboarding import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.View.INVISIBLE import android.view.View.VISIBLE import android.view.WindowManager import android.view.inputmethod.InputMethodManager import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import com.voipgrid.vialer.R import com.voipgrid.vialer.logging.Logger import com.voipgrid.vialer.onboarding.core.OnboardingState import com.voipgrid.vialer.onboarding.core.Step import com.voipgrid.vialer.voipgrid.PasswordResetWebActivity import kotlinx.android.synthetic.main.activity_onboarding.* import androidx.core.app.ComponentActivity.ExtraData import androidx.core.content.ContextCompat.getSystemService import com.voipgrid.vialer.logging.VialerBaseActivity import com.voipgrid.vialer.voipgrid.PasswordResetWebActivity.Companion.PASSWORD_EXTRA import com.voipgrid.vialer.voipgrid.PasswordResetWebActivity.Companion.USERNAME_EXTRA typealias PermissionCallback = () -> Unit abstract class Onboarder : VialerBaseActivity() { override val logger = Logger(this).forceRemoteLogging(true) private var permissionCallback: PermissionCallback? = null open val state: OnboardingState = OnboardingState() var isLoading: Boolean get() = progress.visibility == VISIBLE set(loading) { progress.visibility = if (loading) VISIBLE else INVISIBLE } abstract fun progress(callerStep: Step) abstract fun restart() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_onboarding) } /** * Request a permission and provide a block that will be called back when the * result is received. Only one callback can be active at any one time. * */ fun requestPermission(permission: String, callback: PermissionCallback) { logger.i("Requesting $permission") setCallBack(callback) ActivityCompat.requestPermissions(this, arrayOf(permission), 1) } fun setCallBack(callback: PermissionCallback) { permissionCallback = callback } /** * Invoke the permission callback when the user accepts/denies a permission. * */ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { logger.i("Received permission result, invoking callback") permissionCallback?.invoke() } /** * Whenever we receive an activity result, we want to invoke the permission callback * as this is used when requesting the app to be whitelisted. * */ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PasswordResetWebActivity.REQUEST_CODE) { finish() startActivity(Intent(this, OnboardingActivity::class.java).apply { putExtra(USERNAME_EXTRA, data?.getStringExtra(USERNAME_EXTRA)) putExtra(PASSWORD_EXTRA, data?.getStringExtra(PASSWORD_EXTRA)) }) return } logger.i("Received activity result, invoking callback") permissionCallback?.invoke() } companion object { fun start(activity: Activity) { activity.startActivity(Intent(activity, OnboardingActivity::class.java)) } } }
gpl-3.0
0c89b34c7108e881817d15ad5b758144
33.941176
119
0.727477
4.867486
false
false
false
false
RocketChat/Rocket.Chat.Android
draw/src/main/java/chat/rocket/android/draw/main/ui/DrawActivity.kt
2
8195
package chat.rocket.android.draw.main.ui import android.app.Activity import android.content.Intent import android.content.res.Resources import android.os.Bundle import android.view.View import android.widget.SeekBar import android.widget.Toast import androidx.core.content.res.ResourcesCompat import androidx.core.view.isVisible import chat.rocket.android.draw.R import chat.rocket.android.draw.main.presenter.DrawPresenter import chat.rocket.android.draw.main.presenter.DrawView import dagger.android.support.DaggerAppCompatActivity import kotlinx.android.synthetic.main.activity_drawing.* import kotlinx.android.synthetic.main.color_palette_view.* import javax.inject.Inject const val DRAWING_BYTE_ARRAY_EXTRA_DATA: String = "chat.rocket.android.DrawingByteArray" class DrawingActivity : DaggerAppCompatActivity(), DrawView { @Inject lateinit var presenter: DrawPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_drawing) setupListeners() setupDrawTools() colorSelector() setPaintAlpha() setPaintWidth() } override fun sendByteArray(byteArray: ByteArray) { setResult(Activity.RESULT_OK, Intent().putExtra(DRAWING_BYTE_ARRAY_EXTRA_DATA, byteArray)) finish() } override fun showWrongProcessingMessage() { Toast.makeText(this, getText(R.string.msg_wrong_processing_draw_image), Toast.LENGTH_SHORT) .show() } private fun setupListeners() { custom_draw_view.setOnTouchListener { view, event -> custom_draw_view.onTouch( event, draw_tools, ::toggleCompleteDrawTools ) } image_close_drawing.setOnClickListener { finish() } image_send_drawing.setOnClickListener { presenter.processDrawingImage(custom_draw_view.getBitmap()) } } private fun setupDrawTools() { image_draw_eraser.setOnLongClickListener { custom_draw_view.clearCanvas() return@setOnLongClickListener true } image_draw_eraser.setOnClickListener { custom_draw_view.setColor( ResourcesCompat.getColor(resources, R.color.color_white, null) ) toggleDrawTools(draw_tools, false) } image_draw_width.setOnClickListener { if (draw_tools.translationY == (56).toPx) { toggleDrawTools(draw_tools, true) } else if (draw_tools.translationY == (0).toPx && seekBar_width.isVisible) { toggleDrawTools(draw_tools, false) } seekBar_width.isVisible = true seekBar_opacity.isVisible = false draw_color_palette.isVisible = false } image_draw_opacity.setOnClickListener { if (draw_tools.translationY == (56).toPx) { toggleDrawTools(draw_tools, true) } else if (draw_tools.translationY == (0).toPx && seekBar_opacity.isVisible) { toggleDrawTools(draw_tools, false) } seekBar_width.isVisible = false seekBar_opacity.isVisible = true draw_color_palette.isVisible = false } image_draw_color.setOnClickListener { if (draw_tools.translationY == (56).toPx) { toggleDrawTools(draw_tools, true) } else if (draw_tools.translationY == (0).toPx && draw_color_palette.isVisible) { toggleDrawTools(draw_tools, false) } seekBar_width.isVisible = false seekBar_opacity.isVisible = false draw_color_palette.isVisible = true } image_draw_undo.setOnClickListener { custom_draw_view.undo() toggleDrawTools(draw_tools, false) } image_draw_redo.setOnClickListener { custom_draw_view.redo() toggleDrawTools(draw_tools, false) } } private fun toggleDrawTools(view: View, showView: Boolean = true) { if (showView) { view.animate().translationY((0).toPx) } else { view.animate().translationY((56).toPx) } } private fun toggleCompleteDrawTools(view: View, showView: Boolean = true) { if (view.translationY == (112).toPx && showView) { toggleDrawTools(draw_tools, false) } else { view.animate().translationY((112).toPx) } } private fun colorSelector() { image_color_black.setOnClickListener { custom_draw_view.setColor( ResourcesCompat.getColor(resources, R.color.color_black, null) ) scaleColorView(image_color_black) } image_color_red.setOnClickListener { custom_draw_view.setColor( ResourcesCompat.getColor(resources, R.color.color_red, null) ) scaleColorView(image_color_red) } image_color_yellow.setOnClickListener { custom_draw_view.setColor( ResourcesCompat.getColor( resources, R.color.color_yellow, null ) ) scaleColorView(image_color_yellow) } image_color_green.setOnClickListener { custom_draw_view.setColor( ResourcesCompat.getColor( resources, R.color.color_green, null ) ) scaleColorView(image_color_green) } image_color_blue.setOnClickListener { custom_draw_view.setColor( ResourcesCompat.getColor(resources, R.color.color_blue, null) ) scaleColorView(image_color_blue) } image_color_pink.setOnClickListener { custom_draw_view.setColor( ResourcesCompat.getColor( resources, R.color.color_pink, null ) ) scaleColorView(image_color_pink) } image_color_brown.setOnClickListener { custom_draw_view.setColor( ResourcesCompat.getColor( resources, R.color.color_brown, null ) ) scaleColorView(image_color_brown) } } private fun scaleColorView(view: View) { //reset scale of all views image_color_black.scaleX = 1f image_color_black.scaleY = 1f image_color_red.scaleX = 1f image_color_red.scaleY = 1f image_color_yellow.scaleX = 1f image_color_yellow.scaleY = 1f image_color_green.scaleX = 1f image_color_green.scaleY = 1f image_color_blue.scaleX = 1f image_color_blue.scaleY = 1f image_color_pink.scaleX = 1f image_color_pink.scaleY = 1f image_color_brown.scaleX = 1f image_color_brown.scaleY = 1f //set scale of selected view view.scaleX = 1.5f view.scaleY = 1.5f } private fun setPaintWidth() { seekBar_width.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { custom_draw_view.setStrokeWidth(progress.toFloat()) } override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) {} }) } private fun setPaintAlpha() { seekBar_opacity.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { custom_draw_view.setAlpha(progress) } override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) {} }) } private val Int.toPx: Float get() = (this * Resources.getSystem().displayMetrics.density) }
mit
cd24318264218da77fb397eec7c01f46
31.011719
99
0.597437
4.666856
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/inviteusers/ui/InviteUsersFragment.kt
2
7590
package chat.rocket.android.inviteusers.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import chat.rocket.android.R import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.chatroom.ui.ChatRoomActivity import chat.rocket.android.inviteusers.presentation.InviteUsersPresenter import chat.rocket.android.inviteusers.presentation.InviteUsersView import chat.rocket.android.members.adapter.MembersAdapter import chat.rocket.android.members.uimodel.MemberUiModel import chat.rocket.android.util.extension.asObservable import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.ui import com.google.android.material.chip.Chip import dagger.android.support.AndroidSupportInjection import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.fragment_invite_users.* import java.util.concurrent.TimeUnit import javax.inject.Inject fun newInstance(chatRoomId: String): Fragment = InviteUsersFragment().apply { arguments = Bundle(1).apply { putString(BUNDLE_CHAT_ROOM_ID, chatRoomId) } } internal const val TAG_INVITE_USERS_FRAGMENT = "InviteUsersFragment" private const val BUNDLE_CHAT_ROOM_ID = "chat_room_id" class InviteUsersFragment : Fragment(), InviteUsersView { @Inject lateinit var presenter: InviteUsersPresenter @Inject lateinit var analyticsManager: AnalyticsManager private val compositeDisposable = CompositeDisposable() private val adapter: MembersAdapter = MembersAdapter { processSelectedMember(it) } private lateinit var chatRoomId: String private var memberList = arrayListOf<MemberUiModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) arguments?.run { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "") } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_invite_users) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolBar() setupListeners() setupRecyclerView() subscribeEditTexts() analyticsManager.logScreenView(ScreenViewEvent.InviteUsers) } override fun onDestroyView() { super.onDestroyView() unsubscribeEditTexts() } override fun showLoading() { view_loading?.isVisible = true } override fun hideLoading() { view_loading?.isVisible = false } override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } override fun showGenericErrorMessage() { showMessage(getString(R.string.msg_generic_error)) } override fun showUserSuggestion(dataSet: List<MemberUiModel>) { adapter.clearData() adapter.prependData(dataSet) text_member_not_found?.isVisible = false recycler_view?.isVisible = true } override fun showNoUserSuggestion() { recycler_view?.isVisible = false text_member_not_found?.isVisible = true } override fun showSuggestionViewInProgress() { recycler_view?.isVisible = false text_member_not_found?.isVisible = false showLoading() } override fun hideSuggestionViewInProgress() { hideLoading() } override fun usersInvitedSuccessfully() { memberList.clear() activity?.onBackPressed() showMessage(getString(R.string.mgs_users_invited_successfully)) } override fun enableUserInput() { text_invite_users.isEnabled = true } override fun disableUserInput() { text_invite_users.isEnabled = false } private fun setupToolBar() { (activity as ChatRoomActivity).setupToolbarTitle((getString(R.string.msg_invite_users))) } private fun setupRecyclerView() { ui { recycler_view.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) recycler_view.addItemDecoration( DividerItemDecoration(it, DividerItemDecoration.HORIZONTAL) ) recycler_view.adapter = adapter } } private fun setupListeners() { button_invite_user.setOnClickListener { if (memberList.isNotEmpty()) { presenter.inviteUsers(chatRoomId, memberList) } else { showMessage(R.string.mgs_choose_at_least_one_user) } } } private fun subscribeEditTexts() { val inviteMembersDisposable = text_invite_users.asObservable() .debounce(300, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .filter { t -> t.isNotBlank() } .subscribe { if (it.length >= 3) { presenter.searchUser(it.toString()) } } compositeDisposable.addAll(inviteMembersDisposable) } private fun unsubscribeEditTexts() = compositeDisposable.dispose() private fun processSelectedMember(member: MemberUiModel) { if (memberList.any { it.username == member.username }) { showMessage(getString(R.string.msg_member_already_added)) } else { text_invite_users.setText("") addMember(member) addChip(member) chip_group_member.isVisible = true processBackgroundOfInviteUsersButton() } } private fun addMember(member: MemberUiModel) { memberList.add(member) } private fun removeMember(username: String) { memberList.remove(memberList.find { it.username == username }) } private fun addChip(member: MemberUiModel) { val chip = Chip(context) chip.text = member.username chip.isCloseIconVisible = true chip.setChipBackgroundColorResource(R.color.icon_grey) setupChipOnCloseIconClickListener(chip) chip_group_member.addView(chip) } private fun setupChipOnCloseIconClickListener(chip: Chip) { chip.setOnCloseIconClickListener { removeChip(it) removeMember((it as Chip).text.toString()) // whenever we remove a chip we should process the chip group visibility. processChipGroupVisibility() processBackgroundOfInviteUsersButton() } } private fun removeChip(chip: View) { chip_group_member.removeView(chip) } private fun processChipGroupVisibility() { chip_group_member.isVisible = memberList.isNotEmpty() } private fun processBackgroundOfInviteUsersButton() { if (memberList.isEmpty()) { text_invite_users.alpha = 0.4F } else { text_invite_users.alpha = 1F } } }
mit
10c3ef59e7b2c840995f2d627addae6e
32.148472
103
0.68419
4.809886
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/KotlinBuildScriptIntegrationTest.kt
3
7867
package org.gradle.kotlin.dsl.integration import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest import org.gradle.kotlin.dsl.fixtures.containsMultiLineString import org.gradle.test.fixtures.file.LeaksFileHandles import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import java.io.StringWriter class KotlinBuildScriptIntegrationTest : AbstractKotlinIntegrationTest() { @Test fun `can apply plugin using ObjectConfigurationAction syntax`() { withSettings( """ rootProject.name = "foo" include("bar") """ ) withBuildScript( """ open class ProjectPlugin : Plugin<Project> { override fun apply(target: Project) { target.task("run") { val projectName = target.name doLast { println(projectName + ":42") } } } } apply { plugin<ProjectPlugin>() } subprojects { apply { plugin<ProjectPlugin>() } } """ ) assertThat( build("run", "-q").output, allOf( containsString("foo:42"), containsString("bar:42") ) ) } @Test fun `Project receiver is undecorated`() { withBuildScript( """ fun Project.implicitReceiver() = this require(implicitReceiver() === rootProject) """ ) build("help") } @Test fun `scripts larger than 64KB are supported`() { withBuildScriptLargerThan64KB( """ tasks.register("run") { doLast { println("*42*") } } """ ) assertThat( build("run").output, containsString("*42*") ) } private fun withBuildScriptLargerThan64KB(suffix: String) = withBuildScript( StringWriter().run { var bytesWritten = 0 var i = 0 while (bytesWritten < 64 * 1024) { val stmt = "val v$i = $i\n" write(stmt) i += 1 bytesWritten += stmt.toByteArray().size } write(suffix) toString() } ) @Test fun `can use Kotlin 1 dot 3 language features`() { withBuildScript( """ task("test") { doLast { // Coroutines are no longer experimental val coroutine = sequence { // Unsigned integer types yield(42UL) } // Capturing when when (val value = coroutine.first()) { 42UL -> print("42!") else -> throw IllegalStateException() } } } """ ) assertThat( build("test", "-q").output, equalTo("42!") ) } @Test fun `can use Kotlin 1 dot 4 language features`() { withBuildScript( """ task("test") { doLast { val myList = listOf( "foo", "bar", // trailing comma ) print(myList) } } """ ) assertThat( build("test", "-q").output, equalTo("[foo, bar]") ) } @Test fun `use of the plugins block on nested project block fails with reasonable error message`() { withBuildScript( """ plugins { id("base") } allprojects { plugins { id("java-base") } } """ ) buildAndFail("help").apply { assertThat(error, containsString("The plugins {} block must not be used here")) } } @Test fun `non top-level use of the plugins block fails with reasonable error message`() { withBuildScript( """ plugins { id("java-base") } dependencies { plugins { id("java") } } """ ) buildAndFail("help").apply { assertThat(error, containsString("The plugins {} block must not be used here")) } } @Test @LeaksFileHandles("Kotlin Compiler Daemon working directory") fun `accepts lambda as SAM argument to Kotlin function`() { withKotlinBuildSrc() withFile( "buildSrc/src/main/kotlin/my.kt", """ package my fun <T> applyActionTo(value: T, action: org.gradle.api.Action<T>) = action.execute(value) fun <T> create(name: String, factory: org.gradle.api.NamedDomainObjectFactory<T>): T = factory.create(name) fun <T : Any> create(type: kotlin.reflect.KClass<T>, factory: org.gradle.api.NamedDomainObjectFactory<T>): T = factory.create(type.simpleName!!) """ ) withBuildScript( """ import my.* task("test") { doLast { // Explicit SAM conversion println(create("foo", NamedDomainObjectFactory<String> { it.toUpperCase() })) // Explicit SAM conversion with generic type argument inference println(create<String>("bar", NamedDomainObjectFactory { it.toUpperCase() })) // Implicit SAM conversion println(create<String>("baz") { it.toUpperCase() }) println(create(String::class) { it.toUpperCase() }) println(create(String::class, { name: String -> name.toUpperCase() })) // Implicit SAM with receiver conversion applyActionTo("action") { println(toUpperCase()) } } } """.trimIndent() ) assertThat( build("test", "-q").output, containsMultiLineString( """ FOO BAR BAZ STRING STRING ACTION """ ) ) } @Test fun `can create fileTree from map for backward compatibility`() { val fileTreeFromMap = """ fileTree(mapOf("dir" to ".", "include" to listOf("*.txt"))) .joinToString { it.name } """ withFile("foo.txt") val initScript = withFile( "init.gradle.kts", """ println("INIT: " + $fileTreeFromMap) """ ) withSettings( """ println("SETTINGS: " + $fileTreeFromMap) """ ) withBuildScript( """ task("test") { val ft = $fileTreeFromMap doLast { println("PROJECT: " + ft) } } """ ) assertThat( build("test", "-q", "-I", initScript.absolutePath).output.trim(), equalTo( """ INIT: foo.txt SETTINGS: foo.txt PROJECT: foo.txt """.trimIndent() ) ) } }
apache-2.0
b0bc4236e19ec4e0ae3dc4e381838a3e
24.542208
156
0.443879
5.635387
false
true
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/datatypes/DataTypes.kt
1
2538
package edu.kit.iti.formal.automation.datatypes import java.math.BigInteger import java.util.* /** * * DataTypes class. * * @author Alexander Weigl (25.06.2014) * @version 1 */ object DataTypes { val DEFAULT = BigInteger.ZERO internal var map = HashMap<String, AnyDt>() val dataTypeNames: Set<String> get() = map.keys val integers: Array<AnyInt> get() = signedIntegers + unSignedIntegers val signedIntegers: Array<AnyInt> get() = arrayOf(INT, SINT, DINT, LINT) val unSignedIntegers: Array<AnyInt> get() = arrayOf(UINT, USINT, UDINT, ULINT) init { add(AnyBit.BOOL) add(AnyBit.LWORD) add(AnyBit.WORD) add(AnyBit.DWORD) add(SINT) add(INT) add(DINT) add(LINT) add(USINT) add(UINT) add(UDINT) add(ULINT) add(AnyReal.LREAL) add(AnyReal.REAL) add(IECString.STRING) add(IECString.WSTRING) add(TimeType.TIME_TYPE) add(AnyDate.DATE) add(AnyDate.DATE_AND_TIME) add(AnyDate.TIME_OF_DAY) map["TOD"] = AnyDate.TIME_OF_DAY map["DT"] = AnyDate.DATE_AND_TIME map["T"] = TimeType.TIME_TYPE map["VOID"] = ReferenceDt.ANY_REF } internal fun add(any: AnyDt) { map[any.name] = any map[any.name.replace("_", "")] = any } fun getDataType(name: String): AnyDt? { return map[name] } /* fun getIntegers(anyIntClass: Class<out AnyInt>): List<AnyInt> { val list = get(anyIntClass) list.sort(Comparator.comparingInt<AnyInt> { o -> o.bitLength }) return list } */ private operator fun <T : AnyDt> get(anyClazz: Class<T>) = map.values.filter { anyClazz.isAssignableFrom(it.javaClass) } @JvmOverloads fun findSuitableInteger(s: BigInteger, signed: Boolean): AnyInt { return findSuitableInteger(s, if (signed) DataTypes.signedIntegers else DataTypes.unSignedIntegers ) } @JvmOverloads fun findSuitableInteger(s: BigInteger, integerTypes: Array<AnyInt> = integers): AnyInt { if (s == BigInteger.ZERO) return INT for (anyInt in integerTypes) { if (s.compareTo(anyInt.upperBound) < 0 && anyInt.lowerBound.compareTo(s) < 0) { return anyInt } } throw IllegalStateException("integer literal too big with : $s") } }
gpl-3.0
b5a64fa5f5446a13e185d5019a7b82c0
23.403846
92
0.57565
3.748892
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/scene3d/Torus.kt
1
4297
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.scene3d import com.almasb.fxgl.core.math.FXGLMath.* import javafx.scene.shape.Mesh import javafx.scene.shape.TriangleMesh /** * * @author Almas Baimagambetov ([email protected]) */ class Torus @JvmOverloads constructor( radius: Double = 0.6, tubeRadius: Double = radius * 2.0 / 3.0, numDivisions: Int = DEFAULT_NUM_DIVISIONS ) : CustomShape3D() { private val radiusProp = newDoubleProperty(radius) private val tubeRadiusProp = newDoubleProperty(tubeRadius) private val numDivisionsProp = newIntProperty(if (numDivisions < 3) 3 else numDivisions) var radius: Double get() = radiusProp.value set(value) { radiusProp.value = value } var tubeRadius: Double get() = tubeRadiusProp.value set(value) { tubeRadiusProp.value = value } var numDivisions: Int get() = numDivisionsProp.value set(value) { numDivisionsProp.value = value } fun radiusProperty() = radiusProp fun tubeRadiusProperty() = tubeRadiusProp fun numDivisionsProperty() = numDivisionsProp init { updateMesh() } // adapted from https://github.com/FXyz/FXyz/blob/master/FXyz-Core/src/main/java/org/fxyz3d/shapes/primitives/TorusMesh.java override fun createMesh(): Mesh { val radiusDivisions = numDivisions val tubeDivisions = numDivisions val R = radius.toFloat() val tR = tubeRadius.toFloat() val tubeStartAngle = 0f val xOffset = 0f val yOffset = 0f val zOffset = 1f val numVerts = tubeDivisions * radiusDivisions val faceCount = numVerts * 2 val points = FloatArray(numVerts * 3) val tPoints = FloatArray(numVerts * 2) val faces = IntArray(faceCount * 6) var pPos = 0 var tPos = 0 val tubeFraction = 1.0f / tubeDivisions val radiusFraction = 1.0f / radiusDivisions // create points // create tPoints for (tubeIndex in 0 until tubeDivisions) { val radian = tubeStartAngle + tubeFraction * tubeIndex * PI2 for (radiusIndex in 0 until radiusDivisions) { val localRadian = radiusFraction * radiusIndex * PI2 points[pPos + 0] = (R + tR * cosF(radian)) * (cosF(localRadian) + xOffset) points[pPos + 1] = (R + tR * cosF(radian)) * (sinF(localRadian) + yOffset) points[pPos + 2] = tR * sinF(radian) * zOffset pPos += 3 val r = if (radiusIndex < tubeDivisions) tubeFraction * radiusIndex * PI2 else 0.0 tPoints[tPos + 0] = sinF(r) * 0.5f + 0.5f tPoints[tPos + 1] = cosF(r) * 0.5f + 0.5f tPos += 2 } } var fIndex = 0 //create faces for (point in 0 until tubeDivisions) { for (crossSection in 0 until radiusDivisions) { val p0 = point * radiusDivisions + crossSection var p1 = if (p0 >= 0) p0 + 1 else p0 - radiusDivisions p1 = if (p1 % radiusDivisions != 0) p0 + 1 else p0 + 1 - radiusDivisions val p0r = p0 + radiusDivisions val p2 = if (p0r < numVerts) p0r else p0r - numVerts var p3 = if (p2 < numVerts - 1) p2 + 1 else p2 + 1 - numVerts p3 = if (p3 % radiusDivisions != 0) p2 + 1 else p2 + 1 - radiusDivisions faces[fIndex + 0] = p2 faces[fIndex + 1] = p3 faces[fIndex + 2] = p0 faces[fIndex + 3] = p2 faces[fIndex + 4] = p1 faces[fIndex + 5] = p0 fIndex += 6 faces[fIndex + 0] = p2 faces[fIndex + 1] = p3 faces[fIndex + 2] = p1 faces[fIndex + 3] = p0 faces[fIndex + 4] = p3 faces[fIndex + 5] = p1 fIndex += 6 } } val mesh = TriangleMesh() mesh.points.setAll(*points) mesh.texCoords.setAll(*tPoints) mesh.faces.setAll(*faces) return mesh } }
mit
87c2a6abbcb93ea3f611e83e277807d1
32.317829
128
0.56202
3.635364
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-skills-bukkit/src/main/kotlin/com/rpkit/skills/bukkit/listener/PlayerQuitListener.kt
1
1538
package com.rpkit.skills.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import com.rpkit.skills.bukkit.skills.RPKSkillService import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerQuitEvent class PlayerQuitListener : Listener { @EventHandler fun onPlayerQuit(event: PlayerQuitEvent) { val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return val skillService = Services[RPKSkillService::class.java] ?: return minecraftProfileService.getMinecraftProfile(event.player).thenAccept getMinecraftProfile@{ minecraftProfile -> if (minecraftProfile == null) return@getMinecraftProfile characterService.getActiveCharacter(minecraftProfile).thenAccept getCharacter@{ character -> if (character == null) return@getCharacter // If a player relogs quickly, then by the time the data has been retrieved, the player is sometimes back // online. We only want to unload data if the player is offline. if (!minecraftProfile.isOnline) { skillService.unloadSkillBindings(character) skillService.unloadSkillCooldowns(character) } } } } }
apache-2.0
b61dd22bf47551f9f3599efbbe1ec099
47.09375
121
0.719116
5.377622
false
false
false
false
lvtanxi/TanxiNote
app/src/main/java/com/lv/note/base/BaseTabLayoutActivity.kt
1
1359
package com.lv.note.base import android.support.design.widget.TabLayout import android.support.v4.view.ViewPager import com.lv.note.R import com.lv.note.adapter.LBaseFragmentAdapter import com.lv.test.BaseActivity /** * User: 吕勇 * Date: 2016-05-09 * Time: 14:15 * Description:公用TabLayout的基类 */ abstract class BaseTabLayoutActivity : BaseActivity() { protected var mTabLayout: TabLayout? = null protected var mViewPager: ViewPager? = null protected var mTitles: Array<String>? = null protected var mFragmentAdapter: LBaseFragmentAdapter? = null override fun initViews() { mTabLayout = fdb(R.id.common_tab_layout); mViewPager = fdb(R.id.common_view_pager); } override fun initData() { addTbs() mFragmentAdapter?.let { mViewPager?.adapter = mFragmentAdapter mTabLayout?.setupWithViewPager(mViewPager) mTabLayout?.setTabsFromPagerAdapter(mFragmentAdapter) } } protected fun addTbs() { mTitles?.let { for (title in mTitles!!) { mTabLayout!!.addTab(mTabLayout!!.newTab().setText(title)) } } } override fun onDestroy() { mTabLayout = null mViewPager = null mTitles = null mFragmentAdapter = null super.onDestroy() } }
apache-2.0
986537254ed8b11b04e9496f397f8fb5
24.377358
73
0.640892
4.216301
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/trans/ali/AliTranslator.kt
1
8750
package cn.yiiguxing.plugin.translate.trans.ali import cn.yiiguxing.plugin.translate.message import cn.yiiguxing.plugin.translate.trans.* import cn.yiiguxing.plugin.translate.ui.settings.TranslationEngine.ALI import cn.yiiguxing.plugin.translate.util.* import com.google.gson.Gson import com.google.gson.annotations.SerializedName import com.intellij.openapi.diagnostic.Logger import org.jsoup.nodes.Document import java.net.URL import java.text.SimpleDateFormat import java.util.* import javax.swing.Icon /** * Ali translator */ // Product description: https://www.aliyun.com/product/ai/base_alimt object AliTranslator : AbstractTranslator(), DocumentationTranslator { private const val ALI_TRANSLATE_API_URL = "https://mt.aliyuncs.com/api/translate/web/general" private const val ALI_TRANSLATE_PRODUCT_URL = "https://www.aliyun.com/product/ai/base_alimt" private val SUPPORTED_LANGUAGES: List<Lang> = listOf( Lang.CHINESE, Lang.CHINESE_TRADITIONAL, Lang.ENGLISH, Lang.JAPANESE, Lang.KOREAN, Lang.FRENCH, Lang.SPANISH, Lang.ITALIAN, Lang.GERMAN, Lang.TURKISH, Lang.RUSSIAN, Lang.PORTUGUESE, Lang.VIETNAMESE, Lang.INDONESIAN, Lang.THAI, Lang.MALAY, Lang.ARABIC, Lang.HINDI ) private val SUPPORTED_TARGET_LANGUAGES: List<Lang> = listOf( Lang.CHINESE, Lang.ENGLISH, Lang.JAPANESE, Lang.KOREAN, Lang.FRENCH, Lang.SPANISH, Lang.ITALIAN, Lang.GERMAN, Lang.TURKISH, Lang.RUSSIAN, Lang.PORTUGUESE, Lang.VIETNAMESE, Lang.INDONESIAN, Lang.THAI, Lang.MALAY ) private val logger: Logger = Logger.getInstance(AliTranslator::class.java) override val id: String = ALI.id override val name: String = ALI.translatorName override val icon: Icon = ALI.icon override val intervalLimit: Int = ALI.intervalLimit override val contentLengthLimit: Int = ALI.contentLengthLimit override val primaryLanguage: Lang get() = ALI.primaryLanguage override val supportedSourceLanguages: List<Lang> = SUPPORTED_LANGUAGES .toMutableList() .apply { add(0, Lang.AUTO) } override val supportedTargetLanguages: List<Lang> = SUPPORTED_TARGET_LANGUAGES override fun checkConfiguration(force: Boolean): Boolean { if (force || Settings.aliTranslateSettings.let { it.appId.isEmpty() || it.getAppKey().isEmpty() }) { return ALI.showConfigurationDialog() } return true } override fun doTranslate(text: String, srcLang: Lang, targetLang: Lang): Translation { return SimpleTranslateClient( this, { _, _, _ -> call(text, srcLang, targetLang, false) }, AliTranslator::parseTranslation ).execute(text, srcLang, targetLang) } override fun translateDocumentation(documentation: Document, srcLang: Lang, targetLang: Lang): Document { return checkError { val body = documentation.body() val content = body.html().trim() if (content.isBlank()) { return documentation } checkContentLength(content, contentLengthLimit) val client = SimpleTranslateClient( this, { _, _, _ -> call(content, srcLang, targetLang, true) }, AliTranslator::parseTranslation ) val translation = with(client) { updateCacheKey { it.update("DOCUMENTATION".toByteArray()) } execute(content, srcLang, targetLang) } body.html(translation.translation ?: "") documentation } } /** * 序列化json模型 */ @Suppress("MemberVisibilityCanBePrivate") data class AliTranslationRequest constructor( @SerializedName("SourceText") val sourceText: String, @SerializedName("SourceLanguage") val sourceLanguage: String, @SerializedName("TargetLanguage") val targetLanguage: String, @SerializedName("FormatType") val formatType: String = "text", @SerializedName("Scene") val scene: String = "general" ) private fun call(text: String, srcLang: Lang, targetLang: Lang, isDocumentation: Boolean): String { val formatType = if (isDocumentation) "html" else "text" val request = AliTranslationRequest(text, srcLang.aliLanguageCode, targetLang.aliLanguageCode, formatType) return sendHttpRequest(request) } private fun sendHttpRequest(request: Any): String { val url = ALI_TRANSLATE_API_URL val body = Gson().toJson(request) val realUrl = URL(url) val accept = "application/json" val contentType = "application/json; charset=utf-8" val date: String = toGMTString(Date()) val bodyMd5: String = body.md5Base64() val uuid = UUID.randomUUID().toString() val version = "2019-01-02" val dataToSign = """ POST $accept $bodyMd5 $contentType $date x-acs-signature-method:HMAC-SHA1 x-acs-signature-nonce:$uuid x-acs-version:$version ${realUrl.file} """.trimIndent() logger.i("Data to sign: $dataToSign") val settings = Settings.aliTranslateSettings return Http.post(url, contentType, body) { tuner { conn -> conn.setRequestProperty("Accept", accept) conn.setRequestProperty("Content-MD5", bodyMd5) conn.setRequestProperty("Date", date) conn.setRequestProperty("Host", realUrl.host) settings.getAppKey().takeIf { it.isNotEmpty() }?.let { key -> conn.setRequestProperty("Authorization", "acs ${settings.appId}:${dataToSign.hmacSha1(key)}") } conn.setRequestProperty("x-acs-signature-nonce", uuid) conn.setRequestProperty("x-acs-signature-method", "HMAC-SHA1") conn.setRequestProperty("x-acs-version", version) } } } class AliTranslationResultException(code: Int, val errorMessage: String?) : TranslationResultException(code) { override fun getLocalizedMessage(): String { return "$message[$errorMessage]" } } private fun parseTranslation( translation: String, original: String, srcLang: Lang, targetLang: Lang ): Translation { logger.i("Translate result: $translation") if (translation.isBlank()) { return Translation(original, original, srcLang, targetLang, listOf(srcLang)) } return Gson().fromJson(translation, AliTranslation::class.java).apply { query = original src = srcLang target = targetLang if (!isSuccessful) { throw AliTranslationResultException(intCode, errorMessage) } }.toTranslation() } override fun createErrorInfo(throwable: Throwable): ErrorInfo? { val errorMessage = when (throwable) { is AliTranslationResultException -> when (throwable.code) { 10001 -> message("error.request.timeout") 10002 -> message("error.systemError") 10003 -> message("error.bad.request") 10004 -> message("error.missingParameter") 10005 -> message("error.language.unsupported") 10006 -> message("error.ali.language.detecting.failed") 10007 -> message("error.systemError") 10008 -> message("error.text.too.long") 10009 -> message("error.ali.permission.denied") 10010 -> return ErrorInfo( message("error.service.is.down"), ErrorInfo.browseUrlAction(message("error.service.is.down.action.name"), ALI_TRANSLATE_PRODUCT_URL) ) 10011, 10012 -> message("error.systemError") 10013 -> message("error.account.has.run.out.of.balance") else -> message("error.unknown") + "[${throwable.code}] ${throwable.errorMessage}" } else -> return super.createErrorInfo(throwable) } return ErrorInfo(errorMessage) } private fun toGMTString(date: Date): String { val df = SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.US) df.timeZone = SimpleTimeZone(0, "GMT") return df.format(date) } }
mit
0758dcee5070491fd61f066bc8ee97e8
33.007782
118
0.605835
4.549714
false
false
false
false
alexnuts/kiwi
kiwi/src/main/java/com/kiwi/pipes/Pipes.kt
1
3770
package com.kiwi.pipes /** * Created by alex on 07.07.16. */ interface Pipe<K, V> { fun subscribe(key: K, callback: (K, V) -> Unit) fun unsubscribe(key: K, callback: (K, V) -> Unit) fun onData(key: K, data: V) } internal class PipeImpl<K, V>( private val holder: PipeHolder<K, V> = ListPipeHolder<K, V>()) : Pipe<K, V> { override fun onData(key: K, data: V) = holder.getCallbacks(key).forEach { it.invoke(key, data) } override fun subscribe(key: K, callback: (K, V) -> Unit) = holder.addCallback(key, callback) override fun unsubscribe(key: K, callback: (K, V) -> Unit) = holder.removeCallback(key, callback) } interface CRUDPipes<V, E> { fun subscribeCreate(key: String, callback: (String, V) -> Unit) fun unsubscribeCreate(key: String, callback: (String, V) -> Unit) fun subscribeUpdate(key: String, callback: (String, V) -> Unit) fun unsubscribeUpdate(key: String, callback: (String, V) -> Unit) fun subscribeDelete(key: String, callback: (String, V) -> Unit) fun unsubscribeDelete(key: String, callback: (String, V) -> Unit) fun subscribeRead(key: String, callback: (String, V) -> Unit) fun unsubscribeRead(key: String, callback: (String, V) -> Unit) fun subscribeError(key: String, callback: (String, E) -> Unit) fun unsubscribeError(key: String, callback: (String, E) -> Unit) fun onRead(key: String, value: V) fun onCreate(key: String, value: V) fun onUpdate(key: String, value: V) fun onDelete(key: String, value: V) fun onError(key: String, value: E) } private class CRUPPipesImpl<V, E>( private val readPipe: Pipe<String, V> = PipeImpl() , private val createPipe: Pipe<String, V> = PipeImpl() , private val updatePipe: Pipe<String, V> = PipeImpl() , private val deletePipe: Pipe<String, V> = PipeImpl() , private val errorPipe: Pipe<String, E> = PipeImpl() ) : CRUDPipes<V, E> { override fun onRead(key: String, value: V) = readPipe.onData(key, value) override fun onCreate(key: String, value: V) = createPipe.onData(key, value) override fun onUpdate(key: String, value: V) = updatePipe.onData(key, value) override fun onDelete(key: String, value: V) = deletePipe.onData(key, value) override fun onError(key: String, value: E) = errorPipe.onData(key, value) override fun subscribeCreate(key: String, callback: (String, V) -> Unit) = createPipe.subscribe(key, callback) override fun subscribeUpdate(key: String, callback: (String, V) -> Unit) = updatePipe.subscribe(key, callback) override fun subscribeDelete(key: String, callback: (String, V) -> Unit) = deletePipe.subscribe(key, callback) override fun subscribeRead(key: String, callback: (String, V) -> Unit) = readPipe.subscribe(key, callback) override fun subscribeError(key: String, callback: (String, E) -> Unit) = errorPipe.subscribe(key, callback) override fun unsubscribeCreate(key: String, callback: (String, V) -> Unit) = createPipe.unsubscribe(key, callback) override fun unsubscribeUpdate(key: String, callback: (String, V) -> Unit) = updatePipe.unsubscribe(key, callback) override fun unsubscribeDelete(key: String, callback: (String, V) -> Unit) = deletePipe.unsubscribe(key, callback) override fun unsubscribeRead(key: String, callback: (String, V) -> Unit) = readPipe.unsubscribe(key, callback) override fun unsubscribeError(key: String, callback: (String, E) -> Unit) = errorPipe.unsubscribe(key, callback) } /** * ================================================================== * Producers * ================================================================== */ fun <K, V> createPipe(): Pipe<K, V> = PipeImpl() fun <V, E> createCRUDPipes(): CRUDPipes<V, E> = CRUPPipesImpl()
apache-2.0
de1b2b9ed1a98bed6d2c6f82547c6528
48.605263
118
0.654907
3.539906
false
false
false
false
t-yoshi/peca-android
ui/src/main/java/org/peercast/core/ui/setting/BaseLoadableDelegate.kt
1
3145
package org.peercast.core.ui.setting import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.annotation.CallSuper import androidx.core.view.get import androidx.core.view.isVisible import androidx.leanback.preference.LeanbackPreferenceFragmentCompat import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.preference.PreferenceFragmentCompat import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject import org.peercast.core.common.AppPreferences import org.peercast.core.common.PeerCastConfig import org.peercast.core.ui.R import timber.log.Timber import java.io.IOException internal abstract class BaseLoadableDelegate(protected val fragment: PreferenceFragmentCompat) { protected val appConfig by fragment.inject<PeerCastConfig>() protected val appPrefs by fragment.inject<AppPreferences>() private val isBusy = MutableStateFlow(false) init { //TV設定画面で if (fragment is LeanbackPreferenceFragmentCompat) { fragment.lifecycle.addObserver(object : DefaultLifecycleObserver { override fun onResume(owner: LifecycleOwner) { //戻るボタンのイベントを拾うため (fragment.view as ViewGroup)[0].requestFocus() } }) } } @CallSuper open fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { fragment.preferenceScreen = fragment.preferenceManager.createPreferenceScreen(fragment.requireContext()) isBusy.onEach { fragment.preferenceScreen.isEnabled = !it }.launchIn(fragment.lifecycleScope) } fun wrapProgressView(container: View): ViewGroup { val inflater = LayoutInflater.from(container.context) val v = FrameLayout(inflater.context) v.addView(container) val vProgress = inflater.inflate(R.layout.progress, v, false) v.addView(vProgress) isBusy.onEach { vProgress.isVisible = it }.launchIn(fragment.viewLifecycleOwner.lifecycleScope) return v } protected fun <T> asyncExecute( doInBackground: suspend () -> T, onSuccess: (T) -> Unit = {}, onFailure: (IOException) -> Unit = { Timber.w(it) } ) { isBusy.value = true fragment.lifecycleScope.launch { withContext(Dispatchers.IO) { kotlin.runCatching { doInBackground() } } .onSuccess(onSuccess) .onFailure { e -> when (e) { is IOException -> onFailure(e) else -> throw e } } isBusy.value = false } } }
gpl-3.0
b0911f8672a808f34c1f79f0a0fc3a3b
33.511111
96
0.676973
5.04878
false
false
false
false
GoogleCloudPlatform/kotlin-samples
getting-started/android-with-appengine/frontend/emojify/src/main/java/com/google/cloud/kotlin/emojify/Adapter.kt
1
2181
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.kotlin.emojify import android.support.v7.recyclerview.extensions.ListAdapter import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.yanzhenjie.album.Album import com.yanzhenjie.album.AlbumFile import kotlinx.android.synthetic.main.item_content_image.view.ivAlbumContentImage class AlbumFileDiffCallback : DiffUtil.ItemCallback<AlbumFile>() { override fun areItemsTheSame(oldItem: AlbumFile, newItem: AlbumFile): Boolean { return oldItem.path == newItem.path } override fun areContentsTheSame(oldItem: AlbumFile, newItem: AlbumFile): Boolean { return oldItem == newItem } } class Adapter(private val clickListener: (AlbumFile) -> Unit) : ListAdapter<AlbumFile, Adapter.ViewHolder>(AlbumFileDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) return ViewHolder(inflater.inflate(R.layout.item_content_image, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(getItem(position), clickListener) class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(albumFile: AlbumFile, clickListener: (AlbumFile) -> Unit) { Album.getAlbumConfig().albumLoader.load(itemView.ivAlbumContentImage, albumFile) itemView.setOnClickListener { clickListener(albumFile) } } } }
apache-2.0
7f6870a5d13b7795579ffe834415ea79
37.964286
133
0.754241
4.293307
false
false
false
false
chillcoding-at-the-beach/my-cute-heart
MyCuteHeart/app/src/main/java/com/chillcoding/ilove/extension/MainGameExt.kt
1
3666
package com.chillcoding.ilove.extension import android.media.MediaPlayer import android.os.Bundle import com.chillcoding.ilove.App import com.chillcoding.ilove.MainActivity import com.chillcoding.ilove.R import com.chillcoding.ilove.view.dialog.* import kotlinx.android.synthetic.main.app_bar_main.* import kotlinx.android.synthetic.main.content_main.* import org.jetbrains.anko.contentView fun MainActivity.showLevelDialog() { val bundle = Bundle() bundle.putInt(App.BUNDLE_GAME_LEVEL, gameView.gameData.level) val popup = LevelDialog() popup.arguments = bundle popup.show(fragmentManager, MainActivity::class.java.simpleName) } fun MainActivity.showAlertOnLove() { QuoteDialog().show(fragmentManager, MainActivity::class.java.simpleName) } fun MainActivity.showAwardDialog() { AwardDialog().show(fragmentManager, MainActivity::class.java.simpleName) } fun MainActivity.showHelpDialog() { RulesDialog().show(fragmentManager, MainActivity::class.java.simpleName) } fun MainActivity.setUpGame() { setUpSound() updateScore() updateLevel() } fun MainActivity.pauseGame(animateFab: Boolean = false) { if (animateFab) fab.playAnimation(contentView!!) gameView.pause() mSoundPlayer.pause() } fun MainActivity.playGame(animateFab: Boolean = false) { if (animateFab) fab.playAnimation(contentView!!) if (isSound) mSoundPlayer.start() gameView.play() } fun MainActivity.endGame() { resetSound() fab.playAnimation(contentView!!) val bundle = Bundle() bundle.putParcelable(App.STATE_GAME_DATA, gameView.gameData) val popup = EndGameDialog() popup.arguments = bundle popup.show(fragmentManager, MainActivity::class.java.simpleName) } private fun MainActivity.setUpSound() { mSoundPlayer = MediaPlayer.create(this, R.raw.latina) mSoundPlayer.isLooping = true mSoundPlayer.setVolume(0.6F, 0.6F) } fun MainActivity.updateScore() { when (gameView.gameData.score) { in 0..9 -> mainScorePoints.text = "00${gameView.gameData.score}" in 10..99 -> mainScorePoints.text = "0${gameView.gameData.score}" else -> mainScorePoints.text = "${gameView.gameData.score}" } } fun MainActivity.updateLevel() { mainLevel.text = "${gameView.gameData.level}" } fun MainActivity.updateGauge() { val temp = gameView.gameData.score * 600 / gameView.scoreForNextAward() if (temp < 3) mainGaugeAward.value = 200 + 3 else mainGaugeAward.value = 200 + temp mainGaugeLevel.value = 200 + (gameView.gameData.score - gameView.scoreForLevel(gameView.gameData.level - 1)) * 600 / (gameView.scoreForLevel(gameView.gameData.level) - gameView.scoreForLevel(gameView.gameData.level - 1)) } fun MainActivity.updateNbLife() { when (gameView.gameData.nbLife) { 0 -> { mainFirstLife.setImageResource(R.drawable.ic_life_lost) endGame() } 1 -> { mainSecondLife.setImageResource(R.drawable.ic_life_lost) mainThirdLife.setImageResource(R.drawable.ic_life_lost) } 2 -> mainThirdLife.setImageResource(R.drawable.ic_life_lost) 3 -> { mainFirstLife.setImageResource(R.drawable.ic_life) mainSecondLife.setImageResource(R.drawable.ic_life) mainThirdLife.setImageResource(R.drawable.ic_life) } } } fun MainActivity.updateGameInfo() { updateScore() updateNbLife() updateLevel() updateGauge() } fun MainActivity.resetSound() { mSoundPlayer.reset() setUpSound() } fun MainActivity.setUpNewGame() { gameView.setUpNewGame() updateGameInfo() }
gpl-3.0
58b852ccc26a9996a62ea9680957a4c1
28.336
224
0.7024
3.691843
false
false
false
false
konrad-jamrozik/droidmate
dev/droidmate/projects/reporter/src/test/kotlin/org/droidmate/report/extensions_time_seriesKtTest.kt
1
3655
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2016 Konrad Jamrozik // // 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/>. // // email: [email protected] // web: www.droidmate.org package org.droidmate.report import org.junit.Test import java.time.LocalDateTime import kotlin.test.assertEquals class extensions_time_seriesKtTest { private val startTimeFixture: LocalDateTime = LocalDateTime.of(2000, 1, 1, 0, 0) private val inputDataFixture = listOf( Pair(startTimeFixture.plusSeconds(3), listOf("a", "b", "c")), Pair(startTimeFixture.plusSeconds(7), listOf("a", "c", "d")), Pair(startTimeFixture.plusSeconds(15), listOf("c")), Pair(startTimeFixture.plusSeconds(23), listOf("b", "e")) ) private val itemsAtTimeFixture: Map<Long, List<String>> = mapOf( Pair(3000L, listOf("a", "b", "c")), Pair(7000L, listOf("a", "c", "d")), Pair(15000L, listOf("c")), Pair(23000L, listOf("b", "e")) ) private val accumulatedUniqueStringsFixture: Map<Long, List<String>> = mapOf( Pair(3000L, listOf("a", "b", "c")), Pair(7000L, listOf("a", "b", "c", "d")), Pair(15000L, listOf("a", "b", "c", "d")), Pair(23000L, listOf("a", "b", "c", "d", "e")) ) @Test fun itemsAtTimeTest() { // Act val itemsAtTime: Map<Long, Iterable<String>> = inputDataFixture.itemsAtTime( startTime = startTimeFixture, extractTime = { it.first }, extractItems = { it.second } ) assertEquals(expected = itemsAtTimeFixture, actual = itemsAtTime) } @Test fun accumulateTest() { // Act val accumulatedUniqueStrings = itemsAtTimeFixture.accumulate() assertEquals(expected = accumulatedUniqueStringsFixture, actual = accumulatedUniqueStrings) } private val unpartitionedTimeSeriesFixture = mapOf( Pair(7L, 1), Pair(9L, 2), Pair(13L, 3), Pair(17L, 4), Pair(31L, 5), Pair(45L, 6) ) private val partitionedTimeSeriesFixture: Map<Long, List<Int>> = mapOf( Pair(0L, listOf()), Pair(10L, listOf(1, 2)), Pair(20L, listOf(3, 4)), Pair(30L, listOf()), Pair(40L, listOf(5)), Pair(50L, listOf(6)) ) private val partitionedAccumulatedAndExtendedTimeSeriesFixture = mapOf( Pair(0L, 0), Pair(10L, 2), Pair(20L, 4), Pair(30L, 4), Pair(40L, 5), Pair(50L, 6), Pair(60L, -1), Pair(70L, -1) ) @Test fun partitionTest() { val map: Map<Long, Int> = unpartitionedTimeSeriesFixture // Act val partitionedTimeSeries: Map<Long, List<Int>> = map.partition(10) assertEquals(expected = partitionedTimeSeriesFixture, actual = partitionedTimeSeries) } @Test fun accumulateMaxesAndPadPartitionsTest() { // Act val accumulatedAndPadded: Map<Long, Int> = partitionedTimeSeriesFixture .accumulateMaxes(extractMax = { it.max() ?: 0 }) .padPartitions(partitionSize = 10L, lastPartition = 70L) assertEquals(expected = partitionedAccumulatedAndExtendedTimeSeriesFixture, actual = accumulatedAndPadded) } }
gpl-3.0
33aba966c08a790079c400ef23dc4f0f
28.475806
110
0.674145
3.590373
false
true
false
false
MoonCheesez/sstannouncer
sstannouncer/app/src/main/java/sst/com/anouncements/feed/ui/FeedFragment.kt
1
3132
package sst.com.anouncements.feed.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.fragment_feed.* import org.koin.androidx.viewmodel.ext.android.stateViewModel import sst.com.anouncements.R import java.net.UnknownHostException class FeedFragment : Fragment() { private val feedViewModel: FeedViewModel by stateViewModel(bundle = { requireArguments() }) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return layoutInflater.inflate(R.layout.fragment_feed, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Prepare for feed RecyclerView val viewManager = LinearLayoutManager(context) // Start with no elements, update later when the data is ready val viewAdapter = FeedAdapter(listOf()) { val postArguments: Bundle = Bundle() postArguments.putParcelable("post", it) findNavController().navigate(R.id.action_feedFragment_to_postFragment, postArguments) } feed_recycler_view.apply { layoutManager = viewManager adapter = viewAdapter } // Add dividers to RecyclerView val dividerItemDecoration = DividerItemDecoration( feed_recycler_view.context, viewManager.orientation) feed_recycler_view.addItemDecoration(dividerItemDecoration) // Create view model observers feedViewModel.feedLiveData.observe(viewLifecycleOwner, Observer { feed -> // Show error message if there are any errors if (feed.first == null) { val exception = feed.second!! // Use custom messages for common errors val errorMessage = if (exception is UnknownHostException) { getString(R.string.error_unknown_host) } else { exception.localizedMessage } Toast.makeText(context, errorMessage, Toast.LENGTH_LONG).show() return@Observer } // Set adapter entries when the feed live data is updated val sortedEntries = feed.first!!.entries.sortedByDescending { entry -> entry.publishedDate.time } viewAdapter.setEntries(sortedEntries) }) feedViewModel.isLoading.observe(viewLifecycleOwner, Observer { // Update swipe refresh layout status feed_swipe_refresh_layout.isRefreshing = it }) // Setup swipe refresh layout feed_swipe_refresh_layout.setOnRefreshListener { feedViewModel.refresh() } } }
mit
d08b84c0692a4bec7fa48fabf4288958
37.207317
116
0.673691
5.34471
false
false
false
false
saru95/DSA
Kotlin/Knapsack0_1.kt
1
605
class Knapsack0_1 { fun main(args: Array<String>) { val `val` = intArrayOf(60, 100, 120) val wt = intArrayOf(10, 20, 30) val W = 50 val n = `val`.size System.out.println(knapsack(W, wt, `val`, n)) } private fun knapsack(W: Int, wt: IntArray, `val`: IntArray, n: Int): Int { return if (W == 0 || n == 0) { 0 } else if (wt[n - 1] > W) { knapsack(W, wt, `val`, n - 1) } else { Math.max(`val`[n - 1] + knapsack(W - wt[n - 1], wt, `val`, n - 1), knapsack(W, wt, `val`, n - 1)) } } }
mit
8a0a69b89396ceb5d79a057020dfa42b
26.545455
109
0.449587
2.688889
false
false
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/viewmodels/LiveViewModel.kt
1
2503
package be.digitalia.fosdem.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import androidx.paging.PagingSource import androidx.paging.cachedIn import be.digitalia.fosdem.db.ScheduleDao import be.digitalia.fosdem.flow.countSubscriptionsFlow import be.digitalia.fosdem.flow.flowWhileShared import be.digitalia.fosdem.flow.stateFlow import be.digitalia.fosdem.flow.synchronizedTickerFlow import be.digitalia.fosdem.model.StatusEvent import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import java.time.Duration import java.time.Instant import javax.inject.Inject import kotlin.time.Duration.Companion.minutes @HiltViewModel class LiveViewModel @Inject constructor(scheduleDao: ScheduleDao) : ViewModel() { // Share a single ticker providing the time to ensure both lists are synchronized private val ticker: Flow<Instant> = stateFlow(viewModelScope, null) { subscriptionCount -> synchronizedTickerFlow(REFRESH_PERIOD, subscriptionCount) .map { Instant.now() } }.filterNotNull() @OptIn(ExperimentalCoroutinesApi::class) private fun createLiveEventsHotFlow( pagingSourceFactory: (now: Instant) -> PagingSource<Int, StatusEvent> ): Flow<PagingData<StatusEvent>> { return countSubscriptionsFlow { subscriptionCount -> ticker .flowWhileShared(subscriptionCount, SharingStarted.WhileSubscribed()) .distinctUntilChanged() .flatMapLatest { now -> Pager(PagingConfig(20)) { pagingSourceFactory(now) }.flow }.cachedIn(viewModelScope) } } val nextEvents: Flow<PagingData<StatusEvent>> = createLiveEventsHotFlow { now -> scheduleDao.getEventsWithStartTime(now, now + NEXT_EVENTS_INTERVAL) } val eventsInProgress: Flow<PagingData<StatusEvent>> = createLiveEventsHotFlow { now -> scheduleDao.getEventsInProgress(now) } companion object { private val REFRESH_PERIOD = 1.minutes private val NEXT_EVENTS_INTERVAL = Duration.ofMinutes(30L) } }
apache-2.0
6c352ea1a58be66b47bfd141e2856784
38.125
94
0.760687
4.804223
false
false
false
false
Nagarajj/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ResumeTaskHandlerSpec.kt
1
2409
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.PAUSED import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.pipeline.model.Pipeline import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.* import com.netflix.spinnaker.spek.shouldEqual import com.nhaarman.mockito_kotlin.* import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek object ResumeTaskHandlerSpec : SubjectSpek<ResumeTaskHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() subject { ResumeTaskHandler(queue, repository) } fun resetMocks() = reset(queue, repository) describe("resuming a paused execution") { val pipeline = pipeline { application = "spinnaker" status = RUNNING stage { refId = "1" status = RUNNING task { id = "1" status = PAUSED implementingClass = DummyTask::class.java.name } } } val message = ResumeTask(Pipeline::class.java, pipeline.id, pipeline.application, pipeline.stages.first().id, "1") beforeGroup { whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("sets the stage status to running") { verify(repository).storeStage(check { it.getId() shouldEqual message.stageId it.getTasks().first().status shouldEqual RUNNING }) } it("resumes all paused tasks") { verify(queue).push(RunTask(message, DummyTask::class.java)) verifyNoMoreInteractions(queue) } } })
apache-2.0
b43e7baeec8baaf48f0dd98963434d0d
29.493671
118
0.709008
4.286477
false
false
false
false
nsk-mironov/smuggler
smuggler-compiler/src/main/java/com/joom/smuggler/compiler/common/Types.kt
1
4285
package com.joom.smuggler.compiler.common import com.joom.smuggler.compiler.annotations.AnnotationDelegate import org.objectweb.asm.Type import java.io.Serializable import java.util.ArrayList import java.util.Date import java.util.HashMap import java.util.HashSet import java.util.LinkedHashMap import java.util.LinkedHashSet import java.util.LinkedList import java.util.SortedMap import java.util.SortedSet import java.util.TreeMap import java.util.TreeSet @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") internal object Types { private val PRIMITIVE_TYPES = HashSet<Type>().apply { add(Type.BYTE_TYPE) add(Type.CHAR_TYPE) add(Type.DOUBLE_TYPE) add(Type.FLOAT_TYPE) add(Type.INT_TYPE) add(Type.LONG_TYPE) add(Type.SHORT_TYPE) add(Type.BOOLEAN_TYPE) add(Type.VOID_TYPE) } val OBJECT = getType<Any>() val CLASS = getType<Class<*>>() val CLASS_LOADER = getType<ClassLoader>() val ENUM = getType<Enum<*>>() val SERIALIZABLE = getType<Serializable>() val DATE = getType<Date>() val CHAR_SEQUENCE = getType<CharSequence>() val ITERATOR = getType<Iterator<*>>() val COLLECTION = getType<Collection<*>>() val ENTRY = getType<Map.Entry<*, *>>() val LIST = getType<List<*>>() val ARRAY_LIST = getType<ArrayList<*>>() val LINKED_LIST = getType<LinkedList<*>>() val SET = getType<Set<*>>() val HASH_SET = getType<HashSet<*>>() val LINKED_SET = getType<LinkedHashSet<*>>() val SORTED_SET = getType<SortedSet<*>>() val TREE_SET = getType<TreeSet<*>>() val MAP = getType<Map<*, *>>() val HASH_MAP = getType<HashMap<*, *>>() val LINKED_MAP = getType<LinkedHashMap<*, *>>() val SORTED_MAP = getType<SortedMap<*, *>>() val TREE_MAP = getType<TreeMap<*, *>>() val BYTE = Type.BYTE_TYPE val CHAR = Type.CHAR_TYPE val DOUBLE = Type.DOUBLE_TYPE val FLOAT = Type.FLOAT_TYPE val INT = Type.INT_TYPE val LONG = Type.LONG_TYPE val SHORT = Type.SHORT_TYPE val BOOLEAN = Type.BOOLEAN_TYPE val STRING = getType<String>() val VOID = Type.VOID_TYPE val BOXED_BYTE = getType<Byte>() val BOXED_CHAR = getType<Character>() val BOXED_DOUBLE = getType<Double>() val BOXED_FLOAT = getType<Float>() val BOXED_INT = getType<Integer>() val BOXED_LONG = getType<Long>() val BOXED_SHORT = getType<Short>() val BOXED_BOOLEAN = getType<java.lang.Boolean>() val ANDROID_PARCEL = Type.getObjectType("android/os/Parcel") val ANDROID_PARCELABLE = Type.getObjectType("android/os/Parcelable") val ANDROID_CREATOR = Type.getObjectType("android/os/Parcelable\$Creator") val ANDROID_BUNDLE = Type.getObjectType("android/os/Bundle") val ANDROID_SPARSE_BOOLEAN_ARRAY = Type.getObjectType("android/util/SparseBooleanArray") val ANDROID_SPARSE_ARRAY = Type.getObjectType("android/util/SparseArray") val ANDROID_TEXT_UTILS = Type.getObjectType("android/text/TextUtils") val ANDROID_LOG = Type.getObjectType("android/util/Log") val SMUGGLER_PARCELABLE = Type.getObjectType("com/joom/smuggler/AutoParcelable") val SMUGGLER_GLOBAL_ADAPTER = Type.getObjectType("com/joom/smuggler/GlobalAdapter") val SMUGGLER_LOCAL_ADAPTER = Type.getObjectType("com/joom/smuggler/LocalAdapter") val SMUGGLER_ADAPTER = Type.getObjectType("com/joom/smuggler/TypeAdapter") inline fun <reified T : Any> getType(): Type { return Type.getType(T::class.java) } fun getArrayType(type: Type): Type { return Type.getType("[${type.descriptor}") } fun getElementType(type: Type): Type { if (type.sort != Type.ARRAY) { throw IllegalArgumentException("Types.getElementType() can only be called for array types") } val element = type.elementType val dimensions = type.dimensions return 0.until(dimensions - 1).fold(element) { value, _ -> getArrayType(value) } } fun getAnnotationType(clazz: Class<*>): Type { return clazz.getAnnotation(AnnotationDelegate::class.java)?.run { Type.getObjectType(value.replace('.', '/')) } ?: Type.getType(clazz) } fun getGeneratedType(type: Type, name: String): Type { return Type.getObjectType("${type.internalName}\$\$$name") } fun getClassFilePath(type: Type): String { return "${type.internalName}.class" } fun isPrimitive(type: Type): Boolean { return type in PRIMITIVE_TYPES } }
mit
cb159e1e1bd73eb735750f3c800134fe
31.462121
97
0.703151
3.819073
false
false
false
false
luoyuan800/NeverEnd
dataModel/src/cn/luo/yuan/maze/model/skill/race/RaceSkillModel.kt
1
2038
package cn.luo.yuan.maze.model.skill.race import cn.luo.yuan.maze.model.HarmAble import cn.luo.yuan.maze.model.NameObject import cn.luo.yuan.maze.model.Parameter import cn.luo.yuan.maze.model.Race import cn.luo.yuan.maze.model.skill.AtkSkill import cn.luo.yuan.maze.model.skill.Skill import cn.luo.yuan.maze.model.skill.SkillModel import cn.luo.yuan.maze.model.skill.SkillParameter import cn.luo.yuan.maze.model.skill.result.DoNoThingResult import cn.luo.yuan.maze.model.skill.result.SkillResult import cn.luo.yuan.maze.model.skill.result.SkipThisTurn import cn.luo.yuan.maze.service.BattleMessage import cn.luo.yuan.maze.utils.Random import cn.luo.yuan.maze.utils.StringUtils /** * Created by luoyuan on 2017/9/4. */ class RaceSkillModel(private val s:Skill): SkillModel(s) { fun getDesc():String{ return "当对战的敌人是 ${race().getName()} 时,攻击有50%的几率秒杀对方。" + "<br>已经使用:${StringUtils.formatNumber((skill as AtkSkill).useTime)}次" } private fun race(): Race { var race = Race.Nonsr; when (skill) { is Alayer -> race = Race.Orger is Decide -> race = Race.Elyosr is Exorcism -> race = Race.Ghosr is Masimm -> race = Race.Wizardsr is Painkiller -> race = Race.Eviler } return race } fun perform(parameter: SkillParameter): SkillResult { val m = parameter.get<HarmAble>(Parameter.TARGET) val r = parameter.get<Random>(Parameter.RANDOM); val a = parameter.get<HarmAble>(Parameter.ATKER) var result:SkillResult = DoNoThingResult() if(m!=null && m.race == race() && r!=null && r.nextBoolean()){ m.hp -= m.currentHp; if(a is NameObject && m is NameObject) { result = SkipThisTurn() result.messages.add("${a.displayName}秒杀了${m.displayName}") } }else { result.messages.add("技能没有生效!") } return result; } }
bsd-3-clause
7fc0ea59e65aa312c9851bc594d33f58
34.763636
136
0.647508
3.304202
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/codec/vpx/PictureIdIndexTracker.kt
1
2108
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.codec.vpx /** Like [org.jitsi.nlj.util.Rfc3711IndexTracker], but for VP8/VP9 picture IDs (so with a rollover * of 0x8000). */ class PictureIdIndexTracker { private var roc = 0 private var highestSeqNumReceived = -1 private fun getIndex(seqNum: Int, updateRoc: Boolean): Int { if (highestSeqNumReceived == -1) { if (updateRoc) { highestSeqNumReceived = seqNum } return seqNum } val delta = VpxUtils.getExtendedPictureIdDelta(seqNum, highestSeqNumReceived) val v = if (delta < 0 && highestSeqNumReceived < seqNum) { roc - 1 } else if (delta > 0 && seqNum < highestSeqNumReceived) { (roc + 1).also { if (updateRoc) roc = it } } else { roc } if (updateRoc && delta > 0) { highestSeqNumReceived = seqNum } return 0x8000 * v + seqNum } fun update(seq: Int) = getIndex(seq, updateRoc = true) fun interpret(seq: Int) = getIndex(seq, updateRoc = false) /** Force this sequence to be interpreted as the new highest, regardless * of its rollover state. */ fun resetAt(seq: Int) { val delta = VpxUtils.getExtendedPictureIdDelta(seq, highestSeqNumReceived) if (delta < 0) { roc++ highestSeqNumReceived = seq } getIndex(seq, true) } }
apache-2.0
cd599d206f7204ecc80ed759b378b79e
32.460317
98
0.604839
4.085271
false
false
false
false
edsilfer/presence-control
app/src/main/java/br/com/edsilfer/android/presence_control/place/presentation/model/PlaceViewHolder.kt
1
745
package br.com.edsilfer.android.presence_control.place.presentation.model import android.support.v7.widget.RecyclerView import android.view.View import android.widget.LinearLayout import android.widget.TextView import br.com.edsilfer.android.presence_control.R /** * Created by ferna on 5/21/2017. */ class PlaceViewHolder(v: View) : RecyclerView.ViewHolder(v) { val container: LinearLayout = v.findViewById(R.id.linearLayout_placeContainer) val name: TextView = v.findViewById(R.id.textView_placeName) val description: TextView = v.findViewById(R.id.textView_placeDescription) val address: TextView = v.findViewById(R.id.textView_placeAddress) val geolocation: TextView = v.findViewById(R.id.textView_placeGeolocation) }
apache-2.0
081107d95b141a55b83a156d5dc3365c
40.444444
82
0.789262
3.743719
false
false
false
false
jitsi/jitsi-videobridge
jvb/src/main/kotlin/org/jitsi/videobridge/transport/dtls/DtlsTransport.kt
1
8094
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.transport.dtls import org.jitsi.nlj.dtls.DtlsClient import org.jitsi.nlj.dtls.DtlsServer import org.jitsi.nlj.dtls.DtlsStack import org.jitsi.nlj.srtp.TlsRole import org.jitsi.utils.OrderedJsonObject import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.createChildLogger import org.jitsi.xmpp.extensions.jingle.DtlsFingerprintPacketExtension import org.jitsi.xmpp.extensions.jingle.IceUdpTransportPacketExtension import java.util.concurrent.atomic.AtomicBoolean /** * Transport layer which negotiates a DTLS connection and supports * decrypting and encrypting data. * * Incoming DTLS data should be fed into this layer via [dtlsDataReceived], * and decrypted DTLS application data will be passed to the * [incomingDataHandler], which should be set by an interested party. * * Outgoing data can be sent via [sendDtlsData] and the encrypted data will * be passed to the [outgoingDataHandler], which should be set by an * interested party. */ class DtlsTransport(parentLogger: Logger) { private val logger = createChildLogger(parentLogger) private val running = AtomicBoolean(true) @JvmField var incomingDataHandler: IncomingDataHandler? = null @JvmField var outgoingDataHandler: OutgoingDataHandler? = null @JvmField var eventHandler: EventHandler? = null private var dtlsHandshakeComplete = false val isConnected: Boolean get() = dtlsHandshakeComplete private val stats = Stats() /** * The DTLS stack instance */ private val dtlsStack = DtlsStack(logger).also { // Install a handler for when the DTLS stack has decrypted application data available it.incomingDataHandler = object : DtlsStack.IncomingDataHandler { override fun dataReceived(data: ByteArray, off: Int, len: Int) { stats.numPacketsReceived++ incomingDataHandler?.dtlsAppDataReceived(data, off, len) ?: run { stats.numIncomingPacketsDroppedNoHandler++ } } } // Install a handler to allow the DTLS stack to send out encrypted data it.outgoingDataHandler = object : DtlsStack.OutgoingDataHandler { override fun sendData(data: ByteArray, off: Int, len: Int) { outgoingDataHandler?.sendData(data, off, len)?.also { stats.numPacketsSent++ } ?: run { stats.numOutgoingPacketsDroppedNoHandler++ } } } // Handle DTLS stack events it.eventHandler = object : DtlsStack.EventHandler { override fun handshakeComplete( chosenSrtpProtectionProfile: Int, tlsRole: TlsRole, keyingMaterial: ByteArray ) { dtlsHandshakeComplete = true eventHandler?.handshakeComplete(chosenSrtpProtectionProfile, tlsRole, keyingMaterial) } } } /** * Start a DTLS handshake. The 'role' should have been set before calling this * (via [setSetupAttribute] */ fun startDtlsHandshake() { logger.info("Starting DTLS handshake, role=${dtlsStack.role}") if (dtlsStack.role == null) { logger.warn("Starting the DTLS stack before it knows its role") } try { dtlsStack.start() } catch (t: Throwable) { // TODO: we're not doing anything here, should we? or change the log? logger.error("Error during DTLS negotiation, closing this transport manager", t) } } fun setSetupAttribute(setupAttr: String?) { if (setupAttr.isNullOrEmpty()) { return } when (setupAttr.lowercase()) { "active" -> { logger.info("The remote side is acting as DTLS client, we'll act as server") dtlsStack.actAsServer() } "passive" -> { logger.info("The remote side is acting as DTLS server, we'll act as client") dtlsStack.actAsClient() } else -> { logger.error( "The remote side sent an unrecognized DTLS setup value: " + setupAttr ) } } } fun setRemoteFingerprints(remoteFingerprints: Map<String, String>) { // Don't pass an empty list to the stack in order to avoid wiping // certificates that were contained in a previous request. if (remoteFingerprints.isEmpty()) { return } dtlsStack.remoteFingerprints = remoteFingerprints } /** * Describe the properties of this [DtlsTransport] into the given * [IceUdpTransportPacketExtension] */ fun describe(iceUdpTransportPe: IceUdpTransportPacketExtension) { val fingerprintPE = iceUdpTransportPe.getFirstChildOfType(DtlsFingerprintPacketExtension::class.java) ?: run { DtlsFingerprintPacketExtension().also { iceUdpTransportPe.addChildExtension(it) } } fingerprintPE.setup = when (dtlsStack.role) { is DtlsServer -> "passive" is DtlsClient -> "active" null -> "actpass" else -> throw IllegalStateException("Cannot describe role ${dtlsStack.role}") } fingerprintPE.fingerprint = dtlsStack.localFingerprint fingerprintPE.hash = dtlsStack.localFingerprintHashFunction } /** * Notify this layer that DTLS data has been received from the network */ fun dtlsDataReceived(data: ByteArray, off: Int, len: Int) = dtlsStack.processIncomingProtocolData(data, off, len) /** * Send out DTLS data */ fun sendDtlsData(data: ByteArray, off: Int, len: Int) = dtlsStack.sendApplicationData(data, off, len) fun stop() { if (running.compareAndSet(true, false)) { logger.info("Stopping") dtlsStack.close() } } fun getDebugState(): OrderedJsonObject = stats.toJson().apply { put("running", running.get()) put("role", dtlsStack.role.toString()) put("is_connected", isConnected) } private data class Stats( var numPacketsReceived: Int = 0, var numIncomingPacketsDroppedNoHandler: Int = 0, var numPacketsSent: Int = 0, var numOutgoingPacketsDroppedNoHandler: Int = 0 ) { fun toJson(): OrderedJsonObject = OrderedJsonObject().apply { put("num_packets_received", numPacketsReceived) put("num_incoming_packets_dropped_no_handler", numIncomingPacketsDroppedNoHandler) put("num_packets_sent", numPacketsSent) put("num_outgoing_packets_dropped_no_handler", numOutgoingPacketsDroppedNoHandler) } } /** * A handler for when [DtlsTransport] wants to send data out * onto the network */ interface OutgoingDataHandler { fun sendData(buf: ByteArray, off: Int, len: Int) } /** * A handler for when [DtlsTransport] has received DTLS application * data */ interface IncomingDataHandler { fun dtlsAppDataReceived(buf: ByteArray, off: Int, len: Int) } /** * A handler for [DtlsTransport] events */ interface EventHandler { fun handshakeComplete(chosenSrtpProtectionProfile: Int, tlsRole: TlsRole, keyingMaterial: ByteArray) } }
apache-2.0
e3b9e7996ceb3ec180e6a5880b5bb7e4
34.973333
118
0.63998
4.489185
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/searchsuggestions/SearchSuggestionsViewModel.kt
1
3847
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.searchsuggestions import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import mozilla.components.browser.state.state.selectedOrDefaultSearchEngine import mozilla.components.feature.search.ext.canProvideSearchSuggestions import mozilla.components.service.glean.private.NoExtras import org.mozilla.focus.FocusApplication import org.mozilla.focus.GleanMetrics.SearchSuggestions sealed class State { data class Disabled(val givePrompt: Boolean) : State() data class NoSuggestionsAPI(val givePrompt: Boolean) : State() object ReadyForSuggestions : State() } class SearchSuggestionsViewModel(application: Application) : AndroidViewModel(application) { private val preferences: SearchSuggestionsPreferences = SearchSuggestionsPreferences(application) private val _selectedSearchSuggestion = MutableLiveData<String?>() val selectedSearchSuggestion: LiveData<String?> = _selectedSearchSuggestion private val _searchQuery = MutableLiveData<String>() val searchQuery: LiveData<String> = _searchQuery private val _state = MutableLiveData<State>() val state: LiveData<State> = _state private val _autocompleteSuggestion = MutableLiveData<String?>() val autocompleteSuggestion: LiveData<String?> = _autocompleteSuggestion var alwaysSearch = false private set fun selectSearchSuggestion( suggestion: String, defaultSearchEngineName: String, alwaysSearch: Boolean = false, ) { this.alwaysSearch = alwaysSearch _selectedSearchSuggestion.postValue(suggestion) if (suggestion == searchQuery.value) { SearchSuggestions.searchTapped.record( SearchSuggestions.SearchTappedExtra(defaultSearchEngineName), ) } else { SearchSuggestions.suggestionTapped.record( SearchSuggestions.SuggestionTappedExtra(defaultSearchEngineName), ) } } fun clearSearchSuggestion() { _selectedSearchSuggestion.postValue(null) } fun setAutocompleteSuggestion(text: String) { _autocompleteSuggestion.postValue(text) SearchSuggestions.autocompleteArrowTapped.record(NoExtras()) } fun clearAutocompleteSuggestion() { _autocompleteSuggestion.postValue(null) } fun setSearchQuery(query: String) { _searchQuery.value = query } fun enableSearchSuggestions() { preferences.enableSearchSuggestions() updateState() setSearchQuery(searchQuery.value ?: "") } fun disableSearchSuggestions() { preferences.disableSearchSuggestions() updateState() } fun dismissNoSuggestionsMessage() { preferences.dismissNoSuggestionsMessage() updateState() } fun refresh() { updateState() } private fun updateState() { val enabled = preferences.searchSuggestionsEnabled() val store = getApplication<FocusApplication>().components.store val state = if (enabled) { if (store.state.search.selectedOrDefaultSearchEngine?.canProvideSearchSuggestions == true) { State.ReadyForSuggestions } else { val givePrompt = !preferences.userHasDismissedNoSuggestionsMessage() State.NoSuggestionsAPI(givePrompt) } } else { val givePrompt = !preferences.hasUserToggledSearchSuggestions() State.Disabled(givePrompt) } _state.value = state } }
mpl-2.0
f4c616f2ff486f92a5ec74b2ce4a1e7a
32.163793
104
0.701326
5.170699
false
false
false
false
MaTriXy/PermissionsDispatcher
processor/src/main/kotlin/permissions/dispatcher/processor/util/Extensions.kt
1
4270
package permissions.dispatcher.processor.util import com.squareup.kotlinpoet.* import permissions.dispatcher.NeedsPermission import permissions.dispatcher.OnNeverAskAgain import permissions.dispatcher.OnPermissionDenied import permissions.dispatcher.OnShowRationale import permissions.dispatcher.processor.TYPE_UTILS import javax.lang.model.element.* import javax.lang.model.type.TypeMirror /** * Returns the package name of a TypeElement. */ fun TypeElement.packageName() = enclosingElement.packageName() private fun Element?.packageName(): String { return when (this) { is TypeElement -> packageName() is PackageElement -> qualifiedName.toString() else -> this?.enclosingElement?.packageName() ?: "" } } // to address kotlin internal method try to remove `$module_name_build_variant` from element info. // ex: showCamera$sample_kotlin_debug → showCamera internal fun String.trimDollarIfNeeded(): String { val index = indexOf("$") return if (index == -1) this else substring(0, index) } /** * Returns the simple name of an Element as a string. */ fun Element.simpleString() = this.simpleName.toString().trimDollarIfNeeded() /** * Returns the simple name of a TypeMirror as a string. */ fun TypeMirror.simpleString(): String { val toString: String = this.toString() val indexOfDot: Int = toString.lastIndexOf('.') return if (indexOfDot == -1) toString else toString.substring(indexOfDot + 1) } /** * Returns whether or not an Element is annotated with the provided Annotation class. */ fun <A : Annotation> Element.hasAnnotation(annotationType: Class<A>): Boolean = this.getAnnotation(annotationType) != null /** * Returns whether a variable is nullable by inspecting its annotations. */ fun VariableElement.isNullable(): Boolean = this.annotationMirrors .map { it.annotationType.simpleString() } .toList() .contains("Nullable") /** * Maps a variable to its TypeName, applying necessary transformations * for Java primitive types & mirroring the variable's nullability settings. */ fun VariableElement.asPreparedType(): TypeName = this.asType() .asTypeName() .checkStringType() .mapToNullableTypeIf(this.isNullable()) /** * Returns the inherent value() of a permission Annotation. * <p> * If this is invoked on an Annotation that's not defined by PermissionsDispatcher, this returns an empty list. */ fun Annotation.permissionValue(): List<String> { when (this) { is NeedsPermission -> return this.value.asList() is OnShowRationale -> return this.value.asList() is OnPermissionDenied -> return this.value.asList() is OnNeverAskAgain -> return this.value.asList() } return emptyList() } /** * Returns a list of enclosed elements annotated with the provided Annotations. */ fun <A : Annotation> Element.childElementsAnnotatedWith(annotationClass: Class<A>): List<ExecutableElement> = this.enclosedElements .filter { it.hasAnnotation(annotationClass) } .map { it as ExecutableElement } /** * Returns whether or not a TypeMirror is a subtype of the provided other TypeMirror. */ fun TypeMirror.isSubtypeOf(ofType: TypeMirror): Boolean = TYPE_UTILS.isSubtype(this, ofType) fun FileSpec.Builder.addProperties(properties: List<PropertySpec>): FileSpec.Builder { properties.forEach { addProperty(it) } return this } fun FileSpec.Builder.addFunctions(functions: List<FunSpec>): FileSpec.Builder { functions.forEach { addFunction(it) } return this } fun FileSpec.Builder.addTypes(types: List<TypeSpec>): FileSpec.Builder { types.forEach { addType(it) } return this } /** * To avoid KotlinPoet bug that returns java.lang.String when type name is kotlin.String. * This method should be removed after addressing on KotlinPoet side. */ fun TypeName.checkStringType() = if (this.toString() == "java.lang.String") ClassName("kotlin", "String") else this /** * Returns this TypeName as nullable or non-nullable based on the given condition. */ fun TypeName.mapToNullableTypeIf(nullable: Boolean) = if (nullable) asNullable() else asNonNullable()
apache-2.0
0c5469d0ccf3a80944f6b50453285869
33.144
111
0.711106
4.455115
false
false
false
false
square/leakcanary
shark/src/main/java/shark/internal/ObjectDominators.kt
2
5324
package shark.internal import shark.GcRoot.ThreadObject import shark.HeapGraph import shark.HeapObject.HeapClass import shark.HeapObject.HeapInstance import shark.HeapObject.HeapObjectArray import shark.HeapObject.HeapPrimitiveArray import shark.IgnoredReferenceMatcher import shark.OnAnalysisProgressListener import shark.ValueHolder /** * Exposes high level APIs to compute and render a dominator tree. This class * needs to be public to be used by other LeakCanary modules but is internal and * its API might change at any moment. * * Note that the exposed APIs are not optimized for speed, memory or IO. * * Eventually this capability should become part of the Shark public APIs, please * open an issue if you'd like to use this directly. */ class ObjectDominators { internal data class DominatorNode( val shallowSize: Int, val retainedSize: Int, val retainedCount: Int, val dominatedObjectIds: List<Long> ) fun renderDominatorTree( graph: HeapGraph, ignoredRefs: List<IgnoredReferenceMatcher>, minRetainedSize: Int, threadName: String? = null, printStringContent: Boolean = false ): String { val stringBuilder = StringBuilder() val dominatorTree = buildDominatorTree(graph, ignoredRefs) val root = dominatorTree.getValue(ValueHolder.NULL_REFERENCE) stringBuilder.append( "Total retained: ${root.retainedSize} bytes in ${root.retainedCount} objects. Root dominators: ${root.dominatedObjectIds.size}\n\n" ) val rootIds = if (threadName != null) { setOf(graph.gcRoots.first { gcRoot -> gcRoot is ThreadObject && graph.objectExists(gcRoot.id) && graph.findObjectById(gcRoot.id) .asInstance!!["java.lang.Thread", "name"]!! .value.readAsJavaString() == threadName }.id) } else { root.dominatedObjectIds.filter { dominatorTree.getValue(it).retainedSize > minRetainedSize } } rootIds .forEach { objectId -> printTree( stringBuilder, graph, dominatorTree, objectId, minRetainedSize, 0, "", true, printStringContent ) stringBuilder.append("\n") } return stringBuilder.toString() } @Suppress("LongParameterList") private fun printTree( stringBuilder: StringBuilder, graph: HeapGraph, tree: Map<Long, DominatorNode>, objectId: Long, minSize: Int, depth: Int, prefix: String, isLast: Boolean, printStringContent: Boolean ) { val node = tree.getValue(objectId) val heapObject = graph.findObjectById(objectId) val className = when (heapObject) { is HeapClass -> "class ${heapObject.name}" is HeapInstance -> heapObject.instanceClassName is HeapObjectArray -> heapObject.arrayClassName is HeapPrimitiveArray -> heapObject.arrayClassName } val anchor = if (depth == 0) "" else if (isLast) "╰─" else "├─" val size = if (node.retainedSize != node.shallowSize) { "${node.retainedSize} bytes (${node.shallowSize} self)" } else { "${node.shallowSize} bytes" } val count = if (node.retainedCount > 1) { " ${node.retainedCount} objects" } else { "" } val stringContent = if ( printStringContent && heapObject is HeapInstance && heapObject.instanceClassName == "java.lang.String" ) " \"${heapObject.readAsJavaString()}\"" else "" stringBuilder.append( "$prefix$anchor$className #${heapObject.objectIndex} Retained: $size$count$stringContent\n" ) val newPrefix = when { depth == 0 -> "" isLast -> { "$prefix " } else -> { "$prefix│ " } } val largeChildren = node.dominatedObjectIds.filter { tree.getValue(it).retainedSize > minSize } val lastIndex = node.dominatedObjectIds.lastIndex largeChildren.forEachIndexed { index, objectId -> printTree( stringBuilder, graph, tree, objectId, minSize, depth + 1, newPrefix, index == lastIndex, printStringContent ) } if (largeChildren.size < node.dominatedObjectIds.size) { stringBuilder.append("$newPrefix╰┄\n") } } private fun buildDominatorTree( graph: HeapGraph, ignoredRefs: List<IgnoredReferenceMatcher> ): Map<Long, DominatorNode> { val referenceReader = DelegatingObjectReferenceReader( classReferenceReader = ClassReferenceReader(graph, emptyList()), instanceReferenceReader = ChainingInstanceReferenceReader( listOf(JavaLocalReferenceReader(graph, emptyList())), FieldInstanceReferenceReader(graph, emptyList()) ), objectArrayReferenceReader = ObjectArrayReferenceReader() ) val pathFinder = PathFinder( graph, OnAnalysisProgressListener.NO_OP, referenceReader, ignoredRefs ) val nativeSizeMapper = AndroidNativeSizeMapper(graph) val nativeSizes = nativeSizeMapper.mapNativeSizes() val shallowSizeCalculator = ShallowSizeCalculator(graph) val result = pathFinder.findPathsFromGcRoots(setOf(), true) return result.dominatorTree!!.buildFullDominatorTree { objectId -> val nativeSize = nativeSizes[objectId] ?: 0 val shallowSize = shallowSizeCalculator.computeShallowSize(objectId) nativeSize + shallowSize } } }
apache-2.0
b3dd7765060d4b205215ebbf4b4d6588
31.378049
137
0.683804
4.282258
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/ide/formatter/impl/utils.kt
1
5168
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.impl import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.intellij.psi.tree.TokenSet.orSet import org.rust.lang.core.psi.RS_OPERATORS import org.rust.lang.core.psi.RsAttr import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.RsStmt import org.rust.lang.core.psi.ext.RsItemElement import org.rust.lang.core.psi.ext.RsMod import org.rust.lang.core.psi.ext.elementType import com.intellij.psi.tree.TokenSet.create as ts val SPECIAL_MACRO_ARGS = ts(FORMAT_MACRO_ARGUMENT, LOG_MACRO_ARGUMENT, TRY_MACRO_ARGUMENT, VEC_MACRO_ARGUMENT, ASSERT_MACRO_ARGUMENT) val NO_SPACE_AROUND_OPS = ts(COLONCOLON, DOT, DOTDOT) val SPACE_AROUND_OPS = TokenSet.andNot(RS_OPERATORS, NO_SPACE_AROUND_OPS) val UNARY_OPS = ts(MINUS, MUL, EXCL, AND, ANDAND) val PAREN_DELIMITED_BLOCKS = orSet(ts(VALUE_PARAMETER_LIST, PAREN_EXPR, TUPLE_EXPR, TUPLE_TYPE, VALUE_ARGUMENT_LIST, PAT_TUP, TUPLE_FIELDS, VIS_RESTRICTION), SPECIAL_MACRO_ARGS) val PAREN_LISTS = orSet(PAREN_DELIMITED_BLOCKS, ts(PAT_ENUM)) val BRACK_DELIMITED_BLOCKS = orSet(ts(ARRAY_TYPE, ARRAY_EXPR), SPECIAL_MACRO_ARGS) val BRACK_LISTS = orSet(BRACK_DELIMITED_BLOCKS, ts(INDEX_EXPR)) val BLOCK_LIKE = ts(BLOCK, BLOCK_FIELDS, STRUCT_LITERAL_BODY, MATCH_BODY, ENUM_BODY, MEMBERS) val BRACE_LISTS = orSet(ts(USE_GROUP), SPECIAL_MACRO_ARGS) val BRACE_DELIMITED_BLOCKS = orSet(BLOCK_LIKE, BRACE_LISTS) val ANGLE_DELIMITED_BLOCKS = ts(TYPE_PARAMETER_LIST, TYPE_ARGUMENT_LIST, FOR_LIFETIMES) val ANGLE_LISTS = orSet(ANGLE_DELIMITED_BLOCKS, ts(TYPE_QUAL)) val ATTRS = ts(OUTER_ATTR, INNER_ATTR) val MOD_ITEMS = ts(FOREIGN_MOD_ITEM, MOD_ITEM) val DELIMITED_BLOCKS = orSet(BRACE_DELIMITED_BLOCKS, BRACK_DELIMITED_BLOCKS, PAREN_DELIMITED_BLOCKS, ANGLE_DELIMITED_BLOCKS) val FLAT_BRACE_BLOCKS = orSet(MOD_ITEMS, ts(PAT_STRUCT)) val TYPES = ts(ARRAY_TYPE, REF_LIKE_TYPE, FN_POINTER_TYPE, TUPLE_TYPE, BASE_TYPE, FOR_IN_TYPE) val FN_DECLS = ts(FUNCTION, FN_POINTER_TYPE, LAMBDA_EXPR) val ONE_LINE_ITEMS = ts(USE_ITEM, CONSTANT, MOD_DECL_ITEM, EXTERN_CRATE_ITEM, TYPE_ALIAS, INNER_ATTR) val PsiElement.isTopLevelItem: Boolean get() = (this is RsItemElement || this is RsAttr) && parent is RsMod val PsiElement.isStmtOrExpr: Boolean get() = this is RsStmt || this is RsExpr val ASTNode.isDelimitedBlock: Boolean get() = elementType in DELIMITED_BLOCKS val ASTNode.isFlatBraceBlock: Boolean get() = elementType in FLAT_BRACE_BLOCKS /** * A flat block is a Rust PSI element which does not denote separate PSI * element for its _block_ part (e.g. `{...}`), for example [MOD_ITEM]. */ val ASTNode.isFlatBlock: Boolean get() = isFlatBraceBlock || elementType == PAT_ENUM fun ASTNode.isBlockDelim(parent: ASTNode?): Boolean { if (parent == null) return false val parentType = parent.elementType return when (elementType) { LBRACE, RBRACE -> parentType in BRACE_DELIMITED_BLOCKS || parent.isFlatBraceBlock LBRACK, RBRACK -> parentType in BRACK_LISTS LPAREN, RPAREN -> parentType in PAREN_LISTS || parentType == PAT_ENUM LT, GT -> parentType in ANGLE_LISTS OR -> parentType == VALUE_PARAMETER_LIST && parent.treeParent?.elementType == LAMBDA_EXPR else -> false } } fun ASTNode?.isWhitespaceOrEmpty() = this == null || textLength == 0 || elementType == WHITE_SPACE fun ASTNode.treeNonWSPrev(): ASTNode? { var current = this.treePrev while (current?.elementType == WHITE_SPACE) { current = current?.treePrev } return current } fun ASTNode.treeNonWSNext(): ASTNode? { var current = this.treeNext while (current?.elementType == WHITE_SPACE) { current = current?.treeNext } return current } class CommaList( val list: IElementType, val openingBrace: IElementType, val closingBrace: IElementType, val isElement: (PsiElement) -> Boolean ) { val needsSpaceBeforeClosingBrace: Boolean get() = closingBrace == RBRACE && list != USE_GROUP override fun toString(): String = "CommaList($list)" companion object { fun forElement(elementType: IElementType): CommaList? { return ALL.find { it.list == elementType } } private val ALL = listOf( CommaList(BLOCK_FIELDS, LBRACE, RBRACE, { it.elementType == FIELD_DECL }), CommaList(STRUCT_LITERAL_BODY, LBRACE, RBRACE, { it.elementType == STRUCT_LITERAL_FIELD }), CommaList(ENUM_BODY, LBRACE, RBRACE, { it.elementType == ENUM_VARIANT }), CommaList(USE_GROUP, LBRACE, RBRACE, { it.elementType == USE_SPECK }), CommaList(TUPLE_FIELDS, LPAREN, RPAREN, { it.elementType == TUPLE_FIELD_DECL }), CommaList(VALUE_PARAMETER_LIST, LPAREN, RPAREN, { it.elementType == VALUE_PARAMETER }), CommaList(VALUE_ARGUMENT_LIST, LPAREN, RPAREN, { it is RsExpr }) ) } }
mit
6c7017edfb2fd3fd0a34843c18d38448
37.281481
157
0.711107
3.673063
false
false
false
false
google/horologist
media-sample/src/main/java/com/google/android/horologist/mediasample/di/ViewModelModule.kt
1
4566
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalCoroutinesApi::class) package com.google.android.horologist.mediasample.di import android.content.ComponentName import android.content.Context import androidx.media3.session.MediaBrowser import androidx.media3.session.SessionToken import com.google.android.horologist.media.data.mapper.MediaItemExtrasMapper import com.google.android.horologist.media.data.mapper.MediaItemExtrasMapperNoopImpl import com.google.android.horologist.media.data.mapper.MediaItemMapper import com.google.android.horologist.media.data.mapper.MediaMapper import com.google.android.horologist.media.data.repository.PlayerRepositoryImpl import com.google.android.horologist.media.repository.PlayerRepository import com.google.android.horologist.media3.flows.buildSuspend import com.google.android.horologist.mediasample.data.service.playback.PlaybackService import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.ActivityRetainedLifecycle import dagger.hilt.android.components.ActivityRetainedComponent import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.scopes.ActivityRetainedScoped import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.launch @Module @InstallIn(ActivityRetainedComponent::class) object ViewModelModule { @ActivityRetainedScoped @Provides fun providesCoroutineScope( activityRetainedLifecycle: ActivityRetainedLifecycle ): CoroutineScope { return CoroutineScope(SupervisorJob() + Dispatchers.Default).also { activityRetainedLifecycle.addOnClearedListener { it.cancel() } } } @Provides @ActivityRetainedScoped fun mediaController( @ApplicationContext application: Context, activityRetainedLifecycle: ActivityRetainedLifecycle, coroutineScope: CoroutineScope ): Deferred<MediaBrowser> = coroutineScope.async { MediaBrowser.Builder( application, SessionToken(application, ComponentName(application, PlaybackService::class.java)) ).buildSuspend() }.also { activityRetainedLifecycle.addOnClearedListener { it.cancel() if (it.isCompleted && !it.isCancelled) { it.getCompleted().release() } } } @Provides @ActivityRetainedScoped fun playerRepositoryImpl( mediaMapper: MediaMapper, mediaItemMapper: MediaItemMapper, activityRetainedLifecycle: ActivityRetainedLifecycle, coroutineScope: CoroutineScope, mediaController: Deferred<MediaBrowser> ): PlayerRepositoryImpl = PlayerRepositoryImpl( mediaMapper = mediaMapper, mediaItemMapper = mediaItemMapper ).also { playerRepository -> activityRetainedLifecycle.addOnClearedListener { playerRepository.close() } coroutineScope.launch(Dispatchers.Main) { val player = mediaController.await() playerRepository.connect( player = player, onClose = player::release ) } } @Provides @ActivityRetainedScoped fun playerRepository( playerRepositoryImpl: PlayerRepositoryImpl ): PlayerRepository = playerRepositoryImpl @Provides fun mediaItemExtrasMapper(): MediaItemExtrasMapper = MediaItemExtrasMapperNoopImpl @Provides @ActivityRetainedScoped fun mediaItemMapper(mediaItemExtrasMapper: MediaItemExtrasMapper): MediaItemMapper = MediaItemMapper(mediaItemExtrasMapper) }
apache-2.0
a5564f38c7a061af79dcd2789a823d08
35.528
98
0.729085
5.230241
false
false
false
false
Zhuinden/simple-stack
tutorials/tutorial-sample/src/main/java/com/zhuinden/simplestacktutorials/steps/step_7/features/login/LoginViewModel.kt
1
1926
package com.zhuinden.simplestacktutorials.steps.step_7.features.login import android.content.Context import com.zhuinden.eventemitter.EventEmitter import com.zhuinden.eventemitter.EventSource import com.zhuinden.simplestack.Backstack import com.zhuinden.simplestack.Bundleable import com.zhuinden.simplestack.History import com.zhuinden.simplestack.StateChange import com.zhuinden.simplestacktutorials.steps.step_7.AuthenticationManager import com.zhuinden.simplestacktutorials.steps.step_7.features.profile.ProfileKey import com.zhuinden.simplestacktutorials.steps.step_7.features.registration.EnterProfileDataKey import com.zhuinden.statebundle.StateBundle class LoginViewModel( private val appContext: Context, private val backstack: Backstack ) : Bundleable { private val eventEmitter: EventEmitter<String> = EventEmitter() val events: EventSource<String> get() = eventEmitter var username: String = "" private set var password: String = "" private set fun onUsernameChanged(username: String) { this.username = username } fun onPasswordChanged(password: String) { this.password = password } fun onLoginClicked() { if (username.isNotBlank() && password.isNotBlank()) { AuthenticationManager.saveRegistration(appContext) backstack.setHistory(History.of(ProfileKey()), StateChange.FORWARD) } else { eventEmitter.emit("Invalid username or password!") } } fun onRegisterClicked() { backstack.goTo(EnterProfileDataKey()) } override fun toBundle(): StateBundle = StateBundle().apply { putString("username", username) putString("password", password) } override fun fromBundle(bundle: StateBundle?) { bundle?.run { username = getString("username", "") password = getString("password", "") } } }
apache-2.0
64896c4156359d56e11adee89fe4eea2
31.661017
95
0.711319
4.851385
false
false
false
false
bachhuberdesign/deck-builder-gwent
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/cardviewer/CardRepository.kt
1
1792
package com.bachhuberdesign.deckbuildergwent.features.cardviewer import android.database.Cursor import com.bachhuberdesign.deckbuildergwent.features.shared.exception.CardException import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card import com.bachhuberdesign.deckbuildergwent.features.shared.model.Faction import com.bachhuberdesign.deckbuildergwent.inject.annotation.PersistedScope import com.squareup.sqlbrite.BriteDatabase import javax.inject.Inject /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ @PersistedScope class CardRepository @Inject constructor(val database: BriteDatabase) { companion object { @JvmStatic val TAG: String = CardRepository::class.java.name } fun getCardById(cardId: Int): Card { val cursor = database.query("SELECT * FROM ${Card.TABLE} WHERE ${Card.ID} = $cardId") cursor.use { cursor -> while (cursor.moveToNext()) { return Card.MAPPER.apply(cursor) } } throw CardException("Card $cardId not found.") } fun getAllCards(): List<Card> { val cursor = database.query("SELECT * FROM ${Card.TABLE}") val cards: MutableList<Card> = ArrayList() cursor.use { cursor -> while (cursor.moveToNext()) { cards.add(Card.MAPPER.apply(cursor)) } } if (cards.isEmpty()) { throw CardException("Problem loading cards from database.") } else { return cards } } fun getAllFactionAndNeutralCards(factionId: Int): Cursor { return database.query("SELECT * FROM ${Card.TABLE} " + "WHERE ${Card.FACTION} = $factionId " + "OR ${Card.FACTION} = ${Faction.NEUTRAL}") } }
apache-2.0
0b1bb2065ac402f5de7243a116b781e7
30.45614
94
0.645647
4.392157
false
false
false
false
Kotlin/dokka
plugins/javadoc/src/main/kotlin/org/jetbrains/dokka/javadoc/pages/JavadocPageNodes.kt
1
20227
package org.jetbrains.dokka.javadoc.pages import com.intellij.psi.PsiClass import org.jetbrains.dokka.Platform import org.jetbrains.dokka.analysis.DescriptorDocumentableSource import org.jetbrains.dokka.analysis.PsiDocumentableSource import org.jetbrains.dokka.analysis.from import org.jetbrains.dokka.base.renderers.sourceSets import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.* import org.jetbrains.dokka.model.properties.PropertyContainer import org.jetbrains.dokka.model.properties.WithExtraProperties import org.jetbrains.dokka.pages.* import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.resolve.DescriptorUtils.getClassDescriptorForType interface JavadocPageNode : ContentPage, WithDocumentables interface WithJavadocExtra<T : Documentable> : WithExtraProperties<T> { override fun withNewExtras(newExtras: PropertyContainer<T>): T = throw IllegalStateException("Merging extras is not applicable for javadoc") } fun interface WithNavigable { fun getAllNavigables(): List<NavigableJavadocNode> } interface WithBrief { val brief: List<ContentNode> } class JavadocModulePageNode( override val name: String, override val content: JavadocContentNode, override val children: List<PageNode>, override val dri: Set<DRI>, override val extra: PropertyContainer<DModule> = PropertyContainer.empty() ) : RootPageNode(), WithJavadocExtra<DModule>, NavigableJavadocNode, JavadocPageNode, ModulePage { override val documentables: List<Documentable> = emptyList() override val embeddedResources: List<String> = emptyList() override fun modified(name: String, children: List<PageNode>): RootPageNode = JavadocModulePageNode(name, content, children, dri, extra) override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ContentPage = JavadocModulePageNode(name, content as JavadocContentNode, children, dri, extra) override fun getId(): String = name override fun getDRI(): DRI = dri.first() } class JavadocPackagePageNode( override val name: String, override val content: JavadocContentNode, override val dri: Set<DRI>, override val documentables: List<Documentable> = emptyList(), override val children: List<PageNode> = emptyList(), override val embeddedResources: List<String> = listOf() ) : JavadocPageNode, WithNavigable, NavigableJavadocNode, PackagePage { init { require(name.isNotBlank()) { "Empty name is not supported " } } override fun getAllNavigables(): List<NavigableJavadocNode> = children.filterIsInstance<NavigableJavadocNode>().flatMap { if (it is WithNavigable) it.getAllNavigables() else listOf(it) } override fun modified( name: String, children: List<PageNode> ): PageNode = JavadocPackagePageNode( name, content, dri, documentables, children, embeddedResources ) override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ContentPage = JavadocPackagePageNode( name, content as JavadocContentNode, dri, documentables, children, embeddedResources ) override fun getId(): String = name override fun getDRI(): DRI = dri.first() } interface NavigableJavadocNode { fun getId(): String fun getDRI(): DRI } sealed class AnchorableJavadocNode(open val name: String, open val dri: DRI) : NavigableJavadocNode { override fun getId(): String = name override fun getDRI(): DRI = dri } data class JavadocEntryNode( override val dri: DRI, override val name: String, val signature: JavadocSignatureContentNode, override val brief: List<ContentNode>, override val extra: PropertyContainer<DEnumEntry> = PropertyContainer.empty() ) : AnchorableJavadocNode(name, dri), WithJavadocExtra<DEnumEntry>, WithBrief data class JavadocParameterNode( override val dri: DRI, override val name: String, val type: ContentNode, val description: List<ContentNode>, val typeBound: Bound, override val extra: PropertyContainer<DParameter> = PropertyContainer.empty() ) : AnchorableJavadocNode(name, dri), WithJavadocExtra<DParameter> data class JavadocPropertyNode( override val dri: DRI, override val name: String, val signature: JavadocSignatureContentNode, override val brief: List<ContentNode>, override val extra: PropertyContainer<DProperty> = PropertyContainer.empty() ) : AnchorableJavadocNode(name, dri), WithJavadocExtra<DProperty>, WithBrief data class JavadocFunctionNode( val signature: JavadocSignatureContentNode, override val brief: List<ContentNode>, val description: List<ContentNode>, val parameters: List<JavadocParameterNode>, override val name: String, override val dri: DRI, override val extra: PropertyContainer<DFunction> = PropertyContainer.empty() ) : AnchorableJavadocNode(name, dri), WithJavadocExtra<DFunction>, WithBrief { val isInherited: Boolean get() { val extra = extra[InheritedMember] return extra?.inheritedFrom?.keys?.firstOrNull { it.analysisPlatform == Platform.jvm }?.let { jvm -> extra.isInherited(jvm) } ?: false } } class JavadocClasslikePageNode( override val name: String, override val content: JavadocContentNode, override val dri: Set<DRI>, val signature: JavadocSignatureContentNode, val description: List<ContentNode>, val constructors: List<JavadocFunctionNode>, val methods: List<JavadocFunctionNode>, val entries: List<JavadocEntryNode>, val classlikes: List<JavadocClasslikePageNode>, val properties: List<JavadocPropertyNode>, override val brief: List<ContentNode>, override val documentables: List<Documentable> = emptyList(), override val children: List<PageNode> = emptyList(), override val embeddedResources: List<String> = listOf(), override val extra: PropertyContainer<DClasslike> = PropertyContainer.empty(), ) : JavadocPageNode, WithJavadocExtra<DClasslike>, NavigableJavadocNode, WithNavigable, WithBrief, ClasslikePage { override fun getAllNavigables(): List<NavigableJavadocNode> = methods + entries + classlikes.map { it.getAllNavigables() }.flatten() + this fun getAnchorables(): List<AnchorableJavadocNode> = constructors + methods + entries + properties val kind: String? = documentables.firstOrNull()?.kind() val packageName = dri.first().packageName override fun getId(): String = name override fun getDRI(): DRI = dri.first() override fun modified( name: String, children: List<PageNode> ): PageNode = JavadocClasslikePageNode( name, content, dri, signature, description, constructors, methods, entries, classlikes, properties, brief, documentables, children, embeddedResources, extra ) override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ContentPage = JavadocClasslikePageNode( name, content as JavadocContentNode, dri, signature, description, constructors, methods, entries, classlikes, properties, brief, documentables, children, embeddedResources, extra ) } class AllClassesPage(val classes: List<JavadocClasslikePageNode>) : JavadocPageNode { val classEntries = classes.map { LinkJavadocListEntry(it.name, it.dri, ContentKind.Classlikes, it.sourceSets().toSet()) } override val name: String = "All Classes" override val dri: Set<DRI> = setOf(DRI.topLevel) override val documentables: List<Documentable> = emptyList() override val embeddedResources: List<String> = emptyList() override val content: ContentNode = EmptyNode( DRI.topLevel, ContentKind.Classlikes, classes.flatMap { it.sourceSets() }.toSet() ) override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ContentPage = this override fun modified(name: String, children: List<PageNode>): PageNode = this override val children: List<PageNode> = emptyList() } class DeprecatedPage( val elements: Map<DeprecatedPageSection, Set<DeprecatedNode>>, sourceSet: Set<DisplaySourceSet> ) : JavadocPageNode { override val name: String = "deprecated" override val dri: Set<DRI> = setOf(DRI.topLevel) override val documentables: List<Documentable> = emptyList() override val children: List<PageNode> = emptyList() override val embeddedResources: List<String> = listOf() override val content: ContentNode = EmptyNode( DRI.topLevel, ContentKind.Main, sourceSet ) override fun modified( name: String, children: List<PageNode> ): PageNode = this override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ContentPage = this } class DeprecatedNode(val name: String, val address: DRI, val description: List<ContentNode>) { override fun equals(other: Any?): Boolean = (other as? DeprecatedNode)?.address == address override fun hashCode(): Int = address.hashCode() } enum class DeprecatedPageSection(val id: String, val caption: String, val header: String) { DeprecatedModules("module", "Modules", "Module"), DeprecatedInterfaces("interface", "Interfaces", "Interface"), DeprecatedClasses("class", "Classes", "Class"), DeprecatedExceptions("exception", "Exceptions", "Exceptions"), DeprecatedFields("field", "Fields", "Field"), DeprecatedMethods("method", "Methods", "Method"), DeprecatedConstructors("constructor", "Constructors", "Constructor"), DeprecatedEnums("enum", "Enums", "Enum"), DeprecatedEnumConstants("enum.constant", "Enum Constants", "Enum Constant"), DeprecatedForRemoval("forRemoval", "For Removal", "Element"); internal fun getPosition() = ordinal } class IndexPage( val id: Int, val elements: List<NavigableJavadocNode>, val keys: List<Char>, sourceSet: Set<DisplaySourceSet> ) : JavadocPageNode { override val name: String = "index-$id" override val dri: Set<DRI> = setOf(DRI.topLevel) override val documentables: List<Documentable> = emptyList() override val children: List<PageNode> = emptyList() override val embeddedResources: List<String> = listOf() val title: String = "${keys[id - 1]}-index" override val content: ContentNode = EmptyNode( DRI.topLevel, ContentKind.Classlikes, sourceSet ) override fun modified( name: String, children: List<PageNode> ): PageNode = this override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ContentPage = this } class TreeViewPage( override val name: String, val packages: List<JavadocPackagePageNode>?, val classes: List<JavadocClasslikePageNode>?, override val dri: Set<DRI>, override val documentables: List<Documentable> = emptyList(), val root: PageNode ) : JavadocPageNode { init { assert(packages == null || classes == null) assert(packages != null || classes != null) } private val childrenDocumentables = root.children.filterIsInstance<WithDocumentables>().flatMap { node -> getDocumentableEntries(node) }.groupBy({ it.first }) { it.second }.map { (l, r) -> l to r.first() }.toMap() private val descriptorMap = getDescriptorMap() private val inheritanceTuple = generateInheritanceTree() internal val classGraph = inheritanceTuple.first internal val interfaceGraph = inheritanceTuple.second override val children: List<PageNode> = emptyList() val title = when (documentables.firstOrNull()) { is DPackage -> "$name Class Hierarchy" else -> "All packages" } val kind = when (documentables.firstOrNull()) { is DPackage -> "package" else -> "main" } override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ContentPage = TreeViewPage( name, packages = children.filterIsInstance<JavadocPackagePageNode>().takeIf { it.isNotEmpty() }, classes = children.filterIsInstance<JavadocClasslikePageNode>().takeIf { it.isNotEmpty() }, dri = dri, documentables, root = root ) override fun modified(name: String, children: List<PageNode>): PageNode = TreeViewPage( name, packages = children.filterIsInstance<JavadocPackagePageNode>().takeIf { it.isNotEmpty() }, classes = children.filterIsInstance<JavadocClasslikePageNode>().takeIf { it.isNotEmpty() }, dri = dri, documentables, root = root ) override val embeddedResources: List<String> = emptyList() override val content: ContentNode = EmptyNode( DRI.topLevel, ContentKind.Classlikes, emptySet() ) private fun generateInheritanceTree(): Pair<List<InheritanceNode>, List<InheritanceNode>> { val mergeMap = mutableMapOf<DRI, InheritanceNode>() fun addToMap(info: InheritanceNode, map: MutableMap<DRI, InheritanceNode>) { if (map.containsKey(info.dri)) map.computeIfPresent(info.dri) { _, info2 -> info.copy(children = (info.children + info2.children).distinct()) }!!.children.forEach { addToMap(it, map) } else map[info.dri] = info } fun collect(dri: DRI): InheritanceNode = InheritanceNode( dri, mergeMap[dri]?.children.orEmpty().map { collect(it.dri) }, mergeMap[dri]?.interfaces.orEmpty(), mergeMap[dri]?.isInterface ?: false ) fun classTreeRec(node: InheritanceNode): List<InheritanceNode> = if (node.isInterface) { node.children.flatMap(::classTreeRec) } else { listOf(node.copy(children = node.children.flatMap(::classTreeRec))) } fun classTree(node: InheritanceNode) = classTreeRec(node).singleOrNull() fun interfaceTreeRec(node: InheritanceNode): List<InheritanceNode> = if (node.isInterface) { listOf(node.copy(children = node.children.filter { it.isInterface })) } else { node.children.flatMap(::interfaceTreeRec) } fun interfaceTree(node: InheritanceNode) = interfaceTreeRec(node).firstOrNull() // TODO.single() fun gatherPsiClasses(psi: PsiClass): List<Pair<PsiClass, List<PsiClass>>> = psi.supers.toList().let { l -> listOf(psi to l) + l.flatMap { gatherPsiClasses(it) } } val psiInheritanceTree = childrenDocumentables.flatMap { (_, v) -> (v as? WithSources)?.sources?.values.orEmpty() } .filterIsInstance<PsiDocumentableSource>().mapNotNull { it.psi as? PsiClass } .flatMap(::gatherPsiClasses) .flatMap { entry -> entry.second.map { it to entry.first } } .let { it + it.map { it.second to null } } .groupBy({ it.first }) { it.second } .map { it.key to it.value.filterNotNull().distinct() } .map { (k, v) -> InheritanceNode( DRI.from(k), v.map { InheritanceNode(DRI.from(it)) }, k.supers.filter { it.isInterface }.map { DRI.from(it) }, k.isInterface ) } val descriptorInheritanceTree = descriptorMap.flatMap { (_, v) -> v.typeConstructor.supertypes .map { getClassDescriptorForType(it) to v } } .let { it + it.map { it.second to null } } .groupBy({ it.first }) { it.second } .map { it.key to it.value.filterNotNull().distinct() } .map { (k, v) -> InheritanceNode( DRI.from(k), v.map { InheritanceNode(DRI.from(it)) }, k.typeConstructor.supertypes.map { getClassDescriptorForType(it) } .mapNotNull { cd -> cd.takeIf { it.kind == ClassKind.INTERFACE }?.let { DRI.from(it) } }, isInterface = k.kind == ClassKind.INTERFACE ) } descriptorInheritanceTree.forEach { addToMap(it, mergeMap) } psiInheritanceTree.forEach { addToMap(it, mergeMap) } val rootNodes = mergeMap.entries.filter { it.key.classNames in setOf("Any", "Object") //TODO: Probably should be matched by DRI, not just className }.map { collect(it.value.dri) } return rootNodes.let { Pair(it.mapNotNull(::classTree), it.mapNotNull(::interfaceTree)) } } private fun generateInterfaceGraph() { childrenDocumentables.values.filterIsInstance<DInterface>() } private fun getDocumentableEntries(node: WithDocumentables): List<Pair<DRI, Documentable>> = node.documentables.map { it.dri to it } + (node as? ContentPage)?.children?.filterIsInstance<WithDocumentables>() ?.flatMap(::getDocumentableEntries).orEmpty() private fun getDescriptorMap(): Map<DRI, ClassDescriptor> { val map: MutableMap<DRI, ClassDescriptor> = mutableMapOf() childrenDocumentables .mapNotNull { (k, v) -> v.descriptorForPlatform()?.let { k to it }?.also { (k, v) -> map[k] = v } }.map { it.second }.forEach { gatherSupertypes(it, map) } return map.toMap() } private fun gatherSupertypes(descriptor: ClassDescriptor, map: MutableMap<DRI, ClassDescriptor>) { map.putIfAbsent(DRI.from(descriptor), descriptor) descriptor.typeConstructor.supertypes.map { getClassDescriptorForType(it) } .forEach { gatherSupertypes(it, map) } } private fun Documentable?.descriptorForPlatform(platform: Platform = Platform.jvm) = (this as? WithSources).descriptorForPlatform(platform) private fun WithSources?.descriptorForPlatform(platform: Platform = Platform.jvm) = this?.let { it.sources.entries.find { it.key.analysisPlatform == platform }?.value?.let { it as? DescriptorDocumentableSource }?.descriptor as? ClassDescriptor } data class InheritanceNode( val dri: DRI, val children: List<InheritanceNode> = emptyList(), val interfaces: List<DRI> = emptyList(), val isInterface: Boolean = false ) { override fun equals(other: Any?): Boolean = other is InheritanceNode && other.dri == dri override fun hashCode(): Int = dri.hashCode() } } private fun Documentable.kind(): String? = when (this) { is DClass -> "class" is DEnum -> "enum" is DAnnotation -> "annotation" is DObject -> "object" is DInterface -> "interface" else -> null }
apache-2.0
fcb3d4eabb425347ac48ba70cf6cca0d
33.874138
155
0.642705
4.644546
false
false
false
false
HendraAnggrian/kota
kota/src/Intents.kt
1
729
@file:Suppress("NOTHING_TO_INLINE", "UNUSED") package kota import android.app.Dialog import android.app.Fragment import android.content.Context import android.content.Intent /** Returns true if one or more activities can handle this intent. */ inline fun Intent.isResolvable(context: Context): Boolean = resolveActivity(context.packageManager) != null /** Returns true if one or more activities can handle this intent. */ inline fun Intent.isResolvable(fragment: Fragment): Boolean = resolveActivity(fragment.activity.packageManager) != null /** Returns true if one or more activities can handle this intent. */ inline fun Intent.isResolvable(dialog: Dialog): Boolean = resolveActivity(dialog.context.packageManager) != null
apache-2.0
1493de003722d26eb3b99f5abf472c76
41.941176
119
0.788752
4.339286
false
false
false
false
vsch/idea-multimarkdown
src/test/java/com/vladsch/md/nav/util/TestLinkRef_from.kt
1
2182
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]>, all rights reserved. * * This code is private property of the copyright holder and cannot be used without * having obtained a license or prior written permission of the copyright holder. * * 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.vladsch.md.nav.util import org.junit.Test import kotlin.test.assertEquals class TestLinkRef_from { val exclusionMap: Map<String, String>? = null @Test fun test_explicitFromWiki_1() { val containingFile = FileRef("/Users/vlad/src/MarkdownTest/MardownTest.wiki/Home.md") val wikiLinkRef = WikiLinkRef(containingFile, "Home", null, null, false) val linkRef = LinkRef.from(wikiLinkRef, exclusionMap) assertEquals("#", linkRef.filePathWithAnchor) } @Test fun test_explicitFromWiki_2() { val containingFile = FileRef("/Users/vlad/src/MarkdownTest/MardownTest.wiki/Home.md") val wikiLinkRef = WikiLinkRef(containingFile, "Home", "#anchor", null, false) val linkRef = LinkRef.from(wikiLinkRef, null) assertEquals("#anchor", linkRef.filePathWithAnchor) } @Test fun test_explicitFromWiki_3() { val containingFile = FileRef("/Users/vlad/src/MarkdownTest/MardownTest.wiki/single-line-test.md") val wikiLinkRef = WikiLinkRef(containingFile, "Home", null, null, false) val linkRef = LinkRef.from(wikiLinkRef, null) assertEquals("Home", linkRef.filePathWithAnchor) } @Test fun test_explicitFromWiki_4() { val containingFile = FileRef("/Users/vlad/src/MarkdownTest/MardownTest.wiki/single-line-test.md") val wikiLinkRef = WikiLinkRef(containingFile, "Home", "#anchor", null, false) val linkRef = LinkRef.from(wikiLinkRef, null) assertEquals("Home#anchor", linkRef.filePathWithAnchor) } }
apache-2.0
d3b0446e2abba546ada8fd52e6da203a
35.366667
105
0.707608
4.00367
false
true
false
false
dexbleeker/hamersapp
hamersapp/src/main/java/nl/ecci/hamers/ui/activities/NewBeerActivity.kt
1
2372
package nl.ecci.hamers.ui.activities import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.DatePicker import com.android.volley.VolleyError import kotlinx.android.synthetic.main.activity_general.* import kotlinx.android.synthetic.main.stub_new_beer.* import nl.ecci.hamers.R import nl.ecci.hamers.data.Loader import nl.ecci.hamers.data.PostCallback import nl.ecci.hamers.models.Beer import nl.ecci.hamers.utils.DataUtils import org.json.JSONException import org.json.JSONObject class NewBeerActivity : HamersNewItemActivity() { private var beerID: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initToolbar() stub.layoutResource = R.layout.stub_new_beer stub.inflate() beerID = intent.getIntExtra(Beer.BEER, -1) if (beerID != -1) { val beer = DataUtils.getBeer(this, beerID) beer_name.setText(beer.name) beer_picture.setText(beer.imageURL) beer_soort.setText(beer.kind) beer_percentage.setText(beer.percentage) beer_brewer.setText(beer.brewer) beer_country.setText(beer.country) title = "Wijzig " + beer.name } } override fun postItem() { var percentage = beer_percentage.text.toString() if (!percentage.contains("%")) { percentage += "%" } val body = JSONObject() try { body.put("name", beer_name!!.text.toString()) body.put("picture", beer_picture.text.toString()) body.put("percentage", percentage) body.put("country", beer_country.text.toString()) body.put("brewer", beer_brewer.text.toString()) body.put("soort", beer_soort.text.toString()) } catch (ignored: JSONException) { } Loader.postOrPatchData(this, Loader.BEERURL, body, beerID, object : PostCallback { override fun onSuccess(response: JSONObject) { setResult(Activity.RESULT_OK, Intent()) finish() } override fun onError(error: VolleyError) { disableLoadingAnimation() } }) } override fun onDateSet(datePicker: DatePicker?, year: Int, month: Int, day: Int) { } }
gpl-3.0
b6d847595642b56c1fe74a133604669e
30.223684
90
0.629005
4.190813
false
false
false
false
xiaopansky/Sketch
sample/src/main/java/me/panpf/sketch/sample/event/EventRegistrar.kt
1
5489
@file:Suppress("DEPRECATION") package me.panpf.sketch.sample.event import android.annotation.TargetApi import android.app.Activity import android.app.Application import android.os.Build import android.os.Bundle import android.view.View import androidx.annotation.RequiresApi import org.greenrobot.eventbus.EventBus import java.lang.annotation.Inherited import java.util.* import android.app.Fragment as OriginFragment import android.app.FragmentManager as OriginFragmentManager import androidx.fragment.app.Fragment as SupportFragment import androidx.fragment.app.FragmentManager as SupportFragmentManager @Target(AnnotationTarget.CLASS, AnnotationTarget.FILE) @Retention(AnnotationRetention.RUNTIME) @Inherited annotation class RegisterEvent /** * EventBus 事件注册器,只需给 Activity 或 Fragment 加上 RegisterEvent 注解即可自动执行 EventBus.getDefault().register() 和 EventBus.getDefault().unregister() */ @RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @TargetApi(Build.VERSION_CODES.O) class ActivityEventRegistrar : Application.ActivityLifecycleCallbacks { private val supportFragmentEventRegister = SupportFragmentEventRegistrar() private var originFragmentEventRegistrar: Any? = null private val activityCodes = LinkedList<String>() override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { activity ?: return // onActivityCreated 会先于子类的 onCreate() 执行,这时候子类尚未初始化完成,如果子类的事件方法需要依赖 onCreate() 初始化,比如 view, // 那么在这里注册事件的话,如果子类立马就收到事件就会因依赖未初始化而崩溃 if (activity is androidx.fragment.app.FragmentActivity) { activity.supportFragmentManager.registerFragmentLifecycleCallbacks(supportFragmentEventRegister, true) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val registrar = if (originFragmentEventRegistrar == null) { val newRegistrar = OriginFragmentEventRegistrar() originFragmentEventRegistrar = newRegistrar newRegistrar } else { originFragmentEventRegistrar as OriginFragmentEventRegistrar } activity.fragmentManager.registerFragmentLifecycleCallbacks(registrar, true) } } override fun onActivityStarted(activity: Activity?) { activity?.let { val hashCode = it.hashCode().toString() if (!activityCodes.contains(hashCode)) { activityCodes.add(hashCode) if (it.javaClass.isAnnotationPresent(RegisterEvent::class.java)) { EventBus.getDefault().register(activity) } } } } override fun onActivityResumed(activity: Activity?) { } override fun onActivityPaused(activity: Activity?) { } override fun onActivityStopped(activity: Activity?) { } override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { } override fun onActivityDestroyed(activity: Activity?) { activity ?: return activityCodes.remove(activity.hashCode().toString()) if (activity.javaClass.isAnnotationPresent(RegisterEvent::class.java)) { EventBus.getDefault().unregister(activity) } if (activity is androidx.fragment.app.FragmentActivity) { activity.supportFragmentManager.unregisterFragmentLifecycleCallbacks(supportFragmentEventRegister) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (originFragmentEventRegistrar != null) { activity.fragmentManager.unregisterFragmentLifecycleCallbacks(originFragmentEventRegistrar as OriginFragmentEventRegistrar) } } } } @RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @TargetApi(Build.VERSION_CODES.O) class SupportFragmentEventRegistrar : SupportFragmentManager.FragmentLifecycleCallbacks() { override fun onFragmentViewCreated(fm: SupportFragmentManager, f: SupportFragment, v: View, savedInstanceState: Bundle?) { super.onFragmentViewCreated(fm, f, v, savedInstanceState) if (f.javaClass.isAnnotationPresent(RegisterEvent::class.java)) { EventBus.getDefault().register(f) } } override fun onFragmentViewDestroyed(fm: SupportFragmentManager, f: SupportFragment) { super.onFragmentViewDestroyed(fm, f) // todo 这个方法不执行 if (f.javaClass.isAnnotationPresent(RegisterEvent::class.java)) { EventBus.getDefault().unregister(f) } } } @Suppress("DEPRECATION") @RequiresApi(Build.VERSION_CODES.O) class OriginFragmentEventRegistrar : OriginFragmentManager.FragmentLifecycleCallbacks() { override fun onFragmentViewCreated(fm: OriginFragmentManager?, f: OriginFragment?, v: View?, savedInstanceState: Bundle?) { super.onFragmentViewCreated(fm, f, v, savedInstanceState) if (f?.javaClass?.isAnnotationPresent(RegisterEvent::class.java) == true) { EventBus.getDefault().register(f) } } override fun onFragmentViewDestroyed(fm: OriginFragmentManager?, f: OriginFragment?) { super.onFragmentViewDestroyed(fm, f) if (f?.javaClass?.isAnnotationPresent(RegisterEvent::class.java) == true) { EventBus.getDefault().unregister(f) } } }
apache-2.0
143ad9814bad6c87d8d7c224c0703b36
36.985612
139
0.715287
4.869926
false
false
false
false
infinum/android_dbinspector
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/content/shared/ContentViewHolder.kt
1
3000
package com.infinum.dbinspector.ui.content.shared import android.text.TextUtils import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.infinum.dbinspector.R import com.infinum.dbinspector.databinding.DbinspectorItemCellBinding import com.infinum.dbinspector.domain.shared.models.Cell import com.infinum.dbinspector.domain.shared.models.TruncateMode internal class ContentViewHolder( private val viewBinding: DbinspectorItemCellBinding ) : RecyclerView.ViewHolder(viewBinding.root) { fun bind( item: Cell?, row: Int, onCellClicked: ((Cell) -> Unit)? ) { item?.let { cell -> bindValue(cell) bindRoot(row, cell, onCellClicked) } ?: bindNullValue() } fun unbind() { with(viewBinding) { this.valueView.maxLines = Int.MAX_VALUE this.valueView.ellipsize = null this.truncatedIndicator.isVisible = false this.root.setBackgroundColor(ContextCompat.getColor(this.root.context, android.R.color.transparent)) this.root.setOnClickListener(null) } } private fun bindRoot( row: Int, cell: Cell, onCellClicked: ((Cell) -> Unit)? ) = with(viewBinding) { this.root.setBackgroundColor( ContextCompat.getColor( this.root.context, if (row % 2 == 0) { R.color.dbinspector_alternate_row_background } else { android.R.color.transparent } ) ) this.root.setOnClickListener { onCellClicked?.invoke(cell) } } private fun bindValue(cell: Cell) = with(viewBinding) { this.valueView.maxLines = cell.linesShown this.valueView.ellipsize = cell.truncateMode .takeIf { cell.linesShown != Int.MAX_VALUE } ?.let { when (it) { TruncateMode.START -> TextUtils.TruncateAt.START TruncateMode.MIDDLE -> TextUtils.TruncateAt.MIDDLE TruncateMode.END -> TextUtils.TruncateAt.END else -> TextUtils.TruncateAt.END } } this.valueView.text = cell.text this.truncatedIndicator.isVisible = cell.linesShown != Int.MAX_VALUE && cell.data != null } private fun bindNullValue() = with(viewBinding) { this.valueView.maxLines = Int.MAX_VALUE this.valueView.ellipsize = null this.valueView.text = null this.truncatedIndicator.isVisible = false this.root.background = ContextCompat.getDrawable(this.root.context, R.drawable.dbinspector_placeholder) this.root.setOnClickListener(null) } }
apache-2.0
1fc5554b0a62bd0711d6ad34878a4c62
34.714286
115
0.584667
4.846527
false
false
false
false
sealedtx/coursework-db-kotlin
app/src/main/java/coursework/kiulian/com/freerealestate/model/filters/AdvFilter.kt
1
3173
package coursework.kiulian.com.freerealestate.model.filters import com.raizlabs.android.dbflow.kotlinextensions.or import com.raizlabs.android.dbflow.sql.language.SQLOperator import coursework.kiulian.com.freerealestate.model.dbmodels.* import java.util.* /** * Created by User on 13.04.2017. */ class AdvFilter(var adv: AdvEntity? = null, var price: IntRange? = null, var freeDates: ClosedRange<Date>? = null, var createdAt: ClosedRange<Date>? = null, var confirmed: Boolean = false, var withPhone: Boolean = false, var withEmail: Boolean = false, var withPhoto: Boolean = false, var authorId: Int? = null) : Filter { override fun getConditions(): Array<SQLOperator> { val list = ArrayList<SQLOperator>() authorId?.let { list.add(ContactsEntity_Table.id.withTable().eq(it)) } adv?.let { it.region.city?.let { list.add(RegionEntity_Table.city.eq(it)) } it.region.region?.let { list.add(RegionEntity_Table.region.eq(it)) } it.house.district?.let { list.add(HouseEntity_Table.district.eq(it)) } it.region.city?.let { list.add(RegionEntity_Table.city.eq(it)) } it.house.food?.let { list.add(HouseEntity_Table.food.eq(it)) } it.house.type?.let { list.add(HouseEntity_Table.type.eq(it)) } it.house.price.payment?.let { list.add(PriceEntity_Table.payment.eq(it).or(PriceEntity_Table.payment.eq(Payment.ANY))) } it.house.price.discount?.let { list.add(PriceEntity_Table.discount.eq(it)) } list.add(HouseEntity_Table.beds.greaterThanOrEq(it.house.beds)) list.add(HouseEntity_Table.guests.greaterThanOrEq(it.house.guests)) if (it.house.facility.pets) list.add(FacilityEntity_Table.pets.eq(it.house.facility.pets)) if (it.house.facility.smoking) list.add(FacilityEntity_Table.smoking.eq(it.house.facility.smoking)) } price?.let { list.add(PriceEntity_Table.price.greaterThanOrEq(it.start)) list.add(PriceEntity_Table.price.lessThanOrEq(it.endInclusive)) } freeDates?.let { list.add(DateEntity_Table.start.invertProperty().lessThanOrEq(it.start.time)) list.add(DateEntity_Table.end.invertProperty().greaterThanOrEq(it.endInclusive.time)) } createdAt?.let { list.add(AdvEntity_Table.createdAt.invertProperty().greaterThanOrEq(it.start.time)) list.add(AdvEntity_Table.createdAt.invertProperty().lessThanOrEq(it.endInclusive.time)) } if (confirmed) list.add(ContactsEntity_Table.confirmation.withTable().eq(Confirmation.CONFIRMED)) if (withPhoto) list.add(AdvEntity_Table.image.withTable().isNotNull) if (withEmail) list.add(ContactsEntity_Table.email.withTable().isNotNull) if (withPhone) list.add(ContactsEntity_Table.phone.withTable().isNotNull) return list.toTypedArray() } }
bsd-2-clause
0e3bd60484565bbecda6d888dc0d198b
45
104
0.630003
3.827503
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/entities/GamePlayerPollEntity.kt
1
1153
package com.boardgamegeek.entities data class GamePlayerPollEntity(val results: List<GamePlayerPollResultsEntity>) { val totalVotes: Int = results.maxByOrNull { it.totalVotes }?.totalVotes ?: 0 val bestCounts: Set<Int> by lazy { results.filter { it.calculatedRecommendation == GamePlayerPollResultsEntity.BEST }.map { it.playerCount.toIntOrNull() ?: maxPlayerCount }.sorted().toSet() } private val recommendedCounts: Set<Int> by lazy { results.filter { it.calculatedRecommendation == GamePlayerPollResultsEntity.RECOMMENDED }.map { it.playerCount.toIntOrNull() ?: maxPlayerCount }.sorted().toSet() } val notRecommendedCounts: Set<Int> by lazy { results.filter { it.calculatedRecommendation == GamePlayerPollResultsEntity.NOT_RECOMMENDED }.map { it.playerCount.toIntOrNull() ?: maxPlayerCount }.sorted().toSet() } val recommendedAndBestCounts: Set<Int> by lazy { (bestCounts + recommendedCounts).sorted().toSet() } companion object { const val maxPlayerCount = 100 const val separator = "|" } }
gpl-3.0
d13ab9cf6a8ce3d18b2e7592859779e6
33.939394
107
0.671292
4.668016
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/session/ui/SessionsAdapter.kt
1
2917
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.session.ui import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import android.widget.TextView import mozilla.components.browser.session.Session import mozilla.components.browser.session.SessionManager import org.mozilla.focus.ext.requireComponents /** * Adapter implementation to show a list of active browsing sessions and an "erase" button at the end. */ class SessionsAdapter internal constructor( private val fragment: SessionsSheetFragment, private var sessions: List<Session> = emptyList() ) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), SessionManager.Observer { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) return when (viewType) { EraseViewHolder.LAYOUT_ID -> EraseViewHolder( fragment, inflater.inflate(EraseViewHolder.LAYOUT_ID, parent, false) ) SessionViewHolder.LAYOUT_ID -> SessionViewHolder( fragment, inflater.inflate(SessionViewHolder.LAYOUT_ID, parent, false) as TextView ) else -> throw IllegalStateException("Unknown viewType") } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder.itemViewType) { EraseViewHolder.LAYOUT_ID -> { /* Nothing to do */ } SessionViewHolder.LAYOUT_ID -> (holder as SessionViewHolder).bind(sessions[position]) else -> throw IllegalStateException("Unknown viewType") } } override fun getItemViewType(position: Int): Int { return if (isErasePosition(position)) { EraseViewHolder.LAYOUT_ID } else { SessionViewHolder.LAYOUT_ID } } private fun isErasePosition(position: Int): Boolean { return position == sessions.size } override fun getItemCount(): Int { return sessions.size + 1 } override fun onSessionAdded(session: Session) { onUpdate(fragment.requireComponents.sessionManager.sessions) } override fun onSessionRemoved(session: Session) { onUpdate(fragment.requireComponents.sessionManager.sessions) } override fun onSessionSelected(session: Session) { onUpdate(fragment.requireComponents.sessionManager.sessions) } override fun onAllSessionsRemoved() { onUpdate(fragment.requireComponents.sessionManager.sessions) } private fun onUpdate(sessions: List<Session>) { this.sessions = sessions notifyDataSetChanged() } }
mpl-2.0
d2daed9228a3dd7915b30c4342bf3232
34.573171
102
0.688036
4.886097
false
false
false
false
Kotlin/kotlinx.serialization
formats/json/commonMain/src/kotlinx/serialization/json/internal/lexer/JsonLexer.kt
1
6160
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER") package kotlinx.serialization.json.internal @PublishedApi internal const val BATCH_SIZE: Int = 16 * 1024 private const val DEFAULT_THRESHOLD = 128 /** * For some reason this hand-rolled implementation is faster than * fun ArrayAsSequence(s: CharArray): CharSequence = java.nio.CharBuffer.wrap(s, 0, length) */ internal class ArrayAsSequence(val buffer: CharArray) : CharSequence { override var length: Int = buffer.size override fun get(index: Int): Char = buffer[index] override fun subSequence(startIndex: Int, endIndex: Int): CharSequence { return buffer.concatToString(startIndex, minOf(endIndex, length)) } fun substring(startIndex: Int, endIndex: Int): String { return buffer.concatToString(startIndex, minOf(endIndex, length)) } fun trim(newSize: Int) { length = minOf(buffer.size, newSize) } } internal class ReaderJsonLexer( private val reader: SerialReader, charsBuffer: CharArray = CharArray(BATCH_SIZE) ) : AbstractJsonLexer() { private var threshold: Int = DEFAULT_THRESHOLD // chars override val source: ArrayAsSequence = ArrayAsSequence(charsBuffer) init { preload(0) } override fun tryConsumeComma(): Boolean { val current = skipWhitespaces() if (current >= source.length || current == -1) return false if (source[current] == ',') { ++currentPosition return true } return false } override fun canConsumeValue(): Boolean { ensureHaveChars() var current = currentPosition while (true) { current = prefetchOrEof(current) if (current == -1) break // could be inline function but KT-1436 val c = source[current] // Inlined skipWhitespaces without field spill and nested loop. Also faster then char2TokenClass if (c == ' ' || c == '\n' || c == '\r' || c == '\t') { ++current continue } currentPosition = current return isValidValueStart(c) } currentPosition = current return false } private fun preload(unprocessedCount: Int) { val buffer = source.buffer if (unprocessedCount != 0) { buffer.copyInto(buffer, 0, currentPosition, currentPosition + unprocessedCount) } var filledCount = unprocessedCount val sizeTotal = source.length while (filledCount != sizeTotal) { val actual = reader.read(buffer, filledCount, sizeTotal - filledCount) if (actual == -1) { // EOF, resizing the array so it matches input size source.trim(filledCount) threshold = -1 break } filledCount += actual } currentPosition = 0 } override fun prefetchOrEof(position: Int): Int { if (position < source.length) return position currentPosition = position ensureHaveChars() if (currentPosition != 0 || source.isEmpty()) return -1 // if something was loaded, then it would be zero. return 0 } override fun consumeNextToken(): Byte { ensureHaveChars() val source = source var cpos = currentPosition while (true) { cpos = prefetchOrEof(cpos) if (cpos == -1) break val ch = source[cpos++] return when (val tc = charToTokenClass(ch)) { TC_WHITESPACE -> continue else -> { currentPosition = cpos tc } } } currentPosition = cpos return TC_EOF } override fun ensureHaveChars() { val cur = currentPosition val oldSize = source.length val spaceLeft = oldSize - cur if (spaceLeft > threshold) return // warning: current position is not updated during string consumption // resizing preload(spaceLeft) } override fun consumeKeyString(): String { /* * For strings we assume that escaped symbols are rather an exception, so firstly * we optimistically scan for closing quote via intrinsified and blazing-fast 'indexOf', * than do our pessimistic check for backslash and fallback to slow-path if necessary. */ consumeNextToken(STRING) var current = currentPosition val closingQuote = indexOf('"', current) if (closingQuote == -1) { current = prefetchOrEof(current) if (current == -1) fail(TC_STRING) // it's also possible just to resize buffer, // instead of falling back to slow path, // not sure what is better else return consumeString(source, currentPosition, current) } // Now we _optimistically_ know where the string ends (it might have been an escaped quote) for (i in current until closingQuote) { // Encountered escape sequence, should fallback to "slow" path and symmbolic scanning if (source[i] == STRING_ESC) { return consumeString(source, currentPosition, i) } } this.currentPosition = closingQuote + 1 return substring(current, closingQuote) } override fun indexOf(char: Char, startPos: Int): Int { val src = source for (i in startPos until src.length) { if (src[i] == char) return i } return -1 } override fun substring(startPos: Int, endPos: Int): String { return source.substring(startPos, endPos) } override fun appendRange(fromIndex: Int, toIndex: Int) { escapedString.appendRange(source.buffer, fromIndex, toIndex) } // Can be carefully implemented but postponed for now override fun consumeLeadingMatchingValue(keyToMatch: String, isLenient: Boolean): String? = null }
apache-2.0
897ebd8cc40f0cedf9e4fc6560d53762
33.222222
114
0.603247
4.723926
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/service/internal/testing/EventGroupMetadataDescriptorsServiceTest.kt
1
12643
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.service.internal.testing import com.google.common.truth.Truth.assertThat import com.google.common.truth.extensions.proto.ProtoTruth.assertThat import com.google.protobuf.DescriptorProtos.FileDescriptorSet import io.grpc.Status import io.grpc.StatusRuntimeException import java.time.Clock import kotlin.random.Random import kotlin.test.assertFailsWith import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.api.Version import org.wfanet.measurement.common.identity.IdGenerator import org.wfanet.measurement.common.identity.RandomIdGenerator import org.wfanet.measurement.internal.kingdom.DataProvidersGrpcKt.DataProvidersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.EventGroupMetadataDescriptor import org.wfanet.measurement.internal.kingdom.EventGroupMetadataDescriptorKt.details import org.wfanet.measurement.internal.kingdom.EventGroupMetadataDescriptorsGrpcKt.EventGroupMetadataDescriptorsCoroutineImplBase import org.wfanet.measurement.internal.kingdom.StreamEventGroupMetadataDescriptorsRequestKt.filter import org.wfanet.measurement.internal.kingdom.copy import org.wfanet.measurement.internal.kingdom.eventGroupMetadataDescriptor import org.wfanet.measurement.internal.kingdom.getEventGroupMetadataDescriptorRequest import org.wfanet.measurement.internal.kingdom.streamEventGroupMetadataDescriptorsRequest import org.wfanet.measurement.internal.kingdom.updateEventGroupMetadataDescriptorRequest private const val RANDOM_SEED = 1 private val DETAILS = details { apiVersion = Version.V2_ALPHA.string descriptorSet = FileDescriptorSet.getDefaultInstance() } @RunWith(JUnit4::class) abstract class EventGroupMetadataDescriptorsServiceTest< T : EventGroupMetadataDescriptorsCoroutineImplBase> { private val testClock: Clock = Clock.systemUTC() protected val idGenerator = RandomIdGenerator(testClock, Random(RANDOM_SEED)) private val population = Population(testClock, idGenerator) private lateinit var eventGroupMetadataDescriptorService: T protected lateinit var dataProvidersService: DataProvidersCoroutineImplBase private set protected abstract fun newServices( idGenerator: IdGenerator ): EventGroupMetadataDescriptorsAndHelperServices<T> @Before fun initServices() { val services = newServices(idGenerator) eventGroupMetadataDescriptorService = services.eventGroupMetadataDescriptorService dataProvidersService = services.dataProvidersService } @Test fun `getEventGroupMetadataDescriptor succeeds`() = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val eventGroupMetadataDescriptor = eventGroupMetadataDescriptor { this.externalDataProviderId = externalDataProviderId details = DETAILS } val createdDescriptor = eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor ) val eventGroupMetadataDescriptorRead = eventGroupMetadataDescriptorService.getEventGroupMetadataDescriptor( getEventGroupMetadataDescriptorRequest { this.externalDataProviderId = externalDataProviderId externalEventGroupMetadataDescriptorId = createdDescriptor.externalEventGroupMetadataDescriptorId } ) assertThat(eventGroupMetadataDescriptorRead).isEqualTo(createdDescriptor) } @Test fun `getEventGroupMetadataDescriptor fails for missing EventGroupMetadataDescriptor`() = runBlocking { val exception = assertFailsWith<StatusRuntimeException> { eventGroupMetadataDescriptorService.getEventGroupMetadataDescriptor( getEventGroupMetadataDescriptorRequest { externalEventGroupMetadataDescriptorId = 1L } ) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception) .hasMessageThat() .contains("NOT_FOUND: EventGroupMetadataDescriptor not found") } @Test fun `createEventGroupMetadataDescriptor succeeds`() = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val eventGroupMetadataDescriptor = eventGroupMetadataDescriptor { this.externalDataProviderId = externalDataProviderId details = DETAILS } val createdEventGroupMetadataDescriptor = eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor ) assertThat(createdEventGroupMetadataDescriptor) .ignoringFields( EventGroupMetadataDescriptor.EXTERNAL_EVENT_GROUP_METADATA_DESCRIPTOR_ID_FIELD_NUMBER ) .isEqualTo(eventGroupMetadataDescriptor) assertThat(createdEventGroupMetadataDescriptor.externalEventGroupMetadataDescriptorId) .isGreaterThan(0) } @Test fun `createEventGroupMetadataDescriptor fails for missing data provider`() = runBlocking { val eventGroupMetadataDescriptor = eventGroupMetadataDescriptor { this.externalDataProviderId = 1L details = DETAILS } val exception = assertFailsWith<StatusRuntimeException> { eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor ) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception).hasMessageThat().contains("NOT_FOUND: DataProvider not found") } @Test fun `createEventGroupMetadataDescriptor returns created Descriptor for existing external ID`() = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val createdEventGroupMetadataDescriptor = eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor { this.externalDataProviderId = externalDataProviderId details = DETAILS } ) val secondCreatedEventGroupMetadataDescriptorAttempt = eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor { this.externalDataProviderId = externalDataProviderId externalEventGroupMetadataDescriptorId = createdEventGroupMetadataDescriptor.externalEventGroupMetadataDescriptorId details = DETAILS } ) assertThat(secondCreatedEventGroupMetadataDescriptorAttempt) .isEqualTo(createdEventGroupMetadataDescriptor) } @Test fun `updateEventGroupMetadataDescriptor fails for missing EventGroupMetadataDescriptor`() = runBlocking { val exception = assertFailsWith<StatusRuntimeException> { eventGroupMetadataDescriptorService.updateEventGroupMetadataDescriptor( updateEventGroupMetadataDescriptorRequest { this.eventGroupMetadataDescriptor = eventGroupMetadataDescriptor { this.externalDataProviderId = 1L details = DETAILS } } ) } assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT) assertThat(exception) .hasMessageThat() .contains("ExternalEventGroupMetadataDescriptorId unspecified") } @Test fun `updateEventGroupMetadataDescriptor succeeds`(): Unit = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val eventGroupMetadataDescriptor = eventGroupMetadataDescriptor { this.externalDataProviderId = externalDataProviderId details = DETAILS } val createdEventGroupMetadataDescriptor = eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor ) val modifyEventGroupMetadataDescriptor = createdEventGroupMetadataDescriptor.copy { details = details { apiVersion = "alternate version" } } val updatedEventGroupMetadataDescriptor = eventGroupMetadataDescriptorService.updateEventGroupMetadataDescriptor( updateEventGroupMetadataDescriptorRequest { this.eventGroupMetadataDescriptor = modifyEventGroupMetadataDescriptor } ) assertThat(updatedEventGroupMetadataDescriptor) .isEqualTo( createdEventGroupMetadataDescriptor .toBuilder() .also { it.details = updatedEventGroupMetadataDescriptor.details } .build() ) } @Test fun `streamEventGroupMetadataDescriptors returns all descriptors in order`(): Unit = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val eventGroupMetadataDescriptor1 = eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor { this.externalDataProviderId = externalDataProviderId details = DETAILS } ) val eventGroupMetadataDescriptor2 = eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor { this.externalDataProviderId = externalDataProviderId details = DETAILS } ) val eventGroupMetadataDescriptors: List<EventGroupMetadataDescriptor> = eventGroupMetadataDescriptorService .streamEventGroupMetadataDescriptors( streamEventGroupMetadataDescriptorsRequest { filter = filter { this.externalDataProviderId = externalDataProviderId } } ) .toList() if ( eventGroupMetadataDescriptor1.externalEventGroupMetadataDescriptorId < eventGroupMetadataDescriptor2.externalEventGroupMetadataDescriptorId ) { assertThat(eventGroupMetadataDescriptors) .comparingExpectedFieldsOnly() .containsExactly(eventGroupMetadataDescriptor1, eventGroupMetadataDescriptor2) .inOrder() } else { assertThat(eventGroupMetadataDescriptors) .comparingExpectedFieldsOnly() .containsExactly(eventGroupMetadataDescriptor2, eventGroupMetadataDescriptor1) .inOrder() } } @Test fun `streamEventGroupMetadataDescriptors respects externalEventGroupMetadataDescriptorIds`(): Unit = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor { this.externalDataProviderId = externalDataProviderId details = DETAILS } ) val eventGroupMetadataDescriptor2 = eventGroupMetadataDescriptorService.createEventGroupMetadataDescriptor( eventGroupMetadataDescriptor { this.externalDataProviderId = externalDataProviderId details = DETAILS } ) val eventGroupMetadataDescriptors: List<EventGroupMetadataDescriptor> = eventGroupMetadataDescriptorService .streamEventGroupMetadataDescriptors( streamEventGroupMetadataDescriptorsRequest { filter = filter { this.externalDataProviderId = externalDataProviderId this.externalEventGroupMetadataDescriptorIds += eventGroupMetadataDescriptor2.externalEventGroupMetadataDescriptorId } } ) .toList() assertThat(eventGroupMetadataDescriptors) .comparingExpectedFieldsOnly() .containsExactly(eventGroupMetadataDescriptor2) } } data class EventGroupMetadataDescriptorsAndHelperServices< T : EventGroupMetadataDescriptorsCoroutineImplBase>( val eventGroupMetadataDescriptorService: T, val dataProvidersService: DataProvidersCoroutineImplBase, )
apache-2.0
3bab2d4c4b1695a7f893beb6141ddaf8
36.853293
129
0.766037
5.533042
false
false
false
false
actorapp/actor-bots
actor-bots-example/src/main/java/im/actor/bots/ExampleBots.kt
1
1810
package im.actor.bots import im.actor.bots.framework.MagicBotFork import im.actor.bots.framework.MagicBotMessage import im.actor.bots.framework.MagicBotTextMessage import im.actor.bots.framework.MagicForkScope import im.actor.bots.framework.persistence.MagicPersistentBot import im.actor.bots.framework.stateful.MagicStatefulBot import im.actor.bots.framework.stateful.isText import im.actor.bots.framework.stateful.oneShot import im.actor.bots.framework.stateful.text import org.json.JSONObject /** * Very simple echo bot that forwards message */ class EchoBot(scope: MagicForkScope) : MagicBotFork(scope) { override fun onMessage(message: MagicBotMessage) { when (message) { is MagicBotTextMessage -> { sendText("Received: ${message.text}") } } } } class EchoStatefulBot(scope: MagicForkScope) : MagicStatefulBot(scope) { override fun configure() { // Configure group behaviour ownNickname = "echo" enableInGroups = true onlyWithMentions = false oneShot("/start") { sendText("Hi, i'm simple echo bot, send me text and i'll send it back.") } oneShot("default") { if (isText) { sendText(text) } } } } /** * Echo persistent bot that keeps it's state between restart */ class EchoPersistentBot(scope: MagicForkScope) : MagicPersistentBot(scope) { var receivedCount: Int = 0 override fun onRestoreState(state: JSONObject) { receivedCount = state.optInt("counter", 0) } override fun onMessage(message: MagicBotMessage) { sendText("Received ${receivedCount++} messages") } override fun onSaveState(state: JSONObject) { state.put("counter", receivedCount) } }
apache-2.0
3e5b42391cf9987bb59533e9ad57634c
26.029851
84
0.671823
4.170507
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/utils/logging/AppLogger.kt
1
2591
package com.duopoints.android.utils.logging import android.content.Context import android.util.Log import com.crashlytics.android.Crashlytics import java.util.* // The lowest level that will be logged private var mLogLevel = LogLevel.ERROR private var mTag: String = "DuoPoint" private var mReportCrashes = false fun Context.log(logLevel: LogLevel, message: String): Context { javaClass.log(logLevel, message) return this } fun Context.log(logLevel: LogLevel, throwable: Throwable): Context { javaClass.log(logLevel, throwable) return this } fun Class<*>.log(logLevel: LogLevel, throwable: Throwable): Class<*> { simpleName.log(logLevel, throwable) return this } fun Class<*>.log(logLevel: LogLevel, message: String): Class<*> { simpleName.log(logLevel, message) return this } fun String.log(logLevel: LogLevel, throwable: Throwable): String { let { performLogging(logLevel, it, throwable) } return this } fun String.log(logLevel: LogLevel, message: String): String { let { performLogging(logLevel, it, message) } return this } /******************* * CLASS FUNCTIONS *******************/ /** * Logs a throwable. * * @param logLevel The [LogLevel] to log at. * @param token The token. * @param throwable The throwable to be logged. */ private fun performLogging(logLevel: LogLevel, token: String, throwable: Throwable) { if (logLevel.value >= mLogLevel.value) { if (logLevel.value >= Log.ERROR) { Log.e(mTag, String.format(Locale.ENGLISH, "%s[-20%s]:--", logLevel.key, token)) throwable.printStackTrace() Log.e(mTag, String.format(Locale.ENGLISH, "--%s[-20%s]", logLevel.key, token)) } else { Log.d(mTag, String.format(Locale.ENGLISH, "%s[-20%s]:--", logLevel.key, token)) throwable.printStackTrace() Log.d(mTag, String.format(Locale.ENGLISH, "--%s[-20%s]", logLevel.key, token)) } } if (mReportCrashes) Crashlytics.logException(throwable) } /** * Logs a message. * * @param logLevel The [LogLevel] to log at. * @param token The token. * @param message The message to be logged. */ private fun performLogging(logLevel: LogLevel, token: String, message: String) { val output = String.format(Locale.ENGLISH, "[%-20s]:%s", token, message) if (logLevel.value >= mLogLevel.value) { if (logLevel.value >= Log.ERROR) { Log.e(mTag, output) } else { Log.d(mTag, output) } } if (mReportCrashes) Crashlytics.log(logLevel.value, mTag, output) }
gpl-3.0
d0491d75e974db34434fe496ff829705
27.173913
91
0.6511
3.696148
false
false
false
false
yotkaz/thimman
thimman-backend/src/main/kotlin/yotkaz/thimman/backend/service/impl/AttemptService.kt
1
2887
package yotkaz.thimman.backend.service.impl import org.springframework.security.access.prepost.PostFilter import org.springframework.security.access.prepost.PreAuthorize import org.springframework.stereotype.Service import yotkaz.thimman.backend.model.Attempt import yotkaz.thimman.backend.repository.AttemptRepository import yotkaz.thimman.backend.service.AbstractCRUDService import java.util.* @Service class AttemptService : AbstractCRUDService<Attempt, Long, AttemptRepository>() { @PreAuthorize("hasPermission('getAll')") @PostFilter("hasPermission(filterObject, 'getOne')") fun getNotRated() : List<Attempt> { with(ArrayList<Attempt>()) { addAll(dao.findByRatedTrue()); return this; } } override fun checkSaveConstraints(entity: Attempt) { entity.person ?: throw IllegalArgumentException("There must be a person assigned to the attempt; $entity"); entity.challenge ?: throw IllegalArgumentException("There must be a challenge assigned to the attempt; $entity"); entity.id ?: checkCreateConstraints(entity); checkScore(entity); checkMaxAttemptsCount(entity); } private fun checkCreateConstraints(attempt: Attempt) { if (attempt.rated or (attempt.employeeWhichRated != null) or (attempt.score != null)) { throw IllegalArgumentException("Illegal attempt: $attempt"); } } private fun checkMaxAttemptsCount(attempt: Attempt) { val person = attempt.person!!; val challenge = attempt.challenge!!; var attemptsCount = person.attempts.count { anotherAttempt -> anotherAttempt.challenge == challenge; } if (!person.attempts.contains(attempt)) { attemptsCount++; } val isInJobOffers = challenge.jobOfferChallenges.any { jobOfferChallenge -> ((jobOfferChallenge.challengeAttributes == null) or ((jobOfferChallenge.challengeAttributes!!.maxAttempts != null) and (jobOfferChallenge.challengeAttributes!!.maxAttempts!! >= attemptsCount))); } val isInLessons = challenge.lessonChallenges.any { lessonChallenge -> ((lessonChallenge.challengeAttributes == null) or ((lessonChallenge.challengeAttributes!!.maxAttempts != null) and (lessonChallenge.challengeAttributes!!.maxAttempts!! >= attemptsCount))); } if (isInJobOffers or isInLessons) { return; } throw IllegalArgumentException("Max attempts count reached; $attempt"); } private fun checkScore(attempt: Attempt) { attempt.score?.let { if ((attempt.score!! < 0.0) or (attempt.score!! > 100.0)) { throw IllegalArgumentException("Score must be a double between 0 and 100; $attempt"); } } } }
apache-2.0
3a317a717ff69fa8e945bd2e2e3fcbc0
40.257143
121
0.66505
4.860269
false
false
false
false
fejd/jesture
recognizers/src/main/kotlin/com/jesterlabs/jesture/recognizers/onedollar/Template.kt
1
1842
/* * Copyright (c) 2016 Fredrik Henricsson * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.jesterlabs.jesture.recognizers.onedollar import com.jesterlabs.jesture.recognizers.common.data.Point import com.jesterlabs.jesture.recognizers.onedollar.util.* class Template(val name: String, val points: List<Point>) { var processedPoints = points init { processedPoints = resample(points, NUMPOINTS) val radians = indicativeAngle(processedPoints) processedPoints = rotateBy(processedPoints, radians) processedPoints = scaleTo(processedPoints, SQUARE_SIZE) val origin = Point(0.0, 0.0); processedPoints = translateTo(processedPoints, origin) // Use Protractor? /* this.Vector = Vectorize(this.Points); // for Protractor*/ } }
mit
e99f24cd1355bac131f189005a49194f
46.25641
100
0.742671
4.283721
false
false
false
false
dafi/photoshelf
tag-navigator/src/main/java/com/ternaryop/photoshelf/tagnavigator/adapter/TagNavigatorAdapter.kt
1
2503
package com.ternaryop.photoshelf.tagnavigator.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.ternaryop.photoshelf.api.post.TagInfo import com.ternaryop.photoshelf.tagnavigator.R interface TagNavigatorListener { fun onClick(item: TagInfo) } class TagNavigatorAdapter( private val context: Context, list: List<TagInfo>, val blogName: String, private val listener: TagNavigatorListener ) : RecyclerView.Adapter<TagNavigatorViewHolder>(), View.OnClickListener, Filterable, TagNavigatorFilterListener { val items = list.toMutableList() private var tagFilter: TagNavigatorFilter? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TagNavigatorViewHolder { return TagNavigatorViewHolder( LayoutInflater.from(context).inflate(R.layout.tag_navigator_row, parent, false) ) } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: TagNavigatorViewHolder, position: Int) { val item = items[position] holder.bindModel(item, tagFilter?.pattern) holder.setOnClickListeners(this) } override fun onClick(v: View) { listener.onClick(items[v.tag as Int]) } fun sortByTagCount() { items.sortWith { lhs, rhs -> // sort descending val sign = (rhs.postCount - lhs.postCount).toInt() if (sign == 0) lhs.compareTagTo(rhs) else sign } notifyDataSetChanged() } fun sortByTagName() { items.sortWith { lhs, rhs -> lhs.compareTagTo(rhs) } notifyDataSetChanged() } override fun getFilter(): Filter { val currentInstance = tagFilter if (currentInstance != null) { return currentInstance } val newInstance = TagNavigatorFilter(blogName, this) tagFilter = newInstance return newInstance } override fun onComplete(filter: TagNavigatorFilter, items: List<TagInfo>) { this.items.clear() this.items.addAll(items) notifyDataSetChanged() } override fun onError(filter: TagNavigatorFilter, throwable: Throwable) { Toast.makeText(context, throwable.message, Toast.LENGTH_LONG).show() } }
mit
7074ce6e06571a5b6c5d3f683328f595
27.770115
95
0.686776
4.53442
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/ui/CalendarControlSet.kt
1
4882
package org.tasks.ui import android.app.Activity import android.content.Intent import android.net.Uri import android.provider.CalendarContract import android.view.View import android.view.ViewGroup import android.widget.Toast.LENGTH_SHORT import androidx.compose.ui.platform.ComposeView import com.google.android.material.composethemeadapter.MdcTheme import com.todoroo.astrid.activity.TaskEditFragment import dagger.hilt.android.AndroidEntryPoint import org.tasks.R import org.tasks.Strings.isNullOrEmpty import org.tasks.calendars.CalendarPicker import org.tasks.calendars.CalendarProvider import org.tasks.compose.collectAsStateLifecycleAware import org.tasks.compose.edit.CalendarRow import org.tasks.extensions.Context.toast import org.tasks.preferences.PermissionChecker import timber.log.Timber import javax.inject.Inject @AndroidEntryPoint class CalendarControlSet : TaskEditControlFragment() { @Inject lateinit var activity: Activity @Inject lateinit var calendarProvider: CalendarProvider @Inject lateinit var permissionChecker: PermissionChecker override fun onResume() { super.onResume() val canAccessCalendars = permissionChecker.canAccessCalendars() viewModel.eventUri.value?.let { if (canAccessCalendars && !calendarEntryExists(it)) { viewModel.eventUri.value = null } } if (!canAccessCalendars) { viewModel.selectedCalendar.value = null } } override fun bind(parent: ViewGroup?): View = (parent as ComposeView).apply { setContent { MdcTheme { CalendarRow( eventUri = viewModel.eventUri.collectAsStateLifecycleAware().value, selectedCalendar = viewModel.selectedCalendar.collectAsStateLifecycleAware().value?.let { calendarProvider.getCalendar(it)?.name }, onClick = { if (viewModel.eventUri.value.isNullOrBlank()) { CalendarPicker .newCalendarPicker( requireParentFragment(), TaskEditFragment.REQUEST_CODE_PICK_CALENDAR, viewModel.selectedCalendar.value, ) .show( requireParentFragment().parentFragmentManager, TaskEditFragment.FRAG_TAG_CALENDAR_PICKER ) } else { openCalendarEvent() } }, clear = { viewModel.selectedCalendar.value = null viewModel.eventUri.value = null } ) } } } override fun controlId() = TAG private fun openCalendarEvent() { val cr = activity.contentResolver val uri = Uri.parse(viewModel.eventUri.value) val intent = Intent(Intent.ACTION_VIEW, uri) try { cr.query( uri, arrayOf(CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND), null, null, null).use { cursor -> if (cursor!!.count == 0) { activity.toast(R.string.calendar_event_not_found, duration = LENGTH_SHORT) viewModel.eventUri.value = null } else { cursor.moveToFirst() intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, cursor.getLong(0)) intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, cursor.getLong(1)) startActivity(intent) } } } catch (e: Exception) { Timber.e(e) activity.toast(R.string.gcal_TEA_error) } } private fun calendarEntryExists(eventUri: String?): Boolean { if (isNullOrEmpty(eventUri)) { return false } try { val uri = Uri.parse(eventUri) val contentResolver = activity.contentResolver contentResolver.query( uri, arrayOf(CalendarContract.Events.DTSTART), null, null, null).use { cursor -> if (cursor!!.count != 0) { return true } } } catch (e: Exception) { Timber.e(e, "%s: %s", eventUri, e.message) } return false } companion object { const val TAG = R.string.TEA_ctrl_gcal } }
gpl-3.0
798bf0d6b4092aa5ecb6c8170c6f3ae5
36.844961
113
0.543834
5.497748
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/migration/impl/LoginMigration.kt
1
4112
package cc.aoeiuv020.panovel.migration.impl import android.content.Context import cc.aoeiuv020.gson.GsonUtils import cc.aoeiuv020.gson.toBean import cc.aoeiuv020.panovel.data.DataManager import cc.aoeiuv020.panovel.migration.Migration import cc.aoeiuv020.panovel.report.Reporter import cc.aoeiuv020.panovel.util.VersionName import cc.aoeiuv020.panovel.util.notNullOrReport import com.google.gson.Gson import okhttp3.Cookie import okhttp3.HttpUrl import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.debug import org.jetbrains.anko.error /** * 迁移旧版的内嵌浏览器登录状态, * 2.2.0开始有内嵌浏览器, * cookies原本是存在缓存cacheDir里的, * 2.2.2开始移到filesDir里, * Created by AoEiuV020 on 2018.05.17-17:28:13. */ class LoginMigration : Migration(), AnkoLogger { override val to: VersionName = VersionName("2.2.2") override val message: String = "登录状态," override fun migrate(ctx: Context, from: VersionName) { debug { "migrate from: ${from.name}" } if (from < VersionName("2.2.0")) { // 2.2.0 之前没有内嵌浏览器,不用迁移登录状态, // 但是,2.2.2才开始记录版本号,所以传入的会是"0", 不能跳过, } val cacheDir = ctx.cacheDir.resolve("api") if (!cacheDir.exists()) { // 没有数据就不继续了, return } val fileList = cacheDir.list() if (fileList.isEmpty()) { // 目录里没有网站的记录就不继续了, return } // 用于存取cookies, 和2.2.0版本一样配置的gson, val gson: Gson = GsonUtils.gsonBuilder .disableHtmlEscaping() .setPrettyPrinting() .create() // 以前的缓存目录名是网站上下文的类名, // 而且我还开了混淆,悲剧, // 这是2.2.1的混淆结果, val nameMap = mapOf( "飘天文学" to "c", "笔趣阁" to "a", "溜达小说" to "Liudatxt", "起点中文" to "Qidian", "动漫之家" to "b", "SF轻小说" to "f", "少年文学" to "g", "31小说" to "h", "幼狮书盟" to "i", "齐鲁文学" to "e" ) DataManager.allNovelContexts().forEach { novelContext -> // 新网站不在map里就跳过, val fileName = nameMap[novelContext.site.name].also { debug { "判断<${novelContext.site.name}, $it>" } } ?: return@forEach if (!fileList.contains(fileName)) { // 如果当前网站的缓存目录不存在就跳过这个网站, return@forEach } try { val oldCookiesFile = cacheDir.resolve(fileName) .resolve("cookies") if (!oldCookiesFile.exists()) { // 如果当前网站的cookies文件不存在就跳过这个网站, return@forEach } val cookies: Map<String, String> = oldCookiesFile.readText().toBean(gson) debug { "${novelContext.site.name}: $cookies" } // 导入旧版本cookies, val httpUrl = HttpUrl.parse(novelContext.site.baseUrl).notNullOrReport() novelContext.putCookies(cookies.mapValues { (name, value) -> Cookie.parse(httpUrl, "$name=$value").notNullOrReport() }) } catch (e: Exception) { // 单个网站处理失败正常继续,不抛异常,只上报异常,可能是这个网站数据被其他原因破坏了, val message = "网站<${novelContext.site.name}>登录状态迁移失败," Reporter.post(message, e) error(message, e) } } } }
gpl-3.0
9f8458345c0d00988cdf7147c21416eb
33.166667
89
0.533582
3.591753
false
false
false
false
didi/DoraemonKit
Android/dokit-test/src/main/java/com/didichuxing/doraemonkit/kit/test/widget/FlashTextView.kt
1
1765
package com.didichuxing.doraemonkit.kit.test.widget import android.content.Context import android.util.AttributeSet import kotlinx.coroutines.* import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn /** * didi Create on 2022/4/14 . * * Copyright (c) 2022/4/14 by didiglobal.com. * * @author <a href="[email protected]">zhangjun</a> * @version 1.0 * @Date 2022/4/14 4:27 下午 * @Description 用一句话说明文件功能 */ class FlashTextView : androidx.appcompat.widget.AppCompatTextView { private val flashViewScope = MainScope() + CoroutineName(this.toString()) private var flashFlow = flow { while (true) { (0..3).forEach { emit(it) delay(500) } } } private var flashEnable: Boolean = false constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) fun isFlashEnable(): Boolean { return flashEnable } fun cancelFlash() { flashViewScope.cancel() flashEnable = false } fun startFlash() { if (!flashEnable) { flashEnable = true flashViewScope.launch { flashFlow.flowOn(Dispatchers.IO) .collect { when (it) { 0 -> text = "" 1 -> text = "." 2 -> text = ".." 3 -> text = "..." } } } } } }
apache-2.0
e1953f048a0cf778a02457bb4d704e1e
24.602941
113
0.547961
4.533854
false
false
false
false
didi/DoraemonKit
Android/dokit-ft/src/main/java/com/didichuxing/doraemonkit/kit/filemanager/sqlite/bean/RowFiledInfo.kt
1
386
package com.didichuxing.doraemonkit.kit.filemanager.sqlite.bean /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/6/29-11:07 * 描 述: * 修订历史: * ================================================ */ data class RowFiledInfo(val title: String, val isPrimary: Boolean, val value: String?)
apache-2.0
3cb3c48879afe5446388330135b929a0
27.416667
86
0.461765
3.777778
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/find/shuju/list/QidianshujuListActivity.kt
1
6581
package cc.aoeiuv020.panovel.find.shuju.list import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import cc.aoeiuv020.panovel.IView import cc.aoeiuv020.panovel.R import cc.aoeiuv020.panovel.data.entity.Novel import cc.aoeiuv020.panovel.detail.NovelDetailActivity import cc.aoeiuv020.panovel.settings.OtherSettings import cc.aoeiuv020.panovel.find.shuju.QidianshujuActivity import cc.aoeiuv020.panovel.util.notNullOrReport import cc.aoeiuv020.panovel.util.safelyShow import cc.aoeiuv020.regex.pick import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_qidianshuju_list.* import kotlinx.android.synthetic.main.activity_single_search.srlRefresh import org.jetbrains.anko.* /** * 起点数据首订统计帖子列表页, */ class QidianshujuListActivity : AppCompatActivity(), IView, AnkoLogger { companion object { fun start(ctx: Context, postUrl: String) { ctx.startActivity<QidianshujuListActivity>( "postUrl" to postUrl ) } } private lateinit var presenter: QidianshujuListPresenter private lateinit var adapter: QidianshujuListAdapter private lateinit var postUrl: String private var itemJumpQidian: MenuItem? = null private val snack: Snackbar by lazy { Snackbar.make(rvContent, "", Snackbar.LENGTH_SHORT) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_qidianshuju_list) supportActionBar?.setDisplayHomeAsUpEnabled(true) setTitle(R.string.title_qidianshuju_first_order_ranking) postUrl = intent.getStringExtra("postUrl").notNullOrReport() srlRefresh.isRefreshing = true srlRefresh.setOnRefreshListener { presenter.refresh() } initRecycler() presenter = QidianshujuListPresenter() presenter.attach(this) presenter.start(this, postUrl) } override fun onDestroy() { presenter.stop() super.onDestroy() } private fun initRecycler() { rvContent.adapter = QidianshujuListAdapter().also { adapter = it it.setOnItemClickListener(object : QidianshujuListAdapter.OnItemClickListener { override fun onItemClick(item: Item) { try { openBook(item) } catch (ignore: Exception) { innerBrowse(item.url) } } }) } } fun innerBrowse(url: String) { QidianshujuActivity.start(this, url) } private fun openBook(item: Item) { // http://www.qidianshuju.cn/book/1027440366.html // http://www.qidianshuju.com/book/1021708634.html val bookId = item.url.pick("http.*/book/(\\d*).html").first() // https://book.qidian.com/info/1027440366 // https://m.qidian.com/book/1027440366 if (OtherSettings.jumpQidian) { try { // I/ActivityTaskManager: START u0 {act=android.intent.action.VIEW cat=[android.intent.category.BROWSABLE] dat=QDReader://app/showBook?query={"bookId":1027440366} flg=0x14400000 cmp=com.qidian.QDReader/.ui.activity.MainGroupActivity (has extras)} from uid 10241 // intent://app/showBook?query=%7B%22bookId%22%3A1027440366%7D#Intent;scheme=QDReader;S.browser_fallback_url=http%3A%2F%2Fdownload.qidian.com%2Fapknew%2Fsource%2FQDReaderAndroid.apk;end val intent = Intent.parseUri( "intent://app/showBook?query=%7B%22bookId%22%3A$bookId%7D#Intent;scheme=QDReader;S.browser_fallback_url=http%3A%2F%2Fdownload.qidian.com%2Fapknew%2Fsource%2FQDReaderAndroid.apk;end", Intent.URI_INTENT_SCHEME ) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) return } catch (e: ActivityNotFoundException) { toast(R.string.qidian_not_found) OtherSettings.jumpQidian = false updateItem() } } presenter.open(item, bookId) } fun openNovelDetail(novel: Novel) { NovelDetailActivity.start(ctx, novel) } fun showResult(data: List<Item>) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) { return } srlRefresh.isRefreshing = false adapter.setData(data) snack.dismiss() } fun showProgress(retry: Int, maxRetry: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) { return } srlRefresh.isRefreshing = false snack.setText(getString(R.string.qidianshuju_post_progress_place_holder, retry, maxRetry)) snack.show() } fun showError(message: String, e: Throwable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) { return } srlRefresh.isRefreshing = false snack.dismiss() alert( title = ctx.getString(R.string.error), message = message + e.message ) { okButton { } }.safelyShow() } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_qidianshuju_list, menu) itemJumpQidian = menu.findItem(R.id.qidian) updateItem() return true } override fun onRestart() { super.onRestart() updateItem() } private fun updateItem() { itemJumpQidian?.setIcon( if (OtherSettings.jumpQidian) { R.drawable.ic_jump_qidian } else { R.drawable.ic_jump_qidian_blocked } ) } private fun toggleQidian() { OtherSettings.jumpQidian = !OtherSettings.jumpQidian updateItem() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.browse -> presenter.browse() R.id.qidian -> toggleQidian() else -> return super.onOptionsItemSelected(item) } return true } }
gpl-3.0
d3af2917165b51d18d4ec51a89059a52
32.778351
277
0.635587
4.249676
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/app/Main.kt
1
23639
/* Copyright 2015 Andreas Würl 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.blitzortung.android.app import android.Manifest import android.annotation.TargetApi import android.app.Dialog import android.content.ComponentName import android.content.ServiceConnection import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.graphics.Color import android.location.LocationManager import android.os.Build import android.os.Bundle import android.os.Handler import android.os.IBinder import android.preference.PreferenceManager import android.provider.Settings import android.text.format.DateFormat import android.util.Log import android.view.* import android.widget.ImageButton import android.widget.Toast import com.google.android.maps.GeoPoint import kotlinx.android.synthetic.main.map_overlay.* import org.blitzortung.android.app.BOApplication import org.blitzortung.android.alert.event.AlertResultEvent import org.blitzortung.android.alert.handler.AlertHandler import org.blitzortung.android.app.components.VersionComponent import org.blitzortung.android.app.controller.ButtonColumnHandler import org.blitzortung.android.app.controller.HistoryController import org.blitzortung.android.app.view.PreferenceKey import org.blitzortung.android.app.view.components.StatusComponent import org.blitzortung.android.app.view.get import org.blitzortung.android.app.view.put import org.blitzortung.android.data.provider.result.* import org.blitzortung.android.dialogs.* import org.blitzortung.android.map.OwnMapActivity import org.blitzortung.android.map.OwnMapView import org.blitzortung.android.map.overlay.FadeOverlay import org.blitzortung.android.map.overlay.OwnLocationOverlay import org.blitzortung.android.map.overlay.ParticipantsOverlay import org.blitzortung.android.map.overlay.StrikesOverlay import org.blitzortung.android.map.overlay.color.ParticipantColorHandler import org.blitzortung.android.map.overlay.color.StrikeColorHandler import org.blitzortung.android.util.TabletAwareView import org.blitzortung.android.util.isAtLeast import org.jetbrains.anko.intentFor import org.jetbrains.anko.startActivity class Main : OwnMapActivity(), OnSharedPreferenceChangeListener { private val androidIdsForExtendedFunctionality = setOf("44095eb4f9f1a6a6", "f2be4516e5843964") private lateinit var statusComponent: StatusComponent private lateinit var versionComponent: VersionComponent private lateinit var strikesOverlay: StrikesOverlay private lateinit var participantsOverlay: ParticipantsOverlay private lateinit var ownLocationOverlay: OwnLocationOverlay private lateinit var fadeOverlay: FadeOverlay private var clearData: Boolean = false private lateinit var buttonColumnHandler: ButtonColumnHandler<ImageButton, ButtonGroup> private lateinit var historyController: HistoryController private var appService: AppService? = null private val locationHandler = BOApplication.locationHandler private val alertHandler = BOApplication.alertHandler private val dataHandler = BOApplication.dataHandler private val preferences = BOApplication.sharedPreferences private var serviceConnection: ServiceConnection? = null private var currentResult: ResultEvent? = null val dataEventConsumer: (DataEvent) -> Unit = { event -> if (event is RequestStartedEvent) { buttonColumnHandler.lockButtonColumn(ButtonGroup.DATA_UPDATING) statusComponent.startProgress() } else if (event is ResultEvent) { statusComponent.indicateError(event.failed) if (!event.failed) { if (event.parameters!!.intervalDuration != BOApplication.dataHandler.intervalDuration) { reloadData() } currentResult = event Log.d(Main.LOG_TAG, "Main.onDataUpdate() " + event) val resultParameters = event.parameters clearDataIfRequested() val initializeOverlay = strikesOverlay.parameters != resultParameters with(strikesOverlay) { parameters = resultParameters rasterParameters = event.rasterParameters referenceTime = event.referenceTime } if (event.incrementalData && !initializeOverlay) { strikesOverlay.expireStrikes() } else { strikesOverlay.clear() } if (initializeOverlay && event.totalStrikes != null) { strikesOverlay.addStrikes(event.totalStrikes) } else if (event.strikes != null) { strikesOverlay.addStrikes(event.strikes) } alert_view.setColorHandler(strikesOverlay.getColorHandler(), strikesOverlay.parameters.intervalDuration) strikesOverlay.refresh() legend_view.requestLayout() if (!event.containsRealtimeData()) { setHistoricStatusString() } event.stations?.run { participantsOverlay.setParticipants(this) participantsOverlay.refresh() } } statusComponent.stopProgress() buttonColumnHandler.unlockButtonColumn(ButtonGroup.DATA_UPDATING) mapView.invalidate() legend_view.invalidate() } else if (event is ClearDataEvent) { clearData() } else if (event is StatusEvent) { setStatusString(event.status) } } override fun onCreate(savedInstanceState: Bundle?) { try { super.onCreate(savedInstanceState) } catch (e: NoClassDefFoundError) { Log.e(Main.LOG_TAG, e.toString()) Toast.makeText(baseContext, "bad android version", Toast.LENGTH_LONG).show() } Log.v(LOG_TAG, "Main.onCreate()") versionComponent = VersionComponent(this.applicationContext) setContentView(if (isDebugBuild) R.layout.main_debug else R.layout.main) val mapView = findViewById(R.id.mapview) as OwnMapView mapView.setBuiltInZoomControls(true) this.mapView = mapView PreferenceManager.setDefaultValues(this, R.xml.preferences, false) preferences.registerOnSharedPreferenceChangeListener(this) strikesOverlay = StrikesOverlay(this, StrikeColorHandler(preferences)) participantsOverlay = ParticipantsOverlay(this, ParticipantColorHandler(preferences)) mapView.addZoomListener { zoomLevel -> strikesOverlay.updateZoomLevel(zoomLevel) participantsOverlay.updateZoomLevel(zoomLevel) } fadeOverlay = FadeOverlay(strikesOverlay.getColorHandler()) ownLocationOverlay = OwnLocationOverlay(this, mapView) addOverlay(fadeOverlay) addOverlay(strikesOverlay) addOverlay(participantsOverlay) addOverlay(ownLocationOverlay) updateOverlays() statusComponent = StatusComponent(this) setHistoricStatusString() hideActionBar() buttonColumnHandler = ButtonColumnHandler<ImageButton, ButtonGroup>(if (TabletAwareView.isTablet(this)) 75f else 55f) configureMenuAccess() historyController = HistoryController(this, buttonColumnHandler) buttonColumnHandler.addAllElements(historyController.getButtons(), ButtonGroup.DATA_UPDATING) setupDebugModeButton() buttonColumnHandler.lockButtonColumn(ButtonGroup.DATA_UPDATING) buttonColumnHandler.updateButtonColumn() setupCustomViews() onSharedPreferenceChanged(preferences, PreferenceKey.MAP_TYPE, PreferenceKey.MAP_FADE, PreferenceKey.SHOW_LOCATION, PreferenceKey.ALERT_NOTIFICATION_DISTANCE_LIMIT, PreferenceKey.ALERT_SIGNALING_DISTANCE_LIMIT, PreferenceKey.DO_NOT_SLEEP, PreferenceKey.SHOW_PARTICIPANTS) if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(preferences) } createAndBindToDataService() if (versionComponent.state == VersionComponent.State.FIRST_RUN) { openQuickSettingsDialog() } } private fun createAndBindToDataService() { val serviceIntent = intentFor<AppService>() startService(serviceIntent) serviceConnection = object : ServiceConnection { override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) { appService = (iBinder as AppService.DataServiceBinder).service Log.i(Main.LOG_TAG, "Main.ServiceConnection.onServiceConnected() " + appService) setupService() } override fun onServiceDisconnected(componentName: ComponentName) { } } bindService(serviceIntent, serviceConnection, 0) } private fun setupService() { appService?.run { historyController.setAppService(this) } } private fun setupDebugModeButton() { val androidId = Settings.Secure.getString(baseContext.contentResolver, Settings.Secure.ANDROID_ID) Log.v(Main.LOG_TAG, "AndroidId: $androidId") if ((androidId != null && androidIdsForExtendedFunctionality.contains(androidId))) { with(toggleExtendedMode) { isEnabled = true visibility = View.VISIBLE setOnClickListener { v -> buttonColumnHandler.lockButtonColumn(ButtonGroup.DATA_UPDATING) BOApplication.dataHandler.toggleExtendedMode() reloadData() } buttonColumnHandler.addElement(this, ButtonGroup.DATA_UPDATING) } } } private fun setupCustomViews() { with(legend_view) { strikesOverlay = [email protected] setAlpha(150) setOnClickListener { v -> openQuickSettingsDialog() } } with(alert_view) { setColorHandler(strikesOverlay.getColorHandler(), strikesOverlay.parameters.intervalDuration) setBackgroundColor(Color.TRANSPARENT) setAlpha(200) setOnClickListener { view -> if (alertHandler.isAlertEnabled) { val currentLocation = alertHandler.currentLocation if (currentLocation != null) { var radius = determineTargetZoomRadius(alertHandler) val diameter = 1.5f * 2f * radius animateToLocationAndVisibleSize(currentLocation.longitude, currentLocation.latitude, diameter) } } } } with(histogram_view) { setStrikesOverlay(strikesOverlay) setOnClickListener { view -> val currentResult = currentResult if (currentResult != null) { val rasterParameters = currentResult.rasterParameters if (rasterParameters != null) { animateToLocationAndVisibleSize(rasterParameters.rectCenterLongitude.toDouble(), rasterParameters.rectCenterLatitude.toDouble(), 5000f) } else { animateToLocationAndVisibleSize(0.0, 0.0, 20000f) } } } } } private fun determineTargetZoomRadius(alertHandler: AlertHandler): Float { var radius = alertHandler.maxDistance val alertEvent = alertHandler.alertEvent if (alertEvent is AlertResultEvent) { val alertResult = alertEvent.alertResult if (alertResult != null) { radius = Math.max(Math.min(alertResult.closestStrikeDistance * 1.2f, radius), 50f) } } return radius } private fun openQuickSettingsDialog() { if (isAtLeast(Build.VERSION_CODES.HONEYCOMB)) { val dialog = QuickSettingsDialog() dialog.show(fragmentManager, "QuickSettingsDialog") } } private fun animateToLocationAndVisibleSize(longitude: Double, latitude: Double, diameter: Float) { Log.d(Main.LOG_TAG, "Main.animateAndZoomTo() %.4f, %.4f, %.0fkm".format(longitude, latitude, diameter)) val mapView = mapView val controller = mapView.controller val startZoomLevel = mapView.zoomLevel val targetZoomLevel = mapView.calculateTargetZoomLevel(diameter * 1000f) controller.animateTo(GeoPoint((latitude * 1e6).toInt(), (longitude * 1e6).toInt()), { if (startZoomLevel != targetZoomLevel) { val zoomOut = targetZoomLevel - startZoomLevel < 0 val zoomCount = Math.abs(targetZoomLevel - startZoomLevel) val handler = Handler() var delay: Long = 0 for (i in 0..zoomCount - 1) { handler.postDelayed({ if (zoomOut) { controller.zoomOut() } else { controller.zoomIn() } }, delay) delay += 150 } } }) } val isDebugBuild: Boolean get() { var dbg = false try { val pm = packageManager val pi = pm.getPackageInfo(packageName, 0) dbg = ((pi.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0) } catch (ignored: Exception) { } return dbg } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) val inflater = menuInflater inflater.inflate(R.menu.main_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_info -> showDialog(R.id.info_dialog) R.id.menu_alarms -> showDialog(R.id.alarm_dialog) R.id.menu_log -> showDialog(R.id.log_dialog) R.id.menu_preferences -> startActivity<Preferences>() } return super.onOptionsItemSelected(item) } override fun onStart() { super.onStart() with(locationHandler) { requestUpdates(ownLocationOverlay.locationEventConsumer) requestUpdates(alert_view.locationEventConsumer) } with(alertHandler) { requestUpdates(alert_view.alertEventConsumer) requestUpdates(statusComponent.alertEventConsumer) } with(dataHandler) { requestUpdates(dataEventConsumer) requestUpdates(historyController.dataConsumer) requestUpdates(histogram_view.dataConsumer) } Log.d(Main.LOG_TAG, "Main.onStart() service: " + appService) } override fun onRestart() { super.onRestart() Log.d(Main.LOG_TAG, "Main.onRestart() service: " + appService) } override fun onResume() { super.onResume() Log.d(Main.LOG_TAG, "Main.onResume() service: " + appService) } override fun onPause() { super.onPause() Log.v(Main.LOG_TAG, "Main.onPause()") } override fun onStop() { super.onStop() with(locationHandler) { removeUpdates(ownLocationOverlay.locationEventConsumer) removeUpdates(alert_view.locationEventConsumer) } with(alertHandler) { removeUpdates(alert_view.alertEventConsumer) removeUpdates(statusComponent.alertEventConsumer) } with(dataHandler) { removeUpdates(dataEventConsumer) removeUpdates(historyController.dataConsumer) removeUpdates(histogram_view.dataConsumer) } appService?.apply { Log.v(Main.LOG_TAG, "Main.onStop() remove listeners") historyController.setAppService(null) } ?: Log.i(LOG_TAG, "Main.onStop()") } override fun onDestroy() { super.onDestroy() Log.i(LOG_TAG, "Main: onDestroy() unbind service") unbindService(serviceConnection) } override fun isRouteDisplayed(): Boolean { return false } private fun reloadData() { appService!!.reloadData() } private fun clearDataIfRequested() { if (clearData) { clearData() } } private fun clearData() { Log.v(Main.LOG_TAG, "Main.clearData()") clearData = false strikesOverlay.clear() participantsOverlay.clear() } override fun onCreateDialog(id: Int, args: Bundle?): Dialog? { return when (id) { R.id.info_dialog -> InfoDialog(this, versionComponent) R.id.alarm_dialog -> appService?.let { appService -> AlertDialog(this, appService, AlertDialogColorHandler(PreferenceManager.getDefaultSharedPreferences(this))) } R.id.log_dialog -> LogDialog(this) else -> throw RuntimeException("unhandled dialog with id $id") } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { Log.v(LOG_TAG, "Main.onRequestPermissionsResult() $requestCode - $permissions - $grantResults") val providerRelation = LocationProviderRelation.byOrdinal[requestCode] if (providerRelation != null) { val providerName = providerRelation.providerName if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.i(LOG_TAG, "$providerName permission has now been granted.") val editor = preferences.edit() editor.put(PreferenceKey.LOCATION_MODE, providerName) editor.commit() } else { Log.i(LOG_TAG, "$providerName permission was NOT granted.") } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } locationHandler.update(preferences) } @TargetApi(Build.VERSION_CODES.M) private fun requestPermissions(sharedPreferences: SharedPreferences) { val locationProviderName = sharedPreferences.get(PreferenceKey.LOCATION_MODE, LocationManager.PASSIVE_PROVIDER) val permission = when (locationProviderName) { LocationManager.PASSIVE_PROVIDER, LocationManager.GPS_PROVIDER -> Manifest.permission.ACCESS_FINE_LOCATION LocationManager.NETWORK_PROVIDER -> Manifest.permission.ACCESS_COARSE_LOCATION else -> null } if (permission is String && checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(permission), LocationProviderRelation.byProviderName[locationProviderName]?.ordinal ?: Int.MIN_VALUE) } } private enum class LocationProviderRelation(val providerName : String) { GPS(LocationManager.GPS_PROVIDER), PASSIVE(LocationManager.PASSIVE_PROVIDER), NETWORK(LocationManager.NETWORK_PROVIDER); companion object { val byProviderName: Map<String, LocationProviderRelation> = LocationProviderRelation.values().groupBy {it.providerName}.mapValues { it.value.first() } val byOrdinal : Map<Int, LocationProviderRelation> = LocationProviderRelation.values().groupBy {it.ordinal}.mapValues { it.value.first() } } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, keyString: String) { onSharedPreferenceChanged(sharedPreferences, PreferenceKey.fromString(keyString)) } private fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, vararg keys: PreferenceKey) { keys.forEach { onSharedPreferenceChanged(sharedPreferences, it) } } private fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: PreferenceKey) { when (key) { PreferenceKey.MAP_TYPE -> { val mapTypeString = sharedPreferences.get(key, "SATELLITE") mapView.isSatellite = mapTypeString == "SATELLITE" strikesOverlay.refresh() participantsOverlay.refresh() } PreferenceKey.SHOW_PARTICIPANTS -> { val showParticipants = sharedPreferences.get(key, true) participantsOverlay.enabled = showParticipants updateOverlays() } PreferenceKey.COLOR_SCHEME -> { strikesOverlay.refresh() participantsOverlay.refresh() } PreferenceKey.MAP_FADE -> { val alphaValue = Math.round(255.0f / 100.0f * sharedPreferences.get(key, 40)) fadeOverlay.setAlpha(alphaValue) } PreferenceKey.DO_NOT_SLEEP -> { val doNotSleep = sharedPreferences.get(key, false) val flag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON if (doNotSleep) { window.addFlags(flag) } else { window.clearFlags(flag) } } } } protected fun setHistoricStatusString() { if (!strikesOverlay.hasRealtimeData()) { val referenceTime = strikesOverlay.referenceTime + strikesOverlay.parameters.intervalOffset * 60 * 1000 val timeString = DateFormat.format("@ kk:mm", referenceTime) as String setStatusString(timeString) } } protected fun setStatusString(runStatus: String) { val numberOfStrikes = strikesOverlay.totalNumberOfStrikes var statusText = resources.getQuantityString(R.plurals.strike, numberOfStrikes, numberOfStrikes) statusText += "/" val intervalDuration = strikesOverlay.parameters.intervalDuration statusText += resources.getQuantityString(R.plurals.minute, intervalDuration, intervalDuration) statusText += " " + runStatus statusComponent.setText(statusText) } private fun configureMenuAccess() { val config = ViewConfiguration.get(this) if (isAtLeast(Build.VERSION_CODES.LOLLIPOP) || isAtLeast(Build.VERSION_CODES.ICE_CREAM_SANDWICH) && !config.hasPermanentMenuKey()) { menu.visibility = View.VISIBLE menu.setOnClickListener { v -> openOptionsMenu() } buttonColumnHandler.addElement(menu) } } private fun hideActionBar() { if (isAtLeast(Build.VERSION_CODES.HONEYCOMB)) { actionBar?.hide() } } companion object { val LOG_TAG = "BO_ANDROID" val REQUEST_GPS = 1 } }
apache-2.0
1c4ce18955f24d8826bbf17a08301902
35.592879
171
0.646078
5.123104
false
false
false
false
arturbosch/detekt
detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/config/IssueExtensionSpec.kt
1
1858
package io.gitlab.arturbosch.detekt.core.config import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.core.reporting.filterAutoCorrectedIssues import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.TestDetektion import io.gitlab.arturbosch.detekt.test.createCorrectableFinding import io.gitlab.arturbosch.detekt.test.createFinding import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class IssueExtensionSpec : Spek({ val issues by memoized { mapOf( "Ruleset1" to listOf(createFinding(), createCorrectableFinding()), "Ruleset2" to listOf(createFinding()) ) } test("compute weighted amount of issues") { val detektion = object : TestDetektion() { override val findings: Map<String, List<Finding>> = issues } val amount = detektion.getOrComputeWeightedAmountOfIssues(Config.empty) assertThat(amount).isEqualTo(3) } describe("filter auto corrected issues") { it("excludeCorrectable = false (default)") { val detektion = TestDetektion(createFinding(), createCorrectableFinding()) val findings = detektion.filterAutoCorrectedIssues(Config.empty) assertThat(findings).hasSize(1) } it("excludeCorrectable = true") { val config = TestConfig(mapOf("maxIssues" to "0", "excludeCorrectable" to "true")) val detektion = object : TestDetektion() { override val findings: Map<String, List<Finding>> = issues } val findings = detektion.filterAutoCorrectedIssues(config) assertThat(findings).hasSize(2) } } })
apache-2.0
f400f6f1a4733b5cc29b58b7bab6aa48
36.16
94
0.693219
4.382075
false
true
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/whatsnew/WhatsNew.kt
1
4508
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.whatsnew import android.content.Context import androidx.annotation.VisibleForTesting /** * Helper class tracking whether the application was recently updated in order to show "What's new" * menu items and indicators in the application UI. * * The application is considered updated when the application's version name changes (versionName * in the manifest). The applications version code would be a good candidates too, but it might * change more often (RC builds) without the application actually changing from the user's point * of view. * * Whenever the application was updated we still consider the application to be "recently updated" * for the next couple of (process) starts. */ class WhatsNew private constructor(private val storage: WhatsNewStorage) { private fun hasBeenUpdatedRecently(currentVersion: WhatsNewVersion): Boolean = when { hasAppBeenUpdatedRecently(currentVersion) -> { // The app has just been updated. Remember the new app version name and // reset the session counter so that we will still consider the app to be // updated for the next app starts. storage.setVersion(currentVersion) storage.setSessionCounter(SESSIONS_PER_UPDATE) true } else -> { // If the app has been updated recently then decrement our session // counter. If the counter reaches 0 we will not consider the app to // be updated anymore (until the app version name changes again) decrementAndGetSessionCounter() > 0 } } private fun decrementAndGetSessionCounter(): Int { val cachedSessionCounter = storage.getSessionCounter() val newSessionCounter = maxOf(cachedSessionCounter - 1, 0) storage.setSessionCounter(newSessionCounter) return newSessionCounter } private fun hasAppBeenUpdatedRecently(currentVersion: WhatsNewVersion): Boolean { val lastKnownAppVersion = storage.getVersion() return lastKnownAppVersion?.let { currentVersion.majorVersionNumber > it.majorVersionNumber } ?: run { storage.setVersion(currentVersion); false } } private fun clearWhatsNewCounter() { storage.setSessionCounter(0) } companion object { /** * How many "sessions" do we consider the app to be updated? In this case a session means * process creations. */ private const val SESSIONS_PER_UPDATE = 3 @VisibleForTesting internal var wasUpdatedRecently: Boolean? = null /** * Should we highlight the "What's new" menu item because this app been updated recently? * * This method returns true either if this is the first start of the application since it * was updated or this is a later start but still recent enough to consider the app to be * updated recently. */ @JvmStatic fun shouldHighlightWhatsNew(currentVersion: WhatsNewVersion, storage: WhatsNewStorage): Boolean { // Cache the value for the lifetime of this process (or until userViewedWhatsNew() is called) if (wasUpdatedRecently == null) { val whatsNew = WhatsNew(storage) wasUpdatedRecently = whatsNew.hasBeenUpdatedRecently(currentVersion) } return wasUpdatedRecently!! } /** * Convenience function to run from the context. */ @JvmStatic fun shouldHighlightWhatsNew(context: Context): Boolean { return shouldHighlightWhatsNew(ContextWhatsNewVersion(context), SharedPreferenceWhatsNewStorage(context)) } /** * Reset the "updated" state and continue as if the app was not updated recently. */ @JvmStatic private fun userViewedWhatsNew(storage: WhatsNewStorage) { wasUpdatedRecently = false WhatsNew(storage).clearWhatsNewCounter() } /** * Convenience function to run from the context. */ @JvmStatic fun userViewedWhatsNew(context: Context) { userViewedWhatsNew(SharedPreferenceWhatsNewStorage(context)) } } }
mpl-2.0
283a0cfec946948382841ef85fcf8714
38.2
105
0.663931
5.070866
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/ui/sitemaps/sitemap/SitemapFragment.kt
1
6978
package treehou.se.habit.ui.sitemaps.sitemap import android.app.PendingIntent import android.content.Intent import android.os.Bundle import android.speech.RecognizerIntent import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.* import io.realm.Realm import se.treehou.ng.ohcommunicator.connector.models.OHLinkedPage import se.treehou.ng.ohcommunicator.connector.models.OHServer import se.treehou.ng.ohcommunicator.connector.models.OHSitemap import se.treehou.ng.ohcommunicator.util.GsonHelper import treehou.se.habit.R import treehou.se.habit.core.db.model.ServerDB import treehou.se.habit.dagger.HasActivitySubcomponentBuilders import treehou.se.habit.dagger.fragment.SitemapComponent import treehou.se.habit.dagger.fragment.SitemapModule import treehou.se.habit.mvp.BaseDaggerFragment import treehou.se.habit.service.VoiceService import treehou.se.habit.ui.sitemaps.page.PageFragment import treehou.se.habit.ui.sitemaps.sitemap.SitemapContract.Presenter import javax.inject.Inject class SitemapFragment : BaseDaggerFragment<Presenter>(), SitemapContract.View { @Inject lateinit var sitemapPresenter: Presenter @Inject @JvmField var server: ServerDB? = null @Inject @JvmField var sitemap: OHSitemap? = null override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setupActionbar() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val rootView = inflater.inflate(R.layout.fragment_sitemap, container, false) setHasOptionsMenu(isVoiceCommandSupported(server)) return rootView } /** * Setup actionbar using */ private fun setupActionbar() { val actionBar = (activity as AppCompatActivity).supportActionBar if (actionBar != null) actionBar.title = sitemap?.label } /** * Check if a page is loaded. * @return true if page loaded, else false. */ override fun hasPage(): Boolean { return childFragmentManager.backStackEntryCount > 0 } /** * Add and move to page in view pager. * * @param page the page to add to pager */ override fun showPage(server: ServerDB, page: OHLinkedPage) { Log.d(TAG, "Add page " + page.link) childFragmentManager.beginTransaction() .replace(R.id.pgr_sitemap, PageFragment.newInstance(server, page)) .addToBackStack(null) .commitAllowingStateLoss() } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { super.onCreateOptionsMenu(menu, inflater) inflater!!.inflate(R.menu.sitemap, menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { // Handle presses on the action bar items when (item!!.itemId) { R.id.action_voice_command -> { openVoiceCommand(server) return true } } return super.onOptionsItemSelected(item) } /** * Start voice command listener. * * @param server server to send command to. */ fun openVoiceCommand(server: ServerDB?) { if (isVoiceCommandSupported(server)) { startActivity(createVoiceCommandIntent(server)) } } /** * Creates an intent use to input voice command. * @return intent used to fire voice command */ private fun createVoiceCommandIntent(server: ServerDB?): Intent { val openhabPendingIntent = VoiceService.createPendingVoiceCommand(activity!!, server!!, 9) val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) // Specify the calling package to identify your application intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, VoiceService::class.java.`package`.name) // Display an hint to the user about what he should say. intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.voice_command_title)) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK intent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, openhabPendingIntent) return intent } /** * Check if cvoice command is supported by device. * @return true if supported, else false */ private fun isVoiceCommandSupported(server: ServerDB?): Boolean { val packageManager = context!!.packageManager return packageManager.resolveActivity(createVoiceCommandIntent(server), 0) != null } /** * Pop backstack * @return true if handled by fragment, else false. */ override fun removeAllPages(): Boolean { val fragmentManager = childFragmentManager var backStackEntryCount = fragmentManager.backStackEntryCount if (backStackEntryCount > 0) { fragmentManager.popBackStackImmediate() } backStackEntryCount = fragmentManager.backStackEntryCount return backStackEntryCount >= 1 } override fun getPresenter(): Presenter? { return sitemapPresenter } override fun injectMembers(hasActivitySubcomponentBuilders: HasActivitySubcomponentBuilders) { (hasActivitySubcomponentBuilders.getFragmentComponentBuilder(SitemapFragment::class.java) as SitemapComponent.Builder) .fragmentModule(SitemapModule(this, arguments!!)) .build().injectMembers(this) } companion object { private val TAG = "SitemapFragment" /** * Creates a new instance of fragment showing sitemap. * * @param server the server to use to open sitemap. * @param sitemap the sitemap to load. * @return Fragment displaying sitemap. */ fun newInstance(server: OHServer, sitemap: OHSitemap): SitemapFragment { val serverDB = Realm.getDefaultInstance() .where(ServerDB::class.java) .equalTo("name", server.name) .findFirst() return newInstance(serverDB, sitemap) } /** * Creates a new instance of fragment showing sitemap., * * @param serverDB the server to use to open sitemap. * @param sitemap the sitemap to load. * @return Fragment displaying sitemap. */ fun newInstance(serverDB: ServerDB?, sitemap: OHSitemap): SitemapFragment { val fragment = SitemapFragment() val args = Bundle() args.putString(Presenter.ARG_SITEMAP, GsonHelper.createGsonBuilder().toJson(sitemap)) args.putLong(Presenter.ARG_SERVER, serverDB!!.id) fragment.arguments = args return fragment } } }
epl-1.0
6758d76fb2116a9a3f05f3b9bf33c736
35.15544
126
0.675122
4.903725
false
false
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/feature/player/filter/selectType/SelectFilterTypeViewModel.kt
1
1561
package be.florien.anyflow.feature.player.filter.selectType import be.florien.anyflow.R import be.florien.anyflow.feature.player.filter.BaseFilterViewModel import be.florien.anyflow.player.FiltersManager import javax.inject.Inject class SelectFilterTypeViewModel @Inject constructor(filtersManager: FiltersManager) : BaseFilterViewModel(filtersManager) { private val genreName = R.string.filter_type_genre private val artistName = R.string.filter_type_album_artist private val albumName = R.string.filter_type_album private val songName = R.string.filter_type_song private val playlistName = R.string.filter_type_playlist private val downloadedName = R.string.filter_is_downloaded val filtersIds = listOf( GENRE_ID, ARTIST_ID, ALBUM_ID, SONG_ID, PLAYLIST_ID, DOWNLOAD_ID) val filtersNames = listOf( genreName, artistName, albumName, songName, playlistName, downloadedName) val filtersImages = listOf( R.drawable.ic_genre, R.drawable.ic_album_artist, R.drawable.ic_album, R.drawable.ic_song, R.drawable.ic_playlist, R.drawable.ic_download) companion object { const val GENRE_ID = "Genre" const val ARTIST_ID = "Artist" const val ALBUM_ID = "Album" const val SONG_ID = "Song" const val PLAYLIST_ID = "Playlist" const val DOWNLOAD_ID = "Download" } }
gpl-3.0
d6389cd5aa94379d55573cc3c28cf357
31.541667
123
0.639974
4.184987
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/server/SessionContext.kt
1
5426
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.server import org.slf4j.Logger import org.tmatesoft.svn.core.SVNErrorCode import org.tmatesoft.svn.core.SVNErrorMessage import org.tmatesoft.svn.core.SVNException import org.tmatesoft.svn.core.SVNURL import org.tmatesoft.svn.core.internal.delta.SVNDeltaCompression import svnserver.Loggers import svnserver.StringHelper import svnserver.auth.User import svnserver.parser.SvnServerParser import svnserver.parser.SvnServerWriter import svnserver.repository.RepositoryInfo import svnserver.repository.VcsAccess import svnserver.repository.git.GitBranch import svnserver.repository.git.GitFile import svnserver.server.command.BaseCmd import svnserver.server.msg.ClientInfo import svnserver.server.step.Step import java.io.IOException import java.util.* /** * SVN client session context. * * @author Artem V. Navrotskiy <[email protected]> */ class SessionContext constructor( val parser: SvnServerParser, val writer: SvnServerWriter, private val server: SvnServer, repositoryInfo: RepositoryInfo, clientInfo: ClientInfo ) { private val stepStack: Deque<Step> = ArrayDeque() private val repositoryInfo: RepositoryInfo private val capabilities: Set<String> private val acl: VcsAccess var user: User private set private var parent: String? = null val branch: GitBranch get() { return repositoryInfo.branch } @Throws(SVNException::class) fun setParent(url: SVNURL) { parent = getRepositoryPath(url) } @Throws(SVNException::class) private fun getRepositoryPath(url: SVNURL): String { val root: String = repositoryInfo.baseUrl.path val path: String = url.path if (!path.startsWith(root)) { throw SVNException(SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Invalid relative path: " + path + " (base: " + root + ")")) } if (root.length == path.length) { return "" } val hasSlash: Boolean = root.endsWith("/") if ((!hasSlash) && (path.get(root.length) != '/')) { throw SVNException(SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Invalid relative path: " + path + " (base: " + root + ")")) } return StringHelper.normalize(path.substring(root.length)) } val compression: SVNDeltaCompression get() { when (server.compressionLevel) { SVNDeltaCompression.LZ4 -> { if (capabilities.contains(SvnServer.svndiff2Capability)) return SVNDeltaCompression.LZ4 if (capabilities.contains(SvnServer.svndiff1Capability)) return SVNDeltaCompression.Zlib } SVNDeltaCompression.Zlib -> if (capabilities.contains(SvnServer.svndiff1Capability)) return SVNDeltaCompression.Zlib } return SVNDeltaCompression.None } @Throws(IOException::class, SVNException::class) fun authenticate(allowAnonymous: Boolean) { if (!user.isAnonymous) throw IllegalStateException() user = server.authenticate(this, allowAnonymous and canRead(getRepositoryPath(""))) } @Throws(IOException::class) fun canRead(path: String): Boolean { return acl.canRead(user, branch.shortBranchName, path) } fun getRepositoryPath(localPath: String): String { return StringHelper.joinPath(parent!!, localPath) } fun push(step: Step) { stepStack.push(step) } fun poll(): Step? { return stepStack.poll() } /** * Get repository file. * * @param rev Target revision. * @param path Target path or url. * @return Return file object. */ @Throws(SVNException::class, IOException::class) fun getFile(rev: Int, path: String): GitFile? { return branch.getRevisionInfo(rev).getFile(getRepositoryPath(path)) } @Throws(SVNException::class, IOException::class) fun getFile(rev: Int, url: SVNURL): GitFile? { val path: String = getRepositoryPath(url) checkRead(path) return branch.getRevisionInfo(rev).getFile(path) } @Throws(SVNException::class, IOException::class) fun checkRead(path: String) { acl.checkRead(user, branch.shortBranchName, path) } @Throws(SVNException::class, IOException::class) fun checkWrite(path: String) { acl.checkWrite(user, branch.shortBranchName, path) } @Throws(IOException::class) fun skipUnsupportedCommand(cmd: String) { log.error("Unsupported command: {}", cmd) BaseCmd.sendError(writer, SVNErrorMessage.create(SVNErrorCode.RA_SVN_UNKNOWN_CMD, "Unsupported command: " + cmd)) parser.skipItems() } companion object { private val log: Logger = Loggers.svn } init { user = User.anonymous this.repositoryInfo = repositoryInfo acl = branch.repository.context.sure(VcsAccess::class.java) setParent(clientInfo.url) capabilities = clientInfo.capabilities.toHashSet() } }
gpl-2.0
36a8fde2c1c9989a15c35b42de0bb0a8
33.125786
136
0.6784
4.235753
false
false
false
false
kiruto/kotlin-android-mahjong
app/src/main/java/dev/yuriel/mahjan/texture/NormalFontBlock.kt
1
1999
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.yuriel.mahjan.texture import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.scenes.scene2d.ui.Label /** * Created by yuriel on 8/20/16. */ class NormalFontBlock { var font: BitmapFont? = null private set var label: Label? = null var color: Color? set(value) { label?.color = value } get() = label?.color var text: String set(value) { label?.setText(value) label?.pack() } get() = label?.text?.toString()?: "" fun load(fileName: String, imageName: String) { font = BitmapFont(Gdx.files.internal(fileName), Gdx.files.internal(imageName), false) label = Label("", Label.LabelStyle(font, Color.WHITE)) } }
mit
64dab2332b84fe518a50cdb09e944fe4
34.087719
93
0.697849
4.155925
false
false
false
false
kiruto/kotlin-android-mahjong
mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/rules/yaku/yakuimpl/17_全帯.kt
1
2380
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.yuriel.kotmahjan.rules.yaku.yakuimpl import dev.yuriel.kotmahjan.rules.MentsuSupport /** * Created by yuriel on 7/24/16. * チャンタ判定 * 123の順子と789の順子、および一九字牌の対子と刻子 * のみで構成された場合成立 */ fun 全帯Impl(s: MentsuSupport): Boolean { //雀頭がnullなら七対子なのでfalse if (s.janto == null) { return false } //雀頭が一九字牌以外ならfalse val jantoNum = s.janto?.getHai()?.num if (jantoNum != 1 && jantoNum != 9 && jantoNum != 0) { return false } //順子が無ければfalse if (s.shuntsuCount == 0) { return false } //順子が123の順子と789の順子でなければfalse for (shuntsu in s.getShuntsuList()) { val shuntsuNum = shuntsu.getHai()?.num if (shuntsuNum != 2 && shuntsuNum != 8) { return false } } //刻子・槓子が一九字牌以外ならfalse for (kotsu in s.kotsuKantsu) { val kotsuNum = kotsu.getHai()?.num if (kotsuNum != 1 && kotsuNum != 9 && kotsuNum != 0) { return false } } //ここまでくればtrue return true }
mit
61aa452c71604c98516f2e97d9a850cd
30.434783
81
0.676661
3.26506
false
false
false
false
edvin/tornadofx
src/main/java/tornadofx/adapters/TornadoFXColumns.kt
1
3058
package tornadofx.adapters import javafx.beans.property.DoubleProperty import javafx.scene.control.TableColumn import javafx.scene.control.TreeTableColumn fun TreeTableColumn<*,*>.toTornadoFXColumn() = TornadoFXTreeTableColumn(this) fun TableColumn<*,*>.toTornadoFXColumn() = TornadoFxNormalTableColumn(this) interface TornadoFXColumn<COLUMN> { val column: COLUMN val properties: Properties var prefWidth: Double var maxWidth: Double var minWidth: Double val width: Double val isVisible: Boolean val minWidthProperty: DoubleProperty val maxWidthProperty: DoubleProperty fun isLegalWidth(width: Double) = width in minWidthProperty.get() .. maxWidthProperty.get() } class TornadoFXTreeTableColumn(override val column: TreeTableColumn<*, *>) : TornadoFXColumn<TreeTableColumn<*, *>> { override val minWidthProperty get() = column.minWidthProperty() override val maxWidthProperty get() = column.maxWidthProperty() override var minWidth: Double get() = column.minWidth set(value) { column.minWidth = value } override val properties = column.properties override var prefWidth: Double get() = column.prefWidth set(value) { column.prefWidth = value } override var maxWidth: Double get() = column.maxWidth set(value) { column.maxWidth = value } override val width: Double get() = column.width override val isVisible: Boolean get() = column.isVisible override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TornadoFXTreeTableColumn if (column != other.column) return false return true } override fun hashCode(): Int { return column.hashCode() } } class TornadoFxNormalTableColumn(override val column: TableColumn<*, *>) : TornadoFXColumn<TableColumn<*, *>> { override var minWidth: Double get() = column.minWidth set(value) { column.minWidth = value } override var maxWidth: Double get() = column.maxWidth set(value) { column.maxWidth = value } override var prefWidth: Double get() = column.prefWidth set(value) { column.prefWidth = value } override val properties = column.properties override val width: Double get() = column.width override val minWidthProperty get() = column.minWidthProperty() override val maxWidthProperty get() = column.maxWidthProperty() override val isVisible: Boolean get() = column.isVisible override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TornadoFxNormalTableColumn if (column != other.column) return false return true } override fun hashCode(): Int { return column.hashCode() } }
apache-2.0
8567ce1343e0293b905eda7d0e1170e9
28.403846
117
0.653041
4.908507
false
false
false
false
martin-nordberg/KatyDOM
Katydid-VDOM-JS/src/main/kotlin/o/katydid/vdom/builders/objects/KatydidObjectEmbeddedContentBuilder.kt
1
2477
// // (C) Copyright 2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.vdom.builders.objects import o.katydid.vdom.builders.KatydidAttributesContentBuilder import o.katydid.vdom.builders.KatydidEmbeddedContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Builder DSL to create the contents of an object element. */ interface KatydidObjectEmbeddedContentBuilder<in Msg> : KatydidEmbeddedContentBuilder<Msg> { /** * Adds a `<param>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of the parameter. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineAttributes a DSL-style lambda that builds any custom attributes of the new element. */ fun param( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
650a42be18de2048ca22737f7cd72a33
39.606557
119
0.613646
4.837891
false
false
false
false
akinaru/bbox-api-client
bboxapi-router/src/main/kotlin/fr/bmartel/bboxapi/router/model/Voip.kt
2
580
package fr.bmartel.bboxapi.router.model data class Voip( val voip: List<VoipEntry>? = null ) data class VoipEntry( val id: Int? = null, val status: String? = null, val callstate: CallState? = null, val uri: String? = null, val blockstate: Int? = null, val anoncallstate: Int? = null, val mwi: Int? = null, val message_count: Int? = null, val notanswered: Int? = null ) enum class CallState { Idle, InCall, Ringing, Connecting, Disconnecting, Unknown } enum class Line { LINE1, LINE2 }
mit
49fb0bb149289d78fb4a9663b694a565
21.346154
61
0.6
3.431953
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/TUnReadView.kt
1
7671
package com.tamsiree.rxui.view import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.graphics.drawable.AnimationDrawable import android.os.Handler import android.os.Message import android.util.AttributeSet import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import com.tamsiree.rxui.R /** * Created by [email protected] on 11/20/14. * Description : custom layout to draw bezier */ class TUnReadView : FrameLayout { // 手势坐标 var handX = 300f var handY = 300f // 锚点坐标 var anchorX = 200f var anchorY = 300f // 起点坐标 var startX = 100f var startY = 100f // 定点圆半径 var radius = DEFAULT_RADIUS // 判断动画是否开始 var isAnimStart = false // 判断是否开始拖动 var isTouch = false var exploredImageView: ImageView? = null // ImageView tipImageView; var tipTextView: TextView? = null private var paint: Paint? = null private var path: Path? = null @SuppressLint("HandlerLeak") private val mHandler: Handler = object : Handler() { override fun handleMessage(msg: Message) { when (msg.what) { 1 -> tipTextView!!.text = msg.obj.toString() 2 -> { tipTextView!!.text = "" tipTextView!!.setBackgroundResource(R.drawable.skin_tips_new) } else -> { } } } } constructor(context: Context?) : super(context!!) { init() } constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) { init() } constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context!!, attrs, defStyleAttr) { init() } private fun init() { path = Path() paint = Paint() paint!!.isAntiAlias = true paint!!.style = Paint.Style.FILL_AND_STROKE paint!!.strokeWidth = 2f paint!!.color = Color.RED val params = LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) exploredImageView = ImageView(context) exploredImageView!!.layoutParams = params exploredImageView!!.setImageResource(R.drawable.tip_anim) exploredImageView!!.visibility = View.INVISIBLE tipTextView = TextView(context) tipTextView!!.layoutParams = params tipTextView!!.setTextColor(Color.parseColor("#FFFFFF")) tipTextView!!.setPadding(30, 5, 0, 0) // tipTextView.setGravity(Gravity.CENTER); tipTextView!!.setBackgroundResource(R.drawable.skin_tips_newmessage_ninetynine) /* tipImageView = new ImageView(getContext()); tipImageView.setLayoutParams(params); tipImageView.setImageResource(R.drawable.skin_tips_newmessage_ninetynine);*/ //addView(tipImageView); addView(tipTextView) addView(exploredImageView) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { exploredImageView!!.x = startX - exploredImageView!!.width / 2 exploredImageView!!.y = startY - exploredImageView!!.height / 2 /* tipImageView.setX(startX - tipImageView.getWidth()/2); tipImageView.setY(startY - tipImageView.getHeight()/2);*/tipTextView!!.x = startX - tipTextView!!.width / 2 tipTextView!!.y = startY - tipTextView!!.height / 2 super.onLayout(changed, left, top, right, bottom) } private fun calculate() { val distance = Math.sqrt(Math.pow(handY - startY.toDouble(), 2.0) + Math.pow(handX - startX.toDouble(), 2.0)).toFloat() radius = -distance / 15 + DEFAULT_RADIUS if (radius < 9) { isAnimStart = true exploredImageView!!.visibility = View.VISIBLE exploredImageView!!.setImageResource(R.drawable.tip_anim) (exploredImageView!!.drawable as AnimationDrawable).stop() (exploredImageView!!.drawable as AnimationDrawable).start() //tipImageView.setVisibility(View.GONE); tipTextView!!.visibility = View.GONE } // 根据角度算出四边形的四个点 val offsetX = (radius * Math.sin(Math.atan((handY - startY) / (handX - startX).toDouble()))).toFloat() val offsetY = (radius * Math.cos(Math.atan((handY - startY) / (handX - startX).toDouble()))).toFloat() val x1 = startX - offsetX val y1 = startY + offsetY val x2 = handX - offsetX val y2 = handY + offsetY val x3 = handX + offsetX val y3 = handY - offsetY val x4 = startX + offsetX val y4 = startY - offsetY path!!.reset() path!!.moveTo(x1, y1) path!!.quadTo(anchorX, anchorY, x2, y2) path!!.lineTo(x3, y3) path!!.quadTo(anchorX, anchorY, x4, y4) path!!.lineTo(x1, y1) // 更改图标的位置 /* tipImageView.setX(x - tipImageView.getWidth()/2); tipImageView.setY(y - tipImageView.getHeight()/2);*/tipTextView!!.x = handX - tipTextView!!.width / 2 tipTextView!!.y = handY - tipTextView!!.height / 2 } override fun onDraw(canvas: Canvas) { if (isAnimStart || !isTouch) { canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.OVERLAY) } else { calculate() canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.OVERLAY) canvas.drawPath(path!!, paint!!) canvas.drawCircle(startX, startY, radius, paint!!) canvas.drawCircle(handX, handY, radius, paint!!) } super.onDraw(canvas) } override fun onTouchEvent(event: MotionEvent): Boolean { if (event.action == MotionEvent.ACTION_DOWN) { // 判断触摸点是否在tipImageView中 val rect = Rect() val location = IntArray(2) /* tipImageView.getDrawingRect(rect); tipImageView.getLocationOnScreen(location);*/tipTextView!!.getDrawingRect(rect) tipTextView!!.getLocationOnScreen(location) rect.left = location[0] rect.top = location[1] rect.right = rect.right + location[0] rect.bottom = rect.bottom + location[1] if (rect.contains(event.rawX.toInt(), event.rawY.toInt())) { isTouch = true } } else if (event.action == MotionEvent.ACTION_UP || event.action == MotionEvent.ACTION_CANCEL) { isTouch = false /* tipImageView.setX(startX - tipImageView.getWidth()/2); tipImageView.setY(startY - tipImageView.getHeight()/2); */tipTextView!!.x = startX - tipTextView!!.width / 2 tipTextView!!.y = startY - tipTextView!!.height / 2 } invalidate() if (isAnimStart) { return super.onTouchEvent(event) } anchorX = (event.x + startX) / 2 anchorY = (event.y + startY) / 2 handX = event.x handY = event.y return true } /** * 设置信息的数量 * * @param text */ fun setText(text: CharSequence?) { val msg = Message() msg.obj = text msg.what = 1 mHandler.sendMessage(msg) } /** * 设置有新的信息 */ fun setNewText() { mHandler.sendEmptyMessage(2) } companion object { // 默认定点圆半径 const val DEFAULT_RADIUS = 20f } }
apache-2.0
b0bfa611f497500365464a8a20bfd92e
33.273973
127
0.603198
4.190396
false
false
false
false
Ribesg/anko
dsl/static/src/common/AlertDialogBuilder.kt
1
4027
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.anko import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.database.Cursor import android.graphics.drawable.Drawable import android.view.KeyEvent import android.view.View import android.view.ViewManager import android.widget.ListAdapter class AlertDialogBuilder(val ctx: Context) { val builder: AlertDialog.Builder = AlertDialog.Builder(ctx) protected var dialog: AlertDialog? = null constructor(ankoContext: AnkoContext<*>) : this(ankoContext.ctx) fun dismiss() { dialog?.dismiss() } fun show(): AlertDialogBuilder { dialog = builder.create() dialog!!.show() return this } fun title(title: CharSequence) { builder.setTitle(title) } fun title(resource: Int) { builder.setTitle(resource) } fun message(title: CharSequence) { builder.setMessage(title) } fun message(resource: Int) { builder.setMessage(resource) } fun icon(icon: Int) { builder.setIcon(icon) } fun icon(icon: Drawable) { builder.setIcon(icon) } fun customTitle(title: View) { builder.setCustomTitle(title) } fun customView(view: View) { builder.setView(view) } fun customView(dsl: ViewManager.() -> Unit) { val view = ctx.UI(dsl).view builder.setView(view) } fun cancellable(value: Boolean = true) { builder.setCancelable(value) } fun onCancel(f: () -> Unit) { builder.setOnCancelListener { f() } } fun onKey(f: (keyCode: Int, e: KeyEvent) -> Boolean) { builder.setOnKeyListener({ dialog, keyCode, event -> f(keyCode, event) }) } fun neutralButton(textResource: Int = android.R.string.ok, f: DialogInterface.() -> Unit = { dismiss() }) { neutralButton(ctx.getString(textResource), f) } fun neutralButton(title: String, f: DialogInterface.() -> Unit = { dismiss() }) { builder.setNeutralButton(title, { dialog, which -> dialog.f() }) } fun positiveButton(textResource: Int = android.R.string.ok, f: DialogInterface.() -> Unit) { positiveButton(ctx.getString(textResource), f) } fun positiveButton(title: String, f: DialogInterface.() -> Unit) { builder.setPositiveButton(title, { dialog, which -> dialog.f() }) } fun negativeButton(textResource: Int = android.R.string.cancel, f: DialogInterface.() -> Unit = { dismiss() }) { negativeButton(ctx.getString(textResource), f) } fun negativeButton(title: String, f: DialogInterface.() -> Unit = { dismiss() }) { builder.setNegativeButton(title, { dialog, which -> dialog.f() }) } fun items(itemsId: Int, f: (which: Int) -> Unit) { items(ctx.resources!!.getTextArray(itemsId), f) } fun items(items: List<CharSequence>, f: (which: Int) -> Unit) { items(items.toTypedArray(), f) } fun items(items: Array<CharSequence>, f: (which: Int) -> Unit) { builder.setItems(items, { dialog, which -> f(which) }) } fun adapter(adapter: ListAdapter, f: (which: Int) -> Unit) { builder.setAdapter(adapter, { dialog, which -> f(which) }) } fun adapter(cursor: Cursor, labelColumn: String, f: (which: Int) -> Unit) { builder.setCursor(cursor, { dialog, which -> f(which) }, labelColumn) } }
apache-2.0
bbd97c476591b65f44775c311f2f417b
28.181159
116
0.646139
4.084178
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/mark/canvas/FadingBackgroundCanvasDrawable.kt
1
1887
package com.tamsiree.rxui.view.mark.canvas import android.animation.ValueAnimator import android.graphics.Canvas import android.graphics.Paint import android.view.animation.LinearInterpolator import androidx.core.animation.doOnEnd import com.tamsiree.rxui.view.mark.canvas.CanvasKit.drawBackdropRectangle import com.tamsiree.rxui.view.mark.model.AnimationData import com.tamsiree.rxui.view.mark.model.CanvasAnimation import com.tamsiree.rxui.view.mark.model.ParentMetrics /** * Lightweight canvas drawable for fading a background based on input constraints */ internal class FadingBackgroundCanvasDrawable( private val fadeAnimationData: AnimationData, private val backdropPaint: Paint ) : CanvasDrawable { override var invalidateCallback: () -> Unit = {} private var fadeAnimation: CanvasAnimation? = null private var currentAlpha: Int = 255 override fun onDraw(canvas: Canvas, parentMetrics: ParentMetrics, canvasY: Float, proportion: Float) { if (proportion >= fadeAnimationData.startProportion && fadeAnimation == null) { val animator = createFadeAnimator() fadeAnimation = CanvasAnimation(animator) animator.start() } canvas.drawBackdropRectangle(parentMetrics, canvasY, backdropPaint.apply { alpha = currentAlpha }) } override fun reset() { fadeAnimation?.animator?.cancel() fadeAnimation = null currentAlpha = 255 } private fun createFadeAnimator() = ValueAnimator().apply { setIntValues(255, 0) interpolator = LinearInterpolator() duration = fadeAnimationData.duration addUpdateListener { invalidateCallback() currentAlpha = it.animatedValue as Int } doOnEnd { fadeAnimation = fadeAnimation?.copy(hasEnded = true) } } }
apache-2.0
987b186341e988329277cab0debc181c
31.551724
106
0.702173
4.813776
false
false
false
false
Popalay/Cardme
data/src/main/kotlin/com/popalay/cardme/data/DataBaseMigration.kt
1
1396
package com.popalay.cardme.data import io.realm.DynamicRealm import io.realm.RealmMigration class DataBaseMigration : RealmMigration { override fun migrate(realm: DynamicRealm, oldVersion: Long, newVersion: Long) { val schema = realm.schema var updatedVersion = oldVersion if (updatedVersion == 0L) { schema.get("Card").addField("isTrash", Boolean::class.java) schema.get("Holder").addField("isTrash", Boolean::class.java) schema.get("Debt").addField("isTrash", Boolean::class.java) updatedVersion++ } if (updatedVersion == 1L) { schema.get("Holder") .removePrimaryKey() .removeField("id") .addPrimaryKey("name") schema.get("Card") .removePrimaryKey() .removeField("id") .addPrimaryKey("number") updatedVersion++ } if (updatedVersion == 2L) { schema.get("Holder") .removeField("cardsCount") .removeField("debtCount") .addRealmListField("cards", schema.get("Card")) .addRealmListField("debts", schema.get("Debt")) updatedVersion++ } if (updatedVersion == 3L) { updatedVersion++ } } }
apache-2.0
6f40972f05c74aa5b9c02e00cfd8a5e9
31.488372
83
0.526504
4.847222
false
false
false
false
stripe/stripe-android
paymentsheet/src/test/java/com/stripe/android/model/SetupIntentFixtures.kt
1
12185
package com.stripe.android.model import com.stripe.android.model.parsers.SetupIntentJsonParser import org.json.JSONObject internal object SetupIntentFixtures { private val PARSER = SetupIntentJsonParser() internal val SI_NEXT_ACTION_REDIRECT_JSON = JSONObject( """ { "id": "seti_1EqTSZGMT9dGPIDGVzCUs6dV", "object": "setup_intent", "cancellation_reason": null, "client_secret": "seti_1EqTSZGMT9dGPIDGVzCUs6dV_secret_FL9mS9ILygVyGEOSmVNqHT83rxkqy0Y", "created": 1561677666, "description": "a description", "last_setup_error": null, "livemode": false, "next_action": { "redirect_to_url": { "return_url": "stripe://setup_intent_return", "url": "https://hooks.stripe.com/redirect/authenticate/src_1EqTStGMT9dGPIDGJGPkqE6B?client_secret=src_client_secret_FL9m741mmxtHykDlRTC5aQ02" }, "type": "redirect_to_url" }, "payment_method": "pm_1EqTSoGMT9dGPIDG7dgafX1H", "payment_method_types": [ "card" ], "status": "requires_action", "usage": "off_session" } """.trimIndent() ) internal val SI_WITH_LAST_PAYMENT_ERROR = requireNotNull( PARSER.parse( JSONObject( """ { "id": "seti_1EqTSZGMT9dGPIDGVzCUs6dV", "object": "setup_intent", "cancellation_reason": null, "client_secret": "seti_1EqTSZGMT9dGPIDGVzCUs6dV_secret_FL9mS9ILygVyGEOSmVNqHT83rxkqy0Y", "created": 1561677666, "description": "a description", "last_setup_error": { "code": "setup_intent_authentication_failure", "doc_url": "https://stripe.com/docs/error-codes/payment-intent-authentication-failure", "message": "The provided PaymentMethod has failed authentication. You can provide payment_method_data or a new PaymentMethod to attempt to fulfill this PaymentIntent again.", "payment_method": { "id": "pm_1F7J1bCRMbs6FrXfQKsYwO3U", "object": "payment_method", "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null, "state": null }, "email": null, "name": null, "phone": null }, "card": { "brand": "visa", "checks": { "address_line1_check": null, "address_postal_code_check": null, "cvc_check": null }, "country": null, "exp_month": 8, "exp_year": 2020, "funding": "credit", "generated_from": null, "last4": "3220", "three_d_secure_usage": { "supported": true }, "wallet": null }, "created": 1565775851, "customer": null, "livemode": false, "metadata": {}, "type": "card" }, "type": "invalid_request_error" }, "livemode": false, "next_action": { "redirect_to_url": { "return_url": "stripe://setup_intent_return", "url": "https://hooks.stripe.com/redirect/authenticate/src_1EqTStGMT9dGPIDGJGPkqE6B?client_secret=src_client_secret_FL9m741mmxtHykDlRTC5aQ02" }, "type": "redirect_to_url" }, "payment_method": "pm_1EqTSoGMT9dGPIDG7dgafX1H", "payment_method_types": [ "card" ], "status": "requires_action", "usage": "off_session" } """.trimIndent() ) ) ) internal val CANCELLED = requireNotNull( PARSER.parse( JSONObject( """ { "id": "seti_1FCoS9CRMbs6FrXfxFQOp8Mm", "object": "setup_intent", "application": null, "cancellation_reason": "abandoned", "client_secret": "seti_1FCoS9CRMbs6FrXfxFQOp8Mm_secret_FiEwNDtwMi", "created": 1567088301, "customer": "cus_FWhpaTLIPWLhpJ", "description": null, "last_setup_error": null, "livemode": false, "metadata": {}, "next_action": null, "on_behalf_of": null, "payment_method": "pm_1F1wa2CRMbs6FrXfm9XfWrGS", "payment_method_options": { "card": { "request_three_d_secure": "automatic" } }, "payment_method_types": [ "card" ], "status": "canceled", "usage": "off_session" } """.trimIndent() ) ) ) val SI_WITH_LAST_SETUP_ERROR = PARSER.parse( JSONObject( """ { "id": "si_1F7J1aCRMbs6FrXfaJcvbxF6", "object": "setup_intent", "amount": 1000, "capture_method": "manual", "client_secret": "pi_1F7J1aCRMbs6FrXfaJcvbxF6_secret_mIuDLsSfoo1m6s", "confirmation_method": "automatic", "created": 1565775850, "currency": "usd", "description": "Example SetupIntent", "last_setup_error": { "code": "card_declined", "doc_url": "https://stripe.com/docs/error-codes", "message": "Error message.", "payment_method": { "id": "pm_1F7J1bCRMbs6FrXfQKsYwO3U", "object": "payment_method", "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null, "state": null }, "email": null, "name": null, "phone": null }, "card": { "brand": "visa", "checks": { "address_line1_check": null, "address_postal_code_check": null, "cvc_check": null }, "country": null, "exp_month": 8, "exp_year": 2020, "funding": "credit", "generated_from": null, "last4": "3220", "three_d_secure_usage": { "supported": true }, "wallet": null }, "created": 1565775851, "customer": null, "livemode": false, "metadata": {}, "type": "card" }, "type": "invalid_request_error" }, "livemode": false, "payment_method": null, "payment_method_types": [ "card" ], "receipt_email": null, "source": null, "status": "requires_payment_method" } """.trimIndent() ) )!! internal val SI_SUCCEEDED = requireNotNull( PARSER.parse( JSONObject( """ { "id": "seti_1FCoS9CRMbs6FrXfxFQOp8Mm", "object": "setup_intent", "application": null, "cancellation_reason": "abandoned", "client_secret": "seti_1FCoS9CRMbs6FrXfxFQOp8Mm_secret_FiEwNDtwMi", "created": 1567088301, "customer": "cus_FWhpaTLIPWLhpJ", "description": null, "last_setup_error": null, "livemode": false, "metadata": {}, "next_action": null, "on_behalf_of": null, "payment_method": "pm_1F1wa2CRMbs6FrXfm9XfWrGS", "payment_method_options": { "card": { "request_three_d_secure": "automatic" } }, "payment_method_types": [ "card" ], "status": "succeeded", "usage": "off_session" } """.trimIndent() ) ) ) internal val SI_REQUIRES_PAYMENT_METHOD = requireNotNull( PARSER.parse( JSONObject( """ { "id": "seti_1GSmaFCRMbs", "object": "setup_intent", "cancellation_reason": null, "client_secret": "seti_1GSmaFCRMbs6FrXfmjThcHan_secret_H0oC2iSB4FtW4d", "created": 1585670699, "description": null, "last_setup_error": null, "livemode": false, "payment_method": null, "payment_method_types": [ "card" ], "status": "requires_payment_method", "usage": "off_session" } """.trimIndent() ) ) ) internal val EXPANDED_PAYMENT_METHOD = JSONObject( """ { "id": "seti_1GSmaFCRMbs", "object": "setup_intent", "cancellation_reason": null, "client_secret": "seti_1GSmaFCRMbs6FrXfmjThcHan_secret_H0oC2iSB4FtW4d", "created": 1585670699, "description": null, "last_setup_error": null, "livemode": false, "payment_method": { "id": "pm_1GSmaGCRMbs6F", "object": "payment_method", "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null, "state": null }, "email": null, "name": null, "phone": null }, "card": { "brand": "visa", "checks": { "address_line1_check": null, "address_postal_code_check": null, "cvc_check": null }, "country": "IE", "exp_month": 1, "exp_year": 2025, "funding": "credit", "generated_from": null, "last4": "3238", "three_d_secure_usage": { "supported": true }, "wallet": null }, "created": 1585670700, "customer": null, "livemode": false, "metadata": {}, "type": "card" }, "payment_method_types": ["card"], "status": "requires_action", "usage": "off_session" } """.trimIndent() ) val SI_NEXT_ACTION_REDIRECT = requireNotNull( PARSER.parse(SI_NEXT_ACTION_REDIRECT_JSON) ) }
mit
e2a0d0c26cfacddc44b2dcb3ceabb9b9
34.628655
190
0.405909
4.502956
false
false
false
false
slartus/4pdaClient-plus
core-lib/src/main/java/org/softeg/slartus/forpdaplus/core_lib/ui/fragments/BaseDialogFragment.kt
1
855
package org.softeg.slartus.forpdaplus.core_lib.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import androidx.viewbinding.ViewBinding abstract class BaseDialogFragment<VB : ViewBinding>(private val inflate: Inflate<VB>) : DialogFragment() { private var _binding: VB? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = inflate.invoke(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } protected fun isBindingInitialized() = _binding != null }
apache-2.0
72523bd6e8e6b850d43740222faa51ce
26.612903
87
0.707602
4.697802
false
false
false
false
mihmuh/IntelliJConsole
Konsole/src/com/intellij/idekonsole/scripting/java/quotations.kt
1
1876
package com.intellij.idekonsole.scripting.java import com.intellij.idekonsole.context.Context import com.intellij.psi.* private fun parserFacade() = JavaPsiFacade.getInstance(Context.instance().project).parserFacade private fun PsiElement.brokenReferences(): Sequence<String> { val myBroken = this.references.asSequence().filter { it.resolve() == null }.map { it.canonicalText } return myBroken.plus(children.asSequence().flatMap { it.brokenReferences() }) } class ParsePsiException(message: String) : RuntimeException(message) private fun <T : PsiElement> T.assertValid(): T { val brokenReferences = this.brokenReferences().toList() if (brokenReferences.isNotEmpty()) { val first = brokenReferences.first() throw ParsePsiException("Could not resolve reference `$first`") } return this } fun String.asClass(context: PsiElement? = null): PsiClass = parserFacade().createClassFromText(this, context).assertValid() fun String.asStatement(context: PsiElement? = null): PsiStatement = parserFacade().createStatementFromText(this, context).assertValid() fun String.asTypeElement(context: PsiElement? = null): PsiTypeElement = parserFacade().createTypeElementFromText(this, context).assertValid() fun String.asType(context: PsiElement? = null): PsiType = asTypeElement(context).type fun String.asExpression(context: PsiElement? = null): PsiExpression = parserFacade().createExpressionFromText(this, context).assertValid() fun PsiExpression.hasType(type: String): Boolean { try { val thisType = this.type if (thisType != null) { return type.asType(this).isAssignableFrom(thisType) } return false } catch (e: ParsePsiException) { return false } } fun PsiExpression.replaceWithExpression(newNode: String) { this.replace(newNode.asExpression(this)) } //todo: asPsi
gpl-3.0
ebd8c893f4fcdf5a2cf530a05425cf8e
35.784314
141
0.736674
4.352668
false
false
false
false
stripe/stripe-android
stripe-core/src/main/java/com/stripe/android/core/networking/StripeClientUserAgentHeaderFactory.kt
1
1648
package com.stripe.android.core.networking import android.os.Build import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import com.stripe.android.core.AppInfo import com.stripe.android.core.version.StripeSdkVersion import org.json.JSONObject @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class StripeClientUserAgentHeaderFactory( private val systemPropertySupplier: (String) -> String = DEFAULT_SYSTEM_PROPERTY_SUPPLIER ) { fun create( appInfo: AppInfo? = null ): Map<String, String> { return mapOf( HEADER_STRIPE_CLIENT_USER_AGENT to createHeaderValue(appInfo).toString() ) } @VisibleForTesting fun createHeaderValue( appInfo: AppInfo? = null ): JSONObject { return JSONObject( mapOf( "os.name" to "android", "os.version" to Build.VERSION.SDK_INT.toString(), "bindings.version" to StripeSdkVersion.VERSION_NAME, "lang" to "Java", "publisher" to "Stripe", "http.agent" to systemPropertySupplier(PROP_USER_AGENT) ).plus( appInfo?.createClientHeaders().orEmpty() ) ) } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) companion object { // this is the default user agent set by the system private const val PROP_USER_AGENT = "http.agent" private val DEFAULT_SYSTEM_PROPERTY_SUPPLIER = { name: String -> System.getProperty(name).orEmpty() } const val HEADER_STRIPE_CLIENT_USER_AGENT = "X-Stripe-Client-User-Agent" } }
mit
2d97793801970eabd481f0151c80c034
31.313725
93
0.639563
4.382979
false
false
false
false
AndroidX/androidx
wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/CardSample.kt
3
2635
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material.samples import androidx.annotation.Sampled import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.wear.compose.material.AppCard import androidx.wear.compose.material.CardDefaults import androidx.wear.compose.material.Icon import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.Text import androidx.wear.compose.material.TitleCard @Sampled @Composable fun AppCardWithIcon() { AppCard( onClick = {}, appName = { Text("AppName") }, appImage = { Icon( painter = painterResource(id = R.drawable.ic_airplanemode_active_24px), contentDescription = "airplane", modifier = Modifier.size(CardDefaults.AppImageSize) .wrapContentSize(align = Alignment.Center), ) }, title = { Text("AppCard") }, time = { Text("now") }, ) { Text("Some body content") Text("and some more body content") } } @Sampled @Composable fun TitleCardStandard() { TitleCard( onClick = {}, title = { Text("TitleCard") }, time = { Text("now") }, ) { Text("Some body content") Text("and some more body content") } } @Sampled @Composable fun TitleCardWithImage() { TitleCard( onClick = { /* Do something */ }, title = { Text("TitleCard With an ImageBackground") }, backgroundPainter = CardDefaults.imageWithScrimBackgroundPainter( backgroundImagePainter = painterResource(id = R.drawable.backgroundimage) ), contentColor = MaterialTheme.colors.onSurface, titleColor = MaterialTheme.colors.onSurface, ) { Text("Text coloured to stand out on the image") } }
apache-2.0
7abd64c3afb3bc749a954abb884dbd02
31.134146
87
0.679696
4.451014
false
false
false
false
noud02/Akatsuki
src/main/kotlin/moe/kyubey/akatsuki/commands/Plan.kt
1
2673
/* * Copyright (c) 2017-2019 Yui * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package moe.kyubey.akatsuki.commands import io.sentry.Sentry import moe.kyubey.akatsuki.Akatsuki import moe.kyubey.akatsuki.annotations.Argument import moe.kyubey.akatsuki.annotations.Load import moe.kyubey.akatsuki.entities.Command import moe.kyubey.akatsuki.entities.Context import moe.kyubey.akatsuki.utils.Http import okhttp3.HttpUrl @Load @Argument("step 1 | step 2 | step 3", "string") class Plan : Command() { override fun run(ctx: Context) { val stepArg = ctx.args["step 1 | step 2 | step 3"] as String val steps = stepArg.split("\\s?\\|\\s?".toRegex()) if (steps.size < 3) { return ctx.send("Not enough steps!") // TODO translation } val step1 = steps[0] val step2 = steps[1] val step3 = steps[2] Http.get(HttpUrl.Builder().apply { scheme(if (Akatsuki.config.backend.ssl) "https" else "http") host(Akatsuki.config.backend.host) port(Akatsuki.config.backend.port) addPathSegments("api/plan") addQueryParameter("step1", step1) addQueryParameter("step2", step2) addQueryParameter("step3", step3) }.build()).thenAccept { res -> ctx.channel.sendFile(res.body()!!.bytes(), "plan.png").queue() res.close() }.thenApply {}.exceptionally { ctx.logger.error("Error while trying to get plan image from backend", it) Sentry.capture(it) ctx.sendError(it) } } }
mit
34ee0d346e94e21a07f871fc9d408b40
37.753623
85
0.667415
4.131376
false
false
false
false
MeilCli/Twitter4HK
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/lists/members/Create.kt
1
2102
package com.twitter.meil_mitu.twitter4hk.api.lists.members import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.AbsPost import com.twitter.meil_mitu.twitter4hk.OauthType import com.twitter.meil_mitu.twitter4hk.converter.IUserListConverter import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException class Create<TUserList> : AbsPost<TUserList> { protected val json: IUserListConverter<TUserList> var listId: Long? by longParam("list_id") var userId: Long? by longParam("user_id") var screenName: String? by stringParam("screen_name") var slug: String? by stringParam("slug") var ownerScreenName: String? by stringParam("owner_screen_name") var ownerId: Long? by longParam("owner_id") override val url = "https://api.twitter.com/1.1/lists/members/create.json" override val allowOauthType = OauthType.oauth1 override val isAuthorization = true constructor( oauth: AbsOauth, json: IUserListConverter<TUserList>, listId: Long, userId: Long) : super(oauth) { this.json = json this.listId = listId this.userId = userId } constructor( oauth: AbsOauth, json: IUserListConverter<TUserList>, listId: Long, screenName: String) : super(oauth) { this.json = json this.listId = listId this.screenName = screenName } constructor( oauth: AbsOauth, json: IUserListConverter<TUserList>, slug: String, userId: Long) : super(oauth) { this.json = json this.slug = slug this.userId = userId } constructor( oauth: AbsOauth, json: IUserListConverter<TUserList>, slug: String, screenName: String) : super(oauth) { this.json = json this.slug = slug this.screenName = screenName } @Throws(Twitter4HKException::class) override fun call(): TUserList { return json.toUserList(oauth.post(this)) } }
mit
d6c04794a6aabb19816deeda6da88199
30.848485
78
0.638915
4.195609
false
false
false
false
mvarnagiris/expensius
app-core/src/main/kotlin/com/mvcoding/expensius/feature/RxState.kt
1
1252
package com.mvcoding.expensius.feature import rx.Subscription import rx.lang.kotlin.BehaviorSubject import kotlin.reflect.KClass class RxState<in STATE : Any>(initialState: STATE? = null) { private val stateSubject = BehaviorSubject<STATE>() private val stateActions = hashMapOf<KClass<out STATE>, (STATE) -> List<Subscription>>() private val currentSubscriptions = arrayListOf<Subscription>() private var stateSubscription: Subscription? = null init { if (initialState != null) stateSubject.onNext(initialState) } fun <PRECISE_STATE : STATE> registerState(state: KClass<PRECISE_STATE>, action: (PRECISE_STATE) -> List<Subscription>) { @Suppress("UNCHECKED_CAST") stateActions.put(state, action as (STATE) -> List<Subscription>) } fun subscribe() { stateSubscription = stateSubject.subscribe { currentSubscriptions.forEach { it.unsubscribe() } currentSubscriptions.clear() currentSubscriptions.addAll(stateActions[it::class]?.invoke(it) ?: emptyList()) } } fun setState(state: STATE): Unit = stateSubject.onNext(state) fun unsubscribe() { stateSubscription?.unsubscribe() stateSubscription = null } }
gpl-3.0
693f5cbf1fb47f24f8e2cae174e62aa0
32.864865
124
0.686102
4.503597
false
false
false
false
charleskorn/batect
app/src/journeyTest/kotlin/batect/journeytests/testutils/ApplicationRunner.kt
1
3109
/* Copyright 2017-2020 Charles Korn. 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 batect.journeytests.testutils import java.io.InputStreamReader import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import kotlin.streams.toList data class ApplicationRunner(val testName: String) { val testDirectory: Path = Paths.get("src/journeyTest/resources", testName).toAbsolutePath() init { if (!Files.isDirectory(testDirectory)) { throw RuntimeException("The directory $testDirectory does not exist or is not a directory.") } } fun runApplication(arguments: Iterable<String>, environment: Map<String, String> = emptyMap(), afterStart: (Process) -> Unit = {}): ApplicationResult { val commandLine = commandLineForApplication(arguments) return runCommandLine(commandLine, environment, afterStart) } fun runCommandLine(commandLine: List<String>, environment: Map<String, String> = emptyMap(), afterStart: (Process) -> Unit = {}): ApplicationResult { val containersBefore = DockerUtils.getAllCreatedContainers() val networksBefore = DockerUtils.getAllNetworks() val builder = ProcessBuilder(commandLine) .directory(testDirectory.toFile()) .redirectErrorStream(true) builder.environment().putAll(environment) val process = builder.start() afterStart(process) val output = InputStreamReader(process.inputStream).readText() process.waitFor() val containersAfter = DockerUtils.getAllCreatedContainers() val potentiallyOrphanedContainers = containersAfter - containersBefore val networksAfter = DockerUtils.getAllNetworks() val potentiallyOrphanedNetworks = networksAfter - networksBefore return ApplicationResult(process.exitValue(), output, potentiallyOrphanedContainers, potentiallyOrphanedNetworks) } fun commandLineForApplication(arguments: Iterable<String>): List<String> { val applicationDirectory: Path = Paths.get("build/install/app-shadow/lib").toAbsolutePath() val applicationPath = Files.list(applicationDirectory).toList() .single { it.fileName.toString().startsWith("batect-") && it.fileName.toString().endsWith(".jar") } .toAbsolutePath() return listOf("java", "-jar", applicationPath.toString()) + arguments } } data class ApplicationResult( val exitCode: Int, val output: String, val potentiallyOrphanedContainers: Set<String>, val potentiallyOrphanedNetworks: Set<String> )
apache-2.0
19a7d2064a51286c7a8c14f3e05ae66e
37.8625
155
0.719202
4.873041
false
true
false
false
SevenLines/Celebs-Image-Viewer
src/main/kotlin/theplace/views/GalleryAlbumLayout.kt
1
4795
package theplace.views import javafx.animation.FadeTransition import javafx.animation.Interpolator import javafx.animation.ParallelTransition import javafx.animation.TranslateTransition import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleIntegerProperty import javafx.event.EventHandler import javafx.scene.image.Image import javafx.scene.image.ImageView import javafx.scene.input.MouseButton import javafx.scene.layout.AnchorPane import javafx.scene.layout.BorderPane import javafx.scene.layout.FlowPane import javafx.scene.shape.Rectangle import javafx.util.Duration import theplace.imageloaders.LoadedImage import theplace.parsers.elements.GalleryAlbumPage import tornadofx.Fragment import java.io.InputStream import kotlin.properties.Delegates /** * Created by mk on 03.04.16. */ class GalleryAlbumLayout(albumPage: GalleryAlbumPage) : Fragment() { override val root: AnchorPane by fxml() val flowPanel: FlowPane by fxid() val imageContainer: ImageView by fxid() val imageWrapContainer: BorderPane by fxid() val imageContainerShowAnimation = ParallelTransition(imageWrapContainer) val albumLoadingComplete = SimpleBooleanProperty(false) companion object { @JvmStatic val imageLoading = Image(GalleryAlbumLayout::class.java.getResourceAsStream("images/loading.gif")) @JvmStatic val duration = Duration(300.0) } fun setFit(isReal: Boolean=false) { if (isReal) { imageContainer.fitWidth = 0.0 imageContainer.fitHeight = 0.0 } else { imageContainer.fitWidth = root.width imageContainer.fitHeight = root.height } } fun prepareAnimation() { // WRAPPER ANIMATION val imageContainerFadeTransition = FadeTransition(duration, imageWrapContainer) imageContainerFadeTransition.fromValue = 0.0 imageContainerFadeTransition.interpolator = Interpolator.EASE_BOTH imageContainerFadeTransition.toValue = 1.0 val imageContainerTranslateTransition = TranslateTransition(duration, imageWrapContainer) imageContainerTranslateTransition.fromYProperty().bind( SimpleIntegerProperty(0).subtract(imageWrapContainer.heightProperty())) imageContainerTranslateTransition.toY = 0.0 imageContainerTranslateTransition.interpolator = Interpolator.EASE_BOTH imageContainerShowAnimation.children.addAll(imageContainerFadeTransition, imageContainerTranslateTransition) } init { prepareAnimation() flowPanel.prefWidthProperty().bind(root.widthProperty()) imageWrapContainer.isVisible = false imageWrapContainer.onMouseClicked = EventHandler { if (it.button == MouseButton.SECONDARY) { imageContainerShowAnimation.rate = -1.0 imageContainerShowAnimation.play() } } var clipRect = Rectangle(root.width, root.height) clipRect.widthProperty().bind(root.widthProperty()) clipRect.heightProperty().bind(root.heightProperty()) root.clip = clipRect imageWrapContainer.layoutBoundsProperty().addListener({ obj -> setFit() }) background { albumPage.images } ui { flowPanel.children.addAll(albumPage.images.map { var galleryImageLayout = GalleryImageLayout(it) galleryImageLayout.onImageClick = EventHandler { if (it.button == MouseButton.PRIMARY) { imageContainer.image = imageLoading imageWrapContainer.isVisible = true imageContainerShowAnimation.rate = 1.0 imageContainerShowAnimation.play() var loadedImage: LoadedImage? = null setFit(true) background { loadedImage = galleryImageLayout.img.download() } ui { if (loadedImage != null && loadedImage?.body!= null) { setFit(false) if (loadedImage?.body?.markSupported() ?: false) { loadedImage?.body?.reset() } imageContainer.image = Image(loadedImage?.body) imageContainer.viewport = imageContainer.viewport } else { imageContainer.image = null } } } } return@map galleryImageLayout.root }) albumLoadingComplete.set(true) } } }
mit
a85a58774cae38adc75b90d303b6c3e6
38.636364
117
0.633577
5.524194
false
false
false
false
vitorsalgado/android-boilerplate
api/src/main/kotlin/br/com/vitorsalgado/example/api/Tls12SslSocketFactory.kt
1
2126
package br.com.vitorsalgado.example.api import okhttp3.TlsVersion import java.io.IOException import java.net.InetAddress import java.net.Socket import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory class Tls12SslSocketFactory internal constructor() : SSLSocketFactory() { companion object { private val PROTOCOL = TlsVersion.TLS_1_2.toString() } private val socketFactory: SSLSocketFactory = SSLSocketFactory.getDefault() as SSLSocketFactory override fun getDefaultCipherSuites(): Array<String> { return socketFactory.defaultCipherSuites } override fun getSupportedCipherSuites(): Array<String> { return socketFactory.supportedCipherSuites } @Throws(IOException::class) override fun createSocket(socket: Socket, host: String, port: Int, autoClose: Boolean): Socket { val sslSocket = socketFactory.createSocket(socket, host, port, autoClose) as SSLSocket sslSocket.enabledProtocols = arrayOf(PROTOCOL) return sslSocket } @Throws(IOException::class) override fun createSocket(host: String, port: Int): Socket { val sslSocket = socketFactory.createSocket(host, port) as SSLSocket sslSocket.enabledProtocols = arrayOf(PROTOCOL) return sslSocket } @Throws(IOException::class) override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int): Socket { val sslSocket = socketFactory.createSocket(host, port, localHost, localPort) as SSLSocket sslSocket.enabledProtocols = arrayOf(PROTOCOL) return sslSocket } @Throws(IOException::class) override fun createSocket(host: InetAddress, port: Int): Socket { val sslSocket = socketFactory.createSocket(host, port) as SSLSocket sslSocket.enabledProtocols = arrayOf(PROTOCOL) return sslSocket } @Throws(IOException::class) override fun createSocket( address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int ): Socket { val sslSocket = socketFactory.createSocket(address, port, localAddress, localPort) as SSLSocket sslSocket.enabledProtocols = arrayOf(PROTOCOL) return sslSocket } }
apache-2.0
d61cf36b835cabe30e4c89a6bb0d0ec9
29.811594
102
0.757291
4.756152
false
false
false
false
JakeWharton/Reagent
reagent/common/src/test/kotlin/reagent/operator/TaskMapTest.kt
1
1353
/* * Copyright 2016 Jake Wharton * * 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 reagent.operator import reagent.runTest import reagent.source.observableOf import reagent.source.toTask import reagent.tester.testTask import kotlin.test.Test import kotlin.test.fail class TaskMapTest { @Test fun map() = runTest { observableOf("Hello") .map(String::toUpperCase) .testTask { item("HELLO") } } @Test fun mapError() = runTest { val exception = RuntimeException("Oops!") exception.toTask() .map { fail() } .testTask { error(exception) } } @Test fun mapThrowing() = runTest { val exception = RuntimeException("Oops!") observableOf("Hello") .map { throw exception } .testTask { error(exception) } } }
apache-2.0
aadd04579e3d6681a187af115af43e47
25.529412
75
0.667406
4.201863
false
true
false
false
inorichi/tachiyomi-extensions
src/pt/mangatube/src/eu/kanade/tachiyomi/extension/pt/mangatube/MangaTube.kt
1
10916
package eu.kanade.tachiyomi.extension.pt.mangatube import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.util.asJsoup import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.floatOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import okhttp3.FormBody import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Element import rx.Observable import uy.kohesive.injekt.injectLazy import java.text.ParseException import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit class MangaTube : HttpSource() { override val name = "MangaTube" override val baseUrl = "https://mangatube.site" override val lang = "pt-BR" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient.newBuilder() .addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS)) .addInterceptor(::searchIntercept) .build() override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("Accept", ACCEPT_HTML) .add("Accept-Language", ACCEPT_LANGUAGE) .add("Referer", "$baseUrl/") private fun apiHeadersBuilder(): Headers.Builder = headersBuilder() .set("Accept", ACCEPT) .add("X-Requested-With", "XMLHttpRequest") private val apiHeaders: Headers by lazy { apiHeadersBuilder().build() } private val json: Json by injectLazy() override fun popularMangaRequest(page: Int): Request { return GET(baseUrl, headers) } override fun popularMangaParse(response: Response): MangasPage { val document = response.asJsoup() val mangas = document.select("div:contains(Populares) ~ ul.mangasList li div.gridbox") .map(::popularMangaFromElement) return MangasPage(mangas, hasNextPage = false) } private fun popularMangaFromElement(element: Element): SManga = SManga.create().apply { title = element.select("div.title a").first()!!.text() thumbnail_url = element.select("div.thumb img").first()!!.attr("abs:src") setUrlWithoutDomain(element.select("a").first()!!.attr("href")) } override fun latestUpdatesRequest(page: Int): Request { val form = FormBody.Builder() .add("pagina", page.toString()) .build() val newHeaders = apiHeadersBuilder() .add("Content-Length", form.contentLength().toString()) .add("Content-Type", form.contentType().toString()) .build() return POST("$baseUrl/jsons/news/chapters.json", newHeaders, form) } override fun latestUpdatesParse(response: Response): MangasPage { val result = json.decodeFromString<MangaTubeLatestDto>(response.body!!.string()) val latestMangas = result.releases .map(::latestUpdatesFromObject) val hasNextPage = result.page.toInt() < result.totalPage return MangasPage(latestMangas, hasNextPage) } private fun latestUpdatesFromObject(release: MangaTubeReleaseDto) = SManga.create().apply { title = release.name thumbnail_url = release.image url = release.link } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = "$baseUrl/wp-json/site/search/".toHttpUrlOrNull()!!.newBuilder() .addQueryParameter("keyword", query) .addQueryParameter("type", "undefined") .toString() return GET(url, apiHeaders) } override fun searchMangaParse(response: Response): MangasPage { val result = json.decodeFromString<Map<String, MangaTubeTitleDto>>(response.body!!.string()) val searchResults = result.values.map(::searchMangaFromObject) return MangasPage(searchResults, hasNextPage = false) } private fun searchMangaFromObject(manga: MangaTubeTitleDto) = SManga.create().apply { title = manga.title thumbnail_url = manga.image setUrlWithoutDomain(manga.url) } override fun mangaDetailsParse(response: Response): SManga { val document = response.asJsoup() val infoElement = document.select("div.manga-single div.dados").first() return SManga.create().apply { title = infoElement.select("h1").first()!!.text() thumbnail_url = infoElement.select("div.thumb img").first()!!.attr("abs:src") description = infoElement.select("div.sinopse").first()!!.text() genre = infoElement.select("ul.generos li a span.button").joinToString { it.text() } } } override fun chapterListRequest(manga: SManga): Request = chapterListPaginatedRequest(manga.url) private fun chapterListPaginatedRequest(mangaUrl: String, page: Int = 1): Request { val mangaId = mangaUrl.substringAfterLast("/") val newHeaders = apiHeadersBuilder() .set("Referer", baseUrl + mangaUrl) .build() val url = "$baseUrl/jsons/series/chapters_list.json".toHttpUrlOrNull()!!.newBuilder() .addQueryParameter("page", page.toString()) .addQueryParameter("order", "desc") .addQueryParameter("id_s", mangaId) .toString() return GET(url, newHeaders) } override fun chapterListParse(response: Response): List<SChapter> { val mangaUrl = response.request.header("Referer")!!.substringAfter(baseUrl) var result = json.decodeFromString<MangaTubePaginatedChaptersDto>(response.body!!.string()) if (result.chapters.isNullOrEmpty()) { return emptyList() } val chapters = result.chapters!! .map(::chapterFromObject) .toMutableList() var page = result.page + 1 val lastPage = result.totalPages while (++page <= lastPage) { val nextPageRequest = chapterListPaginatedRequest(mangaUrl, page) result = client.newCall(nextPageRequest).execute().let { json.decodeFromString(it.body!!.string()) } chapters += result.chapters!! .map(::chapterFromObject) .toMutableList() } return chapters } private fun chapterFromObject(chapter: MangaTubeChapterDto): SChapter = SChapter.create().apply { name = "Cap. " + (if (chapter.number.booleanOrNull != null) "0" else chapter.number.content) + (if (chapter.name.isString) " - " + chapter.name.content else "") chapter_number = chapter.number.floatOrNull ?: -1f date_upload = chapter.dateCreated.substringBefore("T").toDate() setUrlWithoutDomain(chapter.link) } private fun pageListApiRequest(chapterUrl: String, serieId: String, token: String): Request { val newHeaders = apiHeadersBuilder() .set("Referer", chapterUrl) .build() val url = "$baseUrl/jsons/series/images_list.json".toHttpUrlOrNull()!!.newBuilder() .addQueryParameter("id_serie", serieId) .addQueryParameter("secury", token) .toString() return GET(url, newHeaders) } override fun pageListParse(response: Response): List<Page> { val document = response.asJsoup() val apiParams = document.select("script:containsData(id_serie)").firstOrNull() ?.data() ?: throw Exception(TOKEN_NOT_FOUND) val chapterUrl = response.request.url.toString() val serieId = apiParams.substringAfter("\"") .substringBefore("\"") val token = TOKEN_REGEX.find(apiParams)!!.groupValues[1] val apiRequest = pageListApiRequest(chapterUrl, serieId, token) val apiResponse = client.newCall(apiRequest).execute().let { json.decodeFromString<MangaTubeReaderDto>(it.body!!.string()) } return apiResponse.images .filter { it.url.startsWith("http") } .mapIndexed { i, page -> Page(i, chapterUrl, page.url) } } override fun fetchImageUrl(page: Page): Observable<String> = Observable.just(page.imageUrl!!) override fun imageUrlParse(response: Response): String = "" override fun imageRequest(page: Page): Request { val newHeaders = headersBuilder() .set("Accept", ACCEPT_IMAGE) .set("Referer", page.url) .build() return GET(page.imageUrl!!, newHeaders) } private fun searchIntercept(chain: Interceptor.Chain): Response { if (chain.request().url.toString().contains("/search/")) { val homeRequest = popularMangaRequest(1) val document = chain.proceed(homeRequest).asJsoup() val apiParams = document.select("script:containsData(pAPI)").first()!!.data() .substringAfter("pAPI = ") .substringBeforeLast(";") .let { json.parseToJsonElement(it) } .jsonObject val newUrl = chain.request().url.newBuilder() .addQueryParameter("nonce", apiParams["nonce"]!!.jsonPrimitive.content) .build() val newRequest = chain.request().newBuilder() .url(newUrl) .build() return chain.proceed(newRequest) } return chain.proceed(chain.request()) } private fun String.toDate(): Long { return try { DATE_FORMATTER.parse(this)?.time ?: 0L } catch (e: ParseException) { 0L } } companion object { private const val ACCEPT = "application/json, text/plain, */*" private const val ACCEPT_HTML = "text/html,application/xhtml+xml,application/xml;q=0.9," + "image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" private const val ACCEPT_IMAGE = "image/avif,image/webp,image/apng,image/*,*/*;q=0.8" private const val ACCEPT_LANGUAGE = "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6,gl;q=0.5" private val TOKEN_REGEX = "token\\s+= \"(.*)\"".toRegex() private val DATE_FORMATTER by lazy { SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH) } private const val TOKEN_NOT_FOUND = "Não foi possível obter o token de leitura." } }
apache-2.0
2849ee9d8190f180f9160b480cd0bb59
36.122449
102
0.651365
4.511782
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/plugin/PluginPostfixLookupPsiImpl.kt
1
3718
/* * Copyright (C) 2020-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.xpath.psi.impl.plugin import com.intellij.lang.ASTNode import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.psi.ASTWrapperPsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.core.sequences.filterIsElementType import uk.co.reecedunn.intellij.plugin.core.sequences.siblings import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNodeItem import uk.co.reecedunn.intellij.plugin.xdm.types.XdmWildcardValue import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginPostfixLookup import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathNCName import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathStringLiteral import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathVarRef import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.impl.XdmWildcardExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.impl.XsNCNameExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.path.XpmAxisType import xqt.platform.intellij.xpath.XPathTokenProvider class PluginPostfixLookupPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), PluginPostfixLookup, XpmSyntaxValidationElement { companion object { private val KEY_EXPRESSION = Key.create<XpmExpression>("KEY_EXPRESSION") } // region PsiElement override fun subtreeChanged() { super.subtreeChanged() clearUserData(KEY_EXPRESSION) } // endregion // region XpmPathStep override val axisType: XpmAxisType = XpmAxisType.Self override val nodeName: XsQNameValue? = null override val nodeType: XdmItemType = XdmNodeItem override val predicateExpression: XpmExpression? = null // endregion // region XpmLookupExpression override val expressionElement: PsiElement get() = children().filterIsElementType(XPathTokenProvider.QuestionMark).first() override val contextExpression: XpmExpression get() = firstChild as XpmExpression override val keyExpression: XpmExpression get() = computeUserDataIfAbsent(KEY_EXPRESSION) { expressionElement.siblings().mapNotNull { when (it) { is XpmExpression -> it is XPathNCName -> XsNCNameExpression(it.localName!!) is XdmWildcardValue -> XdmWildcardExpression else -> null } }.first() } // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = when (val lookup = keyExpression) { is XPathStringLiteral -> lookup is XPathVarRef -> lookup else -> expressionElement } // endregion }
apache-2.0
f845aa111169848a310a0004655fde42
38.136842
87
0.74099
4.479518
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/codegen/bridges/test7.kt
1
496
// generic interface, non-generic impl, vtable call + interface call open class A { open var size: Int = 56 } interface C<T> { var size: T } open class B : C<Int>, A() fun box(): String { val b = B() if (b.size != 56) return "fail 1" b.size = 55 if (b.size != 55) return "fail 2" val c: C<Int> = b if (c.size != 55) return "fail 3" c.size = 57 if (c.size != 57) return "fail 4" return "OK" } fun main(args: Array<String>) { println(box()) }
apache-2.0
6dfdffba78ad2f7bd27014ebb0cb4122
15.566667
68
0.550403
2.867052
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/core/presenters/SearchSuggestionsPresenter.kt
2
2685
package org.stepic.droid.core.presenters import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import io.reactivex.subjects.PublishSubject import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.analytic.Analytic import org.stepic.droid.core.presenters.contracts.SearchSuggestionsView import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepic.droid.model.SearchQuerySource import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.search.repository.SearchRepository import java.util.concurrent.TimeUnit class SearchSuggestionsPresenter constructor( private val courseId: Long, private val searchRepository: SearchRepository, private val analytic: Analytic, @BackgroundScheduler private val scheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<SearchSuggestionsView>() { companion object { private const val AUTOCOMPLETE_DEBOUNCE_MS = 300L } private val compositeDisposable = CompositeDisposable() private val publisher = PublishSubject.create<String>() override fun attachView(view: SearchSuggestionsView) { super.attachView(view) initSearchView(view) } private fun initSearchView(searchView: SearchSuggestionsView) { val queryPublisher = publisher .debounce(AUTOCOMPLETE_DEBOUNCE_MS, TimeUnit.MILLISECONDS) .subscribeOn(scheduler) compositeDisposable += queryPublisher .flatMap { query -> searchRepository.getSearchQueries(courseId, query, DataSourceType.CACHE).toObservable().onErrorResumeNext(Observable.empty()) } .observeOn(mainScheduler) .subscribe { searchView.setSuggestions(it, SearchQuerySource.DB) } compositeDisposable += queryPublisher .flatMap { query -> searchRepository.getSearchQueries(courseId, query, DataSourceType.REMOTE).toObservable().onErrorResumeNext(Observable.empty()) } .observeOn(mainScheduler) .subscribe { searchView.setSuggestions(it, SearchQuerySource.API) } } fun onQueryTextChange(query: String) { publisher.onNext(query) } fun onQueryTextSubmit(query: String) { analytic.reportAmplitudeEvent(AmplitudeAnalytic.Search.SEARCHED, mapOf(AmplitudeAnalytic.Search.PARAM_SUGGESTION to query.toLowerCase())) } override fun detachView(view: SearchSuggestionsView) { compositeDisposable.clear() super.detachView(view) } }
apache-2.0
51faf5ad35a85e098c6c6c27e9c873a1
37.927536
164
0.753073
5.094877
false
false
false
false
mtransitapps/parser
src/main/java/org/mtransit/parser/gtfs/data/GRouteType.kt
1
2035
package org.mtransit.parser.gtfs.data // https://developers.google.com/transit/gtfs/reference/#routestxt // https://developers.google.com/transit/gtfs/reference/extended-route-types enum class GRouteType( // Communal Taxi Service (Please use 717) val id: Int ) { // STANDARD: LIGHT_RAIL(0), // Tram, streetcar, or light rail. Used for any light rail or street-level system within a metropolitan area. SUBWAY(1), // Subway or metro. Used for any underground rail system within a metropolitan area. TRAIN(2), // Rail. Used for intercity or long-distance travel. BUS(3), // Bus. Used for short- and long-distance bus routes. FERRY(4), // Ferry. Used for short- and long-distance boat service // 5: Cable car. Used for street-level cable cars where the cable runs beneath the car. // 6: Gondola or suspended cable car. Typically used for aerial cable cars where the car is suspended from the cable. // 7: Funicular. Used for any rail system that moves on steep inclines with a cable traction system. // EXTENDED: EX_BUS_SERVICE(700), // Bus Service EX_DEMAND_AND_RESPONSE_BUS_SERVICE(715), // Demand and Response Bus Service EX_SHARE_TAXI_SERVICE(717), // Share Taxi Service EX_COMMUNAL_TAXI_SERVICE(1501); companion object { @JvmStatic fun isUnknown(routeType: Int): Boolean { return values().none { it.id == routeType } } @JvmStatic fun isSameType(agencyRouteType: Int, routeType: Int): Boolean { if (agencyRouteType == routeType) { return true } if (agencyRouteType == BUS.id) { if (routeType == EX_BUS_SERVICE.id || routeType == EX_DEMAND_AND_RESPONSE_BUS_SERVICE.id || routeType == EX_SHARE_TAXI_SERVICE.id || routeType == EX_COMMUNAL_TAXI_SERVICE.id ) { return true } } return false } } }
apache-2.0
575e6ee2ba48820e5d4ceee93cd7ad44
41.416667
129
0.618182
3.818011
false
false
false
false
fhanik/spring-security
config/src/test/kotlin/org/springframework/security/config/web/servlet/CsrfDslTests.kt
1
8727
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.web.servlet import org.junit.Rule import org.junit.Test import org.mockito.Mockito.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.test.SpringTestRule import org.springframework.security.core.Authentication import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.provisioning.InMemoryUserDetailsManager import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy import org.springframework.security.web.csrf.CsrfTokenRepository import org.springframework.security.web.csrf.DefaultCsrfToken import org.springframework.security.web.util.matcher.AntPathRequestMatcher import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get import org.springframework.test.web.servlet.post import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RestController import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Tests for [CsrfDsl] * * @author Eleftheria Stein */ class CsrfDslTests { @Rule @JvmField val spring = SpringTestRule() @Autowired lateinit var mockMvc: MockMvc @Test fun `POST when CSRF enabled and no CSRF token then forbidden`() { this.spring.register(DefaultCsrfConfig::class.java).autowire() this.mockMvc.post("/test1") .andExpect { status { isForbidden() } } } @Test fun `POST when CSRF enabled and CSRF token then status OK`() { this.spring.register(DefaultCsrfConfig::class.java, BasicController::class.java).autowire() this.mockMvc.post("/test1") { with(csrf()) }.andExpect { status { isOk() } } } @EnableWebSecurity open class DefaultCsrfConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { csrf { } } } } @Test fun `POST when CSRF disabled and no CSRF token then status OK`() { this.spring.register(CsrfDisabledConfig::class.java, BasicController::class.java).autowire() this.mockMvc.post("/test1") .andExpect { status { isOk() } } } @EnableWebSecurity open class CsrfDisabledConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { csrf { disable() } } } } @Test fun `CSRF when custom CSRF token repository then repo used`() { `when`(CustomRepositoryConfig.REPO.loadToken(any<HttpServletRequest>())) .thenReturn(DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token")) this.spring.register(CustomRepositoryConfig::class.java).autowire() this.mockMvc.get("/test1") verify(CustomRepositoryConfig.REPO).loadToken(any<HttpServletRequest>()) } @EnableWebSecurity open class CustomRepositoryConfig : WebSecurityConfigurerAdapter() { companion object { var REPO: CsrfTokenRepository = mock(CsrfTokenRepository::class.java) } override fun configure(http: HttpSecurity) { http { csrf { csrfTokenRepository = REPO } } } } @Test fun `CSRF when require CSRF protection matcher then CSRF protection on matching requests`() { this.spring.register(RequireCsrfProtectionMatcherConfig::class.java, BasicController::class.java).autowire() this.mockMvc.post("/test1") .andExpect { status { isForbidden() } } this.mockMvc.post("/test2") .andExpect { status { isOk() } } } @EnableWebSecurity open class RequireCsrfProtectionMatcherConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { csrf { requireCsrfProtectionMatcher = AntPathRequestMatcher("/test1") } } } } @Test fun `CSRF when custom session authentication strategy then strategy used`() { this.spring.register(CustomStrategyConfig::class.java).autowire() this.mockMvc.perform(formLogin()) verify(CustomStrategyConfig.STRATEGY, atLeastOnce()) .onAuthentication(any(Authentication::class.java), any(HttpServletRequest::class.java), any(HttpServletResponse::class.java)) } @EnableWebSecurity open class CustomStrategyConfig : WebSecurityConfigurerAdapter() { companion object { var STRATEGY: SessionAuthenticationStrategy = mock(SessionAuthenticationStrategy::class.java) } override fun configure(http: HttpSecurity) { http { formLogin { } csrf { sessionAuthenticationStrategy = STRATEGY } } } @Bean override fun userDetailsService(): UserDetailsService { val userDetails = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build() return InMemoryUserDetailsManager(userDetails) } } @Test fun `CSRF when ignoring request matchers then CSRF disabled on matching requests`() { this.spring.register(IgnoringRequestMatchersConfig::class.java, BasicController::class.java).autowire() this.mockMvc.post("/test1") .andExpect { status { isForbidden() } } this.mockMvc.post("/test2") .andExpect { status { isOk() } } } @EnableWebSecurity open class IgnoringRequestMatchersConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { csrf { requireCsrfProtectionMatcher = AntPathRequestMatcher("/**") ignoringRequestMatchers(AntPathRequestMatcher("/test2")) } } } } @Test fun `CSRF when ignoring ant matchers then CSRF disabled on matching requests`() { this.spring.register(IgnoringAntMatchersConfig::class.java, BasicController::class.java).autowire() this.mockMvc.post("/test1") .andExpect { status { isForbidden() } } this.mockMvc.post("/test2") .andExpect { status { isOk() } } } @EnableWebSecurity open class IgnoringAntMatchersConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { csrf { requireCsrfProtectionMatcher = AntPathRequestMatcher("/**") ignoringAntMatchers("/test2") } } } } @RestController internal class BasicController { @PostMapping("/test1") fun test1() { } @PostMapping("/test2") fun test2() { } } }
apache-2.0
e9e4d6583292d19d3b5e2e6d1c1dad8a
31.932075
141
0.63103
5.301944
false
true
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/components/DuplicateMangaDialog.kt
1
1775
package eu.kanade.presentation.components import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.source.Source @Composable fun DuplicateMangaDialog( onDismissRequest: () -> Unit, onConfirm: () -> Unit, onOpenManga: () -> Unit, duplicateFrom: Source, ) { AlertDialog( onDismissRequest = onDismissRequest, confirmButton = { Row { TextButton(onClick = { onDismissRequest() onOpenManga() },) { Text(text = stringResource(R.string.action_show_manga)) } Spacer(modifier = Modifier.weight(1f)) TextButton(onClick = onDismissRequest) { Text(text = stringResource(android.R.string.cancel)) } TextButton( onClick = { onDismissRequest() onConfirm() }, ) { Text(text = stringResource(R.string.action_add)) } } }, title = { Text(text = stringResource(R.string.are_you_sure)) }, text = { Text( text = stringResource( id = R.string.confirm_manga_add_duplicate, duplicateFrom.name, ), ) }, ) }
apache-2.0
3f629b447f585352a59ba224d25667ce
30.140351
75
0.538028
5.144928
false
false
false
false
rlac/unitconverter
app/src/main/kotlin/au/id/rlac/unitconverter/widget/AspectFrameLayout.kt
1
1389
package au.id.rlac.unitconverter.widget import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout /** * FrameLayout that sets its width or height to best fit while maintaining an aspect ratio. */ open class AspectFrameLayout : FrameLayout { constructor(context: Context) : super(context) { } constructor(context: Context, attrs: AttributeSet) : super(context, attrs, 0) { } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { } private val targetAspect = 0.75 // 3:4 aspect ratio for 3x4 buttons override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var width = MeasureSpec.getSize(widthMeasureSpec) var height = MeasureSpec.getSize(heightMeasureSpec) width -= getPaddingLeft() + getPaddingRight() height -= getPaddingTop() - getPaddingBottom() val initialAspect = width.toDouble() / height.toDouble() if (targetAspect / initialAspect - 1 > 0) { height = (width / targetAspect).toInt() } else { width = (height * targetAspect).toInt() } width += getPaddingLeft() + getPaddingRight() height += getPaddingTop() + getPaddingBottom() super<FrameLayout>.onMeasure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)) } }
apache-2.0
cae8920bf03df2e96d0589c949148a24
30.590909
103
0.716343
4.451923
false
false
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/preferences/KoinModule.kt
2
755
package com.fsck.k9.preferences import com.fsck.k9.Preferences import org.koin.core.qualifier.named import org.koin.dsl.bind import org.koin.dsl.module val preferencesModule = module { factory { SettingsExporter( contentResolver = get(), preferences = get(), folderSettingsProvider = get(), folderRepository = get(), notificationSettingsUpdater = get() ) } factory { FolderSettingsProvider(folderRepository = get()) } factory<AccountManager> { get<Preferences>() } single { RealGeneralSettingsManager( preferences = get(), coroutineScope = get(named("AppCoroutineScope")) ) } bind GeneralSettingsManager::class }
apache-2.0
b9ed97e208b5bf33cb3646ade233ceca
28.038462
64
0.635762
4.934641
false
false
false
false
TeamMeanMachine/meanlib
src/main/kotlin/org/team2471/frc/lib/coroutines/CoroutineUtils.kt
1
3737
package org.team2471.frc.lib.coroutines import edu.wpi.first.wpilibj.DriverStation import edu.wpi.first.wpilibj.Watchdog import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.yield import org.team2471.frc.lib.units.Time import org.team2471.frc.lib.util.measureTimeFPGA class PeriodicScope @PublishedApi internal constructor(val period: Double) { @PublishedApi internal var isDone = false fun stop() { isDone = true } } /** * An alias of `launch(MeanlibDispatcher)`. * * @see CoroutineScope.launch */ fun CoroutineScope.meanlibLaunch( start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ) = launch(MeanlibDispatcher, start, block) /** * Runs the provided [body] of code periodically per [period] seconds. * * The provided [body] loop will continue to loop until [PeriodicScope.stop] is called, or an exception is thrown. * Note that if [PeriodicScope.stop] is called the body will continue to run to the end of the loop. If your * intention is to exit the code early, insert a return after calling [PeriodicScope.stop]. * * The [period] parameter defaults to 0.02 seconds, or 20 milliseconds. * * If the [body] takes longer than the [period] to complete, a warning is printed. This can * be disabled by setting the [watchOverrun] parameter to false. */ suspend inline fun periodic( period: Double = 0.02, watchOverrun: Boolean = false, crossinline body: PeriodicScope.() -> Unit ) { val scope = PeriodicScope(period) val watchdog = if (watchOverrun) { Watchdog(period) { DriverStation.reportWarning("Periodic loop overrun", true) } } else { null } while (true) { watchdog?.reset() val dt = measureTimeFPGA { body(scope) } if (scope.isDone) break val remainder = period - dt if (remainder <= 0.0) { yield() } else { delay(remainder) } } // var cont: CancellableContinuation<Unit>? = null // var notifier: Notifier? = null // try { // suspendCancellableCoroutine<Unit> { c -> // cont = c // notifier = Notifier { // body(scope) // watchdog?.reset() // if (scope.isDone && c.isActive) c.resume(Unit) // }.apply { startPeriodic(period) } // } // } catch (e: Throwable) { // cont?.cancel(e) // } finally { // notifier?.close() // watchdog?.close() // } } /** * Suspends until [condition] evaluates to true. * * @param pollingRate The time between each check, in milliseconds */ suspend inline fun suspendUntil(pollingRate: Int = 20, condition: () -> Boolean) { while (!condition()) delay(pollingRate.toLong()) } /** * Runs each block in [blocks] in a child coroutine, and suspends until all of them have completed. * * If one child is cancelled, the remaining children are stopped, and the exception is propagated upwards. */ suspend inline fun CoroutineScope.parallel(vararg blocks: suspend () -> Unit) { blocks.map { block -> launch { block() } }.forEach { it.join() } } /** * Suspends the coroutine for [time] seconds. * * @see kotlinx.coroutines.delay */ suspend inline fun delay(time: Double) = delay((time * 1000).toLong()) suspend inline fun delay(time: Time) = delay(time.asSeconds) /** * Suspends the coroutine forever. * * A halted coroutine can still be canceled. */ suspend inline fun halt(): Unit = suspendCancellableCoroutine {}
unlicense
94311748a6f7eecd50980a5858397ce9
28.65873
114
0.659888
3.962884
false
false
false
false
peterholak/graphql-ws-kotlin
example/src/main/kotlin/net/holak/graphql/example/ExampleServer.kt
1
3703
package net.holak.graphql.example import com.google.gson.Gson import com.google.gson.internal.LinkedTreeMap import graphql.ExecutionInput import graphql.GraphQL import net.holak.graphql.ws.JsonMap import net.holak.graphql.ws.Publisher import net.holak.graphql.ws.SubscriptionWebSocketHandler import net.holak.graphql.ws.Subscriptions import org.eclipse.jetty.websocket.api.Session import spark.Response import spark.Service import java.io.PrintWriter import java.io.StringWriter class ExampleServer(subscriptions: Subscriptions<Session>, val graphQL: GraphQL, val publisher: Publisher) { val http = Service.ignite()!! val gson = Gson() val socketHandler: SubscriptionWebSocketHandler val indexHtml = ClassLoader.getSystemResourceAsStream("frontend/dist/index.html").reader().readText() init { http.port(4567) socketHandler = SubscriptionWebSocketHandler(subscriptions, publisher) http.webSocket("/subscriptions", socketHandler) http.staticFiles.location("frontend/dist") http.after { req, res -> if (req.headers("Sec-WebSocket-Protocol") == "graphql-ws") { res.header("Sec-WebSocket-Protocol", "graphql-ws") } corsAllowEveryone(res) } http.post("/publish-text") { req, _ -> val value = gson.fromJson(req.body(), LinkedTreeMap::class.java)["value"].toString() publisher.publish("textPublished", value) publisher.publish("multiplyPublishedText", value) publisher.publish("filteredPublishedText", value) { (value.toIntOrNull() ?: return@publish false) < (it["lessThan"] as Int) } publisher.publish("complexInput") } addGraphQLPostHandlers() defaultToIndexHtml() println("Server running at http://localhost:4567/") } private fun defaultToIndexHtml() { http.get("*") { req, res -> // https://github.com/perwendel/spark/issues/502#issuecomment-219324858 if (req.raw().pathInfo == "/subscriptions") return@get null res.type("text/html") indexHtml } } private fun addGraphQLPostHandlers() { http.post("/graphql") { req, res -> try { res.type("application/json") val body = gson.fromJson(req.body(), LinkedTreeMap::class.java) @Suppress("UNCHECKED_CAST") val variables = body["variables"] as JsonMap? ?: emptyMap() val result = graphQL.execute(ExecutionInput( body["query"] as String, body["operationName"] as String?, null, null, variables )) return@post gson.toJson(result.toSpecification()) }catch(e: Exception) { return@post exceptionToJson(e) } } } fun exceptionToJson(e: Exception): String { val writer = StringWriter() e.printStackTrace(PrintWriter(writer)) return gson.toJson(mapOf( "errors" to listOf(mapOf( "message" to ("Server exception: " + e.message), "stackTrace" to writer.toString().split('\n') )) )) } // Obviously this would be a bad idea for production private fun corsAllowEveryone(response: Response) { response.header("access-control-allow-origin", "*") response.header("access-control-allow-methods", "options, post") response.header("access-control-allow-headers", "content-type") } }
mit
f49a5352f16121944aee436e4afeca84
34.961165
108
0.602214
4.646173
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/prefs/accountsettings/AccountSettingsViewModelTest.kt
1
20181
package org.wordpress.android.ui.prefs.accountsettings import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.flow.toList import kotlinx.coroutines.launch import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.wordpress.android.BaseUnitTest import org.wordpress.android.R.string import org.wordpress.android.TEST_DISPATCHER import org.wordpress.android.fluxc.model.AccountModel import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.store.AccountStore.AccountError import org.wordpress.android.fluxc.store.AccountStore.AccountErrorType.GENERIC_ERROR import org.wordpress.android.fluxc.store.AccountStore.OnAccountChanged import org.wordpress.android.test import org.wordpress.android.ui.prefs.accountsettings.AccountSettingsViewModel.AccountSettingsUiState import org.wordpress.android.ui.prefs.accountsettings.AccountSettingsViewModel.SiteUiModel import org.wordpress.android.ui.prefs.accountsettings.usecase.FetchAccountSettingsUseCase import org.wordpress.android.ui.prefs.accountsettings.usecase.GetAccountUseCase import org.wordpress.android.ui.prefs.accountsettings.usecase.GetSitesUseCase import org.wordpress.android.ui.prefs.accountsettings.usecase.PushAccountSettingsUseCase import org.wordpress.android.ui.utils.UiString.UiStringResWithParams import org.wordpress.android.ui.utils.UiString.UiStringText import org.wordpress.android.util.NetworkUtilsWrapper import org.wordpress.android.viewmodel.ResourceProvider @InternalCoroutinesApi class AccountSettingsViewModelTest : BaseUnitTest() { private lateinit var viewModel: AccountSettingsViewModel @Mock private lateinit var resourceProvider: ResourceProvider @Mock private lateinit var networkUtilsWrapper: NetworkUtilsWrapper @Mock private lateinit var fetchAccountSettingsUseCase: FetchAccountSettingsUseCase @Mock private lateinit var pushAccountSettingsUseCase: PushAccountSettingsUseCase @Mock private lateinit var getSitesUseCase: GetSitesUseCase @Mock private lateinit var getAccountUseCase: GetAccountUseCase private val optimisticUpdateHandler = AccountSettingsOptimisticUpdateHandler() @Mock private lateinit var account: AccountModel private val siteViewModels = mutableListOf<SiteUiModel>().apply { add(SiteUiModel("HappyDay", 1L, "http://happyday.wordpress.com")) add(SiteUiModel("WonderLand", 2L, "http://wonderland.wordpress.com")) add(SiteUiModel("FantasyBooks", 3L, "http://fantasybooks.wordpress.com")) } private val uiStateChanges = mutableListOf<AccountSettingsUiState>() private val uiState get() = viewModel.accountSettingsUiState.value @Before fun setUp() = test { whenever(account.primarySiteId).thenReturn(3L) whenever(account.userName).thenReturn("old_wordpressuser_username") whenever(account.displayName).thenReturn("old_wordpressuser_displayname") whenever(account.email).thenReturn("[email protected]") whenever(account.newEmail).thenReturn("") whenever(account.webAddress).thenReturn("http://old_wordpressuser.com") whenever(account.pendingEmailChange).thenReturn(false) whenever(account.usernameCanBeChanged).thenReturn(false) whenever(getAccountUseCase.account).thenReturn(account) val sites = siteViewModels.map { SiteModel().apply { this.siteId = it.siteId this.name = it.siteName this.url = it.homeURLOrHostName } } whenever(getSitesUseCase.get()).thenReturn(sites) initialiseViewModel() } @Test fun `The initial primarysite is shown from cached account settings`() = test { uiState.primarySiteSettingsUiState.primarySite?.siteId?.let { assertThat(it).isEqualTo(getAccountUseCase.account.primarySiteId) } } @Test fun `The initial username is shown from cached account settings`() = test { assertThat(uiState.userNameSettingsUiState.userName) .isEqualTo(getAccountUseCase.account.userName) } @Test fun `The username is allowed to change based on the cached account settings`() = test { assertThat(uiState.userNameSettingsUiState.canUserNameBeChanged) .isEqualTo(getAccountUseCase.account.usernameCanBeChanged) } @Test fun `The username confirmed snackbar is not be shown by default`() = test { assertThat(uiState.userNameSettingsUiState.showUserNameConfirmedSnackBar) .isEqualTo(false) } @Test fun `The initial emailaddress is shown from cached account settings`() = test { assertThat(uiState.emailSettingsUiState.email) .isEqualTo(getAccountUseCase.account.email) } @Test fun `The pending emailaddress change snackbar is shown based on cached account settings`() = test { assertThat(uiState.emailSettingsUiState.hasPendingEmailChange) .isEqualTo(getAccountUseCase.account.pendingEmailChange) } @Test fun `The initial webAddress is shown from cached account settings`() = test { assertThat(uiState.webAddressSettingsUiState.webAddress) .isEqualTo(getAccountUseCase.account.webAddress) } @Test fun `When the username change is confirmed from the server, then new username is updated`() = test { viewModel.onUsernameChangeConfirmedFromServer("new_wordpressuser_username") assertThat(uiState.userNameSettingsUiState.userName) .isEqualTo("new_wordpressuser_username") } @Test fun `When the username change is confirmed from the server, then the snackbar is shown`() = test { viewModel.onUsernameChangeConfirmedFromServer("new_wordpressuser_username") assertThat(uiState.userNameSettingsUiState.showUserNameConfirmedSnackBar) .isEqualTo(true) } @Test fun `The username confirmed snackbar message is Your new username is new_wordpressuser_username'`() = test { viewModel.onUsernameChangeConfirmedFromServer("new_wordpressuser_username") assertThat(uiState.userNameSettingsUiState.newUserChangeConfirmedSnackBarMessageHolder.message) .isEqualTo( UiStringResWithParams( string.settings_username_changer_toast_content, listOf(UiStringText("new_wordpressuser_username")) ) ) } @Test fun `When the server return 'canUserNameBeChanged' as true, then the username is allowed to change`() = test { whenever(getAccountUseCase.account.usernameCanBeChanged).thenReturn(true) initialiseViewModel() assertThat(uiState.userNameSettingsUiState.canUserNameBeChanged).isEqualTo(true) } @Test fun `When the server return 'canUserNameBeChanged' as false, then the username is not allowed to change`() = test { whenever(getAccountUseCase.account.usernameCanBeChanged).thenReturn(false) initialiseViewModel() assertThat(uiState.userNameSettingsUiState.canUserNameBeChanged).isEqualTo(false) } @Test fun `When there is a pending emailaddress change, then the snackbar is shown`() = test { whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(true) whenever(getAccountUseCase.account.newEmail).thenReturn("new_wordpressuser_username") initialiseViewModel() assertThat(uiState.emailSettingsUiState.hasPendingEmailChange).isEqualTo(true) } @Test fun `The pending emailaddress snackbar message is Click the verification link in the email`() = test { assertThat(uiState.emailSettingsUiState.emailVerificationMsgSnackBarMessageHolder.message) .isEqualTo( UiStringResWithParams( string.pending_email_change_snackbar, listOf(UiStringText(getAccountUseCase.account.newEmail)) ) ) } @Test fun `When there is no pending emailaddress change, then the snackbar is not shown`() = test { whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(false) initialiseViewModel() assertThat(uiState.emailSettingsUiState.hasPendingEmailChange).isEqualTo(false) } @Test fun `When a new emailaddress is entered, then the snackbar is shown optimistically`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(false) // When whenever(pushAccountSettingsUseCase.updateEmail("[email protected]")) .thenReturn(mockErrorResponse()) whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(false) whenever(getAccountUseCase.account.newEmail).thenReturn("") viewModel.onEmailChanged("[email protected]") // Then assertThat(uiStateChanges[uiStateChanges.lastIndex - 1].emailSettingsUiState.hasPendingEmailChange) .isEqualTo(true) assertThat(uiStateChanges[uiStateChanges.lastIndex - 1].emailSettingsUiState.newEmail) .isEqualTo("[email protected]") } @Test fun `When a new emailaddress change fails in the server, then the snackbar is dismissed`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(false) // When whenever(pushAccountSettingsUseCase.updateEmail("[email protected]")) .thenReturn(mockErrorResponse()) whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(false) whenever(getAccountUseCase.account.newEmail).thenReturn("") viewModel.onEmailChanged("[email protected]") // Then assertThat(uiStateChanges.last().emailSettingsUiState.hasPendingEmailChange).isEqualTo(false) assertThat(uiStateChanges.last().emailSettingsUiState.newEmail).isEqualTo("") } @Test fun `When a new emailaddress change is updated in the server, then the snackbar continues to show`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(true) // When whenever(pushAccountSettingsUseCase.updateEmail("[email protected]")) .thenReturn(mockSuccessResponse()) whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(true) whenever(getAccountUseCase.account.newEmail).thenReturn("[email protected]") viewModel.onEmailChanged("[email protected]") // Then assertThat(uiStateChanges.last().emailSettingsUiState.hasPendingEmailChange).isEqualTo(true) assertThat(uiStateChanges.last().emailSettingsUiState.newEmail).isEqualTo("[email protected]") } @Test fun `When cancelling of a pending emailaddress change fails, then the snackbar continues to show`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(true) whenever(getAccountUseCase.account.newEmail).thenReturn("[email protected]") // When whenever(pushAccountSettingsUseCase.cancelPendingEmailChange()).thenReturn(mockErrorResponse()) uiState.emailSettingsUiState.onCancelEmailChange.invoke() // Then assertThat(uiStateChanges.last().emailSettingsUiState.hasPendingEmailChange).isEqualTo(true) assertThat(uiStateChanges.last().emailSettingsUiState.newEmail).isEqualTo("[email protected]") } @Test fun `When a pending emailaddress change is cancelled, then the snackbar is dismissed`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(true) // When whenever(pushAccountSettingsUseCase.cancelPendingEmailChange()).thenReturn(mockSuccessResponse()) whenever(getAccountUseCase.account.pendingEmailChange).thenReturn(false) whenever(getAccountUseCase.account.newEmail).thenReturn("") uiState.emailSettingsUiState.onCancelEmailChange.invoke() // Then assertThat(uiStateChanges.last().emailSettingsUiState.hasPendingEmailChange).isEqualTo(false) assertThat(uiStateChanges.last().emailSettingsUiState.newEmail).isEqualTo("") } @Test fun `When a new primarysite is entered, then the primary site is shown optimistically`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.primarySiteId).thenReturn(siteViewModels.last().siteId) // When whenever(pushAccountSettingsUseCase.updatePrimaryBlog(siteViewModels.first().siteId.toString())) .thenReturn(mockErrorResponse()) whenever(getAccountUseCase.account.primarySiteId).thenReturn(siteViewModels.last().siteId) viewModel.onPrimarySiteChanged(siteRemoteId = siteViewModels.first().siteId) // Then assertThat(uiStateChanges[uiStateChanges.lastIndex - 1].primarySiteSettingsUiState.primarySite?.siteId) .isEqualTo(siteViewModels.first().siteId) } @Test fun `When a new primarysite change fails in the server, then the old primarysite is reverted back`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.primarySiteId).thenReturn(siteViewModels.last().siteId) // When whenever(pushAccountSettingsUseCase.updatePrimaryBlog(siteViewModels.first().siteId.toString())) .thenReturn(mockErrorResponse()) whenever(getAccountUseCase.account.primarySiteId).thenReturn(siteViewModels.last().siteId) viewModel.onPrimarySiteChanged(siteRemoteId = siteViewModels.first().siteId) // Then assertThat(uiStateChanges.last().primarySiteSettingsUiState.primarySite?.siteId) .isEqualTo(siteViewModels.last().siteId) } @Test fun `When a new primarysite change is updated in the server, then new primarysite continues to show`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.primarySiteId).thenReturn(siteViewModels.last().siteId) // When whenever(pushAccountSettingsUseCase.updatePrimaryBlog(siteViewModels.first().siteId.toString())) .thenReturn(mockSuccessResponse()) whenever(getAccountUseCase.account.primarySiteId).thenReturn(siteViewModels.first().siteId) viewModel.onPrimarySiteChanged(siteRemoteId = siteViewModels.first().siteId) // Then assertThat(uiStateChanges.last().primarySiteSettingsUiState.primarySite?.siteId) .isEqualTo(siteViewModels.first().siteId) } @Test fun `When a new webaddress is entered, then new webaddress is shown optimistically`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.webAddress).thenReturn("old_webaddress") // When whenever(pushAccountSettingsUseCase.updateWebAddress("new_webaddress")) .thenReturn(mockErrorResponse()) whenever(getAccountUseCase.account.webAddress).thenReturn("old_webaddress") viewModel.onWebAddressChanged("new_webaddress") // Then assertThat(uiStateChanges[uiStateChanges.lastIndex - 1].webAddressSettingsUiState.webAddress) .isEqualTo("new_webaddress") } @Test fun `When a new webaddress is updated in the server, then new webaddress continues to show`() = testUiStateChanges { // Given whenever(getAccountUseCase.account.webAddress).thenReturn("old_webaddress") // When whenever(pushAccountSettingsUseCase.updateWebAddress("new_webaddress")) .thenReturn(mockSuccessResponse()) whenever(getAccountUseCase.account.webAddress).thenReturn("new_webaddress") viewModel.onWebAddressChanged("new_webaddress") // Then assertThat(uiStateChanges.last().webAddressSettingsUiState.webAddress).isEqualTo("new_webaddress") } @Test fun `When a new password is entered, then the changing password progress dialog is shown`() = testUiStateChanges { // Given whenever(pushAccountSettingsUseCase.updatePassword("new_password")) .thenReturn(mockSuccessResponse()) // When viewModel.onPasswordChanged("new_password") // Then assertThat( uiStateChanges[uiStateChanges.lastIndex - 1] .changePasswordSettingsUiState.showChangePasswordProgressDialog ) .isEqualTo(true) } @Test fun `When a new password is updated in the server, then the changing password progress dialog is dismissed`() = testUiStateChanges { // Given whenever(pushAccountSettingsUseCase.updatePassword("new_password")) .thenReturn(mockSuccessResponse()) // When viewModel.onPasswordChanged("new_password") // Then assertThat(uiStateChanges.last().changePasswordSettingsUiState.showChangePasswordProgressDialog) .isEqualTo(false) } // Helper Methods private fun <T> testUiStateChanges( block: suspend CoroutineScope.() -> T ) { test { uiStateChanges.clear() initialiseViewModel() val job = launch(TEST_DISPATCHER) { viewModel.accountSettingsUiState.toList(uiStateChanges) } this.block() job.cancel() } } private fun mockSuccessResponse(): OnAccountChanged { return mock() } private fun mockErrorResponse(): OnAccountChanged { return OnAccountChanged().apply { this.error = AccountError(GENERIC_ERROR, "") } } private fun initialiseViewModel() { viewModel = AccountSettingsViewModel( resourceProvider, networkUtilsWrapper, TEST_DISPATCHER, fetchAccountSettingsUseCase, pushAccountSettingsUseCase, getAccountUseCase, getSitesUseCase, optimisticUpdateHandler ) } }
gpl-2.0
97a81ce4d5a5e0255c061e7398ded332
47.864407
120
0.651702
5.438157
false
true
false
false
google/identity-credential
appholder/src/main/java/com/android/mdl/app/fragment/TransferDocumentFragment.kt
1
8074
package com.android.mdl.app.fragment import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.android.mdl.app.R import com.android.mdl.app.databinding.FragmentTransferDocumentBinding import com.android.mdl.app.document.Document import com.android.mdl.app.document.KeysAndCertificates import com.android.mdl.app.readerauth.SimpleReaderTrustStore import com.android.mdl.app.transfer.TransferManager import com.android.mdl.app.util.TransferStatus import com.android.mdl.app.viewmodel.TransferDocumentViewModel class TransferDocumentFragment : Fragment() { companion object { private const val LOG_TAG = "TransferDocumentFragment" } private var _binding: FragmentTransferDocumentBinding? = null private val binding get() = _binding!! private val viewModel: TransferDocumentViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentTransferDocumentBinding.inflate(inflater) binding.fragment = this binding.vm = viewModel requireActivity().onBackPressedDispatcher.addCallback( viewLifecycleOwner, onBackPressedCallback ) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewModel.getTransferStatus().observe(viewLifecycleOwner) { transferStatus -> when (transferStatus) { TransferStatus.QR_ENGAGEMENT_READY -> Log.d(LOG_TAG, "Engagement Ready") TransferStatus.CONNECTED -> Log.d(LOG_TAG, "Connected") TransferStatus.REQUEST -> onTransferRequested() TransferStatus.REQUEST_SERVED -> Log.d(LOG_TAG, "Request Served") TransferStatus.DISCONNECTED -> onTransferDisconnected() TransferStatus.ERROR -> onTransferError() else -> {} } } viewModel.connectionClosedLiveData.observe(viewLifecycleOwner) { onCloseConnection( sendSessionTerminationMessage = true, useTransportSpecificSessionTermination = false ) } } private fun onTransferRequested() { Log.d(LOG_TAG, "Request") try { val trustStore = SimpleReaderTrustStore( KeysAndCertificates.getTrustedReaderCertificates(requireContext()) ) val requestedDocuments = viewModel.getRequestedDocuments() var readerCommonName = "" var readerIsTrusted = false requestedDocuments.forEach { reqDoc -> val docs = viewModel.getDocuments().filter { reqDoc.docType == it.docType } if (!viewModel.getSelectedDocuments().any { reqDoc.docType == it.docType }) { if (docs.isEmpty()) { binding.txtDocuments.append("- No document found for ${reqDoc.docType}\n") return@forEach } else if (docs.size == 1) { viewModel.getSelectedDocuments().add(docs[0]) } else { showDocumentSelection(docs) return } } val doc = viewModel.getSelectedDocuments().first { reqDoc.docType == it.docType } if (reqDoc.readerAuth != null && reqDoc.readerAuthenticated) { val readerChain = reqDoc.readerCertificateChain val trustPath = trustStore.createCertificationTrustPath(readerChain.toList()) // Look for the common name in the root certificate if it is trusted or not val certChain = if (trustPath?.isNotEmpty() == true) { trustPath } else { readerChain } certChain.first().subjectX500Principal.name.split(",") .forEach { line -> val (key, value) = line.split("=", limit = 2) if (key == "CN") { readerCommonName = value } } // Add some information about the reader certificate used if (trustStore.validateCertificationTrustPath(trustPath)) { readerIsTrusted = true binding.txtDocuments.append("- Trusted reader auth used: ($readerCommonName)\n") } else { readerIsTrusted = false binding.txtDocuments.append("- Not trusted reader auth used: ($readerCommonName)\n") } } binding.txtDocuments.append("- ${doc.userVisibleName} (${doc.docType})\n") } if (viewModel.getSelectedDocuments().isNotEmpty()) { viewModel.createSelectedItemsList() val direction = TransferDocumentFragmentDirections .navigateToConfirmation(readerCommonName, readerIsTrusted) findNavController().navigate(direction) } else { // Send response with 0 documents viewModel.sendResponseForSelection() } } catch (e: Exception) { val message = "On request received error: ${e.message}" Log.e(LOG_TAG, message, e) Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show() binding.txtConnectionStatus.append("\n$message") } } private fun showDocumentSelection(doc: List<Document>) { val alertDialogBuilder = AlertDialog.Builder(requireContext()) alertDialogBuilder.setTitle("Select which document to share") val listItems = doc.map { it.userVisibleName }.toTypedArray() alertDialogBuilder.setSingleChoiceItems(listItems, -1) { dialogInterface, i -> viewModel.getSelectedDocuments().add(doc[i]) onTransferRequested() dialogInterface.dismiss() } val mDialog = alertDialogBuilder.create() mDialog.show() } private fun onTransferDisconnected() { Log.d(LOG_TAG, "Disconnected") hideButtons() TransferManager.getInstance(requireContext()).disconnect() } private fun onTransferError() { Toast.makeText(requireContext(), "An error occurred.", Toast.LENGTH_SHORT).show() hideButtons() TransferManager.getInstance(requireContext()).disconnect() } private fun hideButtons() { binding.txtConnectionStatus.text = getString(R.string.connection_mdoc_closed) binding.btCloseConnection.visibility = View.GONE binding.btCloseTerminationMessage.visibility = View.GONE binding.btCloseTransportSpecific.visibility = View.GONE binding.btOk.visibility = View.VISIBLE } private var onBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { onDone() } } fun onCloseConnection( sendSessionTerminationMessage: Boolean, useTransportSpecificSessionTermination: Boolean ) { viewModel.cancelPresentation( sendSessionTerminationMessage, useTransportSpecificSessionTermination ) hideButtons() } fun onDone() { onCloseConnection( sendSessionTerminationMessage = true, useTransportSpecificSessionTermination = false ) findNavController().navigateUp() } }
apache-2.0
8c20cb0283ef423eefcbc5e601cd387f
40.19898
108
0.611097
5.354111
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/layers/recurrent/lstm/LSTMLayerStructureUtils.kt
1
4866
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.layers.recurrent.lstm import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.models.recurrent.LayersWindow import com.kotlinnlp.simplednn.core.layers.models.recurrent.lstm.LSTMLayerParameters import com.kotlinnlp.simplednn.core.layers.models.recurrent.lstm.LSTMLayer import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import com.kotlinnlp.simplednn.simplemath.ndarray.Shape /** * */ internal object LSTMLayerStructureUtils { /** * */ fun buildLayer(layersWindow: LayersWindow): LSTMLayer<DenseNDArray> = LSTMLayer( inputArray = AugmentedArray(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.8, -0.9, -0.9, 1.0))), inputType = LayerType.Input.Dense, outputArray = AugmentedArray(DenseNDArrayFactory.emptyArray(Shape(5))), params = buildParams(), activationFunction = Tanh, layersWindow = layersWindow, dropout = 0.0 ) /** * */ fun buildParams() = LSTMLayerParameters(inputSize = 4, outputSize = 5).apply { inputGate.weights.values.assignValues( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.5, 0.6, -0.8, -0.6), doubleArrayOf(0.7, -0.4, 0.1, -0.8), doubleArrayOf(0.7, -0.7, 0.3, 0.5), doubleArrayOf(0.8, -0.9, 0.0, -0.1), doubleArrayOf(0.4, 1.0, -0.7, 0.8) ))) outputGate.weights.values.assignValues( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.1, 0.4, -1.0, 0.4), doubleArrayOf(0.7, -0.2, 0.1, 0.0), doubleArrayOf(0.7, 0.8, -0.5, -0.3), doubleArrayOf(-0.9, 0.9, -0.3, -0.3), doubleArrayOf(-0.7, 0.6, -0.6, -0.8) ))) forgetGate.weights.values.assignValues( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-1.0, 0.2, 0.0, 0.2), doubleArrayOf(-0.7, 0.7, -0.3, -0.3), doubleArrayOf(0.3, -0.6, 0.0, 0.7), doubleArrayOf(-1.0, -0.6, 0.9, 0.8), doubleArrayOf(0.5, 0.8, -0.9, -0.8) ))) candidate.weights.values.assignValues( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.2, 0.6, 0.0, 0.1), doubleArrayOf(0.1, -0.3, -0.8, -0.5), doubleArrayOf(-0.1, 0.0, 0.4, -0.4), doubleArrayOf(-0.8, -0.3, -0.7, 0.3), doubleArrayOf(-0.4, 0.9, 0.8, -0.3) ))) inputGate.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.0, -0.3, 0.8, -0.4))) outputGate.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.9, 0.2, -0.9, 0.2, -0.9))) forgetGate.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, -0.5, 1.0, 0.4, 0.9))) candidate.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.2, -0.9, -0.9, 0.5, 0.1))) inputGate.recurrentWeights.values.assignValues( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0, 0.8, 0.8, -1.0, -0.7), doubleArrayOf(-0.7, -0.8, 0.2, -0.7, 0.7), doubleArrayOf(-0.9, 0.9, 0.7, -0.5, 0.5), doubleArrayOf(0.0, -0.1, 0.5, -0.2, -0.8), doubleArrayOf(-0.6, 0.6, 0.8, -0.1, -0.3) ))) outputGate.recurrentWeights.values.assignValues( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.1, -0.6, -1.0, -0.1, -0.4), doubleArrayOf(0.5, -0.9, 0.0, 0.8, 0.3), doubleArrayOf(-0.3, -0.9, 0.3, 1.0, -0.2), doubleArrayOf(0.7, 0.2, 0.3, -0.4, -0.6), doubleArrayOf(-0.2, 0.5, -0.2, -0.9, 0.4) ))) forgetGate.recurrentWeights.values.assignValues( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.2, -0.3, -0.3, -0.5, -0.7), doubleArrayOf(0.4, -0.1, -0.6, -0.4, -0.8), doubleArrayOf(0.6, 0.6, 0.1, 0.7, -0.4), doubleArrayOf(-0.8, 0.9, 0.1, -0.1, -0.2), doubleArrayOf(-0.5, -0.3, -0.6, -0.6, 0.1) ))) candidate.recurrentWeights.values.assignValues( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.3, 0.3, -0.1, 0.6, -0.7), doubleArrayOf(-0.2, -0.8, -0.6, -0.5, -0.4), doubleArrayOf(-0.4, 0.8, -0.5, -0.1, 0.9), doubleArrayOf(0.3, 0.7, 0.3, 0.0, -0.4), doubleArrayOf(-0.3, 0.3, -0.7, 0.0, 0.7) ))) } /** * */ fun getOutputGold() = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.57, 0.75, -0.15, 1.64, 0.45)) }
mpl-2.0
c5ef81009075958fa1ee4aaaea23c503
37.928
112
0.619194
2.977968
false
false
false
false
JordyLangen/vaultbox
app/src/main/java/com/jlangen/vaultbox/vaults/VaultsView.kt
1
1635
package com.jlangen.vaultbox.vaults import android.content.Context import android.support.v7.util.DiffUtil import android.support.v7.widget.LinearLayoutManager import android.util.AttributeSet import android.view.View import android.widget.RelativeLayout import com.jakewharton.rxrelay2.PublishRelay import com.jlangen.vaultbox.architecture.state.StateRenderer import com.jlangen.vaultbox.vaults.Vault import io.reactivex.Observable import kotlinx.android.synthetic.main.activity_vaults_overview.view.* class VaultsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RelativeLayout(context, attrs, defStyleAttr), StateRenderer<VaultsViewState> { private val adapter = VaultsAdapter(emptyList()) val showVaultIntents: Observable<Vault> get() = adapter.onVaultClickRelay override fun onFinishInflate() { super.onFinishInflate() vaults_view_recycler.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) vaults_view_recycler.adapter = adapter } override fun render(state: VaultsViewState) { if (state.isLoading) { vaults_view_progressbar.visibility = View.VISIBLE updateAdapter(emptyList()) } else { vaults_view_progressbar.visibility = View.GONE updateAdapter(state.vaults) } } private fun updateAdapter(vaults: List<Vault>) { val diffResult = DiffUtil.calculateDiff(VaultDiffCallback(adapter.vaults, vaults), true) adapter.vaults = vaults diffResult.dispatchUpdatesTo(adapter) } }
apache-2.0
3f7974d8d3faa70796687d05840ef68f
35.355556
110
0.738838
4.592697
false
false
false
false
byu-oit/android-byu-suite-v2
support/src/main/java/edu/byu/support/location/ByuLocationActivity.kt
1
3563
package edu.byu.support.location import android.app.Activity import android.content.Intent import android.location.Location import android.os.Bundle import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationRequest import edu.byu.support.activity.ByuActivity import edu.byu.support.utils.fastest import edu.byu.support.utils.getFusedLocationClient /** * Created by geogor37 on 6/25/18 * The majority of cases within the app where location updates are needed should be satisfied by extending this class. Non-ByuActivity classes or classes that already extend another class should * implement the ByuLocationListener interface instead of extending this class. The default behavior for classes extending ByuLocationActivity is to stop after receiving a single location update, * so we immediately stop location updates in the onLocationUpdated() function of the ByuCallback. See the ByuLocationListener interface definition for more information about the functions being * overridden here, as well as other functions that might come in handy when extending this class. **/ abstract class ByuLocationActivity: ByuActivity(), ByuLocationListener { override val locationCallback = object: ByuLocationCallback() { override fun onLocationUpdated(location: Location) { stopLocationUpdates() } } override lateinit var activityWithLocationClient: Pair<Activity, FusedLocationProviderClient> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityWithLocationClient = Pair(this, getFusedLocationClient()) // Most of the time we use the user's location to customize the information being displayed to them, so by default we request location updates as soon as they start the activity. requestLocationUpdates() } override fun onDestroy() { super.onDestroy() // Once they leave the activity, we don't want to receive anymore location updates. stopLocationUpdates() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == ByuLocationListener.REQUEST_LOCATION_PERMISSIONS) { // If the user was responding to our request that they change their location settings, then we can just let the ByuLocationListener handle that. super<ByuLocationListener>.onActivityResult(requestCode, resultCode, data) } else { // Otherwise handle it like normal. super<ByuActivity>.onActivityResult(requestCode, resultCode, data) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (requestCode == ByuLocationListener.REQUEST_LOCATION_PERMISSIONS) { // If the user was responding to our request that they grant us location permissions, then we can just let the ByuLocationListener handle that. super<ByuLocationListener>.onRequestPermissionsResult(requestCode, permissions, grantResults) } else { // Otherwise handle it like normal. super<ByuActivity>.onRequestPermissionsResult(requestCode, permissions, grantResults) } } /** * Most features just require a single location update, so by default we set up a request that will get us a location as fast as possible and we stop location updates once we receive the * first location. Please note that if continuous updates are desired, we need to stop and resume location updates in the onPause and onResume methods in order to prevent unnecessary * battery drain. */ override fun getLocationRequest(): LocationRequest = LocationRequest().fastest() }
apache-2.0
66dc24d5e37fe840762b9c1ccae8dfca
51.411765
195
0.798484
4.776139
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/common/view/ContextExtensions.kt
1
2449
package io.ipoli.android.common.view import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.preference.PreferenceManager import android.support.annotation.* import android.support.v4.content.ContextCompat import android.support.v7.view.ContextThemeWrapper import android.util.TypedValue import io.ipoli.android.Constants import io.ipoli.android.player.Theme /** * Created by Venelin Valkov <[email protected]> * on 15.12.17. */ val Context.playerTheme: Int get() { val pm = PreferenceManager.getDefaultSharedPreferences(this) if (pm.contains(Constants.KEY_THEME)) { val themeName = pm.getString(Constants.KEY_THEME, "") if (themeName.isNotEmpty()) { return AndroidTheme.valueOf(themeName).style } } return AndroidTheme.valueOf(Constants.DEFAULT_THEME.name).style } val Context.isDarkTheme: Boolean get() { val pm = PreferenceManager.getDefaultSharedPreferences(this) if (pm.contains(Constants.KEY_THEME)) { val themeName = pm.getString(Constants.KEY_THEME, "") if (themeName.isNotEmpty()) { return Theme.valueOf(themeName).isDark } } return Constants.DEFAULT_THEME.isDark } fun Context.asThemedWrapper() = ContextThemeWrapper(this, playerTheme) fun Context.attrData(@AttrRes attributeRes: Int) = TypedValue().let { theme.resolveAttribute(attributeRes, it, true) it.data } fun Context.isAppInstalled(packageName: String) = try { packageManager.getPackageInfo(packageName, 0) true } catch (e: PackageManager.NameNotFoundException) { false } fun Context.stringRes(@StringRes stringRes: Int): String = resources!!.getString(stringRes) fun Context.stringRes(@StringRes stringRes: Int, vararg formatArgs: Any): String = resources!!.getString(stringRes, *formatArgs) fun Context.stringsRes(@ArrayRes stringArrayRes: Int): List<String> = resources!!.getStringArray(stringArrayRes).toList() fun Context.colorRes(@ColorRes colorRes: Int): Int = ContextCompat.getColor(this, colorRes) fun Context.intRes(@IntegerRes res: Int): Int = resources!!.getInteger(res) fun Context.quantityString(@PluralsRes res: Int, quantity: Int) = resources!!.getQuantityString(res, quantity, quantity)
gpl-3.0
636b25d6d98987581157696d3c38aef8
30.818182
82
0.705594
4.373214
false
false
false
false
GunoH/intellij-community
java/idea-ui/testSrc/com/intellij/jarRepository/RepositoryLibraryTest.kt
2
4694
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.jarRepository import com.intellij.openapi.application.runWriteActionAndWait import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.vfs.VfsUtil import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.RuleChain import com.intellij.testFramework.rules.ProjectModelRule import com.intellij.testFramework.rules.TempDirectory import com.intellij.util.io.exists import com.intellij.workspaceModel.ide.WorkspaceModel import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties import org.jetbrains.idea.maven.utils.library.RepositoryUtils import org.junit.Assert.* import org.junit.Before import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.util.concurrent.TimeUnit class RepositoryLibraryTest { companion object { @JvmStatic @get:ClassRule val applicationRule = ApplicationRule() } private val disposableRule = DisposableRule() private val projectRule = ProjectModelRule() private val mavenRepo = TempDirectory() private val localMavenCache = TempDirectory() @get:Rule val rulesChain = RuleChain(localMavenCache, mavenRepo, projectRule, disposableRule) private val ARTIFACT_NAME = "myArtifact" private val GROUP_NAME = "myGroup" private val LIBRARY_NAME = "NewLibrary" @Before fun setUp() { JarRepositoryManager.setLocalRepositoryPath(localMavenCache.root) MavenRepoFixture(mavenRepo.root).apply { addLibraryArtifact(group = GROUP_NAME, artifact = ARTIFACT_NAME, version = "1.0") generateMavenMetadata(GROUP_NAME, ARTIFACT_NAME) } RemoteRepositoriesConfiguration.getInstance(projectRule.project).repositories = listOf( RemoteRepositoryDescription("id", "name", mavenRepo.root.toURI().toURL().toString()) ) } private fun createLibrary(block: (LibraryEx.ModifiableModelEx) -> Unit = {}): Library { val libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(projectRule.project) val library = runWriteActionAndWait { projectRule.addProjectLevelLibrary(LIBRARY_NAME) { it.kind = RepositoryLibraryType.REPOSITORY_LIBRARY_KIND it.properties = RepositoryLibraryProperties(GROUP_NAME, ARTIFACT_NAME, "1.0", false, emptyList()) block(it) } } disposableRule.register { runWriteActionAndWait { libraryTable.removeLibrary(library) } } return library } private fun getLibraryRoots(library: Library): Set<Pair<OrderRootType, String>> = OrderRootType.getAllTypes().flatMap { rootType -> library.getUrls(rootType).map { url -> rootType to url } }.toSet() @Test fun libraryResolveWithoutRoots() { val jar = localMavenCache.rootPath.resolve(GROUP_NAME).resolve(ARTIFACT_NAME).resolve("1.0").resolve("$ARTIFACT_NAME-1.0.jar") assertFalse(jar.exists()) val library = createLibrary() assertEquals(0, getLibraryRoots(library).size) val modelVersionBefore = workspaceVersion() val roots = RepositoryUtils.loadDependenciesToLibrary(projectRule.project, library as LibraryEx, false, false, null) .blockingGet(1, TimeUnit.MINUTES)!! assertTrue(jar.exists()) assertEquals(1, roots.size) assertEquals(OrderRootType.CLASSES, roots[0].type) assertEquals(VfsUtil.getUrlForLibraryRoot(jar), roots[0].file.url) assertEquals(listOf(OrderRootType.CLASSES to VfsUtil.getUrlForLibraryRoot(jar)), getLibraryRoots(library).toList()) assertTrue(workspaceVersion() > modelVersionBefore) } @Test fun libraryNoUpdateProjectModel() { val jar = localMavenCache.rootPath.resolve(GROUP_NAME).resolve(ARTIFACT_NAME).resolve("1.0").resolve("$ARTIFACT_NAME-1.0.jar") assertFalse(jar.exists()) val jarUrl = VfsUtil.getUrlForLibraryRoot(jar) val library = createLibrary { it.addRoot(jarUrl, OrderRootType.CLASSES) } val modelVersionBefore = workspaceVersion() RepositoryUtils.loadDependenciesToLibrary(projectRule.project, library as LibraryEx, false, false, null) .blockingGet(1, TimeUnit.MINUTES)!! assertTrue(jar.exists()) assertEquals(listOf(OrderRootType.CLASSES to jarUrl), getLibraryRoots(library).toList()) assertTrue(workspaceVersion() == modelVersionBefore) } private fun workspaceVersion() = WorkspaceModel.getInstance(projectRule.project).entityStorage.version }
apache-2.0
e88aca4d8e84c0133480dc6a9cc290a0
38.453782
130
0.766937
4.513462
false
true
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/base/util/src/org/jetbrains/kotlin/idea/debugger/base/util/JvmDebuggerBasePsiUtils.kt
2
2085
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("JvmDebuggerBasePsiUtils") package org.jetbrains.kotlin.idea.debugger.base.util import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.base.psi.getLineEndOffset import org.jetbrains.kotlin.idea.base.psi.getLineStartOffset import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset /** * Returns the `TextRange` of the line with a given zero-based index. */ fun PsiFile.getRangeOfLine(line: Int): TextRange? { if (line < 0) { return null } val startOffset = getLineStartOffset(line) ?: return null val endOffset = getLineEndOffset(line) ?: return null if (TextRange.isProperRange(startOffset, endOffset)) { return TextRange(startOffset, endOffset) } return null } inline fun <reified T : PsiElement> PsiFile.findElementsOfTypeInRange(range: TextRange): List<T> { return findElementsOfTypeInRange(range, T::class.java) } /** * Returns all `PsiElement` of given types containing in the `range`. * Partially included elements (e.g. El<range>element</range>) are also returned. */ fun <T : PsiElement> PsiFile.findElementsOfTypeInRange(range: TextRange, vararg classes: Class<out T>): List<T> { val parent = getParentOfLine(range) ?: return emptyList() return PsiTreeUtil.findChildrenOfAnyType(parent, false, *classes) .filter { el -> range.intersects(el.textRange) } } /** * Returns a `PsiElement` including the complete line range, or `null` if line is empty. */ private fun PsiFile.getParentOfLine(range: TextRange): PsiElement? { var parent = findElementAt(range.startOffset) ?: return null while (true) { if (parent.startOffset <= range.startOffset && parent.endOffset >= range.endOffset) { break } parent = parent.parent ?: break } return parent }
apache-2.0
6bb4cff2b317bb11f0176f1069adfc27
35.596491
120
0.729017
4.001919
false
false
false
false
GunoH/intellij-community
java/idea-ui/src/com/intellij/ide/SetupJavaProjectFromSourcesActivity.kt
4
9269
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide import com.google.common.collect.ArrayListMultimap import com.google.common.collect.Multimap import com.intellij.ide.impl.NewProjectUtil.setCompilerOutputPath import com.intellij.ide.impl.ProjectViewSelectInTarget import com.intellij.ide.projectView.impl.ProjectViewPane import com.intellij.ide.util.DelegatingProgressIndicator import com.intellij.ide.util.importProject.JavaModuleInsight import com.intellij.ide.util.importProject.LibrariesDetectionStep import com.intellij.ide.util.importProject.RootDetectionProcessor import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.ide.util.projectWizard.importSources.impl.ProjectFromSourcesBuilderImpl import com.intellij.notification.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.ex.JavaSdkUtil import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.roots.ui.configuration.findAndSetupSdk import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.* import com.intellij.platform.PlatformProjectOpenProcessor import com.intellij.platform.PlatformProjectOpenProcessor.Companion.isOpenedByPlatformProcessor import com.intellij.projectImport.ProjectOpenProcessor import com.intellij.util.SystemProperties import java.io.File import javax.swing.event.HyperlinkEvent private val NOTIFICATION_GROUP = NotificationGroupManager.getInstance().getNotificationGroup("Build Script Found") private val SETUP_JAVA_PROJECT_IS_DISABLED = SystemProperties.getBooleanProperty("idea.java.project.setup.disabled", false) private const val SCAN_DEPTH_LIMIT = 5 private const val MAX_ROOTS_IN_TRIVIAL_PROJECT_STRUCTURE = 3 internal class SetupJavaProjectFromSourcesActivity : StartupActivity { init { if (ApplicationManager.getApplication().isHeadlessEnvironment) { throw ExtensionNotApplicableException.create() } } override fun runActivity(project: Project) { if (SETUP_JAVA_PROJECT_IS_DISABLED) { return } if (!project.isOpenedByPlatformProcessor()) { return } val projectDir = project.baseDir ?: return // todo get current project structure, and later setup from sources only if it wasn't manually changed by the user val title = JavaUiBundle.message("task.searching.for.project.sources") ProgressManager.getInstance().run(object: Task.Backgroundable(project, title, true) { override fun run(indicator: ProgressIndicator) { val importers = searchImporters(projectDir) if (!importers.isEmpty) { showNotificationToImport(project, projectDir, importers) } else { setupFromSources(project, projectDir, indicator) } } }) } private fun searchImporters(projectDirectory: VirtualFile): ArrayListMultimap<ProjectOpenProcessor, VirtualFile> { val providersAndFiles = ArrayListMultimap.create<ProjectOpenProcessor, VirtualFile>() VfsUtil.visitChildrenRecursively(projectDirectory, object : VirtualFileVisitor<Void>(NO_FOLLOW_SYMLINKS, limit(SCAN_DEPTH_LIMIT)) { override fun visitFileEx(file: VirtualFile): Result { if (file.isDirectory && FileTypeRegistry.getInstance().isFileIgnored(file)) { return SKIP_CHILDREN } val providers = ProjectOpenProcessor.EXTENSION_POINT_NAME.extensionList.filter { provider -> provider.canOpenProject(file) && provider !is PlatformProjectOpenProcessor } for (provider in providers) { val files = providersAndFiles.get(provider) if (files.isEmpty()) { files.add(file) } else if (!VfsUtilCore.isAncestor(files.last(), file, true)) { // add only top-level file/folders for each of providers files.add(file) } } return CONTINUE } }) return providersAndFiles } private fun showNotificationToImport(project: Project, projectDirectory: VirtualFile, providersAndFiles: ArrayListMultimap<ProjectOpenProcessor, VirtualFile>) { val showFileInProjectViewListener = object : NotificationListener.Adapter() { override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) { val file = LocalFileSystem.getInstance().findFileByPath(e.description) ProjectViewSelectInTarget.select(project, file, ProjectViewPane.ID, null, file, true) } } val title: String val content: String if (providersAndFiles.keySet().size == 1) { val processor = providersAndFiles.keySet().single() val files = providersAndFiles[processor] title = JavaUiBundle.message("build.script.found.notification", processor.name, files.size) content = filesToLinks(files, projectDirectory) } else { title = JavaUiBundle.message("build.scripts.from.multiple.providers.found.notification") content = formatContent(providersAndFiles, projectDirectory) } val notification = NOTIFICATION_GROUP.createNotification(title, content, NotificationType.INFORMATION) .setSuggestionType(true) .setListener(showFileInProjectViewListener) if (providersAndFiles.keySet().all { it.canImportProjectAfterwards() }) { val actionName = JavaUiBundle.message("build.script.found.notification.import", providersAndFiles.keySet().size) notification.addAction(NotificationAction.createSimpleExpiring(actionName) { for ((provider, files) in providersAndFiles.asMap()) { for (file in files) { provider.importProjectAfterwards(project, file) } } }) } notification.notify(project) } @NlsSafe private fun formatContent(providersAndFiles: Multimap<ProjectOpenProcessor, VirtualFile>, projectDirectory: VirtualFile): String { return providersAndFiles.asMap().entries.joinToString("<br/>") { (provider, files) -> provider.name + ": " + filesToLinks(files, projectDirectory) } } @NlsSafe private fun filesToLinks(files: MutableCollection<VirtualFile>, projectDirectory: VirtualFile) = files.joinToString { file -> "<a href='${file.path}'>${VfsUtil.getRelativePath(file, projectDirectory)}</a>" } private fun setupFromSources(project: Project, projectDir: VirtualFile, indicator: ProgressIndicator) { val builder = ProjectFromSourcesBuilderImpl(WizardContext(project, project), ModulesProvider.EMPTY_MODULES_PROVIDER) val projectPath = projectDir.path builder.baseProjectPath = projectPath val roots = RootDetectionProcessor.detectRoots(File(projectPath)) val rootsMap = RootDetectionProcessor.createRootsMap(roots) builder.setupProjectStructure(rootsMap) for (detector in rootsMap.keySet()) { val descriptor = builder.getProjectDescriptor(detector) val moduleInsight = JavaModuleInsight(DelegatingProgressIndicator(), builder.existingModuleNames, builder.existingProjectLibraryNames) descriptor.libraries = LibrariesDetectionStep.calculate(moduleInsight, builder) moduleInsight.scanModules() descriptor.modules = moduleInsight.suggestedModules } ApplicationManager.getApplication().invokeAndWait { builder.commit(project) val compileOutput = if (projectPath.endsWith('/')) "${projectPath}out" else "$projectPath/out" setCompilerOutputPath(project, compileOutput) } val modules = ModuleManager.getInstance(project).modules if (modules.any { it is JavaModuleType }) { findAndSetupSdk(project, indicator, JavaSdk.getInstance()) { JavaSdkUtil.applyJdkToProject(project, it) } } if (roots.size > MAX_ROOTS_IN_TRIVIAL_PROJECT_STRUCTURE) { notifyAboutAutomaticProjectStructure(project) } } private fun notifyAboutAutomaticProjectStructure(project: Project) { NOTIFICATION_GROUP.createNotification(JavaUiBundle.message("project.structure.automatically.detected.notification"), NotificationType.INFORMATION) .addAction(NotificationAction.createSimpleExpiring(JavaUiBundle.message("project.structure.automatically.detected.notification.gotit.action")) {}) .addAction(NotificationAction.createSimpleExpiring(JavaUiBundle.message("project.structure.automatically.detected.notification.configure.action")) { ProjectSettingsService.getInstance(project).openProjectSettings() }) .notify(project) } }
apache-2.0
9b96ab02d5b433d7a6bcb7052415b750
43.5625
154
0.74733
4.919851
false
false
false
false
evanchooly/kobalt
src/main/kotlin/com/beust/kobalt/app/remote/OldServer.kt
1
4203
package com.beust.kobalt.app.remote import com.beust.kobalt.api.Kobalt import com.beust.kobalt.api.Project import com.beust.kobalt.internal.remote.CommandData import com.beust.kobalt.internal.remote.ICommandSender import com.beust.kobalt.internal.remote.PingCommand import com.beust.kobalt.misc.log import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParser import java.io.BufferedReader import java.io.InputStreamReader import java.io.PrintWriter import java.net.ServerSocket import java.net.SocketException class OldServer(val initCallback: (String) -> List<Project>, val cleanUpCallback: () -> Unit) : KobaltServer.IServer, ICommandSender { val pending = arrayListOf<CommandData>() override fun run(port: Int) { log(1, "Listening to port $port") var quit = false serverInfo = ServerInfo(port) while (!quit) { if (pending.size > 0) { log(1, "Emptying the queue, size $pending.size()") synchronized(pending) { pending.forEach { sendData(it) } pending.clear() } } var commandName: String? = null try { var line = serverInfo.reader.readLine() while (!quit && line != null) { log(1, "Received from client $line") val jo = JsonParser().parse(line) as JsonObject commandName = jo.get("name").asString if ("quit" == commandName) { log(1, "Quitting") quit = true } else { runCommand(jo, initCallback) // Done, send a quit to the client sendData(CommandData("quit", "")) // Clean up all the plug-in actors cleanUpCallback() line = serverInfo.reader.readLine() } } if (line == null) { log(1, "Received null line, resetting the server") serverInfo.reset() } } catch(ex: SocketException) { log(1, "Client disconnected, resetting") serverInfo.reset() } catch(ex: Throwable) { ex.printStackTrace() if (commandName != null) { sendData(CommandData(commandName, null, ex.message)) } log(1, "Command failed: ${ex.message}") } } } private val COMMAND_CLASSES = listOf(GetDependenciesCommand::class.java, PingCommand::class.java) private val COMMANDS = COMMAND_CLASSES.map { Kobalt.INJECTOR.getInstance(it).let { Pair(it.name, it) } }.toMap() private fun runCommand(jo: JsonObject, initCallback: (String) -> List<Project>) { val command = jo.get("name").asString if (command != null) { (COMMANDS[command] ?: COMMANDS["ping"])!!.run(this, jo, initCallback) } else { error("Did not find a name in command: $jo") } } lateinit var serverInfo: ServerInfo class ServerInfo(val port: Int) { lateinit var reader: BufferedReader lateinit var writer: PrintWriter var serverSocket : ServerSocket? = null init { reset() } fun reset() { if (serverSocket != null) { serverSocket!!.close() } serverSocket = ServerSocket(port) var clientSocket = serverSocket!!.accept() reader = BufferedReader(InputStreamReader(clientSocket.inputStream)) writer = PrintWriter(clientSocket.outputStream, true) } } override fun sendData(commandData: CommandData) { val content = Gson().toJson(commandData) if (serverInfo.writer != null) { serverInfo.writer!!.println(content) } else { log(1, "Queuing $content") synchronized(pending) { pending.add(commandData) } } } }
apache-2.0
7a6c881b5be5007981cb2ab3724e514f
34.025
101
0.543421
4.749153
false
false
false
false