repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
firebase/quickstart-android | auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FacebookLoginFragment.kt | 1 | 4757 | package com.google.firebase.quickstart.auth.kotlin
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 com.facebook.AccessToken
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.firebase.auth.FacebookAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.auth.R
import com.google.firebase.quickstart.auth.databinding.FragmentFacebookBinding
/**
* Demonstrate Firebase Authentication using a Facebook access token.
*/
class FacebookLoginFragment : BaseFragment() {
private lateinit var auth: FirebaseAuth
private var _binding: FragmentFacebookBinding? = null
private val binding: FragmentFacebookBinding
get() = _binding!!
private lateinit var callbackManager: CallbackManager
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentFacebookBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setProgressBar(binding.progressBar)
binding.buttonFacebookSignout.setOnClickListener { signOut() }
// Initialize Firebase Auth
auth = Firebase.auth
// Initialize Facebook Login button
callbackManager = CallbackManager.Factory.create()
binding.buttonFacebookLogin.setPermissions("email", "public_profile")
binding.buttonFacebookLogin.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
Log.d(TAG, "facebook:onSuccess:$loginResult")
handleFacebookAccessToken(loginResult.accessToken)
}
override fun onCancel() {
Log.d(TAG, "facebook:onCancel")
updateUI(null)
}
override fun onError(error: FacebookException) {
Log.d(TAG, "facebook:onError", error)
updateUI(null)
}
})
}
override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
private fun handleFacebookAccessToken(token: AccessToken) {
Log.d(TAG, "handleFacebookAccessToken:$token")
showProgressBar()
val credential = FacebookAuthProvider.getCredential(token.token)
auth.signInWithCredential(credential)
.addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
Toast.makeText(context, "Authentication failed.",
Toast.LENGTH_SHORT).show()
updateUI(null)
}
hideProgressBar()
}
}
fun signOut() {
auth.signOut()
LoginManager.getInstance().logOut()
updateUI(null)
}
private fun updateUI(user: FirebaseUser?) {
hideProgressBar()
if (user != null) {
binding.status.text = getString(R.string.facebook_status_fmt, user.displayName)
binding.detail.text = getString(R.string.firebase_status_fmt, user.uid)
binding.buttonFacebookLogin.visibility = View.GONE
binding.buttonFacebookSignout.visibility = View.VISIBLE
} else {
binding.status.setText(R.string.signed_out)
binding.detail.text = null
binding.buttonFacebookLogin.visibility = View.VISIBLE
binding.buttonFacebookSignout.visibility = View.GONE
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
private const val TAG = "FacebookLogin"
}
}
| apache-2.0 | 8b4a362456f3c14b60cfafa07090deb2 | 34.237037 | 115 | 0.648938 | 5.315084 | false | false | false | false |
chrisdoc/kotlin-koans | src/iii_conventions/MyDate.kt | 1 | 1540 | package iii_conventions
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int): Comparable<MyDate> {
override fun compareTo(other: MyDate): Int {
val result = 2000*(other.year - this.year) + 31*(other.month - this.month) + other.dayOfMonth - this.dayOfMonth
return when {
result == 0 -> 0
result > 0 -> -1
else -> 1
}
}
operator fun plus(interval: TimeInterval): MyDate {
return this.addTimeIntervals(interval, 1)
}
operator fun plus(repeatedTimeInterval: RepeatedTimeInterval): MyDate {
return this.addTimeIntervals(repeatedTimeInterval.ti, repeatedTimeInterval.n)
}
}
operator fun MyDate.rangeTo(other: MyDate): DateRange {
return DateRange(this, other)
}
enum class TimeInterval {
DAY,
WEEK,
YEAR;
operator fun times(i: Int): RepeatedTimeInterval {
return RepeatedTimeInterval(this, i)
}
}
class RepeatedTimeInterval(val ti: TimeInterval, val n: Int)
class DateRange(val start: MyDate, val endInclusive: MyDate): Iterator<MyDate> {
private var currentDate: MyDate = start
override fun hasNext(): Boolean {
return currentDate <= endInclusive
}
override fun next(): MyDate {
val result = currentDate
currentDate = currentDate.nextDay()
return result
}
operator fun contains(date: MyDate): Boolean {
if ((date >= start) && (date <= endInclusive)) {
return true
}
return false
}
}
| mit | 7111bafbe0698e4765993e46faa086d8 | 25.101695 | 119 | 0.633117 | 4.516129 | false | false | false | false |
thomasnield/kotlin-statistics | src/main/kotlin/org/nield/kotlinstatistics/CategoricalStatistics.kt | 1 | 1341 | package org.nield.kotlinstatistics
fun <T> Sequence<T>.mode() = countBy()
.entries
.asSequence()
.sortedByDescending { it.value }
.toList().let { list ->
list.asSequence()
.takeWhile { list[0].value == it.value }
.map { it.key }
}
fun <T> Iterable<T>.mode() = asSequence().mode()
fun <T> Array<out T>.mode() = asIterable().mode()
fun ByteArray.mode() = asIterable().mode()
fun ShortArray.mode() = asIterable().mode()
fun IntArray.mode() = asIterable().mode()
fun LongArray.mode() = asIterable().mode()
fun FloatArray.mode() = asIterable().mode()
fun DoubleArray.mode() = asIterable().mode()
//AGGREGATION OPERATORS
/**
* Groups each distinct value with the number counts it appeared
*/
fun <T> Sequence<T>.countBy() = groupApply({ it }, {it.count()})
/**
* Groups each distinct value with the number counts it appeared
*/
fun <T> Iterable<T>.countBy() = asSequence().countBy()
/**
* Groups each distinct key with the number counts it appeared
*/
inline fun <T,K> Sequence<T>.countBy(crossinline keySelector: (T) -> K) = groupApply(keySelector) { it.count() }
/**
* Groups each distinct key with the number counts it appeared
*/
inline fun <T,K> Iterable<T>.countBy(crossinline keySelector: (T) -> K) = asSequence().countBy(keySelector)
| apache-2.0 | cf6a2c8decffb129f7cf66daf027e1e6 | 32.525 | 112 | 0.642058 | 3.842407 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/org/cups4j/CupsClient.kt | 1 | 6245 | package org.cups4j
/**
* Copyright (C) 2009 Harald Weyhing
*
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser 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 Lesser General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this program; if not, see
* <http:></http:>//www.gnu.org/licenses/>.
*/
/*Notice
* This file has been modified. It is not the original.
* Jon Freeman - 2013
*/
import android.content.Context
import org.cups4j.operations.cups.CupsGetDefaultOperation
import org.cups4j.operations.cups.CupsGetPrintersOperation
import org.cups4j.operations.cups.CupsMoveJobOperation
import org.cups4j.operations.ipp.IppCancelJobOperation
import org.cups4j.operations.ipp.IppGetJobAttributesOperation
import org.cups4j.operations.ipp.IppGetJobsOperation
import org.cups4j.operations.ipp.IppHoldJobOperation
import org.cups4j.operations.ipp.IppReleaseJobOperation
import java.net.URL
import java.security.cert.X509Certificate
import timber.log.Timber
/**
* Main Client for accessing CUPS features like
* - get printers
* - print documents
* - get job attributes
* - ...
*/
class CupsClient @JvmOverloads constructor(
val context: Context,
private val url: URL = URL(DEFAULT_URL),
private val userName: String = DEFAULT_USER
) {
var serverCerts: Array<X509Certificate>? = null
private set // Storage for server certificates if they're not trusted
var lastResponseCode: Int = 0
private set
/**
* Path to list of printers, like xxx://ip:port/printers/printer_name => will contain '/printers/'
* seen in issue: https://github.com/BenoitDuffez/AndroidCupsPrint/issues/40
*/
private var path = "/printers/"
// add default printer if available
@Throws(Exception::class)
fun getPrinters(firstName: String? = null, limit: Int? = null): List<CupsPrinter> {
val cupsGetPrintersOperation = CupsGetPrintersOperation(context)
val printers: List<CupsPrinter>
try {
printers = cupsGetPrintersOperation.getPrinters(url, path, firstName, limit)
} finally {
serverCerts = cupsGetPrintersOperation.serverCerts
lastResponseCode = cupsGetPrintersOperation.lastResponseCode
}
val defaultPrinter = defaultPrinter
for (p in printers) {
if (defaultPrinter != null && p.printerURL.toString() == defaultPrinter.printerURL.toString()) {
p.isDefault = true
}
}
return printers
}
private val defaultPrinter: CupsPrinter?
@Throws(Exception::class)
get() = CupsGetDefaultOperation(context).getDefaultPrinter(url, path)
val host: String
get() = url.host
@Throws(Exception::class)
fun getPrinter(printerURL: URL): CupsPrinter? {
// Extract the printer name
var name = printerURL.path
val pos = name.indexOf('/', 1)
if (pos > 0) {
name = name.substring(pos + 1)
}
val printers = getPrinters(name, 1)
Timber.d("getPrinter: Found ${printers.size} possible CupsPrinters")
for (p in printers) {
if (p.printerURL.path == printerURL.path)
return p
}
return null
}
@Throws(Exception::class)
fun getJobAttributes(jobID: Int): PrintJobAttributes = getJobAttributes(url, userName, jobID)
@Throws(Exception::class)
fun getJobAttributes(userName: String, jobID: Int): PrintJobAttributes =
getJobAttributes(url, userName, jobID)
@Throws(Exception::class)
private fun getJobAttributes(url: URL, userName: String, jobID: Int): PrintJobAttributes =
IppGetJobAttributesOperation(context).getPrintJobAttributes(url, userName, jobID)
@Throws(Exception::class)
fun getJobs(printer: CupsPrinter, whichJobs: WhichJobsEnum, userName: String, myJobs: Boolean): List<PrintJobAttributes> =
IppGetJobsOperation(context).getPrintJobs(printer, whichJobs, userName, myJobs)
@Throws(Exception::class)
fun cancelJob(jobID: Int): Boolean = IppCancelJobOperation(context).cancelJob(url, userName, jobID)
@Throws(Exception::class)
fun cancelJob(url: URL, userName: String, jobID: Int): Boolean =
IppCancelJobOperation(context).cancelJob(url, userName, jobID)
@Throws(Exception::class)
fun holdJob(jobID: Int): Boolean = IppHoldJobOperation(context).holdJob(url, userName, jobID)
@Throws(Exception::class)
fun holdJob(url: URL, userName: String, jobID: Int): Boolean =
IppHoldJobOperation(context).holdJob(url, userName, jobID)
@Throws(Exception::class)
fun releaseJob(jobID: Int): Boolean = IppReleaseJobOperation(context).releaseJob(url, userName, jobID)
@Throws(Exception::class)
fun releaseJob(url: URL, userName: String, jobID: Int): Boolean =
IppReleaseJobOperation(context).releaseJob(url, userName, jobID)
@Throws(Exception::class)
fun moveJob(jobID: Int, userName: String, currentPrinter: CupsPrinter, targetPrinter: CupsPrinter): Boolean {
val currentHost = currentPrinter.printerURL.host
return CupsMoveJobOperation(context).moveJob(currentHost, userName, jobID, targetPrinter.printerURL)
}
/**
* Ensure path starts and ends with a slash
*
* @param path Path to printers on server
* @return Self for easy chained calls
*/
fun setPath(path: String): CupsClient {
this.path = path
if (!path.startsWith("/")) {
this.path = "/$path"
}
if (!path.endsWith("/")) {
this.path += "/"
}
return this
}
companion object {
const val DEFAULT_USER = "anonymous"
private const val DEFAULT_URL = "http://localhost:631"
}
}
| lgpl-3.0 | e34b40a6570d7b6ed6bbb6c368e871c4 | 34.482955 | 126 | 0.681825 | 4.295048 | false | false | false | false |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/media/CustomOkHttpNetworkFetcherUnitTest.kt | 5 | 6827 | package fr.free.nrw.commons.media
import android.net.Uri
import com.facebook.imagepipeline.common.BytesRange
import com.facebook.imagepipeline.image.EncodedImage
import com.facebook.imagepipeline.producers.Consumer
import com.facebook.imagepipeline.producers.NetworkFetcher
import com.facebook.imagepipeline.producers.ProducerContext
import com.facebook.imagepipeline.request.ImageRequest
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.CommonsApplication
import fr.free.nrw.commons.kvstore.JsonKvStore
import okhttp3.*
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.jupiter.api.Assertions
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.powermock.reflect.Whitebox
import java.lang.reflect.Method
import java.util.concurrent.Executor
class CustomOkHttpNetworkFetcherUnitTest {
private lateinit var fetcher: CustomOkHttpNetworkFetcher
private lateinit var okHttpClient: OkHttpClient
private lateinit var state: CustomOkHttpNetworkFetcher.OkHttpNetworkFetchState
@Mock
private lateinit var callback: NetworkFetcher.Callback
@Mock
private lateinit var defaultKvStore: JsonKvStore
@Mock
private lateinit var consumer: Consumer<EncodedImage>
@Mock
private lateinit var context: ProducerContext
@Mock
private lateinit var imageRequest: ImageRequest
@Mock
private lateinit var uri: Uri
@Mock
private lateinit var mCacheControl: CacheControl
@Mock
private lateinit var bytesRange: BytesRange
@Mock
private lateinit var executor: Executor
@Mock
private lateinit var call: Call
@Mock
private lateinit var response: Response
@Mock
private lateinit var body: ResponseBody
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
okHttpClient = OkHttpClient()
fetcher = CustomOkHttpNetworkFetcher(okHttpClient, defaultKvStore)
whenever(context.imageRequest).thenReturn(imageRequest)
whenever(imageRequest.sourceUri).thenReturn(uri)
whenever(imageRequest.bytesRange).thenReturn(bytesRange)
whenever(bytesRange.toHttpRangeHeaderValue()).thenReturn("bytes 200-1000/67589")
whenever(uri.toString()).thenReturn("https://example.com")
state = fetcher.createFetchState(consumer, context)
}
@Test
@Throws(Exception::class)
fun checkNotNull() {
Assert.assertNotNull(fetcher)
}
@Test
@Throws(Exception::class)
fun testFetchCaseReturn() {
whenever(
defaultKvStore.getBoolean(
CommonsApplication.IS_LIMITED_CONNECTION_MODE_ENABLED,
false
)
).thenReturn(true)
fetcher.fetch(state, callback)
verify(callback).onFailure(any())
}
@Test
@Throws(Exception::class)
fun testFetch() {
Whitebox.setInternalState(fetcher, "mCacheControl", mCacheControl)
whenever(
defaultKvStore.getBoolean(
CommonsApplication.IS_LIMITED_CONNECTION_MODE_ENABLED,
false
)
).thenReturn(false)
fetcher.fetch(state, callback)
fetcher.onFetchCompletion(state, 0)
verify(bytesRange).toHttpRangeHeaderValue()
}
@Test
@Throws(Exception::class)
fun testFetchCaseException() {
whenever(uri.toString()).thenReturn("")
whenever(
defaultKvStore.getBoolean(
CommonsApplication.IS_LIMITED_CONNECTION_MODE_ENABLED,
false
)
).thenReturn(false)
fetcher.fetch(state, callback)
verify(callback).onFailure(any())
}
@Test
@Throws(Exception::class)
fun testGetExtraMap() {
val map = fetcher.getExtraMap(state, 40)
Assertions.assertEquals(map!!["image_size"], 40.toString())
}
@Test
@Throws(Exception::class)
fun testOnFetchCancellationRequested() {
Whitebox.setInternalState(fetcher, "mCancellationExecutor", executor)
val method: Method = CustomOkHttpNetworkFetcher::class.java.getDeclaredMethod(
"onFetchCancellationRequested", Call::class.java,
)
method.isAccessible = true
method.invoke(fetcher, call)
verify(executor).execute(any())
}
@Test
@Throws(Exception::class)
fun testOnFetchResponseCaseReturn() {
whenever(response.body()).thenReturn(body)
whenever(response.isSuccessful).thenReturn(false)
whenever(call.isCanceled).thenReturn(true)
val method: Method = CustomOkHttpNetworkFetcher::class.java.getDeclaredMethod(
"onFetchResponse",
CustomOkHttpNetworkFetcher.OkHttpNetworkFetchState::class.java,
Call::class.java,
Response::class.java,
NetworkFetcher.Callback::class.java,
)
method.isAccessible = true
method.invoke(fetcher, state, call, response, callback)
verify(callback).onCancellation()
}
@Test
@Throws(Exception::class)
fun testOnFetchResponse() {
whenever(response.body()).thenReturn(body)
whenever(response.isSuccessful).thenReturn(true)
whenever(response.header("Content-Range")).thenReturn("bytes 200-1000/67589")
whenever(call.isCanceled).thenReturn(true)
whenever(body.contentLength()).thenReturn(-1)
val method: Method = CustomOkHttpNetworkFetcher::class.java.getDeclaredMethod(
"onFetchResponse",
CustomOkHttpNetworkFetcher.OkHttpNetworkFetchState::class.java,
Call::class.java,
Response::class.java,
NetworkFetcher.Callback::class.java,
)
method.isAccessible = true
method.invoke(fetcher, state, call, response, callback)
verify(callback).onResponse(null, 0)
}
@Test
@Throws(Exception::class)
fun testOnFetchResponseCaseException() {
whenever(response.body()).thenReturn(body)
whenever(response.isSuccessful).thenReturn(true)
whenever(response.header("Content-Range")).thenReturn("test")
whenever(call.isCanceled).thenReturn(false)
whenever(body.contentLength()).thenReturn(-1)
val method: Method = CustomOkHttpNetworkFetcher::class.java.getDeclaredMethod(
"onFetchResponse",
CustomOkHttpNetworkFetcher.OkHttpNetworkFetchState::class.java,
Call::class.java,
Response::class.java,
NetworkFetcher.Callback::class.java,
)
method.isAccessible = true
method.invoke(fetcher, state, call, response, callback)
verify(callback).onFailure(any())
}
} | apache-2.0 | 39d4d463d09ec72930e7edb1370b2aa8 | 31.985507 | 88 | 0.686099 | 4.925685 | false | true | false | false |
Logarius/WIMM-Android | app/src/main/java/net/oschina/git/roland/wimm/main/MainActivity.kt | 1 | 2798 | package net.oschina.git.roland.wimm.main
import android.app.AlertDialog
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.FragmentManager
import android.util.SparseArray
import android.view.KeyEvent
import net.oschina.git.roland.wimm.R
import net.oschina.git.roland.wimm.common.base.BaseActivity
import net.oschina.git.roland.wimm.common.view.HeaderFragment
import net.oschina.git.roland.wimm.module.function.FunctionsFragment
import net.oschina.git.roland.wimm.module.runningaccount.RunningAccountFragment
import net.oschina.git.roland.wimm.settings.SettingsFragment
import net.oschina.git.roland.wimm.module.statistics.StatisticsFragment
import kotlinx.android.synthetic.main.activity_main.*
/**
* Created by Roland on 2017/4/10.
*/
class MainActivity : BaseActivity() {
private var fragments: SparseArray<HeaderFragment>? = null
private var fragmentManager: FragmentManager? = null
private var displayingFragment: HeaderFragment? = null
override fun getContentViewLayout(): Int {
return R.layout.activity_main
}
override fun initComp() {
fragments = SparseArray<HeaderFragment>()
fragments!!.put(R.id.home, StatisticsFragment().setHeader(header))
fragments!!.put(R.id.running_account, RunningAccountFragment().setHeader(header))
fragments!!.put(R.id.functions, FunctionsFragment().setHeader(header))
fragments!!.put(R.id.settings, SettingsFragment().setHeader(header))
navigation!!.itemIconTintList = null
fragmentManager = supportFragmentManager
showFragment(R.id.home)
}
override fun initListener() {
navigation!!.setOnNavigationItemSelectedListener(navigationItemSelectedListener)
}
override fun initData() {
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
confirmExit()
return true
}
return super.onKeyUp(keyCode, event)
}
private fun confirmExit() {
val dialog = AlertDialog.Builder(this)
dialog.setMessage(R.string.confirm_exit)
dialog.setNegativeButton(R.string.str_cancel, null)
dialog.setPositiveButton(R.string.str_confirm) { dialog, which -> finish() }
dialog.show()
}
private val navigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
showFragment(item.itemId)
true
}
private fun showFragment(menuId: Int) {
displayingFragment = fragments!!.get(menuId)
if (displayingFragment != null) {
fragmentManager!!.beginTransaction().replace(R.id.content, displayingFragment).commit()
displayingFragment!!.refreshHeader()
}
}
}
| gpl-2.0 | 9d61a968af1449ad1b73b8f0849b436d | 32.710843 | 112 | 0.716583 | 4.609555 | false | false | false | false |
sandjelkovic/configurator | src/main/java/com/saanx/configurator/data/entity/SlotEntryKt.kt | 1 | 819 | package com.saanx.configurator.data.entity
import com.fasterxml.jackson.annotation.JsonIgnore
import org.hibernate.validator.constraints.URL
import org.springframework.data.rest.core.annotation.RestResource
import java.math.BigDecimal
import javax.persistence.*
/**
* @author sandjelkovic
* @date 20.7.17.
*/
@Entity
class SlotEntryKt(@Id @GeneratedValue val id: Long = 0,
val name: String = "",
val data: String = "",
@URL val url: String = "",
val value: BigDecimal = BigDecimal.ZERO,
val selected: Boolean = false,
val position: Int = 0,
@JsonIgnore @ManyToOne @RestResource(exported = false) val slot: SlotKt = SlotKt(),
@Version @JsonIgnore val version: Long = 0)
| apache-2.0 | c8e596df5f793d3fc4f6d16a1dba31a9 | 34.608696 | 101 | 0.620269 | 4.427027 | false | false | false | false |
ajordens/clouddriver | cats/cats-sql/src/main/kotlin/com/netflix/spinnaker/cats/sql/SqlProviderCache.kt | 2 | 11348 | package com.netflix.spinnaker.cats.sql
import com.netflix.spinnaker.cats.agent.CacheResult
import com.netflix.spinnaker.cats.cache.CacheData
import com.netflix.spinnaker.cats.cache.CacheFilter
import com.netflix.spinnaker.cats.cache.DefaultCacheData
import com.netflix.spinnaker.cats.cache.WriteableCache
import com.netflix.spinnaker.cats.provider.ProviderCache
import com.netflix.spinnaker.cats.sql.cache.SqlCache
import com.netflix.spinnaker.clouddriver.core.provider.agent.Namespace.*
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import kotlin.contracts.ExperimentalContracts
@ExperimentalContracts
class SqlProviderCache(private val backingStore: WriteableCache) : ProviderCache {
private val log = LoggerFactory.getLogger(javaClass)
companion object {
private const val ALL_ID = "_ALL_" // this implementation ignores this entirely
}
init {
if (backingStore !is SqlCache) {
throw IllegalStateException("SqlProviderCache must be wired with a SqlCache backingStore")
}
}
/**
* Filters the supplied list of identifiers to only those that exist in the cache.
*
* @param type the type of the item
* @param identifiers the identifiers for the items
* @return the list of identifiers that are present in the cache from the provided identifiers
*/
override fun existingIdentifiers(type: String, identifiers: MutableCollection<String>): MutableCollection<String> {
return backingStore.existingIdentifiers(type, identifiers)
}
/**
* Returns the identifiers for the specified type that match the provided glob.
*
* @param type The type for which to retrieve identifiers
* @param glob The glob to match against the identifiers
* @return the identifiers for the type that match the glob
*/
override fun filterIdentifiers(type: String?, glob: String?): MutableCollection<String> {
return backingStore.filterIdentifiers(type, glob)
}
/**
* Retrieves all the items for the specified type
*
* @param type the type for which to retrieve items
* @return all the items for the type
*/
override fun getAll(type: String): MutableCollection<CacheData> {
return getAll(type, null as CacheFilter?)
}
override fun getAll(type: String, identifiers: MutableCollection<String>?): MutableCollection<CacheData> {
return getAll(type, identifiers, null)
}
override fun getAll(type: String, cacheFilter: CacheFilter?): MutableCollection<CacheData> {
validateTypes(type)
return backingStore.getAll(type, cacheFilter)
}
override fun getAll(
type: String,
identifiers: MutableCollection<String>?,
cacheFilter: CacheFilter?
): MutableCollection<CacheData> {
validateTypes(type)
return backingStore.getAll(type, identifiers, cacheFilter)
}
override fun supportsGetAllByApplication(): Boolean {
return true
}
override fun getAllByApplication(type: String, application: String): Map<String, MutableCollection<CacheData>> {
return getAllByApplication(type, application, null)
}
override fun getAllByApplication(
type: String,
application: String,
cacheFilter: CacheFilter?
): Map<String, MutableCollection<CacheData>> {
validateTypes(type)
return backingStore.getAllByApplication(type, application, cacheFilter)
}
override fun getAllByApplication(
types: Collection<String>,
application: String,
filters: Map<String, CacheFilter?>
): Map<String, MutableCollection<CacheData>> {
validateTypes(types)
return backingStore.getAllByApplication(types, application, filters)
}
/**
* Retrieves the items for the specified type matching the provided identifiers
*
* @param type the type for which to retrieve items
* @param identifiers the identifiers
* @return the items matching the type and identifiers
*/
override fun getAll(type: String, vararg identifiers: String): MutableCollection<CacheData> {
return getAll(type, identifiers.toMutableList())
}
/**
* Gets a single item from the cache by type and id
*
* @param type the type of the item
* @param id the id of the item
* @return the item matching the type and id
*/
override fun get(type: String, id: String?): CacheData? {
return get(type, id, null)
}
override fun get(type: String, id: String?, cacheFilter: CacheFilter?): CacheData? {
if (ALL_ID == id) {
log.warn("Unexpected request for $ALL_ID for type: $type, cacheFilter: $cacheFilter")
return null
}
validateTypes(type)
return backingStore.get(type, id, cacheFilter) ?: return null
}
override fun evictDeletedItems(type: String, ids: Collection<String>) {
try {
MDC.put("agentClass", "evictDeletedItems")
backingStore.evictAll(type, ids)
} finally {
MDC.remove("agentClass")
}
}
/**
* Retrieves all the identifiers for a type
*
* @param type the type for which to retrieve identifiers
* @return the identifiers for the type
*/
override fun getIdentifiers(type: String): MutableCollection<String> {
validateTypes(type)
return backingStore.getIdentifiers(type)
}
override fun putCacheResult(
source: String,
authoritativeTypes: MutableCollection<String>,
cacheResult: CacheResult
) {
try {
MDC.put("agentClass", "$source putCacheResult")
// This is a hack because some types are global and a single agent
// can't be authoritative for cleanup but can supply enough
// information to create the entity. For those types we need an out
// of band cleanup so they should be cached as authoritative but
// without cleanup
//
// TODO Consider adding a GLOBAL type for supported data types to
// allow caching agents to explicitly opt into this rather than
// encoding them in here..
val globalTypes = getGlobalTypes(source, authoritativeTypes, cacheResult)
cacheResult.cacheResults
.filter {
it.key.contains(ON_DEMAND.ns, ignoreCase = true)
}
.forEach {
authoritativeTypes.add(it.key)
}
val cachedTypes = mutableSetOf<String>()
// Update resource table from Authoritative sources only
when {
// OnDemand agents should only be treated as authoritative and don't use standard eviction logic
source.contains(ON_DEMAND.ns, ignoreCase = true) ->
cacheResult.cacheResults
// And OnDemand agents shouldn't update other resource type tables
.filter {
it.key.contains(ON_DEMAND.ns, ignoreCase = true)
}
.forEach {
cacheDataType(it.key, source, it.value, authoritative = true, cleanup = false)
}
authoritativeTypes.isNotEmpty() ->
cacheResult.cacheResults
.filter {
authoritativeTypes.contains(it.key) || globalTypes.contains(it.key)
}
.forEach {
cacheDataType(it.key, source, it.value, authoritative = true, cleanup = !globalTypes.contains(it.key))
cachedTypes.add(it.key)
}
else -> // If there are no authoritative types in cacheResult, override all as authoritative without cleanup
cacheResult.cacheResults
.forEach {
cacheDataType(it.key, source, it.value, authoritative = true, cleanup = false)
cachedTypes.add(it.key)
}
}
// Update relationships for non-authoritative types
if (!source.contains(ON_DEMAND.ns, ignoreCase = true)) {
cacheResult.cacheResults
.filter {
!cachedTypes.contains(it.key)
}
.forEach {
cacheDataType(it.key, source, it.value, authoritative = false)
}
}
if (cacheResult.evictions.isNotEmpty()) {
cacheResult.evictions.forEach {
evictDeletedItems(it.key, it.value)
}
}
} finally {
MDC.remove("agentClass")
}
}
override fun addCacheResult(
source: String,
authoritativeTypes: MutableCollection<String>,
cacheResult: CacheResult
) {
try {
MDC.put("agentClass", "$source putCacheResult")
authoritativeTypes.addAll(getGlobalTypes(source, authoritativeTypes, cacheResult));
val cachedTypes = mutableSetOf<String>()
if (authoritativeTypes.isNotEmpty()) {
cacheResult.cacheResults
.filter {
authoritativeTypes.contains(it.key)
}
.forEach {
cacheDataType(it.key, source, it.value, authoritative = true, cleanup = false)
cachedTypes.add(it.key)
}
}
cacheResult.cacheResults
.filter { !cachedTypes.contains(it.key) }
.forEach {
cacheDataType(it.key, source, it.value, authoritative = false, cleanup = false)
}
} finally {
MDC.remove("agentClass")
}
}
override fun putCacheData(type: String, cacheData: CacheData) {
try {
MDC.put("agentClass", "putCacheData")
backingStore.merge(type, cacheData)
} finally {
MDC.remove("agentClass")
}
}
fun cleanOnDemand(maxAgeMs: Long): Int {
return (backingStore as SqlCache).cleanOnDemand(maxAgeMs)
}
private fun validateTypes(type: String) {
validateTypes(listOf(type))
}
private fun validateTypes(types: Collection<String>) {
val invalid = types
.asSequence()
.filter { it.contains(":") }
.toSet()
if (invalid.isNotEmpty()) {
throw IllegalArgumentException("Invalid types: $invalid")
}
}
private fun cacheDataType(type: String, agent: String, items: Collection<CacheData>, authoritative: Boolean) {
cacheDataType(type, agent, items, authoritative, cleanup = true)
}
private fun cacheDataType(
type: String,
agent: String,
items: Collection<CacheData>,
authoritative: Boolean,
cleanup: Boolean
) {
val toStore = ArrayList<CacheData>(items.size + 1)
items.forEach {
toStore.add(uniqueifyRelationships(it, agent))
}
// OnDemand agents are always updated incrementally and should not trigger auto-cleanup at the WriteableCache layer
val cleanupOverride =
if (agent.contains(ON_DEMAND.ns, ignoreCase = true) || type.contains(ON_DEMAND.ns, ignoreCase = true)) {
false
} else {
cleanup
}
(backingStore as SqlCache).mergeAll(type, agent, toStore, authoritative, cleanupOverride)
}
private fun uniqueifyRelationships(source: CacheData, sourceAgentType: String): CacheData {
val relationships = HashMap<String, Collection<String>>(source.relationships.size)
for ((key, value) in source.relationships) {
relationships["$key:$sourceAgentType"] = value
}
return DefaultCacheData(source.id, source.ttlSeconds, source.attributes, relationships)
}
private fun getGlobalTypes(source: String, authoritativeTypes: Collection<String>, cacheResult: CacheResult): Set<String> = when {
(source.contains("clustercaching", ignoreCase = true) ||
source.contains("titusstreaming", ignoreCase = true)) &&
!authoritativeTypes.contains(CLUSTERS.ns) &&
cacheResult.cacheResults
.any {
it.key.startsWith(CLUSTERS.ns)
} -> setOf(CLUSTERS.ns, APPLICATIONS.ns)
else -> emptySet()
}
}
| apache-2.0 | 0a4236414d1798e833a3570eb9f20a37 | 31.988372 | 132 | 0.679062 | 4.603651 | false | false | false | false |
nfrankel/kaadin | kaadin-core/src/test/kotlin/ch/frankel/kaadin/common/PageTest.kt | 1 | 1751 | /*
* Copyright 2016 Nicolas Fränkel
*
* 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 ch.frankel.kaadin.common
import ch.frankel.kaadin.*
import com.vaadin.server.*
import org.assertj.core.api.Assertions.assertThat
import org.testng.annotations.*
import java.net.URI
class PageTest {
@BeforeMethod
private fun setUp() {
initializeAndSetCurrentUI()
}
@Test
fun `page should be configurable`() {
val fragment = "a fragment"
page {
uriFragment = fragment
}
assertThat(Page.getCurrent().uriFragment).isEqualTo(fragment)
}
@Test
fun `page location can be set with string`() {
val location = "http://localhost:8080"
location(location)
assertThat(Page.getCurrent().location).isEqualTo(URI(location))
}
@Test
fun `page location can be set with URI`() {
val location = URI("http://localhost:8080")
location(location)
assertThat(Page.getCurrent().location).isEqualTo(location)
}
@Test
fun `page uri fragment can be set`() {
val uriFragment = "a fragment"
uriFragment(uriFragment)
assertThat(Page.getCurrent().uriFragment).isEqualTo(uriFragment)
}
} | apache-2.0 | 97830acb6183018ddb418f01ed465b34 | 28.183333 | 75 | 0.675429 | 4.299754 | false | true | false | false |
LorittaBot/Loritta | web/embed-editor/embed-editor/src/main/kotlin/net/perfectdreams/loritta/embededitor/editors/EmbedTitleEditor.kt | 1 | 1405 | package net.perfectdreams.loritta.embededitor.editors
import kotlinx.html.classes
import kotlinx.html.js.onClickFunction
import net.perfectdreams.loritta.embededitor.EmbedEditor
import net.perfectdreams.loritta.embededitor.data.DiscordEmbed
import net.perfectdreams.loritta.embededitor.utils.lovelyButton
object EmbedTitleEditor : EditorBase {
val isNotNull: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo ->
currentElement.classes += "clickable"
currentElement.onClickFunction = {
titlePopup(discordMessage.embed!!, m)
}
}
val isNull: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo ->
lovelyButton(
"fas fa-heading",
"Adicionar Título"
) {
titlePopup(discordMessage.embed!!, m)
}
}
fun titlePopup(embed: DiscordEmbed, m: EmbedEditor) = genericPopupTextAreaWithSaveAndDelete(
m,
{
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!.copy(title = it)
)
},
{
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!.copy(title = null)
)
},
embed.title ?: "Loritta é muito fofa!",
DiscordEmbed.MAX_DESCRIPTION_LENGTH
)
} | agpl-3.0 | af7c4f7682797a6d392bcad2035d0512 | 32.428571 | 96 | 0.602994 | 5.028674 | false | false | false | false |
iarchii/trade_app | app/src/main/java/xyz/thecodeside/tradeapp/helpers/InternetConnectionManager.kt | 1 | 1353 | package xyz.thecodeside.tradeapp.helpers
import android.app.Activity
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.NetworkInfo
import io.reactivex.Flowable
import io.reactivex.processors.BehaviorProcessor
import javax.inject.Inject
class InternetConnectionManager @Inject internal constructor(
private val service: ConnectivityManager){
private val connectionState : BehaviorProcessor<Status> = BehaviorProcessor.create()
private val onConnectionChanged : OnConnectionChanged = object : OnConnectionChanged{
override fun onChange() = connectionState.onNext(isOnline())
}
private val receiver = InternetConnectionReceiver(onConnectionChanged)
fun isOnline(): Status = if(service.activeNetworkInfo?.state == NetworkInfo.State.CONNECTED) Status.ONLINE else Status.OFFLINE
fun observe(activity: Activity?): Flowable<Status> {
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
activity?.registerReceiver(receiver, intentFilter)
return connectionState
}
fun stopObserve(activity: Activity?){
activity?.unregisterReceiver(receiver)
}
interface OnConnectionChanged{
fun onChange()
}
enum class Status{
ONLINE,
OFFLINE
}
} | apache-2.0 | 49cdfd8963c5613100ca9fcfc9bc2713 | 29.088889 | 130 | 0.750185 | 5.412 | false | false | false | false |
j2ghz/tachiyomi-extensions | src/ru/mintmanga/src/eu/kanade/tachiyomi/extension/ru/mintmanga/Mintmanga.kt | 1 | 8526 | package eu.kanade.tachiyomi.extension.ru.mintmanga
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Headers
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
class Mintmanga : ParsedHttpSource() {
override val id: Long = 6
override val name = "Mintmanga"
override val baseUrl = "http://mintmanga.com"
override val lang = "ru"
override val supportsLatest = true
override fun popularMangaRequest(page: Int): Request =
GET("$baseUrl/list?sortType=rate&offset=${70 * (page - 1)}&max=70", headers)
override fun latestUpdatesRequest(page: Int): Request =
GET("$baseUrl/list?sortType=updated&offset=${70 * (page - 1)}&max=70", headers)
override fun popularMangaSelector() = "div.tile"
override fun latestUpdatesSelector() = "div.tile"
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.thumbnail_url = element.select("img.lazy").first().attr("data-original")
element.select("h3 > a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.attr("title")
}
return manga
}
override fun latestUpdatesFromElement(element: Element): SManga =
popularMangaFromElement(element)
override fun popularMangaNextPageSelector() = "a.nextLink"
override fun latestUpdatesNextPageSelector() = "a.nextLink"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val genres = filters.filterIsInstance<Genre>().joinToString("&") { it.id + arrayOf("=", "=in", "=ex")[it.state] }
return GET("$baseUrl/search/advanced?q=$query&$genres", headers)
}
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element)
// max 200 results
override fun searchMangaNextPageSelector() = null
override fun mangaDetailsParse(document: Document): SManga {
val infoElement = document.select("div.leftContent").first()
val manga = SManga.create()
manga.author = infoElement.select("span.elem_author").first()?.text()
manga.genre = infoElement.select("span.elem_genre").text().replace(" ,", ",")
manga.description = infoElement.select("div.manga-description").text()
manga.status = parseStatus(infoElement.html())
manga.thumbnail_url = infoElement.select("img").attr("data-full")
return manga
}
private fun parseStatus(element: String): Int = when {
element.contains("<h3>Запрещена публикация произведения по копирайту</h3>") -> SManga.LICENSED
element.contains("<h1 class=\"names\"> Сингл") || element.contains("<b>Перевод:</b> завершен") -> SManga.COMPLETED
element.contains("<b>Перевод:</b> продолжается") -> SManga.ONGOING
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "div.chapters-link tbody tr"
override fun chapterFromElement(element: Element): SChapter {
val urlElement = element.select("a").first()
val urlText = urlElement.text()
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(urlElement.attr("href") + "?mtr=1")
if (urlText.endsWith(" новое")) {
chapter.name = urlText.dropLast(6)
} else {
chapter.name = urlText
}
chapter.date_upload = element.select("td.hidden-xxs").last()?.text()?.let {
SimpleDateFormat("dd/MM/yy", Locale.US).parse(it).time
} ?: 0
return chapter
}
override fun prepareNewChapter(chapter: SChapter, manga: SManga) {
val basic = Regex("""\s*([0-9]+)(\s-\s)([0-9]+)\s*""")
val extra = Regex("""\s*([0-9]+\sЭкстра)\s*""")
val single = Regex("""\s*Сингл\s*""")
when {
basic.containsMatchIn(chapter.name) -> {
basic.find(chapter.name)?.let {
val number = it.groups[3]?.value!!
chapter.chapter_number = number.toFloat()
}
}
extra.containsMatchIn(chapter.name) -> // Extra chapters doesn't contain chapter number
chapter.chapter_number = -2f
single.containsMatchIn(chapter.name) -> // Oneshoots, doujinshi and other mangas with one chapter
chapter.chapter_number = 1f
}
}
override fun pageListParse(response: Response): List<Page> {
val html = response.body()!!.string()
val beginIndex = html.indexOf("rm_h.init( [")
val endIndex = html.indexOf("], 0, false);", beginIndex)
val trimmedHtml = html.substring(beginIndex, endIndex)
val p = Pattern.compile("'.*?','.*?',\".*?\"")
val m = p.matcher(trimmedHtml)
val pages = mutableListOf<Page>()
var i = 0
while (m.find()) {
val urlParts = m.group().replace("[\"\']+".toRegex(), "").split(',')
pages.add(Page(i++, "", urlParts[1] + urlParts[0] + urlParts[2]))
}
return pages
}
override fun pageListParse(document: Document): List<Page> {
throw Exception("Not used")
}
override fun imageUrlParse(document: Document) = ""
override fun imageRequest(page: Page): Request {
val imgHeader = Headers.Builder().apply {
add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64)")
add("Referer", baseUrl)
}.build()
return GET(page.imageUrl!!, imgHeader)
}
private class Genre(name: String, val id: String) : Filter.TriState(name)
/* [...document.querySelectorAll("tr.advanced_option:nth-child(1) > td:nth-child(3) span.js-link")]
* .map(el => `Genre("${el.textContent.trim()}", $"{el.getAttribute('onclick')
* .substr(31,el.getAttribute('onclick').length-33)"})`).join(',\n')
* on http://mintmanga.com/search/advanced
*/
override fun getFilterList() = FilterList(
Genre("арт", "el_2220"),
Genre("бара", "el_1353"),
Genre("боевик", "el_1346"),
Genre("боевые искусства", "el_1334"),
Genre("вампиры", "el_1339"),
Genre("гарем", "el_1333"),
Genre("гендерная интрига", "el_1347"),
Genre("героическое фэнтези", "el_1337"),
Genre("детектив", "el_1343"),
Genre("дзёсэй", "el_1349"),
Genre("додзинси", "el_1332"),
Genre("драма", "el_1310"),
Genre("игра", "el_5229"),
Genre("история", "el_1311"),
Genre("киберпанк", "el_1351"),
Genre("комедия", "el_1328"),
Genre("меха", "el_1318"),
Genre("мистика", "el_1324"),
Genre("научная фантастика", "el_1325"),
Genre("омегаверс", "el_5676"),
Genre("повседневность", "el_1327"),
Genre("постапокалиптика", "el_1342"),
Genre("приключения", "el_1322"),
Genre("психология", "el_1335"),
Genre("романтика", "el_1313"),
Genre("самурайский боевик", "el_1316"),
Genre("сверхъестественное", "el_1350"),
Genre("сёдзё", "el_1314"),
Genre("сёдзё-ай", "el_1320"),
Genre("сёнэн", "el_1326"),
Genre("сёнэн-ай", "el_1330"),
Genre("спорт", "el_1321"),
Genre("сэйнэн", "el_1329"),
Genre("трагедия", "el_1344"),
Genre("триллер", "el_1341"),
Genre("ужасы", "el_1317"),
Genre("фантастика", "el_1331"),
Genre("фэнтези", "el_1323"),
Genre("школа", "el_1319"),
Genre("эротика", "el_1340"),
Genre("этти", "el_1354"),
Genre("юри", "el_1315"),
Genre("яой", "el_1336")
)
} | apache-2.0 | 9a3e489cbeb3cf73564009bd301facdb | 38.014493 | 122 | 0.588359 | 3.893443 | false | false | false | false |
ericberman/MyFlightbookAndroid | app/src/main/java/model/DataBaseHelper.kt | 1 | 7242 | /*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package model
import android.content.Context
import android.content.res.AssetManager
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import java.io.*
// thanks to http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
// for the code here. IMPORTANT: Follow code at top for create/insert and _id
class DataBaseHelper(context: Context, private val m_DBName: String, dbVersion: Int) :
SQLiteOpenHelper(context, m_DBName, null, dbVersion) {
private var myDataBase: SQLiteDatabase? = null
private val mDBFileName: String = context.getDatabasePath(m_DBName).absolutePath
private val mFilesDir: String = context.filesDir.path
private val mAssetManager: AssetManager = context.assets
/**
* Creates a empty database on the system and rewrites it with your own
* database.
*/
@Throws(Error::class)
fun createDataBase() {
val dbExist = checkDataBase()
var dbRead: SQLiteDatabase? = null
if (!dbExist) {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
try {
dbRead = this.readableDatabase
} catch (e: Exception) {
Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(e))
} finally {
if (dbRead != null && dbRead.isOpen) dbRead.close()
}
try {
copyDataBase()
} catch (e: IOException) {
throw Error("Error copying database" + e.message)
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private fun checkDataBase(): Boolean {
var checkDB: SQLiteDatabase? = null
try {
checkDB = SQLiteDatabase.openDatabase(mDBFileName, null, SQLiteDatabase.OPEN_READONLY)
} catch (e: SQLiteException) {
// database does't exist yet.
} finally {
checkDB?.close()
}
return checkDB != null
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
*/
@Throws(IOException::class)
private fun copyDataBase() {
// Open your local db as the input stream
val myInput: InputStream
// Ensure that the directory exists.
var f = File(mFilesDir)
if (!f.exists()) {
if (f.mkdir()) Log.v(MFBConstants.LOG_TAG, "Database Directory created")
}
// Open the empty db as the output stream
val szFileName = mDBFileName
f = File(szFileName)
if (f.exists()) {
if (!f.delete()) Log.v(MFBConstants.LOG_TAG, "Delete failed for copydatabase")
}
val myOutput: OutputStream = FileOutputStream(szFileName)
try {
// now put the pieces of the DB together (see above)
val szAsset =
if (m_DBName.compareTo(DB_NAME_MAIN) == 0) szDBNameMain else szDBNameAirports
myInput = mAssetManager.open(szAsset)
// transfer bytes from the inputfile to the outputfile
val buffer = ByteArray(1024)
var length: Int
while (myInput.read(buffer).also { length = it } > 0) {
myOutput.write(buffer, 0, length)
}
myInput.close()
} catch (ex: Exception) {
Log.e(MFBConstants.LOG_TAG, "Error copying database: " + ex.message)
} finally {
// Close the streams
try {
myOutput.flush()
myOutput.close()
} catch (ex: Exception) {
Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(ex))
}
}
}
@Throws(SQLException::class)
fun openDataBase() {
// Open the database
myDataBase = SQLiteDatabase.openDatabase(
mDBFileName, null,
SQLiteDatabase.OPEN_READONLY
)
}
@Synchronized
override fun close() {
if (myDataBase != null) myDataBase!!.close()
super.close()
}
override fun onCreate(db: SQLiteDatabase) {}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (m_DBName.compareTo(DB_NAME_MAIN) == 0) {
Log.e(
MFBConstants.LOG_TAG,
String.format("Upgrading main DB from %d to %d", oldVersion, newVersion)
)
// below will attempt to migrate version to version, step by step
// Initial release was (I believe) version 3, so anything less than that
if (oldVersion < newVersion) {
Log.e(MFBConstants.LOG_TAG, "Slamming new main database")
try {
copyDataBase() // just force an upgrade, always. We need to force a download of aircraft again anyhow
} catch (e: IOException) {
Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(e))
}
}
} else // else it is the airport DB. This is read-only, so we can ALWAYS just slam in a new copy.
{
try {
Log.e(
MFBConstants.LOG_TAG,
String.format("Upgrading airport DB from %d to %d", oldVersion, newVersion)
)
copyDataBase()
} catch (e: IOException) {
Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(e))
}
}
}
companion object {
// The Android's default system path of your application database.
// private static String DB_PATH = "/data/data/com.myflightbook.android/databases/";
const val DB_NAME_MAIN = "mfbAndroid.sqlite"
const val DB_NAME_AIRPORTS = "mfbAirports.sqlite"
private const val szDBNameMain = "mfbAndroid.sqlite"
private const val szDBNameAirports = "mfbAirport.sqlite"
}
} | gpl-3.0 | 5fb9ba08576edc8bd363b83a1e461683 | 37.121053 | 122 | 0.606462 | 4.557583 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/mail/appointment_confirmation.kt | 1 | 3062 | package at.cpickl.gadsu.mail
import at.cpickl.gadsu.appointment.Appointment
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.firstNotEmpty
import at.cpickl.gadsu.global.GadsuException
import at.cpickl.gadsu.preferences.Prefs
import at.cpickl.gadsu.service.TemplateData
import at.cpickl.gadsu.service.TemplateDeclaration
import at.cpickl.gadsu.service.TemplatingEngine
import com.google.common.annotations.VisibleForTesting
import javax.inject.Inject
interface AppointmentConfirmationer {
fun sendConfirmation(client: Client, appointment: Appointment)
}
class AppointmentConfirmationerImpl @Inject constructor(
private val templating: TemplatingEngine,
private val mailSender: MailSender,
private val prefs: Prefs
) : AppointmentConfirmationer {
// see: GCalSyncService
override fun sendConfirmation(client: Client, appointment: Appointment) {
client.validateTemplateData()
val subjectTemplate = prefs.preferencesData.templateConfirmSubject ?: throw GadsuException("confirm subject not set!")
val bodyTemplate = prefs.preferencesData.templateConfirmBody?: throw GadsuException("confirm body not set!")
mailSender.send(buildMail(subjectTemplate, bodyTemplate, client, appointment))
}
@VisibleForTesting fun buildMail(subjectTemplate: String, bodyTemplate: String, client: Client, appointment: Appointment): Mail {
val data = AppointmentConfirmationTemplateDeclaration.process(client to appointment)
val subject = templating.process(subjectTemplate, data)
val body = templating.process(bodyTemplate, data)
return Mail(client.contact.mail, subject, body, recipientsAsBcc = false)
}
private fun Client.validateTemplateData() {
if (contact.mail.isEmpty()) {
throw AppointmentConfirmationException("Client mail is not configured for: $this")
}
if (firstName.isEmpty()) {
throw AppointmentConfirmationException("Client mail is not configured for: $this")
}
}
}
class AppointmentConfirmationException(message: String, cause: Exception? = null) : GadsuException(message, cause)
object AppointmentConfirmationTemplateDeclaration : TemplateDeclaration<Pair<Client, Appointment>> {
override val data = listOf(
TemplateData<Pair<Client, Appointment>>("name", "Der externe Spitzname bzw. Vorname falls nicht vorhanden, zB: \${name?lower_case}") {
firstNotEmpty(it.first.nickNameExt, it.first.firstName)
},
TemplateData("dateStart", "Z.B.: termin am \${dateStart?string[\"EEEE 'der' d. MMMMM\"]?lower_case} von \${dateStart?string[\"HH:mm\"]}") {
it.second.start.toDate()
},
TemplateData("dateEnd", "Z.B.: bis \${dateEnd?string[\"HH:mm\"]} uhr") {
it.second.end.toDate()
},
TemplateData("gender", "Z.B.: hallo <#if gender == \"M\">lieber <#elseif gender == \"F\">liebe </#if>") {
it.first.gender.sqlCode
}
)
}
| apache-2.0 | b3848a3b07721c2eb04c3a412795d13f | 42.126761 | 151 | 0.700849 | 4.536296 | false | true | false | false |
RogaLabs/social-login | lib/src/main/java/com/rogalabs/lib/facebook/LoginFacebookPresenter.kt | 1 | 3694 | package com.rogalabs.lib.facebook
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.rogalabs.lib.Callback
import com.rogalabs.lib.LoginContract
import com.rogalabs.lib.model.Hometown
import com.rogalabs.lib.model.SocialUser
import org.json.JSONObject
import java.util.*
/**
* Created by roga on 14/07/16.
*/
class LoginFacebookPresenter(val view: LoginContract.View) : LoginContract.FacebookPresenter,
FacebookCallback<LoginResult>, GraphRequest.GraphJSONObjectCallback {
private var callback: Callback? = null
private var callbackManager: CallbackManager? = null
private var activity: FragmentActivity? = null
private val profileFields = "id, name, email, birthday, hometown"
override fun activityResult(requestCode: Int, resultCode: Int, data: Intent) {
callbackManager?.onActivityResult(requestCode, resultCode, data)
}
override fun create(activity: FragmentActivity?) {
this.activity = activity
callbackManager = com.facebook.CallbackManager.Factory.create()
registerFacebookCallback(callbackManager)
}
override fun pause() {
}
override fun destroy() {
}
private fun registerFacebookCallback(callbackManager: CallbackManager?) {
LoginManager.getInstance().registerCallback(callbackManager, this)
}
override fun onCancel() {
}
override fun onError(error: FacebookException?) {
callback?.onError(error?.cause!!)
}
override fun onSuccess(result: LoginResult?) {
sendGraphRequest()
}
override fun signIn(callback: Callback) {
this.callback = callback
LoginManager.getInstance().logInWithReadPermissions(activity,
Arrays.asList(
"public_profile",
"email",
"user_birthday",
"user_hometown"))
}
override fun signIn(callback: Callback, readPermissions: List<String>) {
this.callback = callback
LoginManager.getInstance().logInWithReadPermissions(activity, readPermissions)
}
override fun signOut() {
LoginManager.getInstance().logOut()
}
override fun onCompleted(jsonResponse: JSONObject?, response: GraphResponse?) {
callback?.onSuccess(buildSocialUser(jsonResponse))
}
private fun sendGraphRequest() {
val graphRequest: GraphRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), this)
val parameters = Bundle()
parameters.putString("fields", profileFields)
graphRequest.setParameters(parameters)
graphRequest.executeAsync()
}
private fun buildSocialUser(jsonObject: JSONObject?): SocialUser {
var hometown: Hometown = Hometown()
var birthday: String = ""
try {
val hometownObj = jsonObject?.getJSONObject("hometown")
birthday = jsonObject?.getString("birthday") as String
hometown = Hometown(hometownObj?.getString("id"), hometownObj?.getString("name"))
} finally {
val user: SocialUser = SocialUser(jsonObject?.getString("id"),
jsonObject?.getString("name"), jsonObject?.getString("email"),
birthday, userPicture(jsonObject?.getString("id")),
hometown, AccessToken.getCurrentAccessToken().token)
return user
}
}
private fun userPicture(id: String?): String {
return "https://graph.facebook.com/${id}/picture?type=large"
}
} | mit | 8579c538fd62217ec9a5248b5a43d9d7 | 32.288288 | 109 | 0.6719 | 5.019022 | false | false | false | false |
siempredelao/Distance-From-Me-Android | app/src/main/java/gc/david/dfm/service/GeofencingService.kt | 1 | 4351 | /*
* Copyright (c) 2019 David Aguiar Gonzalez
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gc.david.dfm.service
import android.app.IntentService
import android.app.Service
import android.content.Intent
import android.location.Location
import android.os.Bundle
import androidx.core.os.bundleOf
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.LocationListener
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import gc.david.dfm.map.LocationUtils
class GeofencingService :
IntentService("GeofencingService"),
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private var googleApiClient: GoogleApiClient? = null
private var locationRequest: LocationRequest? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
createGoogleApiClient()
googleApiClient?.connect()
createLocationRequest()
return Service.START_STICKY
}
override fun onHandleIntent(intent: Intent?) {
// nothing
}
override fun onConnected(bundle: Bundle?) {
val lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient)
if (lastKnownLocation != null) {
sendUpdate(lastKnownLocation)
}
startLocationUpdates()
}
override fun onConnectionSuspended(cause: Int) {
// nothing
}
override fun onConnectionFailed(connectionResult: ConnectionResult) {
// nothing
}
override fun onLocationChanged(location: Location) {
sendUpdate(location)
}
@Synchronized
private fun createGoogleApiClient() {
googleApiClient = GoogleApiClient.Builder(this).addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build()
}
private fun stopLocationUpdates() {
if (googleApiClient?.isConnected == true) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this)
}
}
private fun createLocationRequest() {
locationRequest = LocationRequest.create().apply {
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
interval = LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS
// Set the interval ceiling to one minute
fastestInterval = LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS
}
}
private fun startLocationUpdates() {
val googleApiClient = googleApiClient ?: return
val locationRequest = locationRequest ?: return
if (googleApiClient.isConnected) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this)
}
}
private fun sendUpdate(location: Location) {
val locationIntent = Intent(GEOFENCE_RECEIVER_ACTION).apply {
val bundle =
bundleOf(
GEOFENCE_RECEIVER_LATITUDE_KEY to location.latitude,
GEOFENCE_RECEIVER_LONGITUDE_KEY to location.longitude
)
putExtras(bundle)
}
applicationContext.sendBroadcast(locationIntent)
}
override fun onDestroy() {
super.onDestroy()
stopLocationUpdates()
googleApiClient?.disconnect()
}
companion object {
const val GEOFENCE_RECEIVER_ACTION = "geofence.receiver.action"
const val GEOFENCE_RECEIVER_LATITUDE_KEY = "geofence.receiver.latitude.key"
const val GEOFENCE_RECEIVER_LONGITUDE_KEY = "geofence.receiver.longitude.key"
}
}
| apache-2.0 | 1807f587a1739282e05fc75fdd99c10b | 32.21374 | 108 | 0.689497 | 5.248492 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/proxy/ClientProxy.kt | 2 | 6600 | package com.cout970.magneticraft.proxy
import com.cout970.magneticraft.Debug
import com.cout970.magneticraft.MOD_ID
import com.cout970.magneticraft.Magneticraft
import com.cout970.magneticraft.misc.*
import com.cout970.magneticraft.registry.blocks
import com.cout970.magneticraft.registry.items
import com.cout970.magneticraft.registry.registerSounds
import com.cout970.magneticraft.systems.blocks.BlockBase
import com.cout970.magneticraft.systems.gui.components.CompBookRenderer
import com.cout970.magneticraft.systems.items.ItemBase
import com.cout970.magneticraft.systems.tileentities.TileBase
import com.cout970.magneticraft.systems.tilerenderers.TileRenderer
import com.cout970.modelloader.api.DefaultBlockDecorator
import com.cout970.modelloader.api.ModelLoaderApi
import net.minecraft.client.renderer.block.model.ModelResourceLocation
import net.minecraft.util.SoundEvent
import net.minecraftforge.client.event.ModelBakeEvent
import net.minecraftforge.client.model.ModelLoader
import net.minecraftforge.client.model.obj.OBJLoader
import net.minecraftforge.event.RegistryEvent
import net.minecraftforge.fml.client.registry.ClientRegistry
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import net.minecraftforge.fml.relauncher.Side
/**
* This class extends the functionality of CommonProxy but adds
* thing only for the client: sounds, models, textures and renders
*/
@Suppress("unused")
class ClientProxy : CommonProxy() {
// List of registered TileEntityRenderers
val tileRenderers = mutableListOf<TileRenderer<out TileBase>>()
@SubscribeEvent
fun initSoundsEvent(event: RegistryEvent.Register<SoundEvent>) {
logTime("Task registerSounds:") { registerSounds(event.registry) }
}
override fun postItemRegister() {
super.postItemRegister()
//Item renders
logTime("Task registerItemModels:") { registerItemModels() }
//ItemBlock renders
logTime("Task registerBlockAndItemBlockModels:") { registerBlockAndItemBlockModels() }
//TileEntity renderers
logTime("Task registerTileEntityRenderers:") { registerTileEntityRenderers() }
}
override fun preInit() {
super.preInit()
//Model loaders
OBJLoader.INSTANCE.addDomain(MOD_ID)
// Preload guidebook
logTime("Task loadGuideBookPages:") { CompBookRenderer.book }
}
fun registerItemModels() {
items.forEach { i ->
(i as? ItemBase)?.let { item ->
item.variants.forEach { variant ->
ModelLoader.setCustomModelResourceLocation(
item,
variant.key,
item.registryName!!.toModel(variant.value)
)
}
item.customModels.forEach { (state, location) ->
ModelLoaderApi.registerModelWithDecorator(
ModelResourceLocation(item.registryName!!, state),
location,
DefaultBlockDecorator
)
}
}
}
}
fun registerBlockAndItemBlockModels() {
blocks.forEach { (block, itemBlock) ->
if (itemBlock == null) return@forEach
(block as? BlockBase)?.let { blockBase ->
if (blockBase.generateDefaultItemModel) {
blockBase.inventoryVariants.forEach {
ModelLoader.setCustomModelResourceLocation(
itemBlock,
it.key,
itemBlock.registryName!!.toModel(it.value)
)
}
} else {
ModelLoader.setCustomModelResourceLocation(
itemBlock,
0,
itemBlock.registryName!!.toModel("inventory")
)
}
val mapper = blockBase.getCustomStateMapper()
if (mapper != null) {
ModelLoader.setCustomStateMapper(blockBase, mapper)
}
blockBase.customModels.forEach { (state, location) ->
if (state == "inventory" || blockBase.forceModelBake) {
ModelLoaderApi.registerModelWithDecorator(
modelId = ModelResourceLocation(blockBase.registryName!!, state),
modelLocation = location,
decorator = DefaultBlockDecorator
)
} else {
ModelLoaderApi.registerModel(
modelId = ModelResourceLocation(blockBase.registryName!!, state),
modelLocation = location,
bake = false
)
}
}
}
}
}
@Suppress("UNCHECKED_CAST")
fun registerTileEntityRenderers() {
val data = Magneticraft.asmData.getAll(RegisterRenderer::class.java.canonicalName)
data.forEach {
try {
val clazz = Class.forName(it.className).kotlin
val annotation = clazz.annotations.find { it is RegisterRenderer } as RegisterRenderer
val tile = annotation.tileEntity.java as Class<TileBase>
val renderer = clazz.objectInstance as TileRenderer<TileBase>
register(tile, renderer)
if (Debug.DEBUG) {
info("Registering TESR: Tile = ${clazz.simpleName}, Renderer = ${renderer.javaClass.simpleName}")
}
} catch (e: Exception) {
logError("Unable to register class with @RegisterRenderer: $it")
e.printStackTrace()
}
}
}
override fun getSide() = Side.CLIENT
/**
* Updates all the TileEntityRenderers to reload models
*/
@Suppress("unused", "UNUSED_PARAMETER")
@SubscribeEvent
fun onModelRegistryReload(event: ModelBakeEvent) {
tileRenderers.forEach { it.onModelRegistryReload() }
}
/**
* Binds a TileEntity class with a TileEntityRenderer and
* registers the TileEntityRenderer to update it when ModelBakeEvent is fired
*/
private fun <T : TileBase> register(tileEntityClass: Class<T>, specialRenderer: TileRenderer<T>) {
ClientRegistry.bindTileEntitySpecialRenderer(tileEntityClass, specialRenderer)
tileRenderers.add(specialRenderer)
}
} | gpl-2.0 | cba48400a3d769dccaf3f07747989580 | 37.377907 | 117 | 0.60803 | 5.477178 | false | false | false | false |
andrei-heidelbacher/algostorm | algostorm-systems/src/main/kotlin/com/andreihh/algostorm/systems/MapObject.kt | 1 | 3521 | /*
* Copyright (c) 2017 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.andreihh.algostorm.systems
import com.andreihh.algostorm.core.drivers.audio.AudioStream
import com.andreihh.algostorm.core.drivers.graphics2d.Color
import com.andreihh.algostorm.core.drivers.io.Resource
import com.andreihh.algostorm.core.ecs.Component
import com.andreihh.algostorm.core.ecs.EntityPool
import com.andreihh.algostorm.core.ecs.EntityRef
import com.andreihh.algostorm.core.ecs.EntityRef.Id
import com.andreihh.algostorm.systems.graphics2d.TileSet
import kotlin.properties.Delegates
class MapObject private constructor(
val width: Int,
val height: Int,
val tileWidth: Int,
val tileHeight: Int,
val tileSets: List<TileSet>,
val sounds: List<Resource<AudioStream>>,
val entities: EntityPool,
val backgroundColor: Color?,
val version: String
) {
class Builder {
companion object {
fun mapObject(init: Builder.() -> Unit): MapObject =
Builder().apply(init).build()
}
var width: Int by Delegates.notNull()
var height: Int by Delegates.notNull()
var tileWidth: Int by Delegates.notNull()
var tileHeight: Int by Delegates.notNull()
private val tileSets = arrayListOf<TileSet>()
private val sounds = arrayListOf<Resource<AudioStream>>()
private val initialEntities = hashMapOf<Id, Collection<Component>>()
private val entities = arrayListOf<Collection<Component>>()
var backgroundColor: Color? = null
var version: String = "1.0"
fun tileSet(init: TileSet.Builder.() -> Unit) {
tileSets += TileSet.Builder().apply(init).build()
}
fun tileSet(tileSet: TileSet) {
tileSets += tileSet
}
fun sound(resource: String) {
sounds += Resource(resource)
}
fun sound(resource: Resource<AudioStream>) {
sounds += resource
}
fun entity(id: Id, init: EntityRef.Builder.() -> Unit) {
initialEntities[id] = EntityRef.Builder().apply(init).build()
}
fun entity(id: Id, components: Collection<Component>) {
initialEntities[id] = components
}
fun entity(init: EntityRef.Builder.() -> Unit) {
entities += EntityRef.Builder().apply(init).build()
}
fun entity(components: Collection<Component>) {
entities += components
}
fun build(): MapObject = MapObject(
width = width,
height = height,
tileWidth = tileWidth,
tileHeight = tileHeight,
tileSets = tileSets.toList(),
sounds = sounds.toList(),
entities = EntityPool.of(initialEntities)
.apply { entities.forEach { create(it) } },
backgroundColor = backgroundColor,
version = version
)
}
}
| apache-2.0 | 591e6ed024a5434b5861d45dc3b79057 | 33.519608 | 76 | 0.643283 | 4.596606 | false | false | false | false |
google/horologist | compose-tools/src/main/java/com/google/android/horologist/compose/tools/ThemeValues.kt | 1 | 3202 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.compose.tools
import androidx.compose.ui.graphics.Color
import androidx.wear.compose.material.Colors
public data class ThemeValues(val name: String, val index: Int, val colors: Colors) {
val safeName: String
get() = name.replace("[^A-Za-z0-9]".toRegex(), "")
}
public val themeValues: List<ThemeValues> = listOf(
ThemeValues("Blue (Default - AECBFA)", 0, Colors()),
ThemeValues(
"Blue (7FCFFF)",
1,
Colors(
primary = Color(0xFF7FCFFF),
primaryVariant = Color(0xFF3998D3),
secondary = Color(0xFF6DD58C),
secondaryVariant = Color(0xFF1EA446)
)
),
ThemeValues(
"Lilac (D0BCFF)",
2,
Colors(
primary = Color(0xFFD0BCFF),
primaryVariant = Color(0xFF9A82DB),
secondary = Color(0xFF7FCFFF),
secondaryVariant = Color(0xFF3998D3)
)
),
ThemeValues(
"Green (6DD58C)",
3,
Colors(
primary = Color(0xFF6DD58C),
primaryVariant = Color(0xFF1EA446),
secondary = Color(0xFFFFBB29),
secondaryVariant = Color(0xFFD68400)
)
),
ThemeValues(
"Blue with Text (7FCFFF)",
4,
Colors(
primary = Color(0xFF7FCFFF),
primaryVariant = Color(0xFF3998D3),
onPrimary = Color(0xFF003355),
secondary = Color(0xFF6DD58C),
secondaryVariant = Color(0xFF1EA446),
onSecondary = Color(0xFF0A3818),
surface = Color(0xFF303030),
onSurface = Color(0xFFE3E3E3),
onSurfaceVariant = Color(0xFFC4C7C5),
background = Color.Black,
onBackground = Color.White,
error = Color(0xFFF2B8B5),
onError = Color(0xFF370906)
)
),
ThemeValues(
"Orange-y",
5,
Colors(
secondary = Color(0xFFED612B), // Used for RSB
surface = Color(0xFF202124), // Used for Device Chip
onPrimary = Color(0xFFED612B),
onSurface = Color(0xFFED612B)
)
),
ThemeValues(
"Uamp",
6,
Colors(
primary = Color(0xFF981F68),
primaryVariant = Color(0xFF66003d),
secondary = Color(0xFF981F68),
error = Color(0xFFE24444),
onPrimary = Color.White,
onSurfaceVariant = Color(0xFFDADCE0),
surface = Color(0xFF303133),
onError = Color.Black
)
)
)
| apache-2.0 | 9175aeafe90b6c0e2d1a04d82967be0c | 30.392157 | 85 | 0.584322 | 4.042929 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/view/ScrollingViewWithBottomBarBehavior.kt | 1 | 2028 | package info.papdt.express.helper.view
import android.content.Context
import com.google.android.material.appbar.AppBarLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.recyclerview.widget.RecyclerView
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import info.papdt.express.helper.R
class ScrollingViewWithBottomBarBehavior(context: Context, attrs: AttributeSet?)
: AppBarLayout.ScrollingViewBehavior(context, attrs) {
private var bottomMargin = 0
private fun isBottomBar(view: View): Boolean {
return view.id == R.id.bottom_bar && view is LinearLayout
}
override fun layoutDependsOn(parent: CoordinatorLayout,
child: View,
dependency: View): Boolean {
return super.layoutDependsOn(parent, child, dependency) || isBottomBar(dependency)
}
override fun onDependentViewChanged(parent: CoordinatorLayout,
child: View,
dependency: View): Boolean {
val result = super.onDependentViewChanged(parent, child, dependency)
if (isBottomBar(dependency) && dependency.height != bottomMargin) {
bottomMargin = dependency.height
var targetChild = child
if (child is SmartRefreshLayout) {
for (index in 0 until child.childCount) {
val view = child.getChildAt(index)
if (view is RecyclerView) {
targetChild = view
break
}
}
}
val layout = targetChild.layoutParams as ViewGroup.MarginLayoutParams
layout.bottomMargin = bottomMargin
targetChild.requestLayout()
return true
} else {
return result
}
}
} | gpl-3.0 | 0b872416c656ed06e054b1aba7005bf4 | 35.890909 | 90 | 0.622781 | 5.586777 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/list/PagedListFactoryTest.kt | 1 | 1309 | package org.wordpress.android.fluxc.list
import androidx.paging.DataSource.InvalidatedCallback
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.model.list.PagedListFactory
internal class PagedListFactoryTest {
@Test
fun `create factory triggers create data source`() {
val mockCreateDataSource = mock<() -> TestInternalPagedListDataSource>()
whenever(mockCreateDataSource.invoke()).thenReturn(mock())
val pagedListFactory = PagedListFactory(mockCreateDataSource)
pagedListFactory.create()
verify(mockCreateDataSource, times(1)).invoke()
}
@Test
fun `invalidate triggers create data source`() {
val mockCreateDataSource = mock<() -> TestInternalPagedListDataSource>()
whenever(mockCreateDataSource.invoke()).thenReturn(mock())
val invalidatedCallback = mock<InvalidatedCallback>()
val pagedListFactory = PagedListFactory(mockCreateDataSource)
val currentSource = pagedListFactory.create()
currentSource.addInvalidatedCallback(invalidatedCallback)
pagedListFactory.invalidate()
verify(invalidatedCallback, times(1)).onInvalidated()
}
}
| gpl-2.0 | e107f19796582140652e140c807fef17 | 34.378378 | 80 | 0.744843 | 5.409091 | false | true | false | false |
rpradal/OCTOMeuh | app/src/main/kotlin/com/octo/mob/octomeuh/transversal/HumanlyReadableDurationsConverter.kt | 1 | 3192 | package com.octo.mob.octomeuh.transversal
interface HumanlyReadableDurationsConverter {
fun getReadableStringFromValueInSeconds(secondsDuration: Int): String
}
abstract class HumanlyReadableDurationsConverterImpl : HumanlyReadableDurationsConverter {
private companion object {
val SECONDS_IN_ONE_MINUTE = 60
val MINUTES_IN_ONE_HOUR = 60
val SECONDS_IN_ONE_HOUR = MINUTES_IN_ONE_HOUR * SECONDS_IN_ONE_MINUTE
}
protected fun getSecondsValue(secondsDuration: Int) = secondsDuration % SECONDS_IN_ONE_MINUTE
protected fun getMinutesValue(hourValue: Int, secondsDuration: Int) = (secondsDuration - hourValue * SECONDS_IN_ONE_HOUR) / MINUTES_IN_ONE_HOUR
protected fun getHourValue(secondsDuration: Int) = secondsDuration / (SECONDS_IN_ONE_HOUR)
}
class CompactDurationConverterImpl : HumanlyReadableDurationsConverterImpl() {
override fun getReadableStringFromValueInSeconds(secondsDuration: Int): String {
val hourValue = getHourValue(secondsDuration)
val minutesValue = getMinutesValue(hourValue, secondsDuration)
val secondsValue = getSecondsValue(secondsDuration)
val hourString = getCompactReadableHours(hourValue)
val minutesString = getCompactReadableMinutes(hourValue, minutesValue)
val secondsString = getCompactReadableSeconds(hourValue, minutesValue, secondsValue)
return hourString + minutesString + secondsString
}
private fun getCompactReadableHours(hourValue: Int) = if (hourValue > 0) "$hourValue:" else ""
private fun getCompactReadableMinutes(hourValue: Int, minutesValue: Int): String {
if (minutesValue > 0) {
return String.format("%02d:", minutesValue)
} else if (hourValue > 0) {
return "00:"
} else {
return ""
}
}
private fun getCompactReadableSeconds(hourValue: Int, minutesValue: Int, secondsValue: Int): String {
if (secondsValue > 0) {
return String.format("%02d", secondsValue)
} else if (hourValue == 0 && minutesValue == 0) {
return "0"
} else {
return "00"
}
}
}
class ExpandedDurationConverterImpl : HumanlyReadableDurationsConverterImpl() {
override fun getReadableStringFromValueInSeconds(secondsDuration: Int): String {
val hourValue = getHourValue(secondsDuration)
val minutesValue = getMinutesValue(hourValue, secondsDuration)
val secondsValue = getSecondsValue(secondsDuration)
val hourString = getReadableHours(hourValue)
val minutesString = getReadableMinutes(minutesValue)
val secondsString = getReadableSeconds(hourValue, minutesValue, secondsValue)
return hourString + minutesString + secondsString
}
private fun getReadableSeconds(hourValue: Int, minutesValue: Int, secondsValue: Int) = if (secondsValue > 0) "${secondsValue}s" else if (hourValue == 0 && minutesValue == 0) "0s" else ""
private fun getReadableMinutes(minutesValue: Int) = if (minutesValue > 0) "${minutesValue}min " else ""
private fun getReadableHours(hourValue: Int) = if (hourValue > 0) "${hourValue}h " else ""
}
| mit | 834434a6363b00816282f1bd86233dbc | 37.457831 | 190 | 0.705514 | 5.018868 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/psi/element/MdJekyllFrontMatterBlockStubElementType.kt | 1 | 1427 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.tree.IElementType
import com.vladsch.md.nav.psi.util.BasicTextMapElementTypeProvider
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.md.nav.psi.util.TextMapElementType
import com.vladsch.md.nav.psi.util.TextMapMatch
class MdJekyllFrontMatterBlockStubElementType(debugName: String) : MdPlainTextStubElementType<MdJekyllFrontMatterBlock, MdJekyllFrontMatterBlockStub>(debugName) {
override fun createPsi(stub: MdJekyllFrontMatterBlockStub) = MdJekyllFrontMatterBlockImpl(stub, this)
override fun getExternalId(): String = "markdown.plain-text-referenceable.jekyll-front-matter"
override fun createStub(parentStub: StubElement<PsiElement>, textMapType: TextMapElementType, textMapMatches: Array<TextMapMatch>, referenceableOffsetInParent: Int): MdJekyllFrontMatterBlockStub = MdJekyllFrontMatterBlockStubImpl(parentStub, textMapType, textMapMatches, referenceableOffsetInParent)
override fun getReferenceableTextType(): IElementType = MdTypes.JEKYLL_FRONT_MATTER_BLOCK
override fun getTextMapType(): TextMapElementType = BasicTextMapElementTypeProvider.JEKYLL_FRONT_MATTER
}
| apache-2.0 | 18d5be19ddbc81b65ebb786ce44869be | 74.105263 | 303 | 0.837421 | 4.417957 | false | true | false | false |
devunt/ika | app/src/main/kotlin/org/ozinger/ika/serialization/serializer/ChannelMemberDeclarationSerializer.kt | 1 | 2029 | package org.ozinger.ika.serialization.serializer
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.encoding.encodeStructure
import org.ozinger.ika.definition.MemberMode
import org.ozinger.ika.definition.ModeChangelist
import org.ozinger.ika.serialization.ModeStringDescriptor
import org.ozinger.ika.state.ModeDefinitions
object ChannelMemberDeclarationSerializer : KSerializer<ModeChangelist<MemberMode>> {
override val descriptor = ModeStringDescriptor("ChannelMemberDeclaration", trailing = true)
override fun serialize(encoder: Encoder, value: ModeChangelist<MemberMode>) = encoder.encodeStructure(descriptor) {
val memberModes = mutableMapOf<String, MutableSet<Char>>()
value.adding.forEach { mode ->
val set = memberModes.getOrPut(mode.target.value, ::mutableSetOf)
mode.mode?.let { set.add(it) }
}
val memberString = memberModes.map { (uuid, modes) ->
StringBuilder().apply {
modes.map(::append)
append(",")
append(uuid)
}.toString()
}.joinToString(" ")
encodeStringElement(descriptor, 0, memberString)
}
override fun deserialize(decoder: Decoder): ModeChangelist<MemberMode> {
val adding = mutableSetOf<MemberMode>()
val members = decoder.decodeString().split(" ")
for (member in members) {
val (modes, uuid) = member.split(",")
for (mode in modes) {
if (mode !in ModeDefinitions.member.parameterized) {
throw SerializationException("Invalid member mode: $mode")
}
adding.add(MemberMode(uuid, mode))
}
if (modes.isEmpty()) {
adding.add(MemberMode(uuid))
}
}
return ModeChangelist(adding = adding)
}
}
| agpl-3.0 | 769b3510a5b076fe16f36319bc96702a | 36.574074 | 119 | 0.656481 | 5.022277 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/actions/styling/HeaderLevelUpAction.kt | 1 | 3882 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.actions.styling
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiElement
import com.vladsch.flexmark.util.sequence.RepeatedSequence
import com.vladsch.md.nav.actions.handlers.util.PsiEditAdjustment
import com.vladsch.md.nav.psi.element.MdHeaderElement
import com.vladsch.md.nav.psi.element.MdParagraph
import com.vladsch.md.nav.psi.element.MdSetextHeader
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.plugin.util.rangeLimit
class HeaderLevelUpAction : HeaderAction() {
override fun canPerformAction(element: PsiElement): Boolean {
return element is MdHeaderElement && element.headerLevel < 6 || element is MdParagraph
}
override fun cannotPerformActionReason(element: PsiElement): String {
return if (element is MdHeaderElement && element.canIncreaseLevel) "Cannot increase level heading beyond 6" else "Not Heading or Text element"
}
override fun headerAction(element: PsiElement, document: Document, caretOffset: Int, editContext: PsiEditAdjustment): Int? {
if (element is MdHeaderElement) {
if (element.canIncreaseLevel) {
if (element is MdSetextHeader && element.headerLevel == 1) {
val markerElement = element.headerMarkerNode ?: return null
document.replaceString(markerElement.startOffset, markerElement.startOffset + markerElement.textLength, RepeatedSequence.repeatOf('-', element.headerText.length))
} else {
element.setHeaderLevel(element.headerLevel + 1, editContext)
}
} else if (element.headerLevel < 6) {
// change to ATX and increase level
val offset = (caretOffset - element.headerTextElement!!.node.startOffset).rangeLimit(0, element.headerTextElement!!.node.textLength)
return MdPsiImplUtil.changeHeaderType(element, element.headerLevel + 1, document, offset, editContext)
}
} else if (element is MdParagraph) {
// add # before start of line without prefixes
val startLine = document.getLineNumber(element.node.startOffset)
val caretLine = document.getLineNumber(caretOffset) - startLine
val lines = MdPsiImplUtil.linesForWrapping(element, false, false, false, editContext)
// disabled because it is not undoable by heading down
//if (false && MdCodeStyleSettings.getInstance(element.project).HEADING_PREFERENCE_TYPE().isSetextPreferred) {
// val offset = lines[caretLine].trackedSourceLocation(0).offset + lines[caretLine].trimEnd().length
// document.insertString(offset, "\n" + prefixes.childPrefix + RepeatedSequence.of('=', unPrefixedLines[caretLine].trimEnd().length))
//
// if (caretLine > 0) {
// // insert blank line or all preceding lines will be treated as part of heading
// val startOffset = unPrefixedLines[caretLine].trackedSourceLocation(0).offset
// document.insertString(startOffset, prefixes.childPrefix + "\n")
// }
//} else {
// diagnostics/2556, index out of bounds
val offset = if (caretLine >= lines.lineCount) document.textLength else lines[caretLine].text.startOffset
return if (offset > 0 && document.charsSequence[offset - 1] != '\n') {
document.insertString(offset, "\n# ")
offset + 3
} else {
document.insertString(offset, "# ")
offset + 2
}
//}
}
return null
}
}
| apache-2.0 | 41ae92e72bbe4fbacc16e1bb3ec4178e | 55.26087 | 182 | 0.660227 | 4.870765 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | lib_ui/src/main/java/no/nordicsemi/android/ui/view/KeyValueField.kt | 1 | 2259 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.ui.view
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun KeyValueField(key: String, value: String) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(text = key)
Text(
color = MaterialTheme.colorScheme.onBackground,
text = value
)
}
}
| bsd-3-clause | 92894ba5fc0d384d1f13ea51d8da45cb | 40.833333 | 89 | 0.761842 | 4.735849 | false | false | false | false |
JimSeker/ui | RecyclerViews/RecyclerViewDemo3_kt/app/src/main/java/edu/cs4730/recyclerviewdemo3_kt/Simple1_Fragment.kt | 1 | 1608 | package edu.cs4730.recyclerviewdemo3_kt
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.DefaultItemAnimator
/**
* A "simple" version of the recyclerview with layout.
* There is no simple layout or adapter, so both have to be created.
* Everything is labeled, simple1_ that goes with this one.
*/
class Simple1_Fragment : Fragment() {
lateinit var mRecyclerView: RecyclerView
lateinit var mAdapter: Simple1_myAdapter
var values = arrayOf(
"Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2"
)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val myView = inflater.inflate(R.layout.simple1_fragment, container, false)
//setup the RecyclerView
mRecyclerView = myView.findViewById(R.id.list)
mRecyclerView.layoutManager = LinearLayoutManager(requireContext())
mRecyclerView.itemAnimator = DefaultItemAnimator()
//setup the adapter, which is myAdapter, see the code.
mAdapter = Simple1_myAdapter(values, R.layout.simple1_rowlayout, requireContext())
//add the adapter to the recyclerview
mRecyclerView.adapter = mAdapter
return myView
}
} | apache-2.0 | 9726a6e03210b6846e3cc69f26466356 | 36.418605 | 90 | 0.718284 | 4.647399 | false | false | false | false |
http4k/http4k | http4k-contract/src/test/kotlin/org/http4k/contract/openapi/v3/FieldRetrievalTest.kt | 1 | 900 | package org.http4k.contract.openapi.v3
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import org.junit.jupiter.api.Test
class FieldRetrievalTest {
private val blowUp = FieldRetrieval { p1, p2 -> throw NoFieldFound(p2, p1) }
private val result = Field("hello", true, FieldMetadata.empty)
private val findIt = FieldRetrieval { _, _ -> result }
data class Beany(val nonNullable: String = "hello", val aNullable: String? = "aNullable")
@Test
fun `bombs if can't find field anywhere`() {
assertThat({ FieldRetrieval.compose(blowUp, blowUp)(Beany(), "foo") }, throws<NoFieldFound>())
}
@Test
fun `field retrieval falls back if none found`() {
assertThat(FieldRetrieval.compose(blowUp, findIt)(Beany(), "foo"), equalTo(Field("hello", true, FieldMetadata.empty)))
}
}
| apache-2.0 | 5cf1cf3b93e82bf25f9739ed8f7e8924 | 32.333333 | 126 | 0.701111 | 3.73444 | false | true | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/audio/EffectsController.kt | 1 | 1170 | package com.binarymonks.jj.core.audio
import com.badlogic.gdx.utils.ObjectMap
import com.binarymonks.jj.core.JJ
class EffectsController {
private var singletonMap = ObjectMap<String, SingletonWindow>()
var volume = 0.2f
var isMute = false
fun addSingletonSound(singletonTimeWindow: Float, vararg soundpaths: String) {
val window = SingletonWindow(singletonTimeWindow)
for (soundpath in soundpaths) {
singletonMap.put(soundpath, window)
}
}
fun canTriggerSingleton(soundpath: String): Boolean {
if (!singletonMap.containsKey(soundpath)) {
return true
}
return singletonMap.get(soundpath).elapsed()
}
private inner class SingletonWindow(window: Float) {
var window: Double = 0.toDouble()
var lastTrigger = 0.0
init {
this.window = window.toDouble()
}
fun elapsed(): Boolean {
val currentT = JJ.B.clock.time
val elapsed = currentT - lastTrigger > window
if (elapsed) {
lastTrigger = currentT
}
return elapsed
}
}
}
| apache-2.0 | b410bf4e738659ade89fd131203a3cf7 | 22.877551 | 82 | 0.605983 | 4.642857 | false | false | false | false |
bastienvalentin/myeurocollector | app/src/main/java/fr/vbastien/mycoincollector/db/Coin.kt | 1 | 778 | package fr.vbastien.mycoincollector.db
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.ForeignKey
import android.arch.persistence.room.PrimaryKey
/**
* Created by vbastien on 03/07/2017.
*/
@Entity(tableName = "coin",
foreignKeys = arrayOf(ForeignKey(entity = Country::class,
parentColumns = arrayOf("country_id"),
childColumns = arrayOf("coin_id"),
onDelete = ForeignKey.CASCADE)))
data class Coin (
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "coin_id")
var coinId : Int = 0,
@ColumnInfo(name = "country_id")
var countryId : Int = 0,
var value: Double = 0.0,
var img: String? = null,
var description: String? = null
) | apache-2.0 | 5f168b0716186929c0db58be0e103391 | 27.851852 | 65 | 0.688946 | 3.832512 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/preferences/HtmlHelpPreference.kt | 1 | 2609 | /*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.preferences
import android.content.Context
import android.text.method.LinkMovementMethod
import android.util.AttributeSet
import android.widget.TextView
import androidx.core.text.parseAsHtml
import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
import com.ichi2.anki.R
/**
* Non-clickable preference that shows help text.
*
* The summary is parsed as a format string containing HTML,
* and may contain up to three format specifiers as understood by `Sting.format()`,
* arguments for which can be specified using XML attributes such as `app:substitution1`.
*
* <com.ichi2.preferences.HtmlHelpPreference
* android:summary="@string/format_string"
* app:substitution1="@string/substitution1"
* />
*
* The summary HTML can contain all tags that TextViews can display,
* including new lines and links. Raw HTML can be entered using the CDATA tag, e.g.
*
* <string name="format_string"><![CDATA[<b>Hello, %s</b>]]></string>
*/
class HtmlHelpPreference(context: Context, attrs: AttributeSet?) : Preference(context, attrs) {
init {
isSelectable = false
isPersistent = false
}
private val substitutions = context.usingStyledAttributes(attrs, R.styleable.HtmlHelpPreference) {
arrayOf(
getString(R.styleable.HtmlHelpPreference_substitution1),
getString(R.styleable.HtmlHelpPreference_substitution2),
getString(R.styleable.HtmlHelpPreference_substitution3),
)
}
override fun getSummary() = super.getSummary()
.toString()
.format(*substitutions)
.parseAsHtml()
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val summary = holder.findViewById(android.R.id.summary) as TextView
summary.movementMethod = LinkMovementMethod.getInstance()
summary.maxHeight = Int.MAX_VALUE
}
}
| gpl-3.0 | 102bba6f7424a29879d07b2af94001bf | 37.367647 | 102 | 0.723649 | 4.475129 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/view/custom/DappHeaderView.kt | 1 | 3441 | /*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.view.custom
import android.content.Context
import android.graphics.PorterDuff
import android.support.design.widget.AppBarLayout
import android.util.AttributeSet
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import com.toshi.R
import com.toshi.extensions.getColorById
import kotlinx.android.synthetic.main.view_dapp_header.view.closeButton
import kotlinx.android.synthetic.main.view_dapp_header.view.collapsingToolbar
import kotlinx.android.synthetic.main.view_dapp_header.view.headerImage
import kotlinx.android.synthetic.main.view_dapp_header.view.headerImageWrapper
import kotlinx.android.synthetic.main.view_dapp_header.view.toolbar
class DappHeaderView : AppBarLayout {
private var prevOffset = -1
var offsetChangedListener: ((Float) -> Unit)? = null
constructor(context: Context): super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet?): super(context, attrs) {
init()
}
private fun init() {
inflate(context, R.layout.view_dapp_header, this)
initListeners()
}
private fun initListeners() {
addOnOffsetChangedListener { appBarLayout, verticalOffset ->
handleOffsetChanged(appBarLayout, verticalOffset)
}
}
private fun handleOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
if (prevOffset == verticalOffset) return
prevOffset = verticalOffset
val absVerticalOffset = Math.abs(verticalOffset).toFloat()
val scrollRange = appBarLayout.totalScrollRange.toFloat()
val percentage = 1f - (absVerticalOffset / scrollRange)
setHeaderImageAlpha(percentage)
offsetChangedListener?.invoke(percentage)
}
private fun setHeaderImageAlpha(percentage: Float) {
headerImageWrapper.alpha = percentage
headerImage.alpha = percentage
}
fun enableCollapsing() {
setExpanded(true)
setDarkToolbar()
}
fun disableCollapsing() {
setExpanded(false)
setLightToolbar()
val lp = collapsingToolbar.layoutParams as AppBarLayout.LayoutParams
lp.height = WRAP_CONTENT
}
private fun setLightToolbar() {
collapsingToolbar.setBackgroundColor(getColorById(R.color.windowBackground))
toolbar.setBackgroundColor(getColorById(R.color.windowBackground))
toolbar.closeButton.setColorFilter(getColorById(R.color.textColorSecondary), PorterDuff.Mode.SRC_IN)
}
private fun setDarkToolbar() {
collapsingToolbar.setBackgroundColor(getColorById(R.color.colorPrimary))
toolbar.closeButton.setColorFilter(getColorById(R.color.textColorContrast), PorterDuff.Mode.SRC_IN)
}
} | gpl-3.0 | 8be4095846839f4103b7ca56804af312 | 35.617021 | 108 | 0.723627 | 4.618792 | false | false | false | false |
tfcbandgeek/SmartReminders-android | app/src/main/java/jgappsandgames/smartreminderslite/home/HomeActivity.kt | 1 | 6726 | package jgappsandgames.smartreminderslite.home
// Android OS
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
// Views
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
// Anko
import org.jetbrains.anko.alert
import org.jetbrains.anko.button
import org.jetbrains.anko.customView
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.verticalLayout
import org.jetbrains.anko.wrapContent
import org.jetbrains.anko.sdk25.coroutines.onClick
// App
import jgappsandgames.smartreminderslite.R
import jgappsandgames.smartreminderslite.adapter.TaskAdapter
import jgappsandgames.smartreminderslite.utility.*
// KotlinX
import kotlinx.android.synthetic.main.activity_home.*
// Save Library
import jgappsandgames.smartreminderssave.MasterManager
import jgappsandgames.smartreminderssave.tasks.Task
import jgappsandgames.smartreminderssave.tasks.TaskManager
/**
* HomeActivity
* Created by joshua on 12/13/2017.
*/
class HomeActivity: AppCompatActivity(), TaskAdapter.OnTaskChangedListener {
// LifeCycle Methods ---------------------------------------------------------------------------
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
setTitle(R.string.app_name)
// Handle the Data
loadClass(this)
// Set Click Listeners
home_add_task.setOnClickListener {
home_fab.close(true)
startActivity(buildTaskIntent(this, IntentOptions(), TaskOptions(task = TaskManager.addTask(TaskManager.taskPool.getPoolObject().load("home", Task.TYPE_TASK).save(), true))))
}
home_add_folder.setOnClickListener {
home_fab.close(true)
startActivity(buildTaskIntent(this, IntentOptions(), TaskOptions(task = TaskManager.addTask(TaskManager.taskPool.getPoolObject().load("home", Task.TYPE_FOLDER).save(), true))))
}
home_add_note.setOnClickListener {
home_fab.close(true)
startActivity(buildTaskIntent(this, IntentOptions(), TaskOptions(task = TaskManager.addTask(TaskManager.taskPool.getPoolObject().load("home", Task.TYPE_NOTE).save(), true))))
}
home_bottom_bar_search.setOnClickListener {
if (home_bottom_bar_search_text.visibility == View.VISIBLE) searchVisibility(false)
else searchVisibility(true)
}
home_bottom_bar_more.setOnClickListener {
alert {
title = [email protected](R.string.sort_options)
customView {
verticalLayout {
button {
text = context.getString(R.string.sort_by_tags)
onClick { startActivity(buildTagsIntent(this@HomeActivity, IntentOptions())) }
}.lparams(matchParent, wrapContent)
button {
text = context.getString(R.string.sort_by_status)
onClick { startActivity(buildStatusIntent(this@HomeActivity, IntentOptions())) }
}.lparams(matchParent, wrapContent)
button {
text = context.getString(R.string.sort_by_priority)
onClick { startActivity(buildPriorityIntent(this@HomeActivity, IntentOptions())) }
}.lparams(matchParent, wrapContent)
button {
text = context.getString(R.string.sort_by_days)
onClick { startActivity(buildDayIntent(this@HomeActivity, IntentOptions())) }
}.lparams(matchParent, wrapContent)
button {
text = context.getString(R.string.sort_by_week)
onClick { startActivity(buildWeekIntent(this@HomeActivity, IntentOptions())) }
}.lparams(matchParent, wrapContent)
button {
text = context.getString(R.string.sort_by_month)
onClick { startActivity(buildMonthIntent(this@HomeActivity, IntentOptions())) }
}.lparams(matchParent, wrapContent)
}.layoutParams = ViewGroup.LayoutParams(matchParent, matchParent)
}
}.show()
}
home_bottom_bar_search_text.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
if (home_bottom_bar_search_text.visibility == View.VISIBLE) home_tasks_list.adapter =
TaskAdapter(this@HomeActivity, this@HomeActivity, TaskManager.getHome(), home_bottom_bar_search_text.text.toString())
}
})
}
override fun onResume() {
super.onResume()
home_tasks_list.adapter = TaskAdapter(this, this, TaskManager.getHome(), "")
}
override fun onPause() {
super.onPause()
save()
}
// Menu Methods --------------------------------------------------------------------------------
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_home, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean = onOptionsItemSelected(this, item!!, object: Save { override fun save() = [email protected]() })
// Task Listener -------------------------------------------------------------------------------
override fun onTaskChanged() = onResume()
// Auxiliary Methods ---------------------------------------------------------------------------
fun save() = MasterManager.save()
// Search Methods ------------------------------------------------------------------------------
private fun searchVisibility(visible: Boolean = true) {
if (visible) {
home_bottom_bar_search_text.visibility = View.VISIBLE
home_bottom_bar_search_text.setText("")
home_tasks_list.adapter = TaskAdapter(this, this, TaskManager.getHome(), "")
} else {
home_bottom_bar_search_text.visibility = View.INVISIBLE
home_bottom_bar_search_text.setText("")
home_tasks_list.adapter = TaskAdapter(this, this, TaskManager.getHome(), "")
}
}
} | apache-2.0 | 4d490f3b09660cfc24d5eb12f5b8171f | 41.575949 | 188 | 0.593072 | 5.238318 | false | false | false | false |
sealedtx/coursework-db-kotlin | app/src/main/java/coursework/kiulian/com/freerealestate/view/dialogs/ImagePickDialog.kt | 1 | 1207 | package coursework.kiulian.com.freerealestate.view.dialogs
import android.app.Activity
import android.support.v7.app.AlertDialog
import android.content.pm.PackageManager
import android.support.annotation.NonNull
import coursework.kiulian.com.freerealestate.R
import android.content.Intent
/**
* Created by User on 30.03.2017.
*/
class ImagePickDialog(activity: Activity) {
interface OnAvatarPickListener {
fun onMethodSelected(requestCode: Int)
}
private val items = arrayOf("Take Photo", "Choose from Library")
private val onAvatarPickListener: OnAvatarPickListener
init {
onAvatarPickListener = activity as OnAvatarPickListener
val builder = AlertDialog.Builder(activity)
builder.setTitle("Add Photo")
builder.setItems(items, { dialog, item ->
if (items[item] == "Take Photo") {
onAvatarPickListener.onMethodSelected(TAKE_PHOTO)
} else if (items[item] == "Choose from Library") {
onAvatarPickListener.onMethodSelected(PICK_IMAGE)
}
})
builder.show()
}
companion object {
val TAKE_PHOTO = 1023
val PICK_IMAGE = 2340
}
}
| bsd-2-clause | fb282ad64ba03c2bdf5bf9318c50d388 | 25.23913 | 68 | 0.674399 | 4.520599 | false | false | false | false |
strykeforce/thirdcoast | src/main/kotlin/org/strykeforce/trapper/Trace.kt | 1 | 1246 | package org.strykeforce.trapper
import com.squareup.moshi.JsonClass
import com.squareup.moshi.JsonWriter
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okio.Buffer
import okio.BufferedSource
private val traceJsonAdapter = TraceJsonAdapter(moshi)
@JsonClass(generateAdapter = true)
data class Trace(val time: Int) : Postable {
var id: Int? = null
var action: Int? = null
var data: List<Double> = mutableListOf()
override fun endpoint(baseUrl: String) = "$baseUrl/traces/".toHttpUrl()
override fun asRequestBody(): RequestBody {
val buffer = Buffer()
traceJsonAdapter.toJson(buffer, this)
return buffer.readUtf8().toRequestBody(MEDIA_TYPE_JSON)
}
@Suppress("UNCHECKED_CAST")
override fun <T : Postable> fromJson(source: BufferedSource): T =
traceJsonAdapter.fromJson(source)!! as T
}
internal fun requestBodyFromList(traces: List<Trace>): RequestBody {
val buffer = Buffer()
val writer: JsonWriter = JsonWriter.of(buffer)
writer.beginArray()
traces.forEach { traceJsonAdapter.toJson(writer, it) }
writer.endArray()
return buffer.readUtf8().toRequestBody(MEDIA_TYPE_JSON)
} | mit | 684bf2888cf422d618df61836c819882 | 30.974359 | 75 | 0.735152 | 4.238095 | false | false | false | false |
android/topeka | base/src/main/java/com/google/samples/apps/topeka/persistence/TopekaDatabaseHelper.kt | 1 | 17068 | /*
* Copyright 2017 Google 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.google.samples.apps.topeka.persistence
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.content.res.Resources
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.google.samples.apps.topeka.base.R
import com.google.samples.apps.topeka.helper.toIntArray
import com.google.samples.apps.topeka.helper.toStringArray
import com.google.samples.apps.topeka.model.Category
import com.google.samples.apps.topeka.model.JsonAttributes
import com.google.samples.apps.topeka.model.Theme
import com.google.samples.apps.topeka.model.quiz.AlphaPickerQuiz
import com.google.samples.apps.topeka.model.quiz.FillBlankQuiz
import com.google.samples.apps.topeka.model.quiz.FillTwoBlanksQuiz
import com.google.samples.apps.topeka.model.quiz.FourQuarterQuiz
import com.google.samples.apps.topeka.model.quiz.MultiSelectQuiz
import com.google.samples.apps.topeka.model.quiz.OptionsQuiz
import com.google.samples.apps.topeka.model.quiz.PickerQuiz
import com.google.samples.apps.topeka.model.quiz.Quiz
import com.google.samples.apps.topeka.model.quiz.QuizType
import com.google.samples.apps.topeka.model.quiz.SelectItemQuiz
import com.google.samples.apps.topeka.model.quiz.ToggleTranslateQuiz
import com.google.samples.apps.topeka.model.quiz.TrueFalseQuiz
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.Arrays
import kotlin.collections.ArrayList
/**
* Database for storing and retrieving info for categories and quizzes.
*/
class TopekaDatabaseHelper private constructor(
context: Context
) : SQLiteOpenHelper(context.applicationContext, "topeka.db", null, 1) {
private val resources: Resources = context.resources
private var categories: MutableList<Category> = loadCategories()
override fun onCreate(db: SQLiteDatabase) {
with(db) {
execSQL(CategoryTable.CREATE)
execSQL(QuizTable.CREATE)
fillCategoriesAndQuizzes(db)
}
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) = Unit
@Throws(JSONException::class, IOException::class)
private fun fillCategoriesAndQuizzes(db: SQLiteDatabase) {
db.transact {
val values = ContentValues() // reduce, reuse
val jsonArray = JSONArray(readCategoriesFromResources())
for (i in 0 until jsonArray.length()) {
with(jsonArray.getJSONObject(i)) {
val id = getString(JsonAttributes.ID)
fillCategory(db, values, this, id)
fillQuizzesForCategory(db, values, getJSONArray(JsonAttributes.QUIZZES), id)
}
}
}
}
private fun readCategoriesFromResources(): String {
val rawCategories = resources.openRawResource(R.raw.categories)
val reader = BufferedReader(InputStreamReader(rawCategories))
return reader.readText()
}
private fun fillCategory(db: SQLiteDatabase,
values: ContentValues,
category: JSONObject,
categoryId: String) {
with(values) {
clear()
put(CategoryTable.COLUMN_ID, categoryId)
put(CategoryTable.COLUMN_NAME, category.getString(JsonAttributes.NAME))
put(CategoryTable.COLUMN_THEME, category.getString(JsonAttributes.THEME))
put(CategoryTable.COLUMN_SOLVED, category.getString(JsonAttributes.SOLVED))
put(CategoryTable.COLUMN_SCORES, category.getString(JsonAttributes.SCORES))
}
db.insert(CategoryTable.NAME, null, values)
}
private fun fillQuizzesForCategory(db: SQLiteDatabase,
values: ContentValues,
quizzes: JSONArray,
categoryId: String) {
var quiz: JSONObject
for (i in 0 until quizzes.length()) {
quiz = quizzes.getJSONObject(i)
with(values) {
clear()
put(QuizTable.FK_CATEGORY, categoryId)
put(QuizTable.COLUMN_TYPE, quiz.getString(JsonAttributes.TYPE))
put(QuizTable.COLUMN_QUESTION, quiz.getString(JsonAttributes.QUESTION))
put(QuizTable.COLUMN_ANSWER, quiz.getString(JsonAttributes.ANSWER))
}
putNonEmptyString(values, quiz, JsonAttributes.OPTIONS, QuizTable.COLUMN_OPTIONS)
putNonEmptyString(values, quiz, JsonAttributes.MIN, QuizTable.COLUMN_MIN)
putNonEmptyString(values, quiz, JsonAttributes.MAX, QuizTable.COLUMN_MAX)
putNonEmptyString(values, quiz, JsonAttributes.START, QuizTable.COLUMN_START)
putNonEmptyString(values, quiz, JsonAttributes.END, QuizTable.COLUMN_END)
putNonEmptyString(values, quiz, JsonAttributes.STEP, QuizTable.COLUMN_STEP)
db.insert(QuizTable.NAME, null, values)
}
}
/**
* Puts a non-empty string to ContentValues provided.
* @param values The place where the data should be put.
*
* @param quiz The quiz potentially containing the data.
*
* @param jsonKey The key to look for.
*
* @param contentKey The key use for placing the data in the database.
*/
private fun putNonEmptyString(values: ContentValues,
quiz: JSONObject,
jsonKey: String,
contentKey: String) {
quiz.optString(jsonKey, null)?.let { values.put(contentKey, it) }
}
/**
* Gets all categories with their quizzes.
* @param fromDatabase `true` if a data refresh is needed, else `false`.
*
* @return All categories stored in the database.
*/
fun getCategories(fromDatabase: Boolean = false): List<Category> {
if (fromDatabase) {
categories.clear()
categories.addAll(loadCategories())
}
return categories
}
private fun loadCategories(): MutableList<Category> {
val data = getCategoryCursor()
val tmpCategories = ArrayList<Category>(data.count)
do {
tmpCategories.add(getCategory(data))
} while (data.moveToNext())
return tmpCategories
}
/**
* Gets all categories wrapped in a [Cursor] positioned at it's first element.
*
* There are **no quizzes** within the categories obtained from this cursor.
*
* @return All categories stored in the database.
*/
@SuppressLint("Recycle")
private fun getCategoryCursor(): Cursor {
synchronized(readableDatabase) {
return readableDatabase
.query(CategoryTable.NAME, CategoryTable.PROJECTION,
null, null, null, null, null)
.also {
it.moveToFirst()
}
}
}
/**
* Gets a category from the given position of the cursor provided.
* @param cursor The Cursor containing the data.
*
* @return The found category.
*/
private fun getCategory(cursor: Cursor): Category {
// "magic numbers" based on CategoryTable#PROJECTION
with(cursor) {
val id = getString(0)
val category = Category(
id = id,
name = getString(1),
theme = Theme.valueOf(getString(2)),
quizzes = getQuizzes(id, readableDatabase),
scores = JSONArray(getString(4)).toIntArray(),
solved = getBooleanFromDatabase(getString(3)))
return category
}
}
private fun getBooleanFromDatabase(isSolved: String?) =
// Json stores booleans as true/false strings, whereas SQLite stores them as 0/1 values.
isSolved?.length == 1 && Integer.valueOf(isSolved) == 1
/**
* Looks for a category with a given id.
* @param categoryId Id of the category to look for.
*
* @return The found category.
*/
fun getCategoryWith(categoryId: String): Category {
val selectionArgs = arrayOf(categoryId)
val data = readableDatabase
.query(CategoryTable.NAME, CategoryTable.PROJECTION,
"${CategoryTable.COLUMN_ID}=?", selectionArgs,
null, null, null)
.also { it.moveToFirst() }
return getCategory(data)
}
/**
* Scooooooooooore!
* @return The score over all Categories.
*/
fun getScore() = with(getCategories()) { sumBy { it.score } }
/**
* Updates values for a category.
* @param category The category to update.
*/
fun updateCategory(category: Category) {
val index = categories.indexOfFirst { it.id == category.id }
if (index != -1) {
with (categories) {
removeAt(index)
add(index, category)
}
}
val categoryValues = createContentValuesFor(category)
writableDatabase.update(CategoryTable.NAME,
categoryValues,
"${CategoryTable.COLUMN_ID}=?",
arrayOf(category.id))
val quizzes = category.quizzes
updateQuizzes(writableDatabase, quizzes)
}
/**
* Updates a list of given quizzes.
* @param writableDatabase The database to write the quizzes to.
*
* @param quizzes The quizzes to write.
*/
private fun updateQuizzes(writableDatabase: SQLiteDatabase, quizzes: List<Quiz<*>>) {
var quiz: Quiz<*>
val quizValues = ContentValues()
val quizArgs = arrayOfNulls<String>(1)
for (i in quizzes.indices) {
quiz = quizzes[i]
quizValues.clear()
quizValues.put(QuizTable.COLUMN_SOLVED, quiz.solved)
quizArgs[0] = quiz.question
writableDatabase.update(QuizTable.NAME, quizValues,
"${QuizTable.COLUMN_QUESTION}=?", quizArgs)
}
}
/**
* Resets the contents of Topeka's database to it's initial state.
*/
fun reset() {
with(writableDatabase) {
delete(CategoryTable.NAME, null, null)
delete(QuizTable.NAME, null, null)
fillCategoriesAndQuizzes(this)
}
}
/**
* Creates objects for quizzes according to a category id.
* @param categoryId The category to create quizzes for.
* @param database The database containing the quizzes.
* @return The found quizzes or an empty list if none were available.
*/
@SuppressLint("Recycle")
private fun getQuizzes(categoryId: String, database: SQLiteDatabase): List<Quiz<*>> {
val quizzes = ArrayList<Quiz<*>>()
val cursor = database.query(QuizTable.NAME,
QuizTable.PROJECTION,
"${QuizTable.FK_CATEGORY} LIKE ?", arrayOf(categoryId),
null, null, null)
cursor.moveToFirst()
do quizzes.add(createQuizDueToType(cursor)) while (cursor.moveToNext())
return quizzes
}
/**
* Creates a quiz corresponding to the projection provided from a cursor row.
* Currently only [QuizTable.PROJECTION] is supported.
* @param cursor The Cursor containing the data.
* @return The created quiz.
*/
private fun createQuizDueToType(cursor: Cursor): Quiz<*> {
// "magic numbers" based on QuizTable#PROJECTION
val type = cursor.getString(2)
val question = cursor.getString(3)
val answer = cursor.getString(4)
val options = cursor.getString(5)
val min = cursor.getInt(6)
val max = cursor.getInt(7)
val step = cursor.getInt(8)
val solved = getBooleanFromDatabase(cursor.getString(11))
return when (type) {
QuizType.ALPHA_PICKER.jsonName ->
AlphaPickerQuiz(question, answer, solved)
QuizType.FILL_BLANK.jsonName ->
createFillBlankQuiz(cursor, question, answer, solved)
QuizType.FILL_TWO_BLANKS.jsonName ->
createFillTwoBlanksQuiz(question, answer, solved)
QuizType.FOUR_QUARTER.jsonName ->
createStringOptionsQuiz(question, answer, options, solved) {
q, a, o, s ->
FourQuarterQuiz(q, a, o, s)
}
QuizType.MULTI_SELECT.jsonName ->
createStringOptionsQuiz(question, answer, options, solved) {
q, a, o, s ->
MultiSelectQuiz(q, a, o, s)
}
QuizType.PICKER.jsonName ->
PickerQuiz(question, Integer.valueOf(answer)!!, min, max, step, solved)
QuizType.SINGLE_SELECT.jsonName, QuizType.SINGLE_SELECT_ITEM.jsonName ->
createStringOptionsQuiz(question, answer, options, solved) {
q, a, o, s ->
SelectItemQuiz(q, a, o, s)
}
QuizType.TOGGLE_TRANSLATE.jsonName ->
createToggleTranslateQuiz(question, answer, options, solved)
QuizType.TRUE_FALSE.jsonName -> TrueFalseQuiz(question, "true" == answer, solved)
else -> throw IllegalArgumentException("Quiz type $type is not supported")
}
}
private fun createFillBlankQuiz(cursor: Cursor,
question: String,
answer: String,
solved: Boolean): Quiz<*> {
val start = cursor.getString(9)
val end = cursor.getString(10)
return FillBlankQuiz(question, answer, start, end, solved)
}
private fun createFillTwoBlanksQuiz(question: String,
answer: String,
solved: Boolean): FillTwoBlanksQuiz {
val answerArray = JSONArray(answer).toStringArray()
return FillTwoBlanksQuiz(question, answerArray, solved)
}
private inline fun <T : OptionsQuiz<String>> createStringOptionsQuiz(
question: String,
answer: String,
options: String,
solved: Boolean,
quizFactory: (String, IntArray, Array<String>, Boolean) -> T): T {
val answerArray = JSONArray(answer).toIntArray()
val optionsArray = JSONArray(options).toStringArray()
return quizFactory(question, answerArray, optionsArray, solved)
}
private fun createToggleTranslateQuiz(question: String,
answer: String,
options: String,
solved: Boolean): Quiz<*> {
val answerArray = JSONArray(answer).toIntArray()
val optionsArrays = extractOptionsArrays(options)
return ToggleTranslateQuiz(question, answerArray, optionsArrays, solved)
}
private fun extractOptionsArrays(options: String): Array<Array<String>> {
val optionsLvlOne = JSONArray(options).toStringArray()
return Array(optionsLvlOne.size) { JSONArray(optionsLvlOne[it]).toStringArray() }
}
/**
* Creates the content values to update a category in the database.
* @param category The category to update.
*
* @return ContentValues containing updatable data.
*/
private fun createContentValuesFor(category: Category) = ContentValues().apply {
put(CategoryTable.COLUMN_SOLVED, category.solved)
put(CategoryTable.COLUMN_SCORES, Arrays.toString(category.scores))
}
companion object {
private var _instance: TopekaDatabaseHelper? = null
fun getInstance(context: Context): TopekaDatabaseHelper {
return _instance ?: synchronized(TopekaDatabaseHelper::class) {
TopekaDatabaseHelper(context).also { _instance = it }
}
}
}
}
inline fun SQLiteDatabase.transact(transaction: SQLiteDatabase.() -> Unit) {
try {
beginTransaction()
transaction()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
| apache-2.0 | 3fc3ee9fc8671a145969357e3d2c73f2 | 37.441441 | 100 | 0.617881 | 4.927252 | false | false | false | false |
sephiroth74/AndroidUIGestureRecognizer | uigesturerecognizer/src/main/java/it/sephiroth/android/library/uigestures/UISwipeGestureRecognizer.kt | 1 | 16709 | package it.sephiroth.android.library.uigestures
import android.content.Context
import android.graphics.PointF
import android.os.Message
import android.util.Log
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.ViewConfiguration
/**
* UISwipeGestureRecognizer is a subclass of UIGestureRecognizer that looks for swiping gestures in one or more
* directions. A swipe is a discrete gesture, and thus the associated action message is sent only once per gesture.
*
* @author alessandro crugnola
* @see [
* https://developer.apple.com/reference/uikit/uiswipegesturerecognizer](https://developer.apple.com/reference/uikit/uiswipegesturerecognizer)
*/
@Suppress("MemberVisibilityCanBePrivate", "unused")
open class UISwipeGestureRecognizer(context: Context) : UIGestureRecognizer(context), UIDiscreteGestureRecognizer {
/**
* Minimum fling velocity before the touch can be accepted
* @since 1.0.0
*/
var scaledMinimumFlingVelocity: Int
var scaledMaximumFlingVelocity: Int
/**
* Direction of the swipe gesture. Can be one of RIGHT, LEFT, UP, DOWN
* @since 1.0.0
*/
var direction: Int = RIGHT
/**
* Number of touches required for the gesture to be accepted
* @since 1.0.0
*/
var numberOfTouchesRequired: Int = 1
var scrollX: Float = 0.toFloat()
private set
var scrollY: Float = 0.toFloat()
private set
/**
* @since 1.1.2
*/
val relativeScrollX: Float get() = -scrollX
/**
* @since 1.1.2
*/
val relativeScrollY: Float get() = -scrollY
/**
* @since 1.0.0
*/
var translationX: Float = 0.toFloat()
internal set
/**
* @since 1.0.0
*/
var translationY: Float = 0.toFloat()
internal set
/**
* @since 1.0.0
*/
var yVelocity: Float = 0.toFloat()
private set
/**
* @since 1.0.0
*/
var xVelocity: Float = 0.toFloat()
private set
/**
* Minimum distance in pixel before the touch can be considered
* as a scroll
*/
var scaledTouchSlop: Int
/**
* Minimum total distance before the gesture will begin
* @since 1.0.0
*/
var minimumSwipeDistance: Int = 0
/**
* Maximum amount of time allowed between a touch down and a touch move
* before the gesture will fail
* @since 1.0.0
*/
var maximumTouchSlopTime = MAXIMUM_TOUCH_SLOP_TIME
/**
* During a move event, the maximum time between touches before
* the gesture will fail
* @since 1.0.0
*/
var maximumTouchFlingTime = MAXIMUM_TOUCH_FLING_TIME
private var mDown: Boolean = false
private var mStarted: Boolean = false
private val mLastFocusLocation = PointF()
private val mDownFocusLocation = PointF()
private var mVelocityTracker: VelocityTracker? = null
init {
mStarted = false
val configuration = ViewConfiguration.get(context)
scaledTouchSlop = configuration.scaledTouchSlop
scaledMaximumFlingVelocity = configuration.scaledMaximumFlingVelocity
scaledMinimumFlingVelocity = configuration.scaledMinimumFlingVelocity
minimumSwipeDistance = (scaledTouchSlop * 3f).toInt()
if (logEnabled) {
logMessage(Log.INFO, "scaledTouchSlop: $scaledTouchSlop")
logMessage(Log.INFO, "minimumSwipeDistance: $minimumSwipeDistance")
logMessage(Log.INFO, "scaledMinimumFlingVelocity: $scaledMinimumFlingVelocity")
logMessage(Log.INFO, "scaledMaximumFlingVelocity: $scaledMaximumFlingVelocity")
}
}
override fun handleMessage(msg: Message) {
when (msg.what) {
MESSAGE_RESET -> handleReset()
else -> {
}
}
}
override fun reset() {
super.reset()
handleReset()
}
private fun handleReset() {
mStarted = false
setBeginFiringEvents(false)
state = State.Possible
}
override fun removeMessages() {
removeMessages(MESSAGE_RESET)
}
override fun onStateChanged(recognizer: UIGestureRecognizer) {
if (recognizer.state == State.Failed && state == State.Ended) {
removeMessages()
stopListenForOtherStateChanges()
fireActionEventIfCanRecognizeSimultaneously()
if (!mDown) {
mStarted = false
state = State.Possible
}
} else if (recognizer.inState(State.Began, State.Ended) && mStarted && inState(State.Possible, State.Ended)) {
mStarted = false
setBeginFiringEvents(false)
stopListenForOtherStateChanges()
removeMessages()
state = State.Failed
}
}
private fun fireActionEventIfCanRecognizeSimultaneously() {
if (delegate!!.shouldRecognizeSimultaneouslyWithGestureRecognizer(this)) {
setBeginFiringEvents(true)
fireActionEvent()
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
super.onTouchEvent(event)
if (!isEnabled) {
return false
}
val action = event.actionMasked
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain()
}
mVelocityTracker?.addMovement(event)
when (action) {
MotionEvent.ACTION_POINTER_DOWN -> {
mLastFocusLocation.set(mCurrentLocation)
mDownFocusLocation.set(mCurrentLocation)
if (state == State.Possible && !mStarted) {
if (numberOfTouches > numberOfTouchesRequired) {
state = State.Failed
removeMessages(MESSAGE_RESET)
}
}
}
MotionEvent.ACTION_POINTER_UP -> {
mLastFocusLocation.set(mCurrentLocation)
mDownFocusLocation.set(mCurrentLocation)
mVelocityTracker?.computeCurrentVelocity(1000, scaledMaximumFlingVelocity.toFloat())
val upIndex = event.actionIndex
val id1 = event.getPointerId(upIndex)
val x1 = mVelocityTracker!!.getXVelocity(id1)
val y1 = mVelocityTracker!!.getYVelocity(id1)
for (i in 0 until numberOfTouches) {
if (i == upIndex) {
continue
}
val id2 = event.getPointerId(i)
val x = x1 * mVelocityTracker!!.getXVelocity(id2)
val y = y1 * mVelocityTracker!!.getYVelocity(id2)
val dot = x + y
if (dot < 0) {
mVelocityTracker?.clear()
break
}
}
if (state == State.Possible && !mStarted) {
if (numberOfTouches < numberOfTouchesRequired) {
state = State.Failed
removeMessages(MESSAGE_RESET)
}
}
}
MotionEvent.ACTION_DOWN -> {
if (delegate?.shouldReceiveTouch?.invoke(this)!!) {
mStarted = false
mDown = true
mLastFocusLocation.set(mCurrentLocation)
mDownFocusLocation.set(mCurrentLocation)
mVelocityTracker?.clear()
setBeginFiringEvents(false)
removeMessages(MESSAGE_RESET)
state = State.Possible
}
}
MotionEvent.ACTION_MOVE -> {
scrollX = mLastFocusLocation.x - mCurrentLocation.x
scrollY = mLastFocusLocation.y - mCurrentLocation.y
mVelocityTracker?.computeCurrentVelocity(1000, scaledMaximumFlingVelocity.toFloat())
yVelocity = mVelocityTracker!!.yVelocity
xVelocity = mVelocityTracker!!.xVelocity
if (state == State.Possible) {
val distance = mCurrentLocation.distance(mDownFocusLocation)
logMessage(Log.INFO, "started: $mStarted, distance: $distance, slop: $scaledTouchSlop")
if (!mStarted) {
if (distance > scaledTouchSlop) {
translationX -= scrollX
translationY -= scrollY
mLastFocusLocation.set(mCurrentLocation)
mStarted = true
if (numberOfTouches == numberOfTouchesRequired) {
val time = event.eventTime - event.downTime
logMessage(Log.VERBOSE, "time: $time, maximumTouchSlopTime: $maximumTouchSlopTime")
if (time > maximumTouchSlopTime) {
logMessage(Log.WARN, "passed too much time 1 ($time > $maximumTouchSlopTime)")
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
} else {
val direction =
getTouchDirection(mDownFocusLocation.x, mDownFocusLocation.y, mCurrentLocation.x,
mCurrentLocation.y, xVelocity, yVelocity, 0f)
logMessage(Log.VERBOSE, "(1) direction: $direction")
// this is necessary because sometimes the velocityTracker
// return 0, probably it needs more input events before computing
// correctly the velocities
if (xVelocity != 0f || yVelocity != 0f) {
if (direction == -1 || (this.direction and direction) == 0) {
logMessage(Log.WARN, "invalid direction: $direction")
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
} else {
logMessage(Log.DEBUG, "direction accepted: ${(this.direction and direction)}")
mStarted = true
}
} else {
logMessage(Log.WARN, "velocity is still 0, waiting for the next event...")
mDownFocusLocation.set(mCurrentLocation)
mStarted = false
}
}
} else {
logMessage(Log.WARN, "invalid number of touches ($numberOfTouches != $numberOfTouchesRequired)")
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
}
}
} else {
// touch has been recognized. now let's track the movement
val time = event.eventTime - event.downTime
if (time > maximumTouchFlingTime) {
logMessage(Log.WARN, "passed too much time 2 ($time > $maximumTouchFlingTime)")
mStarted = false
state = State.Failed
} else {
val direction = getTouchDirection(
mDownFocusLocation.x, mDownFocusLocation.y, mCurrentLocation.x, mCurrentLocation.y, xVelocity,
yVelocity, minimumSwipeDistance.toFloat())
if (direction != -1) {
if (this.direction and direction != 0) {
if (delegate?.shouldBegin?.invoke(this)!!) {
state = State.Ended
if (null == requireFailureOf) {
fireActionEventIfCanRecognizeSimultaneously()
} else {
when {
requireFailureOf!!.state == State.Failed -> fireActionEventIfCanRecognizeSimultaneously()
requireFailureOf!!.inState(State.Began, State.Ended, State.Changed) -> {
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
}
else -> {
logMessage(Log.DEBUG, "waiting...")
listenForOtherStateChanges()
setBeginFiringEvents(false)
}
}
}
} else {
state = State.Failed
mStarted = false
setBeginFiringEvents(false)
}
} else {
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
}
}
}
}
}
}
MotionEvent.ACTION_UP -> {
mVelocityTracker?.addMovement(event)
if (mVelocityTracker != null) {
mVelocityTracker!!.recycle()
mVelocityTracker = null
}
// TODO: should we fail if the gesture didn't actually start?
mDown = false
removeMessages(MESSAGE_RESET)
}
MotionEvent.ACTION_CANCEL -> {
if (mVelocityTracker != null) {
mVelocityTracker!!.recycle()
mVelocityTracker = null
}
mDown = false
removeMessages(MESSAGE_RESET)
state = State.Cancelled
mHandler.sendEmptyMessage(MESSAGE_RESET)
}
else -> {
}
}
return cancelsTouchesInView
}
private fun getTouchDirection(
x1: Float, y1: Float, x2: Float, y2: Float, velocityX: Float, velocityY: Float, distanceThreshold: Float): Int {
val diffY = y2 - y1
val diffX = x2 - x1
if (logEnabled) {
logMessage(Log.INFO, "getTouchDirection")
logMessage(Log.VERBOSE, "diff: $diffX, $diffY, distanceThreshold: $distanceThreshold")
logMessage(Log.VERBOSE, "velocity: $velocityX, $velocityY, scaledMinimumFlingVelocity: $scaledMinimumFlingVelocity, " +
"scaledMaximumFlingVelocity: $scaledMaximumFlingVelocity")
}
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > distanceThreshold && Math.abs(velocityX) > scaledMinimumFlingVelocity) {
return if (diffX > 0) {
RIGHT
} else {
LEFT
}
}
} else if (Math.abs(diffY) > distanceThreshold && Math.abs(velocityY) > scaledMinimumFlingVelocity) {
return if (diffY > 0) {
DOWN
} else {
UP
}
}
return -1
}
companion object {
private const val MESSAGE_RESET = 4
const val RIGHT = 1 shl 1
const val LEFT = 1 shl 2
const val UP = 1 shl 3
const val DOWN = 1 shl 4
const val MAXIMUM_TOUCH_SLOP_TIME = 150
const val MAXIMUM_TOUCH_FLING_TIME = 300
}
} | mit | a0c38195d6dbf7be9dd763163b6e4ad1 | 36.133333 | 142 | 0.487761 | 6.230052 | false | false | false | false |
android/android-studio-poet | aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/android_modules/AndroidModuleBuildGradleGenerator.kt | 1 | 6760 | /*
Copyright 2017 Google 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.androidstudiopoet.generators.android_modules
import com.google.androidstudiopoet.generators.toApplyPluginExpression
import com.google.androidstudiopoet.generators.toExpression
import com.google.androidstudiopoet.gradle.Closure
import com.google.androidstudiopoet.gradle.Expression
import com.google.androidstudiopoet.gradle.Statement
import com.google.androidstudiopoet.gradle.StringStatement
import com.google.androidstudiopoet.models.*
import com.google.androidstudiopoet.utils.isNullOrEmpty
import com.google.androidstudiopoet.writers.FileWriter
class AndroidModuleBuildGradleGenerator(val fileWriter: FileWriter) {
fun generate(blueprint: AndroidBuildGradleBlueprint) {
val statements = applyPlugins(blueprint.plugins) +
androidClosure(blueprint) +
dependenciesClosure(blueprint) +
additionalTasksClosures(blueprint) +
(blueprint.extraLines?.map { StringStatement(it) } ?: listOf())
val gradleText = statements.joinToString(separator = "\n") { it.toGroovy(0) }
fileWriter.writeToFile(gradleText, blueprint.path)
}
private fun applyPlugins(plugins: Set<String>): List<Statement> {
return plugins.map { it.toApplyPluginExpression() }
}
private fun androidClosure(blueprint: AndroidBuildGradleBlueprint): Closure {
val statements = listOfNotNull(
Expression("compileSdkVersion", "${blueprint.compileSdkVersion}"),
defaultConfigClosure(blueprint),
buildTypesClosure(blueprint),
kotlinOptionsClosure(blueprint),
buildFeaturesClosure(blueprint),
compileOptionsClosure(),
composeOptionsClosure(blueprint)
) + createFlavorsSection(blueprint.productFlavors, blueprint.flavorDimensions)
return Closure("android", statements)
}
private fun defaultConfigClosure(blueprint: AndroidBuildGradleBlueprint): Closure {
val expressions = listOfNotNull(
if (blueprint.isApplication) Expression("applicationId", "\"${blueprint.packageName}\"") else null,
Expression("minSdkVersion", "${blueprint.minSdkVersion}"),
Expression("targetSdkVersion", "${blueprint.targetSdkVersion}"),
Expression("versionCode", "1"),
Expression("versionName", "\"1.0\""),
Expression("multiDexEnabled", "true"),
Expression("testInstrumentationRunner", "\"android.support.test.runner.AndroidJUnitRunner\"")
)
return Closure("defaultConfig", expressions)
}
private fun buildTypesClosure(blueprint: AndroidBuildGradleBlueprint): Statement {
val releaseClosure = Closure("release", listOf(
Expression("minifyEnabled", "false"),
Expression("proguardFiles", "getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'")
))
val buildTypesClosures = blueprint.buildTypes?.map {
Closure(it.name, it.body?.lines()?.map { line -> StringStatement(line) } ?: listOf())
} ?: listOf()
return Closure("buildTypes", listOf(releaseClosure) + buildTypesClosures)
}
private fun createFlavorsSection(productFlavors: Set<Flavor>?, flavorDimensions: Set<String>?): List<Statement> {
if (productFlavors.isNullOrEmpty() && flavorDimensions.isNullOrEmpty()) {
return listOf()
}
val flavorDimensionsExpression = flavorDimensions?.joinToString { "\"$it\"" }?.let { Expression("flavorDimensions", it) }
val flavorsList = productFlavors!!.map {
Closure(it.name, listOfNotNull(
it.dimension?.let { dimensionName -> Expression("dimension", "\"$dimensionName\"") }
))
}
return listOfNotNull(
flavorDimensionsExpression,
Closure("productFlavors", flavorsList)
)
}
private fun buildFeaturesClosure(blueprint: AndroidBuildGradleBlueprint): Closure? {
val statements = mutableListOf<StringStatement>()
when {
blueprint.enableCompose -> statements.add(StringStatement("compose true"))
blueprint.enableDataBinding -> statements.add(StringStatement("dataBinding true"))
blueprint.enableViewBinding -> statements.add(StringStatement("viewBinding true"))
else -> {}
}
return if (statements.isNotEmpty()) Closure("buildFeatures", statements) else null
}
private fun kotlinOptionsClosure(blueprint: AndroidBuildGradleBlueprint): Closure? {
return if (blueprint.enableCompose) {
Closure("kotlinOptions", listOf(
StringStatement("jvmTarget = '1.8'"),
StringStatement("useIR = true")
))
} else {
null
}
}
private fun compileOptionsClosure(): Closure {
val expressions = listOf(
Expression("targetCompatibility", "1.8"),
Expression("sourceCompatibility", "1.8"),
)
return Closure("compileOptions", expressions)
}
private fun composeOptionsClosure(blueprint: AndroidBuildGradleBlueprint): Closure? {
return if (blueprint.enableCompose) {
Closure("composeOptions", listOf(
Expression("kotlinCompilerExtensionVersion", "'1.0.4'"),
Expression("kotlinCompilerVersion", "'1.5.31'"),
))
} else {
null
}
}
private fun dependenciesClosure(blueprint: AndroidBuildGradleBlueprint): Closure {
val dependencyExpressions: Set<Statement> = blueprint.dependencies.mapNotNull { it.toExpression() }.toSet()
val statements = dependencyExpressions.toList()
return Closure("dependencies", statements)
}
private fun additionalTasksClosures(blueprint: AndroidBuildGradleBlueprint): Set<Closure> =
blueprint.additionalTasks.map { task ->
Closure(
task.name,
task.body?.map { StringStatement(it) } ?: listOf())
}.toSet()
}
| apache-2.0 | f82067995463ee37335a531fe68927c0 | 40.728395 | 129 | 0.658728 | 5.609959 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/upload/UploadTypeDialogFragment.kt | 1 | 1803 | package com.pr0gramm.app.ui.upload
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.pr0gramm.app.R
import com.pr0gramm.app.ui.MenuSheetView
import com.pr0gramm.app.util.catchAll
class UploadTypeDialogFragment : BottomSheetDialogFragment() {
override fun getTheme(): Int = R.style.MyBottomSheetDialog
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val context = requireContext()
val menuSheetView = MenuSheetView(context, R.string.hint_upload) { item ->
dialog?.dismiss()
if (item.itemId == R.id.action_upload_image) {
UploadActivity.openForType(context, UploadMediaType.IMAGE)
}
if (item.itemId == R.id.action_upload_video) {
UploadActivity.openForType(context, UploadMediaType.VIDEO)
}
}
menuSheetView.inflateMenu(R.menu.menu_upload)
return menuSheetView
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState).apply {
setOnShowListener {
val bottomSheet = requireDialog().findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
if (bottomSheet is FrameLayout) {
catchAll {
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED)
}
}
}
}
}
} | mit | c5858a65c1ea11b1b854e55d86ea135f | 35.08 | 122 | 0.677205 | 4.808 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/view/dialog/NoConnectionDialog.kt | 1 | 2594 | package za.org.grassroot2.view.dialog
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import za.org.grassroot2.R
class NoConnectionDialog : DialogFragment() {
private var dialogType: Int = 0
private val notAuthorizedDialog: Dialog
get() {
val builder = AlertDialog.Builder(activity!!)
val v = LayoutInflater.from(activity).inflate(R.layout.dialog_no_connection_not_authorized, null, false)
v.findViewById<View>(R.id.close).setOnClickListener { v1 -> dismiss() }
v.findViewById<View>(R.id.done).setOnClickListener { v1 -> dismiss() }
builder.setView(v)
val d = builder.create()
d.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return d
}
private val authorizedDialog: Dialog
get() {
val builder = AlertDialog.Builder(activity!!)
val v = LayoutInflater.from(activity).inflate(R.layout.dialog_no_connection_authorized, null, false)
v.findViewById<View>(R.id.continueButton).setOnClickListener { v1 -> dismiss() }
v.findViewById<View>(R.id.retryButton).setOnClickListener { v1 -> dismiss() }
v.findViewById<View>(R.id.close).setOnClickListener { v1 -> dismiss() }
builder.setView(v)
val d = builder.create()
d.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return d
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
dialogType = arguments!!.getInt(EXTRA_TYPE)
when (dialogType) {
TYPE_NOT_AUTHORIZED -> return notAuthorizedDialog
else -> return authorizedDialog
}
}
companion object {
const val TYPE_NOT_AUTHORIZED = 0
const val TYPE_AUTHORIZED = 1
private val EXTRA_TYPE = "type"
fun newInstance(dialogType: Int): DialogFragment {
val dialog = NoConnectionDialog()
val args = Bundle()
args.putInt(EXTRA_TYPE, dialogType)
dialog.arguments = args
return dialog
}
}
}
| bsd-3-clause | 016dd373d7167988d809e046b7d43850 | 36.594203 | 116 | 0.656515 | 4.68231 | false | false | false | false |
FHannes/intellij-community | python/src/com/jetbrains/reflection/ReflectionUtils.kt | 3 | 5861 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.reflection
import com.intellij.util.containers.HashMap
import java.beans.Introspector
import java.beans.PropertyDescriptor
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.javaType
import kotlin.reflect.memberProperties
/**
* Tools to fetch properties both from Java and Kotlin code and to copy them from one object to another.
* To be a property container class should have kotlin properties, java bean properties or implement [SimplePropertiesProvider].
*
* Properties should be writable except [DelegationProperty]
* @author Ilya.Kazakevich
*/
interface Property {
fun getName(): String
fun getType(): java.lang.reflect.Type
fun get(): Any?
fun set(value: Any?)
}
private class KotlinProperty(val property: KMutableProperty<*>, val instance: Any?) : Property {
override fun getName() = property.name
override fun getType() = property.returnType.javaType
override fun get() = property.getter.call(instance)
override fun set(value: Any?) = property.setter.call(instance, value)
}
private class JavaProperty(val property: PropertyDescriptor, val instance: Any?) : Property {
override fun getName() = property.name!!
override fun getType() = property.propertyType!!
override fun get() = property.readMethod.invoke(instance)!!
override fun set(value: Any?) {
property.writeMethod.invoke(instance, value)
}
}
private class SimpleProperty(private val propertyName: String,
private val provider: SimplePropertiesProvider) : Property {
override fun getName() = propertyName
override fun getType() = String::class.java
override fun get() = provider.getPropertyValue(propertyName)
override fun set(value: Any?) = provider.setPropertyValue(propertyName, value?.toString())
}
/**
* Implement to handle properties manually
*/
interface SimplePropertiesProvider {
val propertyNames: List<String>
fun setPropertyValue(propertyName: String, propertyValue: String?)
fun getPropertyValue(propertyName: String): String?
}
class Properties(val properties: List<Property>, val instance: Any) {
val propertiesMap: MutableMap<String, Property> = HashMap(properties.map { Pair(it.getName(), it) }.toMap())
init {
if (instance is SimplePropertiesProvider) {
instance.propertyNames.forEach { propertiesMap.put(it, SimpleProperty(it, instance)) }
}
}
fun copyTo(dst: Properties) {
propertiesMap.values.forEach {
val dstProperty = dst.propertiesMap[it.getName()]
if (dstProperty != null) {
val value = it.get()
dstProperty.set(value)
}
}
}
}
private fun KProperty<*>.isAnnotated(annotation: KClass<*>): Boolean {
return this.annotations.find { annotation.java.isAssignableFrom(it.javaClass) } != null
}
/**
* @param instance object with properties (see module doc)
* @param annotationToFilterByClass optional annotation class to fetch only kotlin properties annotated with it. Only supported in Kotlin
* @param usePojoProperties search for java-style properties (kotlin otherwise)
* @return properties of some object
*/
fun getProperties(instance: Any, annotationToFilterByClass: Class<*>? = null, usePojoProperties: Boolean = false): Properties {
val annotationToFilterBy = annotationToFilterByClass?.kotlin
if (usePojoProperties) {
// Java props
val javaProperties = Introspector.getBeanInfo(instance.javaClass).propertyDescriptors
assert(annotationToFilterBy == null, { "Filtering java properties is not supported" })
return Properties(javaProperties.map { JavaProperty(it, instance) }, instance)
}
else {
// Kotlin props
val klass = instance.javaClass.kotlin
val allKotlinProperties = LinkedHashSet(klass.memberProperties.filterIsInstance(KProperty::class.java))
val delegatedProperties = ArrayList<Property>() // See DelegationProperty doc
allKotlinProperties.filter { it.isAnnotated(DelegationProperty::class) }.forEach {
val delegatedInstance = it.getter.call(instance)
if (delegatedInstance != null) {
delegatedProperties.addAll(getProperties(delegatedInstance, annotationToFilterBy?.java, false).properties)
allKotlinProperties.remove(it)
}
}
val firstLevelProperties = allKotlinProperties.filterIsInstance(KMutableProperty::class.java)
if (annotationToFilterBy == null) {
return Properties(firstLevelProperties.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
return Properties(
firstLevelProperties.filter { it.isAnnotated(annotationToFilterBy) }.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
/**
* Property marked with it is not considered to be [Property] by itself, but class with properties instead.
* Following structure is example:
* class User:
* +familyName: String
* +lastName: String
* +credentials: Credentials
*
* class Credentials:
* +login: String
* +password: String
*
* Property credentials here is [DelegationProperty]. It can be val, but all other properties should be var
*/
annotation class DelegationProperty | apache-2.0 | ea4d6685b3500515e9418dd91bac10eb | 36.576923 | 144 | 0.746289 | 4.51889 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/preferences/fragments/DateAndTime.kt | 1 | 7146 | package org.tasks.preferences.fragments
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import androidx.preference.ListPreference
import androidx.preference.Preference
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.R
import org.tasks.dialogs.MyTimePickerDialog.Companion.newTimePicker
import org.tasks.extensions.Context.toast
import org.tasks.injection.InjectingPreferenceFragment
import org.tasks.preferences.Preferences
import org.tasks.time.DateTime
import org.tasks.ui.TimePreference
import java.time.DayOfWeek
import java.time.format.TextStyle
import java.util.*
import javax.inject.Inject
private const val REQUEST_MORNING = 10007
private const val REQUEST_AFTERNOON = 10008
private const val REQUEST_EVENING = 10009
private const val REQUEST_NIGHT = 10010
@AndroidEntryPoint
class DateAndTime : InjectingPreferenceFragment(), Preference.OnPreferenceChangeListener {
@Inject lateinit var preferences: Preferences
@Inject lateinit var locale: Locale
override fun getPreferenceXml() = R.xml.preferences_date_and_time
override suspend fun setupPreferences(savedInstanceState: Bundle?) {
val startOfWeekPreference: ListPreference = getStartOfWeekPreference()
startOfWeekPreference.entries = getWeekdayEntries()
startOfWeekPreference.onPreferenceChangeListener = this
initializeTimePreference(getMorningPreference(), REQUEST_MORNING)
initializeTimePreference(getAfternoonPreference(), REQUEST_AFTERNOON)
initializeTimePreference(getEveningPreference(), REQUEST_EVENING)
initializeTimePreference(getNightPreference(), REQUEST_NIGHT)
updateStartOfWeek(preferences.getStringValue(R.string.p_start_of_week)!!)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_MORNING) {
if (resultCode == RESULT_OK) {
getMorningPreference().handleTimePickerActivityIntent(data)
}
} else if (requestCode == REQUEST_AFTERNOON) {
if (resultCode == RESULT_OK) {
getAfternoonPreference().handleTimePickerActivityIntent(data)
}
} else if (requestCode == REQUEST_EVENING) {
if (resultCode == RESULT_OK) {
getEveningPreference().handleTimePickerActivityIntent(data)
}
} else if (requestCode == REQUEST_NIGHT) {
if (resultCode == RESULT_OK) {
getNightPreference().handleTimePickerActivityIntent(data)
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun initializeTimePreference(preference: TimePreference, requestCode: Int) {
preference.onPreferenceChangeListener = this
preference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val current = DateTime().withMillisOfDay(preference.millisOfDay)
newTimePicker(this, requestCode, current.millis)
.show(parentFragmentManager, FRAG_TAG_TIME_PICKER)
false
}
}
override fun onPreferenceChange(preference: Preference, newValue: Any?): Boolean {
if (preference == getStartOfWeekPreference()) {
updateStartOfWeek(newValue.toString())
} else {
val millisOfDay = newValue as Int
if (preference == getMorningPreference()) {
if (millisOfDay >= getAfternoonPreference().millisOfDay) {
mustComeBefore(R.string.date_shortcut_morning, R.string.date_shortcut_afternoon)
return false
}
} else if (preference == getAfternoonPreference()) {
if (millisOfDay <= getMorningPreference().millisOfDay) {
mustComeAfter(R.string.date_shortcut_afternoon, R.string.date_shortcut_morning)
return false
} else if (millisOfDay >= getEveningPreference().millisOfDay) {
mustComeBefore(R.string.date_shortcut_afternoon, R.string.date_shortcut_evening)
return false
}
} else if (preference == getEveningPreference()) {
if (millisOfDay <= getAfternoonPreference().millisOfDay) {
mustComeAfter(R.string.date_shortcut_evening, R.string.date_shortcut_afternoon)
return false
} else if (millisOfDay >= getNightPreference().millisOfDay) {
mustComeBefore(R.string.date_shortcut_evening, R.string.date_shortcut_night)
return false
}
} else if (preference == getNightPreference()) {
if (millisOfDay <= getEveningPreference().millisOfDay) {
mustComeAfter(R.string.date_shortcut_night, R.string.date_shortcut_evening)
return false
}
}
}
return true
}
private fun mustComeBefore(settingResId: Int, relativeResId: Int) {
invalidSetting(R.string.date_shortcut_must_come_before, settingResId, relativeResId)
}
private fun mustComeAfter(settingResId: Int, relativeResId: Int) {
invalidSetting(R.string.date_shortcut_must_come_after, settingResId, relativeResId)
}
private fun invalidSetting(errorResId: Int, settingResId: Int, relativeResId: Int) =
context?.toast(errorResId, getString(settingResId), getString(relativeResId))
private fun updateStartOfWeek(value: String) {
val preference = getStartOfWeekPreference()
val index = preference.findIndexOfValue(value)
val summary: String? = getWeekdayEntries().get(index)
preference.summary = summary
}
private fun getStartOfWeekPreference(): ListPreference =
findPreference(R.string.p_start_of_week) as ListPreference
private fun getWeekdayDisplayName(dayOfWeek: DayOfWeek): String =
dayOfWeek.getDisplayName(TextStyle.FULL, locale)
private fun getMorningPreference(): TimePreference =
getTimePreference(R.string.p_date_shortcut_morning)
private fun getAfternoonPreference(): TimePreference =
getTimePreference(R.string.p_date_shortcut_afternoon)
private fun getEveningPreference(): TimePreference =
getTimePreference(R.string.p_date_shortcut_evening)
private fun getNightPreference(): TimePreference =
getTimePreference(R.string.p_date_shortcut_night)
private fun getTimePreference(resId: Int): TimePreference =
findPreference(resId) as TimePreference
private fun getWeekdayEntries(): Array<String?> = arrayOf(
getString(R.string.use_locale_default),
getWeekdayDisplayName(DayOfWeek.SUNDAY),
getWeekdayDisplayName(DayOfWeek.MONDAY),
getWeekdayDisplayName(DayOfWeek.TUESDAY),
getWeekdayDisplayName(DayOfWeek.WEDNESDAY),
getWeekdayDisplayName(DayOfWeek.THURSDAY),
getWeekdayDisplayName(DayOfWeek.FRIDAY),
getWeekdayDisplayName(DayOfWeek.SATURDAY)
)
} | gpl-3.0 | bca2e06535c07eb5bc73a8f6a589bf9a | 42.579268 | 100 | 0.6815 | 5.332836 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/tilerenderers/ModelCacheFactory.kt | 2 | 7055 | package com.cout970.magneticraft.systems.tilerenderers
import com.cout970.magneticraft.misc.addPostfix
import com.cout970.magneticraft.misc.addPrefix
import com.cout970.magneticraft.misc.logError
import com.cout970.magneticraft.misc.warn
import com.cout970.modelloader.api.*
import com.cout970.modelloader.api.animation.AnimatedModel
import com.cout970.modelloader.api.formats.gltf.GltfAnimationBuilder
import com.cout970.modelloader.api.formats.gltf.GltfStructure
import com.cout970.modelloader.api.formats.mcx.McxModel
import net.minecraft.client.renderer.block.model.ModelResourceLocation
import net.minecraft.client.renderer.texture.TextureMap
/**
* Created by cout970 on 2017/06/16.
*/
object ModelCacheFactory {
fun createModel(loc: ModelResourceLocation, filters: List<ModelSelector>,
useTextures: Boolean, time: () -> Double, createDefault: Boolean = true): Map<String, IRenderCache> {
val models = mutableMapOf<String, IRenderCache>()
val (baked, model) = ModelLoaderApi.getModelEntry(loc) ?: return models
when (model) {
is Model.Mcx -> processMcx(model, filters, useTextures, models, createDefault)
is Model.Gltf -> processGltf(model, filters, useTextures, time, models, createDefault)
is Model.Obj -> {
if (createDefault) {
if (baked != null) {
val cache = ModelCache { ModelUtilities.renderModel(baked) }
models["default"] = if (useTextures) TextureModelCache(TextureMap.LOCATION_BLOCKS_TEXTURE, cache) else cache
} else {
logError("Error: trying to render a obj model that is not backed, this is not supported!")
}
}
}
Model.Missing -> {
warn("Model for $loc not found")
}
}
return models
}
private fun removeTextures(model: AnimatedModel): AnimatedModel {
return AnimatedModel(model.rootNodes.map { removeTextures(it) }, model.channels)
}
private fun removeTextures(node: AnimatedModel.Node): AnimatedModel.Node {
return node.copy(
children = node.children.map { removeTextures(it) },
cache = removeTextures(node.cache)
)
}
private fun removeTextures(renderCache: IRenderCache): IRenderCache {
return when (renderCache) {
is ModelGroupCache -> ModelGroupCache(*renderCache.cache.map { removeTextures(it) }.toTypedArray())
is TextureModelCache -> ModelGroupCache(*renderCache.cache)
else -> renderCache
}
}
private fun processMcx(model: Model.Mcx, filters: List<ModelSelector>, useTextures: Boolean,
models: MutableMap<String, IRenderCache>, createDefault: Boolean) {
val sections = filters.map { (name, filterFunc) ->
val parts = model.data.parts.filter { filterFunc(it.name, FilterTarget.LEAF) }
name to parts
}
val notUsed = if (filters.any { it.animationFilter != IGNORE_ANIMATION }) {
model.data.parts
} else {
val used = sections.flatMap { it.second }.toSet()
model.data.parts.filter { it !in used }
}
fun store(name: String, partList: List<McxModel.Part>) {
partList.groupBy { it.texture }.forEach { tex, parts ->
val cache = ModelCache { ModelUtilities.renderModelParts(model.data, parts) }
val texture = tex.addPrefix("textures/").addPostfix(".png")
val obj = if (useTextures) TextureModelCache(texture, cache) else cache
if (name in models) {
val old = models[name]!!
if (old is ModelGroupCache) {
models[name] = ModelGroupCache(*old.cache, obj)
} else {
models[name] = ModelGroupCache(old, obj)
}
} else {
models[name] = obj
}
}
}
sections.forEach { store(it.first, it.second) }
if (createDefault) store("default", notUsed)
}
private fun processGltf(model: Model.Gltf, filters: List<ModelSelector>, useTextures: Boolean, time: () -> Double, models: MutableMap<String, IRenderCache>,
createDefault: Boolean) {
val scene = model.data.structure.scenes[0]
val namedAnimations = model.data.structure.animations.mapIndexed { index, animation ->
animation.name ?: index.toString()
}
val sections = filters.map { (name, filter, animation) ->
Triple(name, scene.nodes.flatMap { it.recursiveFilter(filter) }.toSet(), animation)
}
val allNodes = (0 until model.data.definition.nodes.size).toSet()
fun store(name: String, nodes: Set<Int>, filter: Filter) {
val exclusions = (0 until model.data.definition.nodes.size).filter { it !in nodes }.toSet()
val validAnimations = namedAnimations.filter { filter(it, FilterTarget.ANIMATION) }
val builder = GltfAnimationBuilder()
.also { it.excludedNodes = exclusions }
.also { it.transformTexture = { tex -> tex.addPrefix("textures/").addPostfix(".png") } }
val newModel = if (validAnimations.isEmpty()) {
builder.buildPlain(model.data)
} else {
builder.build(model.data).first { it.first in validAnimations }.second
}
val obj = if (useTextures) {
AnimationRenderCache(newModel, time)
} else {
AnimationRenderCache(removeTextures(newModel), time)
}
if (name in models) {
val old = models[name]!!
if (old is ModelGroupCache) {
models[name] = ModelGroupCache(*old.cache, obj)
} else {
models[name] = ModelGroupCache(old, obj)
}
} else {
models[name] = obj
}
}
sections.forEach { store(it.first, it.second, it.third) }
if (createDefault) store("default", allNodes, IGNORE_ANIMATION)
}
private fun GltfStructure.Node.recursiveFilter(filter: Filter): Set<Int> {
val children = children.flatMap { it.recursiveFilter(filter) }.toSet()
val all = children + setOf(index)
val name = name ?: return all
val type = if (mesh == null) FilterTarget.BRANCH else FilterTarget.LEAF
return if (filter(name, type)) all else emptySet()
}
}
class AnimationRenderCache(val model: AnimatedModel, val time: () -> Double) : IRenderCache {
override fun render() = model.render(time())
override fun close() = model.rootNodes.close()
private fun List<AnimatedModel.Node>.close(): Unit = forEach {
it.cache.close()
it.children.close()
}
} | gpl-2.0 | e8232d50d463064e4d31a74c22685672 | 39.32 | 160 | 0.59759 | 4.690824 | false | false | false | false |
aglne/mycollab | mycollab-esb/src/main/java/com/mycollab/module/billing/esb/AccountCreatedCommand.kt | 3 | 9452 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.billing.esb
import com.google.common.eventbus.AllowConcurrentEvents
import com.google.common.eventbus.Subscribe
import com.mycollab.common.NotificationType
import com.mycollab.common.i18n.OptionI18nEnum.StatusI18nEnum
import com.mycollab.common.i18n.WikiI18nEnum
import com.mycollab.common.service.OptionValService
import com.mycollab.core.utils.BeanUtility
import com.mycollab.core.utils.StringUtils
import com.mycollab.module.esb.GenericCommand
import com.mycollab.module.file.PathUtils
import com.mycollab.module.page.domain.Folder
import com.mycollab.module.page.domain.Page
import com.mycollab.module.page.service.PageService
import com.mycollab.module.project.ProjectTypeConstants
import com.mycollab.module.project.domain.*
import com.mycollab.module.project.i18n.OptionI18nEnum.*
import com.mycollab.module.project.service.*
import com.mycollab.module.project.domain.BugWithBLOBs
import com.mycollab.module.project.domain.Version
import com.mycollab.module.project.service.TicketRelationService
import com.mycollab.module.project.service.BugService
import com.mycollab.module.project.service.ComponentService
import com.mycollab.module.project.service.VersionService
import org.springframework.stereotype.Component
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Component
class AccountCreatedCommand(private val optionValService: OptionValService,
private val projectService: ProjectService,
private val messageService: MessageService,
private val milestoneService: MilestoneService,
private val taskService: TaskService,
private val bugService: BugService,
private val bugRelatedService: TicketRelationService,
private val componentService: ComponentService,
private val versionService: VersionService,
private val pageService: PageService,
private val projectNotificationSettingService: ProjectNotificationSettingService) : GenericCommand() {
@AllowConcurrentEvents
@Subscribe
fun execute(event: AccountCreatedEvent) {
createDefaultOptionVals(event.accountId)
if (event.createSampleData != null && event.createSampleData == true) {
createSampleProjectData(event.initialUser, event.accountId)
}
}
private fun createDefaultOptionVals(accountId: Int) {
optionValService.createDefaultOptions(accountId)
}
private fun createSampleProjectData(initialUser: String, accountId: Int) {
val nowDateTime = LocalDateTime.now()
val nowDate = LocalDate.now()
val project = Project()
project.saccountid = accountId
project.description = "Sample project"
project.homepage = "https://www.mycollab.com"
project.name = "Sample project"
project.status = StatusI18nEnum.Open.name
project.shortname = "SP1"
val projectId = projectService.saveWithSession(project, initialUser)
val projectNotificationSetting = ProjectNotificationSetting()
projectNotificationSetting.level = NotificationType.None.name
projectNotificationSetting.projectid = projectId
projectNotificationSetting.saccountid = accountId
projectNotificationSetting.username = initialUser
projectNotificationSettingService.saveWithSession(projectNotificationSetting, initialUser)
val message = Message()
message.isstick = true
message.createduser = initialUser
message.message = "Welcome to MyCollab workspace. I hope you enjoy it!"
message.saccountid = accountId
message.projectid = projectId
message.title = "Thank you for using MyCollab!"
message.createdtime = nowDateTime
messageService.saveWithSession(message, initialUser)
val milestone = Milestone()
milestone.createduser = initialUser
milestone.duedate = nowDate.plusDays(14)
milestone.startdate = nowDate
milestone.enddate = nowDate.plusDays(14)
milestone.name = "Sample milestone"
milestone.assignuser = initialUser
milestone.projectid = projectId
milestone.saccountid = accountId
milestone.status = MilestoneStatus.InProgress.name
val sampleMilestoneId = milestoneService.saveWithSession(milestone, initialUser)
val taskA = Task()
taskA.name = "Task A"
taskA.projectid = projectId
taskA.createduser = initialUser
taskA.percentagecomplete = 0.0
taskA.priority = Priority.Medium.name
taskA.saccountid = accountId
taskA.status = StatusI18nEnum.Open.name
taskA.startdate = nowDate
taskA.enddate = nowDate.plusDays(3)
val taskAId = taskService.saveWithSession(taskA, initialUser)
val taskB = BeanUtility.deepClone(taskA)
taskB.name = "Task B"
taskB.id = null
taskB.milestoneid = sampleMilestoneId
taskB.startdate = nowDate.plusDays(2)
taskB.enddate = nowDate.plusDays(4)
taskService.saveWithSession(taskB, initialUser)
val taskC = BeanUtility.deepClone(taskA)
taskC.id = null
taskC.name = "Task C"
taskC.startdate = nowDate.plusDays(3)
taskC.enddate = nowDate.plusDays(5)
// taskC.parenttaskid = taskAId
taskService.saveWithSession(taskC, initialUser)
val taskD = BeanUtility.deepClone(taskA)
taskD.id = null
taskD.name = "Task D"
taskD.startdate = nowDate
taskD.enddate = nowDate.plusDays(2)
taskService.saveWithSession(taskD, initialUser)
val component = com.mycollab.module.project.domain.Component()
component.name = "Component 1"
component.createduser = initialUser
component.description = "Sample Component 1"
component.status = StatusI18nEnum.Open.name
component.projectid = projectId
component.saccountid = accountId
component.userlead = initialUser
componentService.saveWithSession(component, initialUser)
val version = Version()
version.createduser = initialUser
version.name = "Version 1"
version.description = "Sample version"
version.duedate = nowDate.plusDays(21)
version.projectid = projectId
version.saccountid = accountId
version.status = StatusI18nEnum.Open.name
versionService.saveWithSession(version, initialUser)
val bugA = BugWithBLOBs()
bugA.description = "Sample bug"
bugA.environment = "All platforms"
bugA.assignuser = initialUser
bugA.duedate = nowDate.plusDays(2)
bugA.createduser = initialUser
bugA.milestoneid = sampleMilestoneId
bugA.name = "Bug A"
bugA.status = StatusI18nEnum.Open.name
bugA.priority = Priority.Medium.name
bugA.projectid = projectId
bugA.saccountid = accountId
val bugAId = bugService.saveWithSession(bugA, initialUser)
val bugB = BeanUtility.deepClone(bugA)
bugB.id = null
bugB.name = "Bug B"
bugB.status = StatusI18nEnum.Resolved.name
bugB.resolution = BugResolution.CannotReproduce.name
bugB.priority = Priority.Low.name
bugService.saveWithSession(bugB, initialUser)
bugRelatedService.saveAffectedVersionsOfTicket(bugAId, ProjectTypeConstants.BUG, listOf(version))
bugRelatedService.saveComponentsOfTicket(bugAId, ProjectTypeConstants.BUG, listOf(component))
val page = Page()
page.subject = "Welcome to sample workspace"
page.content = "I hope you enjoy MyCollab!"
page.path = "${PathUtils.getProjectDocumentPath(accountId, projectId)}/${StringUtils.generateSoftUniqueId()}"
page.status = WikiI18nEnum.status_public.name
pageService.savePage(page, initialUser)
val folder = Folder()
folder.name = "Requirements"
folder.description = "Sample folder"
folder.path = "${PathUtils.getProjectDocumentPath(accountId, projectId)}/${StringUtils.generateSoftUniqueId()}"
pageService.createFolder(folder, initialUser)
val timer = Timer("Set member notification")
timer.schedule(object : TimerTask() {
override fun run() {
projectNotificationSetting.level = NotificationType.Default.name
projectNotificationSettingService.updateWithSession(projectNotificationSetting, initialUser)
}
}, 90000)
}
} | agpl-3.0 | 920fa478b55e36ae9ea43fc5693f5d36 | 41.769231 | 130 | 0.698762 | 4.914717 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/test/java/edu/berkeley/boinc/utils/LoggingTest.kt | 2 | 17929 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.utils
import android.util.Log
import io.mockk.Called
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.mockkStatic
import io.mockk.verify
import org.junit.Assert
import org.junit.Before
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runners.MethodSorters
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class LoggingTest {
@Before
fun setUp() {
mockkStatic(Log::class)
every { Log.e(any(), any()) } returns 0
every { Log.e(any(), any(), any()) } returns 0
every { Log.w(any(), any<String>()) } returns 0
every { Log.i(any(), any()) } returns 0
every { Log.d(any(), any()) } returns 0
every { Log.v(any(), any()) } returns 0
}
@Test
fun `Test_01 Logging TAG`() {
Assert.assertEquals("BOINC_GUI", Logging.TAG)
}
@Test
fun `Test_02 Logging WAKELOCK`() {
Assert.assertEquals("BOINC_GUI:MyPowerLock", Logging.WAKELOCK)
}
@Test
fun `Test_03 Logging Default Log Levels`() {
Assert.assertEquals(-1, Logging.getLogLevel())
Assert.assertFalse(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
Logging.setLogCategory("DEVICE", true)
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_04 Logging setLogLevel(-1)`() {
Logging.setLogLevel(-1)
Assert.assertEquals(-1, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_05 Logging setLogLevel(-10)`() {
Logging.setLogLevel(-10)
Assert.assertEquals(-10, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_06 Logging setLogLevel(-42)`() {
Logging.setLogLevel(-42)
Assert.assertEquals(-42, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_07 Logging setLogLevel(0)`() {
Logging.setLogLevel(0)
Assert.assertEquals(0, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_08 Logging setLogLevel(1)`() {
Logging.setLogLevel(1)
Assert.assertEquals(1, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_09 Logging setLogLevel(2)`() {
Logging.setLogLevel(2)
Assert.assertEquals(2, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_10 Logging setLogLevel(3)`() {
Logging.setLogLevel(3)
Assert.assertEquals(3, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_11 Logging setLogLevel(4)`() {
Logging.setLogLevel(4)
Assert.assertEquals(4, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_12 Logging setLogLevel(5)`() {
Logging.setLogLevel(5)
Assert.assertEquals(5, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_13 Logging setLogLevel(6)`() {
Logging.setLogLevel(6)
Assert.assertEquals(6, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_14 Logging setLogLevel(10)`() {
Logging.setLogLevel(10)
Assert.assertEquals(10, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_15 Logging setLogLevel(42)`() {
Logging.setLogLevel(42)
Assert.assertEquals(42, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_16 Logging after category remove`() {
Logging.setLogCategory("DEVICE", false)
Assert.assertFalse(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test(expected = Test.None::class)
fun `Test_17 Logging not fail on double add or double remove`() {
Logging.setLogCategory("RPC", true)
Logging.setLogCategory("RPC", true)
Logging.setLogCategory("RPC", false)
Logging.setLogCategory("RPC", false)
}
@Test(expected = Test.None::class)
fun `Test_18 Logging not fail when non existing category is provided`() {
Logging.setLogCategory("TEST_CATEGORY", true)
Logging.setLogCategory("TEST_CATEGORY", false)
}
@Test
fun `Test_19 Logging after categories list set`() {
Logging.setLogCategories(listOf("DEVICE", "RPC"))
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.RPC))
Logging.setLogCategory("DEVICE", false)
Logging.setLogCategory("RPC", false)
}
@Test
fun `Test_20 only error and exception are logged when logLevel equals ERROR`() {
Logging.setLogLevel(Logging.Level.ERROR.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 0) { Log.w(any(), any<String>()) }
verify(exactly = 0) { Log.i(any(), any()) }
verify(exactly = 0) { Log.d(any(), any()) }
verify(exactly = 0) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
@Test
fun `Test_21 only warning, error and exception are logged when logLevel equals WARNING`() {
Logging.setLogLevel(Logging.Level.WARNING.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 1) { Log.w(any(), any<String>()) }
verify(exactly = 0) { Log.i(any(), any()) }
verify(exactly = 0) { Log.d(any(), any()) }
verify(exactly = 0) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
@Test
fun `Test_22 only info, warning, error and exception are logged when logLevel equals INFO`() {
Logging.setLogLevel(Logging.Level.INFO.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 1) { Log.w(any(), any<String>()) }
verify(exactly = 1) { Log.i(any(), any()) }
verify(exactly = 0) { Log.d(any(), any()) }
verify(exactly = 0) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
@Test
fun `Test_23 only debug, info, warning, error and exception are logged when logLevel equals DEBUG`() {
Logging.setLogLevel(Logging.Level.DEBUG.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 1) { Log.w(any(), any<String>()) }
verify(exactly = 1) { Log.i(any(), any()) }
verify(exactly = 1) { Log.d(any(), any()) }
verify(exactly = 0) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
@Test
fun `Test_24 verbose, debug, info, warning, error and exception are logged when logLevel equals VERBOSE`() {
Logging.setLogLevel(Logging.Level.VERBOSE.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 1) { Log.w(any(), any<String>()) }
verify(exactly = 1) { Log.i(any(), any()) }
verify(exactly = 1) { Log.d(any(), any()) }
verify(exactly = 1) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
}
| lgpl-3.0 | 62c6cf801d295bc7855be15d8ca4f899 | 48.802778 | 112 | 0.703051 | 4.30675 | false | true | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/surroundWith/expression/RsWithParenthesesSurrounder.kt | 1 | 980 | package org.rust.ide.surroundWith.expression
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsParenExpr
import org.rust.lang.core.psi.RsPsiFactory
class RsWithParenthesesSurrounder : RsExpressionSurrounderBase<RsParenExpr>() {
override fun getTemplateDescription(): String = "(expr)"
override fun createTemplate(project: Project): RsParenExpr =
RsPsiFactory(project).createExpression("(a)") as RsParenExpr
override fun getWrappedExpression(expression: RsParenExpr): RsExpr =
expression.expr
override fun isApplicable(expression: RsExpr): Boolean = true
override fun doPostprocessAndGetSelectionRange(editor: Editor, expression: PsiElement): TextRange {
val offset = expression.textRange.endOffset
return TextRange.from(offset, 0)
}
}
| mit | 1a7e2e74650d999313848e9424b96dd4 | 36.692308 | 103 | 0.777551 | 4.666667 | false | false | false | false |
arturbosch/TiNBo | tinbo-time/src/main/kotlin/io/gitlab/arturbosch/tinbo/time/TimeExt.kt | 1 | 575 | package io.gitlab.arturbosch.tinbo.time
import java.time.LocalDate
/**
* @author Artur Bosch
*/
fun weekRange(today: LocalDate): Pair<LocalDate, LocalDate> {
val dayOfWeek = today.dayOfWeek
val from = dayOfWeek.value - 1
val to = 7 - dayOfWeek.value
return today.minusDays(from.toLong()) to today.plusDays(to.toLong())
}
fun TimeEntry.timeAsMinutes(): Int = (hours * 60 + minutes).toInt()
@Throws(IllegalArgumentException::class)
fun Long.validateInHourRange(): Long =
if (this >= 60) throw IllegalArgumentException("Minutes and seconds must be < 60!") else this | apache-2.0 | 57ffed87db6b0700e5b4182ff90b0ad0 | 27.8 | 95 | 0.737391 | 3.639241 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/input/Gestures.kt | 1 | 638 | package com.soywiz.korge.input
import com.soywiz.korge.component.*
import com.soywiz.korge.view.*
import com.soywiz.korio.async.*
import com.soywiz.korma.geom.*
class Gestures(override val view: View) : Component {
class Direction(val point: IPointInt) {
constructor(x: Int, y: Int) : this(IPointInt(x, y))
val x get() = point.x
val y get() = point.y
companion object {
val Up = Direction(0, -1)
val Down = Direction(0, +1)
val Left = Direction(-1, 0)
val Right = Direction(+1, 0)
}
}
val onSwipe = Signal<Direction>()
}
val View.gestures get() = this.getOrCreateComponentOther<Gestures> { Gestures(this) }
| apache-2.0 | b081c1869e5b42a0725ba2100c353ac2 | 23.538462 | 85 | 0.68652 | 3.038095 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/view/common/CommonListAdapter.kt | 2 | 2825 | package com.bennyhuo.github.view.common
import android.animation.ObjectAnimator
import android.support.annotation.LayoutRes
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import com.bennyhuo.github.R
import com.bennyhuo.github.utils.AdapterList
import kotlinx.android.synthetic.main.item_card.view.*
import org.jetbrains.anko.dip
import org.jetbrains.anko.sdk15.listeners.onClick
abstract class CommonListAdapter<T>(@LayoutRes val itemResId: Int) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val CARD_TAP_DURATION = 100L
}
init {
//item有自己的id
setHasStableIds(true)
}
private var oldPosition = -1
val data = AdapterList<T>(this)
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_card, parent, false)
LayoutInflater.from(itemView.context).inflate(itemResId, itemView.contentContainer)
return CommonViewHolder(itemView)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
onBindData(holder, data[position])
holder.itemView.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> ViewCompat.animate(holder.itemView).scaleX(1.03f).scaleY(1.03f).translationZ(holder.itemView.dip(10).toFloat()).duration = CARD_TAP_DURATION
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
ViewCompat.animate(holder.itemView).scaleX(1f).scaleY(1f).translationZ(holder.itemView.dip(0).toFloat()).duration = CARD_TAP_DURATION
}
}
false
}
holder.itemView.onClick {
onItemClicked(holder.itemView, data[position])
}
}
override fun onViewAttachedToWindow(holder: ViewHolder) {
if(holder is CommonViewHolder && holder.layoutPosition > oldPosition){
addItemAnimation(holder.itemView)
oldPosition = holder.layoutPosition
}
}
private fun addItemAnimation(itemView: View) {
ObjectAnimator.ofFloat(itemView, "translationY", 500f, 0f).setDuration(500).start()
}
abstract fun onBindData(viewHolder: ViewHolder, item: T)
abstract fun onItemClicked(itemView: View, item: T)
class CommonViewHolder(itemView: View): ViewHolder(itemView)
} | apache-2.0 | bd9f65bd4f9ccaeb4396724a9d9b3af8 | 34.225 | 183 | 0.698616 | 4.514423 | false | false | false | false |
uchuhimo/kotlin-playground | konf/src/test/kotlin/com/uchuhimo/konf/ConfigSpek.kt | 1 | 9618 | package com.uchuhimo.konf
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.has
import com.natpryce.hamkrest.throws
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.subject.SubjectSpek
object ConfigSpek : SubjectSpek<Config>({
val spec = NetworkBuffer
val size = NetworkBuffer.size
val maxSize = NetworkBuffer.maxSize
val name = NetworkBuffer.name
val type = NetworkBuffer.type
subject { Config { addSpec(spec) } }
given("a config") {
val invalidItem = ConfigSpec("invalid").run { required<Int>("invalidItem") }
group("addSpec operation") {
on("add orthogonal spec") {
val newSpec = object : ConfigSpec(spec.prefix) {
val minSize = optional("minSize", 1)
}
subject.addSpec(newSpec)
it("should contain items in new spec") {
assertThat(newSpec.minSize in subject, equalTo(true))
assertThat(newSpec.minSize.name in subject, equalTo(true))
}
it("should contain new spec") {
assertThat(newSpec in subject.specs, equalTo(true))
assertThat(spec in subject.specs, equalTo(true))
}
}
on("add repeated item") {
it("should throw RepeatedItemException") {
assertThat({ subject.addSpec(spec) }, throws(has(
RepeatedItemException::name,
equalTo(size.name))))
}
}
on("add repeated name") {
val newSpec = ConfigSpec(spec.prefix).apply { required<Int>("size") }
it("should throw NameConflictException") {
assertThat({ subject.addSpec(newSpec) }, throws<NameConflictException>())
}
}
on("add conflict name, which is prefix of existed name") {
val newSpec = ConfigSpec("network").apply { required<Int>("buffer") }
it("should throw NameConflictException") {
assertThat({ subject.addSpec(newSpec) }, throws<NameConflictException>())
}
}
on("add conflict name, and an existed name is prefix of it") {
val newSpec = ConfigSpec(type.name).apply {
required<Int>("subType")
}
it("should throw NameConflictException") {
assertThat({ subject.addSpec(newSpec) }, throws<NameConflictException>())
}
}
}
on("iterate items in config") {
it("should cover all items in config") {
assertThat(subject.items.toSet(), equalTo(spec.items.toSet()))
}
}
group("get operation") {
on("get with valid item") {
it("should return corresponding value") {
assertThat(subject[name], equalTo("buffer"))
}
}
on("get with invalid item") {
it("should throw NoSuchItemException when using `get`") {
assertThat({ subject[invalidItem] },
throws(has(NoSuchItemException::name, equalTo(invalidItem.name))))
}
it("should return null when using `getOrNull`") {
assertThat(subject.getOrNull(invalidItem), absent())
}
}
on("get with valid name") {
it("should return corresponding value") {
assertThat(subject<String>(spec.qualify("name")), equalTo("buffer"))
}
}
on("get with invalid name") {
it("should throw NoSuchItemException when using `get`") {
assertThat({ subject<String>(spec.qualify("invalid")) }, throws(has(
NoSuchItemException::name, equalTo(spec.qualify("invalid")))))
}
it("should return null when using `getOrNull`") {
assertThat(subject.getOrNull<String>(spec.qualify("invalid")), absent())
}
}
on("get unset item") {
it("should throw UnsetValueException") {
assertThat({ subject[size] }, throws(has(
UnsetValueException::name,
equalTo(size.name))))
assertThat({ subject[maxSize] }, throws(has(
UnsetValueException::name,
equalTo(size.name))))
}
}
}
group("set operation") {
on("set with valid item when corresponding value is unset") {
subject[size] = 1024
it("should contain the specified value") {
assertThat(subject[size], equalTo(1024))
}
}
on("set with valid item when corresponding value exists") {
subject[name] = "newName"
it("should contain the specified value") {
assertThat(subject[name], equalTo("newName"))
}
}
on("set with valid item when corresponding value is lazy") {
test("before set, the item should be lazy; after set," +
" the item should be no longer lazy, and it contains the specified value") {
subject[size] = 1024
assertThat(subject[maxSize], equalTo(subject[size] * 2))
subject[maxSize] = 0
assertThat(subject[maxSize], equalTo(0))
subject[size] = 2048
assertThat(subject[maxSize], !equalTo(subject[size] * 2))
assertThat(subject[maxSize], equalTo(0))
}
}
on("set with invalid item") {
it("should throw NoSuchItemException") {
assertThat({ subject[invalidItem] = 1024 },
throws(has(NoSuchItemException::name, equalTo(invalidItem.name))))
}
}
on("set with valid name") {
subject[spec.qualify("size")] = 1024
it("should contain the specified value") {
assertThat(subject[size], equalTo(1024))
}
}
on("set with invalid name") {
it("should throw NoSuchItemException") {
assertThat({ subject[invalidItem] = 1024 },
throws(has(NoSuchItemException::name, equalTo(invalidItem.name))))
}
}
on("set with incorrect type of value") {
it("should throw ClassCastException") {
assertThat({ subject[size.name] = "1024" }, throws<ClassCastException>())
}
}
on("lazy set with valid item") {
subject.lazySet(maxSize) { it[size] * 4 }
subject[size] = 1024
it("should contain the specified value") {
assertThat(subject[maxSize], equalTo(subject[size] * 4))
}
}
on("lazy set with valid name") {
subject.lazySet(maxSize.name) { it[size] * 4 }
subject[size] = 1024
it("should contain the specified value") {
assertThat(subject[maxSize], equalTo(subject[size] * 4))
}
}
on("lazy set with valid name and invalid value with incompatible type") {
subject.lazySet(maxSize.name) { "string" }
it("should throw InvalidLazySetException when getting") {
assertThat({ subject[maxSize.name] }, throws<InvalidLazySetException>())
}
}
on("unset with valid item") {
subject.unset(type)
it("should contain `null` when using `getOrNull`") {
assertThat(subject.getOrNull(type), absent())
}
}
on("unset with valid name") {
subject.unset(type.name)
it("should contain `null` when using `getOrNull`") {
assertThat(subject.getOrNull(type), absent())
}
}
}
group("item property") {
on("declare a property by item") {
var nameProperty by subject.property(name)
it("should behave same as `get`") {
assertThat(nameProperty, equalTo(subject[name]))
}
it("should support set operation as `set`") {
nameProperty = "newName"
assertThat(nameProperty, equalTo("newName"))
}
}
on("declare a property by name") {
var nameProperty by subject.property<String>(name.name)
it("should behave same as `get`") {
assertThat(nameProperty, equalTo(subject[name]))
}
it("should support set operation as `set`") {
nameProperty = "newName"
assertThat(nameProperty, equalTo("newName"))
}
}
}
}
})
| apache-2.0 | 260c2ed77444993e3f467688911705b8 | 43.322581 | 100 | 0.498336 | 5.443124 | false | true | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/IntentUtils.kt | 1 | 27147 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.support.customtabs.CustomTabsIntent
import android.support.v4.app.ActivityCompat
import android.support.v4.app.FragmentActivity
import android.text.TextUtils
import org.mariotaku.chameleon.Chameleon
import org.mariotaku.chameleon.ChameleonUtils
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.BuildConfig
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.*
import de.vanita5.twittnuker.activity.MediaViewerActivity
import de.vanita5.twittnuker.app.TwittnukerApplication
import de.vanita5.twittnuker.constant.chromeCustomTabKey
import de.vanita5.twittnuker.fragment.SensitiveContentWarningDialogFragment
import de.vanita5.twittnuker.model.*
import de.vanita5.twittnuker.model.util.ParcelableLocationUtils
import de.vanita5.twittnuker.model.util.ParcelableMediaUtils
import de.vanita5.twittnuker.util.LinkCreator.getTwidereUserListRelatedLink
import java.util.*
object IntentUtils {
fun getStatusShareText(context: Context, status: ParcelableStatus): String {
val link = LinkCreator.getStatusWebLink(status)
return context.getString(R.string.status_share_text_format_with_link,
status.text_plain, link.toString())
}
fun getStatusShareSubject(context: Context, status: ParcelableStatus): String {
val timeString = Utils.formatToLongTimeString(context, status.timestamp)
return context.getString(R.string.status_share_subject_format_with_time,
status.user_name, status.user_screen_name, timeString)
}
fun openUserProfile(context: Context, user: ParcelableUser, newDocument: Boolean,
activityOptions: Bundle? = null) {
val intent = userProfile(user)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && newDocument) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
}
ActivityCompat.startActivity(context, intent, activityOptions)
}
fun openUserProfile(context: Context, accountKey: UserKey?,
userKey: UserKey?, screenName: String?, profileUrl: String?,
newDocument: Boolean, activityOptions: Bundle? = null) {
val intent = userProfile(accountKey, userKey, screenName, profileUrl)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && newDocument) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
}
ActivityCompat.startActivity(context, intent, activityOptions)
}
fun userProfile(user: ParcelableUser): Intent {
val uri = LinkCreator.getTwidereUserLink(user.account_key, user.key, user.screen_name)
val intent = uri.intent()
intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
intent.putExtra(EXTRA_USER, user)
if (user.extras != null) {
intent.putExtra(EXTRA_PROFILE_URL, user.extras?.statusnet_profile_url)
}
return intent
}
fun userProfile(accountKey: UserKey?, userKey: UserKey?, screenName: String?,
profileUrl: String? = null, accountHost: String? = accountKey?.host ?: userKey?.host): Intent {
val uri = LinkCreator.getTwidereUserLink(accountKey, userKey, screenName)
val intent = uri.intent()
intent.putExtra(EXTRA_PROFILE_URL, profileUrl)
intent.putExtra(EXTRA_ACCOUNT_HOST, accountHost)
return intent
}
fun userTimeline(accountKey: UserKey?, userKey: UserKey?, screenName: String?,
profileUrl: String? = null): Intent {
val uri = LinkCreator.getTwidereUserRelatedLink(AUTHORITY_USER_TIMELINE, accountKey,
userKey, screenName)
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.putExtra(EXTRA_PROFILE_URL, profileUrl)
return intent
}
fun userMediaTimeline(accountKey: UserKey?, userKey: UserKey?, screenName: String?,
profileUrl: String? = null): Intent {
val uri = LinkCreator.getTwidereUserRelatedLink(AUTHORITY_USER_MEDIA_TIMELINE, accountKey,
userKey, screenName)
val intent = uri.intent()
intent.putExtra(EXTRA_PROFILE_URL, profileUrl)
return intent
}
fun userFavorites(accountKey: UserKey?, userKey: UserKey?, screenName: String?,
profileUrl: String? = null): Intent {
val uri = LinkCreator.getTwidereUserRelatedLink(AUTHORITY_USER_FAVORITES, accountKey,
userKey, screenName)
val intent = uri.intent()
intent.putExtra(EXTRA_PROFILE_URL, profileUrl)
return intent
}
fun openItems(context: Context, items: List<Parcelable>?) {
if (items == null) return
val extras = Bundle()
extras.putParcelableArrayList(EXTRA_ITEMS, ArrayList(items))
val builder = UriBuilder(AUTHORITY_ITEMS)
val intent = builder.intent()
intent.putExtras(extras)
context.startActivity(intent)
}
fun openUserMentions(context: Context, accountKey: UserKey?,
screenName: String) {
val builder = UriBuilder(AUTHORITY_USER_MENTIONS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
context.startActivity(builder.intent())
}
fun openMedia(context: Context, status: ParcelableStatus,
current: ParcelableMedia? = null, newDocument: Boolean,
displaySensitiveContents: Boolean, options: Bundle? = null) {
val media = ParcelableMediaUtils.getPrimaryMedia(status) ?: return
openMedia(context, status.account_key, status.is_possibly_sensitive, status, current,
media, newDocument, displaySensitiveContents, options)
}
fun openMedia(context: Context, accountKey: UserKey?, media: Array<ParcelableMedia>,
current: ParcelableMedia? = null, isPossiblySensitive: Boolean,
newDocument: Boolean, displaySensitiveContents: Boolean, options: Bundle? = null) {
openMedia(context, accountKey, isPossiblySensitive, null, current, media, newDocument,
displaySensitiveContents, options)
}
fun openMedia(context: Context, accountKey: UserKey?, isPossiblySensitive: Boolean,
status: ParcelableStatus?, current: ParcelableMedia? = null, media: Array<ParcelableMedia>,
newDocument: Boolean, displaySensitiveContents: Boolean,
options: Bundle? = null) {
if (context is FragmentActivity && isPossiblySensitive && !displaySensitiveContents) {
val fm = context.supportFragmentManager
val fragment = SensitiveContentWarningDialogFragment()
val args = Bundle()
args.putParcelable(EXTRA_ACCOUNT_KEY, accountKey)
args.putParcelable(EXTRA_CURRENT_MEDIA, current)
if (status != null) {
args.putParcelable(EXTRA_STATUS, status)
}
args.putParcelableArray(EXTRA_MEDIA, media)
args.putBundle(EXTRA_ACTIVITY_OPTIONS, options)
args.putBoolean(EXTRA_NEW_DOCUMENT, newDocument)
fragment.arguments = args
fragment.show(fm, "sensitive_content_warning")
} else {
openMediaDirectly(context, accountKey, media, current, options, newDocument, status)
}
}
fun openMediaDirectly(context: Context, accountKey: UserKey?, status: ParcelableStatus,
current: ParcelableMedia, newDocument: Boolean, options: Bundle? = null) {
val media = ParcelableMediaUtils.getPrimaryMedia(status) ?: return
openMediaDirectly(context, accountKey, media, current, options, newDocument, status)
}
fun getDefaultBrowserPackage(context: Context, uri: Uri, checkHandled: Boolean): String? {
if (checkHandled && !isWebLinkHandled(context, uri)) {
return null
}
val intent = Intent(Intent.ACTION_VIEW)
intent.addCategory(Intent.CATEGORY_BROWSABLE)
intent.data = Uri.parse("${uri.scheme}://")
return intent.resolveActivity(context.packageManager)?.takeIf {
it.className != null && it.packageName != "android"
}?.packageName
}
fun isWebLinkHandled(context: Context, uri: Uri): Boolean {
val filter = getWebLinkIntentFilter(context) ?: return false
return filter.match(Intent.ACTION_VIEW, null, uri.scheme, uri,
setOf(Intent.CATEGORY_BROWSABLE), LOGTAG) >= 0
}
fun getWebLinkIntentFilter(context: Context): IntentFilter? {
val testIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/user_name"))
testIntent.addCategory(Intent.CATEGORY_BROWSABLE)
testIntent.`package` = context.packageName
val resolveInfo = context.packageManager.resolveActivity(testIntent,
PackageManager.GET_RESOLVED_FILTER)
return resolveInfo?.filter
}
fun openMediaDirectly(context: Context, accountKey: UserKey?, media: Array<ParcelableMedia>,
current: ParcelableMedia? = null, options: Bundle? = null, newDocument: Boolean,
status: ParcelableStatus? = null, message: ParcelableMessage? = null) {
val intent = Intent(context, MediaViewerActivity::class.java)
intent.putExtra(EXTRA_ACCOUNT_KEY, accountKey)
intent.putExtra(EXTRA_CURRENT_MEDIA, current)
intent.putExtra(EXTRA_MEDIA, media)
if (status != null) {
intent.putExtra(EXTRA_STATUS, status)
intent.data = getMediaViewerUri("status", status.id, accountKey)
}
if (message != null) {
intent.putExtra(EXTRA_MESSAGE, message)
intent.data = getMediaViewerUri("message", message.id, accountKey)
}
if (newDocument && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
}
ActivityCompat.startActivity(context, intent, options)
}
fun getMediaViewerUri(type: String, id: String,
accountKey: UserKey?): Uri {
val builder = Uri.Builder()
builder.scheme(SCHEME_TWITTNUKER)
builder.authority("media")
builder.appendPath(type)
builder.appendPath(id)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
return builder.build()
}
fun openMessageConversation(context: Context, accountKey: UserKey, conversationId: String) {
context.startActivity(messageConversation(accountKey, conversationId))
}
fun messageConversation(accountKey: UserKey, conversationId: String): Intent {
val builder = UriBuilder(AUTHORITY_MESSAGES)
builder.path(PATH_MESSAGES_CONVERSATION)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
builder.appendQueryParameter(QUERY_PARAM_CONVERSATION_ID, conversationId)
return builder.intent()
}
fun messageConversationInfo(accountKey: UserKey, conversationId: String): Intent {
val builder = UriBuilder(AUTHORITY_MESSAGES)
builder.path(PATH_MESSAGES_CONVERSATION_INFO)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
builder.appendQueryParameter(QUERY_PARAM_CONVERSATION_ID, conversationId)
return builder.intent()
}
fun newMessageConversation(accountKey: UserKey): Intent {
val builder = UriBuilder(AUTHORITY_MESSAGES)
builder.path(PATH_MESSAGES_CONVERSATION_NEW)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
return builder.intent()
}
fun openIncomingFriendships(context: Context,
accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_INCOMING_FRIENDSHIPS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openMap(context: Context, latitude: Double, longitude: Double) {
if (!ParcelableLocationUtils.isValidLocation(latitude, longitude)) return
val builder = UriBuilder(AUTHORITY_MAP)
builder.appendQueryParameter(QUERY_PARAM_LAT, latitude.toString())
builder.appendQueryParameter(QUERY_PARAM_LNG, longitude.toString())
context.startActivity(builder.intent())
}
fun openMutesUsers(context: Context,
accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_MUTES_USERS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openSavedSearches(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_SAVED_SEARCHES)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openSearch(context: Context, accountKey: UserKey?, query: String, type: String? = null) {
val builder = UriBuilder(AUTHORITY_SEARCH)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_QUERY, query)
if (!TextUtils.isEmpty(type)) {
builder.appendQueryParameter(QUERY_PARAM_TYPE, type)
}
val intent = builder.intent()
// Some devices cannot process query parameter with hashes well, so add this intent extra
intent.putExtra(EXTRA_QUERY, query)
if (!TextUtils.isEmpty(type)) {
intent.putExtra(EXTRA_TYPE, type)
}
if (accountKey != null) {
intent.putExtra(EXTRA_ACCOUNT_KEY, accountKey)
}
context.startActivity(intent)
}
fun openMastodonSearch(context: Context, accountKey: UserKey?, query: String) {
val builder = UriBuilder(AUTHORITY_MASTODON_SEARCH)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_QUERY, query)
val intent = builder.intent()
// Some devices cannot process query parameter with hashes well, so add this intent extra
intent.putExtra(EXTRA_QUERY, query)
if (accountKey != null) {
intent.putExtra(EXTRA_ACCOUNT_KEY, accountKey)
}
context.startActivity(intent)
}
fun status(accountKey: UserKey?, statusId: String): Intent {
val uri = LinkCreator.getTwidereStatusLink(accountKey, statusId)
return Intent(Intent.ACTION_VIEW, uri).setPackage(BuildConfig.APPLICATION_ID)
}
fun openStatus(context: Context, accountKey: UserKey?, statusId: String) {
context.startActivity(status(accountKey, statusId))
}
fun openStatus(context: Context, status: ParcelableStatus, activityOptions: Bundle? = null) {
val intent = status(status.account_key, status.id)
intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
intent.putExtra(EXTRA_STATUS, status)
ActivityCompat.startActivity(context, intent, activityOptions)
}
fun openStatusFavoriters(context: Context, accountKey: UserKey?, statusId: String) {
val builder = UriBuilder(AUTHORITY_STATUS_FAVORITERS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_STATUS_ID, statusId)
ActivityCompat.startActivity(context, builder.intent(), null)
}
fun openStatusRetweeters(context: Context, accountKey: UserKey?, statusId: String) {
val builder = UriBuilder(AUTHORITY_STATUS_RETWEETERS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_STATUS_ID, statusId)
ActivityCompat.startActivity(context, builder.intent(), null)
}
fun openTweetSearch(context: Context, accountKey: UserKey?, query: String) {
openSearch(context, accountKey, query, QUERY_PARAM_VALUE_TWEETS)
}
fun openUserBlocks(activity: Activity?, accountKey: UserKey) {
if (activity == null) return
val builder = UriBuilder(AUTHORITY_USER_BLOCKS)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
activity.startActivity(builder.intent())
}
fun openUserFavorites(context: Context, accountKey: UserKey?, userKey: UserKey?,
screenName: String?) {
val builder = UriBuilder(AUTHORITY_USER_FAVORITES)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
if (userKey != null) {
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
}
if (screenName != null) {
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
}
context.startActivity(builder.intent())
}
fun openUserFollowers(context: Context, accountKey: UserKey?, userKey: UserKey?,
screenName: String?) {
val intent = LinkCreator.getTwidereUserRelatedLink(AUTHORITY_USER_FOLLOWERS,
accountKey, userKey, screenName)
context.startActivity(Intent(Intent.ACTION_VIEW, intent))
}
fun openUserFriends(context: Context, accountKey: UserKey?, userKey: UserKey?,
screenName: String?) {
val builder = UriBuilder(AUTHORITY_USER_FRIENDS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
if (userKey != null) {
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
}
if (screenName != null) {
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
}
context.startActivity(builder.intent())
}
fun openUserListDetails(context: Context, accountKey: UserKey?, listId: String?,
userKey: UserKey?, screenName: String?, listName: String?) {
context.startActivity(userListDetails(accountKey, listId, userKey, screenName, listName))
}
fun userListDetails(accountKey: UserKey?, listId: String?, userKey: UserKey?,
screenName: String?, listName: String?): Intent {
return getTwidereUserListRelatedLink(AUTHORITY_USER_LIST, accountKey, listId, userKey,
screenName, listName).intent()
}
fun userListTimeline(accountKey: UserKey?, listId: String?, userKey: UserKey?,
screenName: String?, listName: String?): Intent {
return getTwidereUserListRelatedLink(AUTHORITY_USER_LIST_TIMELINE, accountKey, listId,
userKey, screenName, listName).intent()
}
fun openUserListDetails(context: Context, userList: ParcelableUserList) {
context.startActivity(userListDetails(userList))
}
fun userListDetails(userList: ParcelableUserList): Intent {
val userKey = userList.user_key
val listId = userList.id
val builder = UriBuilder(AUTHORITY_USER_LIST)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, userList.account_key.toString())
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
builder.appendQueryParameter(QUERY_PARAM_LIST_ID, listId)
val intent = builder.intent()
intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
intent.putExtra(EXTRA_USER_LIST, userList)
return intent
}
fun openGroupDetails(context: Context, group: ParcelableGroup) {
val builder = UriBuilder(AUTHORITY_GROUP)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, group.account_key.toString())
builder.appendQueryParameter(QUERY_PARAM_GROUP_ID, group.id)
builder.appendQueryParameter(QUERY_PARAM_GROUP_NAME, group.nickname)
val intent = builder.intent()
intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
intent.putExtra(EXTRA_GROUP, group)
context.startActivity(intent)
}
fun openUserLists(context: Context, accountKey: UserKey?, userKey: UserKey?, screenName: String?) {
val builder = Uri.Builder()
builder.scheme(SCHEME_TWITTNUKER)
builder.authority(AUTHORITY_USER_LISTS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
if (userKey != null) {
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
}
if (screenName != null) {
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
}
context.startActivity(builder.intent())
}
fun openUserGroups(context: Context, accountKey: UserKey?, userKey: UserKey?, screenName: String?) {
val builder = UriBuilder(AUTHORITY_USER_GROUPS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
if (userKey != null) {
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
}
if (screenName != null) {
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
}
context.startActivity(builder.intent())
}
fun openDirectMessages(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_MESSAGES)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openInteractions(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_INTERACTIONS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openPublicTimeline(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_PUBLIC_TIMELINE)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openNetworkPublicTimeline(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_NETWORK_PUBLIC_TIMELINE)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openAccountsManager(context: Context) {
val builder = UriBuilder(AUTHORITY_ACCOUNTS)
context.startActivity(builder.intent())
}
fun openDrafts(context: Context) {
val builder = UriBuilder(AUTHORITY_DRAFTS)
context.startActivity(builder.intent())
}
fun settings(initialTag: String? = null): Intent {
val builder = Uri.Builder()
builder.scheme(SCHEME_TWITTNUKER_SETTINGS)
builder.authority(initialTag.orEmpty())
return builder.intent(Intent.ACTION_MAIN)
}
fun openProfileEditor(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_PROFILE_EDITOR)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openFilters(context: Context, initialTab: String? = null) {
val builder = UriBuilder(AUTHORITY_FILTERS)
val intent = builder.intent()
intent.putExtra(EXTRA_INITIAL_TAB, initialTab)
context.startActivity(intent)
}
fun browse(context: Context, preferences: SharedPreferences,
theme: Chameleon.Theme? = Chameleon.getOverrideTheme(context, ChameleonUtils.getActivity(context)),
uri: Uri, forceBrowser: Boolean = true): Pair<Intent, Bundle?> {
if (!preferences[chromeCustomTabKey]) {
val viewIntent = Intent(Intent.ACTION_VIEW, uri)
viewIntent.addCategory(Intent.CATEGORY_BROWSABLE)
return Pair(viewIntent, null)
}
val builder = CustomTabsIntent.Builder()
builder.addDefaultShareMenuItem()
theme?.let { t ->
builder.setToolbarColor(t.colorToolbar)
}
val customTabsIntent = builder.build()
val intent = customTabsIntent.intent
intent.data = uri
if (forceBrowser) {
intent.`package` = getDefaultBrowserPackage(context, uri, false)
}
return Pair(intent, customTabsIntent.startAnimationBundle)
}
fun applyNewDocument(intent: Intent, enable: Boolean) {
if (enable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
}
}
fun UriBuilder(authority: String): Uri.Builder {
return Uri.Builder().scheme(SCHEME_TWITTNUKER).authority(authority)
}
private fun Uri.intent(action: String = Intent.ACTION_VIEW): Intent {
return Intent(action, this).setPackage(BuildConfig.APPLICATION_ID)
}
private fun Uri.Builder.intent(action: String = Intent.ACTION_VIEW): Intent {
return build().intent(action)
}
} | gpl-3.0 | edbc93fe167fb1303f5489ae0da70a76 | 42.298246 | 111 | 0.674697 | 4.788675 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-cupcake | app/src/main/java/com/example/cupcake/CupcakeScreen.kt | 1 | 6980 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.cupcake
import android.content.Context
import android.content.Intent
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.cupcake.data.DataSource.flavors
import com.example.cupcake.data.DataSource.quantityOptions
import com.example.cupcake.data.OrderUiState
import com.example.cupcake.ui.OrderSummaryScreen
import com.example.cupcake.ui.OrderViewModel
import com.example.cupcake.ui.SelectOptionScreen
import com.example.cupcake.ui.StartOrderScreen
/**
* enum values that represent the screens in the app
*/
enum class CupcakeScreen(@StringRes val title: Int) {
Start(title = R.string.app_name),
Flavor(title = R.string.choose_flavor),
Pickup(title = R.string.choose_pickup_date),
Summary(title = R.string.order_summary)
}
/**
* Composable that displays the topBar and displays back button if back navigation is possible.
*/
@Composable
fun CupcakeAppBar(
currentScreen: CupcakeScreen,
canNavigateBack: Boolean,
navigateUp: () -> Unit,
modifier: Modifier = Modifier
) {
TopAppBar(
title = { Text(stringResource(currentScreen.title)) },
modifier = modifier,
navigationIcon = {
if (canNavigateBack) {
IconButton(onClick = navigateUp) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = stringResource(R.string.back_button)
)
}
}
}
)
}
@Composable
fun CupcakeApp(
modifier: Modifier = Modifier,
viewModel: OrderViewModel = viewModel(),
navController: NavHostController = rememberNavController()
) {
// Get current back stack entry
val backStackEntry by navController.currentBackStackEntryAsState()
// Get the name of the current screen
val currentScreen = CupcakeScreen.valueOf(
backStackEntry?.destination?.route ?: CupcakeScreen.Start.name
)
Scaffold(
topBar = {
CupcakeAppBar(
currentScreen = currentScreen,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() }
)
}
) { innerPadding ->
val uiState by viewModel.uiState.collectAsState()
NavHost(
navController = navController,
startDestination = CupcakeScreen.Start.name,
modifier = modifier.padding(innerPadding)
) {
composable(route = CupcakeScreen.Start.name) {
StartOrderScreen(
quantityOptions = quantityOptions,
onNextButtonClicked = {
viewModel.setQuantity(it)
navController.navigate(CupcakeScreen.Flavor.name)
}
)
}
composable(route = CupcakeScreen.Flavor.name) {
val context = LocalContext.current
SelectOptionScreen(
subtotal = uiState.price,
onNextButtonClicked = { navController.navigate(CupcakeScreen.Pickup.name) },
onCancelButtonClicked = {
cancelOrderAndNavigateToStart(viewModel, navController)
},
options = flavors.map { id -> context.resources.getString(id) },
onSelectionChanged = { viewModel.setFlavor(it) }
)
}
composable(route = CupcakeScreen.Pickup.name) {
SelectOptionScreen(
subtotal = uiState.price,
onNextButtonClicked = { navController.navigate(CupcakeScreen.Summary.name) },
onCancelButtonClicked = {
cancelOrderAndNavigateToStart(viewModel, navController)
},
options = uiState.pickupOptions,
onSelectionChanged = { viewModel.setDate(it) }
)
}
composable(route = CupcakeScreen.Summary.name) {
val context = LocalContext.current
OrderSummaryScreen(
orderUiState = uiState,
onCancelButtonClicked = {
cancelOrderAndNavigateToStart(viewModel, navController)
},
onSendButtonClicked = { subject: String, summary: String ->
shareOrder(context, subject = subject, summary = summary)
}
)
}
}
}
}
/**
* Resets the [OrderUiState] and pops up to [CupcakeScreen.Start]
*/
private fun cancelOrderAndNavigateToStart(
viewModel: OrderViewModel,
navController: NavHostController
) {
viewModel.resetOrder()
navController.popBackStack(CupcakeScreen.Start.name, inclusive = false)
}
/**
* Creates an intent to share order details
*/
private fun shareOrder(context: Context, subject: String, summary: String) {
// Create an ACTION_SEND implicit intent with order details in the intent extras
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_SUBJECT, subject)
putExtra(Intent.EXTRA_TEXT, summary)
}
context.startActivity(
Intent.createChooser(
intent,
context.getString(R.string.new_cupcake_order)
)
)
}
| apache-2.0 | 099ae26fa7472d70ed1f0e762281d9f9 | 35.931217 | 97 | 0.648854 | 5.166543 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/VersionedUtils.kt | 2 | 13214 | // Copyright 2015-present 650 Industries. All rights reserved.
package versioned.host.exp.exponent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import com.facebook.common.logging.FLog
import com.facebook.hermes.reactexecutor.HermesExecutorFactory
import com.facebook.react.ReactInstanceManager
import com.facebook.react.ReactInstanceManagerBuilder
import com.facebook.react.bridge.JavaScriptContextHolder
import com.facebook.react.bridge.JavaScriptExecutorFactory
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.common.LifecycleState
import com.facebook.react.common.ReactConstants
import com.facebook.react.jscexecutor.JSCExecutorFactory
import com.facebook.react.modules.systeminfo.AndroidInfoHelpers
import com.facebook.react.packagerconnection.NotificationOnlyHandler
import com.facebook.react.packagerconnection.RequestHandler
import com.facebook.react.shell.MainReactPackage
import expo.modules.jsonutils.getNullable
import host.exp.exponent.Constants
import host.exp.exponent.RNObject
import host.exp.exponent.experience.ExperienceActivity
import host.exp.exponent.experience.ReactNativeActivity
import host.exp.exponent.kernel.KernelProvider
import host.exp.expoview.Exponent
import host.exp.expoview.Exponent.InstanceManagerBuilderProperties
import org.json.JSONObject
import versioned.host.exp.exponent.modules.api.reanimated.ReanimatedJSIModulePackage
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.util.*
object VersionedUtils {
// Update this value when hermes-engine getting updated.
// Currently there is no way to retrieve Hermes bytecode version from Java,
// as an alternative, we maintain the version by hand.
private const val HERMES_BYTECODE_VERSION = 76
private fun toggleExpoDevMenu() {
val currentActivity = Exponent.instance.currentActivity
if (currentActivity is ExperienceActivity) {
currentActivity.toggleDevMenu()
} else {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the Expo dev menu because the current activity could not be found."
)
}
}
private fun reloadExpoApp() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to reload the app because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
devSupportManager.callRecursive("reloadExpoApp")
}
private fun toggleElementInspector() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the element inspector because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
devSupportManager.callRecursive("toggleElementInspector")
}
private fun requestOverlayPermission(context: Context) {
// From the unexposed DebugOverlayController static helper
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Get permission to show debug overlay in dev builds.
if (!Settings.canDrawOverlays(context)) {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + context.packageName)
).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
FLog.w(
ReactConstants.TAG,
"Overlay permissions needs to be granted in order for React Native apps to run in development mode"
)
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
}
}
}
}
private fun togglePerformanceMonitor() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the performance monitor because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
if (devSettings != null) {
val isFpsDebugEnabled = devSettings.call("isFpsDebugEnabled") as Boolean
if (!isFpsDebugEnabled) {
// Request overlay permission if needed when "Show Perf Monitor" option is selected
requestOverlayPermission(currentActivity)
}
devSettings.call("setFpsDebugEnabled", !isFpsDebugEnabled)
}
}
private fun toggleRemoteJSDebugging() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle remote JS debugging because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
if (devSettings != null) {
val isRemoteJSDebugEnabled = devSettings.call("isRemoteJSDebugEnabled") as Boolean
devSettings.call("setRemoteJSDebugEnabled", !isRemoteJSDebugEnabled)
}
}
private fun createPackagerCommandHelpers(): Map<String, RequestHandler> {
// Attach listeners to the bundler's dev server web socket connection.
// This enables tools to automatically reload the client remotely (i.e. in expo-cli).
val packagerCommandHandlers = mutableMapOf<String, RequestHandler>()
// Enable a lot of tools under the same command namespace
packagerCommandHandlers["sendDevCommand"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
if (params != null && params is JSONObject) {
when (params.getNullable<String>("name")) {
"reload" -> reloadExpoApp()
"toggleDevMenu" -> toggleExpoDevMenu()
"toggleRemoteDebugging" -> {
toggleRemoteJSDebugging()
// Reload the app after toggling debugging, this is based on what we do in DevSupportManagerBase.
reloadExpoApp()
}
"toggleElementInspector" -> toggleElementInspector()
"togglePerformanceMonitor" -> togglePerformanceMonitor()
}
}
}
}
// These commands (reload and devMenu) are here to match RN dev tooling.
// Reload the app on "reload"
packagerCommandHandlers["reload"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
reloadExpoApp()
}
}
// Open the dev menu on "devMenu"
packagerCommandHandlers["devMenu"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
toggleExpoDevMenu()
}
}
return packagerCommandHandlers
}
@JvmStatic fun getReactInstanceManagerBuilder(instanceManagerBuilderProperties: InstanceManagerBuilderProperties): ReactInstanceManagerBuilder {
// Build the instance manager
var builder = ReactInstanceManager.builder()
.setApplication(instanceManagerBuilderProperties.application)
.setJSIModulesPackage { reactApplicationContext: ReactApplicationContext, jsContext: JavaScriptContextHolder? ->
val devSupportManager = getDevSupportManager(reactApplicationContext)
if (devSupportManager == null) {
Log.e(
"Exponent",
"Couldn't get the `DevSupportManager`. JSI modules won't be initialized."
)
return@setJSIModulesPackage emptyList()
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
val isRemoteJSDebugEnabled = devSettings != null && devSettings.call("isRemoteJSDebugEnabled") as Boolean
if (!isRemoteJSDebugEnabled) {
return@setJSIModulesPackage ReanimatedJSIModulePackage().getJSIModules(
reactApplicationContext,
jsContext
)
}
emptyList()
}
.addPackage(MainReactPackage())
.addPackage(
ExponentPackage(
instanceManagerBuilderProperties.experienceProperties,
instanceManagerBuilderProperties.manifest,
// DO NOT EDIT THIS COMMENT - used by versioning scripts
// When distributing change the following two arguments to nulls
instanceManagerBuilderProperties.expoPackages,
instanceManagerBuilderProperties.exponentPackageDelegate,
instanceManagerBuilderProperties.singletonModules
)
)
.addPackage(
ExpoTurboPackage(
instanceManagerBuilderProperties.experienceProperties,
instanceManagerBuilderProperties.manifest
)
)
.setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
.setCustomPackagerCommandHandlers(createPackagerCommandHelpers())
.setJavaScriptExecutorFactory(createJSExecutorFactory(instanceManagerBuilderProperties))
if (instanceManagerBuilderProperties.jsBundlePath != null && instanceManagerBuilderProperties.jsBundlePath!!.isNotEmpty()) {
builder = builder.setJSBundleFile(instanceManagerBuilderProperties.jsBundlePath)
}
return builder
}
private fun getDevSupportManager(reactApplicationContext: ReactApplicationContext): RNObject? {
val currentActivity = Exponent.instance.currentActivity
return if (currentActivity != null) {
if (currentActivity is ReactNativeActivity) {
currentActivity.devSupportManager
} else {
null
}
} else try {
val devSettingsModule = reactApplicationContext.catalystInstance.getNativeModule("DevSettings")
val devSupportManagerField = devSettingsModule!!.javaClass.getDeclaredField("mDevSupportManager")
devSupportManagerField.isAccessible = true
RNObject.wrap(devSupportManagerField[devSettingsModule]!!)
} catch (e: Throwable) {
e.printStackTrace()
null
}
}
private fun createJSExecutorFactory(
instanceManagerBuilderProperties: InstanceManagerBuilderProperties
): JavaScriptExecutorFactory? {
val appName = instanceManagerBuilderProperties.manifest.getName() ?: ""
val deviceName = AndroidInfoHelpers.getFriendlyDeviceName()
if (Constants.isStandaloneApp()) {
return JSCExecutorFactory(appName, deviceName)
}
val hermesBundlePair = parseHermesBundleHeader(instanceManagerBuilderProperties.jsBundlePath)
if (hermesBundlePair.first && hermesBundlePair.second != HERMES_BYTECODE_VERSION) {
val message = String.format(
Locale.US,
"Unable to load unsupported Hermes bundle.\n\tsupportedBytecodeVersion: %d\n\ttargetBytecodeVersion: %d",
HERMES_BYTECODE_VERSION, hermesBundlePair.second
)
KernelProvider.instance.handleError(RuntimeException(message))
return null
}
val jsEngineFromManifest = instanceManagerBuilderProperties.manifest.getAndroidJsEngine()
return if (jsEngineFromManifest == "hermes") HermesExecutorFactory() else JSCExecutorFactory(
appName,
deviceName
)
}
private fun parseHermesBundleHeader(jsBundlePath: String?): Pair<Boolean, Int> {
if (jsBundlePath == null || jsBundlePath.isEmpty()) {
return Pair(false, 0)
}
// https://github.com/facebook/hermes/blob/release-v0.5/include/hermes/BCGen/HBC/BytecodeFileFormat.h#L24-L25
val HERMES_MAGIC_HEADER = byteArrayOf(
0xc6.toByte(), 0x1f.toByte(), 0xbc.toByte(), 0x03.toByte(),
0xc1.toByte(), 0x03.toByte(), 0x19.toByte(), 0x1f.toByte()
)
val file = File(jsBundlePath)
try {
FileInputStream(file).use { inputStream ->
val bytes = ByteArray(12)
inputStream.read(bytes, 0, bytes.size)
// Magic header
for (i in HERMES_MAGIC_HEADER.indices) {
if (bytes[i] != HERMES_MAGIC_HEADER[i]) {
return Pair(false, 0)
}
}
// Bytecode version
val bundleBytecodeVersion: Int =
(bytes[11].toInt() shl 24) or (bytes[10].toInt() shl 16) or (bytes[9].toInt() shl 8) or bytes[8].toInt()
return Pair(true, bundleBytecodeVersion)
}
} catch (e: FileNotFoundException) {
} catch (e: IOException) {
}
return Pair(false, 0)
}
internal fun isHermesBundle(jsBundlePath: String?): Boolean {
return parseHermesBundleHeader(jsBundlePath).first
}
internal fun getHermesBundleBytecodeVersion(jsBundlePath: String?): Int {
return parseHermesBundleHeader(jsBundlePath).second
}
}
| bsd-3-clause | 892eb71e6739b8409fb31856eabe93e2 | 37.750733 | 146 | 0.712275 | 5.328226 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/runconfig/buildtool/CargoBuildContext.kt | 2 | 5344 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig.buildtool
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolderEx
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.runconfig.RsExecutableRunner.Companion.artifacts
import org.rust.cargo.runconfig.buildtool.CargoBuildManager.showBuildNotification
import org.rust.cargo.runconfig.command.workingDirectory
import org.rust.cargo.toolchain.impl.CompilerArtifactMessage
import java.nio.file.Path
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
abstract class CargoBuildContextBase(
val cargoProject: CargoProject,
val progressTitle: String,
val isTestBuild: Boolean,
val buildId: Any,
val parentId: Any
) {
val project: Project get() = cargoProject.project
val workingDirectory: Path get() = cargoProject.workingDirectory
@Volatile
var indicator: ProgressIndicator? = null
val errors: AtomicInteger = AtomicInteger()
val warnings: AtomicInteger = AtomicInteger()
@Volatile
var artifacts: List<CompilerArtifactMessage> = emptyList()
}
class CargoBuildContext(
cargoProject: CargoProject,
val environment: ExecutionEnvironment,
val taskName: String,
progressTitle: String,
isTestBuild: Boolean,
buildId: Any,
parentId: Any
) : CargoBuildContextBase(cargoProject, progressTitle, isTestBuild, buildId, parentId) {
@Volatile
var processHandler: ProcessHandler? = null
private val buildSemaphore: Semaphore = project.getUserData(BUILD_SEMAPHORE_KEY)
?: (project as UserDataHolderEx).putUserDataIfAbsent(BUILD_SEMAPHORE_KEY, Semaphore(1))
val result: CompletableFuture<CargoBuildResult> = CompletableFuture()
val started: Long = System.currentTimeMillis()
@Volatile
var finished: Long = started
private val duration: Long get() = finished - started
fun waitAndStart(): Boolean {
indicator?.pushState()
try {
indicator?.text = "Waiting for the current build to finish..."
indicator?.text2 = ""
while (true) {
indicator?.checkCanceled()
try {
if (buildSemaphore.tryAcquire(100, TimeUnit.MILLISECONDS)) break
} catch (e: InterruptedException) {
throw ProcessCanceledException()
}
}
} catch (e: ProcessCanceledException) {
canceled()
return false
} finally {
indicator?.popState()
}
return true
}
fun finished(isSuccess: Boolean) {
val isCanceled = indicator?.isCanceled ?: false
environment.artifacts = artifacts.takeIf { isSuccess && !isCanceled }
finished = System.currentTimeMillis()
buildSemaphore.release()
val finishMessage: String
val finishDetails: String?
val errors = errors.get()
val warnings = warnings.get()
// We report successful builds with errors or warnings correspondingly
val messageType = if (isCanceled) {
finishMessage = "$taskName canceled"
finishDetails = null
MessageType.INFO
} else {
val hasWarningsOrErrors = errors > 0 || warnings > 0
finishMessage = if (isSuccess) "$taskName finished" else "$taskName failed"
finishDetails = if (hasWarningsOrErrors) {
val errorsString = if (errors == 1) "error" else "errors"
val warningsString = if (warnings == 1) "warning" else "warnings"
"$errors $errorsString and $warnings $warningsString"
} else {
null
}
when {
!isSuccess -> MessageType.ERROR
hasWarningsOrErrors -> MessageType.WARNING
else -> MessageType.INFO
}
}
result.complete(CargoBuildResult(
succeeded = isSuccess,
canceled = isCanceled,
started = started,
duration = duration,
errors = errors,
warnings = warnings,
message = finishMessage
))
showBuildNotification(project, messageType, finishMessage, finishDetails, duration)
}
fun canceled() {
finished = System.currentTimeMillis()
result.complete(CargoBuildResult(
succeeded = false,
canceled = true,
started = started,
duration = duration,
errors = errors.get(),
warnings = warnings.get(),
message = "$taskName canceled"
))
environment.notifyProcessNotStarted()
}
companion object {
private val BUILD_SEMAPHORE_KEY: Key<Semaphore> = Key.create("BUILD_SEMAPHORE_KEY")
}
}
| mit | 0a0189eff5e99cbb38c9062a9a271aec | 32.192547 | 95 | 0.652695 | 5.158301 | false | false | false | false |
erva/CellAdapter | sample-x-kotlin/src/main/kotlin/io/erva/sample/DividerItemDecoration.kt | 1 | 3197 | package io.erva.sample
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.annotation.DrawableRes
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class DividerItemDecoration : RecyclerView.ItemDecoration {
private var divider: Drawable? = null
constructor(context: Context) {
val a = context.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider))
divider = a.getDrawable(0)
a.recycle()
}
constructor(divider: Drawable) {
this.divider = divider
}
constructor(context: Context, @DrawableRes drawableId: Int) {
divider = ResourcesCompat.getDrawable(context.resources, drawableId, null)
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
if (divider == null) return
if (parent.getChildAdapterPosition(view) < 1) return
if (getOrientation(parent) == LinearLayoutManager.VERTICAL)
outRect.top = divider!!.intrinsicHeight
else
outRect.left = divider!!.intrinsicWidth
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (divider == null) {
super.onDrawOver(c, parent, state)
return
}
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 1..childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val size = divider!!.intrinsicHeight
val top = child.top - params.topMargin
val bottom = top + size
divider!!.setBounds(left, top, right, bottom)
divider!!.draw(c)
}
} else { //horizontal
val top = parent.paddingTop
val bottom = parent.height - parent.paddingBottom
val childCount = parent.childCount
for (i in 1..childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val size = divider!!.intrinsicWidth
val left = child.left - params.leftMargin
val right = left + size
divider!!.setBounds(left, top, right, bottom)
divider!!.draw(c)
}
}
}
private fun getOrientation(parent: RecyclerView): Int {
if (parent.layoutManager is LinearLayoutManager) {
val layoutManager = parent.layoutManager as LinearLayoutManager
return layoutManager.orientation
} else
throw IllegalStateException("DividerItemDecoration can only be used with a LinearLayoutManager.")
}
} | mit | 4e0c45713bc931b9f9423f60a5a07447 | 36.186047 | 109 | 0.637785 | 5.249589 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/model/Informacion.kt | 1 | 568 | package com.quijotelui.model
import org.hibernate.annotations.Immutable
import java.io.Serializable
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Immutable
@Table(name = "v_ele_informaciones")
class Informacion : Serializable {
@Id
@Column(name = "id")
var id : Long? = null
@Column(name = "documento")
var documento : String? = null
@Column(name = "nombre")
var nombre : String? = null
@Column(name = "valor")
var valor : String? = null
} | gpl-3.0 | 751dc5a243f6b83bd43b859b95a62655 | 19.321429 | 42 | 0.702465 | 3.688312 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/guilds/GuildDetailFragment.kt | 1 | 9039 | package com.habitrpg.android.habitica.ui.fragments.social.guilds
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.habitrpg.android.habitica.MainNavDirections
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ChallengeRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.databinding.FragmentGuildDetailBinding
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.social.Challenge
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.modules.AppModule
import com.habitrpg.android.habitica.ui.activities.GroupInviteActivity
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import com.habitrpg.android.habitica.ui.helpers.setMarkdown
import com.habitrpg.android.habitica.ui.viewmodels.GroupViewModel
import com.habitrpg.android.habitica.ui.views.HabiticaIcons
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.SnackbarActivity
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Named
class GuildDetailFragment : BaseFragment<FragmentGuildDetailBinding>() {
@Inject
lateinit var configManager: AppConfigManager
override var binding: FragmentGuildDetailBinding? = null
@Inject
lateinit var challengeRepository: ChallengeRepository
@Inject
lateinit var userRepository: UserRepository
@field:[Inject Named(AppModule.NAMED_USER_ID)]
lateinit var userId: String
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentGuildDetailBinding {
return FragmentGuildDetailBinding.inflate(inflater, container, false)
}
var viewModel: GroupViewModel? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.refreshLayout?.setOnRefreshListener { this.refresh() }
viewModel?.getGroupData()?.observe(viewLifecycleOwner, { updateGuild(it) })
viewModel?.getLeaderData()?.observe(viewLifecycleOwner, { setLeader(it) })
viewModel?.getIsMemberData()?.observe(viewLifecycleOwner, { updateMembership(it) })
binding?.guildDescription?.movementMethod = LinkMovementMethod.getInstance()
binding?.guildBankIcon?.setImageBitmap(HabiticaIconsHelper.imageOfGem())
binding?.leaveButton?.setOnClickListener {
leaveGuild()
}
binding?.joinButton?.setOnClickListener {
viewModel?.joinGroup {
(this.activity as? SnackbarActivity)?.showSnackbar(title = getString(R.string.joined_guild))
}
}
binding?.inviteButton?.setOnClickListener {
val intent = Intent(activity, GroupInviteActivity::class.java)
sendInvitesResult.launch(intent)
}
binding?.leaderWrapper?.setOnClickListener {
viewModel?.leaderID?.let { leaderID ->
val profileDirections = MainNavDirections.openProfileActivity(leaderID)
MainNavigationController.navigate(profileDirections)
}
}
}
private fun setLeader(leader: Member?) {
if (leader == null) {
return
}
binding?.leaderAvatarView?.setAvatar(leader)
binding?.leaderProfileName?.username = leader.displayName
binding?.leaderProfileName?.tier = leader.contributor?.level ?: 0
binding?.leaderUsername?.text = leader.formattedUsername
}
private fun updateMembership(isMember: Boolean?) {
binding?.joinButton?.visibility = if (isMember == true) View.GONE else View.VISIBLE
binding?.leaveButton?.visibility = if (isMember == true) View.VISIBLE else View.GONE
}
private val sendInvitesResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
val inviteData = HashMap<String, Any>()
inviteData["inviter"] = viewModel?.user?.value?.profile?.name ?: ""
val emails = it.data?.getStringArrayExtra(GroupInviteActivity.EMAILS_KEY)
if (emails != null && emails.isNotEmpty()) {
val invites = ArrayList<HashMap<String, String>>()
emails.forEach { email ->
val invite = HashMap<String, String>()
invite["name"] = ""
invite["email"] = email
invites.add(invite)
}
inviteData["emails"] = invites
}
val userIDs = it.data?.getStringArrayExtra(GroupInviteActivity.USER_IDS_KEY)
if (userIDs != null && userIDs.isNotEmpty()) {
val invites = ArrayList<String>()
userIDs.forEach { invites.add(it) }
inviteData["usernames"] = invites
}
viewModel?.inviteToGroup(inviteData)
}
}
private fun refresh() {
viewModel?.retrieveGroup {
binding?.refreshLayout?.isRefreshing = false
}
}
private fun getGroupChallenges(): List<Challenge> {
val groupChallenges = mutableListOf<Challenge>()
userRepository.getUser(userId).forEach {
it.challenges?.forEach {
challengeRepository.getChallenge(it.challengeID).forEach {
if (it.groupId.equals(viewModel?.groupID)) {
groupChallenges.add(it)
}
}
}
}
return groupChallenges
}
internal fun leaveGuild() {
val context = context
if (context != null) {
val groupChallenges = getGroupChallenges()
lifecycleScope.launch(Dispatchers.Main) {
delay(500)
if (groupChallenges.isNotEmpty()) {
val alert = HabiticaAlertDialog(context)
alert.setTitle(R.string.guild_challenges)
alert.setMessage(R.string.leave_guild_challenges_confirmation)
alert.addButton(R.string.keep_challenges, true) { _, _ ->
viewModel?.leaveGroup(groupChallenges, true) { showLeaveSnackbar() }
}
alert.addButton(R.string.leave_challenges_delete_tasks, isPrimary = false, isDestructive = true) { _, _ ->
viewModel?.leaveGroup(groupChallenges, false) { showLeaveSnackbar() }
}
alert.setExtraCloseButtonVisibility(View.VISIBLE)
alert.show()
} else {
val alert = HabiticaAlertDialog(context)
alert.setTitle(R.string.leave_guild_confirmation)
alert.setMessage(R.string.rejoin_guild)
alert.addButton(R.string.leave, isPrimary = true, isDestructive = true) { _, _ ->
viewModel?.leaveGroup(groupChallenges, false) {
showLeaveSnackbar()
}
}
alert.setExtraCloseButtonVisibility(View.VISIBLE)
alert.show()
}
}
}
}
private fun showLeaveSnackbar() {
(this.activity as? MainActivity)?.showSnackbar(title = getString(R.string.left_guild))
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun updateGuild(guild: Group?) {
binding?.titleView?.text = guild?.name
binding?.guildMembersIcon?.setImageBitmap(HabiticaIcons.imageOfGuildCrestMedium((guild?.memberCount ?: 0).toFloat()))
binding?.guildMembersText?.text = guild?.memberCount.toString()
binding?.guildBankText?.text = guild?.gemCount.toString()
binding?.guildSummary?.setMarkdown(guild?.summary)
binding?.guildDescription?.setMarkdown(guild?.description)
}
companion object {
fun newInstance(viewModel: GroupViewModel?): GuildDetailFragment {
val args = Bundle()
val fragment = GuildDetailFragment()
fragment.arguments = args
fragment.viewModel = viewModel
return fragment
}
}
}
| gpl-3.0 | 6a91e0c25bdd54b64202eddc30e0f561 | 41.43662 | 126 | 0.658591 | 5.332743 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/ConversationSettingsRepository.kt | 1 | 7703 | package org.thoughtcrime.securesms.components.settings.conversation
import android.content.Context
import android.database.Cursor
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.signal.core.util.concurrent.SignalExecutors
import org.signal.core.util.logging.Log
import org.signal.storageservice.protos.groups.local.DecryptedGroup
import org.signal.storageservice.protos.groups.local.DecryptedPendingMember
import org.thoughtcrime.securesms.contacts.sync.ContactDiscovery
import org.thoughtcrime.securesms.database.GroupDatabase
import org.thoughtcrime.securesms.database.MediaDatabase
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.model.IdentityRecord
import org.thoughtcrime.securesms.database.model.StoryViewState
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.groups.GroupId
import org.thoughtcrime.securesms.groups.GroupProtoUtil
import org.thoughtcrime.securesms.groups.LiveGroup
import org.thoughtcrime.securesms.groups.v2.GroupAddMembersResult
import org.thoughtcrime.securesms.groups.v2.GroupManagementRepository
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.recipients.RecipientUtil
import org.thoughtcrime.securesms.util.FeatureFlags
import java.io.IOException
import java.util.Optional
private val TAG = Log.tag(ConversationSettingsRepository::class.java)
class ConversationSettingsRepository(
private val context: Context,
private val groupManagementRepository: GroupManagementRepository = GroupManagementRepository(context)
) {
@WorkerThread
fun getThreadMedia(threadId: Long): Optional<Cursor> {
return if (threadId <= 0) {
Optional.empty()
} else {
Optional.of(SignalDatabase.media.getGalleryMediaForThread(threadId, MediaDatabase.Sorting.Newest))
}
}
fun getStoryViewState(groupId: GroupId): Observable<StoryViewState> {
return Observable.fromCallable {
SignalDatabase.recipients.getByGroupId(groupId)
}.flatMap {
StoryViewState.getForRecipientId(it.get())
}.observeOn(Schedulers.io())
}
fun getThreadId(recipientId: RecipientId, consumer: (Long) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(SignalDatabase.threads.getThreadIdIfExistsFor(recipientId))
}
}
fun getThreadId(groupId: GroupId, consumer: (Long) -> Unit) {
SignalExecutors.BOUNDED.execute {
val recipientId = Recipient.externalGroupExact(groupId).id
consumer(SignalDatabase.threads.getThreadIdIfExistsFor(recipientId))
}
}
fun isInternalRecipientDetailsEnabled(): Boolean = SignalStore.internalValues().recipientDetails()
fun hasGroups(consumer: (Boolean) -> Unit) {
SignalExecutors.BOUNDED.execute { consumer(SignalDatabase.groups.activeGroupCount > 0) }
}
fun getIdentity(recipientId: RecipientId, consumer: (IdentityRecord?) -> Unit) {
SignalExecutors.BOUNDED.execute {
if (SignalStore.account().aci != null && SignalStore.account().pni != null) {
consumer(ApplicationDependencies.getProtocolStore().aci().identities().getIdentityRecord(recipientId).orElse(null))
} else {
consumer(null)
}
}
}
fun getGroupsInCommon(recipientId: RecipientId, consumer: (List<Recipient>) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(
SignalDatabase
.groups
.getPushGroupsContainingMember(recipientId)
.asSequence()
.filter { it.members.contains(Recipient.self().id) }
.map(GroupDatabase.GroupRecord::getRecipientId)
.map(Recipient::resolved)
.sortedBy { gr -> gr.getDisplayName(context) }
.toList()
)
}
}
fun getGroupMembership(recipientId: RecipientId, consumer: (List<RecipientId>) -> Unit) {
SignalExecutors.BOUNDED.execute {
val groupDatabase = SignalDatabase.groups
val groupRecords = groupDatabase.getPushGroupsContainingMember(recipientId)
val groupRecipients = ArrayList<RecipientId>(groupRecords.size)
for (groupRecord in groupRecords) {
groupRecipients.add(groupRecord.recipientId)
}
consumer(groupRecipients)
}
}
fun refreshRecipient(recipientId: RecipientId) {
SignalExecutors.UNBOUNDED.execute {
try {
ContactDiscovery.refresh(context, Recipient.resolved(recipientId), false)
} catch (e: IOException) {
Log.w(TAG, "Failed to refresh user after adding to contacts.")
}
}
}
fun setMuteUntil(recipientId: RecipientId, until: Long) {
SignalExecutors.BOUNDED.execute {
SignalDatabase.recipients.setMuted(recipientId, until)
}
}
fun getGroupCapacity(groupId: GroupId, consumer: (GroupCapacityResult) -> Unit) {
SignalExecutors.BOUNDED.execute {
val groupRecord: GroupDatabase.GroupRecord = SignalDatabase.groups.getGroup(groupId).get()
consumer(
if (groupRecord.isV2Group) {
val decryptedGroup: DecryptedGroup = groupRecord.requireV2GroupProperties().decryptedGroup
val pendingMembers: List<RecipientId> = decryptedGroup.pendingMembersList
.map(DecryptedPendingMember::getUuid)
.map(GroupProtoUtil::uuidByteStringToRecipientId)
val members = mutableListOf<RecipientId>()
members.addAll(groupRecord.members)
members.addAll(pendingMembers)
GroupCapacityResult(Recipient.self().id, members, FeatureFlags.groupLimits(), groupRecord.isAnnouncementGroup)
} else {
GroupCapacityResult(Recipient.self().id, groupRecord.members, FeatureFlags.groupLimits(), false)
}
)
}
}
fun addMembers(groupId: GroupId, selected: List<RecipientId>, consumer: (GroupAddMembersResult) -> Unit) {
groupManagementRepository.addMembers(groupId, selected, consumer)
}
fun setMuteUntil(groupId: GroupId, until: Long) {
SignalExecutors.BOUNDED.execute {
val recipientId = Recipient.externalGroupExact(groupId).id
SignalDatabase.recipients.setMuted(recipientId, until)
}
}
fun block(recipientId: RecipientId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.resolved(recipientId)
if (recipient.isGroup) {
RecipientUtil.block(context, recipient)
} else {
RecipientUtil.blockNonGroup(context, recipient)
}
}
}
fun unblock(recipientId: RecipientId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.resolved(recipientId)
RecipientUtil.unblock(recipient)
}
}
fun block(groupId: GroupId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.externalGroupExact(groupId)
RecipientUtil.block(context, recipient)
}
}
fun unblock(groupId: GroupId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.externalGroupExact(groupId)
RecipientUtil.unblock(recipient)
}
}
@WorkerThread
fun isMessageRequestAccepted(recipient: Recipient): Boolean {
return RecipientUtil.isMessageRequestAccepted(context, recipient)
}
fun getMembershipCountDescription(liveGroup: LiveGroup): LiveData<String> {
return liveGroup.getMembershipCountDescription(context.resources)
}
fun getExternalPossiblyMigratedGroupRecipientId(groupId: GroupId, consumer: (RecipientId) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(Recipient.externalPossiblyMigratedGroup(groupId).id)
}
}
}
| gpl-3.0 | 83aae793df0c20e1f2f3cf9e2c4d9d78 | 35.680952 | 123 | 0.746333 | 4.654381 | false | false | false | false |
SimpleMobileTools/Simple-Notes | app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/MyMovementMethod.kt | 1 | 1769 | package com.simplemobiletools.notes.pro.helpers
import android.text.Selection
import android.text.Spannable
import android.text.method.ArrowKeyMovementMethod
import android.text.style.ClickableSpan
import android.view.MotionEvent
import android.widget.TextView
class MyMovementMethod : ArrowKeyMovementMethod() {
companion object {
private var sInstance: MyMovementMethod? = null
fun getInstance(): MyMovementMethod {
if (sInstance == null) {
sInstance = MyMovementMethod()
}
return sInstance!!
}
}
override fun onTouchEvent(widget: TextView, buffer: Spannable, event: MotionEvent): Boolean {
val action = event.action
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
var x = event.x.toInt()
var y = event.y.toInt()
x -= widget.totalPaddingLeft
y -= widget.totalPaddingTop
x += widget.scrollX
y += widget.scrollY
val layout = widget.layout
val line = layout.getLineForVertical(y)
val off = layout.getOffsetForHorizontal(line, x.toFloat())
val links = buffer.getSpans(off, off, ClickableSpan::class.java)
if (links.isNotEmpty()) {
if (action == MotionEvent.ACTION_UP) {
links[0].onClick(widget)
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer,
buffer.getSpanStart(links[0]),
buffer.getSpanEnd(links[0]))
}
return true
}
}
return super.onTouchEvent(widget, buffer, event)
}
}
| gpl-3.0 | cd568c77e0de56b4c65a6e743cda3263 | 31.759259 | 97 | 0.582815 | 4.969101 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/overrideImplement/KotlinOverrideMembersAction.kt | 1 | 7548 | /*******************************************************************************
* Copyright 2000-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.kotlin.ui.overrideImplement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.SmartList
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds
import org.eclipse.jdt.ui.actions.SelectionDispatchAction
import org.eclipse.jface.text.ITextSelection
import org.eclipse.jface.window.Window
import org.eclipse.ui.PlatformUI
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.ui.editors.KotlinCommonEditor
import org.jetbrains.kotlin.ui.editors.quickassist.KotlinImplementMethodsProposal
import org.jetbrains.kotlin.ui.editors.quickassist.resolveToDescriptor
import java.util.LinkedHashMap
import java.util.LinkedHashSet
public class KotlinOverrideMembersAction(
val editor: KotlinCommonEditor,
val filterMembersFromAny: Boolean = false) : SelectionDispatchAction(editor.getSite()) {
init {
setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS)
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION)
val overrideImplementText = "Override/Implement Members"
setText(overrideImplementText)
setDescription("Override or implement members declared in supertypes")
setToolTipText(overrideImplementText)
}
val membersFromAny = listOf("equals", "hashCode", "toString")
companion object {
val ACTION_ID = "OverrideMethods"
}
override fun run(selection: ITextSelection) {
val jetClassOrObject = getKtClassOrObject(selection)
if (jetClassOrObject == null) return
val generatedMembers = collectMembersToGenerate(jetClassOrObject)
val selectedMembers = if (filterMembersFromAny) {
generatedMembers.filterNot { it.getName().asString() in membersFromAny }
} else {
showDialog(generatedMembers)
}
if (selectedMembers.isEmpty()) return
KotlinImplementMethodsProposal(editor).generateMethods(editor.document, jetClassOrObject, selectedMembers.toSet())
}
private fun getKtClassOrObject(selection: ITextSelection): KtClassOrObject? {
val psiElement = EditorUtil.getPsiElement(editor, selection.getOffset())
return if (psiElement != null) {
PsiTreeUtil.getNonStrictParentOfType(psiElement, KtClassOrObject::class.java)
} else {
null
}
}
private fun showDialog(descriptors: Set<CallableMemberDescriptor>): Set<CallableMemberDescriptor> {
val shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()
val types = descriptors.map { it.getContainingDeclaration() as ClassDescriptor }.toSet()
val dialog = CheckedTreeSelectionDialog(shell,
KotlinCallableLabelProvider(),
KotlinCallableContentProvider(descriptors, types))
dialog.setTitle("Override/Implement members")
dialog.setContainerMode(true)
dialog.setExpandedElements(types.toTypedArray())
dialog.setInput(Any()) // Initialize input
if (dialog.open() != Window.OK) {
return emptySet()
}
val selected = dialog.getResult()?.filterIsInstance(CallableMemberDescriptor::class.java)
return selected?.toSet() ?: emptySet()
}
private fun collectMembersToGenerate(classOrObject: KtClassOrObject): Set<CallableMemberDescriptor> {
val descriptor = classOrObject.resolveToDescriptor()
if (descriptor !is ClassDescriptor) return emptySet()
val result = LinkedHashSet<CallableMemberDescriptor>()
for (member in descriptor.unsubstitutedMemberScope.getContributedDescriptors()) {
if (member is CallableMemberDescriptor
&& (member.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE || member.kind == CallableMemberDescriptor.Kind.DELEGATION)) {
val overridden = member.overriddenDescriptors
if (overridden.any { it.modality == Modality.FINAL || Visibilities.isPrivate(it.visibility.normalize()) }) continue
class Data(
val realSuper: CallableMemberDescriptor,
val immediateSupers: MutableList<CallableMemberDescriptor> = SmartList()
)
val byOriginalRealSupers = LinkedHashMap<CallableMemberDescriptor, Data>()
for (immediateSuper in overridden) {
for (realSuper in toRealSupers(immediateSuper)) {
byOriginalRealSupers.getOrPut(realSuper.original) { Data(realSuper) }.immediateSupers.add(immediateSuper)
}
}
val realSupers = byOriginalRealSupers.values.map { it.realSuper }
val nonAbstractRealSupers = realSupers.filter { it.modality != Modality.ABSTRACT }
val realSupersToUse = if (nonAbstractRealSupers.isNotEmpty()) {
nonAbstractRealSupers
}
else {
listOf(realSupers.first())
}
for (realSuper in realSupersToUse) {
val immediateSupers = byOriginalRealSupers[realSuper.original]!!.immediateSupers
assert(immediateSupers.isNotEmpty())
val immediateSuperToUse = if (immediateSupers.size == 1) {
immediateSupers.single()
}
else {
immediateSupers.singleOrNull { (it.containingDeclaration as? ClassDescriptor)?.kind == ClassKind.CLASS } ?: immediateSupers.first()
}
result.add(immediateSuperToUse)
}
}
}
return result
}
private fun toRealSupers(immediateSuper: CallableMemberDescriptor): Collection<CallableMemberDescriptor> {
if (immediateSuper.kind != CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
return listOf(immediateSuper)
}
val overridden = immediateSuper.overriddenDescriptors
assert(overridden.isNotEmpty())
return overridden.flatMap { toRealSupers(it) }.distinctBy { it.original }
}
} | apache-2.0 | f11a455306d3ba6633321fb24f540cc5 | 44.203593 | 155 | 0.66309 | 5.641256 | false | false | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/commands/sc/SCKills.kt | 1 | 1916 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands.sc
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.commands.ResponseBuilder
import com.demonwav.statcraft.querydsl.QKills
import com.demonwav.statcraft.querydsl.QPlayers
import org.bukkit.command.CommandSender
import java.sql.Connection
class SCKills(plugin: StatCraft) : SCTemplate(plugin) {
init {
plugin.baseCommand.registerCommand("kills", this)
}
override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.kills")
override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String {
val id = getId(name) ?: return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Kills" }
stats["Total"] = "0"
}
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val k = QKills.kills
val result = query.from(k).where(k.id.eq(id)).uniqueResult(k.amount.sum()) ?: 0
return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Kills" }
stats["Total"] = df.format(result)
}
}
override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String {
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val k = QKills.kills
val p = QPlayers.players
val list = query
.from(k)
.innerJoin(p)
.on(k.id.eq(p.id))
.groupBy(p.name)
.orderBy(k.amount.sum().desc())
.limit(num)
.list(p.name, k.amount.sum())
return topListResponse("Kills", list)
}
}
| mit | de83bc260796465d1ba122bbbb856905 | 29.412698 | 126 | 0.637265 | 4.102784 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/debug/commands/KotlinStepIntoSelectionHandler.kt | 1 | 4314 | /*******************************************************************************
* Copyright 2000-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.kotlin.ui.debug.commands
import org.eclipse.core.commands.AbstractHandler
import org.eclipse.core.commands.ExecutionEvent
import org.eclipse.ui.handlers.HandlerUtil
import org.jetbrains.kotlin.ui.editors.KotlinFileEditor
import org.eclipse.jface.text.ITextSelection
import org.eclipse.jdt.internal.debug.ui.EvaluationContextManager
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil
import org.jetbrains.kotlin.core.references.getReferenceExpression
import org.jetbrains.kotlin.core.references.resolveToSourceElements
import org.jetbrains.kotlin.core.references.createReferences
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.core.resolve.lang.java.resolver.EclipseJavaSourceElement
import org.jetbrains.kotlin.core.model.sourceElementsToLightElements
import org.eclipse.jdt.core.IJavaElement
import org.eclipse.jdt.debug.core.IJavaStackFrame
import org.eclipse.jdt.internal.debug.ui.actions.StepIntoSelectionHandler
import org.eclipse.jdt.debug.core.IJavaThread
import org.eclipse.jdt.core.IMethod
import org.jetbrains.kotlin.ui.debug.findTopmostType
import org.eclipse.jdt.internal.debug.ui.actions.StepIntoSelectionUtils
import org.eclipse.ui.IEditorPart
import org.eclipse.debug.core.model.IThread
import org.jetbrains.kotlin.core.log.KotlinLogger
import org.eclipse.jdt.core.IType
public class KotlinStepIntoSelectionHandler : AbstractHandler() {
override fun execute(event: ExecutionEvent): Any? {
val editor = HandlerUtil.getActiveEditor(event) as KotlinFileEditor
val selection = editor.getEditorSite().getSelectionProvider().getSelection()
if (selection is ITextSelection) {
stepIntoSelection(editor, selection)
}
return null
}
}
private fun stepIntoSelection(editor: KotlinFileEditor, selection: ITextSelection) {
val frame = EvaluationContextManager.getEvaluationContext(editor)
if (frame == null || !frame.isSuspended()) return
val psiElement = EditorUtil.getPsiElement(editor, selection.getOffset())
if (psiElement == null) return
val expression = getReferenceExpression(psiElement)
if (expression == null) return
val sourceElements = createReferences(expression).resolveToSourceElements()
val javaElements = sourceElementsToLightElements(sourceElements)
if (javaElements.size > 1) {
KotlinLogger.logWarning("There are more than one java element for $sourceElements")
return
}
val element = javaElements.first()
val method = when (element) {
is IMethod -> element
is IType -> element.getMethod(element.elementName, emptyArray())
else -> null
} ?: return
stepIntoElement(method, frame, selection, editor)
}
private fun stepIntoElement(method: IMethod, frame: IJavaStackFrame, selection: ITextSelection, editor: KotlinFileEditor) {
if (selection.getStartLine() + 1 == frame.getLineNumber()) {
val handler = StepIntoSelectionHandler(frame.getThread() as IJavaThread, frame, method)
handler.step()
} else {
val refMethod = StepIntoSelectionUtils::class.java.getDeclaredMethod(
"runToLineBeforeStepIn",
IEditorPart::class.java,
String::class.java,
ITextSelection::class.java,
IThread::class.java,
IMethod::class.java)
refMethod.setAccessible(true)
refMethod.invoke(null, editor, frame.getReceivingTypeName(), selection, frame.getThread(), method)
}
} | apache-2.0 | b3ee154ea8c7786a58d50beded519676 | 43.030612 | 123 | 0.721372 | 4.628755 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/color/ElmColorSettingsPage.kt | 1 | 2511 | package org.elm.ide.color
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import org.elm.ide.highlight.ElmSyntaxHighlighter
import org.elm.ide.icons.ElmIcons
class ElmColorSettingsPage : ColorSettingsPage {
private val ATTRS = ElmColor.values().map { it.attributesDescriptor }.toTypedArray()
override fun getDisplayName() =
"Elm"
override fun getIcon() =
ElmIcons.FILE
override fun getAttributeDescriptors() =
ATTRS
override fun getColorDescriptors(): Array<ColorDescriptor> =
ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter() =
ElmSyntaxHighlighter()
override fun getAdditionalHighlightingTagToDescriptorMap() =
// special tags in [demoText] for semantic highlighting
mapOf(
"type" to ElmColor.TYPE_EXPR,
"variant" to ElmColor.UNION_VARIANT,
"accessor" to ElmColor.RECORD_FIELD_ACCESSOR,
"field" to ElmColor.RECORD_FIELD,
"func_decl" to ElmColor.DEFINITION_NAME
).mapValues { it.value.textAttributesKey }
override fun getDemoText() =
demoCodeText
}
private const val demoCodeText = """
module Todo exposing (..)
import Html exposing (div, h1, ul, li, text)
-- a single line comment
type alias Model =
{ <field>page</field> : <type>Int</type>
, <field>title</field> : <type>String</type>
, <field>stepper</field> : <type>Int</type> -> <type>Int</type>
}
type Msg <type>a</type>
= <variant>ModeA</variant>
| <variant>ModeB</variant> <type>Maybe a</type>
<func_decl>update</func_decl> : <type>Msg</type> -> <type>Model</type> -> ( <type>Model</type>, <type>Cmd Msg</type> )
<func_decl>update</func_decl> msg model =
case msg of
<variant>ModeA</variant> ->
{ model
| <field>page</field> = 0
, <field>title</field> = "Mode A"
, <field>stepper</field> = (\k -> k + 1)
}
! []
<func_decl>view</func_decl> : <type>Model</type> -> <type>Html.Html Msg</type>
<func_decl>view</func_decl> model =
let
<func_decl>itemify</func_decl> label =
li [] [ text label ]
in
div []
[ h1 [] [ text "Chapter One" ]
, ul []
(List.map <accessor>.value</accessor> model.<field>items</field>)
]
"""
| mit | 70221003161e3bbab49b491c38d7861a | 30.3875 | 118 | 0.593389 | 4.011182 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/translations/intentions/RemoveDuplicatesIntention.kt | 1 | 1393 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.intentions
import com.demonwav.mcdev.translations.Translation
import com.demonwav.mcdev.translations.TranslationFiles
import com.demonwav.mcdev.translations.index.TranslationInverseIndex
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
class RemoveDuplicatesIntention(private val translation: Translation) : PsiElementBaseIntentionAction() {
override fun getText() = "Remove duplicates (keep this translation)"
override fun getFamilyName() = "Minecraft localization"
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement) = true
override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
val keep = TranslationFiles.seekTranslation(element) ?: return
val entries = TranslationInverseIndex.findElements(
translation.key,
GlobalSearchScope.fileScope(element.containingFile)
)
for (other in entries) {
if (other !== keep) {
TranslationFiles.remove(other)
}
}
}
}
| mit | ab42f15c2b092b6d070d5160f099ef01 | 32.97561 | 105 | 0.735104 | 4.836806 | false | false | false | false |
rosenpin/QuickDrawEverywhere | app/src/main/java/com/tomer/draw/utils/AndroidMethods.kt | 1 | 3653 | package com.tomer.draw.utils
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.view.View
import android.view.ViewAnimationUtils
import android.widget.Toast
import com.tomer.draw.R
/**
* DrawEverywhere
* Created by Tomer Rosenfeld on 7/28/17.
*/
fun Context.isAndroidNewerThan(version: Int): Boolean = Build.VERSION.SDK_INT >= version
fun Context.hasPermissions(vararg permissions: String): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return true
return permissions.none { checkSelfPermission(it) == PackageManager.PERMISSION_DENIED }
}
fun View.circularRevealHide(cx: Int = width / 2, cy: Int = height / 2, radius: Float = -1f, action: Runnable? = null) {
if (context.isAndroidNewerThan(Build.VERSION_CODES.LOLLIPOP)) {
val finalRadius =
if (radius == -1f)
Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()
else
radius
val anim = ViewAnimationUtils
.createCircularReveal(this, cx, cy, finalRadius, 0f)
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
action?.run()
}
})
anim.interpolator = FastOutSlowInInterpolator()
anim.start()
} else {
val fadeOut = ObjectAnimator.ofFloat(this, "alpha", 1f, .1f)
fadeOut.duration = 300
fadeOut.addListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) {
}
override fun onAnimationEnd(animation: Animator?) {
action?.run()
}
override fun onAnimationCancel(animation: Animator?) {
}
override fun onAnimationStart(animation: Animator?) {
}
})
fadeOut.start()
}
}
fun View.circularRevealShow(cx: Int = width / 2, cy: Int = height / 2, radius: Float = -1f) {
post {
if (context.isAndroidNewerThan(Build.VERSION_CODES.LOLLIPOP)) {
val finalRadius =
if (radius == -1f)
Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()
else
radius
val anim = ViewAnimationUtils.createCircularReveal(this, cx, cy, 0f, finalRadius)
anim.interpolator = FastOutSlowInInterpolator()
anim.start()
} else {
val fadeIn = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f)
fadeIn.duration = 300
fadeIn.start()
}
}
}
fun Activity.askPermissionNoCallBack(vararg permissions: String) {
ActivityCompat.requestPermissions(this, permissions, 22)
}
fun Activity.askDrawOverPermission() {
val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + packageName))
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
if (doesIntentExist(intent)) {
startActivity(intent)
} else {
Toast.makeText(this, R.string.error_1_open_draw_over, Toast.LENGTH_LONG).show()
}
}
fun Context.doesIntentExist(intent: Intent): Boolean {
val mgr = packageManager
val list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return list.size > 0
}
fun Context.canDrawOverlaysCompat(): Boolean {
if (isAndroidNewerThan(Build.VERSION_CODES.M))
return Settings.canDrawOverlays(this)
return true
}
fun Context.safeUnregisterReceiver(receiver: BroadcastReceiver) {
try {
unregisterReceiver(receiver)
} catch (ignored: IllegalArgumentException) {
}
}
| gpl-3.0 | 0ce1cf6f150771c63a2a3856e9368174 | 28.459677 | 119 | 0.742951 | 3.686176 | false | false | false | false |
campos20/tnoodle | webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/zip/folder/OrderedScramblesFolder.kt | 1 | 6734 | package org.worldcubeassociation.tnoodle.server.webscrambles.zip.folder
import org.worldcubeassociation.tnoodle.server.webscrambles.Translate
import org.worldcubeassociation.tnoodle.server.webscrambles.exceptions.ScheduleMatchingException
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.StringUtil.toFileSafeString
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.CompetitionDrawingData
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.WCIFDataBuilder
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model.Schedule
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.folder
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.model.Folder
import java.time.LocalDate
import java.time.Period
import java.time.ZonedDateTime
data class OrderedScramblesFolder(val globalTitle: String, val scrambleDrawingData: CompetitionDrawingData) {
fun assemble(wcifSchedule: Schedule, generationDate: LocalDate, versionTag: String): Folder {
val wcifBindings = wcifSchedule.allActivities
// scrambleSetId as assigned by WCIFScrambleMatcher#matchActivity
.filter { it.scrambleSetId != null }
.associateWith { act ->
scrambleDrawingData.scrambleSheets.filter { it.scrambleSet.id == act.scrambleSetId }.unlessEmpty()
?: ScheduleMatchingException.error("Ordered Scrambles: Could not find ScrambleSet ${act.scrambleSetId} associated with Activity $act")
}.mapValues { (act, scrs) ->
scrs.filter { act.activityCode.isParentOf(it.activityCode) }.unlessEmpty()
?: ScheduleMatchingException.error("Ordered Scrambles: Could not find any activity for scramble sheets affiliated with ScrambleSet ${act.scrambleSetId}")
}
val activityDays = wcifSchedule.activitiesWithLocalStartTimes
.map { it.value.dayOfYear }
.distinct()
// hasMultipleDays gets a variable assigned on the competition creation using the website's form.
// Online schedule fit to it and the user should not be able to put events outside it, but we double check here.
// The next assignment fix possible mistakes (eg. a competition is assigned with 1 day, but events are spread among 2 days).
val hasMultipleDays = wcifSchedule.hasMultipleDays || activityDays.size > 1
val hasMultipleVenues = wcifSchedule.hasMultipleVenues
// We consider the competition start date as the earlier activity from the schedule.
// This prevents miscalculation of dates for multiple timezones.
val competitionStartActivity = wcifSchedule.earliestActivity
return folder("Ordered Scrambles") {
for (venue in wcifSchedule.venues) {
val venueName = venue.fileSafeName
val hasMultipleRooms = venue.hasMultipleRooms
val timezone = venue.dateTimeZone
val competitionStartDate = competitionStartActivity.getLocalStartTime(timezone)
for (room in venue.rooms) {
val roomName = room.fileSafeName
val activitiesPerDay = room.activities
.flatMap { it.leafChildActivities }
.groupBy {
Period.between(
competitionStartDate.atLocalStartOfDay(),
it.getLocalStartTime(timezone).atLocalStartOfDay()
).days
}
for ((nthDay, activities) in activitiesPerDay) {
val scrambles = activities.associateWith(wcifBindings::get)
.filterValuesNotNull()
val activitiesHaveScrambles = scrambles.values.flatten().isNotEmpty()
if (activitiesHaveScrambles) {
val filenameDay = nthDay + 1
val parts = listOfNotNull(
"$venueName/".takeIf { hasMultipleVenues },
"Day $filenameDay/".takeIf { hasMultipleDays },
"Ordered Scrambles",
" - $venueName".takeIf { hasMultipleVenues },
" - Day $filenameDay".takeIf { hasMultipleDays },
" - $roomName".takeIf { hasMultipleRooms },
".pdf"
)
if (hasMultipleVenues || hasMultipleDays || hasMultipleRooms) {
// In addition to different folders, we stamp venue, day and room in the PDF's name
// to prevent different files with the same name.
val pdfFileName = parts.joinToString("")
val sortedScrambles = scrambles.entries
.sortedBy { it.key.getLocalStartTime(timezone) }
.flatMap { it.value }
val sheetData = scrambleDrawingData.copy(scrambleSheets = sortedScrambles)
val sheet = WCIFDataBuilder.requestsToCompletePdf(sheetData, generationDate, versionTag, Translate.DEFAULT_LOCALE)
file(pdfFileName, sheet.render())
}
}
}
}
}
// Generate all scrambles ordered
val allScramblesOrdered = wcifSchedule.activitiesWithLocalStartTimes.entries
.sortedBy { it.value }
// the notNull will effectively never happen, because we guarantee that all relevant activities are indexed
.mapNotNull { wcifBindings[it.key] }
.flatten()
.distinct()
val allScramblesData = scrambleDrawingData.copy(scrambleSheets = allScramblesOrdered)
val completeOrderedPdf = WCIFDataBuilder.requestsToCompletePdf(allScramblesData, generationDate, versionTag, Translate.DEFAULT_LOCALE)
val safeGlobalTitle = globalTitle.toFileSafeString()
file("Ordered $safeGlobalTitle - All Scrambles.pdf", completeOrderedPdf.render())
}
}
companion object {
fun ZonedDateTime.atLocalStartOfDay() = toLocalDate().atStartOfDay(zone).toLocalDate()
fun <K, V> Map<K, V?>.filterValuesNotNull(): Map<K, V> = mapNotNull { (k, v) -> v?.let { k to it } }.toMap()
fun <T, C : Collection<T>> C.unlessEmpty(): C? = takeIf { it.isNotEmpty() }
}
}
| gpl-3.0 | 7e36f324faf12afadeb9f1c1f37df3b0 | 54.196721 | 173 | 0.610484 | 5.745734 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/step_quiz_fill_blanks/ui/delegate/FillBlanksStepQuizFormDelegate.kt | 1 | 4327 | package org.stepik.android.view.step_quiz_fill_blanks.ui.delegate
import android.view.View
import androidx.fragment.app.FragmentManager
import com.google.android.flexbox.FlexboxLayoutManager
import kotlinx.android.synthetic.main.fragment_step_quiz.view.*
import kotlinx.android.synthetic.main.layout_step_quiz_fill_blanks.view.*
import org.stepic.droid.R
import ru.nobird.android.core.model.mutate
import org.stepik.android.model.Reply
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz.model.ReplyResult
import org.stepik.android.view.step_quiz.resolver.StepQuizFormResolver
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFormDelegate
import org.stepik.android.view.step_quiz_fill_blanks.ui.adapter.delegate.FillBlanksItemInputAdapterDelegate
import org.stepik.android.view.step_quiz_fill_blanks.ui.adapter.delegate.FillBlanksItemSelectAdapterDelegate
import org.stepik.android.view.step_quiz_fill_blanks.ui.adapter.delegate.FillBlanksItemTextAdapterDelegate
import org.stepik.android.view.step_quiz_fill_blanks.ui.fragment.FillBlanksInputBottomSheetDialogFragment
import org.stepik.android.view.step_quiz_fill_blanks.ui.mapper.FillBlanksItemMapper
import org.stepik.android.view.step_quiz_fill_blanks.ui.model.FillBlanksItem
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
import ru.nobird.android.view.base.ui.extension.showIfNotExists
class FillBlanksStepQuizFormDelegate(
private val containerView: View,
private val fragmentManager: FragmentManager,
private val onQuizChanged: (ReplyResult) -> Unit
) : StepQuizFormDelegate {
private val quizDescription = containerView.stepQuizDescription
private val itemsAdapter = DefaultDelegateAdapter<FillBlanksItem>()
private val fillBlanksItemMapper = FillBlanksItemMapper()
init {
quizDescription.setText(R.string.step_quiz_fill_blanks_description)
itemsAdapter += FillBlanksItemTextAdapterDelegate()
itemsAdapter += FillBlanksItemInputAdapterDelegate(onItemClicked = ::inputItemAction)
itemsAdapter += FillBlanksItemSelectAdapterDelegate(onItemClicked = ::selectItemAction)
with(containerView.fillBlanksRecycler) {
itemAnimator = null
adapter = itemsAdapter
isNestedScrollingEnabled = false
layoutManager = FlexboxLayoutManager(context)
}
}
fun updateInputItem(index: Int, text: String) {
itemsAdapter.items = itemsAdapter.items.mutate {
val inputItem = get(index) as FillBlanksItem.Input
set(index, inputItem.copy(text = text))
}
itemsAdapter.notifyItemChanged(index)
onQuizChanged(createReply())
}
private fun selectItemAction(index: Int, text: String) {
itemsAdapter.items = itemsAdapter.items.mutate {
val selectItem = get(index) as FillBlanksItem.Select
set(index, selectItem.copy(text = text))
}
onQuizChanged(createReply())
}
private fun inputItemAction(index: Int, text: String) {
FillBlanksInputBottomSheetDialogFragment
.newInstance(index, text)
.showIfNotExists(fragmentManager, FillBlanksInputBottomSheetDialogFragment.TAG)
}
override fun setState(state: StepQuizFeature.State.AttemptLoaded) {
val submission = (state.submissionState as? StepQuizFeature.SubmissionState.Loaded)
?.submission
itemsAdapter.items = fillBlanksItemMapper.mapToFillBlanksItems(state.attempt, submission, StepQuizFormResolver.isQuizEnabled(state))
containerView.post { containerView.fillBlanksRecycler.requestLayout() }
}
override fun createReply(): ReplyResult =
ReplyResult(
Reply(
blanks = itemsAdapter
.items
.mapNotNull { item ->
when (item) {
is FillBlanksItem.Text ->
null
is FillBlanksItem.Input ->
item.text
is FillBlanksItem.Select ->
item.text
}
}
),
ReplyResult.Validation.Success
)
} | apache-2.0 | f9f8b8aef9ce40b9e0ae44ba99590a6d | 42.717172 | 140 | 0.701641 | 5.054907 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/ParalyzeBow.kt | 1 | 3061 | package nl.sugcube.dirtyarrows.bow.ability
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.BowAbility
import nl.sugcube.dirtyarrows.bow.DefaultBow
import nl.sugcube.dirtyarrows.util.fuzz
import org.bukkit.Material
import org.bukkit.entity.Arrow
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.event.entity.ProjectileHitEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
import kotlin.random.Random
/**
* Paralyzes the target, which is a random cocktail of:
* - Confusion
* - Slowness
* - Weakness
* - Blindness
*
* @author SugarCaney
*/
open class ParalyzeBow(plugin: DirtyArrows) : BowAbility(
plugin = plugin,
type = DefaultBow.PARALYZE,
canShootInProtectedRegions = true,
costRequirements = listOf(ItemStack(Material.NETHER_WART, 1)),
removeArrow = false,
description = "Paralyzes the target."
) {
/**
* How long the effects last in ticks.
*/
val effectTime = config.getInt("$node.effect-time")
/**
* How much variance there is in the effect time, in ticks.
*/
val effectTimeFuzzing = config.getInt("$node.effect-time-fuzzing")
/**
* How much chance the target has to be applied a certain effect in `[0,1]`.
*/
val effectChance = config.getDouble("$node.effect-chance")
/**
* How much chance the target has to be confused in `[0,1]`.
*/
val confusionChance = config.getDouble("$node.confusion-chance")
init {
check(effectTime >= 0) { "$node.effect-time must not be negative, got <$effectTime>" }
check(effectTimeFuzzing >= 0) { "$node.effect-time-fuzzing must not be negative, got <$effectTimeFuzzing>" }
check(effectChance in 0.0..1.0) { "$node.effect-chance must be between 0 and 1, got <$effectChance>" }
check(confusionChance in 0.0..1.0) { "$node.confusion-chance must be between 0 and 1, got <$confusionChance>" }
}
override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) {
val target = event.hitEntity as? LivingEntity ?: return
if (Random.nextDouble() < confusionChance) {
target.giveEffect(PotionEffectType.CONFUSION)
}
if (Random.nextDouble() < effectChance) {
target.giveEffect(PotionEffectType.SLOW)
}
if (Random.nextDouble() < effectChance) {
target.giveEffect(PotionEffectType.WEAKNESS)
}
if (Random.nextDouble() < effectChance) {
target.giveEffect(PotionEffectType.BLINDNESS)
}
}
/**
* Applies the given potion/paralyze effect for a random time.
*/
private fun LivingEntity.giveEffect(type: PotionEffectType) {
val time = effectTime.fuzz(effectTimeFuzzing) + if (type == PotionEffectType.CONFUSION) 60 else 0
val level = if (type == PotionEffectType.CONFUSION) 1.fuzz(1) else 20
addPotionEffect(PotionEffect(type, time, level))
}
} | gpl-3.0 | 0c3178961bd2e0a680eea695a45b3b9f | 34.195402 | 119 | 0.676576 | 4.130904 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android | api_pact/src/test/java/com/vmenon/mpo/api/pact/MpoApiPactTest.kt | 1 | 5932 | package com.vmenon.mpo.api.pact
import au.com.dius.pact.consumer.dsl.LambdaDsl
import au.com.dius.pact.consumer.dsl.LambdaDslObject
import au.com.dius.pact.consumer.dsl.PactDslJsonRootValue
import au.com.dius.pact.consumer.dsl.PactDslWithProvider
import au.com.dius.pact.consumer.junit.PactProviderRule
import au.com.dius.pact.consumer.junit.PactVerification
import au.com.dius.pact.core.model.RequestResponsePact
import au.com.dius.pact.core.model.annotations.Pact
import com.vmenon.mpo.api.model.RegisterUserRequest
import com.vmenon.mpo.common.framework.di.dagger.ApiModule
import okhttp3.OkHttpClient
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
class MpoApiPactTest {
@Rule
@JvmField
val provider = PactProviderRule("mpo-api", this)
@Pact(consumer = "consumer-mpo-api")
fun createSearchPact(builder: PactDslWithProvider): RequestResponsePact {
return builder
.given("default")
.uponReceiving("Search for shows")
.path("/podcasts")
.query("keyword=$SEARCH_KEYWORD")
.method("GET")
.willRespondWith()
.status(200)
.body(LambdaDsl.newJsonArray { array ->
array.`object` { item ->
item.stringType(
"name",
"artworkUrl",
"feedUrl",
"smallArtworkUrl",
"author"
)
item.eachLike("genres", PactDslJsonRootValue.stringType())
}
}.build()).toPact()
}
@Pact(consumer = "consumer-mpo-api")
fun createShowDetailsPact(builder: PactDslWithProvider): RequestResponsePact {
return builder
.given("default")
.uponReceiving("Get Show Details")
.path("/podcastdetails")
.query("maxEpisodes=$MAX_EPISODES&feedUrl=$FEED_URL")
.method("GET")
.willRespondWith()
.status(200)
.body(LambdaDsl.newJsonBody { root ->
root.stringType(
"name",
"description",
"imageUrl"
)
root.eachLike("episodes") { item: LambdaDslObject ->
item.stringType(
"name",
"artworkUrl",
"feedUrl",
"smallArtworkUrl",
"author"
)
item.eachLike("genres", PactDslJsonRootValue.stringType())
}
}.build()).toPact()
}
@Pact(consumer = "consumer-mpo-api")
fun createShowUpdatePact(builder: PactDslWithProvider): RequestResponsePact {
return builder
.given("default")
.uponReceiving("Get Show update")
.path("/podcastupdate")
.query("feedUrl=$FEED_URL&publishTimestamp=$PUBLISH_TIMESTAMP")
.method("GET")
.willRespondWith()
.status(200)
.body(LambdaDsl.newJsonBody { root ->
root.stringType(
"name",
"artworkUrl",
"description",
"type",
"artworkUrl"
)
root.numberType(
"published",
"length"
)
}.build()).toPact()
}
@Pact(consumer = "consumer-mpo-api")
fun registerUserPact(builder: PactDslWithProvider): RequestResponsePact {
return builder
.given("default")
.uponReceiving("Register a User")
.path("/register_user")
.method("POST")
.body(LambdaDsl.newJsonBody { body ->
body.stringType(
"firstName",
"lastName",
"email",
"password"
)
}.build())
.willRespondWith()
.status(200)
.body(LambdaDsl.newJsonBody { body ->
body.stringType(
"firstName",
"lastName",
"email"
)
}.build()).toPact()
}
@Test
@PactVerification(fragment = "createSearchPact")
fun `should fetch shows from provider`() {
val response = client().searchPodcasts(SEARCH_KEYWORD).blockingGet()
Assert.assertFalse(response.isEmpty())
}
@Test
@PactVerification(fragment = "createShowDetailsPact")
fun `should fetch show details from provider`() {
val response = client().getPodcastDetails(FEED_URL, MAX_EPISODES).blockingGet()
Assert.assertNotNull(response)
}
@Test
@PactVerification(fragment = "createShowUpdatePact")
fun `should fetch show update from provider`() {
val response = client().getPodcastUpdate(FEED_URL, PUBLISH_TIMESTAMP).blockingGet()
Assert.assertNotNull(response)
}
@Test
@PactVerification(fragment = "registerUserPact")
fun `should register a User`() {
val response = client().registerUser(
RegisterUserRequest(
firstName = "User First Name",
lastName = "User Last Name",
email = "User email",
password = "User password"
)
).blockingGet()
Assert.assertNotNull(response)
}
private fun client() =
ApiModule.provideMediaPlayerRetrofitApi(provider.url, OkHttpClient.Builder().build())
companion object {
private const val SEARCH_KEYWORD = "Game Scoop! TV (Video)"
private const val MAX_EPISODES = 10
private const val FEED_URL = "http://feeds.ign.com/ignfeeds/podcasts/video/gamescoop"
private const val PUBLISH_TIMESTAMP = 1507661400000
}
} | apache-2.0 | 49047df77243c16afffb6c68c827ae68 | 33.494186 | 93 | 0.541133 | 4.959866 | false | false | false | false |
Bios-Marcel/ServerBrowser | src/main/kotlin/com/msc/serverbrowser/gui/controllers/implementations/FilesController.kt | 1 | 5669 | package com.msc.serverbrowser.gui.controllers.implementations
import com.github.plushaze.traynotification.animations.Animations
import com.github.plushaze.traynotification.notification.NotificationTypeImplementations
import com.github.plushaze.traynotification.notification.TrayNotificationBuilder
import com.msc.serverbrowser.Client
import com.msc.serverbrowser.constants.PathConstants
import com.msc.serverbrowser.data.properties.ClientPropertiesController
import com.msc.serverbrowser.data.properties.UseDarkThemeProperty
import com.msc.serverbrowser.gui.controllers.interfaces.ViewController
import com.msc.serverbrowser.gui.views.FilesView
import com.msc.serverbrowser.info
import com.msc.serverbrowser.severe
import com.msc.serverbrowser.util.basic.FileUtility
import com.msc.serverbrowser.util.basic.StringUtility
import com.msc.serverbrowser.warn
import javafx.event.EventHandler
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.util.function.Predicate
import java.util.regex.Pattern
/**
* Controls the Files view which allows you to look at your taken screenshots, your chatlogs and
* your saved positions.
*
* @author Marcel
* @since 08.07.2017
*
* @property filesView the view to be used by this controller
*/
class FilesController(private val filesView: FilesView) : ViewController {
init {
filesView.setLoadChatLogsButtonAction(EventHandler { loadChatLog() })
filesView.setClearChatLogsButtonAction(EventHandler { clearChatLog() })
filesView.showColorsProperty.addListener { _ -> loadChatLog() }
filesView.showColorsAsTextProperty.addListener { _ -> loadChatLog() }
filesView.showTimesIfAvailableProperty.addListener { _ -> loadChatLog() }
filesView.lineFilterProperty.addListener { _ -> loadChatLog() }
loadChatLog()
}
private fun loadChatLog() {
val darkThemeInUse = ClientPropertiesController.getProperty(UseDarkThemeProperty)
val gray = "#333131"
val white = "#FFFFFF"
val newContent = StringBuilder("<html><body style='background-color: ")
.append(if (darkThemeInUse) gray else white)
.append("; color: ")
.append(if (darkThemeInUse) white else gray)
.append("';")
.append(">")
try {
val path = Paths.get(PathConstants.SAMP_CHATLOG)
val filterProperty = filesView.lineFilterProperty.valueSafe.toLowerCase()
FileUtility.readAllLinesTryEncodings(path, StandardCharsets.ISO_8859_1, StandardCharsets.UTF_8, StandardCharsets.US_ASCII)
.stream()
.filter(Predicate<String> { it.isEmpty() }.negate())
.filter { line -> line.toLowerCase().contains(filterProperty) }
.map { StringUtility.escapeHTML(it) }
.map { this.processSampChatlogTimestamps(it) }
.map { this.processSampColorCodes(it) }
.map { line -> "$line<br/>" }
.forEach { newContent.append(it) }
} catch (exception: FileNotFoundException) {
info("Chatlog file doesn't exist.")
} catch (exception: IOException) {
severe("Error loading chatlog.", exception)
}
filesView.setChatLogTextAreaContent(newContent.toString())
}
private fun processSampChatlogTimestamps(line: String): String {
if (filesView.showTimesIfAvailableProperty.get()) {
return line
}
val timeRegex = "\\[(?:(?:([01]?\\d|2[0-3]):)?([0-5]?\\d):)?([0-5]?\\d)]"
return if (line.length >= 10 && line.substring(0, 10).matches(timeRegex.toRegex())) {
line.replaceFirst(timeRegex.toRegex(), "")
} else line
}
private fun processSampColorCodes(line: String): String {
val showColorsAsText = filesView.showColorsAsTextProperty.get()
val showColors = filesView.showColorsProperty.get()
if (showColorsAsText && !showColors) {
return line
}
val colorRegex = "([{](.{6})[}])"
if (showColors) {
var fixedLine = "<span>" + line.replace("{000000}", "{FFFFFF}")
val colorCodeMatcher = Pattern.compile(colorRegex).matcher(fixedLine)
while (colorCodeMatcher.find()) {
val replacementColorCode = "#" + colorCodeMatcher.group(2)
val replacement = StringBuilder("</span><span style='color:")
.append(replacementColorCode)
.append(";'>")
val color = colorCodeMatcher.group(1)
if (showColorsAsText) {
replacement.append(color)
}
fixedLine = fixedLine.replace(color, replacement.toString())
}
return "$fixedLine</span>"
}
return line.replace(colorRegex.toRegex(), "")
}
private fun clearChatLog() {
try {
Files.deleteIfExists(Paths.get(PathConstants.SAMP_CHATLOG))
loadChatLog()
} catch (exception: IOException) {
TrayNotificationBuilder()
.type(NotificationTypeImplementations.ERROR)
.animation(Animations.POPUP)
.title(Client.getString("couldntClearChatLog"))
.message(Client.getString("checkLogsForMoreInformation")).build().showAndDismiss(Client.DEFAULT_TRAY_DISMISS_TIME)
warn("Couldn't clear chatlog", exception)
}
}
}
| mpl-2.0 | 4286edaa295f3122f015e52b4a0e8bfc | 39.492857 | 134 | 0.644382 | 4.658176 | false | false | false | false |
rinp/javaQuiz | src/main/kotlin/xxx/jq/controller/AccountController.kt | 1 | 2488 | package xxx.jq.controller
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import xxx.jq.consts.Authorizes
import xxx.jq.entity.Account
import xxx.jq.form.SignInForm
import xxx.jq.form.SignUpForm
import xxx.jq.service.AccountService
import xxx.jq.service.AuthenticationService
import javax.servlet.http.HttpServletRequest
/**
* @author rinp
* @since 2015/10/08
*/
@RestController
@RequestMapping(value = "/v1/accounts")
open class AccountController {
@Autowired
lateinit private var service: AccountService
@Autowired
lateinit private var auth: AuthenticationService
@RequestMapping(value = "/signup", method = arrayOf(RequestMethod.POST), consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE))
open fun signUp(@RequestBody @Validated form: SignUpForm, request: HttpServletRequest): Account {
val account = service.save(form.toAccount())
auth.setAuthentication(account, form.password, request)
return account
}
@RequestMapping(value = "/signin", method = arrayOf(RequestMethod.POST), consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE))
open fun signIn(@RequestBody @Validated form: SignInForm, request: HttpServletRequest): Account {
val account = service.findByAccountId(form.accountId)
val rawPass = form.password
auth.setAuthentication(account, rawPass, request)
return account
}
//TODO これもMypageか別途コントローラーを切り出したい
@RequestMapping(value = "/in", method = arrayOf(RequestMethod.GET))
open fun isSignIn(): Boolean {
return auth.currentAccount.accountId != "system"
}
//TODO これもMypageか別途コントローラーを切り出したい
@RequestMapping(value = "/admin", method = arrayOf(RequestMethod.GET))
open fun isAdmin(): Boolean {
return auth.currentAccount.isAdmin
}
@PreAuthorize(Authorizes.ADMIN)
@RequestMapping(value = "/users", method = arrayOf(RequestMethod.GET))
open fun get(): List<Account> {
return service.findAll()
}
}
| mit | 6e8e4ce6933fd70750f829fefce1e728 | 34.940299 | 130 | 0.752907 | 4.3 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/vimscript/Executor.kt | 1 | 4246 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.textarea.TextComponentEditorImpl
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimScriptExecutorBase
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.ex.FinishException
import com.maddyhome.idea.vim.history.HistoryConstants
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.register.RegisterConstants.LAST_COMMAND_REGISTER
import com.maddyhome.idea.vim.vimscript.model.CommandLineVimLContext
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
import com.maddyhome.idea.vim.vimscript.model.VimLContext
import com.maddyhome.idea.vim.vimscript.model.commands.Command
import com.maddyhome.idea.vim.vimscript.model.commands.RepeatCommand
import com.maddyhome.idea.vim.vimscript.parser.VimscriptParser
import java.io.File
import java.io.IOException
import javax.swing.JTextArea
@Service
class Executor : VimScriptExecutorBase() {
private val logger = logger<Executor>()
override var executingVimscript = false
@Throws(ExException::class)
override fun execute(script: String, editor: VimEditor, context: ExecutionContext, skipHistory: Boolean, indicateErrors: Boolean, vimContext: VimLContext?): ExecutionResult {
var finalResult: ExecutionResult = ExecutionResult.Success
val myScript = VimscriptParser.parse(script)
myScript.units.forEach { it.vimContext = vimContext ?: myScript }
for (unit in myScript.units) {
try {
val result = unit.execute(editor, context)
if (result is ExecutionResult.Error) {
finalResult = ExecutionResult.Error
if (indicateErrors) {
VimPlugin.indicateError()
}
}
} catch (e: ExException) {
if (e is FinishException) {
break
}
finalResult = ExecutionResult.Error
if (indicateErrors) {
VimPlugin.showMessage(e.message)
VimPlugin.indicateError()
} else {
logger.warn("Failed while executing $unit. " + e.message)
}
} catch (e: NotImplementedError) {
if (indicateErrors) {
VimPlugin.showMessage("Not implemented yet :(")
VimPlugin.indicateError()
}
} catch (e: Exception) {
logger.warn("Caught: ${e.message}")
logger.warn(e.stackTrace.toString())
if (injector.application.isUnitTest()) {
throw e
}
}
}
if (!skipHistory) {
VimPlugin.getHistory().addEntry(HistoryConstants.COMMAND, script)
if (myScript.units.size == 1 && myScript.units[0] is Command && myScript.units[0] !is RepeatCommand) {
VimPlugin.getRegister().storeTextSpecial(LAST_COMMAND_REGISTER, script)
}
}
return finalResult
}
override fun execute(script: String, skipHistory: Boolean) {
val editor = TextComponentEditorImpl(null, JTextArea()).vim
val context = DataContext.EMPTY_CONTEXT.vim
execute(script, editor, context, skipHistory, indicateErrors = true, CommandLineVimLContext)
}
override fun executeFile(file: File, indicateErrors: Boolean) {
val editor = TextComponentEditorImpl(null, JTextArea()).vim
val context = DataContext.EMPTY_CONTEXT.vim
try {
execute(file.readText(), editor, context, skipHistory = true, indicateErrors)
} catch (ignored: IOException) { }
}
@Throws(ExException::class)
override fun executeLastCommand(editor: VimEditor, context: ExecutionContext): Boolean {
val reg = VimPlugin.getRegister().getRegister(':') ?: return false
val text = reg.text ?: return false
execute(text, editor, context, skipHistory = false, indicateErrors = true, CommandLineVimLContext)
return true
}
}
| mit | 1cef65a842ab4d474933975e339c7e9b | 37.252252 | 176 | 0.721856 | 4.345957 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/DefaultRadioButtonGroup.kt | 1 | 2933 | package org.hexworks.zircon.internal.component.impl
import org.hexworks.cobalt.databinding.api.extension.orElseGet
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.cobalt.events.api.Subscription
import org.hexworks.zircon.api.Components
import org.hexworks.zircon.api.component.AttachedComponent
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.RadioButton
import org.hexworks.zircon.api.component.RadioButtonGroup
import org.hexworks.zircon.api.dsl.component.buildRadioButton
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.internal.component.InternalComponent
import org.hexworks.zircon.internal.component.InternalGroup
import kotlin.jvm.Synchronized
class DefaultRadioButtonGroup internal constructor(
initialIsDisabled: Boolean,
initialIsHidden: Boolean,
initialTheme: ColorTheme,
initialTileset: TilesetResource,
private val groupDelegate: InternalGroup<RadioButton> = Components.group<RadioButton>()
.withIsDisabled(initialIsDisabled)
.withIsHidden(initialIsHidden)
.withTheme(initialTheme)
.withTileset(initialTileset)
.build() as InternalGroup<RadioButton>
) : RadioButtonGroup, InternalGroup<RadioButton> by groupDelegate {
private val buttons = mutableMapOf<String, Pair<GroupAttachedComponent, Subscription>>()
override var selectedButtonProperty: Property<RadioButton?> = null.toProperty()
override var selectedButton: RadioButton? by selectedButtonProperty.asDelegate()
@Synchronized
override fun addComponent(component: RadioButton): AttachedComponent {
require(component is InternalComponent) {
"The supplied component does not implement required interface: InternalComponent."
}
require(buttons.containsKey(component.key).not()) {
"There is already a Radio Button in this Radio Button Group with the key '${component.key}'."
}
val handle = GroupAttachedComponent(component, this)
buttons[component.key] = handle to component.selectedProperty.onChange { (_, newlySelected) ->
selectedButton?.let { previousSelected ->
if (newlySelected && previousSelected !== component) {
previousSelected.isSelected = false
selectedButton = component
}
}.orElseGet {
selectedButton = component
}
}
if (component.isSelected) {
selectedButton?.let { oldSelection ->
oldSelection.isSelected = false
}
selectedButton = component
}
groupDelegate.addComponent(component)
return handle
}
override fun addComponents(vararg components: RadioButton) = components.map(::addComponent)
}
| apache-2.0 | 4cb01501403bbf8801ffc49c4adc8067 | 42.776119 | 105 | 0.724173 | 5.127622 | false | false | false | false |
Tiofx/semester_6 | MIT/MIT_lab_8/app/src/main/java/com/example/andrej/mit_lab_8/MainActivity.kt | 1 | 8189 | package com.example.andrej.mit_lab_8
import android.app.*
import android.content.Context
import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.NotificationCompat
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.andrej.mit_lab_8.SqlHelper.Companion.COLUMN_NAME
import com.example.andrej.mit_lab_8.SqlHelper.Companion.TABLE_NAME
import java.util.*
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
val editTextTitle by lazy {
findViewById(R.id.editTextTitle) as EditText
}
val editTextMessage by lazy {
findViewById(R.id.editTextMessage) as EditText
}
val editTextTime by lazy {
findViewById(R.id.editTextTime) as EditText
}
val editTextDate by lazy {
findViewById(R.id.editTextDate) as EditText
}
val buttonAddNotification by lazy {
findViewById(R.id.buttonAddNotification) as Button
}
val buttonShowNotifications by lazy {
findViewById(R.id.buttonShowNotifications) as Button
}
val buttonRemove by lazy {
findViewById(R.id.buttonRemove) as Button
}
val calendar = Calendar.getInstance()
val sqlDB by lazy { SqlHelper(this@MainActivity) }
val newNotification = mutableListOf<NotificationData>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
PushNotification(this).execute(sqlDB.getAllRecords().toMutableList())
buttonRemove.setOnClickListener { sqlDB.removeOldNotification() }
buttonShowNotifications.setOnClickListener {
Intent(this@MainActivity, TableViewActivity::class.java)
.let(this@MainActivity::startActivity)
}
buttonAddNotification.setOnClickListener {
NotificationData(
title = editTextTitle.text.toString(),
message = editTextMessage.text.toString(),
date = calendar.let {
Date(it[Calendar.YEAR],
it[Calendar.MONTH],
it[Calendar.DAY_OF_MONTH],
it[Calendar.HOUR_OF_DAY],
it[Calendar.MINUTE]
)
}
).let {
sqlDB.insert(it)
synchronized(newNotification, { newNotification.add(it) })
}
Toast.makeText(this@MainActivity, "Уведомление добавлено", Toast.LENGTH_LONG)
.show()
}
editTextDate.setOnClickListener {
DatePickerDialog(this@MainActivity,
DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
editTextDate.text.let {
calendar.set(year, month, dayOfMonth)
it.clear()
it.append("$year-$month-$dayOfMonth")
}
},
calendar[Calendar.YEAR],
calendar[Calendar.MONTH],
calendar[Calendar.DAY_OF_MONTH]
).show()
}
editTextTime.setOnClickListener {
TimePickerDialog(this@MainActivity,
TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
editTextTime.text.let {
with(calendar) {
set(get(Calendar.YEAR),
get(Calendar.MONTH),
get(Calendar.DAY_OF_MONTH),
hourOfDay, minute)
}
it.clear()
it.append("$hourOfDay:$minute")
}
},
calendar[Calendar.HOUR_OF_DAY],
calendar[Calendar.MINUTE],
true
).show()
}
}
var notificationId = 0
fun NotificationData.addNotification() {
val builder = NotificationCompat.Builder(this@MainActivity).apply {
setSmallIcon(R.drawable.kotlin)
setContentTitle(title)
setContentText(message)
}
Intent(this@MainActivity, MainActivity::class.java)
.let {
TaskStackBuilder.create(this@MainActivity).apply {
addParentStack(MainActivity::class.java)
addNextIntent(it)
builder.setContentIntent(getPendingIntent(notificationId, PendingIntent.FLAG_UPDATE_CURRENT))
}
}
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
.notify(notificationId, builder.build())
notificationId++
}
}
class PushNotification(val main: MainActivity) : AsyncTask<MutableList<NotificationData>, Unit, Unit>() {
override fun doInBackground(vararg params: MutableList<NotificationData>?) {
val mutableList = params[0]!!
while (true) {
val currentTime = Date().let { Date(it.year, it.month, it.date, it.hours, it.minutes) }
mutableList += synchronized(main.newNotification, { main.newNotification })
mutableList
.filter { it.date == currentTime }
.forEach {
main.apply { it.addNotification() }
mutableList.remove(it)
}
synchronized(main.newNotification, { main.newNotification.clear() })
TimeUnit.SECONDS.sleep(2)
}
}
}
data class NotificationData(val id: Int = -1,
val title: String,
val message: String,
val date: Date)
class SqlHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, 2) {
companion object {
const val DATABASE_NAME = "MIT_lab_8_DB"
const val TABLE_NAME = "NotificationData"
val COLUMN_NAME = arrayOf("_id", "title", "message", "date")
val DEFAULT = arrayOf("", "заголовок не установлин", "сообщение не установлено", "давно")
}
override fun onCreate(db: SQLiteDatabase?) {
db!!.execSQL("CREATE TABLE $TABLE_NAME(" +
"${COLUMN_NAME[0]} INTEGER PRIMARY KEY AUTOINCREMENT," +
"${COLUMN_NAME[1]} TEXT DEFAULT '${DEFAULT[1]}'," +
"${COLUMN_NAME[2]} TEXT DEFAULT '${DEFAULT[2]}'," +
"${COLUMN_NAME[3]} TEXT DEFAULT '${DEFAULT[3]}');")
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db!!.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
db.version = newVersion
onCreate(db)
}
fun insert(radio: NotificationData) = with(radio) {
writableDatabase.execSQL("INSERT INTO $TABLE_NAME" +
"(${COLUMN_NAME[1]}, ${COLUMN_NAME[2]}, ${COLUMN_NAME[3]}) " +
"VALUES('$title', '$message', '${date.apply { year -= 1900 }}');")
}
fun getAllRecords(): List<NotificationData> {
val cursor = writableDatabase.rawQuery("SELECT ${COLUMN_NAME.joinToString(",")} FROM $TABLE_NAME;", null)
cursor.moveToFirst()
return (0..cursor.count - 1).map {
with(cursor) {
NotificationData(
getInt(0),
getString(1),
getString(2),
Date(getString(3))
).apply { moveToNext() }
}
}
}
}
fun SqlHelper.removeOldNotification(date: Date = Date()) = writableDatabase
.execSQL("DELETE FROM $TABLE_NAME WHERE ${COLUMN_NAME[3]} <= '$date'") | gpl-3.0 | 32d79ea0778e80e2f040114a5949e5e5 | 35.421525 | 117 | 0.555104 | 5.117202 | false | false | false | false |
pyamsoft/pydroid | ui/src/main/java/com/pyamsoft/pydroid/ui/internal/about/AboutListItem.kt | 1 | 3797 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.ui.internal.about
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.pyamsoft.pydroid.bootstrap.libraries.OssLibraries
import com.pyamsoft.pydroid.bootstrap.libraries.OssLibrary
import com.pyamsoft.pydroid.theme.keylines
import com.pyamsoft.pydroid.ui.R
import com.pyamsoft.pydroid.ui.defaults.CardDefaults
@Composable
internal fun AboutListItem(
modifier: Modifier = Modifier,
library: OssLibrary,
onViewHomePage: () -> Unit,
onViewLicense: () -> Unit
) {
Card(
modifier = modifier,
shape = MaterialTheme.shapes.medium,
elevation = CardDefaults.Elevation,
) {
Column(
modifier = Modifier.padding(MaterialTheme.keylines.baseline),
) {
Name(
library = library,
)
License(
library = library,
)
Description(
library = library,
)
Row(
modifier = Modifier.padding(top = MaterialTheme.keylines.baseline),
) {
ViewLicense(
onClick = onViewLicense,
)
VisitHomepage(
onClick = onViewHomePage,
)
}
}
}
}
@Composable
private fun Name(library: OssLibrary) {
Text(
style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.W700),
text = library.name,
)
}
@Composable
private fun License(library: OssLibrary) {
Text(
style = MaterialTheme.typography.caption,
text = stringResource(R.string.license_name, library.licenseName),
)
}
@Composable
private fun Description(library: OssLibrary) {
val description = library.description
AnimatedVisibility(visible = description.isNotBlank()) {
Box(
modifier = Modifier.padding(vertical = MaterialTheme.keylines.baseline),
) {
Text(
style = MaterialTheme.typography.body2,
text = description,
)
}
}
}
@Composable
private fun ViewLicense(onClick: () -> Unit) {
TextButton(
onClick = onClick,
) {
Text(
text = stringResource(R.string.view_license),
)
}
}
@Composable
private fun VisitHomepage(onClick: () -> Unit) {
Box(
modifier = Modifier.padding(start = MaterialTheme.keylines.baseline),
) {
TextButton(
onClick = onClick,
) {
Text(
text = stringResource(R.string.visit_homepage),
)
}
}
}
@Preview
@Composable
private fun PreviewAboutListItem() {
Surface {
AboutListItem(
library = OssLibraries.libraries().first(),
onViewLicense = {},
onViewHomePage = {},
)
}
}
| apache-2.0 | c18f0a433d0963ed48c4042170707853 | 24.829932 | 80 | 0.693179 | 4.266292 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/arrays/ParamsArray.kt | 1 | 7848 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.arrays
import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer
import com.kotlinnlp.simplednn.core.functionalities.updatemethods.UpdaterSupportStructure
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import com.kotlinnlp.simplednn.simplemath.ndarray.sparse.SparseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.sparse.SparseNDArrayFactory
import java.io.Serializable
import java.util.UUID
/**
* The [ParamsArray] is a wrapper of a [DenseNDArray] extending it with an unique identifier [uuid],
* with an [updaterSupportStructure] and with methods to build the params [Errors].
*
* @property values the values of the parameters
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*/
class ParamsArray(
val values: DenseNDArray,
private val defaultErrorsType: ErrorsType = ErrorsType.Dense
) : Serializable {
companion object {
/**
* Private val used to serialize the class (needed from [Serializable])
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
}
/**
* Build a new [ParamsArray] with the given [values].
*
* @param values the values
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(values: DoubleArray,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.arrayOf(values),
defaultErrorsType = defaultErrorsType
)
/**
* Build a new [ParamsArray] with the given [values].
*
* @param values the values
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(values: List<DoubleArray>,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.arrayOf(values),
defaultErrorsType = defaultErrorsType
)
/**
* Build a new [ParamsArray] with the given dimensions.
*
* @param dim1 the first dimension of the array
* @param dim2 the second dimension of the array
* @param initializer the initializer of the values (can be null)
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(dim1: Int,
dim2: Int,
initializer: Initializer? = null,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.zeros(Shape(dim1, dim2)).apply { initializer?.initialize(this) },
defaultErrorsType = defaultErrorsType
)
/**
* Build a new [ParamsArray] with the given [shape].
*
* @param shape the shape
* @param initializer the initializer of the values (can be null)
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(shape: Shape,
initializer: Initializer? = null,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.zeros(shape).apply { initializer?.initialize(this) },
defaultErrorsType = defaultErrorsType
)
/**
* Build a new [ParamsArray] with the given [size].
*
* @param size the size
* @param initializer the initializer of the values (can be null)
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(size: Int,
initializer: Initializer? = null,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.zeros(Shape(size)).apply { initializer?.initialize(this) },
defaultErrorsType = defaultErrorsType
)
/**
* The errors type.
*/
enum class ErrorsType { Dense, Sparse }
/**
* ParamsErrors.
*
* @property values the error of the parameters
*/
inner class Errors<T: NDArray<T>>(val values: T) {
/**
* Reference parameters.
*
* The instance of the [ParamsArray] from witch the [Errors] has been created.
*/
val refParams: ParamsArray = this@ParamsArray
/**
* @return a copy of this params errors (the copy share the same [refParams])
*/
fun copy() = Errors(this.values.copy())
/**
* @return the hash code for this object
*/
override fun hashCode(): Int = this.refParams.uuid.hashCode()
/**
* @param other an object
*
* @return `true` if the other object is equal to this one, otherwise `false`
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Errors<*>
if (refParams.uuid != other.refParams.uuid) return false
return true
}
}
/**
* The unique identifier of this [ParamsArray].
*/
val uuid = UUID.randomUUID().toString()
/**
* The updater support structure used by [com.kotlinnlp.simplednn.core.functionalities.updatemethods].
*/
var updaterSupportStructure: UpdaterSupportStructure? = null
/**
* Return the [updaterSupportStructure].
*
* If the [updaterSupportStructure] is null, set it with a new [StructureType].
* If the [updaterSupportStructure] has already been initialized, it must be compatible with the required
* [StructureType].
*
* @return the [updaterSupportStructure]
*/
inline fun <reified StructureType: UpdaterSupportStructure>getOrSetSupportStructure(): StructureType {
if (this.updaterSupportStructure == null) {
this.updaterSupportStructure = StructureType::class.constructors.first().call(this.values.shape)
}
require(this.updaterSupportStructure is StructureType) { "Incompatible support structure" }
@Suppress("UNCHECKED_CAST")
return this.updaterSupportStructure as StructureType
}
/**
* Return a new instance of [Errors] initialized to zeros or with the given [values] if not null.
*
* @param values the values used to initialize the errors (can be null)
*
* @return a new instance of errors parameters
*/
fun buildDenseErrors(values: DenseNDArray? = null) =
Errors(values ?: DenseNDArrayFactory.zeros(this.values.shape))
/**
* Return a new instance of [Errors] initialized to zeros or with the given [values] if not null.
*
* @param values the values used to initialize the errors (can be null)
*
* @return a new instance of errors parameters
*/
fun buildSparseErrors(values: SparseNDArray? = null) =
Errors(values ?: SparseNDArrayFactory.zeros(this.values.shape))
/**
* Return a new instance of [Errors] initialized to zeros.
*
* If the [defaultErrorsType] is [ErrorsType.Sparse], build sparse errors.
* If the [defaultErrorsType] is [ErrorsType.Dense], build dense errors.
*
* @return a new instance of errors parameters
*/
fun buildDefaultErrors() = when (defaultErrorsType) {
ErrorsType.Dense -> this.buildDenseErrors()
ErrorsType.Sparse -> this.buildSparseErrors()
}
}
| mpl-2.0 | 8c7c63cfd2cfafdeffc2f8accf031d7e | 33.121739 | 113 | 0.693298 | 4.616471 | false | false | false | false |
y20k/transistor | app/src/main/java/org/y20k/transistor/helpers/ImportHelper.kt | 1 | 5183 | /*
* ImportHelper.kt
* Implements the ImportHelper object
* A ImportHelper provides methods for integrating station files from Transistor v3
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor.helpers
import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import org.y20k.transistor.Keys
import org.y20k.transistor.core.Collection
import org.y20k.transistor.core.Station
import java.io.File
import java.util.*
/*
* ImportHelper object
*/
object ImportHelper {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(ImportHelper::class.java)
/* Converts older station of type .m3u */
fun convertOldStations(context: Context): Boolean {
val oldStations: ArrayList<Station> = arrayListOf()
val oldCollectionFolder: File? = context.getExternalFilesDir(Keys.TRANSISTOR_LEGACY_FOLDER_COLLECTION)
if (oldCollectionFolder != null && shouldStartImport(oldCollectionFolder)) {
CoroutineScope(IO).launch {
var success: Boolean = false
// start import
oldCollectionFolder.listFiles()?.forEach { file ->
// look for station files from Transistor v3
if (file.name.endsWith(Keys.TRANSISTOR_LEGACY_STATION_FILE_EXTENSION)) {
// read stream uri and name
val station: Station = FileHelper.readStationPlaylist(file.inputStream())
station.nameManuallySet = true
// detect stream content
station.streamContent = NetworkHelper.detectContentType(station.getStreamUri()).type
// try to also import station image
val sourceImageUri: String = getLegacyStationImageFileUri(context, station)
if (sourceImageUri != Keys.LOCATION_DEFAULT_STATION_IMAGE) {
// create and add image and small image + get main color
station.image = FileHelper.saveStationImage(context, station.uuid, sourceImageUri, Keys.SIZE_STATION_IMAGE_CARD, Keys.STATION_SMALL_IMAGE_FILE).toString()
station.smallImage = FileHelper.saveStationImage(context, station.uuid, sourceImageUri, Keys.SIZE_STATION_IMAGE_MAXIMUM, Keys.STATION_IMAGE_FILE).toString()
station.imageColor = ImageHelper.getMainColor(context, sourceImageUri)
station.imageManuallySet = true
}
// improvise a name if empty
if (station.name.isEmpty()) {
station.name = file.name.substring(0, file.name.lastIndexOf("."))
station.nameManuallySet = false
}
station.modificationDate = GregorianCalendar.getInstance().time
// add station
oldStations.add(station)
success = true
}
}
// check for success (= at least one station was found)
if (success) {
// delete files from Transistor v3
oldCollectionFolder.deleteRecursively()
// sort and save collection
val newCollection: Collection = CollectionHelper.sortCollection(Collection(stations = oldStations))
CollectionHelper.saveCollection(context, newCollection)
}
}
// import has been started
return true
} else {
// import has NOT been started
return false
}
}
/* Checks if conditions for a station import are met */
private fun shouldStartImport(oldCollectionFolder: File): Boolean {
return oldCollectionFolder.exists() &&
oldCollectionFolder.isDirectory &&
oldCollectionFolder.listFiles()?.isNotEmpty()!! &&
!FileHelper.checkForCollectionFile(oldCollectionFolder)
}
/* Gets Uri for station images created by older Transistor versions */
private fun getLegacyStationImageFileUri(context: Context, station: Station): String {
val collectionFolder: File? = context.getExternalFilesDir(Keys.TRANSISTOR_LEGACY_FOLDER_COLLECTION)
if (collectionFolder != null && collectionFolder.exists() && collectionFolder.isDirectory) {
val stationNameCleaned: String = station.name.replace(Regex("[:/]"), "_")
val legacyStationImage = File("$collectionFolder/$stationNameCleaned.png")
if (legacyStationImage.exists()) {
return legacyStationImage.toString()
} else {
return Keys.LOCATION_DEFAULT_STATION_IMAGE
}
} else {
return Keys.LOCATION_DEFAULT_STATION_IMAGE
}
}
}
| mit | df77d39f6fb6b0a96e65571468cbed31 | 42.923729 | 184 | 0.605055 | 5.359876 | false | false | false | false |
LittleLightCz/SheepsGoHome | core/src/com/sheepsgohome/shared/GameData.kt | 1 | 2578 | package com.sheepsgohome.shared
import com.badlogic.gdx.Application.ApplicationType.Desktop
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Preferences
import com.badlogic.gdx.utils.I18NBundle
import com.sheepsgohome.android.Android
import com.sheepsgohome.google.GoogleLeaderboard
import java.util.*
object GameData {
private val gamePreferences: Preferences by lazy { Gdx.app.getPreferences("gamePreferences") }
val loc: I18NBundle by lazy {
val baseFileHandle = Gdx.files.internal("loc/Language")
val locale = Locale.getDefault()
I18NBundle.createBundle(baseFileHandle, locale)
}
//----------------ANDROID BRIDGE-----------------
var android: Android? = null
var leaderboard: GoogleLeaderboard? = null
//----------------CONSTANTS----------------------
val VERSION_STRING = "1.0.3"
val codeX = "oiaewj023897rvoiuwanvoiune0v9128n09r2898v7q3342089"
val CAMERA_HEIGHT = 160f
val CAMERA_WIDTH = 90f
val SETTINGS_TITLE_FONT_SCALE = 0.35f
val SETTINGS_ITEM_FONT_SCALE = 0.5f
//----------------PREFERENCES----------------------
var VIRTUAL_JOYSTICK = 0
var VIRTUAL_JOYSTICK_NONE = 0
var VIRTUAL_JOYSTICK_LEFT = 1
var VIRTUAL_JOYSTICK_RIGHT = 2
var SOUND_ENABLED = true
var SOUND_VOLUME = 0.7f
var MUSIC_ENABLED = true
//----------------GAME-DATA----------------------
var LEVEL = 1
var PLAYER_NAME = ""
fun loadPreferences() {
with(gamePreferences) {
LEVEL = getInteger("LEVEL", 1)
MUSIC_ENABLED = getBoolean("MUSICENABLED", true)
SOUND_ENABLED = getBoolean("SOUNDENABLED", true)
SOUND_VOLUME = getFloat("SOUNDVOLUME", 0.5f)
PLAYER_NAME = getString("PLAYERNAME", "")
val preferredJoystick = when (Gdx.app.type) {
Desktop -> VIRTUAL_JOYSTICK_NONE
else -> VIRTUAL_JOYSTICK_RIGHT
}
VIRTUAL_JOYSTICK = getInteger("VIRTUALJOYSTICK", preferredJoystick)
}
}
fun savePreferences() {
with(gamePreferences) {
putInteger("LEVEL", LEVEL)
putInteger("VIRTUALJOYSTICK", VIRTUAL_JOYSTICK)
putBoolean("SOUNDENABLED", SOUND_ENABLED)
putBoolean("MUSICENABLED", MUSIC_ENABLED)
putFloat("SOUNDVOLUME", SOUND_VOLUME)
putString("PLAYERNAME", PLAYER_NAME)
flush()
}
}
fun levelUp() {
LEVEL++
gamePreferences.putInteger("LEVEL", GameData.LEVEL)
gamePreferences.flush()
}
}
| gpl-3.0 | ede52654dbf447b584d3491a03d87517 | 29.329412 | 98 | 0.606284 | 4.391823 | false | false | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.kt | 1 | 3882 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("PluginsAdvertiser")
package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginNode
import com.intellij.ide.plugins.RepositoryHelper
import com.intellij.ide.plugins.advertiser.PluginData
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationGroupManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.PlatformUtils.isIdeaUltimate
import org.jetbrains.annotations.ApiStatus
import java.io.IOException
private const val IGNORE_ULTIMATE_EDITION = "ignoreUltimateEdition"
@get:JvmName("getLog")
internal val LOG = Logger.getInstance("#PluginsAdvertiser")
private val propertiesComponent
get() = PropertiesComponent.getInstance()
var isIgnoreIdeSuggestion: Boolean
get() = propertiesComponent.isTrueValue(IGNORE_ULTIMATE_EDITION)
set(value) = propertiesComponent.setValue(IGNORE_ULTIMATE_EDITION, value)
@JvmField
@ApiStatus.ScheduledForRemoval
@Deprecated("Use `notificationGroup` property")
val NOTIFICATION_GROUP = notificationGroup
val notificationGroup: NotificationGroup
get() = NotificationGroupManager.getInstance().getNotificationGroup("Plugins Suggestion")
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use `installAndEnable(Project, Set, Boolean, Runnable)`")
fun installAndEnablePlugins(
pluginIds: Set<String>,
onSuccess: Runnable,
) {
installAndEnable(
LinkedHashSet(pluginIds.map { PluginId.getId(it) }),
onSuccess,
)
}
@Deprecated("Use `installAndEnable(Project, Set, Boolean, Runnable)`")
fun installAndEnable(
pluginIds: Set<PluginId>,
onSuccess: Runnable,
) = installAndEnable(null, pluginIds, true, false, null, onSuccess)
@JvmOverloads
fun installAndEnable(
project: Project?,
pluginIds: Set<PluginId>,
showDialog: Boolean = false,
selectAlInDialog: Boolean = false,
modalityState: ModalityState? = null,
onSuccess: Runnable,
) {
require(!showDialog || modalityState == null) {
"`modalityState` can be not null only if plugin installation won't show the dialog"
}
ProgressManager.getInstance().run(InstallAndEnableTask(project, pluginIds, showDialog, selectAlInDialog, modalityState, onSuccess))
}
internal fun getBundledPluginToInstall(
plugins: Collection<PluginData>,
descriptorsById: Map<PluginId, IdeaPluginDescriptor> = PluginManagerCore.buildPluginIdMap(),
): List<String> {
return if (isIdeaUltimate()) {
emptyList()
}
else {
plugins.filter { it.isBundled }
.filterNot { descriptorsById.containsKey(it.pluginId) }
.map { it.pluginName }
}
}
/**
* Loads list of plugins, compatible with a current build, from all configured repositories
*/
@JvmOverloads
internal fun loadPluginsFromCustomRepositories(indicator: ProgressIndicator? = null): List<PluginNode> {
return RepositoryHelper
.getPluginHosts()
.filterNot {
it == null
&& ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()
}.flatMap {
try {
RepositoryHelper.loadPlugins(it, null, indicator)
}
catch (e: IOException) {
LOG.info("Couldn't load plugins from $it: $e")
LOG.debug(e)
emptyList<PluginNode>()
}
}.distinctBy { it.pluginId }
}
| apache-2.0 | e43b3c4507ab34ed8998f2256a96b6cd | 33.353982 | 158 | 0.776146 | 4.572438 | false | false | false | false |
wojta/serverless-webrtc-android | app/src/main/kotlin/cz/sazel/android/serverlesswebrtcandroid/adapters/ConsoleAdapter.kt | 1 | 1781 | package cz.sazel.android.serverlesswebrtcandroid.adapters
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Context.CLIPBOARD_SERVICE
import android.os.Build
import android.support.v7.widget.RecyclerView
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
import cz.sazel.android.serverlesswebrtcandroid.R
import org.jetbrains.anko.find
/**
* This is just to do the printing into the RecyclerView.
*/
class ConsoleAdapter(val items: List<String>) : RecyclerView.Adapter<ConsoleAdapter.ConsoleVH>() {
@Suppress("DEPRECATION")
override fun onBindViewHolder(holder: ConsoleVH, position: Int) {
holder.tvText.text = Html.fromHtml(items[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConsoleVH {
val view = LayoutInflater.from(parent.context).inflate(R.layout.l_item, parent, false)
return ConsoleVH(view)
}
override fun getItemCount(): Int = items.count()
class ConsoleVH(view: View) : RecyclerView.ViewHolder(view) {
var tvText: TextView = view.find(R.id.tvText)
init {
tvText.setOnLongClickListener {
//clipboard on long touch
val text = tvText.text.toString()
val clipboard = tvText.context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
clipboard.primaryClip = ClipData.newPlainText("text", text)
Toast.makeText(tvText.context, R.string.clipboard_copy, LENGTH_SHORT).show()
true
}
}
}
}
| unlicense | 093f2154813d9a8c25fc84a23f384edb | 31.981481 | 102 | 0.713644 | 4.365196 | false | false | false | false |
C06A/KUrlet | src/main/kotlin/com/helpchoice/kotlin/urlet/Expression.kt | 1 | 5479 | package com.helpchoice.kotlin.urlet
/**
* Holds a single substitution placeholder with leading literal in front of it
*
*
*/
abstract class Expression(private val prefix: String, placeholder: String?) {
val type: Char?
var names: Collection<Triple<String, Int?, Char?>> = listOf()
init {
if (placeholder == null) {
type = null
} else {
var holder = placeholder
if (holder[0] in "/?&@+#;.") {
type = holder[0]
holder = placeholder.substring(1)
} else {
type = null
}
holder.split(',').map { variable: String ->
val multiplier = if (variable.last() == '*') '*' else null
val name =
multiplier?.let {
variable.dropLast(1)
} ?: variable
val splits = name.split(':')
if (splits.size > 1) {
names += Triple(splits[0], splits[1].toInt(), multiplier)
} else {
names += Triple(splits[0], null, multiplier)
}
}
}
}
fun appendTo(buffer: StringBuilder, with: Map<String, Any?>) {
buffer.append(prefix)
var separator = """${type ?: ""}"""
var preparator = separator
when (type) {
null -> {
separator = ","
preparator = ""
}
'?' -> {
separator = "&"
preparator = if (buffer.toString().contains('?')) "&" else "?"
}
'+' -> {
separator = ","
preparator = ""
}
'#' -> {
separator = ","
}
}
for (varDeclaration in names) {
val variable = with[varDeclaration.first]
fun incode(value: String, limit: Int?): String {
var str = value
str = str.substring(0, minOf(str.length, limit ?: str.length))
str = if (type == null || !"+#".contains(type)) {
encode(str).replace("+", "%20")
} else {
str.replace(" ", "%20")
}
return str
}
when {
variable is Collection<*> -> {
if (variable.isNotEmpty()) {
var prefix = "$type"
var infix: String
when (type) {
null, '+' -> {
prefix = ""
infix = ","
}
'#' -> {
infix = ","
}
';', '&' -> {
prefix = "$type${varDeclaration.first}="
infix = prefix
}
'?' -> {
prefix = "?${varDeclaration.first}="
infix = "&${varDeclaration.first}="
}
else -> {
infix = prefix
}
}
if (varDeclaration.third != '*') {
infix = ","
}
variable.mapNotNull {
incode(it.toString(), varDeclaration.second)
}.joinTo(buffer, infix, prefix)
}
}
variable is Map<*, *> -> {
if (variable.isNotEmpty()) {
val mapped = variable.mapNotNull {
val str = incode(it.value.toString(), varDeclaration.second)
"${it.key}${if (varDeclaration.third == '*') "=" else ","}$str"
}
if (varDeclaration.third == '*') {
mapped.joinTo(buffer, separator, preparator)
} else {
mapped.joinTo(buffer, ","
, preparator + if (type != null && ";?&".contains(type)) "${varDeclaration.first}=" else "")
}
}
}
variable != null -> {
var str = incode(variable.toString(), varDeclaration.second)
buffer.append(preparator)
type?.let {
if (";?&".contains(type)) {
buffer.append(varDeclaration.first)
if (type != ';' || str.isNotEmpty()) {
buffer.append(if (varDeclaration.third == '*') separator else "=")
}
}
}
buffer.append(str)
}
}
if (type == null || "+#?".contains(type)) {
preparator = if (variable != null) separator else preparator
}
}
}
fun getNames(): Iterable<String> {
return names.map { name: Triple<String, Int?, Char?> ->
name.first
}
}
abstract fun encode(str: String): String
} | apache-2.0 | babc8118a4eb58494e26b46396255699 | 34.354839 | 128 | 0.352254 | 5.872454 | false | false | false | false |
caarmen/FRCAndroidWidget | app/src/main/kotlin/ca/rmen/android/frccommon/compat/NotificationCompat.kt | 1 | 4345 | /*
* French Revolutionary Calendar Android Widget
* Copyright (C) 2016-2017 Carmen Alvarez
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package ca.rmen.android.frccommon.compat
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.support.annotation.ColorInt
import android.support.annotation.DrawableRes
import android.util.Log
import ca.rmen.android.frccommon.Action
import ca.rmen.android.frccommon.Constants
import ca.rmen.android.frenchcalendar.R
import java.lang.reflect.InvocationTargetException
object NotificationCompat {
private val TAG = Constants.TAG + NotificationCompat::class.java.simpleName
fun getNotificationPriority(priority: String): Int =
if (ApiHelper.apiLevel < 16) {
0
} else {
Api16Helper.getNotificationPriority(priority)
}
fun createNotification(context: Context,
priority: Int,
@ColorInt color: Int,
tickerText: String,
contentText: String,
bigText: String,
defaultIntent: PendingIntent,
vararg actions: Action): Notification {
@DrawableRes val iconId: Int = R.drawable.ic_notif
when {
ApiHelper.apiLevel < 11 -> {
val notification = Notification()
notification.tickerText = tickerText
notification.`when` = System.currentTimeMillis()
@Suppress("DEPRECATION")
notification.icon = iconId
notification.contentIntent = defaultIntent
notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL
// Google removed setLatestEventInfo in sdk 23.
try {
val method = Notification::class.java.getMethod("setLatestEventInfo", Context::class.java, CharSequence::class.java, CharSequence::class.java, PendingIntent::class.java)
method.invoke(notification, context, tickerText, contentText, defaultIntent)
} catch (e: NoSuchMethodException) {
Log.v(TAG, "Error creating notification", e)
} catch (e: IllegalAccessException) {
Log.v(TAG, "Error creating notification", e)
} catch (e: InvocationTargetException) {
Log.v(TAG, "Error creating notification", e)
}
return notification
}
ApiHelper.apiLevel < 16 -> return Api11Helper.createNotification(context, iconId, tickerText, contentText, defaultIntent)
// convoluted way to pass actions. We have to convert from vararg to array, because the spread operator (*) crashes on cupcake.
// Arrays.copyOf() is used by the spread operator, and this doesn't exist on cupcake.
ApiHelper.apiLevel < 20 -> return Api16Helper.createNotification(context, priority, iconId, tickerText, contentText, bigText, defaultIntent, Array(actions.size) { actions[it] })
ApiHelper.apiLevel < 23 -> return Api20Helper.createNotification(context, priority, iconId, color, tickerText, contentText, bigText, defaultIntent, Array(actions.size) { actions[it] })
ApiHelper.apiLevel < 26 -> return Api23Helper.createNotification(context, priority, iconId, color, tickerText, contentText, bigText, defaultIntent, Array(actions.size) { actions[it] })
else -> return Api26Helper.createNotification(context, iconId, color, tickerText, contentText, bigText, defaultIntent, Array(actions.size) { actions[it] })
}
}
}
| gpl-3.0 | 9a8c1dddeb22da273a9d1ce573f05a32 | 51.987805 | 196 | 0.656847 | 5.028935 | false | false | false | false |
AberrantFox/hotbot | src/test/kotlin/me/aberrantfox/hotbot/permissions/RoleRequiredTest.kt | 1 | 2679 | package me.aberrantfox.hotbot.permissions
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import kotlinx.coroutines.experimental.runBlocking
import me.aberrantfox.hotbot.dsls.command.Command
import me.aberrantfox.hotbot.dsls.command.CommandsContainer
import me.aberrantfox.hotbot.services.Configuration
import me.aberrantfox.hotbot.services.ServerInformation
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.entities.Guild
import net.dv8tion.jda.core.entities.Member
import net.dv8tion.jda.core.entities.Role
import net.dv8tion.jda.core.entities.User
import org.junit.*
import java.io.File
import java.nio.file.Files
private const val commandName = "test-command"
private const val permsFilePath = "fake-path"
class PermissionTests {
companion object {
@BeforeClass
@JvmStatic
fun beforeAll() = cleanupFiles()
@AfterClass
@JvmStatic
fun afterAll() = cleanupFiles()
}
private lateinit var manager: PermissionManager
@Before
fun beforeEach() { manager = produceManager() }
@Test
fun correctPermissionIsStored() = assert(manager.roleRequired(commandName) == PermissionLevel.JrMod)
@Test
fun permissionStoredIsNotEqualToOtherPermissions() = assert(manager.roleRequired(commandName) != PermissionLevel.Moderator)
@Test
fun unknownCommandIsOfLevelOwner() = assert(manager.roleRequired("unknown-cmd-test") == PermissionLevel.Owner)
}
private fun produceManager(): PermissionManager {
val userMock = mock<User> {
on { id } doReturn "non-blank"
}
val memberMock = mock<Member> {
on { roles } doReturn listOf<Role>()
}
val guildMock = mock<Guild> {
on { getMember(userMock) } doReturn memberMock
}
val commandMock = mock<Command> {
on { name } doReturn commandName
}
val containerMock = mock<CommandsContainer> {
on { commands } doReturn hashMapOf(commandName to commandMock)
}
val serverInformationMock = mock<ServerInformation> {
on { ownerID } doReturn ""
on { guildid } doReturn "guildid"
}
val config = mock<Configuration> {
on { serverInformation } doReturn serverInformationMock
}
val jdaMock = mock<JDA> {
on { getGuildById(config.serverInformation.guildid) } doReturn guildMock
}
val manager = PermissionManager(jdaMock, containerMock, config, permsFilePath)
runBlocking { manager.setPermission(commandName, PermissionLevel.JrMod).join() }
return manager
}
private fun cleanupFiles() {
val permsFile = File(permsFilePath)
Files.deleteIfExists(permsFile.toPath())
} | mit | 491d8465a358fb8781b4ea42a93e3f4d | 28.130435 | 127 | 0.720045 | 4.265924 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/ChangeMethodParameters.kt | 4 | 10457 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix.crossLanguage
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.lang.jvm.actions.AnnotationRequest
import com.intellij.lang.jvm.actions.ChangeParametersRequest
import com.intellij.lang.jvm.actions.ExpectedParameter
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JvmPsiConversionHelper
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.resolveToKotlinType
import org.jetbrains.kotlin.load.java.NOT_NULL_ANNOTATIONS
import org.jetbrains.kotlin.load.java.NULLABLE_ANNOTATIONS
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
internal class ChangeMethodParameters(
target: KtNamedFunction,
val request: ChangeParametersRequest
) : KotlinQuickFixAction<KtNamedFunction>(target) {
override fun getText(): String {
val target = element ?: return KotlinBundle.message("fix.change.signature.unavailable")
val helper = JvmPsiConversionHelper.getInstance(target.project)
val parametersString = request.expectedParameters.joinToString(", ", "(", ")") { ep ->
val kotlinType =
ep.expectedTypes.firstOrNull()?.theType?.let { helper.convertType(it).resolveToKotlinType(target.getResolutionFacade()) }
val parameterName = ep.semanticNames.firstOrNull() ?: KotlinBundle.message("fix.change.signature.unnamed.parameter")
"$parameterName: ${kotlinType?.let {
IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it)
} ?: KotlinBundle.message("fix.change.signature.error")}"
}
val shortenParameterString = StringUtil.shortenTextWithEllipsis(parametersString, 30, 5)
return QuickFixBundle.message("change.method.parameters.text", shortenParameterString)
}
override fun getFamilyName(): String = QuickFixBundle.message("change.method.parameters.family")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null && request.isValid
private sealed class ParameterModification {
data class Keep(val ktParameter: KtParameter) : ParameterModification()
data class Remove(val ktParameter: KtParameter) : ParameterModification()
data class Add(
val name: String,
val ktType: KotlinType,
val expectedAnnotations: Collection<AnnotationRequest>,
val beforeAnchor: KtParameter?
) : ParameterModification()
}
private tailrec fun getParametersModifications(
target: KtNamedFunction,
currentParameters: List<KtParameter>,
expectedParameters: List<ExpectedParameter>,
index: Int = 0,
collected: List<ParameterModification> = ArrayList(expectedParameters.size)
): List<ParameterModification> {
val expectedHead = expectedParameters.firstOrNull() ?: return collected + currentParameters.map { ParameterModification.Remove(it) }
if (expectedHead is ChangeParametersRequest.ExistingParameterWrapper) {
val expectedExistingParameter = expectedHead.existingKtParameter
if (expectedExistingParameter == null) {
LOG.error("can't find the kotlinOrigin for parameter ${expectedHead.existingParameter} at index $index")
return collected
}
val existingInTail = currentParameters.indexOf(expectedExistingParameter)
if (existingInTail == -1) {
throw IllegalArgumentException("can't find existing for parameter ${expectedHead.existingParameter} at index $index")
}
return getParametersModifications(
target,
currentParameters.subList(existingInTail + 1, currentParameters.size),
expectedParameters.subList(1, expectedParameters.size),
index,
collected
+ currentParameters.subList(0, existingInTail).map { ParameterModification.Remove(it) }
+ ParameterModification.Keep(expectedExistingParameter)
)
}
val helper = JvmPsiConversionHelper.getInstance(target.project)
val theType = expectedHead.expectedTypes.firstOrNull()?.theType ?: return emptyList()
val kotlinType = helper.convertType(theType).resolveToKotlinType(target.getResolutionFacade()) ?: return emptyList()
return getParametersModifications(
target,
currentParameters,
expectedParameters.subList(1, expectedParameters.size),
index + 1,
collected + ParameterModification.Add(
expectedHead.semanticNames.firstOrNull() ?: "param$index",
kotlinType,
expectedHead.expectedAnnotations,
currentParameters.firstOrNull { anchor ->
expectedParameters.any {
it is ChangeParametersRequest.ExistingParameterWrapper && it.existingKtParameter == anchor
}
})
)
}
private val ChangeParametersRequest.ExistingParameterWrapper.existingKtParameter
get() = (existingParameter as? KtLightElement<*, *>)?.kotlinOrigin as? KtParameter
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (!request.isValid) return
val target = element ?: return
val functionDescriptor = target.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return
val parameterActions = getParametersModifications(target, target.valueParameters, request.expectedParameters)
val parametersGenerated = parameterActions.filterIsInstance<ParameterModification.Add>().let {
it zip generateParameterList(project, functionDescriptor, it).parameters
}.toMap()
for (action in parameterActions) {
when (action) {
is ParameterModification.Add -> {
val parameter = parametersGenerated.getValue(action)
for (expectedAnnotation in action.expectedAnnotations.reversed()) {
addAnnotationEntry(parameter, expectedAnnotation, null)
}
val anchor = action.beforeAnchor
if (anchor != null) {
target.valueParameterList!!.addParameterBefore(parameter, anchor)
} else {
target.valueParameterList!!.addParameter(parameter)
}
}
is ParameterModification.Keep -> {
// Do nothing
}
is ParameterModification.Remove -> {
target.valueParameterList!!.removeParameter(action.ktParameter)
}
}
}
ShortenReferences.DEFAULT.process(target.valueParameterList!!)
}
private fun generateParameterList(
project: Project,
functionDescriptor: FunctionDescriptor,
paramsToAdd: List<ParameterModification.Add>
): KtParameterList {
val newFunctionDescriptor = SimpleFunctionDescriptorImpl.create(
functionDescriptor.containingDeclaration,
functionDescriptor.annotations,
functionDescriptor.name,
functionDescriptor.kind,
SourceElement.NO_SOURCE
).apply {
initialize(
functionDescriptor.extensionReceiverParameter?.copy(this),
functionDescriptor.dispatchReceiverParameter,
functionDescriptor.contextReceiverParameters.map { it.copy(this) },
functionDescriptor.typeParameters,
paramsToAdd.mapIndexed { index, parameter ->
ValueParameterDescriptorImpl(
this, null, index, Annotations.EMPTY,
Name.identifier(parameter.name),
parameter.ktType, declaresDefaultValue = false,
isCrossinline = false, isNoinline = false, varargElementType = null, source = SourceElement.NO_SOURCE
)
},
functionDescriptor.returnType,
functionDescriptor.modality,
functionDescriptor.visibility
)
}
val renderer = IdeDescriptorRenderers.SOURCE_CODE.withOptions {
defaultParameterValueRenderer = null
}
val newFunction = KtPsiFactory(project).createFunction(renderer.render(newFunctionDescriptor)).apply {
valueParameters.forEach { param ->
param.annotationEntries.forEach { a ->
a.typeReference?.run {
val fqName = FqName(this.text)
if (fqName in (NULLABLE_ANNOTATIONS + NOT_NULL_ANNOTATIONS)) a.delete()
}
}
}
}
return newFunction.valueParameterList!!
}
companion object {
fun create(ktNamedFunction: KtNamedFunction, request: ChangeParametersRequest): ChangeMethodParameters =
ChangeMethodParameters(ktNamedFunction, request)
private val LOG = Logger.getInstance(ChangeMethodParameters::class.java)
}
}
| apache-2.0 | ab1633850da6fa98c572f83dff46a2f9 | 44.663755 | 140 | 0.671321 | 5.874719 | false | false | false | false |
pdvrieze/kotlinsql | util/src/main/kotlin/io/github/pdvrieze/jdbc/recorder/AbstractRecordingResultSet.kt | 1 | 29566 | /*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.jdbc.recorder
import io.github.pdvrieze.jdbc.recorder.actions.ResultSetClose
import io.github.pdvrieze.jdbc.recorder.actions.StringAction
import java.io.InputStream
import java.io.Reader
import java.lang.Exception
import java.math.BigDecimal
import java.net.URL
import java.sql.*
import java.sql.Array as SqlArray
import java.sql.Date
import java.util.*
abstract class AbstractRecordingResultSet(
delegate: ResultSet,
val query: String
) : WrappingActionRecorder<ResultSet>(delegate), ResultSet {
protected val columnNames = arrayOfNulls<String>(delegate.metaData.columnCount)
protected inline fun <R> recordGet(columnNo: Int, crossinline action: () -> R): R {
return action().also {
val p = columnNames[columnNo-1]?.let { n -> "$columnNo ~> $n"} ?: columnNo.toString()
recordRes3(it, p)
}
}
protected inline fun <R> recordGet(columnNo: Int, arg2: Any?, crossinline action: () -> R): R {
return action().also {
val p = columnNames[columnNo-1]?.let { n -> "$columnNo ~> $n"} ?: columnNo.toString()
recordRes3(it, p, arg2)
}
}
protected fun <R> recordRes3(result: R, columnIndex: String, arg2: Any? = Unit): R {
val calledFunction = Exception().stackTrace[2].methodName
val arg2s = if (arg2==Unit) "" else ", ${arg2.stringify()}"
val ac = when {
result == Unit -> StringAction("$this.$calledFunction($columnIndex$arg2s)")
else -> StringAction("$this.$calledFunction($columnIndex$arg2s) -> ${result.stringify()}")
}
recordAction(ac)
return result
}
protected fun recordUpdate(columnNo: Int, vararg args: Any?) {
val p = columnNames[columnNo-1]?.let { n -> "$columnNo -> $n"} ?: columnNo.toString()
val calledFunction = Exception().stackTrace[1].methodName
val ac = StringAction("$this.$calledFunction($p, ${args.joinToString()})")
recordAction(ac)
}
override fun absolute(row: Int): Boolean = record(row) {
delegate.absolute(row)
}
override fun afterLast() {
record()
delegate.afterLast()
}
override fun beforeFirst() {
record()
delegate.beforeFirst()
}
override fun cancelRowUpdates() {
record()
delegate.cancelRowUpdates()
}
override fun clearWarnings() {
record()
delegate.clearWarnings()
}
override fun close() {
recordAction(ResultSetClose)
}
override fun deleteRow() {
record()
delegate.deleteRow()
}
override fun findColumn(columnLabel: String): Int = record(columnLabel) {
delegate.findColumn(columnLabel).also { columnNames[it-1] = columnLabel }
}
override fun first(): Boolean = record {
delegate.first()
}
override fun getArray(columnIndex: Int): SqlArray = recordGet(columnIndex) {
delegate.getArray(columnIndex)
}
override fun getArray(columnLabel: String?): SqlArray = record(columnLabel) {
delegate.getArray(columnLabel)
}
override fun getAsciiStream(columnIndex: Int): InputStream = recordGet(columnIndex) {
delegate.getAsciiStream(columnIndex)
}
override fun getAsciiStream(columnLabel: String?): InputStream = record(columnLabel) {
delegate.getAsciiStream(columnLabel)
}
override fun getBigDecimal(columnIndex: Int, scale: Int): BigDecimal = recordGet(columnIndex, scale) {
@Suppress("DEPRECATION")
delegate.getBigDecimal(columnIndex, scale)
}
override fun getBigDecimal(columnLabel: String?, scale: Int): BigDecimal = record(columnLabel, scale) {
@Suppress("DEPRECATION")
delegate.getBigDecimal(columnLabel, scale)
}
override fun getBigDecimal(columnIndex: Int): BigDecimal = recordGet(columnIndex) {
delegate.getBigDecimal(columnIndex)
}
override fun getBigDecimal(columnLabel: String?): BigDecimal = record(columnLabel) {
delegate.getBigDecimal(columnLabel)
}
override fun getBinaryStream(columnIndex: Int): InputStream = recordGet(columnIndex) {
delegate.getBinaryStream(columnIndex)
}
override fun getBinaryStream(columnLabel: String?): InputStream = record(columnLabel) {
delegate.getBinaryStream(columnLabel)
}
override fun getBlob(columnIndex: Int): Blob = recordGet(columnIndex) {
delegate.getBlob(columnIndex)
}
override fun getBlob(columnLabel: String?): Blob = record(columnLabel) {
delegate.getBlob(columnLabel)
}
override fun getBoolean(columnIndex: Int): Boolean = recordGet(columnIndex) {
delegate.getBoolean(columnIndex)
}
override fun getBoolean(columnLabel: String?): Boolean = record(columnLabel) {
delegate.getBoolean(columnLabel)
}
override fun getByte(columnIndex: Int): Byte = recordGet(columnIndex) {
delegate.getByte(columnIndex)
}
override fun getByte(columnLabel: String?): Byte = record(columnLabel) {
delegate.getByte(columnLabel)
}
override fun getBytes(columnIndex: Int): ByteArray = recordGet(columnIndex) {
delegate.getBytes(columnIndex)
}
override fun getBytes(columnLabel: String?): ByteArray = record(columnLabel) {
delegate.getBytes(columnLabel)
}
override fun getCharacterStream(columnIndex: Int): Reader = recordGet(columnIndex) {
delegate.getCharacterStream(columnIndex)
}
override fun getCharacterStream(columnLabel: String?): Reader = record(columnLabel) {
delegate.getCharacterStream(columnLabel)
}
override fun getClob(columnIndex: Int): Clob = recordGet(columnIndex) {
delegate.getClob(columnIndex)
}
override fun getClob(columnLabel: String?): Clob = record(columnLabel) {
delegate.getClob(columnLabel)
}
override fun getConcurrency(): Int = record {
delegate.concurrency
}
override fun getCursorName(): String = record {
delegate.cursorName
}
override fun getDate(columnIndex: Int): Date = recordGet(columnIndex) {
delegate.getDate(columnIndex)
}
override fun getDate(columnLabel: String?): Date = record(columnLabel) {
delegate.getDate(columnLabel)
}
override fun getDate(columnIndex: Int, cal: Calendar?): Date = recordGet(columnIndex, cal) {
delegate.getDate(columnIndex, cal)
}
override fun getDate(columnLabel: String?, cal: Calendar?): Date = record(columnLabel, cal) {
delegate.getDate(columnLabel, cal)
}
override fun getDouble(columnIndex: Int): Double = recordGet(columnIndex) {
delegate.getDouble(columnIndex)
}
override fun getDouble(columnLabel: String?): Double = record(columnLabel) {
delegate.getDouble(columnLabel)
}
override fun getFetchDirection(): Int = record {
delegate.fetchDirection
}
override fun getFetchSize(): Int = record {
delegate.fetchSize
}
override fun getFloat(columnIndex: Int): Float = recordGet(columnIndex) {
delegate.getFloat(columnIndex)
}
override fun getFloat(columnLabel: String?): Float = record(columnLabel) {
delegate.getFloat(columnLabel)
}
override fun getHoldability(): Int = record {
delegate.holdability
}
override fun getInt(columnIndex: Int): Int = recordGet(columnIndex) {
delegate.getInt(columnIndex)
}
override fun getInt(columnLabel: String): Int = record(columnLabel){
delegate.getInt(columnLabel)
}
override fun getLong(columnIndex: Int): Long = recordGet(columnIndex) {
delegate.getLong(columnIndex)
}
override fun getLong(columnLabel: String?): Long = record(columnLabel) {
delegate.getLong(columnLabel)
}
abstract override fun getMetaData(): AbstractRecordingResultsetMetaData
override fun getNCharacterStream(columnIndex: Int): Reader = recordGet(columnIndex) {
delegate.getNCharacterStream(columnIndex)
}
override fun getNCharacterStream(columnLabel: String?): Reader = record(columnLabel) {
delegate.getNCharacterStream(columnLabel)
}
override fun getNClob(columnIndex: Int): NClob = recordGet(columnIndex) {
delegate.getNClob(columnIndex)
}
override fun getNClob(columnLabel: String?): NClob = record(columnLabel) {
delegate.getNClob(columnLabel)
}
override fun getNString(columnIndex: Int): String = recordGet(columnIndex) {
delegate.getNString(columnIndex)
}
override fun getNString(columnLabel: String?): String = record(columnLabel) {
delegate.getNString(columnLabel)
}
override fun getObject(columnIndex: Int): Any = recordGet(columnIndex) {
delegate.getObject(columnIndex)
}
override fun getObject(columnLabel: String?): Any = record(columnLabel) {
delegate.getObject(columnLabel)
}
override fun getObject(columnIndex: Int, map: MutableMap<String, Class<*>>): Any = recordGet(columnIndex, map) {
delegate.getObject(columnIndex, map)
}
override fun getObject(columnLabel: String?, map: MutableMap<String, Class<*>>): Any = record(columnLabel, map) {
delegate.getObject(columnLabel, map)
}
override fun <T : Any?> getObject(columnIndex: Int, type: Class<T>?): T = recordGet(columnIndex, type) {
delegate.getObject(columnIndex, type)
}
override fun <T : Any?> getObject(columnLabel: String?, type: Class<T>?): T = record(columnLabel, type) {
delegate.getObject(columnLabel, type)
}
override fun getRef(columnIndex: Int): Ref = recordGet(columnIndex) {
delegate.getRef(columnIndex)
}
override fun getRef(columnLabel: String?): Ref = record(columnLabel) {
delegate.getRef(columnLabel)
}
override fun getRow(): Int = record {
delegate.row
}
override fun getRowId(columnIndex: Int): RowId = recordGet(columnIndex) {
delegate.getRowId(columnIndex)
}
override fun getRowId(columnLabel: String?): RowId = record(columnLabel) {
delegate.getRowId(columnLabel)
}
override fun getShort(columnIndex: Int): Short = recordGet(columnIndex) {
delegate.getShort(columnIndex)
}
override fun getShort(columnLabel: String?): Short = record(columnLabel) {
delegate.getShort(columnLabel)
}
override fun getSQLXML(columnIndex: Int): SQLXML = recordGet(columnIndex) {
delegate.getSQLXML(columnIndex)
}
override fun getSQLXML(columnLabel: String?): SQLXML = record(columnLabel) {
delegate.getSQLXML(columnLabel)
}
override fun getStatement(): Statement = record {
delegate.statement
}
override fun getString(columnIndex: Int): String? = recordGet(columnIndex) {
delegate.getString(columnIndex)
}
override fun getString(columnLabel: String): String? = record {
delegate.getString(columnLabel)
}
override fun getTime(columnIndex: Int): Time = recordGet(columnIndex) {
delegate.getTime(columnIndex)
}
override fun getTime(columnLabel: String?): Time = record(columnLabel) {
delegate.getTime(columnLabel)
}
override fun getTime(columnIndex: Int, cal: Calendar?): Time = recordGet(columnIndex, cal) {
delegate.getTime(columnIndex, cal)
}
override fun getTime(columnLabel: String?, cal: Calendar?): Time = record(columnLabel, cal) {
delegate.getTime(columnLabel, cal)
}
override fun getTimestamp(columnIndex: Int): Timestamp = recordGet(columnIndex) {
delegate.getTimestamp(columnIndex)
}
override fun getTimestamp(columnLabel: String?): Timestamp = record(columnLabel) {
delegate.getTimestamp(columnLabel)
}
override fun getTimestamp(columnIndex: Int, cal: Calendar?): Timestamp = recordGet(columnIndex, cal) {
delegate.getTimestamp(columnIndex, cal)
}
override fun getTimestamp(columnLabel: String?, cal: Calendar?): Timestamp = record(columnLabel, cal) {
delegate.getTimestamp(columnLabel, cal)
}
override fun getType(): Int = record {
delegate.type
}
override fun getUnicodeStream(columnIndex: Int): InputStream = recordGet(columnIndex) {
@Suppress("DEPRECATION")
delegate.getUnicodeStream(columnIndex)
}
override fun getUnicodeStream(columnLabel: String?): InputStream = record(columnLabel) {
@Suppress("DEPRECATION")
delegate.getUnicodeStream(columnLabel)
}
override fun getURL(columnIndex: Int): URL = recordGet(columnIndex) {
delegate.getURL(columnIndex)
}
override fun getURL(columnLabel: String?): URL = record(columnLabel) {
delegate.getURL(columnLabel)
}
override fun getWarnings(): SQLWarning = record {
delegate.warnings
}
override fun insertRow() {
record()
delegate.insertRow()
}
override fun isAfterLast(): Boolean = record {
delegate.isAfterLast
}
override fun isBeforeFirst(): Boolean = record {
delegate.isBeforeFirst
}
override fun isClosed(): Boolean = record {
delegate.isClosed
}
override fun isFirst(): Boolean = record {
delegate.isFirst
}
override fun isLast(): Boolean = record {
delegate.isLast
}
override fun last(): Boolean = record {
delegate.last()
}
override fun moveToCurrentRow() {
record()
delegate.moveToCurrentRow()
}
override fun moveToInsertRow() {
record()
delegate.moveToInsertRow()
}
override fun relative(rows: Int): Boolean = record(rows) {
delegate.relative(rows)
}
override fun next(): Boolean = record {
delegate.next()
}
override fun previous(): Boolean = record {
delegate.previous()
}
override fun refreshRow() {
record()
delegate.refreshRow()
}
override fun rowDeleted(): Boolean = record {
delegate.rowDeleted()
}
override fun rowInserted(): Boolean = record {
delegate.rowInserted()
}
override fun rowUpdated(): Boolean = record {
delegate.rowUpdated()
}
override fun setFetchDirection(direction: Int) {
record(direction)
delegate.fetchDirection = direction
}
override fun setFetchSize(rows: Int) {
record(rows)
delegate.fetchSize = rows
}
override fun updateArray(columnIndex: Int, x: SqlArray?) {
recordUpdate(columnIndex, x)
delegate.updateArray(columnIndex, x)
}
override fun updateArray(columnLabel: String?, x: SqlArray?) {
record(columnLabel, x)
delegate.updateArray(columnLabel, x)
}
override fun updateAsciiStream(columnIndex: Int, x: InputStream?, length: Int) {
recordUpdate(columnIndex, x, length)
delegate.updateAsciiStream(columnIndex, x, length)
}
override fun updateAsciiStream(columnLabel: String?, x: InputStream?, length: Int) {
record(columnLabel, x, length)
delegate.updateAsciiStream(columnLabel, x, length)
}
override fun updateAsciiStream(columnIndex: Int, x: InputStream?, length: Long) {
recordUpdate(columnIndex, x, length)
delegate.updateAsciiStream(columnIndex, x, length)
}
override fun updateAsciiStream(columnLabel: String?, x: InputStream?, length: Long) {
record(columnLabel, x, length)
delegate.updateAsciiStream(columnLabel, x, length)
}
override fun updateAsciiStream(columnIndex: Int, x: InputStream?) {
recordUpdate(columnIndex, x)
delegate.updateAsciiStream(columnIndex, x)
}
override fun updateAsciiStream(columnLabel: String?, x: InputStream?) {
record(columnLabel, x)
delegate.updateAsciiStream(columnLabel, x)
}
override fun updateBigDecimal(columnIndex: Int, x: BigDecimal?) {
recordUpdate(columnIndex, x)
delegate.updateBigDecimal(columnIndex, x)
}
override fun updateBigDecimal(columnLabel: String?, x: BigDecimal?) {
record(columnLabel, x)
delegate.updateBigDecimal(columnLabel, x)
}
override fun updateBinaryStream(columnIndex: Int, x: InputStream?, length: Int) {
recordUpdate(columnIndex, x, length)
delegate.updateBinaryStream(columnIndex, x, length)
}
override fun updateBinaryStream(columnLabel: String?, x: InputStream?, length: Int) {
record(columnLabel, x, length)
delegate.updateBinaryStream(columnLabel, x, length)
}
override fun updateBinaryStream(columnIndex: Int, x: InputStream?, length: Long) {
recordUpdate(columnIndex, x, length)
delegate.updateBinaryStream(columnIndex, x, length)
}
override fun updateBinaryStream(columnLabel: String?, x: InputStream?, length: Long) {
record(columnLabel, x, length)
delegate.updateBinaryStream(columnLabel, x, length)
}
override fun updateBinaryStream(columnIndex: Int, x: InputStream?) {
recordUpdate(columnIndex, x)
delegate.updateBinaryStream(columnIndex, x)
}
override fun updateBinaryStream(columnLabel: String?, x: InputStream?) {
record(columnLabel, x)
delegate.updateBinaryStream(columnLabel, x)
}
override fun updateBlob(columnIndex: Int, x: Blob?) {
recordUpdate(columnIndex, x)
delegate.updateBlob(columnIndex, x)
}
override fun updateBlob(columnLabel: String?, x: Blob?) {
record(columnLabel, x)
delegate.updateBlob(columnLabel, x)
}
override fun updateBlob(columnIndex: Int, inputStream: InputStream?, length: Long) {
recordUpdate(columnIndex, inputStream, length)
delegate.updateBlob(columnIndex, inputStream, length)
}
override fun updateBlob(columnLabel: String?, inputStream: InputStream?, length: Long) {
record(columnLabel, inputStream, length)
delegate.updateBlob(columnLabel, inputStream, length)
}
override fun updateBlob(columnIndex: Int, inputStream: InputStream?) {
recordUpdate(columnIndex, inputStream)
delegate.updateBlob(columnIndex, inputStream)
}
override fun updateBlob(columnLabel: String?, inputStream: InputStream?) {
record(columnLabel, inputStream)
delegate.updateBlob(columnLabel, inputStream)
}
override fun updateBoolean(columnIndex: Int, x: Boolean) {
recordUpdate(columnIndex, x)
delegate.updateBoolean(columnIndex, x)
}
override fun updateBoolean(columnLabel: String?, x: Boolean) {
record(columnLabel, x)
delegate.updateBoolean(columnLabel, x)
}
override fun updateByte(columnIndex: Int, x: Byte) {
recordUpdate(columnIndex, x)
delegate.updateByte(columnIndex, x)
}
override fun updateByte(columnLabel: String?, x: Byte) {
record(columnLabel, x)
delegate.updateByte(columnLabel, x)
}
override fun updateBytes(columnIndex: Int, x: ByteArray?) {
recordUpdate(columnIndex, x)
delegate.updateBytes(columnIndex, x)
}
override fun updateBytes(columnLabel: String?, x: ByteArray?) {
record(columnLabel, x)
delegate.updateBytes(columnLabel, x)
}
override fun updateCharacterStream(columnIndex: Int, x: Reader?, length: Int) {
recordUpdate(columnIndex, x, length)
delegate.updateCharacterStream(columnIndex, x, length)
}
override fun updateCharacterStream(columnLabel: String?, reader: Reader?, length: Int) {
record(columnLabel, reader, length)
delegate.updateCharacterStream(columnLabel, reader, length)
}
override fun updateCharacterStream(columnIndex: Int, x: Reader?, length: Long) {
recordUpdate(columnIndex, x, length)
delegate.updateCharacterStream(columnIndex, x, length)
}
override fun updateCharacterStream(columnLabel: String?, reader: Reader?, length: Long) {
record(columnLabel, reader, length)
delegate.updateCharacterStream(columnLabel, reader, length)
}
override fun updateCharacterStream(columnIndex: Int, x: Reader?) {
recordUpdate(columnIndex, x)
delegate.updateCharacterStream(columnIndex, x)
}
override fun updateCharacterStream(columnLabel: String?, reader: Reader?) {
record(columnLabel, reader)
delegate.updateCharacterStream(columnLabel, reader)
}
override fun updateClob(columnIndex: Int, x: Clob?) {
recordUpdate(columnIndex, x)
delegate.updateClob(columnIndex, x)
}
override fun updateClob(columnLabel: String?, x: Clob?) {
record(columnLabel, x)
delegate.updateClob(columnLabel, x)
}
override fun updateClob(columnIndex: Int, reader: Reader?, length: Long) {
recordUpdate(columnIndex, reader, length)
delegate.updateClob(columnIndex, reader, length)
}
override fun updateClob(columnLabel: String?, reader: Reader?, length: Long) {
record(columnLabel, reader, length)
delegate.updateClob(columnLabel, reader, length)
}
override fun updateClob(columnIndex: Int, reader: Reader?) {
recordUpdate(columnIndex, reader)
delegate.updateClob(columnIndex, reader)
}
override fun updateClob(columnLabel: String?, reader: Reader?) {
record(columnLabel, reader)
delegate.updateClob(columnLabel, reader)
}
override fun updateDate(columnIndex: Int, x: Date?) {
recordUpdate(columnIndex, x)
delegate.updateDate(columnIndex, x)
}
override fun updateDate(columnLabel: String?, x: Date?) {
record(columnLabel, x)
delegate.updateDate(columnLabel, x)
}
override fun updateDouble(columnIndex: Int, x: Double) {
recordUpdate(columnIndex, x)
delegate.updateDouble(columnIndex, x)
}
override fun updateDouble(columnLabel: String?, x: Double) {
record(columnLabel, x)
delegate.updateDouble(columnLabel, x)
}
override fun updateFloat(columnIndex: Int, x: Float) {
recordUpdate(columnIndex, x)
delegate.updateFloat(columnIndex, x)
}
override fun updateFloat(columnLabel: String?, x: Float) {
record(columnLabel, x)
delegate.updateFloat(columnLabel, x)
}
override fun updateInt(columnIndex: Int, x: Int) {
recordUpdate(columnIndex, x)
delegate.updateInt(columnIndex, x)
}
override fun updateInt(columnLabel: String?, x: Int) {
record(columnLabel, x)
delegate.updateInt(columnLabel, x)
}
override fun updateLong(columnIndex: Int, x: Long) {
recordUpdate(columnIndex, x)
delegate.updateLong(columnIndex, x)
}
override fun updateLong(columnLabel: String?, x: Long) {
record(columnLabel, x)
delegate.updateLong(columnLabel, x)
}
override fun updateNCharacterStream(columnIndex: Int, x: Reader?, length: Long) {
recordUpdate(columnIndex, x, length)
delegate.updateNCharacterStream(columnIndex, x, length)
}
override fun updateNCharacterStream(columnLabel: String?, reader: Reader?, length: Long) {
record(columnLabel, reader, length)
delegate.updateNCharacterStream(columnLabel, reader, length)
}
override fun updateNCharacterStream(columnIndex: Int, x: Reader?) {
recordUpdate(columnIndex, x)
delegate.updateNCharacterStream(columnIndex, x)
}
override fun updateNCharacterStream(columnLabel: String?, reader: Reader?) {
record(columnLabel, reader)
delegate.updateNCharacterStream(columnLabel, reader)
}
override fun updateNClob(columnIndex: Int, nClob: NClob?) {
recordUpdate(columnIndex, nClob)
delegate.updateNClob(columnIndex, nClob)
}
override fun updateNClob(columnLabel: String?, nClob: NClob?) {
record(columnLabel, nClob)
delegate.updateNClob(columnLabel, nClob)
}
override fun updateNClob(columnIndex: Int, reader: Reader?, length: Long) {
recordUpdate(columnIndex, reader, length)
delegate.updateNClob(columnIndex, reader, length)
}
override fun updateNClob(columnLabel: String?, reader: Reader?, length: Long) {
record(columnLabel, reader, length)
delegate.updateNClob(columnLabel, reader, length)
}
override fun updateNClob(columnIndex: Int, reader: Reader?) {
recordUpdate(columnIndex, reader)
delegate.updateNClob(columnIndex, reader)
}
override fun updateNClob(columnLabel: String?, reader: Reader?) {
record(columnLabel, reader)
delegate.updateNClob(columnLabel, reader)
}
override fun updateNString(columnIndex: Int, nString: String?) {
recordUpdate(columnIndex, nString)
delegate.updateNString(columnIndex, nString)
}
override fun updateNString(columnLabel: String?, nString: String?) {
record(columnLabel, nString)
delegate.updateNString(columnLabel, nString)
}
override fun updateNull(columnIndex: Int) {
recordUpdate(columnIndex)
delegate.updateNull(columnIndex)
}
override fun updateNull(columnLabel: String?) {
record(columnLabel)
delegate.updateNull(columnLabel)
}
override fun updateObject(columnIndex: Int, x: Any?, scaleOrLength: Int) {
recordUpdate(columnIndex, x, scaleOrLength)
delegate.updateObject(columnIndex, x, scaleOrLength)
}
override fun updateObject(columnLabel: String?, x: Any?, scaleOrLength: Int) {
record(columnLabel, x, scaleOrLength)
delegate.updateObject(columnLabel, x, scaleOrLength)
}
override fun updateObject(columnIndex: Int, x: Any?) {
recordUpdate(columnIndex, x)
delegate.updateObject(columnIndex, x)
}
override fun updateObject(columnLabel: String?, x: Any?) {
record(columnLabel, x)
delegate.updateObject(columnLabel, x)
}
override fun updateRef(columnIndex: Int, x: Ref?) {
recordUpdate(columnIndex, x)
delegate.updateRef(columnIndex, x)
}
override fun updateRef(columnLabel: String?, x: Ref?) {
record(columnLabel, x)
delegate.updateRef(columnLabel, x)
}
override fun updateRow() {
record()
delegate.updateRow()
}
override fun updateRowId(columnIndex: Int, x: RowId?) {
recordUpdate(columnIndex, x)
delegate.updateRowId(columnIndex, x)
}
override fun updateRowId(columnLabel: String?, x: RowId?) {
record(columnLabel, x)
delegate.updateRowId(columnLabel, x)
}
override fun updateShort(columnIndex: Int, x: Short) {
recordUpdate(columnIndex, x)
delegate.updateShort(columnIndex, x)
}
override fun updateShort(columnLabel: String?, x: Short) {
record(columnLabel, x)
delegate.updateShort(columnLabel, x)
}
override fun updateSQLXML(columnIndex: Int, xmlObject: SQLXML?) {
recordUpdate(columnIndex, xmlObject)
delegate.updateSQLXML(columnIndex, xmlObject)
}
override fun updateSQLXML(columnLabel: String?, xmlObject: SQLXML?) {
record(columnLabel, xmlObject)
delegate.updateSQLXML(columnLabel, xmlObject)
}
override fun updateString(columnIndex: Int, x: String?) {
recordUpdate(columnIndex, x)
delegate.updateString(columnIndex, x)
}
override fun updateString(columnLabel: String?, x: String?) {
record(columnLabel, x)
delegate.updateString(columnLabel, x)
}
override fun updateTime(columnIndex: Int, x: Time?) {
recordUpdate(columnIndex, x)
delegate.updateTime(columnIndex, x)
}
override fun updateTime(columnLabel: String?, x: Time?) {
record(columnLabel, x)
delegate.updateTime(columnLabel, x)
}
override fun updateTimestamp(columnIndex: Int, x: Timestamp?) {
recordUpdate(columnIndex, x)
delegate.updateTimestamp(columnIndex, x)
}
override fun updateTimestamp(columnLabel: String?, x: Timestamp?) {
record(columnLabel, x)
delegate.updateTimestamp(columnLabel, x)
}
override fun wasNull(): Boolean = record {
delegate.wasNull()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AbstractRecordingResultSet) return false
if (query != other.query) return false
return true
}
override fun hashCode(): Int {
return query.hashCode()
}
override fun toString(): String {
return "ResultSet($query)"
}
} | apache-2.0 | baf46005bcec7b5cd82e412536318240 | 30.354189 | 117 | 0.668335 | 4.748795 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-core/common/src/io/ktor/client/utils/ByteChannelUtils.kt | 1 | 1104 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.utils
import io.ktor.client.content.*
import io.ktor.utils.io.*
import io.ktor.utils.io.pool.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
@OptIn(DelicateCoroutinesApi::class)
internal fun ByteReadChannel.observable(
context: CoroutineContext,
contentLength: Long?,
listener: ProgressListener
) = GlobalScope.writer(context, autoFlush = true) {
ByteArrayPool.useInstance { byteArray ->
val total = contentLength ?: -1
var bytesSend = 0L
while ([email protected]) {
val read = [email protected](byteArray)
channel.writeFully(byteArray, offset = 0, length = read)
bytesSend += read
listener(bytesSend, total)
}
val closedCause = [email protected]
channel.close(closedCause)
if (closedCause == null && bytesSend == 0L) {
listener(bytesSend, total)
}
}
}.channel
| apache-2.0 | fc32b61041c547870b6da48d01dbdcbe | 31.470588 | 119 | 0.67029 | 4.363636 | false | false | false | false |
cfieber/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandler.kt | 1 | 11222 | /*
* 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.spectator.api.BasicTag
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.orca.*
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.exceptions.TimeoutException
import com.netflix.spinnaker.orca.ext.failureStatus
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.pipeline.util.StageNavigator
import com.netflix.spinnaker.orca.q.CompleteTask
import com.netflix.spinnaker.orca.q.InvalidTaskType
import com.netflix.spinnaker.orca.q.PauseTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.metrics.MetricsTagHelper
import com.netflix.spinnaker.orca.time.toDuration
import com.netflix.spinnaker.orca.time.toInstant
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.Queue
import org.apache.commons.lang.time.DurationFormatUtils
import org.springframework.stereotype.Component
import java.time.Clock
import java.time.Duration
import java.time.Duration.ZERO
import java.time.Instant
import java.time.temporal.TemporalAmount
import java.util.concurrent.TimeUnit
import kotlin.collections.set
@Component
class RunTaskHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
override val stageNavigator: StageNavigator,
override val contextParameterProcessor: ContextParameterProcessor,
private val tasks: Collection<Task>,
private val clock: Clock,
private val exceptionHandlers: List<ExceptionHandler>,
private val registry: Registry
) : OrcaMessageHandler<RunTask>, ExpressionAware, AuthenticationAware {
override fun handle(message: RunTask) {
message.withTask { stage, taskModel, task ->
val execution = stage.execution
val thisInvocationStartTimeMs = clock.millis()
try {
if (execution.isCanceled) {
task.onCancel(stage)
queue.push(CompleteTask(message, CANCELED))
} else if (execution.status.isComplete) {
queue.push(CompleteTask(message, CANCELED))
} else if (execution.status == PAUSED) {
queue.push(PauseTask(message))
} else {
try {
task.checkForTimeout(stage, taskModel, message)
} catch (e: TimeoutException) {
registry
.timeoutCounter(stage.execution.type, stage.execution.application, stage.type, taskModel.name)
.increment()
task.onTimeout(stage)
throw e
}
stage.withAuth {
task.execute(stage.withMergedContext()).let { result: TaskResult ->
// TODO: rather send this data with CompleteTask message
stage.processTaskOutput(result)
when (result.status) {
RUNNING -> {
queue.push(message, task.backoffPeriod(taskModel, stage))
trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status)
}
SUCCEEDED, REDIRECT, FAILED_CONTINUE -> {
queue.push(CompleteTask(message, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status)
}
CANCELED -> {
task.onCancel(stage)
val status = stage.failureStatus(default = result.status)
queue.push(CompleteTask(message, status, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
TERMINAL -> {
val status = stage.failureStatus(default = result.status)
queue.push(CompleteTask(message, status, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
else ->
TODO("Unhandled task status ${result.status}")
}
}
}
}
} catch (e: Exception) {
val exceptionDetails = exceptionHandlers.shouldRetry(e, taskModel.name)
if (exceptionDetails?.shouldRetry == true) {
log.warn("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]")
queue.push(message, task.backoffPeriod(taskModel, stage))
trackResult(stage, thisInvocationStartTimeMs, taskModel, RUNNING)
} else if (e is TimeoutException && stage.context["markSuccessfulOnTimeout"] == true) {
queue.push(CompleteTask(message, SUCCEEDED))
} else {
log.error("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]", e)
stage.context["exception"] = exceptionDetails
repository.storeStage(stage)
queue.push(CompleteTask(message, stage.failureStatus()))
trackResult(stage, thisInvocationStartTimeMs, taskModel, stage.failureStatus())
}
}
}
}
private fun trackResult(stage: Stage, thisInvocationStartTimeMs: Long, taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, status: ExecutionStatus) {
val commonTags = MetricsTagHelper.commonTags(stage, taskModel, status)
val detailedTags = MetricsTagHelper.detailedTaskTags(stage, taskModel, status)
val elapsedMillis = clock.millis() - thisInvocationStartTimeMs
hashMapOf(
"task.invocations.duration" to commonTags + BasicTag("application", stage.execution.application),
"task.invocations.duration.withType" to commonTags + detailedTags
).forEach {
name, tags ->
registry.timer(name, tags).record(elapsedMillis, TimeUnit.MILLISECONDS)
}
}
override val messageType = RunTask::class.java
private fun RunTask.withTask(block: (Stage, com.netflix.spinnaker.orca.pipeline.model.Task, Task) -> Unit) =
withTask { stage, taskModel ->
tasks
.find { taskType.isAssignableFrom(it.javaClass) }
.let { task ->
if (task == null) {
queue.push(InvalidTaskType(this, taskType.name))
} else {
block.invoke(stage, taskModel, task)
}
}
}
private fun Task.backoffPeriod(taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, stage: Stage): TemporalAmount =
when (this) {
is RetryableTask -> Duration.ofMillis(
getDynamicBackoffPeriod(stage, Duration.ofMillis(System.currentTimeMillis() - (taskModel.startTime
?: 0)))
)
else -> Duration.ofSeconds(1)
}
private fun formatTimeout(timeout: Long): String {
return DurationFormatUtils.formatDurationWords(timeout, true, true)
}
private fun Task.checkForTimeout(stage: Stage, taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, message: Message) {
checkForStageTimeout(stage)
checkForTaskTimeout(taskModel, stage, message)
}
private fun Task.checkForTaskTimeout(taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, stage: Stage, message: Message) {
if (this is RetryableTask) {
val startTime = taskModel.startTime.toInstant()
if (startTime != null) {
val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime)
val elapsedTime = Duration.between(startTime, clock.instant())
val actualTimeout = (
if (this is OverridableTimeoutRetryableTask && stage.parentWithTimeout.isPresent)
stage.parentWithTimeout.get().timeout.get().toDuration()
else
timeout.toDuration()
)
if (elapsedTime.minus(pausedDuration) > actualTimeout) {
val durationString = formatTimeout(elapsedTime.toMillis())
val msg = StringBuilder("${javaClass.simpleName} of stage ${stage.name} timed out after $durationString. ")
msg.append("pausedDuration: ${formatTimeout(pausedDuration.toMillis())}, ")
msg.append("elapsedTime: ${formatTimeout(elapsedTime.toMillis())},")
msg.append("timeoutValue: ${formatTimeout(actualTimeout.toMillis())}")
log.warn(msg.toString())
throw TimeoutException(msg.toString())
}
}
}
}
private fun checkForStageTimeout(stage: Stage) {
stage.parentWithTimeout.ifPresent {
val startTime = it.startTime.toInstant()
if (startTime != null) {
val elapsedTime = Duration.between(startTime, clock.instant())
val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime)
val timeout = Duration.ofMillis(it.timeout.get())
if (elapsedTime.minus(pausedDuration) > timeout) {
throw TimeoutException("Stage ${stage.name} timed out after ${formatTimeout(elapsedTime.toMillis())}")
}
}
}
}
private fun Registry.timeoutCounter(executionType: ExecutionType,
application: String,
stageType: String,
taskType: String) =
counter(
createId("queue.task.timeouts")
.withTags(mapOf(
"executionType" to executionType.toString(),
"application" to application,
"stageType" to stageType,
"taskType" to taskType
))
)
private fun Execution.pausedDurationRelativeTo(instant: Instant?): Duration {
val pausedDetails = paused
return if (pausedDetails != null) {
if (pausedDetails.pauseTime.toInstant()?.isAfter(instant) == true) {
Duration.ofMillis(pausedDetails.pausedMs)
} else ZERO
} else ZERO
}
/**
* Keys that should never be added to global context. Eventually this will
* disappear along with global context itself.
*/
private val blacklistGlobalKeys = setOf(
"propertyIdList",
"originalProperties",
"propertyAction",
"propertyAction",
"deploymentDetails"
)
private fun Stage.processTaskOutput(result: TaskResult) {
val filteredOutputs = result.outputs.filterKeys { it != "stageTimeoutMs" }
if (result.context.isNotEmpty() || filteredOutputs.isNotEmpty()) {
context.putAll(result.context)
outputs.putAll(filteredOutputs)
repository.storeStage(this)
}
}
}
| apache-2.0 | 71145a127ec6468891906ca489d91449 | 41.029963 | 158 | 0.671182 | 4.847516 | false | false | false | false |
mre/the-coding-interview | problems/codejam/2013/quali/Fair-and-Square/fair-and-square.kt | 1 | 944 | import java.io.File
import java.text.NumberFormat
import kotlin.math.sqrt
import kotlin.test.assertEquals
val nf: NumberFormat = NumberFormat.getInstance()
inline val Number.isPalindrome get() = nf.format(this).let { it == it.reversed() }
inline val Number.square get() = sqrt(toDouble())
fun IntRange.fairAndSquare() =
fold(0) { acc, i -> acc + if (i.isPalindrome && i.square.isPalindrome) 1 else 0 }
fun main(args: Array<String>) {
val dir = File(args.firstOrNull() ?: ".")
val input = File("$dir/C-small-practice.in").readLines()
val output = File("$dir/C-small-practice.out").readLines().map { it.split(' ', limit = 3).last().toInt() }
for (i in 1..input.first().toInt()) {
input[i].split(' ', limit = 2).let { it[0].toInt()..it[1].toInt() }.fairAndSquare().let {
val message = "Case #$i: $it"
assertEquals(output[i - 1], it, message)
println(message)
}
}
}
| mit | 8eae0153fb336687768a1c15efbf9faa | 33.962963 | 110 | 0.621822 | 3.407942 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/androidTest/java/org/hisp/dhis/android/core/fileresource/internal/FileResourceRoutineShould.kt | 1 | 3391 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.fileresource.internal
import com.google.common.truth.Truth.assertThat
import java.io.File
import org.hisp.dhis.android.core.fileresource.FileResourceRoutine
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(D2JunitRunner::class)
internal class FileResourceRoutineShould : BaseFileResourceRoutineIntegrationShould() {
private val fileResourceRoutine by lazy {
FileResourceRoutine(
dataElementCollectionRepository = d2.dataElementModule().dataElements(),
dataValueCollectionRepository = d2.dataValueModule().dataValues(),
fileResourceCollectionRepository = d2.fileResourceModule().fileResources(),
fileResourceStore = fileResourceStore,
trackedEntityAttributeCollectionRepository = d2.trackedEntityModule().trackedEntityAttributes(),
trackedEntityAttributeValueCollectionRepository = d2.trackedEntityModule().trackedEntityAttributeValues(),
trackedEntityDataValueCollectionRepository = d2.trackedEntityModule().trackedEntityDataValues()
)
}
@Test
fun delete_outdated_file_resources_if_present() {
trackedEntityDataValueStore.delete()
trackedEntityAttributeValueStore.delete()
fileResourceRoutine.blockingDeleteOutdatedFileResources()
val fileResources = d2.fileResourceModule().fileResources().blockingGet()
assertThat(fileResources.size).isEqualTo(1)
assertThat(File(FileResourceRoutineSamples.fileResource1.path()!!).exists()).isFalse()
assertThat(File(FileResourceRoutineSamples.fileResource2.path()!!).exists()).isFalse()
assertThat(File(FileResourceRoutineSamples.fileResource3.path()!!).exists()).isTrue()
}
}
| bsd-3-clause | d5583d0b09e8b9c399396a00e6d25d95 | 51.984375 | 118 | 0.764081 | 5.046131 | false | false | false | false |
meik99/CoffeeList | app/src/main/java/rynkbit/tk/coffeelist/db/dao/InvoiceDao.kt | 1 | 1053 | package rynkbit.tk.coffeelist.db.dao
import androidx.room.Dao
import androidx.room.Query
import io.reactivex.Flowable
import io.reactivex.Single
import rynkbit.tk.coffeelist.contract.entity.InvoiceState
import rynkbit.tk.coffeelist.db.entity.DatabaseInvoice
@Dao
interface InvoiceDao : BaseDao<DatabaseInvoice> {
@Query("select * from invoice")
override fun findAll(): Flowable<List<DatabaseInvoice>>
@Query("select * from invoice where id = :invoiceId")
fun findById(invoiceId: Int): Single<DatabaseInvoice>
@Query("select * from invoice where customer_id = :customerId")
fun findByCustomer(customerId: Int): Flowable<List<DatabaseInvoice>>
@Query("select * from invoice where customer_id = :customerId and state = :state")
fun findByCustomerAndState(customerId: Int, state: InvoiceState): Flowable<List<DatabaseInvoice>>
@Query("delete from invoice where customer_id = :customerId")
fun deleteByCustomer(customerId: Int): Single<Unit>
@Query("delete from invoice")
fun deleteAll(): Single<Unit>
} | mit | 718b55dedd7f96ab3570ed4bc4bfe819 | 35.344828 | 101 | 0.754036 | 4.297959 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/task/impl/ProjectTaskManagerStatisticsCollector.kt | 7 | 1313 | // 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.task.impl
import com.intellij.internal.statistic.collectors.fus.ClassNameRuleValidator
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
class ProjectTaskManagerStatisticsCollector : CounterUsagesCollector() {
companion object {
val GROUP = EventLogGroup("build", 6)
@JvmField
val TASK_RUNNER = EventFields.StringListValidatedByCustomRule("task_runner_class", ClassNameRuleValidator::class.java)
@JvmField
val MODULES = EventFields.Int("modules")
@JvmField
val INCREMENTAL = EventFields.Boolean("incremental")
@JvmField
val HAS_ERRORS = EventFields.Boolean("has_errors")
@JvmField
val BUILD_ACTIVITY = GROUP.registerIdeActivity(null,
startEventAdditionalFields = arrayOf(TASK_RUNNER, EventFields.PluginInfo, MODULES, INCREMENTAL),
finishEventAdditionalFields = arrayOf(HAS_ERRORS))
}
override fun getGroup(): EventLogGroup {
return GROUP
}
} | apache-2.0 | 85c104a809c46929967dfc51a79ac083 | 37.647059 | 147 | 0.723534 | 5.089147 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/comparison/AbstractFE1UastCommentsTest.kt | 4 | 1226 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.kotlin.comparison
import org.jetbrains.uast.UFile
import org.jetbrains.uast.test.common.kotlin.UastCommentLogTestBase
import org.jetbrains.uast.test.kotlin.AbstractKotlinUastTest
import java.io.File
abstract class AbstractFE1UastCommentsTest : AbstractKotlinUastTest(), UastCommentLogTestBase {
override val isFirUastPlugin: Boolean = false
override fun check(filePath: String, file: UFile) {
super<UastCommentLogTestBase>.check(filePath, file)
}
override var testDataDir = File("plugins/uast-kotlin-fir/testData")
fun doTest(filePath: String) {
testDataDir = File(filePath).parentFile
val testName = filePath.substring(filePath.lastIndexOf('/') + 1).removeSuffix(".kt")
val virtualFile = getVirtualFile(testName)
val psiFile = psiManager.findFile(virtualFile) ?: error("Can't get psi file for $testName")
val uFile = uastContext.convertElementWithParent(psiFile, null) ?: error("Can't get UFile for $testName")
check(filePath, uFile as UFile)
}
}
| apache-2.0 | 473ca40d5518dfd11e5802a617506e79 | 42.785714 | 158 | 0.743883 | 4.458182 | false | true | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/utils/Extensions.kt | 1 | 4715 | package com.tungnui.dalatlaptop.utils
import android.app.Activity
import android.content.Context
import android.support.annotation.IdRes
import android.support.design.widget.Snackbar
import android.support.design.widget.TextInputLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import com.tungnui.dalatlaptop.views.ResizableImageViewHeight
import com.squareup.picasso.Picasso
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.libraryhelper.Utils
import com.tungnui.dalatlaptop.models.Image
import java.text.DecimalFormat
import java.util.regex.Pattern
/**
* Created by thanh on 23/09/2017.
*/
fun ViewGroup.inflate(layoutId: Int, attachToRoot: Boolean = false): View {
return LayoutInflater.from(context).inflate(layoutId, this, attachToRoot)
}
fun ImageView.loadImg(imageUrl: String?) {
Picasso.with(context).load(imageUrl)
.fit().centerInside()
.placeholder(R.drawable.placeholder_loading)
.error(R.drawable.placeholder_error)
.into(this)
}
fun ResizableImageViewHeight.loadImg(imageUrl: String?){
Picasso.with(context)
.load(imageUrl)
.fit().centerInside()
.placeholder(R.drawable.placeholder_loading)
.error(R.drawable.placeholder_error)
.into(this)
}
fun List<Image>.getFeaturedImage():Image{
for(item in this){
if(item.position == 0)
return item
}
return Image()
}
fun String.formatPrice():String{
val formatter = DecimalFormat("#,###")
return formatter.format(this.toDouble()) + "đ"
}
/*
* GET NEXT URL FROM LINK IN HEADER
* */
fun String.getNextUrl(): String? {
val urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)"
val pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE)
val urlMatcher = pattern.matcher(this)
val result = mutableListOf<String>()
while (urlMatcher.find()) {
result.add(this.substring(urlMatcher.start(0),urlMatcher.end(0)))
}
return when(result.count()){
1->if(this.contains("rel=\"next\"")) result[0].replace("%5B0%5D","") else null
else-> result[1].replace("%5B0%5D","")
}
}
fun View.showSnackBar(message: String, duration: Int) {
Snackbar.make(this, message, duration).show()
}
//Appcompat extension
fun AppCompatActivity.replaceFragmentInActivity(fragment: Fragment, @IdRes frameId: Int) {
supportFragmentManager.transact {
replace(frameId, fragment)
}
}
/**
* The `fragment` is added to the container view with tag. The operation is
* performed by the `fragmentManager`.
*/
fun AppCompatActivity.addFragmentToActivity(fragment: Fragment, tag: String) {
supportFragmentManager.transact {
add(fragment, tag)
}
}
/**
* Runs a FragmentTransaction, then calls commit().
*/
private inline fun FragmentManager.transact(action: FragmentTransaction.() -> Unit) {
beginTransaction().apply {
action()
}.commit()
}
fun <T1, T2> ifNotNull(value1: T1?, value2: T2?, bothNotNull: (T1, T2) -> (Unit)) {
if (value1 != null && value2 != null) {
bothNotNull(value1, value2)
}
}
//TExt input
fun TextInputLayout.getTextFromInputLayout(): String {
return this.editText?.text.toString()
}
fun TextInputLayout.setTextToInputLayout(text: String) {
if (this.editText != null) {
this.editText?.setText(text)
}
}
fun TextInputLayout.isVaildForEmail():Boolean{
val input = editText?.text.toString()
if(input.isNullOrBlank()){
error = resources.getString(R.string.required)
return false
}
return false
}
fun TextInputLayout.checkTextInputLayoutValueRequirement(errorValue: String): Boolean {
if (this.editText != null) {
val text = Utils.getTextFromInputLayout(this)
if (text == null || text.isEmpty()) {
this.isErrorEnabled = true
this.error = errorValue
return false
} else {
this.isErrorEnabled = false
return true
}
}
return false
}
//HideKeyboard
fun Activity.hideKeyboard():Boolean{
val view= currentFocus
view?.let{
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
return inputMethodManager.hideSoftInputFromWindow(view.windowToken,InputMethodManager.HIDE_NOT_ALWAYS)
}
return false
} | mit | 4f5cb2987d0d1037f3b580107c2a9acc | 29.616883 | 110 | 0.690072 | 4.046352 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/translations/identification/TranslationInstance.kt | 1 | 4094 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.identification
import com.demonwav.mcdev.platform.mcp.util.McpConstants
import com.demonwav.mcdev.translations.TranslationConstants
import com.demonwav.mcdev.util.MemberReference
import com.intellij.psi.PsiElement
data class TranslationInstance(
val foldingElement: PsiElement?,
val foldStart: Int,
val referenceElement: PsiElement?,
val key: Key,
val text: String?,
val formattingError: FormattingError? = null,
val superfluousVarargStart: Int = -1
) {
data class Key(val prefix: String, val infix: String, val suffix: String) {
val full = (prefix + infix + suffix).trim()
}
companion object {
enum class FormattingError {
MISSING, SUPERFLUOUS
}
val translationFunctions = listOf(
TranslationFunction(
MemberReference(
TranslationConstants.FORMAT,
"(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;",
TranslationConstants.I18N_CLIENT_CLASS
),
0,
formatting = true,
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.TRANSLATE_TO_LOCAL,
"(Ljava/lang/String;)Ljava/lang/String;",
TranslationConstants.I18N_COMMON_CLASS
),
0,
formatting = false,
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.TRANSLATE_TO_LOCAL_FORMATTED,
"(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;",
TranslationConstants.I18N_COMMON_CLASS
),
0,
formatting = true,
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;[Ljava/lang/Object;)V",
TranslationConstants.TRANSLATION_COMPONENT_CLASS
),
0,
formatting = true,
foldParameters = true
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;[Ljava/lang/Object;)V",
TranslationConstants.COMMAND_EXCEPTION_CLASS
),
0,
formatting = true,
foldParameters = true
),
TranslationFunction(
MemberReference(
TranslationConstants.SET_BLOCK_NAME,
"(Ljava/lang/String;)Lnet/minecraft/block/Block;",
McpConstants.BLOCK
),
0,
formatting = false,
setter = true,
foldParameters = true,
prefix = "tile.",
suffix = ".name",
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.SET_ITEM_NAME,
"(Ljava/lang/String;)Lnet/minecraft/item/Item;",
McpConstants.ITEM
),
0,
formatting = false,
setter = true,
foldParameters = true,
prefix = "item.",
suffix = ".name",
obfuscatedName = true
)
)
fun find(element: PsiElement): TranslationInstance? =
TranslationIdentifier.INSTANCES
.firstOrNull { it.elementClass().isAssignableFrom(element.javaClass) }
?.identifyUnsafe(element)
}
}
| mit | 1844834c4612377293ddcc1b2f1b6ba6 | 32.557377 | 86 | 0.510503 | 5.899135 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/VorbisMapping.kt | 1 | 1681 | package org.runestar.client.updater.mapper.std.classes
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.*
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.withDimensions
class VorbisMapping :IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.instanceFields.count { it.type == INT_TYPE } == 2 }
.and { it.instanceFields.count { it.type == IntArray::class.type } == 2 }
class submaps : OrderMapper.InConstructor.Field(VorbisMapping::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class mappingMux : OrderMapper.InConstructor.Field(VorbisMapping::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class submapFloor : OrderMapper.InConstructor.Field(VorbisMapping::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE.withDimensions(1) }
}
class submapResidue : OrderMapper.InConstructor.Field(VorbisMapping::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE.withDimensions(1) }
}
} | mit | fdca06851eb8ddd82102552d7914b2f3 | 47.057143 | 130 | 0.735872 | 4.040865 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/output/ToolWindowScratchOutputHandler.kt | 1 | 9805 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.scratch.output
import com.intellij.execution.filters.OpenFileHyperlinkInfo
import com.intellij.execution.impl.ConsoleViewImpl
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.scratch.ScratchExpression
import org.jetbrains.kotlin.idea.scratch.ScratchFile
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.KtPsiFactory
/**
* Method to retrieve shared instance of scratches ToolWindow output handler.
*
* [releaseToolWindowHandler] must be called for every output handler received from this method.
*
* Can be called from EDT only.
*
* @return new toolWindow output handler if one does not exist, otherwise returns the existing one. When application in test mode,
* returns [TestOutputHandler].
*/
fun requestToolWindowHandler(): ScratchOutputHandler {
return if (isUnitTestMode()) {
TestOutputHandler
} else {
ScratchToolWindowHandlerKeeper.requestOutputHandler()
}
}
/**
* Should be called once with the output handler received from the [requestToolWindowHandler] call.
*
* When release is called for every request, the output handler is actually disposed.
*
* When application in test mode, does nothing.
*
* Can be called from EDT only.
*/
fun releaseToolWindowHandler(scratchOutputHandler: ScratchOutputHandler) {
if (!isUnitTestMode()) {
ScratchToolWindowHandlerKeeper.releaseOutputHandler(scratchOutputHandler)
}
}
/**
* Implements logic of shared pointer for the toolWindow output handler.
*
* Not thread safe! Can be used only from the EDT.
*/
private object ScratchToolWindowHandlerKeeper {
private var toolWindowHandler: ScratchOutputHandler? = null
private var toolWindowDisposable = Disposer.newDisposable()
private var counter = 0
fun requestOutputHandler(): ScratchOutputHandler {
if (counter == 0) {
toolWindowHandler = ToolWindowScratchOutputHandler(toolWindowDisposable)
}
counter += 1
return toolWindowHandler!!
}
fun releaseOutputHandler(scratchOutputHandler: ScratchOutputHandler) {
require(counter > 0) { "Counter is $counter, nothing to release!" }
require(toolWindowHandler === scratchOutputHandler) { "$scratchOutputHandler differs from stored $toolWindowHandler" }
counter -= 1
if (counter == 0) {
Disposer.dispose(toolWindowDisposable)
toolWindowDisposable = Disposer.newDisposable()
toolWindowHandler = null
}
}
}
private class ToolWindowScratchOutputHandler(private val parentDisposable: Disposable) : ScratchOutputHandlerAdapter() {
override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) {
printToConsole(file) {
val psiFile = file.getPsiFile()
if (psiFile != null) {
printHyperlink(
getLineInfo(psiFile, expression),
OpenFileHyperlinkInfo(
project,
psiFile.virtualFile,
expression.lineStart
)
)
print(" ", ConsoleViewContentType.NORMAL_OUTPUT)
}
print(output.text, output.type.convert())
}
}
override fun error(file: ScratchFile, message: String) {
printToConsole(file) {
print(message, ConsoleViewContentType.ERROR_OUTPUT)
}
}
private fun printToConsole(file: ScratchFile, print: ConsoleViewImpl.() -> Unit) {
invokeLater {
val project = file.project.takeIf { !it.isDisposed } ?: return@invokeLater
val toolWindow = getToolWindow(project) ?: createToolWindow(file)
val contents = toolWindow.contentManager.contents
for (content in contents) {
val component = content.component
if (component is ConsoleViewImpl) {
component.print()
component.print("\n", ConsoleViewContentType.NORMAL_OUTPUT)
}
}
toolWindow.setAvailable(true, null)
if (!file.options.isInteractiveMode) {
toolWindow.show(null)
}
toolWindow.setIcon(ExecutionUtil.getLiveIndicator(AllIcons.FileTypes.Text))
}
}
override fun clear(file: ScratchFile) {
invokeLater {
val toolWindow = getToolWindow(file.project) ?: return@invokeLater
val contents = toolWindow.contentManager.contents
for (content in contents) {
val component = content.component
if (component is ConsoleViewImpl) {
component.clear()
}
}
if (!file.options.isInteractiveMode) {
toolWindow.hide(null)
}
toolWindow.setIcon(AllIcons.FileTypes.Text)
}
}
private fun ScratchOutputType.convert() = when (this) {
ScratchOutputType.OUTPUT -> ConsoleViewContentType.SYSTEM_OUTPUT
ScratchOutputType.RESULT -> ConsoleViewContentType.NORMAL_OUTPUT
ScratchOutputType.ERROR -> ConsoleViewContentType.ERROR_OUTPUT
}
private fun getToolWindow(project: Project): ToolWindow? {
val toolWindowManager = ToolWindowManager.getInstance(project)
return toolWindowManager.getToolWindow(ScratchToolWindowFactory.ID)
}
private fun createToolWindow(file: ScratchFile): ToolWindow {
val project = file.project
val toolWindowManager = ToolWindowManager.getInstance(project)
toolWindowManager.registerToolWindow(ScratchToolWindowFactory.ID, true, ToolWindowAnchor.BOTTOM)
val window =
toolWindowManager.getToolWindow(ScratchToolWindowFactory.ID) ?: error("ScratchToolWindowFactory.ID should be registered")
ScratchToolWindowFactory().createToolWindowContent(project, window)
Disposer.register(parentDisposable, Disposable {
toolWindowManager.unregisterToolWindow(ScratchToolWindowFactory.ID)
})
return window
}
}
private fun getLineInfo(psiFile: PsiFile, expression: ScratchExpression) =
"${psiFile.name}:${expression.lineStart + 1}"
private class ScratchToolWindowFactory : ToolWindowFactory {
companion object {
const val ID = "Scratch Output"
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
val consoleView = ConsoleViewImpl(project, true)
toolWindow.setToHideOnEmptyContent(true)
toolWindow.setIcon(AllIcons.FileTypes.Text)
toolWindow.hide(null)
val contentManager = toolWindow.contentManager
val content = contentManager.factory.createContent(consoleView.component, null, false)
contentManager.addContent(content)
val editor = consoleView.editor
if (editor is EditorEx) {
editor.isRendererMode = true
}
Disposer.register(KotlinPluginDisposable.getInstance(project), consoleView)
}
}
private object TestOutputHandler : ScratchOutputHandlerAdapter() {
private val errors = arrayListOf<String>()
private val inlays = arrayListOf<Pair<ScratchExpression, String>>()
override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) {
inlays.add(expression to output.text)
}
override fun error(file: ScratchFile, message: String) {
errors.add(message)
}
override fun onFinish(file: ScratchFile) {
TransactionGuard.submitTransaction(KotlinPluginDisposable.getInstance(file.project), Runnable {
val psiFile = file.getPsiFile()
?: error(
"PsiFile cannot be found for scratch to render inlays in tests:\n" +
"project.isDisposed = ${file.project.isDisposed}\n" +
"inlays = ${inlays.joinToString { it.second }}\n" +
"errors = ${errors.joinToString()}"
)
if (inlays.isNotEmpty()) {
testPrint(psiFile, inlays.map { (expression, text) ->
"/** ${getLineInfo(psiFile, expression)} $text */"
})
inlays.clear()
}
if (errors.isNotEmpty()) {
testPrint(psiFile, listOf(errors.joinToString(prefix = "/** ", postfix = " */")))
errors.clear()
}
})
}
private fun testPrint(file: PsiFile, comments: List<String>) {
WriteCommandAction.runWriteCommandAction(file.project) {
for (comment in comments) {
file.addAfter(
KtPsiFactory(file.project).createComment(comment),
file.lastChild
)
}
}
}
}
| apache-2.0 | bc13d9adbbad2192150c5035582a4d36 | 36.423664 | 158 | 0.664763 | 5.337507 | false | false | false | false |
JetBrains/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/projectTree/MarkdownTreeStructureProvider.kt | 1 | 2941 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.ui.projectTree
import com.intellij.ide.projectView.TreeStructureProvider
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.settings.MarkdownSettings
class MarkdownTreeStructureProvider(private val project: Project) : TreeStructureProvider {
override fun modify(
parent: AbstractTreeNode<*>,
children: MutableCollection<AbstractTreeNode<*>>,
settings: ViewSettings?
): MutableCollection<AbstractTreeNode<*>> {
if (children.find { it.value is MarkdownFile } == null) {
return children
}
val result = mutableListOf<AbstractTreeNode<*>>()
val childrenToRemove = mutableListOf<AbstractTreeNode<*>>()
for (child in children) {
val childValue = (child.value as? MarkdownFile)
val childVirtualFile = childValue?.virtualFile
if (childVirtualFile != null && parent.value !is MarkdownFileNode) {
val markdownChildren = findMarkdownFileNodeChildren(childVirtualFile, children)
if (markdownChildren.size <= 1) {
result.add(child)
continue
}
result.add(createMarkdownViewNode(childVirtualFile, markdownChildren, settings))
childrenToRemove.addAll(markdownChildren)
} else {
result.add(child)
}
}
result.removeAll(childrenToRemove)
return result
}
private fun findMarkdownFileNodeChildren(
markdownFile: VirtualFile,
children: MutableCollection<AbstractTreeNode<*>>
): MutableCollection<AbstractTreeNode<*>> {
val fileName = markdownFile.nameWithoutExtension
return children.asSequence().filter { node ->
val file = (node.value as? PsiFile)?.virtualFile
file?.let { isDocumentsGroupingEnabled(it, fileName) } == true
}.toMutableList()
}
private fun createMarkdownViewNode(
markdownFile: VirtualFile,
children: MutableCollection<AbstractTreeNode<*>>,
settings: ViewSettings?
): MarkdownViewNode {
val nodeChildren = children.mapNotNull { it.value as? PsiFile }
val markdownNode = MarkdownFileNode(markdownFile.nameWithoutExtension, nodeChildren)
return MarkdownViewNode(project, markdownNode, settings, children)
}
private fun isDocumentsGroupingEnabled(file: VirtualFile, fileName: String) =
file.extension?.lowercase() in extensionsToFold &&
file.nameWithoutExtension == fileName &&
MarkdownSettings.getInstance(project).isFileGroupingEnabled
companion object {
private val extensionsToFold = listOf("pdf", "docx", "html", "md")
}
}
| apache-2.0 | 6eed83046500b8082fb4b33305580412 | 39.847222 | 158 | 0.741925 | 4.853135 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/concurrent/test/LimitedParallelismConcurrentTest.kt | 1 | 1656 | /*
* Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlinx.coroutines.exceptions.*
import kotlin.test.*
class LimitedParallelismConcurrentTest : TestBase() {
private val targetParallelism = 4
private val iterations = 100_000
private val parallelism = atomic(0)
private fun checkParallelism() {
val value = parallelism.incrementAndGet()
randomWait()
assertTrue { value <= targetParallelism }
parallelism.decrementAndGet()
}
@Test
fun testLimitedExecutor() = runMtTest {
val executor = newFixedThreadPoolContext(targetParallelism, "test")
val view = executor.limitedParallelism(targetParallelism)
doStress {
repeat(iterations) {
launch(view) {
checkParallelism()
}
}
}
executor.close()
}
private suspend inline fun doStress(crossinline block: suspend CoroutineScope.() -> Unit) {
repeat(stressTestMultiplier) {
coroutineScope {
block()
}
}
}
@Test
fun testTaskFairness() = runMtTest {
val executor = newSingleThreadContext("test")
val view = executor.limitedParallelism(1)
val view2 = executor.limitedParallelism(1)
val j1 = launch(view) {
while (true) {
yield()
}
}
val j2 = launch(view2) { j1.cancel() }
joinAll(j1, j2)
executor.close()
}
}
| apache-2.0 | 8b4c13c4376cdf6fa6736275496d2468 | 26.147541 | 102 | 0.596014 | 4.786127 | false | true | false | false |
zdary/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/controlFlow/impl/ArgumentsInstruction.kt | 5 | 1808 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.util.recursionAwareLazy
class ArgumentsInstruction(call: GrCall) : InstructionImpl(call) {
override fun getElement(): GrCall = super.getElement() as GrCall
override fun getElementPresentation(): String = "ARGUMENTS " + super.getElementPresentation()
val variableDescriptors: Collection<VariableDescriptor> get() = arguments.keys
val arguments: Map<VariableDescriptor, Collection<Argument>> by recursionAwareLazy(this::obtainArguments)
private fun obtainArguments(): Map<VariableDescriptor, Collection<Argument>> {
// don't use GrCall#getArguments() because it calls #getType() on GrSpreadArgument operand
val argumentList = element.argumentList ?: return emptyMap()
val result = ArrayList<Pair<VariableDescriptor, ExpressionArgument>>()
for (expression in argumentList.expressionArguments) {
if (expression !is GrReferenceExpression) continue
if (expression.isQualified) continue
val descriptor = expression.createDescriptor() ?: continue
result += Pair(descriptor, ExpressionArgument(expression))
}
if (result.isEmpty()) return emptyMap()
return result.groupByTo(LinkedHashMap(), { it.first }, { it.second })
}
}
| apache-2.0 | 590993128efd9e7381752b2e290c701c | 52.176471 | 140 | 0.784292 | 4.696104 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/callableReference/property/delegatedMutable.kt | 5 | 537 | import kotlin.reflect.KProperty
var result: String by Delegate
object Delegate {
var value = "lol"
operator fun getValue(instance: Any?, data: KProperty<*>): String {
return value
}
operator fun setValue(instance: Any?, data: KProperty<*>, newValue: String) {
value = newValue
}
}
fun box(): String {
val f = ::result
if (f.get() != "lol") return "Fail 1: {$f.get()}"
Delegate.value = "rofl"
if (f.get() != "rofl") return "Fail 2: {$f.get()}"
f.set("OK")
return f.get()
}
| apache-2.0 | fd70f463e794effc06106804fd1e7379 | 21.375 | 81 | 0.581006 | 3.509804 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.