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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
badoualy/kotlogram | mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/model/MTSession.kt | 1 | 1910 | package com.github.badoualy.telegram.mtproto.model
import com.github.badoualy.telegram.mtproto.secure.RandomUtils
import com.github.badoualy.telegram.mtproto.time.TimeOverlord
import com.github.badoualy.telegram.tl.TLObjectUtils
import com.github.badoualy.telegram.tl.core.TLObject
import org.slf4j.MarkerFactory
import java.math.BigInteger
/** see https://core.telegram.org/mtproto/description#session
a (random) 64-bit number generated by the client */
class MTSession(var dataCenter: DataCenter, var id: ByteArray = RandomUtils.randomSessionId(),
var salt: Long = 0, var contentRelatedCount: Int = 0, var lastMessageId: Long = 0, tag: String) {
@Transient
val tag = "$tag:${BigInteger(id).toLong()}"
@Transient
val marker = MarkerFactory.getMarker(this.tag)!!
/**
* Generate a valid seqNo value for the given message type
* @param clazz message type
* @return a valid seqNo value to send
* @see <a href="https://core.telegram.org/mtproto/description#message-sequence-number-msg-seqno">MTProto description</a>
*/
fun generateSeqNo(clazz: Class<out TLObject>) =
generateSeqNo(TLObjectUtils.isContentRelated(clazz))
private fun generateSeqNo(contentRelated: Boolean): Int {
var seqNo = -1
synchronized(this) {
seqNo = if (contentRelated) {
seqNo = contentRelatedCount * 2 + 1
contentRelatedCount++
seqNo
} else {
contentRelatedCount * 2
}
}
return seqNo
}
fun generateSeqNo(message: TLObject) = generateSeqNo(message.javaClass)
fun generateMessageId(): Long {
val weakMessageId = TimeOverlord.generateMessageId(dataCenter)
synchronized(this) {
lastMessageId = Math.max(weakMessageId, lastMessageId + 4)
}
return lastMessageId
}
} | mit | 8bd04d133500feaf430a6df6b610f0bb | 35.056604 | 125 | 0.670681 | 4.152174 | false | false | false | false |
Ufkoku/AndroidMVPHelper | mvp_base/src/main/kotlin/com/ufkoku/mvp_base/view/lifecycle/ActivityLifecycle.kt | 1 | 1372 | /*
* Copyright 2017 Ufkoku (https://github.com/Ufkoku/AndroidMVPHelper)
*
* 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.ufkoku.mvp_base.view.lifecycle
import android.support.annotation.IntDef
import java.lang.annotation.Inherited
object ActivityLifecycle {
const val ON_CREATE = 0
const val ON_START = 1
const val ON_RESUME = 2
const val ON_PAUSE = 3
const val ON_STOP = 4
const val ON_SAVE_INSTANCE = 5
const val ON_DESTROY = 6
@Target(AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.SOURCE)
@IntDef(ON_CREATE, ON_START, ON_RESUME, ON_SAVE_INSTANCE, ON_PAUSE, ON_STOP, ON_DESTROY)
annotation class ActivityEvent
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@Inherited
annotation class OnLifecycleEvent(@ActivityEvent val event: Int)
} | apache-2.0 | 2f34226bc893d3ffdb3ae31880402c03 | 31.690476 | 92 | 0.738338 | 3.988372 | false | false | false | false |
foresterre/mal | kotlin/src/mal/reader.kt | 4 | 4818 | package mal
import kotlin.text.Regex
val TOKEN_REGEX = Regex("[\\s,]*(~@|[\\[\\]{}()'`~^@]|\"(?:\\\\.|[^\\\\\"])*\"|;.*|[^\\s\\[\\]{}('\"`,;)]*)")
val ATOM_REGEX = Regex("(^-?[0-9]+$)|(^nil$)|(^true$)|(^false$)|^\"(.*)\"$|:(.*)|(^[^\"]*$)")
class Reader(sequence: Sequence<String>) {
val tokens = sequence.iterator()
var current = advance()
fun next(): String? {
var result = current
current = advance()
return result
}
fun peek(): String? = current
private fun advance(): String? = if (tokens.hasNext()) tokens.next() else null
}
fun read_str(input: String?): MalType {
val tokens = tokenizer(input) ?: return NIL
return read_form(Reader(tokens))
}
fun tokenizer(input: String?): Sequence<String>? {
if (input == null) return null
return TOKEN_REGEX.findAll(input)
.map({ it -> it.groups[1]?.value as String })
.filter({ it != "" && !it.startsWith(";")})
}
fun read_form(reader: Reader): MalType =
when (reader.peek()) {
null -> throw MalContinue()
"(" -> read_list(reader)
")" -> throw MalReaderException("expected form, got ')'")
"[" -> read_vector(reader)
"]" -> throw MalReaderException("expected form, got ']'")
"{" -> read_hashmap(reader)
"}" -> throw MalReaderException("expected form, got '}'")
"'" -> read_shorthand(reader, "quote")
"`" -> read_shorthand(reader, "quasiquote")
"~" -> read_shorthand(reader, "unquote")
"~@" -> read_shorthand(reader, "splice-unquote")
"^" -> read_with_meta(reader)
"@" -> read_shorthand(reader, "deref")
else -> read_atom(reader)
}
fun read_list(reader: Reader): MalType = read_sequence(reader, MalList(), ")")
fun read_vector(reader: Reader): MalType = read_sequence(reader, MalVector(), "]")
private fun read_sequence(reader: Reader, sequence: IMutableSeq, end: String): MalType {
reader.next()
do {
val form = when (reader.peek()) {
null -> throw MalReaderException("expected '$end', got EOF")
end -> { reader.next(); null }
else -> read_form(reader)
}
if (form != null) {
sequence.conj_BANG(form)
}
} while (form != null)
return sequence
}
fun read_hashmap(reader: Reader): MalType {
reader.next()
val hashMap = MalHashMap()
do {
var value : MalType? = null;
val key = when (reader.peek()) {
null -> throw MalReaderException("expected '}', got EOF")
"}" -> { reader.next(); null }
else -> {
var key = read_form(reader)
if (key !is MalString) {
throw MalReaderException("hash-map keys must be strings or keywords")
}
value = when (reader.peek()) {
null -> throw MalReaderException("expected form, got EOF")
else -> read_form(reader)
}
key
}
}
if (key != null) {
hashMap.assoc_BANG(key, value as MalType)
}
} while (key != null)
return hashMap
}
fun read_shorthand(reader: Reader, symbol: String): MalType {
reader.next()
val list = MalList()
list.conj_BANG(MalSymbol(symbol))
list.conj_BANG(read_form(reader))
return list
}
fun read_with_meta(reader: Reader): MalType {
reader.next()
val meta = read_form(reader)
val obj = read_form(reader)
val list = MalList()
list.conj_BANG(MalSymbol("with-meta"))
list.conj_BANG(obj)
list.conj_BANG(meta)
return list
}
fun read_atom(reader: Reader): MalType {
val next = reader.next() ?: throw MalReaderException("Unexpected null token")
val groups = ATOM_REGEX.find(next)?.groups ?: throw MalReaderException("Unrecognized token: " + next)
return if (groups[1]?.value != null) {
MalInteger(groups[1]?.value?.toLong() ?: throw MalReaderException("Error parsing number: " + next))
} else if (groups[2]?.value != null) {
NIL
} else if (groups[3]?.value != null) {
TRUE
} else if (groups[4]?.value != null) {
FALSE
} else if (groups[5]?.value != null) {
MalString((groups[5]?.value as String).replace(Regex("""\\(.)"""))
{ m: MatchResult ->
if (m.groups[1]?.value == "n") "\n"
else m.groups[1]?.value.toString()
})
} else if (groups[6]?.value != null) {
MalKeyword(groups[6]?.value as String)
} else if (groups[7]?.value != null) {
MalSymbol(groups[7]?.value as String)
} else {
throw MalReaderException("Unrecognized token: " + next)
}
}
| mpl-2.0 | acbaf348cc6ec46972c7ae9b231b2dc8 | 30.285714 | 109 | 0.534247 | 3.835987 | false | false | false | false |
gradle/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/initialization/ConfigurationCacheStartParameter.kt | 2 | 3360 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.configurationcache.initialization
import org.gradle.StartParameter
import org.gradle.api.internal.StartParameterInternal
import org.gradle.configurationcache.extensions.unsafeLazy
import org.gradle.initialization.StartParameterBuildOptions.ConfigurationCacheProblemsOption
import org.gradle.initialization.layout.BuildLayout
import org.gradle.internal.buildoption.InternalFlag
import org.gradle.internal.buildoption.InternalOptions
import org.gradle.internal.service.scopes.Scopes
import org.gradle.internal.service.scopes.ServiceScope
import java.io.File
@ServiceScope(Scopes.BuildTree::class)
class ConfigurationCacheStartParameter(
private val buildLayout: BuildLayout,
private val startParameter: StartParameterInternal,
options: InternalOptions
) {
val loadAfterStore = options.getOption(InternalFlag("org.gradle.configuration-cache.internal.load-after-store")).get()
val gradleProperties: Map<String, Any?>
get() = startParameter.projectProperties
val isQuiet: Boolean
get() = startParameter.isConfigurationCacheQuiet
val maxProblems: Int
get() = startParameter.configurationCacheMaxProblems
val isDebug: Boolean
get() = startParameter.isConfigurationCacheDebug
val failOnProblems: Boolean
get() = startParameter.configurationCacheProblems == ConfigurationCacheProblemsOption.Value.FAIL
val recreateCache: Boolean
get() = startParameter.isConfigurationCacheRecreateCache
/**
* See [StartParameter.getProjectDir].
*/
val projectDirectory: File?
get() = startParameter.projectDir
val currentDirectory: File
get() = startParameter.currentDir
val settingsDirectory: File
get() = buildLayout.settingsDir
@Suppress("DEPRECATION")
val settingsFile: File?
get() = startParameter.settingsFile
val rootDirectory: File
get() = buildLayout.rootDirectory
val isOffline
get() = startParameter.isOffline
val isRefreshDependencies
get() = startParameter.isRefreshDependencies
val isWriteDependencyLocks
get() = startParameter.isWriteDependencyLocks && !isUpdateDependencyLocks
val isUpdateDependencyLocks
get() = startParameter.lockedDependenciesToUpdate.isNotEmpty()
val requestedTaskNames: List<String> by unsafeLazy {
startParameter.taskNames
}
val excludedTaskNames: Set<String>
get() = startParameter.excludedTaskNames
val allInitScripts: List<File>
get() = startParameter.allInitScripts
val gradleUserHomeDir: File
get() = startParameter.gradleUserHomeDir
val includedBuilds: List<File>
get() = startParameter.includedBuilds
}
| apache-2.0 | ad569ca6f3d6313f7f71c0c5f50093c9 | 31.621359 | 122 | 0.749405 | 5.007452 | false | true | false | false |
kamgurgul/cpu-info | app/src/main/java/com/kgurgul/cpuinfo/theme/Color.kt | 1 | 301 | package com.kgurgul.cpuinfo.theme
import androidx.compose.ui.graphics.Color
val RedLight = Color(0xFFD84315)
val RedDark = Color(0xFFD32F2F)
val RedError = Color(0xFFF44336)
val Gray18 = Color(0xFF121212)
val Gray28 = Color(0xFF1C1C1C)
val Gray50 = Color(0xFF323232)
val Gray66 = Color(0xFF424242)
| apache-2.0 | 0f1946b9109a2bf3cd48cbe9b048c213 | 24.083333 | 41 | 0.790698 | 2.640351 | false | false | false | false |
crunchersaspire/worshipsongs | app/src/main/java/org/worshipsongs/dialog/RemoteSongPresentation.kt | 3 | 4686 | package org.worshipsongs.dialog
import android.annotation.TargetApi
import android.app.Presentation
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Display
import android.view.View
import android.widget.ImageView
import android.widget.ScrollView
import android.widget.TextView
import org.worshipsongs.R
import org.worshipsongs.service.CustomTagColorService
import org.worshipsongs.service.UserPreferenceSettingService
/**
* @author: Madasamy
* @version: 3.x
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
class RemoteSongPresentation(context: Context?, display: Display?): Presentation(context, display)
{
private val preferenceSettingService = UserPreferenceSettingService(context!!)
private val customTagColorService = CustomTagColorService()
private var songSlideTextView: TextView? = null
private var imageView: ImageView? = null
private var scrollView: ScrollView? = null
private var verseTextView: TextView? = null
private var songTitleTextView: TextView? = null
private var authorNameTextView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.song_content_landscape_view_fragment)
setImageView()
setScrollView()
setVerseView()
setSongTitleView()
setAuthorNameView()
setSongSlide()
}
private fun setImageView()
{
imageView = findViewById<View>(R.id.logo_image_view) as ImageView
setImageViewVisibility(View.VISIBLE)
}
fun setImageViewVisibility(visible: Int)
{
imageView!!.visibility = visible
imageView!!.background = ColorDrawable(preferenceSettingService.presentationBackgroundColor)
}
private fun setScrollView()
{
scrollView = findViewById<View>(R.id.verse_land_scape_scrollview) as ScrollView
setVerseVisibility(View.GONE)
}
fun setVerseVisibility(visible: Int)
{
scrollView!!.visibility = visible
scrollView!!.background = ColorDrawable(preferenceSettingService.presentationBackgroundColor)
}
private fun setVerseView()
{
verseTextView = findViewById<View>(R.id.text) as TextView
verseTextView!!.text = ""
}
fun setVerse(verse: String)
{
verseTextView!!.text = ""
customTagColorService.setCustomTagTextView(verseTextView!!, verse, preferenceSettingService.presentationPrimaryColor, preferenceSettingService.presentationSecondaryColor)
verseTextView!!.textSize = preferenceSettingService.landScapeFontSize
// verseTextView.setTextColor(preferenceSettingService.getPrimaryColor());
verseTextView!!.isVerticalScrollBarEnabled = true
}
private fun setSongTitleView()
{
songTitleTextView = findViewById<View>(R.id.song_title) as TextView
}
fun setSongTitleAndChord(title: String, chord: String, color: Int)
{
songTitleTextView!!.text = ""
val formattedTitle = resources.getString(R.string.title) + " " + title + " " + getChord(chord)
songTitleTextView!!.text = formattedTitle
songTitleTextView!!.setTextColor(color)
}
private fun getChord(chord: String?): String
{
return if (chord != null && chord.length > 0)
{
" [$chord]"
} else ""
}
private fun setAuthorNameView()
{
authorNameTextView = findViewById<View>(R.id.author_name) as TextView
}
fun setAuthorName(authorName: String, color: Int)
{
authorNameTextView!!.text = ""
val formattedAuthor = resources.getString(R.string.author) + " " + authorName
authorNameTextView!!.text = formattedAuthor
authorNameTextView!!.setTextColor(color)
}
private fun setSongSlide()
{
songSlideTextView = findViewById<View>(R.id.song_slide) as TextView
}
fun setSlidePosition(position: Int, size: Int, color: Int)
{
songSlideTextView!!.text = ""
val slidePosition = resources.getString(R.string.slide) + " " + getSongSlideValue(position, size)
songSlideTextView!!.text = slidePosition
songSlideTextView!!.setTextColor(color)
}
private fun getSongSlideValue(currentPosition: Int, size: Int): String
{
val slidePosition = currentPosition + 1
return "$slidePosition of $size"
}
override fun onDisplayRemoved()
{
super.onDisplayRemoved()
Log.i(RemoteSongPresentation::class.java.simpleName, "When display is removed")
}
}
| apache-2.0 | b683284e53a290cf8eb42d5ef96cbc3d | 31.09589 | 178 | 0.69889 | 4.686 | false | false | false | false |
andretietz/retroauth | android-accountmanager/src/main/java/com/andretietz/retroauth/AndroidAccountManagerOwnerStorage.kt | 1 | 3177 | /*
* Copyright (c) 2016 Andre Tietz
*
* 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.andretietz.retroauth
import android.accounts.Account
import android.accounts.AccountManager
import android.app.Application
import android.content.Context
import android.os.Build
/**
* This is the Android implementation of an [OwnerStorage]. It does all the Android [Account]
* handling using tha Android [AccountManager].
*/
@Suppress("unused")
class AndroidAccountManagerOwnerStorage constructor(
private val application: Application,
private val ownerType: String
) : OwnerStorage<Account> {
companion object {
private const val RETROAUTH_ACCOUNT_NAME_KEY = "com.andretietz.retroauth.ACTIVE_ACCOUNT"
}
private val activityManager by lazy { ActivityManager[application] }
private val accountManager by lazy { AccountManager.get(application) }
@Suppress("BlockingMethodInNonBlockingContext")
override fun createOwner(credentialType: String): Account? {
val bundle = accountManager.addAccount(
ownerType,
credentialType,
null,
null,
activityManager.activity,
null,
null).result
return bundle.getString(AccountManager.KEY_ACCOUNT_NAME)?.let {
Account(bundle.getString(AccountManager.KEY_ACCOUNT_NAME),
bundle.getString(AccountManager.KEY_ACCOUNT_TYPE))
}
}
override fun getOwner(ownerName: String): Account? {
return accountManager.getAccountsByType(ownerType)
.firstOrNull { ownerName == it.name }
}
override fun getActiveOwner(): Account? {
return application.getSharedPreferences(ownerType, Context.MODE_PRIVATE)
.getString(RETROAUTH_ACCOUNT_NAME_KEY, null)?.let { accountName ->
getOwner(accountName)
}
}
override fun getOwners(): List<Account> = accountManager.accounts.toList()
.filter { it.type == ownerType }
override fun switchActiveOwner(owner: Account?) {
val preferences = application.getSharedPreferences(ownerType, Context.MODE_PRIVATE)
if (owner == null) {
preferences.edit().remove(RETROAUTH_ACCOUNT_NAME_KEY).apply()
} else {
preferences.edit().putString(RETROAUTH_ACCOUNT_NAME_KEY, owner.name).apply()
}
}
override fun removeOwner(owner: Account): Boolean {
val success = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
accountManager.removeAccount(owner, null, null, null).result
.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)
} else {
@Suppress("DEPRECATION")
accountManager.removeAccount(owner, null, null).result
}
if (success) switchActiveOwner(owner)
return success
}
}
| apache-2.0 | 707b9277a2cf17e9025dbeda4c1bea0b | 32.797872 | 93 | 0.721121 | 4.40638 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/util/TagManager.kt | 1 | 2359 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.util
import uk.co.nickthecoder.tickle.Role
/**
* Remembers which Roles have which tags. Director has a TagManager, and is the easiest way to manage tags.
* However, if you need multiple TagManager per Scene, then you do not need to use the one on Director.
*
* NOTE.TagManager was originally created because I found the concept useful when working with other game
* engines. However, since writing Tickle, I've found TagManager to be redundant. Instead, I tend to use
* interfaces where I would previously use Tags. YMMV.
* TagManager can be more efficient than filtering all Roles based on their interface, so if your game
* has LOTS of game objects, then TagManager may still be useful.
*/
class TagManager {
private val tagRoleMap = mutableMapOf<Any, MutableSet<TaggedRole>>()
fun findRoles(tag: Any): Set<TaggedRole> = tagRoleMap[tag] ?: emptySet()
fun findARole(tag: Any): Role? = tagRoleMap[tag]?.firstOrNull()
/**
* Returns the closest role with the given tag, or null if there are no roles with that tag.
* 'toMe' is never returned.
*/
fun closest(toMe: Role, tag: Any): Role? {
return toMe.closest(findRoles(tag))
}
internal fun add(role: TaggedRole, vararg tags: Any) {
tags.forEach { tag ->
val set = tagRoleMap[tag]
if (set == null) {
val newSet = mutableSetOf(role)
tagRoleMap[tag] = newSet
} else {
set.add(role)
}
}
}
internal fun remove(role: Role, vararg tags: Any) {
tags.forEach { tag ->
tagRoleMap[tag]?.remove(role)
}
}
}
| gpl-3.0 | 032252abf54bbd4056d4d8eb4df82bfc | 33.691176 | 107 | 0.68546 | 4.074266 | false | false | false | false |
xfmax/BasePedo | app/src/main/java/com/base/basepedo/service/StepInPedometer.kt | 1 | 1806 | package com.base.basepedo.service
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorManager
import android.util.Log
import com.base.basepedo.base.StepMode
import com.base.basepedo.callback.StepCallBack
/**
* Created by base on 2016/8/17.
*/
class StepInPedometer(context: Context?, stepCallBack: StepCallBack?) : StepMode(context!!, stepCallBack!!) {
private val TAG = "StepInPedometer"
private val lastStep = -1
private var liveStep = 0
private val increment = 0
//0-TYPE_STEP_DETECTOR 1-TYPE_STEP_COUNTER
private var sensorMode = 0
override fun registerSensor() {
addCountStepListener()
}
override fun onSensorChanged(event: SensorEvent) {
liveStep = event.values[0].toInt()
if (sensorMode == 0) {
CURRENT_SETP += liveStep
} else if (sensorMode == 1) {
CURRENT_SETP = liveStep
}
stepCallBack.Step(CURRENT_SETP)
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
private fun addCountStepListener() {
val detectorSensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)
val countSensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
if (detectorSensor != null) {
sensorManager!!.registerListener(this, detectorSensor, SensorManager.SENSOR_DELAY_UI)
isAvailable = true
sensorMode = 0
} else if (countSensor != null) {
sensorManager!!.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI)
isAvailable = true
sensorMode = 1
} else {
isAvailable = false
Log.v(TAG, "Count sensor not available!")
}
}
}
| apache-2.0 | 08901a4cdea9702401c33bb93384cdde | 33.075472 | 109 | 0.662237 | 4.3 | false | false | false | false |
nb7123/RNapp | android/app/src/main/java/com/rnapp/ImagePickerModule.kt | 1 | 2877 | package com.rnapp
import android.app.Activity
import android.content.Intent
import com.facebook.react.bridge.BaseActivityEventListener
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
/**
* Created by michael on 17-7-25.
*/
class ImagePickerModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
private var mPickerPromise: Promise? = null
private val mActivityEventListener = object : BaseActivityEventListener() {
override fun onActivityResult(activity: Activity?, requestCode: Int, resultCode: Int, intent: Intent?) {
if (requestCode == IMAGE_PICKER_REQUEST) {
if (mPickerPromise != null) {
if (resultCode == Activity.RESULT_CANCELED) {
mPickerPromise!!.reject(E_PICKER_CANCELLED, "Image picker was cancelled")
} else if (resultCode == Activity.RESULT_OK) {
val uri = intent!!.data
if (uri == null) {
mPickerPromise!!.reject(E_NO_IMAGE_DATA_FOUND, "No image data found")
} else {
mPickerPromise!!.resolve(uri.toString())
}
}
mPickerPromise = null
}
}
}
}
init {
// Add the listener for `onActivityResult`
reactContext.addActivityEventListener(mActivityEventListener)
}
override fun getName(): String {
return "ImagePickerModule"
}
@ReactMethod
fun pickImage(promise: Promise) {
val currentActivity = currentActivity
if (currentActivity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist")
return
}
// Store the promise to resolve/reject when picker returns data
mPickerPromise = promise
try {
val galleryIntent = Intent(Intent.ACTION_PICK)
galleryIntent.type = "image/*"
val chooserIntent = Intent.createChooser(galleryIntent, "Pick an image")
currentActivity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST)
} catch (e: Exception) {
mPickerPromise!!.reject(E_FAILED_TO_SHOW_PICKER, e)
mPickerPromise = null
}
}
companion object {
private val IMAGE_PICKER_REQUEST = 467081
private val E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST"
private val E_PICKER_CANCELLED = "E_PICKER_CANCELLED"
private val E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER"
private val E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND"
}
}
| apache-2.0 | 61afc83a562f8ccc0a5a6f8b677044bd | 31.693182 | 112 | 0.613486 | 4.739703 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustFnImplMixin.kt | 1 | 1189 | package org.rust.lang.core.psi.impl.mixin
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.stubs.StubElement
import org.rust.lang.core.psi.RustFnElement
import org.rust.lang.core.psi.RustInnerAttrElement
import org.rust.lang.core.psi.impl.RustStubbedNamedElementImpl
import org.rust.lang.core.psi.queryAttributes
import org.rust.lang.core.stubs.RustFnStub
import org.rust.lang.core.stubs.RustNamedStub
abstract class RustFnImplMixin<StubT> : RustStubbedNamedElementImpl<StubT>,
RustFnElement
where StubT : RustFnStub, StubT: RustNamedStub, StubT : StubElement<*> {
constructor(node: ASTNode) : super(node)
constructor(stub: StubT, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
final override val innerAttrList: List<RustInnerAttrElement>
get() = block?.innerAttrList.orEmpty()
override val isAbstract: Boolean get() = stub?.isAbstract ?: block == null
override val isStatic: Boolean get() = stub?.isStatic ?: parameters?.selfArgument == null
override val isTest: Boolean get() = stub?.isTest ?: queryAttributes.hasAtomAttribute("test")
}
| mit | 56bc72b5a73cecc84a8c9d7ac750d868 | 40 | 97 | 0.746005 | 4.003367 | false | true | false | false |
LorittaBot/Loritta | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/routes/DonateRoute.kt | 1 | 16197 | package net.perfectdreams.spicymorenitta.routes
import kotlinx.browser.document
import kotlinx.html.InputType
import kotlinx.html.TD
import kotlinx.html.a
import kotlinx.html.div
import kotlinx.html.dom.create
import kotlinx.html.h2
import kotlinx.html.h3
import kotlinx.html.i
import kotlinx.html.id
import kotlinx.html.img
import kotlinx.html.input
import kotlinx.html.js.onClickFunction
import kotlinx.html.p
import kotlinx.html.stream.appendHTML
import kotlinx.html.style
import kotlinx.html.table
import kotlinx.html.td
import kotlinx.html.th
import kotlinx.html.tr
import kotlinx.serialization.builtins.ListSerializer
import net.perfectdreams.loritta.common.utils.ServerPremiumPlans
import net.perfectdreams.loritta.common.utils.UserPremiumPlans
import net.perfectdreams.spicymorenitta.SpicyMorenitta
import net.perfectdreams.spicymorenitta.application.ApplicationCall
import net.perfectdreams.spicymorenitta.locale
import net.perfectdreams.spicymorenitta.utils.PaymentUtils
import net.perfectdreams.spicymorenitta.utils.TingleModal
import net.perfectdreams.spicymorenitta.utils.TingleOptions
import net.perfectdreams.spicymorenitta.utils.appendBuilder
import net.perfectdreams.spicymorenitta.utils.page
import net.perfectdreams.spicymorenitta.utils.trackOverflowChanges
import net.perfectdreams.spicymorenitta.utils.visibleModal
import net.perfectdreams.spicymorenitta.views.dashboard.ServerConfig
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.get
import kotlin.collections.set
class DonateRoute(val m: SpicyMorenitta) : BaseRoute("/donate") {
companion object {
const val LOCALE_PREFIX = "website.donate"
}
override fun onRender(call: ApplicationCall) {
val plansTable = page.getElementById("plans-features") as HTMLDivElement
val rewards = listOf(
DonationReward("ignore_me", 0.0, false),
DonationReward("ignore_me", 99.99, false),
// ===[ RECOMMENDED ]===
DonationReward(locale["${LOCALE_PREFIX}.rewards.exclusiveProfileBadge"], 39.99, false),
DonationReward(locale["${LOCALE_PREFIX}.rewards.customProfileBackground"], 39.99, false),
// DonationReward("Personalizar nome/avatar da Loritta nas notificações do YouTube/Twitch/Twitter", 39.99, false),
DonationReward(locale["${LOCALE_PREFIX}.rewards.reducedCooldown"], 39.99, false),
// ===[ COMPLETE ]===
// ===[ NUMBERS ]===
DonationReward(locale["${LOCALE_PREFIX}.rewards.everyMinuteSonhos"], 39.99, false, callback = { column ->
when {
column >= 99.99 -> +"10"
column >= 39.99 -> +"4"
column >= 19.99 -> +"2"
else -> +"0"
}
}),
DonationReward(locale["${LOCALE_PREFIX}.rewards.dailyMultiplier"], 19.99, false, callback = { column ->
+ (ServerPremiumPlans.getPlanFromValue(column).dailyMultiplier.toString() + "x")
}),
DonationReward(locale["${LOCALE_PREFIX}.rewards.maxLevelUpRoles"], 19.99, false, callback = { column ->
+ ServerPremiumPlans.getPlanFromValue(column).maxLevelUpRoles.toString()
}),
DonationReward(locale["${LOCALE_PREFIX}.rewards.maxMemberCounters"], 19.99, false, callback = { column ->
+ ServerPremiumPlans.getPlanFromValue(column).memberCounterCount.toString()
}),
DonationReward(locale["${LOCALE_PREFIX}.rewards.maxSocialAccountsRelay"], 19.99, false, callback = { column ->
+ ServerPremiumPlans.getPlanFromValue(column).maxYouTubeChannels.toString()
}),
DonationReward(locale["${LOCALE_PREFIX}.rewards.maxDailyLimit"], 39.99, false, callback = { column ->
+ UserPremiumPlans.getPlanFromValue(column).maxDreamsInDaily.toString()
}),
DonationReward(locale["${LOCALE_PREFIX}.rewards.giveBackRepChange"], 39.99, false, callback = { column ->
+ (UserPremiumPlans.getPlanFromValue(column).loriReputationRetribution.toString() + "%")
}),
DonationReward(locale["${LOCALE_PREFIX}.rewards.globalExperienceMultiplier"], 99.99, false, callback = { column ->
+ (ServerPremiumPlans.getPlanFromValue(column).globalXpMultiplier.toString() + "x")
})
)
plansTable.appendBuilder(
StringBuilder().appendHTML(true).table(classes = "fancy-table centered-text") {
style = "margin: 0 auto;"
val rewardColumn = mutableListOf<Double>()
tr {
th { +"" }
rewards.asSequence()
.map { it.minimumDonation }
.distinct()
.filter { it == 0.0 || it == 19.99 || it == 39.99 || it == 99.99 }
.sortedBy { it }.toList().forEach {
th {
val titlePrefix = when (it) {
0.0 -> locale["${LOCALE_PREFIX}.plans.free"]
19.99 -> locale["${LOCALE_PREFIX}.plans.essential"]
39.99 -> locale["${LOCALE_PREFIX}.plans.recommended"]
99.99 -> locale["${LOCALE_PREFIX}.plans.complete"]
else -> "???"
}
if (it == 0.0) {
style = "opacity: 0.7; font-size: 0.9em;"
}
if (it == 39.99) {
style = "background-color: #83ff836b; font-size: 1.3em;"
}
+("$titlePrefix (R$" + it.toString().replace(".", ",") + ")")
}
rewardColumn.add(it)
}
}
for (reward in rewards.filterNot { it.doNotDisplayInPlans }.filter { it.name != "ignore_me" }) {
tr {
td {
attributes["style"] = "font-weight: 800;"
+reward.name
}
for (column in rewardColumn) {
td {
if (column == 0.0) {
style = "opacity: 0.7; font-size: 0.8em;"
}
if (column == 39.99) {
style = "background-color: #83ff836b;"
}
reward.callback.invoke(this, column)
}
}
}
}
tr {
// =====[ PREMIUM PLANS ]=====
td {
+ ""
}
val needsToLogin = m.userIdentification == null
val url = "https://discordapp.com/oauth2/authorize?redirect_uri=https://loritta.website%2Fdashboard&scope=identify%20guilds%20email&response_type=code&client_id=297153970613387264"
td {
}
fun TD.createBuyPlanButton(buttonPlanId: String, isBigger: Boolean) {
if (isBigger)
style = "background-color: #83ff836b;"
if (needsToLogin) {
a(href = url) {
div(classes = "button-discord button-discord-info pure-button") {
if (isBigger)
style = "font-size: 1.2em;"
i(classes = "fas fa-gift") {}
+" ${locale["${LOCALE_PREFIX}.buyPlan"]}"
}
}
} else {
div(classes = "button-discord button-discord-info pure-button") {
id = buttonPlanId
if (isBigger)
style = "font-size: 1.2em;"
i(classes = "fas fa-gift") {}
+" ${locale["${LOCALE_PREFIX}.buyPlan"]}"
}
}
}
td {
createBuyPlanButton("donate-button-plan1", false)
}
td {
createBuyPlanButton("donate-button-plan2", true)
}
td {
createBuyPlanButton("donate-button-plan3", false)
}
}
}
)
(document.getElementById("donate-button-plan1") as HTMLDivElement?)?.onclick = {
showPaymentSelectionModal(19.99)
}
(document.getElementById("donate-button-plan2") as HTMLDivElement?)?.onclick = {
showPaymentSelectionModal(39.99)
}
(document.getElementById("donate-button-plan3") as HTMLDivElement?)?.onclick = {
showPaymentSelectionModal(99.99)
}
(document.getElementById("renew-button") as HTMLDivElement?)?.onclick = {
val donationKeysJson = document.getElementById("donation-keys-json")?.innerHTML!!
val donationKeys = kotlinx.serialization.json.JSON.nonstrict.decodeFromString(ListSerializer(ServerConfig.DonationKey.serializer()), donationKeysJson)
if (donationKeys.isNotEmpty()) {
val modal = TingleModal(
TingleOptions(
footer = true,
cssClass = arrayOf("tingle-modal--overflow")
)
)
modal.setContent(
document.create.div {
div(classes = "category-name") {
+ "Suas keys atuais"
}
p {
+ "Parece que você já possui algumas keys, você deseja renovar elas?"
}
for (key in donationKeys) {
h2 {
+ "Key ${key.id} (R$ ${key.value})"
}
h3 {
+ "Você pode renovar ela por apenas R$ ${key.value * 0.8}!"
}
div(classes = "button-discord button-discord-info pure-button") {
style = "font-size: 1.25em; margin: 5px;"
+ "Renovar"
onClickFunction = {
val o = object {
val money = key.value // unused
val keyId = key.id.toString()
}
println(JSON.stringify(o))
modal.close()
PaymentUtils.requestAndRedirectToPaymentUrl(o)
}
}
}
}
)
/* modal.addFooterBtn("<i class=\"fas fa-gift\"></i> Eu quero comprar uma nova key", "button-discord button-discord-info pure-button button-discord-modal") {
modal.close()
showDonateModal(19.99)
} */
modal.addFooterBtn("<i class=\"fas fa-times\"></i> Fechar", "button-discord pure-button button-discord-modal button-discord-modal-secondary-action") {
modal.close()
}
modal.open()
} else {
showDonateModal(19.99)
}
}
}
fun showDonateModal(inputValue: Double) {
val modal = TingleModal(
TingleOptions(
footer = true,
cssClass = arrayOf("tingle-modal--overflow")
)
)
modal.setContent(
document.create.div {
div(classes = "category-name") {
+ locale["website.donate.areYouGoingToDonate"]
}
div {
style = "text-align: center;"
img {
src = "https://cdn.discordapp.com/attachments/510601125221761054/535199384535826442/FreshLori.gif"
}
p {
+ "Obrigada por querer doar para mim! Você não faz ideia de como cada compra me ajuda a sobreviver."
}
p {
+ "Antes de doar, veja todas as recompensas que você pode ganhar doando a quantidade que você deseja!"
}
p {
+ "Mas então... Quanto você vai querer doar?"
}
input(InputType.number, classes = "how-much-money") {
min = "1"
max = "1000"
value = inputValue.toString()
step = "0.10"
}
+ " reais"
p {
+ "Não se esqueça de entrar no meu servidor de suporte caso você tenha dúvidas sobre as vantagens, formas de pagamento e, na pior das hipóteses, se der algum problema. (vai se dá algum problema, né?)"
}
/* div {
div(classes = "button-discord button-discord-info pure-button") {
style = "font-size: 1.25em; margin: 5px;"
+ "PayPal (Cartão de Crédito e Saldo do PayPal)"
}
} */
}
}
)
modal.addFooterBtn("<i class=\"fas fa-cash-register\"></i> Escolher Forma de Pagamento", "button-discord button-discord-info pure-button button-discord-modal") {
modal.close()
showPaymentSelectionModal((visibleModal.getElementsByClassName("how-much-money")[0] as HTMLInputElement).value.toDouble())
}
modal.addFooterBtn("<i class=\"fas fa-times\"></i> Fechar", "button-discord pure-button button-discord-modal button-discord-modal-secondary-action") {
modal.close()
}
modal.open()
modal.trackOverflowChanges(m)
}
fun showPaymentSelectionModal(price: Double) {
val o = object {
val money = price
}
PaymentUtils.requestAndRedirectToPaymentUrl(o)
}
data class DonationReward(val name: String, val minimumDonation: Double, val doNotDisplayInPlans: Boolean, val callback: TD.(Double) -> Unit = { column ->
if (column >= minimumDonation) {
i("fas fa-check") {}
} else {
i("fas fa-times") {}
}
})
} | agpl-3.0 | 80c518877589c5b1c2a66f0a7b363091 | 43.811634 | 228 | 0.458519 | 5.171355 | false | false | false | false |
wakingrufus/mastodon-jfx | src/main/kotlin/com/github/wakingrufus/mastodon/ui/TootEditor.kt | 1 | 2197 | package com.github.wakingrufus.mastodon.ui
import com.github.wakingrufus.mastodon.client.parseUrl
import com.github.wakingrufus.mastodon.toot.createToot
import com.github.wakingrufus.mastodon.ui.styles.DefaultStyles
import com.sys1yagi.mastodon4j.MastodonClient
import com.sys1yagi.mastodon4j.api.entity.Status
import javafx.scene.paint.Color
import mu.KLogging
import tornadofx.*
class TootEditor : Fragment() {
companion object : KLogging()
val client: MastodonClient by param()
val inReplyTo: Status? by param()
val toot: (String) -> Status by param({ tootString ->
createToot(
client = client,
status = tootString,
inReplyToId = inReplyTo?.id)
})
val parseUrlFunc: (String) -> String by param(defaultValue = ::parseUrl)
var createdToot: Status? = null
override val root = vbox {
style {
backgroundColor = multi(DefaultStyles.backgroundColor)
}
inReplyTo?.let {
label("Replying to:") {
style {
fontSize = 2.em
minWidth = 11.em
padding = CssBox(1.px, 1.px, 1.px, 1.px)
textFill = DefaultStyles.armedTextColor
}
}
this += find<AccountFragment>(mapOf(
"account" to it.account!!,
"server" to parseUrlFunc(it.uri)))
val toot = parseToot(it.content)
toot.style {
backgroundColor = multi(DefaultStyles.backgroundColor)
textFill = Color.WHITE
}
this += toot
}
val tootText = textarea {
id = "toot-editor"
}
buttonbar {
button("Toot") {
addClass(DefaultStyles.smallButton)
id = "toot-submit"
action {
createdToot = toot(tootText.text)
close()
}
}
button("Close") {
addClass(DefaultStyles.smallButton)
action {
close()
}
}
}
}
} | mit | 2dd4fdd95c2c45f6ab35ff98c6644fa7 | 29.109589 | 76 | 0.526172 | 4.511294 | false | false | false | false |
sav007/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ResponseFieldSpec.kt | 1 | 22773 | package com.apollographql.apollo.compiler
import com.apollographql.apollo.api.ResponseField
import com.apollographql.apollo.api.ResponseReader
import com.apollographql.apollo.api.ResponseWriter
import com.apollographql.apollo.compiler.ir.CodeGenerationContext
import com.apollographql.apollo.compiler.ir.Field
import com.squareup.javapoet.*
import java.io.IOException
import java.util.*
import javax.lang.model.element.Modifier
class ResponseFieldSpec(
val irField: Field,
val fieldSpec: FieldSpec,
val normalizedFieldSpec: FieldSpec,
val responseFieldType: ResponseField.Type,
val typeConditions: List<String> = emptyList(),
val context: CodeGenerationContext
) {
fun factoryCode(): CodeBlock {
val factoryMethod = FACTORY_METHODS[responseFieldType]!!
return when (responseFieldType) {
ResponseField.Type.CUSTOM -> customTypeFactoryCode(irField, factoryMethod)
ResponseField.Type.INLINE_FRAGMENT,
ResponseField.Type.FRAGMENT ->
fragmentFactoryCode(irField, factoryMethod, typeConditions)
else -> genericFactoryCode(irField, factoryMethod)
}
}
fun readValueCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
return when (responseFieldType) {
ResponseField.Type.STRING,
ResponseField.Type.INT,
ResponseField.Type.LONG,
ResponseField.Type.DOUBLE,
ResponseField.Type.BOOLEAN -> readScalarCode(readerParam, fieldParam)
ResponseField.Type.CUSTOM -> readCustomCode(readerParam, fieldParam)
ResponseField.Type.ENUM -> readEnumCode(readerParam, fieldParam)
ResponseField.Type.OBJECT -> readObjectCode(readerParam, fieldParam)
ResponseField.Type.SCALAR_LIST -> readScalarListCode(readerParam, fieldParam)
ResponseField.Type.CUSTOM_LIST -> readCustomListCode(readerParam, fieldParam)
ResponseField.Type.OBJECT_LIST -> readObjectListCode(readerParam, fieldParam)
ResponseField.Type.INLINE_FRAGMENT -> readInlineFragmentCode(readerParam, fieldParam)
ResponseField.Type.FRAGMENT -> readFragmentsCode(readerParam, fieldParam)
}
}
fun writeValueCode(writerParam: CodeBlock, fieldParam: CodeBlock, marshaller: CodeBlock): CodeBlock {
return when (responseFieldType) {
ResponseField.Type.STRING,
ResponseField.Type.INT,
ResponseField.Type.LONG,
ResponseField.Type.DOUBLE,
ResponseField.Type.BOOLEAN -> writeScalarCode(writerParam, fieldParam)
ResponseField.Type.ENUM -> writeEnumCode(writerParam, fieldParam)
ResponseField.Type.CUSTOM -> writeCustomCode(writerParam, fieldParam)
ResponseField.Type.OBJECT -> writeObjectCode(writerParam, fieldParam, marshaller)
ResponseField.Type.SCALAR_LIST -> writeScalarList(writerParam, fieldParam)
ResponseField.Type.CUSTOM_LIST -> writeCustomList(writerParam, fieldParam)
ResponseField.Type.OBJECT_LIST -> writeObjectList(writerParam, fieldParam, marshaller)
ResponseField.Type.INLINE_FRAGMENT -> writeInlineFragmentCode(writerParam, marshaller)
ResponseField.Type.FRAGMENT -> writeFragmentsCode(writerParam, marshaller)
else -> CodeBlock.of("")
}
}
private fun customTypeFactoryCode(irField: Field, factoryMethod: String): CodeBlock {
val customScalarEnum = CustomEnumTypeSpecBuilder.className(context)
val customScalarEnumConst = normalizeGraphQlType(irField.type).toUpperCase(Locale.ENGLISH)
return CodeBlock.of("\$T.\$L(\$S, \$S, \$L, \$L, \$T.\$L)", ResponseField::class.java, factoryMethod,
irField.responseName, irField.fieldName, irField.argumentCodeBlock(), irField.isOptional(), customScalarEnum,
customScalarEnumConst)
}
private fun fragmentFactoryCode(irField: Field, factoryMethod: String, typeConditions: List<String>): CodeBlock {
val typeConditionListCode = typeConditions
.foldIndexed(CodeBlock.builder().add("\$T.asList(", Arrays::class.java)) { i, builder, typeCondition ->
builder.add(if (i > 0) ",\n" else "").add("\$S", typeCondition)
}
.add(")")
.build()
return CodeBlock.of("\$T.\$L(\$S, \$S, \$L)", ResponseField::class.java, factoryMethod, irField.responseName,
irField.fieldName, typeConditionListCode)
}
private fun genericFactoryCode(irField: Field, factoryMethod: String): CodeBlock {
return CodeBlock.of("\$T.\$L(\$S, \$S, \$L, \$L)", ResponseField::class.java, factoryMethod, irField.responseName,
irField.fieldName, irField.argumentCodeBlock(), irField.isOptional())
}
private fun readEnumCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val readValueCode = CodeBlock.builder()
.addStatement("final \$T \$L", normalizedFieldSpec.type, fieldSpec.name)
.beginControlFlow("if (\$LStr != null)", fieldSpec.name)
.addStatement("\$L = \$T.valueOf(\$LStr)", fieldSpec.name, normalizedFieldSpec.type, fieldSpec.name)
.nextControlFlow("else")
.addStatement("\$L = null", fieldSpec.name)
.endControlFlow()
.build()
return CodeBlock
.builder()
.addStatement("final \$T \$LStr = \$L.\$L(\$L)", ClassNames.STRING, fieldSpec.name, readerParam,
READ_METHODS[ResponseField.Type.STRING], fieldParam)
.add(readValueCode)
.build()
}
private fun readScalarCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
return CodeBlock.of("final \$T \$L = \$L.\$L(\$L);\n", normalizedFieldSpec.type, fieldSpec.name, readerParam,
READ_METHODS[responseFieldType], fieldParam)
}
private fun readCustomCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
return CodeBlock.of("final \$T \$L = \$L.\$L((\$T) \$L);\n", normalizedFieldSpec.type, fieldSpec.name, readerParam,
READ_METHODS[responseFieldType], ResponseField.CustomTypeField::class.java, fieldParam)
}
private fun readObjectCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val readerTypeSpec = TypeSpec.anonymousClassBuilder("")
.superclass(responseFieldObjectReaderTypeName(normalizedFieldSpec.type))
.addMethod(MethodSpec
.methodBuilder("read")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.returns(normalizedFieldSpec.type)
.addParameter(RESPONSE_READER_PARAM)
.addStatement("return \$L.map(\$L)", (normalizedFieldSpec.type as ClassName).mapperFieldName(),
RESPONSE_READER_PARAM.name)
.build())
.build()
return CodeBlock.of("final \$T \$L = \$L.\$L(\$L, \$L);\n", normalizedFieldSpec.type, fieldSpec.name, readerParam,
READ_METHODS[responseFieldType], fieldParam, readerTypeSpec)
}
private fun readScalarListCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val rawFieldType = with(normalizedFieldSpec.type) { if (isList()) listParamType() else this }
val readMethod = SCALAR_LIST_ITEM_READ_METHODS[rawFieldType] ?: "readString"
val readStatement = if (rawFieldType.isEnum(context)) {
CodeBlock.of("return \$T.valueOf(\$L.\$L());\n", rawFieldType, RESPONSE_LIST_ITEM_READER_PARAM.name, readMethod)
} else {
CodeBlock.of("return \$L.\$L();\n", RESPONSE_LIST_ITEM_READER_PARAM.name, readMethod)
}
val readerTypeSpec = TypeSpec.anonymousClassBuilder("")
.superclass(responseFieldListItemReaderType(rawFieldType))
.addMethod(MethodSpec
.methodBuilder("read")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.returns(rawFieldType)
.addParameter(RESPONSE_LIST_ITEM_READER_PARAM)
.addCode(readStatement)
.build())
.build()
return CodeBlock.of("final \$T \$L = \$L.\$L(\$L, \$L);\n", normalizedFieldSpec.type, fieldSpec.name, readerParam,
READ_METHODS[responseFieldType], fieldParam, readerTypeSpec)
}
private fun readCustomListCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val rawFieldType = normalizedFieldSpec.type.let { if (it.isList()) it.listParamType() else it }
val customScalarEnum = CustomEnumTypeSpecBuilder.className(context)
val customScalarEnumConst = normalizeGraphQlType(irField.type).toUpperCase(Locale.ENGLISH)
val readerTypeSpec = TypeSpec.anonymousClassBuilder("")
.superclass(responseFieldListItemReaderType(rawFieldType))
.addMethod(MethodSpec
.methodBuilder("read")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.returns(rawFieldType)
.addParameter(RESPONSE_LIST_ITEM_READER_PARAM)
.addStatement("return \$L.readCustomType(\$T.\$L)", RESPONSE_LIST_ITEM_READER_PARAM.name, customScalarEnum,
customScalarEnumConst)
.build())
.build()
return CodeBlock.of("final \$T \$L = \$L.\$L(\$L, \$L);\n", normalizedFieldSpec.type, fieldSpec.name, readerParam,
READ_METHODS[responseFieldType], fieldParam, readerTypeSpec)
}
private fun readObjectListCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val rawFieldType = normalizedFieldSpec.type.let { if (it.isList()) it.listParamType() else it }
val objectReaderTypeSpec = TypeSpec.anonymousClassBuilder("")
.superclass(responseFieldObjectReaderTypeName(rawFieldType))
.addMethod(MethodSpec
.methodBuilder("read")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.returns(rawFieldType)
.addParameter(RESPONSE_READER_PARAM)
.addStatement("return \$L.map(\$L)", (rawFieldType as ClassName).mapperFieldName(),
RESPONSE_READER_PARAM.name)
.build())
.build()
val listReaderTypeSpec = TypeSpec.anonymousClassBuilder("")
.superclass(responseFieldListItemReaderType(rawFieldType))
.addMethod(MethodSpec
.methodBuilder("read")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.returns(rawFieldType)
.addParameter(RESPONSE_LIST_ITEM_READER_PARAM)
.addStatement("return \$L.readObject(\$L)", RESPONSE_LIST_ITEM_READER_PARAM.name, objectReaderTypeSpec)
.build())
.build()
return CodeBlock.of("final \$T \$L = \$L.\$L(\$L, \$L);\n", normalizedFieldSpec.type, fieldSpec.name, readerParam,
READ_METHODS[responseFieldType], fieldParam, listReaderTypeSpec)
}
private fun readInlineFragmentCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val readerTypeSpec = TypeSpec.anonymousClassBuilder("")
.superclass(conditionalResponseFieldReaderTypeName(normalizedFieldSpec.type))
.addMethod(MethodSpec
.methodBuilder("read")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.returns(normalizedFieldSpec.type)
.addParameter(ParameterSpec.builder(String::class.java, CONDITIONAL_TYPE_VAR).build())
.addParameter(RESPONSE_READER_PARAM)
.addStatement("return \$L.map(\$L)", (normalizedFieldSpec.type as ClassName).mapperFieldName(),
RESPONSE_READER_PARAM.name)
.build())
.build()
return CodeBlock.of("final \$T \$L = \$L.\$L((\$T) \$L, \$L);\n", normalizedFieldSpec.type, fieldSpec.name,
readerParam, READ_METHODS[responseFieldType], ResponseField.ConditionalTypeField::class.java, fieldParam,
readerTypeSpec)
}
private fun readFragmentsCode(readerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val readerTypeSpec = TypeSpec.anonymousClassBuilder("")
.superclass(conditionalResponseFieldReaderTypeName(FRAGMENTS_CLASS))
.addMethod(MethodSpec
.methodBuilder("read")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.returns(FRAGMENTS_CLASS)
.addParameter(ParameterSpec.builder(String::class.java, CONDITIONAL_TYPE_VAR).build())
.addParameter(RESPONSE_READER_PARAM)
.addStatement("return \$L.map(\$L, \$L)", FRAGMENTS_CLASS.mapperFieldName(),
RESPONSE_READER_PARAM.name, CONDITIONAL_TYPE_VAR)
.build())
.build()
return CodeBlock.of("final \$T \$L = \$L.\$L((\$T) \$L, \$L);\n", normalizedFieldSpec.type, fieldSpec.name,
readerParam, READ_METHODS[responseFieldType], ResponseField.ConditionalTypeField::class.java, fieldParam,
readerTypeSpec)
}
private fun writeScalarCode(writerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val valueCode = fieldSpec.type.unwrapOptionalValue(fieldSpec.name)
return CodeBlock.of("\$L.\$L(\$L, \$L);\n", writerParam, WRITE_METHODS[responseFieldType],
fieldParam, valueCode)
}
private fun writeEnumCode(writerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val valueCode = fieldSpec.type.unwrapOptionalValue(fieldSpec.name) {
CodeBlock.of("\$L.name()", it)
}
return CodeBlock.of("\$L.\$L(\$L, \$L);\n", writerParam, WRITE_METHODS[responseFieldType],
fieldParam, valueCode)
}
private fun writeCustomCode(writerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val valueCode = fieldSpec.type.unwrapOptionalValue(fieldSpec.name)
return CodeBlock.of("\$L.\$L((\$T) \$L, \$L);\n", writerParam, WRITE_METHODS[responseFieldType],
ResponseField.CustomTypeField::class.java, fieldParam, valueCode)
}
private fun writeObjectCode(writerParam: CodeBlock, fieldParam: CodeBlock, marshaller: CodeBlock): CodeBlock {
val valueCode = fieldSpec.type.unwrapOptionalValue(fieldSpec.name) {
CodeBlock.of("\$L.\$L", it, marshaller)
}
return CodeBlock.of("\$L.\$L(\$L, \$L);\n", writerParam, WRITE_METHODS[responseFieldType], fieldParam, valueCode)
}
private fun writeScalarList(writerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val rawFieldType = with(normalizedFieldSpec.type) { if (isList()) listParamType() else this }
val writeMethod = SCALAR_LIST_ITEM_WRITE_METHODS[rawFieldType] ?: "writeString"
val writeStatement = CodeBlock.builder()
.beginControlFlow("for (\$T \$L : \$L)", rawFieldType, "\$item",
fieldSpec.type.unwrapOptionalValue(fieldSpec.name, false))
.add(
if (rawFieldType.isEnum(context)) {
CodeBlock.of("\$L.\$L(\$L.name());\n", RESPONSE_LIST_ITEM_WRITER_PARAM.name, writeMethod, "\$item")
} else {
CodeBlock.of("\$L.\$L(\$L);\n", RESPONSE_LIST_ITEM_WRITER_PARAM.name, writeMethod, "\$item")
})
.endControlFlow()
.build()
val listWriterType = TypeSpec.anonymousClassBuilder("")
.addSuperinterface(ResponseWriter.ListWriter::class.java)
.addMethod(MethodSpec.methodBuilder("write")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.addParameter(RESPONSE_LIST_ITEM_WRITER_PARAM)
.addCode(writeStatement)
.build()
)
.build()
val valueCode = fieldSpec.type.unwrapOptionalValue(fieldSpec.name) {
CodeBlock.of("\$L", listWriterType)
}
return CodeBlock.of("\$L.\$L(\$L, \$L);\n", writerParam, WRITE_METHODS[responseFieldType], fieldParam, valueCode)
}
private fun writeCustomList(writerParam: CodeBlock, fieldParam: CodeBlock): CodeBlock {
val rawFieldType = normalizedFieldSpec.type.let { if (it.isList()) it.listParamType() else it }
val customScalarEnum = CustomEnumTypeSpecBuilder.className(context)
val customScalarEnumConst = normalizeGraphQlType(irField.type).toUpperCase(Locale.ENGLISH)
val writeStatement = CodeBlock.builder()
.beginControlFlow("for (\$T \$L : \$L)", rawFieldType, "\$item",
fieldSpec.type.unwrapOptionalValue(fieldSpec.name, false))
.addStatement("\$L.writeCustom(\$T.\$L, \$L)", RESPONSE_LIST_ITEM_WRITER_PARAM.name,
customScalarEnum, customScalarEnumConst, "\$item")
.endControlFlow()
.build()
val listWriterType = TypeSpec.anonymousClassBuilder("")
.addSuperinterface(ResponseWriter.ListWriter::class.java)
.addMethod(MethodSpec.methodBuilder("write")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.addParameter(RESPONSE_LIST_ITEM_WRITER_PARAM)
.addCode(writeStatement)
.build()
)
.build()
val valueCode = fieldSpec.type.unwrapOptionalValue(fieldSpec.name) {
CodeBlock.of("\$L", listWriterType)
}
return CodeBlock.of("\$L.\$L(\$L, \$L);\n", writerParam, WRITE_METHODS[responseFieldType], fieldParam, valueCode)
}
private fun writeObjectList(writerParam: CodeBlock, fieldParam: CodeBlock, marshaller: CodeBlock): CodeBlock {
val rawFieldType = with(normalizedFieldSpec.type) { if (isList()) listParamType() else this }
val writeStatement = CodeBlock.builder()
.beginControlFlow("for (\$T \$L : \$L)", rawFieldType, "\$item",
fieldSpec.type.unwrapOptionalValue(fieldSpec.name, false))
.addStatement("\$L.writeObject(\$L.\$L)", RESPONSE_LIST_ITEM_WRITER_PARAM.name, "\$item", marshaller)
.endControlFlow()
.build()
val listWriterType = TypeSpec.anonymousClassBuilder("")
.addSuperinterface(ResponseWriter.ListWriter::class.java)
.addMethod(MethodSpec.methodBuilder("write")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.addParameter(RESPONSE_LIST_ITEM_WRITER_PARAM)
.addCode(writeStatement)
.build()
)
.build()
val valueCode = fieldSpec.type.unwrapOptionalValue(fieldSpec.name) {
CodeBlock.of("\$L", listWriterType)
}
return CodeBlock.of("\$L.\$L(\$L, \$L);\n", writerParam, WRITE_METHODS[responseFieldType], fieldParam, valueCode)
}
private fun writeInlineFragmentCode(writerParam: CodeBlock, marshaller: CodeBlock): CodeBlock {
return CodeBlock.builder()
.addStatement("final \$T \$L = \$L", fieldSpec.type.unwrapOptionalType().withoutAnnotations(),
"\$${fieldSpec.name}", fieldSpec.type.unwrapOptionalValue(fieldSpec.name))
.beginControlFlow("if (\$L != null)", "\$${fieldSpec.name}")
.addStatement("\$L.\$L.marshal(\$L)", "\$${fieldSpec.name}", marshaller, writerParam)
.endControlFlow()
.build()
}
private fun writeFragmentsCode(writerParam: CodeBlock, marshaller: CodeBlock): CodeBlock {
return CodeBlock.of("\$L.\$L.marshal(\$L);\n", fieldSpec.name, marshaller, writerParam)
}
private fun responseFieldObjectReaderTypeName(type: TypeName) =
ParameterizedTypeName.get(ClassName.get(ResponseReader.ObjectReader::class.java), type)
private fun conditionalResponseFieldReaderTypeName(type: TypeName) =
ParameterizedTypeName.get(ClassName.get(ResponseReader.ConditionalTypeReader::class.java), type)
private fun responseFieldListItemReaderType(type: TypeName) =
ParameterizedTypeName.get(ClassName.get(ResponseReader.ListReader::class.java), type)
companion object {
private val FACTORY_METHODS = mapOf(
ResponseField.Type.STRING to "forString",
ResponseField.Type.INT to "forInt",
ResponseField.Type.LONG to "forLong",
ResponseField.Type.DOUBLE to "forDouble",
ResponseField.Type.BOOLEAN to "forBoolean",
ResponseField.Type.ENUM to "forString",
ResponseField.Type.OBJECT to "forObject",
ResponseField.Type.SCALAR_LIST to "forScalarList",
ResponseField.Type.CUSTOM_LIST to "forCustomList",
ResponseField.Type.OBJECT_LIST to "forObjectList",
ResponseField.Type.CUSTOM to "forCustomType",
ResponseField.Type.FRAGMENT to "forFragment",
ResponseField.Type.INLINE_FRAGMENT to "forInlineFragment"
)
private val READ_METHODS = mapOf(
ResponseField.Type.STRING to "readString",
ResponseField.Type.INT to "readInt",
ResponseField.Type.LONG to "readLong",
ResponseField.Type.DOUBLE to "readDouble",
ResponseField.Type.BOOLEAN to "readBoolean",
ResponseField.Type.ENUM to "readString",
ResponseField.Type.OBJECT to "readObject",
ResponseField.Type.SCALAR_LIST to "readList",
ResponseField.Type.CUSTOM_LIST to "readList",
ResponseField.Type.OBJECT_LIST to "readList",
ResponseField.Type.CUSTOM to "readCustomType",
ResponseField.Type.FRAGMENT to "readConditional",
ResponseField.Type.INLINE_FRAGMENT to "readConditional"
)
private val WRITE_METHODS = mapOf(
ResponseField.Type.STRING to "writeString",
ResponseField.Type.INT to "writeInt",
ResponseField.Type.LONG to "writeLong",
ResponseField.Type.DOUBLE to "writeDouble",
ResponseField.Type.BOOLEAN to "writeBoolean",
ResponseField.Type.ENUM to "writeString",
ResponseField.Type.CUSTOM to "writeCustom",
ResponseField.Type.OBJECT to "writeObject",
ResponseField.Type.SCALAR_LIST to "writeList",
ResponseField.Type.CUSTOM_LIST to "writeList",
ResponseField.Type.OBJECT_LIST to "writeList"
)
private val SCALAR_LIST_ITEM_READ_METHODS = mapOf(
ClassNames.STRING to "readString",
TypeName.INT to "readInt",
TypeName.INT.box() to "readInt",
TypeName.LONG to "readLong",
TypeName.LONG.box() to "readLong",
TypeName.DOUBLE to "readDouble",
TypeName.DOUBLE.box() to "readDouble",
TypeName.BOOLEAN to "readBoolean",
TypeName.BOOLEAN.box() to "readBoolean"
)
private val SCALAR_LIST_ITEM_WRITE_METHODS = mapOf(
ClassNames.STRING to "writeString",
TypeName.INT to "writeInt",
TypeName.INT.box() to "writeInt",
TypeName.LONG to "writeLong",
TypeName.LONG.box() to "writeLong",
TypeName.DOUBLE to "writeDouble",
TypeName.DOUBLE.box() to "writeDouble",
TypeName.BOOLEAN to "writeBoolean",
TypeName.BOOLEAN.box() to "writeBoolean"
)
private val RESPONSE_READER_PARAM =
ParameterSpec.builder(ResponseReader::class.java, "reader").build()
private val RESPONSE_LIST_ITEM_READER_PARAM =
ParameterSpec.builder(ResponseReader.ListItemReader::class.java, "reader").build()
private val RESPONSE_LIST_ITEM_WRITER_PARAM =
ParameterSpec.builder(ResponseWriter.ListItemWriter::class.java, "listItemWriter").build()
private val FRAGMENTS_CLASS = ClassName.get("", "Fragments")
private val CONDITIONAL_TYPE_VAR = "conditionalType"
}
} | mit | 7fc227b843df579a51f5e66ebf4cd69f | 49.162996 | 119 | 0.685944 | 4.340194 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/features/quests/QuestDetailFragment.kt | 1 | 7386 | package com.ghstudios.android.features.quests
import androidx.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import com.ghstudios.android.AssetLoader
import com.ghstudios.android.data.classes.Quest
import com.ghstudios.android.mhgendatabase.R
import com.ghstudios.android.features.locations.LocationDetailPagerActivity
import com.ghstudios.android.ClickListeners.MonsterClickListener
import com.ghstudios.android.data.classes.MonsterToQuest
import com.ghstudios.android.mhgendatabase.databinding.FragmentQuestDetailBinding
import com.ghstudios.android.util.applyArguments
import com.ghstudios.android.util.setImageAsset
/**
* Shows the main quest information.
* This class's views are binded via Kotlin KTX extensions
*/
class QuestDetailFragment : Fragment() {
companion object {
private const val ARG_QUEST_ID = "QUEST_ID"
@JvmStatic fun newInstance(questId: Long): QuestDetailFragment {
return QuestDetailFragment().applyArguments {
putLong(ARG_QUEST_ID, questId)
}
}
}
private lateinit var binding: FragmentQuestDetailBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = FragmentQuestDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewModel = ViewModelProvider(activity!!).get(QuestDetailViewModel::class.java)
viewModel.quest.observe(viewLifecycleOwner, Observer { quest ->
if (quest != null) updateUI(quest)
})
viewModel.monsters.observe(viewLifecycleOwner, Observer { monsters ->
if (monsters != null) bindMonsters(monsters)
})
// Click listener for quest location
binding.locationLayout.setOnClickListener { v ->
// The id argument will be the Monster ID; CursorAdapter gives us this
// for free
val i = Intent(activity, LocationDetailPagerActivity::class.java)
var id = v.tag as Long
if (id > 100) id = id - 100
i.putExtra(LocationDetailPagerActivity.EXTRA_LOCATION_ID, id)
startActivity(i)
}
}
/**
* Renders the list of monsters in the Quest Detail.
* Internally, it creates an adapter and then uses it to populate a linear layout.
*/
private fun bindMonsters(monsters: List<MonsterToQuest>) {
// Use adapter to manually populate a LinearLayout
val adapter = MonsterToQuestListAdapter(context!!, monsters)
for (i in 0 until adapter.count) {
val v = adapter.getView(i, null, binding.monsterHabitatFragment)
binding.monsterHabitatFragment.addView(v)
}
}
private fun updateUI(mQuest: Quest) {
// bind title bar
with (binding.titlebar) {
setIconDrawable(AssetLoader.loadIconFor(mQuest))
setTitleText(mQuest.name)
}
with(binding) {
goal.text = mQuest.goal
hub.text = AssetLoader.localizeHub(mQuest.hub)
level.text = mQuest.starString
hrp.setValueText(mQuest.hrp.toString())
reward.setValueText("" + mQuest.reward + "z")
fee.setValueText("" + mQuest.fee + "z")
location.text = mQuest.location?.name
location.tag = mQuest.location?.id
locationLayout.tag = mQuest.location?.id
subquest.text = mQuest.subGoal
subhrp.text = "" + mQuest.subHrp
subreward.text = "" + mQuest.subReward + "z"
description.text = mQuest.flavor
// Get Location based on ID and set image thumbnail
locationImage.setImageAsset(mQuest.location)
}
}
/**
* Internal adapter used to render the list of monsters shown in a quest
*/
private class MonsterToQuestListAdapter(context: Context,
items: List<MonsterToQuest>) : ArrayAdapter<MonsterToQuest>(context, 0, items) {
override fun getView(position: Int, view: View?, parent: ViewGroup): View {
var view = view
if (view == null) {
val inflater = LayoutInflater.from(context)
view = inflater.inflate(R.layout.fragment_quest_monstertoquest, parent, false)
}
val monsterToQuest = getItem(position)
// Set up the text view
val itemLayout = view!!.findViewById<LinearLayout>(R.id.listitem)
val habitatLayout = view.findViewById<LinearLayout>(R.id.habitat_layout)
val monsterImageView = view.findViewById<ImageView>(R.id.detail_monster_image)
val monsterTextView = view.findViewById<TextView>(R.id.detail_monster_label)
val unstableTextView = view.findViewById<TextView>(R.id.detail_monster_unstable)
val startTextView = view.findViewById<TextView>(R.id.habitat_start)
val travelTextView = view.findViewById<TextView>(R.id.habitat_travel)
val endTextView = view.findViewById<TextView>(R.id.habitat_end)
val hyperTextView = view.findViewById<TextView>(R.id.detail_monster_hyper)
val cellMonsterText = monsterToQuest!!.monster!!.name
if (monsterToQuest.isUnstable) {
unstableTextView.visibility = View.VISIBLE
unstableTextView.setText(R.string.unstable)
} else
unstableTextView.visibility = View.GONE
if (monsterToQuest.isHyper) {
hyperTextView.visibility = View.VISIBLE
hyperTextView.setText(R.string.hyper)
} else
hyperTextView.visibility = View.GONE
monsterTextView.text = cellMonsterText
AssetLoader.setIcon(monsterImageView, monsterToQuest.monster!!)
val habitat = monsterToQuest.habitat
if (habitat != null) {
val start = habitat.start
val area = habitat.areas
val rest = habitat.rest
var areas = ""
for (j in area!!.indices) {
areas += java.lang.Long.toString(area[j])
if (j != area.size - 1) {
areas += ", "
}
}
startTextView.text = java.lang.Long.toString(start)
travelTextView.text = areas
endTextView.text = java.lang.Long.toString(rest)
habitatLayout.visibility = View.VISIBLE
} else
habitatLayout.visibility = View.GONE
itemLayout.tag = monsterToQuest.monster!!.id
itemLayout.setOnClickListener(MonsterClickListener(context,
monsterToQuest.monster!!.id))
return view
}
}
}
| mit | 96da5a86d6912bdb96b26ade613af5ff | 38.079365 | 124 | 0.635797 | 4.716475 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/development/development.kt | 1 | 1520 | package at.cpickl.gadsu.development
import at.cpickl.gadsu.global.GadsuSystemProperty
import at.cpickl.gadsu.global.UserEvent
import at.cpickl.gadsu.view.GadsuMenuBar
import com.google.common.eventbus.EventBus
import javax.swing.JMenu
import javax.swing.JMenuItem
@Suppress("SimplifyBooleanWithConstants")
object Development {
val ENABLED: Boolean = GadsuSystemProperty.development.isEnabledOrFalse()
val COLOR_ENABLED = ENABLED && false
val SHOW_DEV_WINDOW_AT_STARTUP = ENABLED && false
val MOCKMAIL_ENABLED = ENABLED && true
init {
if (ENABLED) {
println("Development mode is enabled via '-D${GadsuSystemProperty.development.key}=true'")
}
}
fun fiddleAroundWithMenuBar(menu: GadsuMenuBar, bus: EventBus) {
if (!ENABLED) {
return
}
val menuDevelopment = JMenu("Development")
menu.add(menuDevelopment)
addItemTo(menuDevelopment, "Development Window", ShowDevWindowEvent(), bus)
menuDevelopment.addSeparator()
addItemTo(menuDevelopment, "Reset Data", DevelopmentResetDataEvent(), bus)
addItemTo(menuDevelopment, "Reset Screenshot Data", DevelopmentResetScreenshotDataEvent(), bus)
addItemTo(menuDevelopment, "Clear Data", DevelopmentClearDataEvent(), bus)
}
private fun addItemTo(menu: JMenu, label: String, event: UserEvent, bus: EventBus) {
val item = JMenuItem(label)
item.addActionListener { bus.post(event) }
menu.add(item)
}
}
| apache-2.0 | 57d95c23ee1b0ffb1e1ecf267cda93d8 | 31.340426 | 103 | 0.701316 | 4.380403 | false | false | false | false |
simonorono/SRSM | src/main/kotlin/srsm/window/Columnas.kt | 1 | 1276 | /*
* Copyright 2016 Sociedad Religiosa Servidores de María
*
* 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 srsm.window
import javafx.fxml.FXMLLoader
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.stage.Stage
import srsm.controller.Columnas
class Columnas {
private val stage = Stage()
private val controller: Columnas
init {
val loader = FXMLLoader(javaClass.classLoader.getResource("fxml/columnas.fxml"))
val root: Parent = loader.load()
val scene = Scene(root)
controller = loader.getController()
stage.title = "Columnas"
stage.scene = scene
}
fun selectedColumns() = controller.selectedColumns.toTypedArray()
fun showAndWait() = stage.showAndWait()
}
| apache-2.0 | b2f4cea08da21e0abd74309b4ddce025 | 30.097561 | 88 | 0.720784 | 4.126214 | false | false | false | false |
PizzaGames/emulio | core/src/main/com/github/emulio/ui/screens/scraper/EditGameInfoDialog.kt | 1 | 11628 | package com.github.emulio.ui.screens.scraper
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Group
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.utils.Pools
import com.github.czyzby.lml.parser.impl.AbstractLmlView
import com.github.czyzby.lml.util.Lml
import com.github.emulio.Emulio
import com.github.emulio.model.config.InputConfig
import com.github.emulio.ui.screens.EmulioDialog
import com.github.emulio.ui.screens.addClickListener
import mu.KotlinLogging
import kotlin.reflect.KClass
val logger = KotlinLogging.logger { }
class EditGameInfoDialog(emulio: Emulio,
stage: Stage,
private val confirmCallback: (text: String) -> Unit = {}) : EmulioDialog("Game info", emulio) {
private val view: EditGameInfoView
private val btCancel: Button
private val btConfirm: Button
// private val btSpace: Button
// private val btShift: Button
// private val btBackspace: Button
// private val buttons: List<Button>
//
// private val textArea: TextArea
//
// private var mapTraverseButtons: Map<Button, TraverseKey>
var text: String? = null
init {
logger.debug { "initializing virtual keyboard" }
val parser = Lml.parser().skin(skin).build()
logger.debug { "reading keyboard lml file" }
val template = Gdx.files.internal("templates/EditGameInfo.lml")
view = EditGameInfoView(stage)
logger.debug { "filling dialog with template read from lml file" }
parser.createView(view, template).forEach { actor ->
contentTable.add(actor).expand().fill()
}
logger.debug { "mapping buttons and keys" }
btCancel = contentTable.findActor("cancel")
btConfirm = contentTable.findActor("confirm")
/*
btSpace = contentTable.findActor("space")
btShift = contentTable.findActor("shift")
btBackspace = contentTable.findActor("backspace")
textArea = contentTable.findActor("text")
buttons = contentTable.findByType(Button::class)
val buttonsMap = buttons.filterIsInstance(TextButton::class.java).map { it.text.toString().toUpperCase() to it }.toMap()
fun key(letter: String): Actor {
return buttonsMap[letter] ?: error("Key not found")
}
logger.debug { "creating traverse keys map" }
mapTraverseButtons = buttons.map { button ->
button to if (button is TextButton) {
when (button.text.toString().toUpperCase()) {
"1" -> TraverseKey(button, key("0"), key("2"), btConfirm, key("Q"))
"2" -> TraverseKey(button, key("1"), key("3"), btConfirm, key("W"))
"3" -> TraverseKey(button, key("2"), key("4"), btConfirm, key("E"))
"4" -> TraverseKey(button, key("3"), key("5"), btConfirm, key("R"))
"5" -> TraverseKey(button, key("4"), key("6"), btConfirm, key("T"))
"6" -> TraverseKey(button, key("5"), key("7"), btConfirm, key("Y"))
"7" -> TraverseKey(button, key("6"), key("8"), btCancel, key("U"))
"8" -> TraverseKey(button, key("7"), key("9"), btCancel, key("I"))
"9" -> TraverseKey(button, key("8"), key("0"), btCancel, key("O"))
"0" -> TraverseKey(button, key("9"), key("1"), btCancel, key("P"))
"Q" -> TraverseKey(button, key("P"), key("W"), key("1"), key("A"))
"W" -> TraverseKey(button, key("Q"), key("E"), key("2"), key("S"))
"E" -> TraverseKey(button, key("W"), key("R"), key("3"), key("D"))
"R" -> TraverseKey(button, key("E"), key("T"), key("4"), key("F"))
"T" -> TraverseKey(button, key("R"), key("Y"), key("5"), key("G"))
"Y" -> TraverseKey(button, key("T"), key("U"), key("6"), key("H"))
"U" -> TraverseKey(button, key("Y"), key("I"), key("7"), key("J"))
"I" -> TraverseKey(button, key("U"), key("O"), key("8"), key("K"))
"O" -> TraverseKey(button, key("I"), key("P"), key("9"), key("K"))
"P" -> TraverseKey(button, key("O"), key("Q"), key("0"), key("L"))
"A" -> TraverseKey(button, key("L"), key("S"), key("Q"), key("Z"))
"S" -> TraverseKey(button, key("A"), key("D"), key("W"), key("Z"))
"D" -> TraverseKey(button, key("S"), key("F"), key("E"), key("X"))
"F" -> TraverseKey(button, key("D"), key("G"), key("R"), key("C"))
"G" -> TraverseKey(button, key("F"), key("H"), key("T"), key("V"))
"H" -> TraverseKey(button, key("G"), key("J"), key("Y"), key("B"))
"J" -> TraverseKey(button, key("H"), key("K"), key("U"), key("N"))
"K" -> TraverseKey(button, key("J"), key("L"), key("I"), key("M"))
"L" -> TraverseKey(button, key("K"), key("A"), key("O"), key("M"))
"Z" -> TraverseKey(button, key("M"), key("X"), key("S"), btShift)
"X" -> TraverseKey(button, key("Z"), key("C"), key("D"), key("@"))
"C" -> TraverseKey(button, key("X"), key("V"), key("F"), btSpace)
"V" -> TraverseKey(button, key("C"), key("B"), key("H"), btSpace)
"B" -> TraverseKey(button, key("V"), key("N"), key("J"), btSpace)
"N" -> TraverseKey(button, key("B"), key("M"), key("K"), key("/"))
"M" -> TraverseKey(button, key("N"), key("Z"), key("J"), btBackspace)
"@" -> TraverseKey(button, btShift, btSpace, key("Z"), btConfirm)
"/" -> TraverseKey(button, btSpace, btBackspace, key("M"), btCancel)
else -> when (button) {
btSpace -> TraverseKey(btSpace, key("@"), key("/"), key("C"), btConfirm)
btConfirm -> TraverseKey(btConfirm, btCancel, btCancel, btSpace, key("1"))
btCancel -> TraverseKey(btCancel, btConfirm, btConfirm, btSpace, key("1"))
else -> error("Key not found for $button")
}
}
} else {
when (button) {
btShift -> TraverseKey(btShift, btBackspace, key("@"), key("Z"), btConfirm)
btBackspace -> TraverseKey(btBackspace, key("/"), btShift, key("M"), btCancel)
else -> error("Key not found for $button")
}
}
}.toMap()
logger.debug { "adding listeners" }
for (button in buttons.filterIsInstance(TextButton::class.java).filter { it.name == null }) {
button.addClickListener {
val char = button.text[0].let {
if (btShift.isChecked) {
btShift.isChecked = false
it.toUpperCase()
} else {
it.toLowerCase()
}
}
textArea.text = textArea.text + char
}
}
*/
/*
btSpace.addClickListener {
textArea.text = textArea.text + " "
}
btBackspace.addClickListener {
if (!textArea.text.isBlank()) {
textArea.text = textArea.text.substring(0, textArea.text.length - 1)
}
}
*/
btConfirm.addClickListener {
confirmAction()
}
btCancel.addClickListener {
cancelAction()
}
}
private fun cancelAction() {
logger.debug { "cancelAction" }
this.text = null
closeDialog()
}
private fun confirmAction() {
// this.text = textArea.text
logger.info { "VirtualKeyboard confirmed (text: $text)" }
this.confirmCallback(this.text ?: "")
closeDialog()
}
enum class Traverse {
UP,
DOWN,
LEFT,
RIGHT
}
data class TraverseKey(
val key: Actor,
val keyLeft: Actor,
val keyRight: Actor,
val keyUp: Actor,
val keyDown: Actor)
private fun traverseButtons(direction: Traverse) {
logger.debug { "traverse buttons: $direction" }
val focused = stage.keyboardFocus
// if (focused !is Button) {
// stage.keyboardFocus = buttons.first()
// return
// }
//
// fun findTraverse(button: Button): TraverseKey {
// return mapTraverseButtons[button] ?: error("Key not found")
// }
// when (direction) {
// Traverse.LEFT -> stage.keyboardFocus = findTraverse(focused).keyLeft
// Traverse.RIGHT -> stage.keyboardFocus = findTraverse(focused).keyRight
// Traverse.UP -> stage.keyboardFocus = findTraverse(focused).keyUp
// Traverse.DOWN -> stage.keyboardFocus = findTraverse(focused).keyDown
// }
}
override fun onConfirmButton(input: InputConfig) {
val focused = stage.keyboardFocus
if (focused is Button) {
fireClick(focused)
}
}
private fun fireKey(actor: Actor, character: Char) {
val inputEvent = Pools.obtain(InputEvent::class.java).apply {
reset()
this.button = 0
this.relatedActor = actor
this.character = character
}
try {
inputEvent.type = InputEvent.Type.keyTyped
actor.fire(inputEvent)
} finally {
Pools.free(inputEvent)
}
}
private fun fireClick(button: Button) {
val inputEvent = Pools.obtain(InputEvent::class.java).apply {
reset()
this.button = 0
this.relatedActor = button
}
try {
inputEvent.type = InputEvent.Type.touchDown
button.fire(inputEvent)
inputEvent.type = InputEvent.Type.touchUp
button.fire(inputEvent)
} finally {
Pools.free(inputEvent)
}
}
override fun onCancelButton(input: InputConfig) {
// if (stage.keyboardFocus != textArea) {
// cancelAction()
// }
}
override fun onUpButton(input: InputConfig) {
traverseButtons(Traverse.UP)
}
override fun onDownButton(input: InputConfig) {
traverseButtons(Traverse.DOWN)
}
override fun onLeftButton(input: InputConfig) {
traverseButtons(Traverse.LEFT)
}
override fun onRightButton(input: InputConfig) {
traverseButtons(Traverse.RIGHT)
}
override fun onSelectButton(input: InputConfig) {
// stage.keyboardFocus = textArea
}
override fun onExitButton(input: InputConfig) {
cancelAction()
}
}
private fun <T : Actor> Group.findByType(kClass: KClass<T>): List<T> {
val found = ArrayList<T>()
this.children.forEach { child ->
if (kClass.java.isInstance(child)) {
@Suppress("UNCHECKED_CAST")
found.add(child as T)
}
if (child is Group) {
found.addAll(child.findByType(kClass))
}
}
return found
}
class EditGameInfoView(stage: Stage): AbstractLmlView(stage) {
override fun getViewId(): String {
return "EditGameInfoId"
}
} | gpl-3.0 | fee7fa306753df5c4929f5a08b2d06c9 | 35.340625 | 128 | 0.532422 | 4.130728 | false | false | false | false |
TheFallOfRapture/First-Game-Engine | src/main/kotlin/com/morph/engine/graphics/components/Particles.kt | 2 | 5408 | package com.morph.engine.graphics.components
import com.morph.engine.collision.components.BoundingBox2D
import com.morph.engine.core.IWorld
import com.morph.engine.entities.Component
import com.morph.engine.entities.EntityFactory
import com.morph.engine.graphics.Color
import com.morph.engine.graphics.Texture
import com.morph.engine.graphics.shaders.InstancedShader
import com.morph.engine.math.Vector2f
import com.morph.engine.math.Vector3f
import com.morph.engine.physics.components.RigidBody
import com.morph.engine.physics.components.Transform2D
import org.lwjgl.opengl.GL11.GL_DOUBLE
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.glEnableVertexAttribArray
import org.lwjgl.opengl.GL20.glVertexAttribPointer
import org.lwjgl.opengl.GL30.glBindVertexArray
import org.lwjgl.opengl.GL30.glGenVertexArrays
import org.lwjgl.opengl.GL33.glVertexAttribDivisor
import java.util.*
class Particle(var color : Color, val emitter : Emitter) : Component() {
var age = 0f
}
class Emitter(
val color : Color,
val spawnRate : Float,
val velocity : Vector3f,
val lifetime : Float,
val shader : InstancedShader,
val texture : Texture = Texture(null),
var enabled : Boolean = true,
private val particles: Queue<Particle> = LinkedList()
) : Component(), Queue<Particle> by particles {
var acc = 0f
val maxParticles
get() = Math.ceil((lifetime * spawnRate).toDouble()).toLong()
var vao : Int = 0
var particleBuffer = 0
var texCoordBuffer = 0
var colorBuffer = 0
var transformBuffer = 0
var indexBuffer = 0
override fun init() {
particleBuffer = glGenBuffers()
colorBuffer = glGenBuffers()
texCoordBuffer = glGenBuffers()
transformBuffer = glGenBuffers()
indexBuffer = glGenBuffers()
vao = glGenVertexArrays()
val particleData = doubleArrayOf(
-0.5, -0.5, 0.0,
-0.5, 0.5, 0.0,
0.5, 0.5, 0.0,
0.5, -0.5, 0.0
)
val texCoordData = doubleArrayOf(
0.0, 1.0,
0.0, 0.0,
1.0, 0.0,
1.0, 1.0
)
val indexData = intArrayOf(0, 1, 3, 1, 2, 3)
glBindBuffer(GL_ARRAY_BUFFER, particleBuffer)
glBufferData(GL_ARRAY_BUFFER, particleData, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer)
glBufferData(GL_ARRAY_BUFFER, maxParticles * 4, GL_DYNAMIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer)
glBufferData(GL_ARRAY_BUFFER, texCoordData, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, transformBuffer)
glBufferData(GL_ARRAY_BUFFER, maxParticles * 16, GL_DYNAMIC_DRAW)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexData, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
glBindVertexArray(vao)
glEnableVertexAttribArray(0)
glBindBuffer(GL_ARRAY_BUFFER, particleBuffer)
glVertexAttribPointer(0, 3, GL_DOUBLE, false, 0, 0)
glVertexAttribDivisor(0, 0)
glEnableVertexAttribArray(1)
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer)
glVertexAttribPointer(1, 4, GL_DOUBLE, false, 0, 0)
glVertexAttribDivisor(1, 1)
glEnableVertexAttribArray(2)
glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer)
glVertexAttribPointer(2, 2, GL_DOUBLE, false, 0, 0)
glVertexAttribDivisor(2, 0)
glEnableVertexAttribArray(3)
glEnableVertexAttribArray(4)
glEnableVertexAttribArray(5)
glEnableVertexAttribArray(6)
glBindBuffer(GL_ARRAY_BUFFER, transformBuffer)
glVertexAttribPointer(3, 4, GL_DOUBLE, false, 128, 0)
glVertexAttribDivisor(3, 1)
glVertexAttribPointer(4, 4, GL_DOUBLE, false, 128, 32)
glVertexAttribDivisor(4, 1)
glVertexAttribPointer(5, 4, GL_DOUBLE, false, 128, 64)
glVertexAttribDivisor(5, 1)
glVertexAttribPointer(6, 4, GL_DOUBLE, false, 128, 96)
glVertexAttribDivisor(6, 1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer)
glBindVertexArray(0)
}
fun spawnParticle(world : IWorld) {
val particle = Particle(color, this)
val randomOffset = Vector2f((Math.random() - 0.5).toFloat() * Emitter.spread, (Math.random() - 0.5).toFloat() * Emitter.spread)
val particlePos = parent?.getComponent<Transform2D>()?.position!! + randomOffset
// TODO: Handle the case where a particle emitter has no parent entity (?)
val entity = EntityFactory.getEntity("Particle-${System.nanoTime()}")
.addComponent(Transform2D(position = particlePos, scale = Vector2f(Emitter.size, Emitter.size)))
.addComponent(particle)
.addComponent(RigidBody(mass = 10f))
// .addComponent(BoundingBox2D(Vector2f(), Vector2f(Emitter.size, Emitter.size) * 0.5f))// TODO: Remove; generalize
entity.getComponent<Transform2D>()!!.position = particlePos
world.addEntity(entity)
particles.add(particle)
}
companion object {
var size = 1f
var spread = 3f
}
} | mit | c2c4a42b43ab5e1c8ef1ac0af242a053 | 35.06 | 135 | 0.648484 | 4.205288 | false | false | false | false |
iZettle/wrench | wrench-app/src/main/java/com/izettle/wrench/dialogs/stringvalue/StringValueFragment.kt | 1 | 2646 | package com.izettle.wrench.dialogs.stringvalue
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.inputmethod.EditorInfo
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import com.izettle.wrench.R
import com.izettle.wrench.databinding.FragmentStringValueBinding
import org.koin.androidx.viewmodel.ext.android.viewModel
class StringValueFragment : DialogFragment() {
private lateinit var binding: FragmentStringValueBinding
private val viewModel: FragmentStringValueViewModel by viewModel()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
assert(arguments != null)
binding = FragmentStringValueBinding.inflate(LayoutInflater.from(context))
val args = StringValueFragmentArgs.fromBundle(arguments!!)
viewModel.init(args.configurationId, args.scopeId)
viewModel.configuration.observe(this, Observer { wrenchConfiguration ->
if (wrenchConfiguration != null) {
requireDialog().setTitle(wrenchConfiguration.key)
}
})
viewModel.selectedConfigurationValueLiveData.observe(this, Observer { wrenchConfigurationValue ->
viewModel.selectedConfigurationValue = wrenchConfigurationValue
if (wrenchConfigurationValue != null) {
binding.value.setText(wrenchConfigurationValue.value)
}
})
binding.value.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
viewModel.updateConfigurationValue(binding.value.text!!.toString())
dismiss()
}
false
}
return AlertDialog.Builder(requireActivity())
.setTitle(".")
.setView(binding.root)
.setPositiveButton(android.R.string.ok) { _, _ ->
viewModel.updateConfigurationValue(binding.value.text!!.toString())
dismiss()
}
.setNegativeButton(R.string.revert) { _, _ ->
if (viewModel.selectedConfigurationValue != null) {
viewModel.deleteConfigurationValue()
}
dismiss()
}
.create()
}
companion object {
fun newInstance(args: StringValueFragmentArgs): StringValueFragment {
val fragment = StringValueFragment()
fragment.arguments = args.toBundle()
return fragment
}
}
}
| mit | 183e95168580bef9f4b5fa93cb2ebc81 | 35.246575 | 105 | 0.640212 | 5.605932 | false | true | false | false |
facebook/litho | litho-core-kotlin/src/test/kotlin/com/facebook/litho/KBatchedStateUpdatesTest.kt | 1 | 14634 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho
import android.content.Context
import android.widget.TextView
import com.facebook.litho.core.height
import com.facebook.litho.core.width
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.testing.BackgroundLayoutLooperRule
import com.facebook.litho.testing.LithoViewRule
import com.facebook.litho.testing.assertj.LithoAssertions
import com.facebook.litho.testing.testrunner.LithoTestRunner
import com.facebook.litho.testing.viewtree.ViewPredicates.hasVisibleText
import com.facebook.litho.view.onClick
import com.facebook.litho.view.viewTag
import com.facebook.rendercore.MeasureResult
import java.util.concurrent.atomic.AtomicInteger
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.junit.runner.RunWith
import org.robolectric.annotation.LooperMode
import org.robolectric.shadows.ShadowLooper
/** Unit tests for [useState]. */
@LooperMode(LooperMode.Mode.LEGACY)
@RunWith(LithoTestRunner::class)
class KBatchedStateUpdatesTest {
@get:Rule val lithoViewRule = LithoViewRule()
@get:Rule val expectedException = ExpectedException.none()
@get:Rule
val backgroundLayoutLooperRule: BackgroundLayoutLooperRule = BackgroundLayoutLooperRule()
@Test
fun stateUpdates_numberOfRendersTriggeredCorrectly() {
val renderCount = AtomicInteger(0)
class TestComponent : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val counter = useState { 0 }
return Row(
style =
Style.height(100.dp).width(100.dp).viewTag("test_view").onClick {
// have to block the main looper while we are queueing updates to make
// sure that if any scheduling is posted to the main thread, it only
// happens after the work inside the onClick finishes.
withMainLooperPaused {
executeAndRunPendingBgTasks { counter.update { it + 1 } }
executeAndRunPendingBgTasks { counter.update { it + 1 } }
}
}) {
child(Text(text = "Counter: ${counter.value}"))
}
}
}
val testLithoView = lithoViewRule.render { TestComponent() }
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 0")
assertThat(renderCount.get()).isEqualTo(1)
lithoViewRule.act(testLithoView) { clickOnTag("test_view") }
backgroundLayoutLooperRule.runToEndOfTasksSync()
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 2")
/* initial render + render triggered by batched updates */
val expectedRenderCount = 2
assertThat(renderCount.get()).isEqualTo(expectedRenderCount)
}
/**
* In this test we:
* 1. Run two async updates (which are being batched when batching is enabled).
* 2. Run on sync update. This sync update will end up consuming the currently batched updates and
* trigger one layout calculation.
* 3. Then we start another batching with two async updates, which will trigger another layout
* calculation.
*
* The goal of this test is that the batching mechanism still works correctly, even when
* interrupted by another sync update.
*/
@Test
fun stateUpdates_concurrent_sync_update_consumes_pending_state_updates_and_batching_can_be_resumed() {
val renderCount = AtomicInteger(0)
class TestComponent : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val counter = useState { 0 }
return Row(
style =
Style.height(100.dp).width(100.dp).viewTag("test_view").onClick {
withMainLooperPaused {
executeAndRunPendingBgTasks { counter.update { it + 1 } }
executeAndRunPendingBgTasks { counter.update { it + 1 } }
/* this sync should consume all pending batched updates when batching is enabled */
executeAndRunPendingBgTasks { counter.updateSync { it + 1 } }
}
withMainLooperPaused {
executeAndRunPendingBgTasks { counter.update { it + 1 } }
executeAndRunPendingBgTasks { counter.update { it + 1 } }
}
}) {
child(Text(text = "Counter: ${counter.value}"))
}
}
}
val testLithoView = lithoViewRule.render { TestComponent() }
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 0")
assertThat(renderCount.get()).isEqualTo(1)
lithoViewRule.act(testLithoView) { clickOnTag("test_view") }
backgroundLayoutLooperRule.runToEndOfTasksSync()
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 5")
/* initial render + render triggered by sync update (which interrupts batching) + render triggered by async update */
val expectedCount = 3
assertThat(renderCount.get()).isEqualTo(expectedCount)
}
/**
* In this test we:
*
* 1. Execute two async updates (which are being batched when batching is enabled)
* 2. Execute one sync update. This sync update actually ends up on consuming the already enqueued
* updates.
* 3. In this scenario we only have one layout calculation (besides the initial one).
*
* This test guarantees that we don't do any extra layout calculation due to the batching.
*/
@Test
fun stateUpdates_concurrent_sync_update_consumes_all_updates_and_consumes_all_batched_updates() {
val renderCount = AtomicInteger(0)
class TestComponent : KComponent() {
override fun ComponentScope.render(): Component {
renderCount.incrementAndGet()
val counter = useState { 0 }
return Row(
style =
Style.height(100.dp).width(100.dp).viewTag("test_view").onClick {
withMainLooperPaused {
executeAndRunPendingBgTasks { counter.update { it + 1 } }
executeAndRunPendingBgTasks { counter.update { it + 1 } }
/* this sync should consume all pending batched updates when batching is enabled */
executeAndRunPendingBgTasks { counter.updateSync { it + 1 } }
}
}) {
child(Text(text = "Counter: ${counter.value}"))
}
}
}
val testLithoView = lithoViewRule.render { TestComponent() }
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 0")
assertThat(renderCount.get()).isEqualTo(1)
executeAndRunPendingBgTasks { lithoViewRule.act(testLithoView) { clickOnTag("test_view") } }
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 3")
/* initial render + render triggered by sync update */
val expectedCount = 2
assertThat(renderCount.get()).isEqualTo(expectedCount)
}
@Test
fun stateUpdates_numberOfRendersTriggeredCorrectly_forMountable() {
val renderCount = AtomicInteger(0)
class TestComponent : MountableComponent() {
override fun MountableComponentScope.render(): MountableRenderResult {
renderCount.incrementAndGet()
val counter = useState { 0 }
return MountableRenderResult(
TestTextMountable(text = "Counter: ${counter.value}"),
style =
Style.height(100.dp).width(100.dp).viewTag("test_view").onClick {
// have to block the main looper while we are queueing updates to make
// sure that if any scheduling is posted to the main thread, it only
// happens after the work inside the onClick finishes.
withMainLooperPaused {
executeAndRunPendingBgTasks { counter.update { it + 1 } }
executeAndRunPendingBgTasks { counter.update { it + 1 } }
}
})
}
}
val testLithoView = lithoViewRule.render { TestComponent() }
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 0")
assertThat(renderCount.get()).isEqualTo(1)
lithoViewRule.act(testLithoView) { clickOnTag("test_view") }
backgroundLayoutLooperRule.runToEndOfTasksSync()
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 2")
/* initial render + render triggered by batched updates */
val expectedRenderCount = 2
assertThat(renderCount.get()).isEqualTo(expectedRenderCount)
}
/**
* In this test we:
* 1. Run two async updates (which are being batched when batching is enabled).
* 2. Run on sync update. This sync update will end up consuming the currently batched updates and
* trigger one layout calculation.
* 3. Then we start another batching with two async updates, which will trigger another layout
* calculation.
*
* The goal of this test is that the batching mechanism still works correctly, even when
* interrupted by another sync update.
*/
@Test
fun stateUpdates_concurrent_sync_update_consumes_pending_state_updates_and_batching_can_be_resumed_forMountable() {
val renderCount = AtomicInteger(0)
class TestComponent : MountableComponent() {
override fun MountableComponentScope.render(): MountableRenderResult {
renderCount.incrementAndGet()
val counter = useState { 0 }
return MountableRenderResult(
TestTextMountable(text = "Counter: ${counter.value}"),
style =
Style.height(100.dp).width(100.dp).viewTag("test_view").onClick {
withMainLooperPaused {
executeAndRunPendingBgTasks { counter.update { it + 1 } }
executeAndRunPendingBgTasks { counter.update { it + 1 } }
/* this sync should consume all pending batched updates when batching is enabled */
executeAndRunPendingBgTasks { counter.updateSync { it + 1 } }
}
withMainLooperPaused {
executeAndRunPendingBgTasks { counter.update { it + 1 } }
executeAndRunPendingBgTasks { counter.update { it + 1 } }
}
})
}
}
val testLithoView = lithoViewRule.render { TestComponent() }
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 0")
assertThat(renderCount.get()).isEqualTo(1)
lithoViewRule.act(testLithoView) { clickOnTag("test_view") }
backgroundLayoutLooperRule.runToEndOfTasksSync()
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 5")
/* initial render + render triggered by sync update (which interrupts batching) + render triggered by async update */
val expectedCount = 3
assertThat(renderCount.get()).isEqualTo(expectedCount)
}
/**
* In this test we:
*
* 1. Execute two async updates (which are being batched when batching is enabled)
* 2. Execute one sync update. This sync update actually ends up on consuming the already enqueued
* updates.
* 3. In this scenario we only have one layout calculation (besides the initial one).
*
* This test guarantees that we don't do any extra layout calculation due to the batching.
*/
@Test
fun stateUpdates_concurrent_sync_update_consumes_all_updates_and_consumes_all_batched_updates_forMountable() {
val renderCount = AtomicInteger(0)
class TestComponent : MountableComponent() {
override fun MountableComponentScope.render(): MountableRenderResult {
renderCount.incrementAndGet()
val counter = useState { 0 }
return MountableRenderResult(
TestTextMountable(text = "Counter: ${counter.value}"),
style =
Style.height(100.dp).width(100.dp).viewTag("test_view").onClick {
withMainLooperPaused {
executeAndRunPendingBgTasks { counter.update { it + 1 } }
executeAndRunPendingBgTasks { counter.update { it + 1 } }
/* this sync should consume all pending batched updates when batching is enabled */
executeAndRunPendingBgTasks { counter.updateSync { it + 1 } }
}
})
}
}
val testLithoView = lithoViewRule.render { TestComponent() }
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 0")
assertThat(renderCount.get()).isEqualTo(1)
executeAndRunPendingBgTasks { lithoViewRule.act(testLithoView) { clickOnTag("test_view") } }
LithoAssertions.assertThat(testLithoView).hasVisibleText("Counter: 3")
/* initial render + render triggered by sync update */
val expectedCount = 2
assertThat(renderCount.get()).isEqualTo(expectedCount)
}
private fun withMainLooperPaused(body: () -> Unit) {
ShadowLooper.pauseMainLooper()
body()
ShadowLooper.unPauseMainLooper()
}
private fun executeAndRunPendingBgTasks(body: () -> Unit) {
body()
backgroundLayoutLooperRule.runToEndOfTasksSync()
}
}
internal class TestTextMountable(private val text: String, private val tag: String? = null) :
SimpleMountable<TextView>(RenderType.VIEW) {
override fun createContent(context: Context): TextView = TextView(context)
override fun MeasureScope.measure(widthSpec: Int, heightSpec: Int): MeasureResult =
MeasureResult(100, 100)
override fun mount(c: Context, content: TextView, layoutData: Any?) {
content.setText(text)
content.tag = tag
content.contentDescription = tag
}
override fun unmount(c: Context, content: TextView, layoutData: Any?) {
content.setText("")
content.tag = null
}
override fun shouldUpdate(
newMountable: SimpleMountable<TextView>,
currentLayoutData: Any?,
nextLayoutData: Any?
): Boolean {
newMountable as TestTextMountable
return text != newMountable.text || tag != newMountable.tag
}
}
| apache-2.0 | 2f6a77308cf8f5ddf1df00cab501e174 | 37.612137 | 121 | 0.671655 | 4.614948 | false | true | false | false |
DadosAbertosBrasil/android-radar-politico | app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/miscellaneous/connection/parsers/CDXmlParser.kt | 1 | 15134 | package br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.connection.parsers
import android.util.Log
import br.edu.ifce.engcomp.francis.radarpolitico.models.*
import org.apache.commons.lang3.StringUtils
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
/**
* Created by francisco on 27/04/16.
*/
object CDXmlParser {
fun parseDeputadoFromXML(xmlInputStream: InputStream): Deputado {
val xmlPullParserFactory = XmlPullParserFactory.newInstance()
val parser = xmlPullParserFactory.newPullParser()
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(xmlInputStream, null)
var event = parser.eventType
var tagAtual: String? = null
val deputados = ArrayList<Deputado>()
var deputado: Deputado? = null
while (event != XmlPullParser.END_DOCUMENT) {
when (event) {
XmlPullParser.START_TAG -> {
tagAtual = parser.name
if (tagAtual.equals("deputado", ignoreCase = true)) {
deputado = Deputado()
}
}
XmlPullParser.TEXT -> if (!parser.text.contains("\n") && deputado != null) {
when (tagAtual) {
"email" -> deputado.email = parser.text
"ufRepresentacaoAtual" -> deputado.uf = parser.text
"sigla" -> deputado.partido = parser.text
"nomeParlamentarAtual" -> deputado.nomeParlamentar = parser.text
"ideCadastro" -> deputado.idCadastro = parser.text
"numLegislatura" -> deputado.numeroLegislatura = parser.text.toInt()
}
}
XmlPullParser.END_TAG -> {
tagAtual = parser.name
if (tagAtual == "Deputado") {
if (deputado != null) {
deputados.add(deputado)
deputado = null
}
}
}
}
event = parser.next()
}
deputados.sortByDescending { it.numeroLegislatura }
return deputados.first()
}
fun parseDeputadosFromXML(xmlInputStream: InputStream): ArrayList<Deputado> {
val xmlPullParserFactory = XmlPullParserFactory.newInstance()
val parser = xmlPullParserFactory.newPullParser()
val deputados = ArrayList<Deputado>()
var event: Int = 0
var tagAtual: String? = null
var deputado: Deputado? = null
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(xmlInputStream, null)
event = parser.eventType
while(event != XmlPullParser.END_DOCUMENT) {
when (event) {
XmlPullParser.START_TAG -> {
tagAtual = parser.name
if(tagAtual.equals("deputado", ignoreCase = true)) {
deputado = Deputado()
}
}
XmlPullParser.TEXT -> {
if (!parser.text.contains("\n") && deputado != null) {
when (tagAtual) {
"ideCadastro" -> deputado.idCadastro = parser.text
"condicao" -> deputado.condicao = parser.text
"matricula" -> deputado.matricula = parser.text
"idParlamentar" -> deputado.idParlamentar = parser.text
"nome" -> deputado.nome = parser.text
"nomeParlamentar" -> deputado.nomeParlamentar = parser.text
"urlFoto" -> deputado.urlFoto = parser.text
"uf" -> deputado.uf = parser.text
"partido" -> deputado.partido = parser.text
"gabinete" -> deputado.gabinete = parser.text
"anexo" -> deputado.anexo = parser.text
"fone" -> deputado.fone = parser.text
"email" -> deputado.email = parser.text
}
}
}
XmlPullParser.END_TAG -> {
tagAtual = parser.name
if (tagAtual.equals("deputado", ignoreCase = true) && deputado != null) {
deputados.add(deputado)
deputado = null
}
}
}
event = parser.next()
}
return deputados
}
fun parseFrequenciaFromXML(xmlInputStream: InputStream): ArrayList<Dia> {
val xmlPullParserFactory = XmlPullParserFactory.newInstance()
val parser = xmlPullParserFactory.newPullParser()
val dias = ArrayList<Dia>()
var event: Int = 0
var tagAtual: String? = null
var dia: Dia? = null
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(xmlInputStream, null)
event = parser.eventType
while (event != XmlPullParser.END_DOCUMENT) {
when(event) {
XmlPullParser.START_TAG -> {
tagAtual = parser.name
if(tagAtual.equals("dia", ignoreCase = true)) {
dia = Dia()
}
}
XmlPullParser.TEXT -> {
if (!parser.text.contains("\n") && dia != null) {
when(tagAtual) {
"data" -> dia.data = parser.text
"frequencianoDia" -> dia.frequencia = parser.text
}
}
}
XmlPullParser.END_TAG -> {
tagAtual = parser.name
if (tagAtual.equals("dia", ignoreCase = true) && dia != null) {
dias.add(dia)
dia = null
}
}
}
event = parser.next()
}
return dias
}
fun parseProposicaoFromXML(xmlInputStream: InputStream): Proposicao {
val xmlPullParserFactory = XmlPullParserFactory.newInstance()
val parser = xmlPullParserFactory.newPullParser()
var proposicao = Proposicao()
var event: Int = 0
var tagAtual: String? = null
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(xmlInputStream, null)
event = parser.eventType
while(event != XmlPullParser.END_DOCUMENT) {
when (event) {
XmlPullParser.START_TAG -> {
tagAtual = parser.name
if (tagAtual.equals("proposicao", ignoreCase = true) && proposicao.sigla!!.isEmpty()) {
proposicao.sigla = parser.getAttributeValue(null, "tipo")?.replace("\\s+".toRegex(), "")
proposicao.numero = parser.getAttributeValue(null, "numero")?.replace("\\s+".toRegex(), "")
proposicao.ano = parser.getAttributeValue(null, "ano")?.replace("\\s+".toRegex(), "")
}
}
XmlPullParser.TEXT -> {
if (!parser.text.contains("\n")) {
when (tagAtual) {
"nomeProposicao" -> proposicao.nome = parser.text
"idProposicao" -> proposicao.id = parser.text
"tipoProposicao" -> proposicao.tipoProposicao = parser.text
"tema" -> proposicao.tema = parser.text
"Ementa" -> proposicao.ementa = parser.text
"Autor" -> proposicao.nomeAutor = parser.text
"ideCadastro" -> proposicao.idAutor = parser.text
"RegimeTramitacao" -> proposicao.regimeTramitacao = parser.text
"Situacao" -> proposicao.situacao = parser.text
"LinkInteiroTeor" -> proposicao.urlInteiroTeor = parser.text
}
}
}
}
event = parser.next()
}
return proposicao
}
fun parseProposicoesFromXML(xmlInputStream: InputStream): ArrayList<Proposicao> {
val xmlPullParserFactory = XmlPullParserFactory.newInstance()
val parser = xmlPullParserFactory.newPullParser()
val proposicoes = ArrayList<Proposicao>()
val formatter = SimpleDateFormat("dd/MM/yyyy")
var proposicao:Proposicao? = null
var event: Int = 0
var tagAtual: String? = null
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(xmlInputStream, null)
event = parser.eventType
while(event != XmlPullParser.END_DOCUMENT) {
when(event) {
XmlPullParser.START_TAG -> {
tagAtual = parser.name
if (tagAtual.equals("proposicao", ignoreCase = true)) {
proposicao = Proposicao()
}
}
XmlPullParser.TEXT -> {
if (!parser.text.contains("\n")) {
when (tagAtual) {
"codProposicao" -> {
proposicao?.id = parser.text
}
"dataVotacao" -> {
proposicao?.dataVotacao = formatter.parse(parser.text)
}
}
}
}
XmlPullParser.END_TAG -> {
tagAtual = parser.name
if (tagAtual.equals("proposicao", ignoreCase = true) && proposicao != null) {
proposicoes.add(proposicao)
proposicao = null
}
}
}
event = parser.next()
}
return proposicoes
}
fun parseVotacaoFromXML(xmlInputStream: InputStream): Votacao {
val xmlPullParserFactory = XmlPullParserFactory.newInstance()
val parser = xmlPullParserFactory.newPullParser()
val votacoes = ArrayList<Votacao>()
var votacao:Votacao? = null
var voto:Voto? = null
var event: Int = 0
var tagAtual: String? = null
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(xmlInputStream, null)
event = parser.eventType
while(event != XmlPullParser.END_DOCUMENT){
when(event){
XmlPullParser.START_TAG -> {
tagAtual = parser.name
if (tagAtual.equals("votacao", ignoreCase = true)) {
val resumo = parser.getAttributeValue(null, "Resumo")
val simPattern = Pattern.compile("[Ss]im:\\s?([0-9]*);")
val naoPattern = Pattern.compile("[Nn]ão:\\s?([0-9]*);")
val abstencoesPattern = Pattern.compile("[Aa]bstenção:\\s?([0-9]*);")
val abstencaoPattern = Pattern.compile("[Aa]bstenções:\\s?([0-9]*);")
val totalPattern = Pattern.compile("[Tt]otal:\\s?([0-9]*);?.?")
val simMatcher = simPattern.matcher(resumo)
val naoMatcher = naoPattern.matcher(resumo)
val abstencaoMatcher = abstencaoPattern.matcher(resumo)
val abstencoesMatcher = abstencoesPattern.matcher(resumo)
val totalMatcher = totalPattern.matcher(resumo)
var simVotos = "0"
var naoVotos = "0"
var abstencaoVotos = "0"
var totalVotos = "0"
while(simMatcher.find()){
simVotos = simMatcher.group(1)
}
while(naoMatcher.find()){
naoVotos = naoMatcher.group(1)
}
while(abstencaoMatcher.find()){
abstencaoVotos = abstencaoMatcher.group(1)
}
while(abstencoesMatcher.find()){
abstencaoVotos = abstencoesMatcher.group(1)
}
while(totalMatcher.find()){
totalVotos = totalMatcher.group(1)
}
votacao = Votacao()
votacao.resumo = resumo
votacao.totalVotosSim = simVotos
votacao.totalVotosNao = naoVotos
votacao.totalVotosAbstencao = abstencaoVotos
votacao.totalVotosSessao = totalVotos
votacao.data = parser.getAttributeValue(null, "Data")?.replace("\\s".toRegex(), "")
votacao.hora = parser.getAttributeValue(null, "Hora")?.replace("\\s".toRegex(), "")
votacao.objetoVotacao = parser.getAttributeValue(null, "ObjVotacao")?.replace("\\s".toRegex(), "")
votacao.codigoSessao = parser.getAttributeValue(null, "codSessao")?.replace("\\s".toRegex(), "")
}
else if (tagAtual.equals("deputado", ignoreCase = true)) {
voto = Voto()
voto.nome = parser.getAttributeValue(null, "Nome")?.replace("\\s".toRegex(), "")
voto.idCadastro = parser.getAttributeValue(null, "ideCadastro")?.replace("\\s".toRegex(), "")
voto.partido = parser.getAttributeValue(null, "Partido")?.replace("\\s".toRegex(), "")
voto.uf = parser.getAttributeValue(null, "UF")?.replace("\\s".toRegex(), "")
voto.voto = parser.getAttributeValue(null, "Voto")?.replace("\\s".toRegex(), "")
}
}
XmlPullParser.END_TAG -> {
tagAtual = parser.name
if(tagAtual.equals("votacao", ignoreCase = true)){
votacoes.add(votacao!!)
votacao = null
}
else if (votacao != null && tagAtual.equals("deputado", true)){
votacao.votos.add(voto!!)
voto = null
}
}
}
event = parser.next()
}
return votacoes.last()
}
} | gpl-2.0 | 423fbedaa48a107a869e1a9acf28c213 | 33.861751 | 122 | 0.48483 | 4.72929 | false | false | false | false |
lskycity/AndroidTools | app/src/main/java/com/lskycity/androidtools/ui/PublishInformActivity.kt | 1 | 1916 | package com.lskycity.androidtools.ui
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import android.widget.Toast
import com.lskycity.androidtools.InformCheck
import com.lskycity.androidtools.R
import com.lskycity.androidtools.app.BaseActivity
/**
* Created by zhaofliu on 2/5/17.
*
*/
class PublishInformActivity : BaseActivity() {
private lateinit var informReceiver: PublishInformActivity.InformReceiver;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_inform)
updateContent()
val filter = IntentFilter(InformCheck.ACTION_INFORM_CHANGED)
informReceiver = InformReceiver();
registerReceiver(informReceiver, filter)
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(informReceiver)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.refresh, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.refresh) {
Toast.makeText(this, R.string.refreshing, Toast.LENGTH_LONG).show()
InformCheck.checkInform()
return true
}
return super.onOptionsItemSelected(item)
}
private fun updateContent() {
val inform = InformCheck.getInformFromSharedPreference(this)
val content = findViewById<TextView>(R.id.content)
content.text = inform.content
}
internal inner class InformReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) = updateContent();
}
}
| apache-2.0 | b7fdf2995117e9d7af830ffacc4bea23 | 28.030303 | 83 | 0.716597 | 4.551069 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/language/completion/util/MdReferenceDefinitionContext.kt | 1 | 794 | // 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.language.completion.util
data class MdReferenceDefinitionContext(val id: String) {
var isFirstInsert = true
private var referenceIdMap: HashMap<String, String>? = null
operator fun get(id: String): String {
return referenceIdMap?.get(id) ?: id
}
operator fun set(id: String, mappedId: String) {
if (id == mappedId) return
var referenceIdMap = referenceIdMap
if (referenceIdMap == null) {
referenceIdMap = HashMap()
this.referenceIdMap = referenceIdMap
}
referenceIdMap[id] = mappedId
}
}
| apache-2.0 | 35581587eaddc6dd8f3e8aa94836d2be | 33.521739 | 177 | 0.673804 | 4.245989 | false | false | false | false |
jtlalka/fiszki | app/src/main/kotlin/net/tlalka/fiszki/view/fragments/LanguageDialogFragment.kt | 1 | 1831 | package net.tlalka.fiszki.view.fragments
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.app.DialogFragment
import android.content.DialogInterface
import android.os.Bundle
import net.tlalka.fiszki.R
import net.tlalka.fiszki.model.dto.parcel.LanguagesDto
import net.tlalka.fiszki.model.types.LanguageType
import net.tlalka.fiszki.view.adapters.LanguageAdapter
class LanguageDialogFragment : DialogFragment() {
private var listener: DialogListener? = null
private var languagesDto: LanguagesDto? = null
interface DialogListener {
fun onLanguageSelected(languageType: LanguageType)
}
private inner class LanguageListener : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
listener?.onLanguageSelected(languagesDto!!.languages[which])
}
}
override fun onAttach(activity: Activity) {
super.onAttach(activity)
listener = activity as DialogListener
}
override fun onCreateDialog(bundle: Bundle): Dialog {
languagesDto = arguments.getParcelable(LanguagesDto::class.java.name)
return AlertDialog.Builder(activity)
.setIcon(R.drawable.language_icon)
.setTitle(R.string.language_dialog_title)
.setAdapter(LanguageAdapter(activity, languagesDto!!.languages), LanguageListener())
.create()
}
companion object {
fun getInstance(languageTypes: List<LanguageType>): LanguageDialogFragment {
val bundle = Bundle()
bundle.putParcelable(LanguagesDto::class.java.name, LanguagesDto(languageTypes))
val fragment = LanguageDialogFragment()
fragment.arguments = bundle
return fragment
}
}
}
| mit | d03f895f561856d97e7b98401533c944 | 32.907407 | 100 | 0.706171 | 4.856764 | false | false | false | false |
http4k/http4k | http4k-incubator/src/main/kotlin/org/http4k/events/HttpTracer.kt | 1 | 1683 | package org.http4k.events
import org.http4k.core.Method
import org.http4k.core.Status
import org.http4k.core.Uri
import org.http4k.filter.ZipkinTraces
/**
* Traces HTTP call stacks for standard HttpEvents.
* The important thing here is to supply the way of getting the
* outbound host (or service) name out of the parent and child metadata events
* - we can do this with an EventFilter.
*/
fun HttpTracer(
childHostName: (MetadataEvent) -> String,
parentHostName: (MetadataEvent) -> String = { (it.event as HttpEvent.Outgoing).uri.host },
) = object : Tracer<HttpTraceTree> {
override operator fun invoke(
parent: MetadataEvent,
rest: List<MetadataEvent>,
tracer: Tracer<TraceTree>
) = parent.takeIf { it.event is HttpEvent.Outgoing }
?.let { listOf(it.toTraceTree(rest - it, tracer)) } ?: emptyList()
private fun MetadataEvent.toTraceTree(rest: List<MetadataEvent>, tracer: Tracer<TraceTree>): HttpTraceTree {
val parentEvent = event as HttpEvent.Outgoing
return HttpTraceTree(
childHostName(this),
parentEvent.uri.path("/" + parentEvent.xUriTemplate), parentEvent.method, parentEvent.status,
rest
.filter { traces().spanId == it.traces().parentSpanId }
.filter { parentHostName(this) == childHostName(it) }
.flatMap { tracer(it, rest - it, tracer) })
}
private fun MetadataEvent.traces() = (metadata["traces"] as ZipkinTraces)
}
data class HttpTraceTree(
override val origin: String,
val uri: Uri,
val method: Method,
val status: Status,
override val children: List<TraceTree>
) : TraceTree
| apache-2.0 | d551aa00c2e51014d7e2fa8c5269115f | 36.4 | 112 | 0.675579 | 3.988152 | false | false | false | false |
orbit/orbit | src/orbit-client/src/test/kotlin/orbit/client/LoopTest.kt | 1 | 1089 | /*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.client
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import mu.KotlinLogging
import orbit.client.actor.GreeterActor
import orbit.client.actor.createProxy
fun main() {
val logger = KotlinLogging.logger { }
val targetUri = "orbit://localhost:50056/test"
val namespace = "test"
val client = OrbitClient(
OrbitClientConfig(
grpcEndpoint = targetUri,
namespace = namespace,
packages = listOf("orbit.client.actor")
)
)
runBlocking {
client.start().join()
val greeter = client.actorFactory.createProxy<GreeterActor>()
do {
try {
val result = greeter.greetAsync("Joe").await()
logger.info { result }
} catch (e: Throwable) {
logger.error { e }
}
delay(10000)
} while (true)
}
} | bsd-3-clause | 5b3a89c25f1ee41af2858bfa8d4cb81d | 25.585366 | 69 | 0.604224 | 4.373494 | false | false | false | false |
codestation/henkaku-android | app/src/main/java/com/codestation/henkakuserver/MainActivity.kt | 1 | 5404 | /*
* Copyright 2018 codestation. All Rights Reserved.
*
* 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.codestation.henkakuserver
import android.Manifest
import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.WifiManager
import android.os.Bundle
import android.support.annotation.RequiresPermission
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException
class MainActivity : AppCompatActivity() {
// INSTANCE OF ANDROID WEB SERVER
private var henkakuServer: HenkakuServer = HenkakuServer(this, BuildConfig.defaultPort)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
versionText.text = BuildConfig.VERSION_NAME
textViewIpAccess.text = getString(R.string.enable_access_point)
floatingActionButtonOnOff.setOnClickListener {
updateServerStatus()
}
// INIT BROADCAST RECEIVER TO LISTEN NETWORK STATE CHANGED
initBroadcastReceiverNetworkStateChanged()
}
private fun updateServerStatus() {
if (isApOnline()) {
if (!isStarted && startAndroidWebServer()) {
isStarted = true
textViewIpAccess.text = getString(R.string.default_host, BuildConfig.defaultAddress, BuildConfig.defaultPort)
textViewMessage.visibility = View.VISIBLE
floatingActionButtonOnOff.backgroundTintList = ContextCompat.getColorStateList(this@MainActivity, R.color.colorGreen)
} else if (stopAndroidWebServer()) {
isStarted = false
textViewMessage.visibility = View.INVISIBLE
textViewIpAccess.text = getString(R.string.enable_access_point)
floatingActionButtonOnOff.backgroundTintList = ContextCompat.getColorStateList(this@MainActivity, R.color.colorRed)
}
} else {
Snackbar.make(coordinatorLayout, getString(R.string.wifi_message), Snackbar.LENGTH_LONG).show()
}
}
//region Start And Stop AndroidWebServer
private fun startAndroidWebServer(): Boolean {
if (!isStarted) {
try {
henkakuServer.start()
return true
} catch (e: IOException) {
e.printStackTrace()
Snackbar.make(coordinatorLayout, "Cannot start HenkakuServer listening on port ${BuildConfig.defaultPort}", Snackbar.LENGTH_LONG).show()
}
}
return false
}
private fun stopAndroidWebServer(): Boolean {
if (isStarted) {
henkakuServer.stop()
return true
}
return false
}
//endregion
private fun initBroadcastReceiverNetworkStateChanged() {
val filters = IntentFilter()
filters.addAction("android.net.wifi.WIFI_STATE_CHANGED")
filters.addAction("android.net.wifi.STATE_CHANGE")
filters.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED")
val broadcastReceiverNetworkState = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
updateServerStatus()
}
}
super.registerReceiver(broadcastReceiverNetworkState, filters)
}
@RequiresPermission(value = Manifest.permission.ACCESS_NETWORK_STATE)
private fun isApOnline(): Boolean {
val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val method = wifiManager.javaClass.getDeclaredMethod("isWifiApEnabled")
method.isAccessible = true
return method.invoke(wifiManager) as Boolean
}
//endregion
override fun onKeyDown(keyCode: Int, evt: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (isStarted) {
AlertDialog.Builder(this)
.setTitle(R.string.warning)
.setMessage(R.string.dialog_exit_message)
.setPositiveButton(resources.getString(android.R.string.ok)) { _, _ -> finish() }
.setNegativeButton(resources.getString(android.R.string.cancel), null)
.show()
} else {
finish()
}
return true
}
return false
}
override fun onDestroy() {
super.onDestroy()
stopAndroidWebServer()
isStarted = false
}
companion object {
private var isStarted = false
}
}
| apache-2.0 | 887cbf3890ec87ea9ef05338ca5b46be | 34.788079 | 152 | 0.662842 | 4.980645 | false | false | false | false |
http4k/http4k | http4k-multipart/src/test/kotlin/org/http4k/multipart/CircularBufferedInputStreamTest.kt | 1 | 5594 | package org.http4k.multipart
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.containsSubstring
import com.natpryce.hamkrest.equalTo
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.fail
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.nio.InvalidMarkException
class CircularBufferedInputStreamTest {
@Test
fun returns_a_byte_at_a_time() {
val bytes = "hello my name is Tiest".toByteArray()
val inputStream = createInputStream(bytes, 3)
for (b in bytes) {
val read = inputStream.read()
assertThat(read, equalTo(b.toInt()))
}
assertThat(inputStream.read(), equalTo(-1))
}
@Test
fun returns_bytes() {
val bytes = "hello my name is Tiest".toByteArray()
val inputStream = createInputStream(bytes, 3)
var buffer = ByteArray(2)
var read = inputStream.read(buffer, 0, 2)
assertThat(read, equalTo(2))
assertThat(buffer[0].toInt().toChar(), equalTo('h'))
assertThat(buffer[1].toInt().toChar(), equalTo('e'))
buffer = ByteArray(5)
read = inputStream.read(buffer, 0, 5)
assertThat(read, equalTo(5))
assertThat(buffer[0].toInt().toChar(), equalTo('l'))
assertThat(buffer[1].toInt().toChar(), equalTo('l'))
assertThat(buffer[2].toInt().toChar(), equalTo('o'))
assertThat(buffer[3].toInt().toChar(), equalTo(' '))
assertThat(buffer[4].toInt().toChar(), equalTo('m'))
buffer = ByteArray(50)
read = inputStream.read(buffer, 10, 40)
assertThat(read, equalTo(15))
assertThat(buffer[10].toInt().toChar(), equalTo('y'))
assertThat(buffer[24].toInt().toChar(), equalTo('t'))
read = inputStream.read(buffer, 10, 40)
assertThat(read, equalTo(-1))
}
@Test
fun cannot_mark_further_then_buffer_size() {
val bytes = "hello my name is Tiest".toByteArray()
val inputStream = createInputStream(bytes, 3)
try {
inputStream.mark(5)
fail("can't have readlimit larger than buffer")
} catch (e: ArrayIndexOutOfBoundsException) {
assertThat(e.localizedMessage, containsSubstring("Readlimit (5) cannot be bigger than buffer size (4)"))
}
}
@Test
fun marks_and_resets() {
val bytes = "My name is Tiest don't you know".toByteArray()
val inputStream = createInputStream(bytes, 7)
inputStream.read() // M
inputStream.read() // y
inputStream.read() // ' '
inputStream.mark(8)
val marked = inputStream.read() // n
inputStream.read() // a
inputStream.read() // m
inputStream.read() // e
inputStream.reset()
val secondMark = inputStream.read() // n
assertThat(secondMark.toChar(), equalTo(marked.toChar()))
inputStream.read() // a
inputStream.read() // m
inputStream.read() // e
inputStream.reset()
assertThat(inputStream.read().toChar(), equalTo(secondMark.toChar()))
inputStream.read() // a
inputStream.read() // m
inputStream.read() // e
inputStream.read() // ' '
inputStream.read() // i
inputStream.read() // s
inputStream.mark(8)
val thirdMark = inputStream.read() // ' '
inputStream.read() // T
inputStream.read() // i
inputStream.read() // e
inputStream.reset()
assertThat(inputStream.read().toChar(), equalTo(thirdMark.toChar()))
}
@Test
fun resetting_after_reading_past_readlimit_fails() {
val bytes = "My name is Tiest don't you know".toByteArray()
val inputStream = createInputStream(bytes, 7)
inputStream.read() // M
inputStream.read() // y
inputStream.read() // ' '
inputStream.mark(2)
inputStream.read() // n
inputStream.read() // a
inputStream.read() // m
inputStream.read() // e
inputStream.read() //
inputStream.read() // i - reads new values into buffer, reseting the leftBound/mark
try {
inputStream.reset()
fail("Have read past readlimit, should fail")
} catch (e: InvalidMarkException) {
assertThat(e.message, equalTo(null))
}
}
@Test
fun resetting_after_reading_past_readlimit_fails_2() {
val bytes = "My name is Tiest don't you know".toByteArray()
val inputStream = createInputStream(bytes, 7)
inputStream.read() // M
inputStream.read() // y
inputStream.read() // ' '
inputStream.read() // n
inputStream.read() // a
inputStream.read() // m
inputStream.mark(2)
val marked = inputStream.read() // e - reads new values into buffer, reseting the leftBound/mark
inputStream.read() // ' '
inputStream.reset()
assertThat(inputStream.read().toChar(), equalTo(marked.toChar()))
inputStream.read() // ' '
inputStream.read() // i
inputStream.read() // s
try {
inputStream.reset()
fail("Have read past readlimit, should fail")
} catch (e: InvalidMarkException) {
assertThat(e.message, equalTo(null))
}
}
private fun createInputStream(bytes: ByteArray, bufSize: Int): InputStream = CircularBufferedInputStream(ByteArrayInputStream(bytes), bufSize)
// return new BufferedInputStream(new ByteArrayInputStream(bytes), bufSize);
}
| apache-2.0 | d4cfab883cdf266efcb4e620e3fbbdd5 | 30.784091 | 146 | 0.598856 | 4.394344 | false | false | false | false |
alashow/music-android | modules/base/src/main/java/tm/alashow/base/util/QueryHighlighter.kt | 1 | 3201 | /*
* Copyright (C) 2020, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.base.util
import android.graphics.Typeface
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.CharacterStyle
import android.text.style.StyleSpan
import android.widget.TextView
import java.text.Normalizer
import java.util.*
import java.util.regex.Pattern
/**
* From https://cyrilmottier.com/2017/03/06/highlighting-search-terms/
*/
class QueryHighlighter(
private var highlightStyle: CharacterStyle = StyleSpan(Typeface.BOLD),
private val queryNormalizer: QueryNormalizer = QueryNormalizer.FOR_SEARCH,
private val mode: Mode = Mode.CHARACTERS
) {
enum class Mode { CHARACTERS, WORDS }
class QueryNormalizer(private val normalizer: (source: CharSequence) -> CharSequence = { s -> s }) {
operator fun invoke(source: CharSequence) = normalizer(source)
companion object {
val NONE: QueryNormalizer = QueryNormalizer()
val CASE: QueryNormalizer = QueryNormalizer { source ->
if (TextUtils.isEmpty(source)) {
source
} else source.toString().uppercase()
}
private val PATTERN_DIACRITICS = Pattern.compile("\\p{InCombiningDiacriticalMarks}+")
private val PATTERN_NON_LETTER_DIGIT_TO_SPACES = Pattern.compile("[^\\p{L}\\p{Nd}]")
val FOR_SEARCH: QueryNormalizer = QueryNormalizer { searchTerm ->
var result = Normalizer.normalize(searchTerm, Normalizer.Form.NFD)
result = PATTERN_DIACRITICS.matcher(result).replaceAll("")
result = PATTERN_NON_LETTER_DIGIT_TO_SPACES.matcher(result).replaceAll(" ")
result.lowercase()
}
}
}
fun apply(text: CharSequence, wordPrefix: CharSequence): CharSequence {
val normalizedText = queryNormalizer(text)
val normalizedWordPrefix = queryNormalizer(wordPrefix)
val index = indexOfQuery(normalizedText, normalizedWordPrefix)
return if (index != -1) {
SpannableString(text).apply {
setSpan(highlightStyle, index, index + normalizedWordPrefix.length, 0)
}
} else text
}
fun apply(view: TextView, text: CharSequence, query: CharSequence) {
view.text = apply(text, query)
}
private fun indexOfQuery(text: CharSequence?, query: CharSequence?): Int {
if (query == null || text == null) {
return -1
}
val textLength = text.length
val queryLength = query.length
if (queryLength == 0 || textLength < queryLength) {
return -1
}
for (i in 0..textLength - queryLength) {
// Only match word prefixes
if (mode == Mode.WORDS && i > 0 && text[i - 1] != ' ') {
continue
}
var j = 0
while (j < queryLength) {
if (text[i + j] != query[j]) {
break
}
j++
}
if (j == queryLength) {
return i
}
}
return -1
}
}
| apache-2.0 | c97b18a7936c88ddcd7a4044d63b57db | 33.419355 | 104 | 0.593565 | 4.527581 | false | false | false | false |
Retronic/life-in-space | core/src/main/kotlin/com/retronicgames/utils/RecyclableArray.kt | 1 | 1329 | /**
* Copyright (C) 2015 Oleg Dolya
* Copyright (C) 2015 Eduardo Garcia
*
* This file is part of Life in Space, by Retronic Games
*
* Life in Space 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.
*
* Life in Space 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 Life in Space. If not, see <http://www.gnu.org/licenses/>.
*/
package com.retronicgames.utils
import com.badlogic.gdx.utils.Disposable
import com.badlogic.gdx.utils.Pool
class RecyclableArray<T>(private val pool: Pool<T>, size: Int) : Iterable<T>, Disposable {
private val array = com.badlogic.gdx.utils.Array<T>(size)
val size:Int
get() = array.size
override fun iterator() = array.iterator()
override fun dispose() {
pool.freeAll(array)
}
operator fun get(index: Int) = array.get(index)
fun add(value: T) = array.add(value)
override fun toString() = "[${array.toString(", ")}]"
} | gpl-3.0 | 25cde4ff95a0fe01986b4ceef66e3fee | 30.666667 | 90 | 0.722348 | 3.621253 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/data/handler/DataHandler.kt | 1 | 6294 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.data.handler
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.util.Log
import co.timetableapp.data.TimetableDbHelper
import co.timetableapp.data.query.Query
import co.timetableapp.data.schema.SqliteSeqSchema
import co.timetableapp.model.BaseItem
import java.util.*
/**
* The base data handler class.
*
* It provides implementations of database-related functions using a generic type (specifically, a
* subclass of [BaseItem]). Since the table to read from, column names, and the method of adding
* data from the data model class to the database table vary between the different types, subclasses
* of this base handler must provide definitions to some fields and methods.
*
* Furthermore, some of the functions can be overridden to incorporate additional functionality when
* performing a common task - for example, some subclasses may want to add a notification alarm
* after the item has been added to the database.
*/
abstract class DataHandler<T : BaseItem>(val context: Context) {
companion object {
private const val LOG_TAG = "DataHandler"
}
/**
* The name of the database table for reading/writing data.
* It is used in almost every function from this base class.
*/
abstract val tableName: String
/**
* The column name of the column storing the integer identifiers in the table.
*/
abstract val itemIdCol: String
/**
* Constructs the data model type using column values from the cursor provided.
*
* @see addItem
* @see createFromId
*/
abstract fun createFromCursor(cursor: Cursor): T
/**
* Constructs the data model type using its integer identifier.
*
* @throws DataNotFoundException if the item cannot be found in the database
*
* @see createFromCursor
*/
@Throws(DataNotFoundException::class)
abstract fun createFromId(id: Int): T
/**
* Puts properties of the data model type into [ContentValues] and returns this.
*
* @see addItem
*/
abstract fun propertiesAsContentValues(item: T): ContentValues
/**
* @param query the condition for selecting data items from the table. If this is null, all
* data items will be selected.
* @return a list of the selected data items of type [T]
*/
@JvmOverloads
fun getAllItems(query: Query? = null): ArrayList<T> {
val items = ArrayList<T>()
val dbHelper = TimetableDbHelper.getInstance(context)
val cursor = dbHelper.readableDatabase.query(
tableName,
null,
query?.filter?.sqlStatement,
null, null, null, null)
cursor.moveToFirst()
while (!cursor.isAfterLast) {
items.add(createFromCursor(cursor))
cursor.moveToNext()
}
cursor.close()
return items
}
/**
* @return the id of the most recently added item (will have the highest id). This is typically
* used as a way of determining the id of a new item to be added.
*/
fun getHighestItemId(): Int {
val db = TimetableDbHelper.getInstance(context).readableDatabase
val cursor = db.query(
SqliteSeqSchema.TABLE_NAME,
null,
SqliteSeqSchema.COL_NAME + "=?",
arrayOf(tableName),
null, null, null)
val highestId = if (cursor.count == 0) {
0
} else {
cursor.moveToFirst()
cursor.getInt(cursor.getColumnIndex(SqliteSeqSchema.COL_SEQ))
}
cursor.close()
Log.v(LOG_TAG, "Highest id found is $highestId")
return highestId
}
/**
* Adds an item's data to the database table.
*
* @param item the data model class reference for the item to be added
* @see deleteItem
* @see replaceItem
*/
open fun addItem(item: T) {
val values = propertiesAsContentValues(item)
val db = TimetableDbHelper.getInstance(context).writableDatabase
db.insert(tableName, null, values)
Log.i(LOG_TAG, "Added item with id ${item.id} to $tableName")
}
/**
* Removes an item of type [T], with the specified integer identifier, to the database table.
*
* @see addItem
* @see replaceItem
* @see deleteItemWithReferences
*/
open fun deleteItem(itemId: Int) {
val db = TimetableDbHelper.getInstance(context).writableDatabase
db.delete(tableName,
"$itemIdCol=?",
arrayOf(itemId.toString()))
Log.i(LOG_TAG, "Deleted item with id $itemId from $tableName")
}
/**
* Replaces an item of type [T] using its old integer identifier and a reference to the new data
* model class.
* By default, it merely deletes the old item using the id, and adds it again using values from
* the new data model class.
*
* @see addItem
* @see deleteItem
*/
open fun replaceItem(oldItemId: Int, newItem: T) {
Log.i(LOG_TAG, "Replacing item...")
deleteItem(oldItemId)
addItem(newItem)
}
/**
* Deletes the item from the table and deletes all references to it (which would otherwise be
* redundant data in the table).
* By default, this function only deletes the item (assumes there are no references). Subclasses
* should override to specify their own additional behaviour.
*
* @see deleteItem
*/
open fun deleteItemWithReferences(itemId: Int) {
deleteItem(itemId)
}
}
| apache-2.0 | 84445c8fefd5b7cc2e817f84faebaa04 | 31.95288 | 100 | 0.65062 | 4.550976 | false | false | false | false |
rock3r/detekt | detekt-cli/src/test/kotlin/io/gitlab/arturbosch/detekt/cli/runners/AstPrinterSpec.kt | 1 | 2035 | package io.gitlab.arturbosch.detekt.cli.runners
import io.gitlab.arturbosch.detekt.cli.CliArgs
import io.gitlab.arturbosch.detekt.test.NullPrintStream
import io.gitlab.arturbosch.detekt.test.resource
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import java.nio.file.Paths
class AstPrinterSpec : Spek({
describe("element printer") {
val path = Paths.get(resource("cases")).toString()
describe("successful AST printing") {
val output = ByteArrayOutputStream()
it("should print the AST as string") {
val args = CliArgs()
args.input = Paths.get(resource("cases/Poko.kt")).toString()
val printer = AstPrinter(args, PrintStream(output))
printer.execute()
assertThat(output.toString()).isNotEmpty()
}
}
it("throws an exception when declaring multiple input files") {
val multiplePaths = "$path,$path"
val args = CliArgs()
args.input = multiplePaths
val printer = AstPrinter(args, NullPrintStream())
assertThatIllegalArgumentException()
.isThrownBy { printer.execute() }
.withMessage("More than one input path specified. Printing AST is only supported for single files.")
}
it("throws an exception when trying to print the AST of a directory") {
val args = CliArgs()
args.input = path
val printer = AstPrinter(args, NullPrintStream())
assertThatIllegalArgumentException()
.isThrownBy { printer.execute() }
.withMessageStartingWith("Input path ")
.withMessageEndingWith(" must be a kotlin file and not a directory.")
}
}
})
| apache-2.0 | 35b56fb7af4bd4cd92162715d7f882eb | 34.701754 | 116 | 0.643243 | 5.012315 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/view/fragment/toplevel/MeFragment.kt | 1 | 9065 | /*
* 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.fragment.toplevel
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.toshi.BuildConfig
import com.toshi.R
import com.toshi.extensions.addHorizontalLineDivider
import com.toshi.extensions.getColorById
import com.toshi.extensions.getPxSize
import com.toshi.extensions.startActivity
import com.toshi.extensions.startActivityAndFinish
import com.toshi.extensions.startActivityForResult
import com.toshi.extensions.toast
import com.toshi.model.local.User
import com.toshi.model.network.Balance
import com.toshi.util.ImageUtil
import com.toshi.util.ScannerResultType
import com.toshi.util.sharedPrefs.AppPrefs
import com.toshi.view.activity.BackupPhraseInfoActivity
import com.toshi.view.activity.CurrencyActivity
import com.toshi.view.activity.LicenseListActivity
import com.toshi.view.activity.NetworkSwitcherActivity
import com.toshi.view.activity.ScannerActivity
import com.toshi.view.activity.SignOutActivity
import com.toshi.view.activity.ViewProfileActivity
import com.toshi.view.activity.WalletsActivity
import com.toshi.view.adapter.MeAdapter
import com.toshi.view.adapter.listeners.OnItemClickListener
import com.toshi.viewModel.MeViewModel
import kotlinx.android.synthetic.main.fragment_me.avatar
import kotlinx.android.synthetic.main.fragment_me.backupPhrase
import kotlinx.android.synthetic.main.fragment_me.checkboxBackupPhrase
import kotlinx.android.synthetic.main.fragment_me.currentNetwork
import kotlinx.android.synthetic.main.fragment_me.currentWallet
import kotlinx.android.synthetic.main.fragment_me.myProfileCard
import kotlinx.android.synthetic.main.fragment_me.name
import kotlinx.android.synthetic.main.fragment_me.network
import kotlinx.android.synthetic.main.fragment_me.securityStatus
import kotlinx.android.synthetic.main.fragment_me.settings
import kotlinx.android.synthetic.main.fragment_me.username
import kotlinx.android.synthetic.main.fragment_me.version
import kotlinx.android.synthetic.main.fragment_me.wallet
import java.math.BigInteger
class MeFragment : TopLevelFragment() {
companion object {
private const val TAG = "MeFragment"
private const val SCAN_REQUEST_CODE = 200
}
override fun getFragmentTag() = TAG
private lateinit var meAdapter: MeAdapter
private lateinit var viewModel: MeViewModel
private var scannerCounter = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, inState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_me, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) = init()
private fun init() {
val activity = activity ?: return
setStatusBarColor(activity)
initViewModel(activity)
setVersionName()
setSecurityState()
initClickListeners()
initRecyclerView()
initObservers()
}
private fun setStatusBarColor(activity: FragmentActivity) {
activity.window.statusBarColor = getColorById(R.color.colorPrimaryDark) ?: 0
}
private fun initViewModel(activity: FragmentActivity) {
viewModel = ViewModelProviders.of(activity).get(MeViewModel::class.java)
}
private fun setVersionName() {
val versionName = BuildConfig.VERSION_NAME
val appVersion = getString(R.string.app_version, versionName)
version.text = appVersion
}
private fun setSecurityState() {
if (AppPrefs.hasBackedUpPhrase()) {
checkboxBackupPhrase.isChecked = true
securityStatus.visibility = View.GONE
}
}
private fun initClickListeners() {
myProfileCard.setOnClickListener { startActivity<ViewProfileActivity>() }
backupPhrase.setOnClickListener { startActivity<BackupPhraseInfoActivity>() }
wallet.setOnClickListener { startActivity<WalletsActivity>() }
network.setOnClickListener { startActivity<NetworkSwitcherActivity>() }
version.setOnClickListener { handleVersionClicked() }
}
private fun handleVersionClicked() {
scannerCounter++
if (scannerCounter % 10 == 0) startActivityForResult<ScannerActivity>(SCAN_REQUEST_CODE) {
putExtra(ScannerActivity.SCANNER_RESULT_TYPE, ScannerResultType.NO_ACTION)
}
}
private fun initRecyclerView() {
meAdapter = MeAdapter()
.apply { onItemClickListener = OnItemClickListener { handleItemClickListener(it) } }
settings.apply {
layoutManager = LinearLayoutManager(context)
adapter = meAdapter
addHorizontalLineDivider(leftPadding = getPxSize(R.dimen.margin_primary))
}
}
private fun handleItemClickListener(option: Int) {
when (option) {
MeAdapter.LOCAL_CURRENCY -> startActivity<CurrencyActivity>()
MeAdapter.LEGAL_AND_PRIVACY -> startActivity<LicenseListActivity>()
MeAdapter.SIGN_OUT -> viewModel.getBalance()
else -> toast(R.string.option_not_supported)
}
}
private fun initObservers() {
viewModel.user.observe(this, Observer {
user -> user?.let { updateUi(it) } ?: handleNoUser()
})
viewModel.singleBalance.observe(this, Observer {
balance -> balance?.let { showDialog(it) }
})
viewModel.currentNetwork.observe(this, Observer {
if (it != network) currentNetwork.text = it?.name
})
viewModel.currentWalletName.observe(this, Observer {
if (it != null) currentWallet.text = it
})
}
private fun updateUi(user: User) {
name.text = user.displayName
username.text = user.username
ImageUtil.load(user.avatar, avatar)
}
private fun handleNoUser() {
name.text = getString(R.string.profile__unknown_name)
username.text = ""
avatar.setImageResource(R.drawable.ic_unknown_user_24dp)
}
private fun showDialog(balance: Balance) {
val isWalletEmpty = balance.unconfirmedBalance.compareTo(BigInteger.ZERO) == 0
val shouldCancelSignOut = !AppPrefs.hasBackedUpPhrase() && !isWalletEmpty
if (shouldCancelSignOut) showSignOutCancelledDialog()
else showSignOutWarning()
}
private fun showSignOutCancelledDialog() {
val context = context ?: return
val builder = AlertDialog.Builder(context, R.style.AlertDialogCustom)
.setTitle(R.string.sign_out_cancelled_title)
.setMessage(R.string.sign_out_cancelled_message)
.setPositiveButton(R.string.ok) { dialog, _ -> dialog.dismiss() }
builder.create().show()
}
private fun showSignOutWarning() {
val context = context ?: return
val builder = AlertDialog.Builder(context, R.style.AlertDialogCustom)
.setTitle(R.string.sign_out_warning_title)
.setMessage(R.string.sign_out_warning_message)
.setPositiveButton(R.string.yes) { dialog, _ ->
dialog.dismiss()
showSignOutConfirmationDialog()
}
.setNegativeButton(R.string.no) { dialog, _ -> dialog.dismiss() }
builder.create().show()
}
private fun showSignOutConfirmationDialog() {
val context = context ?: return
val builder = AlertDialog.Builder(context, R.style.AlertDialogCustom)
.setTitle(R.string.sign_out_confirmation_title)
.setPositiveButton(R.string.sign_out) { dialog, _ ->
dialog.dismiss()
startActivityAndFinish<SignOutActivity>()
}
.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() }
builder.create().show()
}
override fun onStart() {
super.onStart()
updateMeAdapter()
updateNetworkView()
}
private fun updateMeAdapter() = meAdapter.notifyDataSetChanged()
private fun updateNetworkView() = getMainActivity()?.showNetworkStatusView()
} | gpl-3.0 | ec98b5b4853f161d38799088dfc4ed8b | 37.909871 | 105 | 0.701489 | 4.58523 | false | false | false | false |
raatiniemi/worker | app/src/androidTest/java/me/raatiniemi/worker/data/repository/TimesheetRoomRepositoryTest.kt | 1 | 12527 | /*
* Copyright (C) 2018 Tobias Raatiniemi
*
* 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, version 2 of the License.
*
* 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 me.raatiniemi.worker.data.repository
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import me.raatiniemi.worker.data.Database
import me.raatiniemi.worker.data.projects.TimeIntervalDao
import me.raatiniemi.worker.data.projects.TimesheetDao
import me.raatiniemi.worker.data.projects.projectEntity
import me.raatiniemi.worker.data.projects.timeIntervalEntity
import me.raatiniemi.worker.domain.comparator.TimesheetDateComparator
import me.raatiniemi.worker.domain.comparator.TimesheetItemComparator
import me.raatiniemi.worker.domain.model.Project
import me.raatiniemi.worker.domain.model.TimeInterval
import me.raatiniemi.worker.domain.model.TimesheetItem
import me.raatiniemi.worker.domain.repository.PageRequest
import me.raatiniemi.worker.domain.repository.TimesheetRepository
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*
@RunWith(AndroidJUnit4::class)
class TimesheetRoomRepositoryTest {
private val project = Project(1, "Name")
private lateinit var database: Database
private lateinit var timesheet: TimesheetDao
private lateinit var timeIntervals: TimeIntervalDao
private lateinit var repository: TimesheetRepository
@Before
fun setUp() {
val context = ApplicationProvider.getApplicationContext<Context>()
database = Room.inMemoryDatabaseBuilder(context, Database::class.java)
.allowMainThreadQueries()
.build()
database.projects()
.add(
projectEntity {
id = project.id ?: 0
name = project.name
}
)
timesheet = database.timesheet()
timeIntervals = database.timeIntervals()
repository = TimesheetRoomRepository(timesheet, timeIntervals)
}
@After
fun tearDown() {
database.close()
}
private fun timesheetItemSet(timeIntervals: List<TimeInterval>): SortedSet<TimesheetItem> {
return timeIntervals.map { TimesheetItem(it) }
.toSortedSet(TimesheetItemComparator())
}
private fun timesheetItemSet(timeInterval: TimeInterval): SortedSet<TimesheetItem> {
return timesheetItemSet(listOf(timeInterval))
}
@Test
fun getTimesheet_withoutTimeIntervals() {
val actual = repository.getTimesheet(1, PageRequest.withOffset(0))
assertEquals(emptyMap<Date, Set<TimeInterval>>(), actual)
}
@Test
fun getTimesheet_withoutProjectTimeInterval() {
database.projects().add(
projectEntity {
id = 2
name = "Name #2"
}
)
val entity = timeIntervalEntity {
projectId = 2
startInMilliseconds = 1
stopInMilliseconds = 10
}
timeIntervals.add(entity)
val actual = repository.getTimesheet(1, PageRequest.withOffset(0))
assertEquals(emptyMap<Date, Set<TimeInterval>>(), actual)
}
@Test
fun getTimesheet_withTimeIntervalsForSameDate() {
val ti1 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 1
stopInMilliseconds = 10
}
val ti2 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 11
stopInMilliseconds = 30
}
listOf(ti1, ti2).forEach { timeIntervals.add(it) }
val timeIntervals = listOf(
ti1.copy(id = 1).toTimeInterval(),
ti2.copy(id = 2).toTimeInterval()
)
val expected = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()).apply {
put(Date(ti1.startInMilliseconds), timesheetItemSet(timeIntervals))
}
val actual = repository.getTimesheet(1, PageRequest.withOffset(0))
assertEquals(expected, actual)
}
@Test
fun getTimesheet_withTimeIntervalsForDifferentDates() {
val ti1 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 1
stopInMilliseconds = 10
}
val ti2 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 90000000
stopInMilliseconds = 93000000
}
listOf(ti1, ti2).forEach { timeIntervals.add(it) }
val expected = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()).apply {
put(Date(ti1.startInMilliseconds), timesheetItemSet(ti1.copy(id = 1).toTimeInterval()))
put(Date(ti2.startInMilliseconds), timesheetItemSet(ti2.copy(id = 2).toTimeInterval()))
}
val actual = repository.getTimesheet(1, PageRequest.withOffset(0))
assertEquals(expected, actual)
}
@Test
fun getTimesheet_withTimeIntervalsWithOffset() {
val ti1 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 1
stopInMilliseconds = 10
}
val ti2 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 90000000
stopInMilliseconds = 93000000
}
listOf(ti1, ti2).forEach { timeIntervals.add(it) }
val expected = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()).apply {
put(Date(ti1.startInMilliseconds), timesheetItemSet(ti1.copy(id = 1).toTimeInterval()))
}
val actual = repository.getTimesheet(1, PageRequest.withOffset(1))
assertEquals(expected, actual)
}
@Test
fun getTimesheet_withTimeIntervalsWithMaxResult() {
val ti1 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 1
stopInMilliseconds = 10
}
val ti2 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 90000000
stopInMilliseconds = 93000000
}
listOf(ti1, ti2).forEach { timeIntervals.add(it) }
val expected = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()).apply {
put(Date(ti2.startInMilliseconds), timesheetItemSet(ti2.copy(id = 2).toTimeInterval()))
}
val actual = repository.getTimesheet(1, PageRequest.withMaxResults(1))
assertEquals(expected, actual)
}
@Test
fun getTimesheetWithoutRegisteredEntries_withoutTimeIntervals() {
val actual = repository.getTimesheetWithoutRegisteredEntries(
1,
PageRequest.withOffset(0)
)
assertEquals(emptyMap<Date, Set<TimeInterval>>(), actual)
}
@Test
fun getTimesheetWithoutRegisteredEntries_withoutProjectTimeInterval() {
database.projects().add(
projectEntity {
id = 2
name = "Name #2"
}
)
val entity = timeIntervalEntity {
projectId = 2
startInMilliseconds = 1
stopInMilliseconds = 10
}
timeIntervals.add(entity)
val actual = repository.getTimesheetWithoutRegisteredEntries(
1,
PageRequest.withOffset(0)
)
assertEquals(emptyMap<Date, Set<TimeInterval>>(), actual)
}
@Test
fun getTimesheetWithoutRegisteredEntries_withTimeIntervalsForSameDate() {
val ti1 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 1
stopInMilliseconds = 10
}
val ti2 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 11
stopInMilliseconds = 30
}
listOf(ti1, ti2).forEach { timeIntervals.add(it) }
val timeIntervals = listOf(
ti1.copy(id = 1).toTimeInterval(),
ti2.copy(id = 2).toTimeInterval()
)
val expected = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()).apply {
put(Date(ti1.startInMilliseconds), timesheetItemSet(timeIntervals))
}
val actual = repository.getTimesheetWithoutRegisteredEntries(
1,
PageRequest.withOffset(0)
)
assertEquals(expected, actual)
}
@Test
fun getTimesheetWithoutRegisteredEntries_withTimeIntervalsForDifferentDates() {
val ti1 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 1
stopInMilliseconds = 10
}
val ti2 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 90000000
stopInMilliseconds = 93000000
}
listOf(ti1, ti2).forEach { timeIntervals.add(it) }
val expected = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()).apply {
put(Date(ti1.startInMilliseconds), timesheetItemSet(ti1.copy(id = 1).toTimeInterval()))
put(Date(ti2.startInMilliseconds), timesheetItemSet(ti2.copy(id = 2).toTimeInterval()))
}
val actual = repository.getTimesheetWithoutRegisteredEntries(
1,
PageRequest.withOffset(0)
)
assertEquals(expected, actual)
}
@Test
fun getTimesheetWithoutRegisteredEntries_withTimeIntervalsWithOffset() {
val ti1 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 1
stopInMilliseconds = 10
}
val ti2 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 90000000
stopInMilliseconds = 93000000
}
listOf(ti1, ti2).forEach { timeIntervals.add(it) }
val expected = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()).apply {
put(Date(ti1.startInMilliseconds), timesheetItemSet(ti1.copy(id = 1).toTimeInterval()))
}
val actual = repository.getTimesheetWithoutRegisteredEntries(
1,
PageRequest.withOffset(1)
)
assertEquals(expected, actual)
}
@Test
fun getTimesheetWithoutRegisteredEntries_withTimeIntervalsWithMaxResult() {
val ti1 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 1
stopInMilliseconds = 10
}
val ti2 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 90000000
stopInMilliseconds = 93000000
}
listOf(ti1, ti2).forEach { timeIntervals.add(it) }
val expected = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()).apply {
put(Date(ti2.startInMilliseconds), timesheetItemSet(ti2.copy(id = 2).toTimeInterval()))
}
val actual = repository.getTimesheetWithoutRegisteredEntries(
1,
PageRequest.withMaxResults(1)
)
assertEquals(expected, actual)
}
@Test
fun getTimesheetWithoutRegisteredEntries_withRegisteredTimeInterval() {
val ti1 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 1
stopInMilliseconds = 10
registered = true
}
val ti2 = timeIntervalEntity {
projectId = 1
startInMilliseconds = 90000000
stopInMilliseconds = 93000000
}
listOf(ti1, ti2).forEach { timeIntervals.add(it) }
val expected = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()).apply {
put(Date(ti2.startInMilliseconds), timesheetItemSet(ti2.copy(id = 2).toTimeInterval()))
}
val actual = repository.getTimesheetWithoutRegisteredEntries(
1,
PageRequest.withOffset(0)
)
assertEquals(expected, actual)
}
}
| gpl-2.0 | d2d6aa033b7e0617f38b5021fc6bd6ac | 33.133515 | 99 | 0.627764 | 5.022855 | false | false | false | false |
Nearsoft/nearbooks-android | app/src/main/java/com/nearsoft/nearbooks/util/ErrorUtil.kt | 2 | 2114 | package com.nearsoft.nearbooks.util
import android.content.Context
import com.nearsoft.nearbooks.NearbooksApplication
import com.nearsoft.nearbooks.R
import com.nearsoft.nearbooks.exceptions.NearbooksException
import retrofit2.Response
import rx.Observable
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
/**
* Error utilities.
* Created by epool on 1/12/16.
*/
object ErrorUtil {
private val sRetrofit = NearbooksApplication.applicationComponent.provideNearbooksRetrofit()
fun <T> parseError(responseClass: Class<T>, response: Response<*>): T? {
val converter = sRetrofit.responseBodyConverter<T>(responseClass, responseClass.annotations)
try {
return converter.convert(response.errorBody())
} catch (e: IOException) {
e.printStackTrace()
return null
}
}
fun parseError(response: Response<*>): String? {
try {
val reader = BufferedReader(InputStreamReader(response.errorBody().byteStream()))
val out = StringBuilder()
var line: String? = reader.readLine()
while (line != null) {
out.append(line)
line = reader.readLine()
}
return out.toString()
} catch (e: IOException) {
e.printStackTrace()
return null
}
}
fun getGeneralExceptionMessage(context: Context, vararg formatArgs: Any): String? {
return getMessageFromThrowable(getGeneralException(*formatArgs), context)
}
fun getMessageFromThrowable(t: Throwable, context: Context): String? {
if (t is NearbooksException) {
return t.getDisplayMessage(context)
}
return t.message
}
fun getGeneralException(vararg formatArgs: Any): NearbooksException {
return NearbooksException("General error", R.string.error_general, *formatArgs)
}
fun <T> getGeneralExceptionObservable(vararg formatArgs: Any): Observable<T> {
return Observable.error<T>(getGeneralException(*formatArgs))
}
}
| mit | 49e9ac8f4c5a577383e05b80ac4dd146 | 29.637681 | 100 | 0.663198 | 4.565875 | false | false | false | false |
hubme/WorkHelperApp | app/src/test/java/com/king/app/workhelper/DimensGenerator.kt | 1 | 3074 | import org.junit.Test
import java.io.File
import java.io.FileOutputStream
import kotlin.math.min
/**
* @Author: leavesC
* @Date: 2021/08/24 10:46
* @Desc:
* @Github https://github.com/leavesCZY
*/
private const val XML_FILE_NAME = """dimens.xml"""
private const val XML_HEADER = """<?xml version="1.0" encoding="utf-8"?>"""
private const val XML_RESOURCE_START = """<resources>"""
private const val XML_SW_DP_TAG = """<string name="sw_dp">%ddp</string>"""
private const val XML_DIMEN_TEMPLATE_TO_DP = """<dimen name="DIMEN_%ddp">%.2fdp</dimen>"""
private const val XML_DIMEN_TEMPLATE_TO_PX = """<dimen name="DIMEN_%dpx">%.2fdp</dimen>"""
private const val XML_RESOURCE_END = """</resources>"""
private const val DESIGN_WIDTH_DP = 375
private const val DESIGN_HEIGHT_DP = 667
private const val DESIGN_WIDTH_PX = 1080
private const val DESIGN_HEIGHT_PX = 1920
class DimensGenerator {
@Test
fun main() {
val designWidthDp = min(DESIGN_WIDTH_DP, DESIGN_HEIGHT_DP)
val srcDirFileDp = File("src-dp")
makeDimens(designWidthDp, srcDirFileDp, XML_DIMEN_TEMPLATE_TO_DP)
val designWidthPx = min(DESIGN_WIDTH_PX, DESIGN_HEIGHT_PX)
val srcDirFilePx = File("src-px")
makeDimens(designWidthPx, srcDirFilePx, XML_DIMEN_TEMPLATE_TO_PX)
}
private fun makeDimens(designWidth: Int, srcDirFile: File, xmlDimenTemplate: String) {
if (srcDirFile.exists() && !srcDirFile.deleteRecursively()) {
return
}
srcDirFile.mkdirs()
val smallestWidthList = mutableListOf<Int>().apply {
for (i in 320..460 step 10) {
add(i)
}
}.toList()
for (smallestWidth in smallestWidthList) {
makeDimensFile(designWidth, smallestWidth, xmlDimenTemplate, srcDirFile)
}
}
private fun makeDimensFile(
designWidth: Int,
smallestWidth: Int,
xmlDimenTemplate: String,
srcDirFile: File
) {
val dimensFolderName = "values-sw" + smallestWidth + "dp"
val dimensFile = File(srcDirFile, dimensFolderName)
dimensFile.mkdirs()
val fos = FileOutputStream(dimensFile.absolutePath + File.separator + XML_FILE_NAME)
fos.write(generateDimens(designWidth, smallestWidth, xmlDimenTemplate).toByteArray())
fos.flush()
fos.close()
}
private fun generateDimens(
designWidth: Int,
smallestWidth: Int,
xmlDimenTemplate: String
): String {
val sb = StringBuilder()
sb.append(XML_HEADER)
sb.append("\n")
sb.append(XML_RESOURCE_START)
sb.append("\n")
sb.append(" ")
sb.append(String.format(XML_SW_DP_TAG, smallestWidth))
sb.append("\n")
for (i in 1..designWidth) {
val dpValue = i.toFloat() * smallestWidth / designWidth
sb.append(" ")
sb.append(String.format(xmlDimenTemplate, i, dpValue))
sb.append("\n")
}
sb.append(XML_RESOURCE_END)
return sb.toString()
}
} | apache-2.0 | b675aaeb42d41b77579e512469b043ed | 32.064516 | 93 | 0.622642 | 3.790382 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/SetMeasurementResult.kt | 1 | 4918 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers
import com.google.cloud.spanner.Value
import org.wfanet.measurement.common.identity.ExternalId
import org.wfanet.measurement.common.identity.InternalId
import org.wfanet.measurement.gcloud.common.toGcloudByteArray
import org.wfanet.measurement.gcloud.spanner.bufferInsertMutation
import org.wfanet.measurement.gcloud.spanner.bufferUpdateMutation
import org.wfanet.measurement.gcloud.spanner.set
import org.wfanet.measurement.internal.kingdom.Measurement
import org.wfanet.measurement.internal.kingdom.MeasurementKt.resultInfo
import org.wfanet.measurement.internal.kingdom.SetMeasurementResultRequest
import org.wfanet.measurement.internal.kingdom.copy
import org.wfanet.measurement.kingdom.deploy.common.DuchyIds
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyCertificateNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementNotFoundByComputationException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.CertificateReader
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.MeasurementReader
private val NEXT_MEASUREMENT_STATE = Measurement.State.SUCCEEDED
/**
* Sets participant details for a computationParticipant in the database.
*
* Throws a subclass of [KingdomInternalException] on [execute].
* @throws [MeasurementNotFoundByComputationException] Measurement not found
* @throws [DuchyNotFoundException] Duchy not found
* @throws [DuchyCertificateNotFoundException] Duchy's Certificate not found
*/
class SetMeasurementResult(private val request: SetMeasurementResultRequest) :
SpannerWriter<Measurement, Measurement>() {
override suspend fun TransactionScope.runTransaction(): Measurement {
val (measurementConsumerId, measurementId, measurement) =
MeasurementReader(Measurement.View.DEFAULT)
.readByExternalComputationId(transactionContext, ExternalId(request.externalComputationId))
?: throw MeasurementNotFoundByComputationException(
ExternalId(request.externalComputationId)
) {
"Measurement for external computation ID ${request.externalComputationId} not found"
}
val aggregatorDuchyId =
DuchyIds.getInternalId(request.externalAggregatorDuchyId)
?: throw DuchyNotFoundException(request.externalAggregatorDuchyId) {
"Duchy with external ID ${request.externalAggregatorDuchyId} not found"
}
val aggregatorCertificateId =
CertificateReader.getDuchyCertificateId(
transactionContext,
InternalId(aggregatorDuchyId),
ExternalId(request.externalAggregatorCertificateId)
)
?: throw DuchyCertificateNotFoundException(
request.externalAggregatorDuchyId,
ExternalId(request.externalAggregatorCertificateId)
) {
"Aggregator certificate ${request.externalAggregatorCertificateId} not found"
}
transactionContext.bufferInsertMutation("DuchyMeasurementResults") {
set("MeasurementConsumerId" to measurementConsumerId)
set("MeasurementId" to measurementId)
set("DuchyId" to aggregatorDuchyId)
set("CertificateId" to aggregatorCertificateId)
set("CreateTime" to Value.COMMIT_TIMESTAMP)
set("EncryptedResult" to request.encryptedResult.toGcloudByteArray())
}
transactionContext.bufferUpdateMutation("Measurements") {
set("MeasurementConsumerId" to measurementConsumerId)
set("MeasurementId" to measurementId)
set("UpdateTime" to Value.COMMIT_TIMESTAMP)
set("State" to NEXT_MEASUREMENT_STATE)
}
return measurement.copy {
state = NEXT_MEASUREMENT_STATE
results += resultInfo {
externalAggregatorDuchyId = request.externalAggregatorDuchyId
externalCertificateId = request.externalAggregatorCertificateId
encryptedResult = request.encryptedResult
}
}
}
override fun ResultScope<Measurement>.buildResult(): Measurement {
return checkNotNull(transactionResult).copy { updateTime = commitTimestamp.toProto() }
}
}
| apache-2.0 | 56387e3f0ab65b027a0d779e8aa28d0a | 46.288462 | 108 | 0.782635 | 4.957661 | false | false | false | false |
LISTEN-moe/android-app | app/src/main/kotlin/me/echeung/moemoekyun/ui/activity/auth/AuthActivityUtil.kt | 1 | 3211 | package me.echeung.moemoekyun.ui.activity.auth
import android.app.Activity
import android.content.Intent
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import me.echeung.moemoekyun.R
import me.echeung.moemoekyun.client.auth.AuthUtil
import me.echeung.moemoekyun.service.RadioService
import me.echeung.moemoekyun.util.ext.toast
import me.echeung.moemoekyun.viewmodel.RadioViewModel
import me.echeung.moemoekyun.viewmodel.UserViewModel
import org.koin.android.ext.android.get
import org.koin.core.component.KoinComponent
object AuthActivityUtil : KoinComponent {
// Intent codes
const val LOGIN_REQUEST = 0
const val LOGIN_FAVORITE_REQUEST = 1
const val REGISTER_REQUEST = 2
// Intent extra keys
const val LOGIN_NAME = "login_name"
const val LOGIN_PASS = "login_pass"
const val AUTH_EVENT = "auth_event"
fun FragmentActivity.showLoginActivity(requestCode: Int = LOGIN_REQUEST) {
startActivityForResult(Intent(this, AuthLoginActivity::class.java), requestCode)
}
fun FragmentActivity.showLoginActivity(intent: Intent) {
intent.setClass(this, AuthLoginActivity::class.java)
startActivityForResult(intent, LOGIN_REQUEST)
}
fun FragmentActivity.showRegisterActivity() {
startActivityForResult(Intent(this, AuthRegisterActivity::class.java), REGISTER_REQUEST)
}
fun FragmentActivity.broadcastAuthEvent() {
sendBroadcast(
Intent(AUTH_EVENT).apply {
setPackage(applicationContext.packageName)
},
)
val radioViewModel: RadioViewModel = get()
val authUtil: AuthUtil = get()
radioViewModel.isAuthed = authUtil.isAuthenticated
}
fun FragmentActivity.showLogoutDialog() {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.logout)
.setMessage(getString(R.string.logout_confirmation))
.setPositiveButton(R.string.logout) { _, _ -> logout() }
.setNegativeButton(android.R.string.cancel, null)
.create()
.show()
}
fun FragmentActivity.handleAuthActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode != Activity.RESULT_OK) {
return
}
invalidateOptionsMenu()
broadcastAuthEvent()
when (requestCode) {
// Redirect to login after registering
REGISTER_REQUEST -> showLoginActivity(data!!)
// Favorite song after logging in
LOGIN_FAVORITE_REQUEST -> sendBroadcast(
Intent(RadioService.TOGGLE_FAVORITE).apply {
setPackage(packageName)
},
)
}
}
private fun FragmentActivity.logout() {
val authUtil: AuthUtil = get()
if (!authUtil.isAuthenticated) {
return
}
authUtil.clearAuthToken()
val userViewModel: UserViewModel = get()
userViewModel.reset()
toast(getString(R.string.logged_out), Toast.LENGTH_LONG)
invalidateOptionsMenu()
broadcastAuthEvent()
}
}
| mit | 8a2f1eb90713a1280f236b93710f2975 | 29.875 | 101 | 0.668016 | 4.792537 | false | false | false | false |
damien5314/imgur-shenanigans | app/src/main/java/ddiehl/android/imgurtest/view/WebViewFragment.kt | 1 | 3535 | package ddiehl.android.imgurtest.view
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import ddiehl.android.imgurtest.BuildConfig
import ddiehl.android.imgurtest.R
import ddiehl.android.imgurtest.utils.disableWebViewZoomControls
import org.jetbrains.anko.AnkoComponent
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.webView
import timber.log.Timber
class WebViewFragment : Fragment() {
companion object {
private val ARG_URL = "arg_url"
fun newInstance(url: String) =
WebViewFragment().apply {
arguments = Bundle().apply {
putString(ARG_URL, url)
}
}
}
private lateinit var mURL: String
private lateinit var mWebView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true)
}
mURL = arguments.getString(ARG_URL)
Timber.d("Loading URL: " + mURL)
activity.setTitle(R.string.app_name)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = mUI
initWebView()
return view
}
private fun initWebView() {
mWebView.settings.apply {
javaScriptEnabled = true
useWideViewPort = true
loadWithOverviewMode = true
domStorageEnabled = true
}
mWebView.disableWebViewZoomControls()
mWebView.setWebViewClient(object: WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
// if (url.startsWith("http://m.imgur.com/")) return true
Timber.d("Loading URL: " + url)
return false
}
})
mWebView.loadUrl(mURL)
mWebView.setOnKeyListener { v1, keyCode, event ->
// Check if the key event was the Back button and if there's history
if (event.action == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
mWebView.goBack()
}
false
}
}
override fun onDestroyView() {
(mWebView.parent as ViewGroup).removeView(mWebView)
mWebView.removeAllViews()
mWebView.destroy()
super.onDestroyView()
}
private val mUI: View by lazy {
object: AnkoComponent<WebViewFragment> {
override fun createView(ui: AnkoContext<WebViewFragment>): View =
ui.apply {
mWebView = webView {
lparams {
width = matchParent
height = matchParent
}
}
}.view
}.createView(AnkoContext.create(context, this))
}
// override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
// Dialog(activity, R.style.DialogOverlay).apply {
// setContentView(object: AnkoComponent<WebViewFragment> {
// override fun createView(ui: AnkoContext<WebViewFragment>) =
// ui.apply {
// mWebView = webView {
// lparams {
// width = matchParent
// height = matchParent
// }
// }
// }.view
// }.createView(AnkoContext.create(context, this@WebViewFragment)))
// }
}
| apache-2.0 | 034a682368719d863d7f8de3484e4b77 | 29.73913 | 92 | 0.6529 | 4.54955 | false | false | false | false |
asamm/locus-api | locus-api-android/src/main/java/locus/api/android/objects/TrackRecordProfileSimple.kt | 1 | 2428 | /****************************************************************************
*
* Created by menion on 13/03/2019.
* Copyright (c) 2019. All rights reserved.
*
* This file is part of the Asamm team software.
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
***************************************************************************/
package locus.api.android.objects
import locus.api.objects.Storable
import locus.api.utils.DataReaderBigEndian
import locus.api.utils.DataWriterBigEndian
import java.io.IOException
/**
* Simple container for track recording profiles.
*
* To obtain list of all available profiles defined in certain Locus Map application,
* use ActionBasics.getTrackRecordingProfiles]
*/
class TrackRecordProfileSimple() : Storable() {
/**
* Profile ID.
*/
var id: Long = 0L
private set
/**
* Readable profile name.
*/
var name: String = ""
private set
/**
* Profile generated description.
*/
var desc: String = ""
private set
/**
* Current profile icon. Icon may be converted to bitmap object
* thanks to 'Utils.getBitmap()' function.
*/
var icon: ByteArray? = null
private set
/**
* Generate object from known values.
*/
internal constructor(id: Long, name: String, desc: String, icon: ByteArray?): this() {
this.id = id
this.name = name
this.desc = desc
this.icon = icon
}
//*************************************************
// STORABLE PART
//*************************************************
override fun getVersion(): Int {
return 0
}
@Throws(IOException::class)
override fun readObject(version: Int, dr: DataReaderBigEndian) {
id = dr.readLong()
name = dr.readString()
desc = dr.readString()
val imgSize = dr.readInt()
if (imgSize > 0) {
icon = ByteArray(imgSize)
dr.readBytes(icon!!)
}
}
@Throws(IOException::class)
override fun writeObject(dw: DataWriterBigEndian) {
dw.writeLong(id)
dw.writeString(name)
dw.writeString(desc)
val imgSize = icon?.size ?: 0
dw.writeInt(imgSize)
if (imgSize > 0) {
dw.write(icon!!)
}
}
}
| mit | 241b246a7dc0a621b02a13ce506d39c3 | 25.681319 | 90 | 0.541598 | 4.589792 | false | false | false | false |
FHannes/intellij-community | platform/projectModel-api/src/com/intellij/util/io/io.kt | 13 | 3342 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.io
import com.intellij.util.SmartList
import com.intellij.util.text.CharArrayCharSequence
import java.io.InputStreamReader
import java.net.URLEncoder
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.util.*
fun InputStreamReader.readCharSequence(length: Int): CharSequence {
use {
val chars = CharArray(length)
var count = 0
while (count < chars.size) {
val n = read(chars, count, chars.size - count)
if (n <= 0) {
break
}
count += n
}
return CharSequenceBackedByChars(chars, 0, count)
}
}
/**
* Think twice before use - consider to to specify length.
*/
fun InputStreamReader.readCharSequence(): CharSequence {
var chars = CharArray(DEFAULT_BUFFER_SIZE)
var buffers: MutableList<CharArray>? = null
var count = 0
var total = 0
while (true) {
val n = read(chars, count, chars.size - count)
if (n <= 0) {
break
}
count += n
total += n
if (count == chars.size) {
if (buffers == null) {
buffers = SmartList<CharArray>()
}
buffers.add(chars)
val newLength = Math.min(1024 * 1024, chars.size * 2)
chars = CharArray(newLength)
count = 0
}
}
if (buffers == null) {
return CharSequenceBackedByChars(chars, 0, total)
}
val result = CharArray(total)
for (buffer in buffers) {
System.arraycopy(buffer, 0, result, result.size - total, buffer.size)
total -= buffer.size
}
System.arraycopy(chars, 0, result, result.size - total, total)
return CharSequenceBackedByChars(result)
}
// we must return string on subSequence() - JsonReaderEx will call toString in any case
class CharSequenceBackedByChars : CharArrayCharSequence {
val byteBuffer: ByteBuffer
get() = Charsets.UTF_8.encode(CharBuffer.wrap(myChars, myStart, length))
constructor(charBuffer: CharBuffer) : super(charBuffer.array(), charBuffer.arrayOffset(), charBuffer.position()) {
}
constructor(chars: CharArray, start: Int, end: Int) : super(chars, start, end) {
}
constructor(chars: CharArray) : super(*chars) {
}
override fun subSequence(start: Int, end: Int): CharSequence {
return if (start == 0 && end == length) this else String(myChars, myStart + start, end - start)
}
}
fun ByteBuffer.toByteArray(): ByteArray {
if (hasArray()) {
val offset = arrayOffset()
if (offset == 0 && array().size == limit()) {
return array()
}
return Arrays.copyOfRange(array(), offset, offset + limit())
}
val bytes = ByteArray(limit())
get(bytes)
return bytes
}
fun String.encodeUrlQueryParameter() = URLEncoder.encode(this, Charsets.UTF_8.name())!!
fun String.decodeBase64(): ByteArray = Base64.getDecoder().decode(this) | apache-2.0 | 76acb0e8547ae999ef4f717b29728857 | 27.818966 | 116 | 0.681628 | 3.89057 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/location/AndroidGeofenceTransitionIntentService.kt | 1 | 1581 | package org.tasks.location
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.Notifier
import org.tasks.data.LocationDao
import org.tasks.injection.InjectingJobIntentService
import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint
class AndroidGeofenceTransitionIntentService : InjectingJobIntentService() {
@Inject lateinit var locationDao: LocationDao
@Inject lateinit var notifier: Notifier
override suspend fun doWork(intent: Intent) {
val arrival = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false)
Timber.d("geofence[${intent.data}] arrival[$arrival]")
val place = intent.data?.lastPathSegment?.toLongOrNull()?.let { locationDao.getPlace(it) }
if (place == null) {
Timber.e("Failed to find place ${intent.data}")
return
}
val geofences = if (arrival) {
locationDao.getArrivalGeofences(place.uid!!)
} else {
locationDao.getDepartureGeofences(place.uid!!)
}
notifier.triggerNotifications(place.id, geofences, arrival)
}
class Broadcast : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
enqueueWork(
context,
AndroidGeofenceTransitionIntentService::class.java,
JOB_ID_GEOFENCE_TRANSITION,
intent)
}
}
} | gpl-3.0 | 8201dc551b348bc1f9372f563253c133 | 34.954545 | 98 | 0.683112 | 4.909938 | false | false | false | false |
tasks/tasks | app/src/main/java/com/todoroo/astrid/api/BooleanCriterion.kt | 1 | 1000 | package com.todoroo.astrid.api
import android.os.Parcel
import android.os.Parcelable
class BooleanCriterion constructor() : CustomFilterCriterion(), Parcelable {
constructor(identifier: String, title: String, sql: String): this() {
this.identifier = identifier
this.text = title
this.sql = sql
this.name = title
}
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
writeToParcel(dest)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<BooleanCriterion> = object : Parcelable.Creator<BooleanCriterion> {
override fun createFromParcel(source: Parcel?): BooleanCriterion {
val item = BooleanCriterion()
item.readFromParcel(source)
return item
}
override fun newArray(size: Int): Array<BooleanCriterion?> {
return arrayOfNulls(size)
}
}
}
} | gpl-3.0 | d168290ed0d5d8072d6d8c259ca341f9 | 27.6 | 107 | 0.619 | 5.050505 | false | false | false | false |
ademar111190/Studies | Projects/Test/app/src/main/java/ademar/study/test/view/base/BaseActivity.kt | 1 | 2606 | package ademar.study.test.view.base
import ademar.study.test.App
import ademar.study.test.R
import ademar.study.test.injection.DaggerLifeCycleComponent
import ademar.study.test.injection.LifeCycleComponent
import ademar.study.test.injection.LifeCycleModule
import ademar.study.test.model.ErrorViewModel
import ademar.study.test.presenter.LoadDataView
import android.app.ActivityManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.support.v4.app.NavUtils
import android.support.v4.app.TaskStackBuilder
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
abstract class BaseActivity : AppCompatActivity(), LoadDataView {
protected val component: LifeCycleComponent by lazy {
DaggerLifeCycleComponent.builder()
.coreComponent(getApp().coreComponent)
.lifeCycleModule(makeLifeCycleModule())
.build()
}
protected open fun makeLifeCycleModule() = LifeCycleModule(this)
protected fun prepareTaskDescription(
label: String = getString(R.string.app_name),
icon: Int = R.drawable.ic_task,
colorPrimary: Int = ContextCompat.getColor(this, R.color.primary)
) {
val drawable = ContextCompat.getDrawable(this, icon)
if (drawable != null) {
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
setTaskDescription(ActivityManager.TaskDescription(label, bitmap, colorPrimary))
}
}
fun getApp() = applicationContext as App
override fun getBaseActivity() = this
override fun showLoading() {
}
override fun showRetry() {
}
override fun showContent() {
}
override fun showError(viewModel: ErrorViewModel) = AlertDialog
.Builder(this, R.style.AppAlertDialog)
.setMessage(viewModel.message)
.setPositiveButton(R.string.app_ok, null)
.create()
.show()
fun back() {
val upIntent = NavUtils.getParentActivityIntent(this) ?: intent
if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot) {
TaskStackBuilder.create(this)
.addNextIntentWithParentStack(upIntent)
.startActivities()
} else {
NavUtils.navigateUpTo(this, upIntent)
}
}
}
| mit | ba488d4f250275001180e91f5413c1aa | 33.289474 | 120 | 0.685725 | 4.637011 | false | true | false | false |
robertwb/incubator-beam | examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/cookbook/BigQueryTornadoes.kt | 8 | 7059 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.examples.kotlin.cookbook
import com.google.api.services.bigquery.model.TableFieldSchema
import com.google.api.services.bigquery.model.TableRow
import com.google.api.services.bigquery.model.TableSchema
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.Method
import org.apache.beam.sdk.io.gcp.bigquery.WriteResult
import org.apache.beam.sdk.options.*
import org.apache.beam.sdk.transforms.Count
import org.apache.beam.sdk.transforms.DoFn
import org.apache.beam.sdk.transforms.PTransform
import org.apache.beam.sdk.transforms.ParDo
import org.apache.beam.sdk.values.KV
import org.apache.beam.sdk.values.PCollection
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists
/**
* An example that reads the public samples of weather data from BigQuery, counts the number of
* tornadoes that occur in each month, and writes the results to BigQuery.
*
*
* Concepts: Reading/writing BigQuery; counting a PCollection; user-defined PTransforms
*
*
* Note: Before running this example, you must create a BigQuery dataset to contain your output
* table.
*
*
* To execute this pipeline locally, specify the BigQuery table for the output with the form:
*
* <pre>`--output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
`</pre> *
*
*
* To change the runner, specify:
*
* <pre>`--runner=YOUR_SELECTED_RUNNER
`</pre> *
*
* See examples/java/README.md for instructions about how to configure different runners.
*
*
* The BigQuery input table defaults to `clouddataflow-readonly:samples.weather_stations`
* and can be overridden with `--input`.
*/
object BigQueryTornadoes {
// Default to using a 1000 row subset of the public weather station table publicdata:samples.gsod.
private const val WEATHER_SAMPLES_TABLE = "clouddataflow-readonly:samples.weather_stations"
/**
* Examines each row in the input table. If a tornado was recorded in that sample, the month in
* which it occurred is output.
*/
internal class ExtractTornadoesFn : DoFn<TableRow, Int>() {
@ProcessElement
fun processElement(c: ProcessContext) {
val row = c.element()
if (row["tornado"] as Boolean) {
c.output(Integer.parseInt(row["month"] as String))
}
}
}
/**
* Prepares the data for writing to BigQuery by building a TableRow object containing an integer
* representation of month and the number of tornadoes that occurred in each month.
*/
internal class FormatCountsFn : DoFn<KV<Int, Long>, TableRow>() {
@ProcessElement
fun processElement(c: ProcessContext) {
val row = TableRow()
.set("month", c.element().key)
.set("tornado_count", c.element().value)
c.output(row)
}
}
/**
* Takes rows from a table and generates a table of counts.
*
*
* The input schema is described by https://developers.google.com/bigquery/docs/dataset-gsod .
* The output contains the total number of tornadoes found in each month in the following schema:
*
*
* * month: integer
* * tornado_count: integer
*
*/
internal class CountTornadoes : PTransform<PCollection<TableRow>, PCollection<TableRow>>() {
override fun expand(rows: PCollection<TableRow>): PCollection<TableRow> {
// row... => month...
val tornadoes = rows.apply(ParDo.of(ExtractTornadoesFn()))
// month... => <month,count>...
val tornadoCounts = tornadoes.apply(Count.perElement())
// <month,count>... => row...
return tornadoCounts.apply(ParDo.of(FormatCountsFn()))
}
}
/**
* Options supported by [BigQueryTornadoes].
*
*
* Inherits standard configuration options.
*/
interface Options : PipelineOptions {
@get:Description("Table to read from, specified as <project_id>:<dataset_id>.<table_id>")
@get:Default.String(WEATHER_SAMPLES_TABLE)
var input: String
@get:Description("Mode to use when reading from BigQuery")
@get:Default.Enum("EXPORT")
var readMethod: Method
@get:Description("BigQuery table to write to, specified as <project_id>:<dataset_id>.<table_id>. The dataset must already exist.")
@get:Validation.Required
var output: String
}
private fun runBigQueryTornadoes(options: Options) {
val p = Pipeline.create(options)
// Build the table schema for the output table.
val fields = arrayListOf<TableFieldSchema>(
TableFieldSchema().setName("month").setType("INTEGER"),
TableFieldSchema().setName("tornado_count").setType("INTEGER")
)
val schema = TableSchema().setFields(fields)
val rowsFromBigQuery: PCollection<TableRow>
if (options.readMethod == Method.DIRECT_READ) {
rowsFromBigQuery = p.apply(
BigQueryIO.readTableRows()
.from(options.input)
.withMethod(Method.DIRECT_READ)
.withSelectedFields(Lists.newArrayList("month", "tornado")))
} else {
rowsFromBigQuery = p.apply(
BigQueryIO.readTableRows()
.from(options.input)
.withMethod(options.readMethod))
}
rowsFromBigQuery
.apply(CountTornadoes())
.apply<WriteResult>(
BigQueryIO.writeTableRows()
.to(options.output)
.withSchema(schema)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE))
p.run().waitUntilFinish()
}
@JvmStatic
fun main(args: Array<String>) {
val options = PipelineOptionsFactory.fromArgs(*args).withValidation() as Options
runBigQueryTornadoes(options)
}
}
| apache-2.0 | 2f4351cbb40272225921f4a1f0c34e0b | 36.152632 | 138 | 0.650659 | 4.179396 | false | false | false | false |
michaelgallacher/intellij-community | platform/credential-store/src/PasswordSafeImpl.kt | 2 | 5588 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("PackageDirectoryMismatch")
package com.intellij.ide.passwordSafe.impl
import com.intellij.credentialStore.*
import com.intellij.credentialStore.PasswordSafeSettings.ProviderType
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.ide.passwordSafe.PasswordStorage
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.SettingsSavingComponent
import com.intellij.openapi.diagnostic.catchAndLog
import org.jetbrains.concurrency.runAsync
class PasswordSafeImpl(/* public - backward compatibility */val settings: PasswordSafeSettings) : PasswordSafe(), SettingsSavingComponent {
private @Volatile var currentProvider: PasswordStorage
// it is helper storage to support set password as memory-only (see setPassword memoryOnly flag)
private val memoryHelperProvider = lazy { KeePassCredentialStore(emptyMap(), memoryOnly = true) }
override fun isMemoryOnly() = settings.providerType == ProviderType.MEMORY_ONLY
val isNativeCredentialStoreUsed: Boolean
get() = currentProvider !is KeePassCredentialStore
init {
if (settings.providerType == ProviderType.MEMORY_ONLY || ApplicationManager.getApplication().isUnitTestMode) {
currentProvider = KeePassCredentialStore(memoryOnly = true)
}
else {
currentProvider = createPersistentCredentialStore()
}
ApplicationManager.getApplication().messageBus.connect().subscribe(PasswordSafeSettings.TOPIC, object: PasswordSafeSettingsListener {
override fun typeChanged(oldValue: ProviderType, newValue: ProviderType) {
val memoryOnly = newValue == ProviderType.MEMORY_ONLY
if (memoryOnly) {
val provider = currentProvider
if (provider is KeePassCredentialStore) {
provider.memoryOnly = true
provider.deleteFileStorage()
}
else {
currentProvider = KeePassCredentialStore(memoryOnly = true)
}
}
else {
currentProvider = createPersistentCredentialStore(currentProvider as? KeePassCredentialStore)
}
}
})
}
override fun get(attributes: CredentialAttributes): Credentials? {
val value = currentProvider.get(attributes)
if (value == null && memoryHelperProvider.isInitialized()) {
// if password was set as `memoryOnly`
return memoryHelperProvider.value.get(attributes)
}
return value
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
currentProvider.set(attributes, credentials)
if (memoryHelperProvider.isInitialized()) {
val memoryHelper = memoryHelperProvider.value
// update password in the memory helper, but only if it was previously set
if (credentials == null || memoryHelper.get(attributes) != null) {
memoryHelper.set(attributes, credentials)
}
}
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?, memoryOnly: Boolean) {
if (memoryOnly) {
memoryHelperProvider.value.set(attributes, credentials)
// remove to ensure that on getPassword we will not return some value from default provider
currentProvider.set(attributes, null)
}
else {
set(attributes, credentials)
}
}
// maybe in the future we will use native async, so, this method added here instead "if need, just use runAsync in your code"
override fun getAsync(attributes: CredentialAttributes) = runAsync { get(attributes) }
override fun save() {
(currentProvider as? KeePassCredentialStore)?.let { it.save() }
}
fun clearPasswords() {
LOG.info("Passwords cleared", Error())
try {
if (memoryHelperProvider.isInitialized()) {
memoryHelperProvider.value.clear()
}
}
finally {
(currentProvider as? KeePassCredentialStore)?.let { it.clear() }
}
ApplicationManager.getApplication().messageBus.syncPublisher(PasswordSafeSettings.TOPIC).credentialStoreCleared()
}
// public - backward compatibility
@Suppress("unused", "DeprecatedCallableAddReplaceWith")
@Deprecated("Do not use it")
val masterKeyProvider: PasswordStorage
get() = currentProvider
@Suppress("unused")
@Deprecated("Do not use it")
// public - backward compatibility
val memoryProvider: PasswordStorage
get() = memoryHelperProvider.value
}
private fun createPersistentCredentialStore(existing: KeePassCredentialStore? = null, convertFileStore: Boolean = false): PasswordStorage {
LOG.catchAndLog {
for (factory in CredentialStoreFactory.CREDENTIAL_STORE_FACTORY.extensions) {
val store = factory.create() ?: continue
if (convertFileStore) {
LOG.catchAndLog {
val fileStore = KeePassCredentialStore()
fileStore.copyTo(store)
fileStore.clear()
fileStore.save()
}
}
return store
}
}
existing?.let {
it.memoryOnly = false
return it
}
return KeePassCredentialStore()
} | apache-2.0 | dfc494b47ad88c6821d700a1ea523b7a | 35.292208 | 139 | 0.722083 | 4.867596 | false | false | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/game/command/aggregate/TableBalancer.kt | 1 | 4724 | package com.flexpoker.game.command.aggregate
import com.flexpoker.exception.FlexPokerException
import com.flexpoker.game.command.events.GameEvent
import com.flexpoker.game.command.events.PlayerMovedToNewTableEvent
import com.flexpoker.game.command.events.TablePausedForBalancingEvent
import com.flexpoker.game.command.events.TableRemovedEvent
import com.flexpoker.game.command.events.TableResumedAfterBalancingEvent
import org.pcollections.PMap
import org.pcollections.PSet
import java.util.Optional
import java.util.UUID
fun createSingleBalancingEvent(gameId: UUID, maxPlayersPerTable: Int, subjectTableId: UUID,
pausedTablesForBalancing: Set<UUID>, tableToPlayersMap: PMap<UUID, PSet<UUID>>,
playerToChipsAtTableMap: Map<UUID, Int>): Optional<GameEvent> {
// make sure at least two players exists. we're in a bad state if not
val totalNumberOfPlayers = getTotalNumberOfPlayers(tableToPlayersMap)
if (totalNumberOfPlayers < 2) {
throw FlexPokerException(
"the game should be over since less than two players are left. no balancing should be done"
)
}
// remove any empty tables first
val emptyTable = tableToPlayersMap.entries.firstOrNull { it.value.isEmpty() }
if (emptyTable != null) {
return Optional.of(TableRemovedEvent(gameId, emptyTable.key))
}
// check to see if the number of tables is greater than the number it
// should have. if so, move all the players from this table to other
// tables starting with the one with the lowest number
if (tableToPlayersMap.size > getRequiredNumberOfTables(maxPlayersPerTable, totalNumberOfPlayers)) {
return createEventToMoveUserFromSubjectTableToAnyMinTable(gameId,
subjectTableId, tableToPlayersMap, playerToChipsAtTableMap)
}
if (isTableOutOfBalance(subjectTableId, tableToPlayersMap)) {
val tableSize = tableToPlayersMap[subjectTableId]!!.size
// in the min case, pause the table since it needs to get another player
if (tableSize == tableToPlayersMap.values.map { it.size }.minOrNull()) {
return Optional.of(TablePausedForBalancingEvent(gameId, subjectTableId))
}
// only move a player if the out of balance table has the max number
// of players. an out-of-balance medium-sized table should not send
// any players
if (tableSize == tableToPlayersMap.values.map { it.size }.maxOrNull()) {
return createEventToMoveUserFromSubjectTableToAnyMinTable(gameId,
subjectTableId, tableToPlayersMap, playerToChipsAtTableMap)
}
}
// re-examine the paused tables to see if they are still not balanced
val pausedTablesThatShouldStayPaused = pausedTablesForBalancing
.filter { isTableOutOfBalance(it, tableToPlayersMap) }
.toSet()
// resume the first table that is currently paused, but are now balanced
val tableToResume = pausedTablesForBalancing.firstOrNull { !pausedTablesThatShouldStayPaused.contains(it) }
return if (tableToResume == null) Optional.empty()
else Optional.of(TableResumedAfterBalancingEvent(gameId, tableToResume))
}
private fun createEventToMoveUserFromSubjectTableToAnyMinTable(gameId: UUID, subjectTableId: UUID,
tableToPlayersMap: Map<UUID, MutableSet<UUID>>, playerToChipsAtTableMap: Map<UUID, Int>
): Optional<GameEvent> {
val playerToMove = tableToPlayersMap[subjectTableId]!!.first()
val toTableId = findNonSubjectMinTableId(subjectTableId, tableToPlayersMap)
val chips = playerToChipsAtTableMap[playerToMove]!!
return Optional.of(PlayerMovedToNewTableEvent(gameId, subjectTableId, toTableId, playerToMove, chips))
}
private fun findNonSubjectMinTableId(subjectTableId: UUID, tableToPlayersMap: Map<UUID, MutableSet<UUID>>): UUID {
return tableToPlayersMap.filter { it.key != subjectTableId }.minByOrNull { it.value.size }!!.key
}
private fun isTableOutOfBalance(tableId: UUID, tableToPlayersMap: Map<UUID, MutableSet<UUID>>): Boolean {
val tableSize = tableToPlayersMap[tableId]!!.size
return if (tableSize == 1) {
true
} else tableToPlayersMap.values.any { it.size >= tableSize + 2 || it.size <= tableSize - 2 }
}
private fun getTotalNumberOfPlayers(tableToPlayersMap: Map<UUID, MutableSet<UUID>>): Int {
return tableToPlayersMap.values.sumBy { it.size }
}
private fun getRequiredNumberOfTables(maxPlayersPerTable: Int, totalNumberOfPlayers: Int): Int {
var numberOfRequiredTables = totalNumberOfPlayers / maxPlayersPerTable
if (totalNumberOfPlayers % maxPlayersPerTable != 0) {
numberOfRequiredTables++
}
return numberOfRequiredTables
}
| gpl-2.0 | b6186f11718ec18dd6895e9db97f11dc | 47.204082 | 114 | 0.741956 | 4.202847 | false | false | false | false |
adrcotfas/Goodtime | app/src/main/java/com/apps/adrcotfas/goodtime/main/TimerActivity.kt | 1 | 30302 | /*
* Copyright 2016-2020 Adrian Cotfas
*
* 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.apps.adrcotfas.goodtime.main
import com.apps.adrcotfas.goodtime.settings.reminders.ReminderHelper.Companion.removeNotification
import com.apps.adrcotfas.goodtime.util.BatteryUtils.Companion.isIgnoringBatteryOptimizations
import dagger.hilt.android.AndroidEntryPoint
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import com.apps.adrcotfas.goodtime.statistics.main.SelectLabelDialog.OnLabelSelectedListener
import javax.inject.Inject
import com.apps.adrcotfas.goodtime.settings.PreferenceHelper
import com.apps.adrcotfas.goodtime.bl.CurrentSessionManager
import android.widget.TextView
import com.google.android.material.chip.Chip
import com.apps.adrcotfas.goodtime.statistics.SessionViewModel
import com.apps.adrcotfas.goodtime.bl.SessionType
import com.apps.adrcotfas.goodtime.bl.TimerState
import android.content.Intent
import com.apps.adrcotfas.goodtime.bl.TimerService
import android.os.Build
import android.os.Bundle
import org.greenrobot.eventbus.EventBus
import androidx.databinding.DataBindingUtil
import com.apps.adrcotfas.goodtime.R
import com.kobakei.ratethisapp.RateThisApp
import android.view.animation.Animation
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.snackbar.BaseTransientBottomBar
import android.annotation.SuppressLint
import com.apps.adrcotfas.goodtime.settings.SettingsActivity
import com.apps.adrcotfas.goodtime.bl.NotificationHelper
import android.content.SharedPreferences
import android.graphics.PorterDuff
import android.content.DialogInterface
import com.apps.adrcotfas.goodtime.bl.CurrentSession
import android.widget.Toast
import android.widget.FrameLayout
import org.greenrobot.eventbus.Subscribe
import com.apps.adrcotfas.goodtime.util.Constants.FinishWorkEvent
import com.apps.adrcotfas.goodtime.util.Constants.FinishBreakEvent
import com.apps.adrcotfas.goodtime.util.Constants.FinishLongBreakEvent
import com.apps.adrcotfas.goodtime.util.Constants.StartSessionEvent
import com.apps.adrcotfas.goodtime.util.Constants.OneMinuteLeft
import com.apps.adrcotfas.goodtime.statistics.main.SelectLabelDialog
import android.content.res.ColorStateList
import android.net.Uri
import android.provider.Settings
import android.util.Log
import android.view.*
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import com.apps.adrcotfas.goodtime.BuildConfig
import com.apps.adrcotfas.goodtime.database.Label
import com.apps.adrcotfas.goodtime.database.Session
import com.apps.adrcotfas.goodtime.databinding.ActivityMainBinding
import com.apps.adrcotfas.goodtime.ui.ActivityWithBilling
import com.apps.adrcotfas.goodtime.util.*
import com.apps.adrcotfas.goodtime.util.Constants.ClearNotificationEvent
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*
import java.util.concurrent.TimeUnit
@AndroidEntryPoint
class TimerActivity : ActivityWithBilling(), OnSharedPreferenceChangeListener,
OnLabelSelectedListener,
FinishedSessionDialog.Listener {
private lateinit var binding: ActivityMainBinding
@Inject
lateinit var currentSessionManager: CurrentSessionManager
private var sessionFinishedDialog: FinishedSessionDialog? = null
private var fullscreenHelper: FullscreenHelper? = null
private var backPressedAt: Long = 0
private lateinit var blackCover: View
private lateinit var whiteCover: View
private lateinit var labelButton: MenuItem
private lateinit var boundsView: View
private lateinit var timeView: TextView
private lateinit var toolbar: Toolbar
private lateinit var tutorialDot: ImageView
private lateinit var labelChip: Chip
private val sessionViewModel: SessionViewModel by viewModels()
private val mainViewModel: TimerActivityViewModel by viewModels()
private var sessionsCounterText: TextView? = null
private var currentSessionType = SessionType.INVALID
fun onStartButtonClick(view: View) {
start(SessionType.WORK)
}
fun onStopButtonClick() {
stop()
}
fun onSkipButtonClick() {
skip()
}
fun onAdd60SecondsButtonClick() {
add60Seconds()
}
private fun skip() {
if (currentSession.timerState.value !== TimerState.INACTIVE) {
val skipIntent: Intent = IntentWithAction(
this@TimerActivity, TimerService::class.java,
Constants.ACTION.SKIP
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(skipIntent)
} else {
startService(skipIntent)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
EventBus.getDefault().register(this)
if (preferenceHelper.isFirstRun()) {
// show app intro
val i = Intent(this@TimerActivity, MainIntroActivity::class.java)
startActivity(i)
preferenceHelper.consumeFirstRun()
}
ThemeHelper.setTheme(this, preferenceHelper.isAmoledTheme())
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
blackCover = binding.blackCover
whiteCover = binding.whiteCover
toolbar = binding.bar
timeView = binding.timeLabel
tutorialDot = binding.tutorialDot
boundsView = binding.main
labelChip = binding.labelView
labelChip.setOnClickListener { showEditLabelDialog() }
setupTimeLabelEvents()
setSupportActionBar(toolbar)
supportActionBar?.title = null
// dismiss it at orientation change
val selectLabelDialog =
supportFragmentManager.findFragmentByTag(DIALOG_SELECT_LABEL_TAG) as DialogFragment?
selectLabelDialog?.dismiss()
if (!BuildConfig.F_DROID) {
// Monitor launch times and interval from installation
RateThisApp.onCreate(this)
// If the condition is satisfied, "Rate this app" dialog will be shown
RateThisApp.showRateDialogIfNeeded(this)
}
}
override fun showSnackBar(@StringRes resourceId: Int) {
if (this::binding.isInitialized) {
Snackbar.make(binding.root, getString(resourceId), Snackbar.LENGTH_LONG)
.setAnchorView(toolbar).show()
}
}
/**
* Shows the tutorial snackbars
*/
private fun showTutorialSnackbars() {
val messageSize = 4
val i = preferenceHelper.lastIntroStep
if (i < messageSize) {
val messages = listOf(
getString(R.string.tutorial_tap),
getString(R.string.tutorial_swipe_left),
getString(R.string.tutorial_swipe_up),
getString(R.string.tutorial_swipe_down)
)
val animations = listOf(
AnimationUtils.loadAnimation(applicationContext, R.anim.tutorial_tap),
AnimationUtils.loadAnimation(applicationContext, R.anim.tutorial_swipe_right),
AnimationUtils.loadAnimation(applicationContext, R.anim.tutorial_swipe_up),
AnimationUtils.loadAnimation(applicationContext, R.anim.tutorial_swipe_down)
)
tutorialDot.visibility = View.VISIBLE
tutorialDot.animate().translationX(0f).translationY(0f)
tutorialDot.clearAnimation()
tutorialDot.animation = animations[preferenceHelper.lastIntroStep]
val s = Snackbar.make(
toolbar,
messages[preferenceHelper.lastIntroStep],
Snackbar.LENGTH_INDEFINITE
)
.setAction("OK") {
val nextStep = i + 1
preferenceHelper.lastIntroStep = nextStep
showTutorialSnackbars()
}
.setAnchorView(toolbar)
s.behavior = object : BaseTransientBottomBar.Behavior() {
override fun canSwipeDismissView(child: View): Boolean {
return false
}
}
s.show()
} else {
tutorialDot.animate().translationX(0f).translationY(0f)
tutorialDot.clearAnimation()
tutorialDot.visibility = View.GONE
}
}
@SuppressLint("ClickableViewAccessibility")
private fun setupTimeLabelEvents() {
timeView.setOnTouchListener(object : OnSwipeTouchListener(this@TimerActivity) {
public override fun onSwipeRight(view: View) {
onSkipSession()
}
public override fun onSwipeLeft(view: View) {
onSkipSession()
}
public override fun onSwipeBottom(view: View) {
onStopSession()
if (preferenceHelper.isScreensaverEnabled()) {
recreate()
}
}
public override fun onSwipeTop(view: View) {
if (currentSession.timerState.value !== TimerState.INACTIVE) {
onAdd60SecondsButtonClick()
}
}
public override fun onClick(view: View) {
onStartButtonClick(view)
}
public override fun onLongClick(view: View) {
val settingsIntent = Intent(this@TimerActivity, SettingsActivity::class.java)
startActivity(settingsIntent)
}
public override fun onPress(view: View) {
timeView.startAnimation(
AnimationUtils.loadAnimation(
applicationContext, R.anim.scale_reversed
)
)
}
public override fun onRelease(view: View) {
timeView.startAnimation(
AnimationUtils.loadAnimation(
applicationContext, R.anim.scale
)
)
if (currentSession.timerState.value === TimerState.PAUSED) {
lifecycleScope.launch {
delay(300)
timeView.startAnimation(
AnimationUtils.loadAnimation(applicationContext, R.anim.blink)
)
}
}
}
})
}
private fun onSkipSession() {
if (currentSession.timerState.value !== TimerState.INACTIVE) {
onSkipButtonClick()
}
}
private fun onStopSession() {
if (currentSession.timerState.value !== TimerState.INACTIVE) {
onStopButtonClick()
}
}
override fun onAttachedToWindow() {
window.addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
}
override fun onPause() {
super.onPause()
mainViewModel.isActive = false
}
override fun onResume() {
super.onResume()
removeNotification(applicationContext)
mainViewModel.isActive = true
if (mainViewModel.showFinishDialog) {
showFinishedSessionUI()
}
// initialize notification channels on the first run
if (preferenceHelper.isFirstRun()) {
NotificationHelper(this)
}
// this is to refresh the current status icon color
invalidateOptionsMenu()
val pref = PreferenceManager.getDefaultSharedPreferences(this)
pref.registerOnSharedPreferenceChangeListener(this)
toggleKeepScreenOn(preferenceHelper.isScreenOnEnabled())
toggleFullscreenMode()
showTutorialSnackbars()
setTimeLabelColor()
blackCover.animate().alpha(0f).duration = 500
// the only reason we're doing this here is because a FinishSessionEvent
// comes together with a "bring activity on top"
if (preferenceHelper.isFlashingNotificationEnabled() && mainViewModel.enableFlashingNotification) {
whiteCover.visibility = View.VISIBLE
if (preferenceHelper.isAutoStartBreak() && (currentSessionType === SessionType.BREAK || currentSessionType === SessionType.LONG_BREAK)
|| preferenceHelper.isAutoStartWork() && currentSessionType === SessionType.WORK
) {
startFlashingNotificationShort()
} else {
startFlashingNotification()
}
}
}
override fun onDestroy() {
val pref = PreferenceManager.getDefaultSharedPreferences(this)
pref.unregisterOnSharedPreferenceChangeListener(this)
EventBus.getDefault().unregister(this)
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val menuInflater = menuInflater
menuInflater.inflate(R.menu.menu_main, menu)
val batteryButton = menu.findItem(R.id.action_battery_optimization)
batteryButton.isVisible = !isIgnoringBatteryOptimizations(this)
labelButton = menu.findItem(R.id.action_current_label).also {
it.icon.setColorFilter(
ThemeHelper.getColor(this, ThemeHelper.COLOR_INDEX_ALL_LABELS),
PorterDuff.Mode.SRC_ATOP
)
}
//TODO: move this to onResume
setupEvents()
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
val bottomNavigationDrawerFragment = BottomNavigationDrawerFragment()
bottomNavigationDrawerFragment.show(
supportFragmentManager,
bottomNavigationDrawerFragment.tag
)
}
R.id.action_battery_optimization -> showBatteryOptimizationDialog()
R.id.action_current_label -> showEditLabelDialog()
R.id.action_sessions_counter -> {
AlertDialog.Builder(this)
.setTitle(R.string.action_reset_counter_title)
.setMessage(R.string.action_reset_counter)
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
sessionViewModel.deleteSessionsFinishedAfter(startOfTodayMillis() +
preferenceHelper.getStartOfDayDeltaMillis())
preferenceHelper.resetCurrentStreak()
}
.setNegativeButton(android.R.string.cancel) { _: DialogInterface?, _: Int -> }
.show()
return true
}
}
return super.onOptionsItemSelected(item)
}
@SuppressLint("BatteryLife")
private fun showBatteryOptimizationDialog() {
val intent = Intent()
intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
intent.data = Uri.parse("package:" + this.packageName)
startActivity(intent)
}
private fun setupEvents() {
currentSession.duration.observe(
this,
{ millis: Long -> updateTimeLabel(millis) })
currentSession.sessionType.observe(this, { sessionType: SessionType ->
currentSessionType = sessionType
setupLabelView()
setTimeLabelColor()
})
currentSession.timerState.observe(this, { timerState: TimerState ->
when {
timerState === TimerState.INACTIVE -> {
setupLabelView()
setTimeLabelColor()
lifecycleScope.launch {
delay(300)
timeView.clearAnimation()
}
}
timerState === TimerState.PAUSED -> {
lifecycleScope.launch {
delay(300)
timeView.startAnimation(
AnimationUtils.loadAnimation(applicationContext, R.anim.blink)
)
}
}
else -> {
lifecycleScope.launch {
delay(300)
timeView.clearAnimation()
}
}
}
})
}
private val currentSession: CurrentSession
get() = currentSessionManager.currentSession
@SuppressLint("WrongConstant")
override fun onBackPressed() {
if (currentSession.timerState.value !== TimerState.INACTIVE) {
moveTaskToBack(true)
} else {
if (backPressedAt + 2000 > System.currentTimeMillis()) {
super.onBackPressed()
} else {
try {
Toast.makeText(
baseContext,
R.string.action_press_back_button,
Toast.LENGTH_SHORT
)
.show()
} catch (th: Throwable) {
// ignoring this exception
}
}
backPressedAt = System.currentTimeMillis()
}
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val alertMenuItem = menu.findItem(R.id.action_sessions_counter)
alertMenuItem.isVisible = false
val sessionsCounterEnabled = preferenceHelper.isSessionsCounterEnabled
if (sessionsCounterEnabled) {
val mSessionsCounter = alertMenuItem.actionView as FrameLayout
sessionsCounterText = mSessionsCounter.findViewById(R.id.view_alert_count_textview)
mSessionsCounter.setOnClickListener { onOptionsItemSelected(alertMenuItem) }
val startOfDayDeltaMillis = preferenceHelper.getStartOfDayDeltaMillis()
sessionViewModel.getAllSessionsUnarchived(
startOfTodayMillis() + startOfDayDeltaMillis,
startOfTomorrowMillis() + startOfDayDeltaMillis
).observe(this, { sessions: List<Session> ->
if (sessionsCounterText != null) {
sessionsCounterText!!.text = sessions.count().toString()
}
alertMenuItem.isVisible = true
})
}
return super.onPrepareOptionsMenu(menu)
}
/**
* Called when an event is posted to the EventBus
* @param o holds the type of the Event
*/
@Subscribe
fun onEventMainThread(o: Any?) {
if (o is FinishWorkEvent) {
if (preferenceHelper.isAutoStartBreak()) {
if (preferenceHelper.isFlashingNotificationEnabled()) {
mainViewModel.enableFlashingNotification = true
}
} else {
mainViewModel.dialogPendingType = SessionType.WORK
showFinishedSessionUI()
}
} else if (o is FinishBreakEvent || o is FinishLongBreakEvent) {
if (preferenceHelper.isAutoStartWork()) {
if (preferenceHelper.isFlashingNotificationEnabled()) {
mainViewModel.enableFlashingNotification = true
}
} else {
mainViewModel.dialogPendingType = SessionType.BREAK
showFinishedSessionUI()
}
} else if (o is StartSessionEvent) {
if (sessionFinishedDialog != null) {
sessionFinishedDialog!!.dismissAllowingStateLoss()
}
mainViewModel.showFinishDialog = false
if (!preferenceHelper.isAutoStartBreak() && !preferenceHelper.isAutoStartWork()) {
stopFlashingNotification()
}
} else if (o is OneMinuteLeft) {
if (preferenceHelper.isFlashingNotificationEnabled()) {
startFlashingNotificationShort()
}
}
}
private fun updateTimeLabel(millis: Long) {
var seconds = TimeUnit.MILLISECONDS.toSeconds(millis)
val minutes = TimeUnit.SECONDS.toMinutes(seconds)
seconds -= minutes * 60
val currentFormattedTick: String
val isMinutesStyle =
preferenceHelper.timerStyle == resources.getString(R.string.pref_timer_style_minutes_value)
currentFormattedTick = if (isMinutesStyle) {
TimeUnit.SECONDS.toMinutes(minutes * 60 + seconds + 59).toString()
} else {
((if (minutes > 9) minutes else "0$minutes")
.toString() + ":"
+ if (seconds > 9) seconds else "0$seconds")
}
timeView!!.text = currentFormattedTick
Log.v(TAG, "drawing the time label.")
if (preferenceHelper.isScreensaverEnabled() && seconds == 1L && currentSession.timerState.value !== TimerState.PAUSED) {
teleportTimeView()
}
}
private fun start(sessionType: SessionType) {
var startIntent = Intent()
when (currentSession.timerState.value) {
TimerState.INACTIVE -> startIntent = IntentWithAction(
this@TimerActivity, TimerService::class.java,
Constants.ACTION.START, sessionType
)
TimerState.ACTIVE, TimerState.PAUSED -> startIntent = IntentWithAction(
this@TimerActivity,
TimerService::class.java,
Constants.ACTION.TOGGLE
)
else -> Log.wtf(TAG, "Invalid timer state.")
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(startIntent)
} else {
startService(startIntent)
}
}
private fun stop() {
val stopIntent: Intent =
IntentWithAction(this@TimerActivity, TimerService::class.java, Constants.ACTION.STOP)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(stopIntent)
} else {
startService(stopIntent)
}
whiteCover!!.visibility = View.GONE
whiteCover!!.clearAnimation()
}
private fun add60Seconds() {
val stopIntent: Intent = IntentWithAction(
this@TimerActivity,
TimerService::class.java,
Constants.ACTION.ADD_SECONDS
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(stopIntent)
} else {
startService(stopIntent)
}
}
private fun showEditLabelDialog() {
val fragmentManager = supportFragmentManager
SelectLabelDialog.newInstance(
this,
preferenceHelper.currentSessionLabel.title,
isExtendedVersion = false,
showProfileSelection = true
)
.show(fragmentManager, DIALOG_SELECT_LABEL_TAG)
}
private fun showFinishedSessionUI() {
if (mainViewModel.isActive) {
mainViewModel.showFinishDialog = false
mainViewModel.enableFlashingNotification = true
Log.i(TAG, "Showing the finish dialog.")
sessionFinishedDialog = FinishedSessionDialog.newInstance(this)
.also { it.show(supportFragmentManager, TAG) }
} else {
mainViewModel.showFinishDialog = true
mainViewModel.enableFlashingNotification = false
}
}
private fun toggleFullscreenMode() {
if (preferenceHelper.isFullscreenEnabled()) {
if (fullscreenHelper == null) {
fullscreenHelper = FullscreenHelper(findViewById(R.id.main), supportActionBar)
} else {
fullscreenHelper!!.hide()
}
} else {
if (fullscreenHelper != null) {
fullscreenHelper!!.disable()
fullscreenHelper = null
}
}
}
private fun delayToggleFullscreenMode() {
lifecycleScope.launch {
delay(300)
toggleFullscreenMode()
}
}
private fun toggleKeepScreenOn(enabled: Boolean) {
if (enabled) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
when (key) {
PreferenceHelper.WORK_DURATION -> if (currentSession.timerState.value
=== TimerState.INACTIVE
) {
currentSession.setDuration(
TimeUnit.MINUTES.toMillis(
preferenceHelper.getSessionDuration(SessionType.WORK)
)
)
}
PreferenceHelper.ENABLE_SCREEN_ON -> toggleKeepScreenOn(preferenceHelper.isScreenOnEnabled())
PreferenceHelper.AMOLED -> {
recreate()
if (!preferenceHelper.isScreensaverEnabled()) {
recreate()
}
}
PreferenceHelper.ENABLE_SCREENSAVER_MODE -> if (!preferenceHelper.isScreensaverEnabled()) {
recreate()
}
else -> {
}
}
}
private fun setupLabelView() {
val label = preferenceHelper.currentSessionLabel
if (isInvalidLabel(label)) {
labelChip!!.visibility = View.GONE
labelButton!!.isVisible = true
val color = ThemeHelper.getColor(this, ThemeHelper.COLOR_INDEX_ALL_LABELS)
labelButton!!.icon.setColorFilter(
color, PorterDuff.Mode.SRC_ATOP
)
} else {
val color = ThemeHelper.getColor(this, label.colorId)
if (preferenceHelper.showCurrentLabel()) {
labelButton!!.isVisible = false
labelChip!!.visibility = View.VISIBLE
labelChip!!.text = label.title
labelChip!!.chipBackgroundColor = ColorStateList.valueOf(color)
} else {
labelChip!!.visibility = View.GONE
labelButton!!.isVisible = true
labelButton!!.icon.setColorFilter(
color, PorterDuff.Mode.SRC_ATOP
)
}
}
}
private fun isInvalidLabel(label: Label): Boolean {
return label.title == "" || label.title == getString(R.string.label_unlabeled)
}
private fun setTimeLabelColor() {
val label = preferenceHelper.currentSessionLabel
if (timeView != null) {
if (currentSessionType === SessionType.BREAK || currentSessionType === SessionType.LONG_BREAK) {
timeView!!.setTextColor(ThemeHelper.getColor(this, ThemeHelper.COLOR_INDEX_BREAK))
return
}
if (!isInvalidLabel(label)) {
timeView!!.setTextColor(ThemeHelper.getColor(this, label.colorId))
} else {
timeView!!.setTextColor(
ThemeHelper.getColor(
this,
ThemeHelper.COLOR_INDEX_UNLABELED
)
)
}
}
}
override fun onLabelSelected(label: Label) {
currentSession.setLabel(label.title)
preferenceHelper.currentSessionLabel = label
setupLabelView()
setTimeLabelColor()
}
private fun teleportTimeView() {
val maxY = boundsView.height - timeView.height
if (maxY > 0) {
val r = Random()
val newY = r.nextInt(maxY)
timeView.animate().y(newY.toFloat()).duration = 100
}
}
override fun onFinishedSessionDialogPositiveButtonClick(sessionType: SessionType) {
if (sessionType === SessionType.WORK) {
start(SessionType.BREAK)
} else {
start(SessionType.WORK)
}
delayToggleFullscreenMode()
stopFlashingNotification()
}
override fun onFinishedSessionDialogNeutralButtonClick(sessionType: SessionType) {
EventBus.getDefault().post(ClearNotificationEvent())
delayToggleFullscreenMode()
stopFlashingNotification()
}
private fun startFlashingNotification() {
whiteCover!!.visibility = View.VISIBLE
whiteCover!!.startAnimation(
AnimationUtils.loadAnimation(
applicationContext, R.anim.blink_screen
)
)
}
private fun startFlashingNotificationShort() {
whiteCover!!.visibility = View.VISIBLE
val anim = AnimationUtils.loadAnimation(applicationContext, R.anim.blink_screen_3_times)
anim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {
stopFlashingNotification()
}
override fun onAnimationRepeat(animation: Animation) {}
})
whiteCover!!.startAnimation(anim)
}
private fun stopFlashingNotification() {
whiteCover!!.visibility = View.GONE
whiteCover.clearAnimation()
mainViewModel.enableFlashingNotification = false
}
companion object {
private val TAG = TimerActivity::class.java.simpleName
private const val DIALOG_SELECT_LABEL_TAG = "dialogSelectLabel"
}
} | apache-2.0 | d697d5d0bed200c855bffaa8eae3a2b4 | 36.973684 | 146 | 0.615999 | 5.315208 | false | false | false | false |
wiltonlazary/kotlin-native | build-tools/src/main/kotlin/org/jetbrains/kotlin/CompileToBitcode.kt | 1 | 4320 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin
import org.gradle.api.Action
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.jetbrains.kotlin.konan.target.Family
import org.jetbrains.kotlin.konan.target.HostManager
import org.jetbrains.kotlin.konan.target.KonanTarget
import java.io.File
import javax.inject.Inject
open class CompileToBitcode @Inject constructor(@InputDirectory val srcRoot: File,
val folderName: String,
val target: String) : DefaultTask() {
enum class Language {
C, CPP
}
val compilerArgs = mutableListOf<String>()
val linkerArgs = mutableListOf<String>()
val excludeFiles = mutableListOf<String>()
var srcDir = File(srcRoot, "cpp")
var headersDir = File(srcRoot, "headers")
var skipLinkagePhase = false
var excludedTargets = mutableListOf<String>()
var language = Language.CPP
private val targetDir by lazy { File(project.buildDir, target) }
val objDir by lazy { File(targetDir, folderName) }
private val KonanTarget.isMINGW
get() = this.family == Family.MINGW
val executable
get() = when (language) {
Language.C -> "clang"
Language.CPP -> "clang++"
}
val compilerFlags: List<String>
get() {
val commonFlags = listOf("-c", "-emit-llvm", "-I$headersDir")
val languageFlags = when (language) {
Language.C ->
// Used flags provided by original build of allocator C code.
listOf("-std=gnu11", "-O3", "-Wall", "-Wextra", "-Wno-unknown-pragmas",
"-Werror", "-ftls-model=initial-exec", "-Wno-unused-function")
Language.CPP ->
listOfNotNull("-std=c++14", "-Werror", "-O2",
"-Wall", "-Wextra",
"-Wno-unused-parameter", // False positives with polymorphic functions.
"-Wno-unused-function", // TODO: Enable this warning when we have C++ runtime tests.
"-fPIC".takeIf { !HostManager().targetByName(target).isMINGW })
}
return commonFlags + languageFlags + compilerArgs
}
val inputFiles: Iterable<File>
get() {
val srcFilesPatterns =
when (language) {
Language.C -> listOf("**/*.c")
Language.CPP -> listOf("**/*.cpp", "**/*.mm")
}
return project.fileTree(srcDir) {
it.include(srcFilesPatterns)
it.exclude(excludeFiles)
}.files
}
@OutputFile
val outFile = File(targetDir, "${folderName}.bc")
@TaskAction
fun compile() {
if (target in excludedTargets) return
objDir.mkdirs()
val plugin = project.convention.getPlugin(ExecClang::class.java)
plugin.execKonanClang(target, Action {
it.workingDir = objDir
it.executable = executable
it.args = compilerFlags + inputFiles.map { it.absolutePath }
})
if (!skipLinkagePhase) {
project.exec {
val llvmDir = project.findProperty("llvmDir")
it.executable = "$llvmDir/bin/llvm-link"
it.args = listOf("-o", outFile.absolutePath) + linkerArgs +
project.fileTree(objDir) {
it.include("**/*.bc")
}.files.map { it.absolutePath }
}
}
}
}
| apache-2.0 | 2db66dbfcd473631fa7d8a5800d88d7a | 35.923077 | 113 | 0.580324 | 4.620321 | false | false | false | false |
nemerosa/ontrack | ontrack-ui-graphql/src/test/java/net/nemerosa/ontrack/graphql/support/GQLScalarJSONTest.kt | 1 | 4145 | package net.nemerosa.ontrack.graphql.support
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import graphql.language.*
import net.nemerosa.ontrack.json.asJson
import net.nemerosa.ontrack.test.assertIs
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class GQLScalarJSONTest {
@Test
fun `Parse string value`() {
val json = GQLScalarJSON.INSTANCE.coercing.parseValue("""{"passed":15}""")
assertEquals(
mapOf(
"passed" to 15
).asJson(),
json
)
}
@Test
fun `Parse JSON value`() {
val json = GQLScalarJSON.INSTANCE.coercing.parseValue(
mapOf(
"passed" to 15
).asJson()
)
assertEquals(
mapOf(
"passed" to 15
).asJson(),
json
)
}
@Test
fun `Parse map value`() {
val json = GQLScalarJSON.INSTANCE.coercing.parseValue(
mapOf(
"passed" to 15
)
)
assertEquals(
mapOf(
"passed" to 15
).asJson(),
json
)
}
@Test
fun `Parse literal object`() {
val input = ObjectValue(
listOf(
ObjectField("value", IntValue(30.toBigInteger()))
)
)
val value = GQLScalarJSON.INSTANCE.coercing.parseLiteral(input)
assertIs<ObjectNode>(value) {
assertEquals(30, it.path("value").asInt())
}
}
@Test
fun `Parse literal array`() {
val input = ArrayValue(
listOf(
StringValue("one"),
StringValue("two")
)
)
val value = GQLScalarJSON.INSTANCE.coercing.parseLiteral(input)
assertIs<ArrayNode>(value) {
assertEquals(
listOf("one", "two"),
it.map { it.asText() }
)
}
}
@Test
fun `JSON text`() {
// Data as string
val data = "Some text"
// Serialization
val json = GQLScalarJSON.INSTANCE.coercing.serialize(data) as JsonNode
// Checks the data
assertEquals("Some text", json.asText())
}
@Test
fun `Obfuscation of password`() {
// Data with password
val data = SampleConfig("user", "secret")
// As JSON scalar
val json = GQLScalarJSON.INSTANCE.coercing.serialize(data) as JsonNode
// Checks the data
assertEquals("user", json["user"].asText())
assertTrue(json["password"].isNull, "Password field set to null")
}
@Test
fun `Deep obfuscation of password in objects`() {
// Data with password
val data = SampleData("value", SampleConfig("user", "secret"))
// As JSON scaler
val json = GQLScalarJSON.INSTANCE.coercing.serialize(data) as JsonNode
// Checks the data
assertEquals("value", json["value"].asText())
assertEquals("user", json["config"]["user"].asText())
assertTrue(json["config"]["password"].isNull, "Password field set to null")
}
@Test
fun `Deep obfuscation of password in arrays`() {
// Data with password
val data = SampleArray(
"value",
listOf(
SampleConfig("user", "secret")
)
)
// As JSON scaler
val json = GQLScalarJSON.INSTANCE.coercing.serialize(data) as JsonNode
// Checks the data
assertEquals("value", json["value"].asText())
assertEquals("user", json["configs"][0]["user"].asText())
assertTrue(json["configs"][0]["password"].isNull, "Password set to null")
}
data class SampleConfig(
val user: String,
val password: String
)
data class SampleData(
val value: String,
val config: SampleConfig
)
data class SampleArray(
val value: String,
val configs: List<SampleConfig>
)
} | mit | ed829b14de547ef0ba26ed0017af91c4 | 26.456954 | 83 | 0.550302 | 4.595344 | false | true | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/jobs/OfflineSyncWork.kt | 1 | 5987 | /*
* Nextcloud Android client application
*
* @author Mario Danic
* @author Chris Narkiewicz
* Copyright (C) 2018 Mario Danic
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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.nextcloud.client.jobs
import android.content.ContentResolver
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.network.ConnectivityService
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.lib.resources.files.CheckEtagRemoteOperation
import com.owncloud.android.operations.SynchronizeFileOperation
import com.owncloud.android.utils.FileStorageUtils
import java.io.File
@Suppress("LongParameterList") // Legacy code
class OfflineSyncWork constructor(
private val context: Context,
params: WorkerParameters,
private val contentResolver: ContentResolver,
private val userAccountManager: UserAccountManager,
private val connectivityService: ConnectivityService,
private val powerManagementService: PowerManagementService
) : Worker(context, params) {
companion object {
const val TAG = "OfflineSyncJob"
}
override fun doWork(): Result {
if (!powerManagementService.isPowerSavingEnabled) {
val users = userAccountManager.allUsers
for (user in users) {
val storageManager = FileDataStorageManager(user, contentResolver)
val ocRoot = storageManager.getFileByPath(OCFile.ROOT_PATH)
if (ocRoot.storagePath == null) {
break
}
recursive(File(ocRoot.storagePath), storageManager, user)
}
}
return Result.success()
}
private fun recursive(folder: File, storageManager: FileDataStorageManager, user: User) {
val downloadFolder = FileStorageUtils.getSavePath(user.accountName)
val folderName = folder.absolutePath.replaceFirst(downloadFolder.toRegex(), "") + OCFile.PATH_SEPARATOR
Log_OC.d(TAG, "$folderName: enter")
// exit
if (folder.listFiles() == null) {
return
}
val updatedEtag = checkEtagChanged(folderName, storageManager, user) ?: return
// iterate over downloaded files
val files = folder.listFiles { obj: File -> obj.isFile }
if (files != null) {
for (file in files) {
val ocFile = storageManager.getFileByLocalPath(file.path)
val synchronizeFileOperation = SynchronizeFileOperation(
ocFile?.remotePath,
user,
true,
context,
storageManager
)
synchronizeFileOperation.execute(context)
}
}
// recursive into folder
val subfolders = folder.listFiles { obj: File -> obj.isDirectory }
if (subfolders != null) {
for (subfolder in subfolders) {
recursive(subfolder, storageManager, user)
}
}
// update eTag
@Suppress("TooGenericExceptionCaught") // legacy code
try {
val ocFolder = storageManager.getFileByPath(folderName)
ocFolder.etagOnServer = updatedEtag
storageManager.saveFile(ocFolder)
} catch (e: Exception) {
Log_OC.e(TAG, "Failed to update etag on " + folder.absolutePath, e)
}
}
/**
* @return new etag if changed, `null` otherwise
*/
private fun checkEtagChanged(folderName: String, storageManager: FileDataStorageManager, user: User): String? {
val ocFolder = storageManager.getFileByPath(folderName)
Log_OC.d(TAG, folderName + ": currentEtag: " + ocFolder.etag)
// check for etag change, if false, skip
val checkEtagOperation = CheckEtagRemoteOperation(
ocFolder.remotePath,
ocFolder.etagOnServer
)
val result = checkEtagOperation.execute(user, context)
return when (result.code) {
ResultCode.ETAG_UNCHANGED -> {
Log_OC.d(TAG, "$folderName: eTag unchanged")
null
}
ResultCode.FILE_NOT_FOUND -> {
val removalResult = storageManager.removeFolder(ocFolder, true, true)
if (!removalResult) {
Log_OC.e(TAG, "removal of " + ocFolder.storagePath + " failed: file not found")
}
null
}
ResultCode.ETAG_CHANGED -> {
Log_OC.d(TAG, "$folderName: eTag changed")
result.data[0] as String
}
else -> if (connectivityService.isInternetWalled) {
Log_OC.d(TAG, "No connectivity, skipping sync")
null
} else {
Log_OC.d(TAG, "$folderName: eTag changed")
result.data[0] as String
}
}
}
}
| gpl-2.0 | f4036a6a1a68f2b51d795c5d974cfa65 | 38.649007 | 115 | 0.640555 | 4.828226 | false | false | false | false |
samtstern/quickstart-android | auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MultiFactorEnrollActivity.kt | 1 | 5632 | package com.google.firebase.quickstart.auth.kotlin
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.google.firebase.FirebaseException
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthOptions
import com.google.firebase.auth.PhoneAuthProvider
import com.google.firebase.auth.PhoneMultiFactorGenerator
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.ActivityPhoneAuthBinding
import com.google.firebase.quickstart.auth.java.BaseActivity
import java.util.concurrent.TimeUnit
/**
* Activity that allows the user to enroll second factors.
*/
class MultiFactorEnrollActivity : BaseActivity(), View.OnClickListener {
private lateinit var binding: ActivityPhoneAuthBinding
private var lastCodeVerificationId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPhoneAuthBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.titleText.text = "SMS as a Second Factor"
binding.status.visibility = View.GONE
binding.detail.visibility = View.GONE
binding.buttonStartVerification.setOnClickListener(this)
binding.buttonVerifyPhone.setOnClickListener(this)
}
private fun onClickVerifyPhoneNumber() {
val phoneNumber = binding.fieldPhoneNumber.text.toString()
val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
// Instant-validation has been disabled (see requireSmsValidation below).
// Auto-retrieval has also been disabled (timeout is set to 0).
// This should never be triggered.
throw RuntimeException(
"onVerificationCompleted() triggered with instant-validation and auto-retrieval disabled.")
}
override fun onCodeSent(
verificationId: String,
token: PhoneAuthProvider.ForceResendingToken
) {
Log.d(TAG, "onCodeSent:$verificationId")
Toast.makeText(
this@MultiFactorEnrollActivity, "SMS code has been sent", Toast.LENGTH_SHORT)
.show()
lastCodeVerificationId = verificationId
}
override fun onVerificationFailed(e: FirebaseException) {
Log.w(TAG, "onVerificationFailed ", e)
Toast.makeText(
this@MultiFactorEnrollActivity, "Verification failed: " + e.message, Toast.LENGTH_SHORT)
.show()
}
}
Firebase.auth
.currentUser!!
.multiFactor
.session
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val phoneAuthOptions = PhoneAuthOptions.newBuilder()
.setPhoneNumber(phoneNumber) // A timeout of 0 disables SMS-auto-retrieval.
.setTimeout(0L, TimeUnit.SECONDS)
.setMultiFactorSession(task.result!!)
.setCallbacks(callbacks) // Disable instant-validation.
.requireSmsValidation(true)
.build()
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
} else {
Toast.makeText(
this@MultiFactorEnrollActivity,
"Failed to get session: " + task.exception, Toast.LENGTH_SHORT)
.show()
}
}
}
private fun onClickSignInWithPhoneNumber() {
val smsCode = binding.fieldVerificationCode.text.toString()
if (TextUtils.isEmpty(smsCode)) {
return
}
val credential = PhoneAuthProvider.getCredential(lastCodeVerificationId!!, smsCode)
enrollWithPhoneAuthCredential(credential)
}
private fun enrollWithPhoneAuthCredential(credential: PhoneAuthCredential) {
Firebase.auth
.currentUser!!
.multiFactor
.enroll(PhoneMultiFactorGenerator.getAssertion(credential), /* displayName= */null)
.addOnSuccessListener {
Toast.makeText(
this@MultiFactorEnrollActivity,
"MFA enrollment was successful",
Toast.LENGTH_LONG)
.show()
finish()
}
.addOnFailureListener { e ->
Log.d(TAG, "MFA failure", e)
Toast.makeText(
this@MultiFactorEnrollActivity,
"MFA enrollment was unsuccessful. $e",
Toast.LENGTH_LONG)
.show()
}
}
override fun onClick(v: View) {
when (v.id) {
R.id.buttonStartVerification -> onClickVerifyPhoneNumber()
R.id.buttonVerifyPhone -> onClickSignInWithPhoneNumber()
}
}
companion object {
private const val TAG = "PhoneAuthActivity"
}
}
| apache-2.0 | 09747f240da92e4f9a173871e6f38f87 | 41.345865 | 115 | 0.589489 | 5.415385 | false | false | false | false |
ivan-osipov/Clabo | src/main/kotlin/com/github/ivan_osipov/clabo/api/output/dto/UpdatesParams.kt | 1 | 620 | package com.github.ivan_osipov.clabo.api.output.dto
data class UpdatesParams(var offset: Long? = null,
var limit: Short? = null,
var timeout: Long? = null,
var allowedUpdates: List<String>? = null) : OutputParams {
override val queryId: String
get() = Queries.GET_UPDATES
override fun toListOfPairs() : MutableList<Pair<String,*>> {
return mutableListOf(
"offset" to offset,
"limit" to limit,
"timeout" to timeout,
"allowed_updates" to allowedUpdates
)
}
} | apache-2.0 | a20bb8f60771fb008d1c95a43feb7003 | 30.05 | 78 | 0.548387 | 4.525547 | false | false | false | false |
Jire/Abendigo | src/main/kotlin/org/abendigo/plugin/csgo/TriggerBotPlugin.kt | 1 | 1382 | package org.abendigo.plugin.csgo
import org.abendigo.DEBUG
import org.abendigo.csgo.Client.clientDLL
import org.abendigo.csgo.Client.enemies
import org.abendigo.csgo.Me
import org.abendigo.csgo.offsets.m_dwForceAttack
import org.abendigo.plugin.sleep
import org.abendigo.util.random
object TriggerBotPlugin : InGamePlugin(name = "Trigger Bot", duration = 32) {
override val author = "Jire"
override val description = "Fires when your crosshair is on an enemy"
private const val LEGIT = true
private const val MIN_SCOPE_DURATION = 85
private const val MAX_SCOPE_DURATION = 160
private const val BOLT_ACTION_ONLY = true
private var scopeDuration = 0
override fun cycle() {
val scoped = +Me.inScope
if (!scoped) {
scopeDuration = 0
return
}
scopeDuration += duration
if (scopeDuration < random(MIN_SCOPE_DURATION, MAX_SCOPE_DURATION)) return
try {
val weapon = (+Me().weapon).type!!
if (!weapon.sniper || (BOLT_ACTION_ONLY && !weapon.boltAction)) return
} catch (t: Throwable) {
if (DEBUG) t.printStackTrace()
}
for ((i, e) in enemies) if (e.address == +Me.targetAddress) {
if (LEGIT) {
val spotted = +e.spotted
sleep(random(duration, if (spotted) duration * 3 else duration * 5))
}
clientDLL[m_dwForceAttack] = 5.toByte()
sleep(random(duration, duration * 2))
clientDLL[m_dwForceAttack] = 4.toByte()
}
}
} | gpl-3.0 | d5dbd945165689175ead0f5fa82ced0f | 25.09434 | 77 | 0.70767 | 3.228972 | false | false | false | false |
alvarlagerlof/temadagar-android | app/src/main/java/com/alvarlagerlof/temadagarapp/Main/List/Adapter/GridAdapter.kt | 1 | 6837 | package com.alvarlagerlof.temadagarapp.Main.List.Adapter
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.LayoutInflater
import android.view.ViewGroup
import com.alvarlagerlof.temadagarapp.Blur
import com.alvarlagerlof.temadagarapp.Main.List.Object.DayObject
import com.alvarlagerlof.temadagarapp.Main.List.Object.SetupObject
import com.alvarlagerlof.temadagarapp.Main.List.ViewHolder.ViewHolderGrid
import com.alvarlagerlof.temadagarapp.Main.List.ViewHolder.ViewHolderSetup
import com.alvarlagerlof.temadagarapp.R
import com.alvarlagerlof.temadagarapp.Vars
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import com.squareup.picasso.Transformation
import org.jetbrains.anko.sdk25.coroutines.onClick
/**
* Created by alvar on 2017-06-25.
*/
class GridAdapter(private val context: Context,
private val data: ArrayList<Any>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(viewGroup.context)
when (i) {
TYPE_SETUP -> return ViewHolderSetup(inflater.inflate(R.layout.item_setup, viewGroup, false))
TYPE_ITEM -> return ViewHolderGrid(inflater.inflate(R.layout.item_grid, viewGroup, false))
}
throw RuntimeException("there is no type that matches the type $i + make sure your using types correctly")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is ViewHolderGrid -> {
val item = data[position] as DayObject
// Set
holder.title.text = item.title
holder.date.text = item.date
/*Glide.with(context)
.asBitmap()
.load(Vars.IMAGE_GRID_SMALL + item.id)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(bitmap: Bitmap, anim: GlideAnimation) {
holder.image.setImageBitmap(bitmap)
Glide.with(context)
.asBitmap()
.load(Vars.IMAGE_GRID + item.id)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(bitmap: Bitmap, anim: GlideAnimation) {
holder.image.setImageBitmap(bitmap)
}
})
}
})
Glide.with(context)
.load(Vars.IMAGE_GRID_SMALL + item.id)
.bitmapTransform(BlurTransformation(context, 25))
.listener(GlidePalette.with(Vars.IMAGE_GRID + item.id)
.use(BitmapPalette.Profile.VIBRANT_DARK)
.intoBackground(holder.card)
.intoBackground(holder.box)
.intoTextColor(holder.title, BitmapPalette.Swatch.TITLE_TEXT_COLOR)
.intoTextColor(holder.date, BitmapPalette.Swatch.BODY_TEXT_COLOR)
.crossfade(true)
)
.into(holder.image)*/
val blurTransformation = object : Transformation {
override fun transform(source: Bitmap): Bitmap? {
val blurred = Blur.fastblur(holder.image.context, source, 10)
source.recycle()
return blurred
}
override fun key(): String {
return "blur()"
}
}
Picasso.with(context)
.load(Vars.IMAGE_GRID_SMALL + item.id) // thumbnail url goes here
.placeholder(R.raw.day_holder)
.transform(blurTransformation)
//.resize(imageViewWidth, imageViewHeight)
.into(holder.image, object : Callback {
override fun onSuccess() {
Picasso.with(context)
.load(Vars.IMAGE_GRID + item.id)
.into(object: com.squareup.picasso.Target {
override fun onBitmapFailed(errorDrawable: Drawable?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
holder.image.setImageBitmap(bitmap)
}
})
}
override fun onError() {}
})
holder.card.setCardBackgroundColor(Color.parseColor(item.color))
holder.box.setBackgroundColor(Color.parseColor(item.color))
holder.itemView.onClick {
// TODO: ADD THIS
}
}
is ViewHolderSetup -> {
val layoutParams = holder.itemView.layoutParams as StaggeredGridLayoutManager.LayoutParams
layoutParams.isFullSpan = true
}
}
}
override fun getItemViewType(position: Int): Int {
when (data[position]) {
is SetupObject -> return TYPE_SETUP
is DayObject -> return TYPE_ITEM
else -> { // Note the block
throw RuntimeException("there is no type that matches the type $data[position] + make sure your using types correctly")
}
}
}
override fun getItemCount(): Int {
return data.count()
}
companion object {
val TYPE_SETUP = 0
val TYPE_ITEM = 1
}
} | mit | c21d9105797ae0821d9b094c37bfd6e3 | 39.461538 | 147 | 0.517332 | 5.404743 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/PublishJobDestinations.kt | 1 | 863 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Contains information about upload/post status on all third party social networks available for publishing.
*
* @param facebook Information about the upload/post on Facebook.
* @param youTube Information about the upload/post on YouTube.
* @param linkedIn Information about the upload/post on LinkedIn.
* @param twitter Information about the upload/post on Twitter.
*/
@JsonClass(generateAdapter = true)
data class PublishJobDestinations(
@Json(name = "facebook")
val facebook: PublishJobDestination? = null,
@Json(name = "youtube")
val youTube: PublishJobDestination? = null,
@Json(name = "linkedin")
val linkedIn: PublishJobDestination? = null,
@Json(name = "twitter")
val twitter: PublishJobDestination? = null
)
| mit | 25d55906c2e321c147061a4124ef3623 | 29.821429 | 109 | 0.742758 | 4.169082 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/gesturehandler/GestureHandler.kt | 2 | 22965 | package versioned.host.exp.exponent.modules.api.components.gesturehandler
import android.view.MotionEvent
import android.view.MotionEvent.PointerCoords
import android.view.MotionEvent.PointerProperties
import android.view.View
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.bridge.WritableArray
import com.facebook.react.uimanager.PixelUtil
import versioned.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerTouchEvent
import java.lang.IllegalStateException
import java.util.*
open class GestureHandler<ConcreteGestureHandlerT : GestureHandler<ConcreteGestureHandlerT>> {
private val trackedPointerIDs = IntArray(MAX_POINTERS_COUNT)
private var trackedPointersIDsCount = 0
var tag = 0
var view: View? = null
private set
var state = STATE_UNDETERMINED
private set
var x = 0f
private set
var y = 0f
private set
var isWithinBounds = false
private set
var isEnabled = true
private set
var usesDeviceEvents = false
var changedTouchesPayload: WritableArray? = null
private set
var allTouchesPayload: WritableArray? = null
private set
var touchEventType = RNGestureHandlerTouchEvent.EVENT_UNDETERMINED
private set
var trackedPointersCount = 0
private set
private val trackedPointers: Array<PointerData?> = Array(MAX_POINTERS_COUNT) { null }
var needsPointerData = false
private var hitSlop: FloatArray? = null
var eventCoalescingKey: Short = 0
private set
var lastAbsolutePositionX = 0f
private set
var lastAbsolutePositionY = 0f
private set
private var manualActivation = false
private var lastEventOffsetX = 0f
private var lastEventOffsetY = 0f
private var shouldCancelWhenOutside = false
var numberOfPointers = 0
private set
private var orchestrator: GestureHandlerOrchestrator? = null
private var onTouchEventListener: OnTouchEventListener? = null
private var interactionController: GestureHandlerInteractionController? = null
@Suppress("UNCHECKED_CAST")
protected fun self(): ConcreteGestureHandlerT = this as ConcreteGestureHandlerT
protected inline fun applySelf(block: ConcreteGestureHandlerT.() -> Unit): ConcreteGestureHandlerT =
self().apply { block() }
// set and accessed only by the orchestrator
var activationIndex = 0
// set and accessed only by the orchestrator
var isActive = false
// set and accessed only by the orchestrator
var isAwaiting = false
open fun dispatchStateChange(newState: Int, prevState: Int) {
onTouchEventListener?.onStateChange(self(), newState, prevState)
}
open fun dispatchHandlerUpdate(event: MotionEvent) {
onTouchEventListener?.onHandlerUpdate(self(), event)
}
open fun dispatchTouchEvent() {
if (changedTouchesPayload != null) {
onTouchEventListener?.onTouchEvent(self())
}
}
open fun resetConfig() {
needsPointerData = false
manualActivation = false
shouldCancelWhenOutside = false
isEnabled = true
hitSlop = null
}
fun hasCommonPointers(other: GestureHandler<*>): Boolean {
for (i in trackedPointerIDs.indices) {
if (trackedPointerIDs[i] != -1 && other.trackedPointerIDs[i] != -1) {
return true
}
}
return false
}
fun setShouldCancelWhenOutside(shouldCancelWhenOutside: Boolean): ConcreteGestureHandlerT =
applySelf { this.shouldCancelWhenOutside = shouldCancelWhenOutside }
fun setEnabled(enabled: Boolean): ConcreteGestureHandlerT = applySelf {
// Don't cancel handler when not changing the value of the isEnabled, executing it always caused
// handlers to be cancelled on re-render because that's the moment when the config is updated.
// If the enabled prop "changed" from true to true the handler would get cancelled.
if (view != null && isEnabled != enabled) {
// If view is set then handler is in "active" state. In that case we want to "cancel" handler
// when it changes enabled state so that it gets cleared from the orchestrator
UiThreadUtil.runOnUiThread { cancel() }
}
isEnabled = enabled
}
fun setManualActivation(manualActivation: Boolean): ConcreteGestureHandlerT =
applySelf { this.manualActivation = manualActivation }
fun setHitSlop(
leftPad: Float,
topPad: Float,
rightPad: Float,
bottomPad: Float,
width: Float,
height: Float,
): ConcreteGestureHandlerT = applySelf {
if (hitSlop == null) {
hitSlop = FloatArray(6)
}
hitSlop!![HIT_SLOP_LEFT_IDX] = leftPad
hitSlop!![HIT_SLOP_TOP_IDX] = topPad
hitSlop!![HIT_SLOP_RIGHT_IDX] = rightPad
hitSlop!![HIT_SLOP_BOTTOM_IDX] = bottomPad
hitSlop!![HIT_SLOP_WIDTH_IDX] = width
hitSlop!![HIT_SLOP_HEIGHT_IDX] = height
require(!(hitSlopSet(width) && hitSlopSet(leftPad) && hitSlopSet(rightPad))) { "Cannot have all of left, right and width defined" }
require(!(hitSlopSet(width) && !hitSlopSet(leftPad) && !hitSlopSet(rightPad))) { "When width is set one of left or right pads need to be defined" }
require(!(hitSlopSet(height) && hitSlopSet(bottomPad) && hitSlopSet(topPad))) { "Cannot have all of top, bottom and height defined" }
require(!(hitSlopSet(height) && !hitSlopSet(bottomPad) && !hitSlopSet(topPad))) { "When height is set one of top or bottom pads need to be defined" }
}
fun setHitSlop(padding: Float): ConcreteGestureHandlerT {
return setHitSlop(padding, padding, padding, padding, HIT_SLOP_NONE, HIT_SLOP_NONE)
}
fun setInteractionController(controller: GestureHandlerInteractionController?): ConcreteGestureHandlerT =
applySelf { interactionController = controller }
fun prepare(view: View?, orchestrator: GestureHandlerOrchestrator?) {
check(!(this.view != null || this.orchestrator != null)) { "Already prepared or hasn't been reset" }
Arrays.fill(trackedPointerIDs, -1)
trackedPointersIDsCount = 0
state = STATE_UNDETERMINED
this.view = view
this.orchestrator = orchestrator
}
private fun findNextLocalPointerId(): Int {
var localPointerId = 0
while (localPointerId < trackedPointersIDsCount) {
var i = 0
while (i < trackedPointerIDs.size) {
if (trackedPointerIDs[i] == localPointerId) {
break
}
i++
}
if (i == trackedPointerIDs.size) {
return localPointerId
}
localPointerId++
}
return localPointerId
}
fun startTrackingPointer(pointerId: Int) {
if (trackedPointerIDs[pointerId] == -1) {
trackedPointerIDs[pointerId] = findNextLocalPointerId()
trackedPointersIDsCount++
}
}
fun stopTrackingPointer(pointerId: Int) {
if (trackedPointerIDs[pointerId] != -1) {
trackedPointerIDs[pointerId] = -1
trackedPointersIDsCount--
}
}
private fun needAdapt(event: MotionEvent): Boolean {
if (event.pointerCount != trackedPointersIDsCount) {
return true
}
for (i in trackedPointerIDs.indices) {
val trackedPointer = trackedPointerIDs[i]
if (trackedPointer != -1 && trackedPointer != i) {
return true
}
}
return false
}
private fun adaptEvent(event: MotionEvent): MotionEvent {
if (!needAdapt(event)) {
return event
}
var action = event.actionMasked
var actionIndex = -1
if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) {
actionIndex = event.actionIndex
val actionPointer = event.getPointerId(actionIndex)
action = if (trackedPointerIDs[actionPointer] != -1) {
if (trackedPointersIDsCount == 1) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_POINTER_DOWN
} else {
MotionEvent.ACTION_MOVE
}
} else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
actionIndex = event.actionIndex
val actionPointer = event.getPointerId(actionIndex)
action = if (trackedPointerIDs[actionPointer] != -1) {
if (trackedPointersIDsCount == 1) MotionEvent.ACTION_UP else MotionEvent.ACTION_POINTER_UP
} else {
MotionEvent.ACTION_MOVE
}
}
initPointerProps(trackedPointersIDsCount)
var count = 0
val oldX = event.x
val oldY = event.y
event.setLocation(event.rawX, event.rawY)
var index = 0
val size = event.pointerCount
while (index < size) {
val origPointerId = event.getPointerId(index)
if (trackedPointerIDs[origPointerId] != -1) {
event.getPointerProperties(index, pointerProps[count])
pointerProps[count]!!.id = trackedPointerIDs[origPointerId]
event.getPointerCoords(index, pointerCoords[count])
if (index == actionIndex) {
action = action or (count shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
}
count++
}
index++
}
// introduced in 1.11.0, remove if crashes are not reported
if (pointerProps.isEmpty() || pointerCoords.isEmpty()) {
throw IllegalStateException("pointerCoords.size=${pointerCoords.size}, pointerProps.size=${pointerProps.size}")
}
val result: MotionEvent
try {
result = MotionEvent.obtain(
event.downTime,
event.eventTime,
action,
count,
pointerProps, /* props are copied and hence it is safe to use static array here */
pointerCoords, /* same applies to coords */
event.metaState,
event.buttonState,
event.xPrecision,
event.yPrecision,
event.deviceId,
event.edgeFlags,
event.source,
event.flags
)
} catch (e: IllegalArgumentException) {
throw AdaptEventException(this, event, e)
}
event.setLocation(oldX, oldY)
result.setLocation(oldX, oldY)
return result
}
// exception to help debug https://github.com/software-mansion/react-native-gesture-handler/issues/1188
class AdaptEventException(
handler: GestureHandler<*>,
event: MotionEvent,
e: IllegalArgumentException
) : Exception(
"""
handler: ${handler::class.simpleName}
state: ${handler.state}
view: ${handler.view}
orchestrator: ${handler.orchestrator}
isEnabled: ${handler.isEnabled}
isActive: ${handler.isActive}
isAwaiting: ${handler.isAwaiting}
trackedPointersCount: ${handler.trackedPointersCount}
trackedPointers: ${handler.trackedPointerIDs.joinToString(separator = ", ")}
while handling event: $event
""".trimIndent(),
e
)
fun handle(origEvent: MotionEvent) {
if (!isEnabled ||
state == STATE_CANCELLED ||
state == STATE_FAILED ||
state == STATE_END ||
trackedPointersIDsCount < 1
) {
return
}
val event = adaptEvent(origEvent)
x = event.x
y = event.y
numberOfPointers = event.pointerCount
isWithinBounds = isWithinBounds(view, x, y)
if (shouldCancelWhenOutside && !isWithinBounds) {
if (state == STATE_ACTIVE) {
cancel()
} else if (state == STATE_BEGAN) {
fail()
}
return
}
lastAbsolutePositionX = GestureUtils.getLastPointerX(event, true)
lastAbsolutePositionY = GestureUtils.getLastPointerY(event, true)
lastEventOffsetX = event.rawX - event.x
lastEventOffsetY = event.rawY - event.y
onHandle(event)
if (event != origEvent) {
event.recycle()
}
}
private fun dispatchTouchDownEvent(event: MotionEvent) {
changedTouchesPayload = null
touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_DOWN
val pointerId = event.getPointerId(event.actionIndex)
val offsetX = event.rawX - event.x
val offsetY = event.rawY - event.y
trackedPointers[pointerId] = PointerData(
pointerId,
event.getX(event.actionIndex),
event.getY(event.actionIndex),
event.getX(event.actionIndex) + offsetX,
event.getY(event.actionIndex) + offsetY,
)
trackedPointersCount++
addChangedPointer(trackedPointers[pointerId]!!)
extractAllPointersData()
dispatchTouchEvent()
}
private fun dispatchTouchUpEvent(event: MotionEvent) {
extractAllPointersData()
changedTouchesPayload = null
touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_UP
val pointerId = event.getPointerId(event.actionIndex)
val offsetX = event.rawX - event.x
val offsetY = event.rawY - event.y
trackedPointers[pointerId] = PointerData(
pointerId,
event.getX(event.actionIndex),
event.getY(event.actionIndex),
event.getX(event.actionIndex) + offsetX,
event.getY(event.actionIndex) + offsetY,
)
addChangedPointer(trackedPointers[pointerId]!!)
trackedPointers[pointerId] = null
trackedPointersCount--
dispatchTouchEvent()
}
private fun dispatchTouchMoveEvent(event: MotionEvent) {
changedTouchesPayload = null
touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_MOVE
val offsetX = event.rawX - event.x
val offsetY = event.rawY - event.y
var pointersAdded = 0
for (i in 0 until event.pointerCount) {
val pointerId = event.getPointerId(i)
val pointer = trackedPointers[pointerId] ?: continue
if (pointer.x != event.getX(i) || pointer.y != event.getY(i)) {
pointer.x = event.getX(i)
pointer.y = event.getY(i)
pointer.absoluteX = event.getX(i) + offsetX
pointer.absoluteY = event.getY(i) + offsetY
addChangedPointer(pointer)
pointersAdded++
}
}
// only data about pointers that have changed their position is sent, it makes no sense to send
// an empty move event (especially when this method is called during down/up event and there is
// only info about one pointer)
if (pointersAdded > 0) {
extractAllPointersData()
dispatchTouchEvent()
}
}
fun updatePointerData(event: MotionEvent) {
if (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_POINTER_DOWN) {
dispatchTouchDownEvent(event)
dispatchTouchMoveEvent(event)
} else if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_POINTER_UP) {
dispatchTouchMoveEvent(event)
dispatchTouchUpEvent(event)
} else if (event.actionMasked == MotionEvent.ACTION_MOVE) {
dispatchTouchMoveEvent(event)
}
}
private fun extractAllPointersData() {
allTouchesPayload = null
for (pointerData in trackedPointers) {
if (pointerData != null) {
addPointerToAll(pointerData)
}
}
}
private fun cancelPointers() {
touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_CANCELLED
changedTouchesPayload = null
extractAllPointersData()
for (pointer in trackedPointers) {
pointer?.let {
addChangedPointer(it)
}
}
trackedPointersCount = 0
trackedPointers.fill(null)
dispatchTouchEvent()
}
private fun addChangedPointer(pointerData: PointerData) {
if (changedTouchesPayload == null) {
changedTouchesPayload = Arguments.createArray()
}
changedTouchesPayload!!.pushMap(createPointerData(pointerData))
}
private fun addPointerToAll(pointerData: PointerData) {
if (allTouchesPayload == null) {
allTouchesPayload = Arguments.createArray()
}
allTouchesPayload!!.pushMap(createPointerData(pointerData))
}
private fun createPointerData(pointerData: PointerData) = Arguments.createMap().apply {
putInt("id", pointerData.pointerId)
putDouble("x", PixelUtil.toDIPFromPixel(pointerData.x).toDouble())
putDouble("y", PixelUtil.toDIPFromPixel(pointerData.y).toDouble())
putDouble("absoluteX", PixelUtil.toDIPFromPixel(pointerData.absoluteX).toDouble())
putDouble("absoluteY", PixelUtil.toDIPFromPixel(pointerData.absoluteY).toDouble())
}
fun consumeChangedTouchesPayload(): WritableArray? {
val result = changedTouchesPayload
changedTouchesPayload = null
return result
}
fun consumeAllTouchesPayload(): WritableArray? {
val result = allTouchesPayload
allTouchesPayload = null
return result
}
private fun moveToState(newState: Int) {
UiThreadUtil.assertOnUiThread()
if (state == newState) {
return
}
// if there are tracked pointers and the gesture is about to end, send event cancelling all pointers
if (trackedPointersCount > 0 && (newState == STATE_END || newState == STATE_CANCELLED || newState == STATE_FAILED)) {
cancelPointers()
}
val oldState = state
state = newState
if (state == STATE_ACTIVE) {
// Generate a unique coalescing-key each time the gesture-handler becomes active. All events will have
// the same coalescing-key allowing EventDispatcher to coalesce RNGestureHandlerEvents when events are
// generated faster than they can be treated by JS thread
eventCoalescingKey = nextEventCoalescingKey++
}
orchestrator!!.onHandlerStateChange(this, newState, oldState)
onStateChange(newState, oldState)
}
fun wantEvents(): Boolean {
return isEnabled &&
state != STATE_FAILED &&
state != STATE_CANCELLED &&
state != STATE_END &&
trackedPointersIDsCount > 0
}
open fun shouldRequireToWaitForFailure(handler: GestureHandler<*>): Boolean {
if (handler === this) {
return false
}
return interactionController?.shouldRequireHandlerToWaitForFailure(this, handler) ?: false
}
fun shouldWaitForHandlerFailure(handler: GestureHandler<*>): Boolean {
if (handler === this) {
return false
}
return interactionController?.shouldWaitForHandlerFailure(this, handler) ?: false
}
open fun shouldRecognizeSimultaneously(handler: GestureHandler<*>): Boolean {
if (handler === this) {
return true
}
return interactionController?.shouldRecognizeSimultaneously(this, handler) ?: false
}
open fun shouldBeCancelledBy(handler: GestureHandler<*>): Boolean {
if (handler === this) {
return false
}
return interactionController?.shouldHandlerBeCancelledBy(this, handler) ?: false
}
fun isWithinBounds(view: View?, posX: Float, posY: Float): Boolean {
var left = 0f
var top = 0f
var right = view!!.width.toFloat()
var bottom = view.height.toFloat()
if (hitSlop != null) {
val padLeft = hitSlop!![HIT_SLOP_LEFT_IDX]
val padTop = hitSlop!![HIT_SLOP_TOP_IDX]
val padRight = hitSlop!![HIT_SLOP_RIGHT_IDX]
val padBottom = hitSlop!![HIT_SLOP_BOTTOM_IDX]
if (hitSlopSet(padLeft)) {
left -= padLeft
}
if (hitSlopSet(padTop)) {
top -= padTop
}
if (hitSlopSet(padRight)) {
right += padRight
}
if (hitSlopSet(padBottom)) {
bottom += padBottom
}
val width = hitSlop!![HIT_SLOP_WIDTH_IDX]
val height = hitSlop!![HIT_SLOP_HEIGHT_IDX]
if (hitSlopSet(width)) {
if (!hitSlopSet(padLeft)) {
left = right - width
} else if (!hitSlopSet(padRight)) {
right = left + width
}
}
if (hitSlopSet(height)) {
if (!hitSlopSet(padTop)) {
top = bottom - height
} else if (!hitSlopSet(padBottom)) {
bottom = top + height
}
}
}
return posX in left..right && posY in top..bottom
}
fun cancel() {
if (state == STATE_ACTIVE || state == STATE_UNDETERMINED || state == STATE_BEGAN) {
onCancel()
moveToState(STATE_CANCELLED)
}
}
fun fail() {
if (state == STATE_ACTIVE || state == STATE_UNDETERMINED || state == STATE_BEGAN) {
moveToState(STATE_FAILED)
}
}
fun activate() = activate(force = false)
open fun activate(force: Boolean) {
if ((!manualActivation || force) && (state == STATE_UNDETERMINED || state == STATE_BEGAN)) {
moveToState(STATE_ACTIVE)
}
}
fun begin() {
if (state == STATE_UNDETERMINED) {
moveToState(STATE_BEGAN)
}
}
fun end() {
if (state == STATE_BEGAN || state == STATE_ACTIVE) {
moveToState(STATE_END)
}
}
protected open fun onHandle(event: MotionEvent) {
moveToState(STATE_FAILED)
}
protected open fun onStateChange(newState: Int, previousState: Int) {}
protected open fun onReset() {}
protected open fun onCancel() {}
fun reset() {
view = null
orchestrator = null
Arrays.fill(trackedPointerIDs, -1)
trackedPointersIDsCount = 0
trackedPointersCount = 0
trackedPointers.fill(null)
touchEventType = RNGestureHandlerTouchEvent.EVENT_UNDETERMINED
onReset()
}
fun setOnTouchEventListener(listener: OnTouchEventListener?): GestureHandler<*> {
onTouchEventListener = listener
return this
}
override fun toString(): String {
val viewString = if (view == null) null else view!!.javaClass.simpleName
return this.javaClass.simpleName + "@[" + tag + "]:" + viewString
}
val lastRelativePositionX: Float
get() = lastAbsolutePositionX - lastEventOffsetX
val lastRelativePositionY: Float
get() = lastAbsolutePositionY - lastEventOffsetY
companion object {
const val STATE_UNDETERMINED = 0
const val STATE_FAILED = 1
const val STATE_BEGAN = 2
const val STATE_CANCELLED = 3
const val STATE_ACTIVE = 4
const val STATE_END = 5
const val HIT_SLOP_NONE = Float.NaN
private const val HIT_SLOP_LEFT_IDX = 0
private const val HIT_SLOP_TOP_IDX = 1
private const val HIT_SLOP_RIGHT_IDX = 2
private const val HIT_SLOP_BOTTOM_IDX = 3
private const val HIT_SLOP_WIDTH_IDX = 4
private const val HIT_SLOP_HEIGHT_IDX = 5
const val DIRECTION_RIGHT = 1
const val DIRECTION_LEFT = 2
const val DIRECTION_UP = 4
const val DIRECTION_DOWN = 8
private const val MAX_POINTERS_COUNT = 12
private lateinit var pointerProps: Array<PointerProperties?>
private lateinit var pointerCoords: Array<PointerCoords?>
private fun initPointerProps(size: Int) {
var size = size
if (!::pointerProps.isInitialized) {
pointerProps = arrayOfNulls(MAX_POINTERS_COUNT)
pointerCoords = arrayOfNulls(MAX_POINTERS_COUNT)
}
while (size > 0 && pointerProps[size - 1] == null) {
pointerProps[size - 1] = PointerProperties()
pointerCoords[size - 1] = PointerCoords()
size--
}
}
private var nextEventCoalescingKey: Short = 0
private fun hitSlopSet(value: Float): Boolean {
return !java.lang.Float.isNaN(value)
}
fun stateToString(state: Int): String? {
when (state) {
STATE_UNDETERMINED -> return "UNDETERMINED"
STATE_ACTIVE -> return "ACTIVE"
STATE_FAILED -> return "FAILED"
STATE_BEGAN -> return "BEGIN"
STATE_CANCELLED -> return "CANCELLED"
STATE_END -> return "END"
}
return null
}
}
private data class PointerData(
val pointerId: Int,
var x: Float,
var y: Float,
var absoluteX: Float,
var absoluteY: Float
)
}
| bsd-3-clause | a7844008b2a9fd91e0e111030b8988ff | 30.895833 | 153 | 0.679469 | 4.286914 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/timeTracker/actions/SaveTrackerAction.kt | 1 | 1933 | package com.github.jk1.ytplugin.timeTracker.actions
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.logger
import com.github.jk1.ytplugin.timeTracker.TimeTracker
import com.github.jk1.ytplugin.timeTracker.TrackerNotification
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.WindowManager
class SaveTrackerAction {
fun saveTimer(project: Project, taskId: String) {
val trackerNote = TrackerNotification()
val timer = ComponentAware.of(project).timeTrackerComponent
try {
val savedTimeStorage = ComponentAware.of(project).spentTimePerTaskStorage
savedTimeStorage.setSavedTimeForLocalTask(taskId,
System.currentTimeMillis() - timer.startTime - timer.pausedTime)
val updatedTime = savedTimeStorage.getSavedTimeForLocalTask(taskId)
if (savedTimeStorage.getSavedTimeForLocalTask(taskId) >= 60000) {
trackerNote.notify(
"Tracked time for ${ComponentAware.of(project).taskManagerComponent.getActiveTask()}" +
" saved: ${TimeTracker.formatTimePeriod(updatedTime)}",
NotificationType.INFORMATION
)
}
timer.reset()
timer.isPaused = true
val store: PropertiesComponent = PropertiesComponent.getInstance(project)
store.saveFields(timer)
val bar = WindowManager.getInstance().getStatusBar(project)
bar?.removeWidget("Time Tracking Clock")
} catch (e: IllegalStateException) {
logger.warn("Time tracking exception: ${e.message}")
logger.debug(e)
trackerNote.notify("Could not stop time tracking: timer is not running", NotificationType.WARNING)
}
}
} | apache-2.0 | 2e8f28acb0729caa8a79071a0ffa09a7 | 38.469388 | 110 | 0.681324 | 4.969152 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/refactoring/generate/GenerateConstructorActionTest.kt | 2 | 6775 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.generate
class GenerateConstructorActionTest : RsGenerateBaseTest() {
override val generateId: String = "Rust.GenerateConstructor"
fun `test generic struct`() = doTest("""
struct S<T> {
n: i32,/*caret*/
m: T
}
""", listOf(
MemberSelection("n: i32", true),
MemberSelection("m: T", true)
), """
struct S<T> {
n: i32,
m: T
}
impl<T> S<T> {
pub fn new(n: i32, m: T) -> Self {
Self { n, m }
}/*caret*/
}
""")
fun `test empty type declaration`() = doTest("""
struct S {
n: i32,/*caret*/
m:
}
""", listOf(
MemberSelection("n: i32", true),
MemberSelection("m: ()", true)
), """
struct S {
n: i32,
m:
}
impl S {
pub fn new(n: i32, m: ()) -> Self {
Self { n, m }
}/*caret*/
}
""")
fun `test empty struct`() = doTest("""
struct S {/*caret*/}
""", emptyList(), """
struct S {}
impl S {
pub fn new() -> Self {
Self {}
}
}
""")
fun `test tuple struct`() = doTest("""
struct Color(i32, i32, i32)/*caret*/;
""", listOf(
MemberSelection("field0: i32", true),
MemberSelection("field1: i32", true),
MemberSelection("field2: i32", true)
), """
struct Color(i32, i32, i32);
impl Color {
pub fn new(field0: i32, field1: i32, field2: i32) -> Self {
Self(field0, field1, field2)
}/*caret*/
}
""")
fun `test select none fields`() = doTest("""
struct S {
n: i32,/*caret*/
m: i64,
}
""", listOf(
MemberSelection("n: i32", false),
MemberSelection("m: i64", false)
), """
struct S {
n: i32,
m: i64,
}
impl S {
pub fn new() -> Self {
Self { n: (), m: () }
}/*caret*/
}
""")
fun `test select all fields`() = doTest("""
struct S {
n: i32,/*caret*/
m: i64,
}
""", listOf(
MemberSelection("n: i32", true),
MemberSelection("m: i64", true)
), """
struct S {
n: i32,
m: i64,
}
impl S {
pub fn new(n: i32, m: i64) -> Self {
Self { n, m }
}/*caret*/
}
""")
fun `test select some fields`() = doTest("""
struct S {
n: i32,/*caret*/
m: i64,
}
""", listOf(
MemberSelection("n: i32", true),
MemberSelection("m: i64", false)
), """
struct S {
n: i32,
m: i64,
}
impl S {
pub fn new(n: i32) -> Self {
Self { n, m: () }
}/*caret*/
}
""")
fun `test generate all fields on impl`() = doTest("""
struct S {
n: i32,
m: i64,
}
impl S {
/*caret*/
}
""", listOf(
MemberSelection("n: i32", true),
MemberSelection("m: i64", true)
), """
struct S {
n: i32,
m: i64,
}
impl S {
pub fn new(n: i32, m: i64) -> Self {
Self { n, m }
}/*caret*/
}
""")
fun `test not available when new method exists`() = doUnavailableTest("""
struct S {
n: i32,
m: i64,
}
impl S {
pub fn new() {}
/*caret*/
}
""")
fun `test not available on trait impl`() = doUnavailableTest("""
trait T { fn foo() }
struct S {
n: i32,
m: i64,
}
impl T for S {
/*caret*/
}
""")
fun `test take type parameters from impl block`() = doTest("""
struct S<T>(T);
impl S<i32> {
/*caret*/
}
""", listOf(MemberSelection("field0: i32", true)), """
struct S<T>(T);
impl S<i32> {
pub fn new(field0: i32) -> Self {
Self(field0)
}/*caret*/
}
""")
fun `test take lifetimes from impl block`() = doTest("""
struct S<'a, T>(&'a T);
impl <'a> S<'a, i32> {
/*caret*/
}
""", listOf(MemberSelection("field0: &'a i32", true)), """
struct S<'a, T>(&'a T);
impl <'a> S<'a, i32> {
pub fn new(field0: &'a i32) -> Self {
Self(field0)
}/*caret*/
}
""")
fun `test type alias`() = doTest("""
type Coordinates = (u32, u32);
struct System/*caret*/ {
point: Coordinates,
}
""", listOf(MemberSelection("point: Coordinates", true)), """
type Coordinates = (u32, u32);
struct System {
point: Coordinates,
}
impl System {
pub fn new(point: Coordinates) -> Self {
Self { point }
}/*caret*/
}
""")
fun `test qualified path named struct`() = doTest("""
mod foo {
pub struct S;
}
struct System/*caret*/ {
s: foo::S
}
""", listOf(MemberSelection("s: foo::S", true)), """
mod foo {
pub struct S;
}
struct System {
s: foo::S
}
impl System {
pub fn new(s: foo::S) -> Self {
Self { s }
}/*caret*/
}
""")
fun `test qualified path tuple struct`() = doTest("""
mod foo {
pub struct S;
}
struct System/*caret*/(foo::S);
""", listOf(MemberSelection("field0: foo::S", true)), """
mod foo {
pub struct S;
}
struct System(foo::S);
impl System {
pub fn new(field0: foo::S) -> Self {
Self(field0)
}/*caret*/
}
""")
fun `test reuse impl block`() = doTest("""
struct System {
s: u32/*caret*/
}
impl System {
fn foo(&self) {}
}
""", listOf(MemberSelection("s: u32", true)), """
struct System {
s: u32
}
impl System {
fn foo(&self) {}
pub fn new(s: u32) -> Self {
Self { s }
}/*caret*/
}
""")
}
| mit | 8a17ac5ce11dad1602929c811f796efe | 20.854839 | 77 | 0.389963 | 4.076414 | false | true | false | false |
androidx/androidx | glance/glance-wear-tiles-preview/src/androidAndroidTest/kotlin/androidx/glance/wear/tiles/preview/FirstGlancePreview.kt | 3 | 2110 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.wear.tiles.preview
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import androidx.glance.action.Action
import androidx.glance.Button
import androidx.glance.GlanceModifier
import androidx.glance.layout.Alignment
import androidx.glance.layout.Column
import androidx.glance.layout.Row
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.fillMaxWidth
import androidx.glance.layout.height
import androidx.glance.layout.padding
import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextStyle
@Composable
fun FirstGlancePreview() {
Column(
modifier = GlanceModifier
.fillMaxSize()
.padding(16.dp)
) {
Text(
text = "First Glance widget",
modifier = GlanceModifier
.fillMaxWidth()
.padding(bottom = 8.dp),
style = TextStyle(fontWeight = FontWeight.Bold),
)
Row(
modifier = GlanceModifier.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically
) {
Button(
text = "Button 1",
modifier = GlanceModifier.height(48.dp),
onClick = object : Action { }
)
Button(
text = "Button 2",
modifier = GlanceModifier.height(48.dp),
onClick = object : Action { }
)
}
}
} | apache-2.0 | 8efeec13e71b2e438b2c8918f84bad97 | 31.476923 | 75 | 0.659242 | 4.668142 | false | false | false | false |
androidx/androidx | room/room-compiler/src/test/test-data/kotlinCodeGen/relations_nullable.kt | 3 | 13683 | import android.database.Cursor
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.RoomSQLiteQuery.Companion.acquire
import androidx.room.util.appendPlaceholders
import androidx.room.util.getColumnIndex
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.newStringBuilder
import androidx.room.util.query
import androidx.room.util.recursiveFetchHashMap
import java.lang.Class
import java.lang.StringBuilder
import java.util.ArrayList
import java.util.HashMap
import javax.`annotation`.processing.Generated
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.List
import kotlin.collections.Set
import kotlin.jvm.JvmStatic
@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"])
public class MyDao_Impl(
__db: RoomDatabase,
) : MyDao {
private val __db: RoomDatabase
init {
this.__db = __db
}
public override fun getSongsWithArtist(): SongWithArtist {
val _sql: String = "SELECT * FROM Song"
val _statement: RoomSQLiteQuery = acquire(_sql, 0)
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, true, null)
try {
val _cursorIndexOfSongId: Int = getColumnIndexOrThrow(_cursor, "songId")
val _cursorIndexOfArtistKey: Int = getColumnIndexOrThrow(_cursor, "artistKey")
val _collectionArtist: HashMap<Long, Artist?> = HashMap<Long, Artist?>()
while (_cursor.moveToNext()) {
val _tmpKey: Long?
if (_cursor.isNull(_cursorIndexOfArtistKey)) {
_tmpKey = null
} else {
_tmpKey = _cursor.getLong(_cursorIndexOfArtistKey)
}
if (_tmpKey != null) {
_collectionArtist.put(_tmpKey, null)
}
}
_cursor.moveToPosition(-1)
__fetchRelationshipArtistAsArtist(_collectionArtist)
val _result: SongWithArtist
if (_cursor.moveToFirst()) {
val _tmpSong: Song
val _tmpSongId: Long
_tmpSongId = _cursor.getLong(_cursorIndexOfSongId)
val _tmpArtistKey: Long?
if (_cursor.isNull(_cursorIndexOfArtistKey)) {
_tmpArtistKey = null
} else {
_tmpArtistKey = _cursor.getLong(_cursorIndexOfArtistKey)
}
_tmpSong = Song(_tmpSongId,_tmpArtistKey)
val _tmpArtist: Artist?
val _tmpKey_1: Long?
if (_cursor.isNull(_cursorIndexOfArtistKey)) {
_tmpKey_1 = null
} else {
_tmpKey_1 = _cursor.getLong(_cursorIndexOfArtistKey)
}
if (_tmpKey_1 != null) {
_tmpArtist = _collectionArtist.get(_tmpKey_1)
} else {
_tmpArtist = null
}
_result = SongWithArtist(_tmpSong,_tmpArtist)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public override fun getArtistAndSongs(): ArtistAndSongs {
val _sql: String = "SELECT * FROM Artist"
val _statement: RoomSQLiteQuery = acquire(_sql, 0)
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, true, null)
try {
val _cursorIndexOfArtistId: Int = getColumnIndexOrThrow(_cursor, "artistId")
val _collectionSongs: HashMap<Long, ArrayList<Song>> = HashMap<Long, ArrayList<Song>>()
while (_cursor.moveToNext()) {
val _tmpKey: Long
_tmpKey = _cursor.getLong(_cursorIndexOfArtistId)
if (!_collectionSongs.containsKey(_tmpKey)) {
_collectionSongs.put(_tmpKey, ArrayList<Song>())
}
}
_cursor.moveToPosition(-1)
__fetchRelationshipSongAsSong(_collectionSongs)
val _result: ArtistAndSongs
if (_cursor.moveToFirst()) {
val _tmpArtist: Artist
val _tmpArtistId: Long
_tmpArtistId = _cursor.getLong(_cursorIndexOfArtistId)
_tmpArtist = Artist(_tmpArtistId)
val _tmpSongsCollection: ArrayList<Song>
val _tmpKey_1: Long
_tmpKey_1 = _cursor.getLong(_cursorIndexOfArtistId)
_tmpSongsCollection = _collectionSongs.getValue(_tmpKey_1)
_result = ArtistAndSongs(_tmpArtist,_tmpSongsCollection)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public override fun getPlaylistAndSongs(): PlaylistAndSongs {
val _sql: String = "SELECT * FROM Playlist"
val _statement: RoomSQLiteQuery = acquire(_sql, 0)
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, true, null)
try {
val _cursorIndexOfPlaylistId: Int = getColumnIndexOrThrow(_cursor, "playlistId")
val _collectionSongs: HashMap<Long, ArrayList<Song>> = HashMap<Long, ArrayList<Song>>()
while (_cursor.moveToNext()) {
val _tmpKey: Long
_tmpKey = _cursor.getLong(_cursorIndexOfPlaylistId)
if (!_collectionSongs.containsKey(_tmpKey)) {
_collectionSongs.put(_tmpKey, ArrayList<Song>())
}
}
_cursor.moveToPosition(-1)
__fetchRelationshipSongAsSong_1(_collectionSongs)
val _result: PlaylistAndSongs
if (_cursor.moveToFirst()) {
val _tmpPlaylist: Playlist
val _tmpPlaylistId: Long
_tmpPlaylistId = _cursor.getLong(_cursorIndexOfPlaylistId)
_tmpPlaylist = Playlist(_tmpPlaylistId)
val _tmpSongsCollection: ArrayList<Song>
val _tmpKey_1: Long
_tmpKey_1 = _cursor.getLong(_cursorIndexOfPlaylistId)
_tmpSongsCollection = _collectionSongs.getValue(_tmpKey_1)
_result = PlaylistAndSongs(_tmpPlaylist,_tmpSongsCollection)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
private fun __fetchRelationshipArtistAsArtist(_map: HashMap<Long, Artist?>): Unit {
val __mapKeySet: Set<Long> = _map.keys
if (__mapKeySet.isEmpty()) {
return
}
if (_map.size > RoomDatabase.MAX_BIND_PARAMETER_CNT) {
recursiveFetchHashMap(_map, false) {
__fetchRelationshipArtistAsArtist(it)
}
return
}
val _stringBuilder: StringBuilder = newStringBuilder()
_stringBuilder.append("SELECT `artistId` FROM `Artist` WHERE `artistId` IN (")
val _inputSize: Int = __mapKeySet.size
appendPlaceholders(_stringBuilder, _inputSize)
_stringBuilder.append(")")
val _sql: String = _stringBuilder.toString()
val _argCount: Int = 0 + _inputSize
val _stmt: RoomSQLiteQuery = acquire(_sql, _argCount)
var _argIndex: Int = 1
for (_item: Long in __mapKeySet) {
_stmt.bindLong(_argIndex, _item)
_argIndex++
}
val _cursor: Cursor = query(__db, _stmt, false, null)
try {
val _itemKeyIndex: Int = getColumnIndex(_cursor, "artistId")
if (_itemKeyIndex == -1) {
return
}
val _cursorIndexOfArtistId: Int = 0
while (_cursor.moveToNext()) {
val _tmpKey: Long
_tmpKey = _cursor.getLong(_itemKeyIndex)
if (_map.containsKey(_tmpKey)) {
val _item_1: Artist?
val _tmpArtistId: Long
_tmpArtistId = _cursor.getLong(_cursorIndexOfArtistId)
_item_1 = Artist(_tmpArtistId)
_map.put(_tmpKey, _item_1)
}
}
} finally {
_cursor.close()
}
}
private fun __fetchRelationshipSongAsSong(_map: HashMap<Long, ArrayList<Song>>): Unit {
val __mapKeySet: Set<Long> = _map.keys
if (__mapKeySet.isEmpty()) {
return
}
if (_map.size > RoomDatabase.MAX_BIND_PARAMETER_CNT) {
recursiveFetchHashMap(_map, true) {
__fetchRelationshipSongAsSong(it)
}
return
}
val _stringBuilder: StringBuilder = newStringBuilder()
_stringBuilder.append("SELECT `songId`,`artistKey` FROM `Song` WHERE `artistKey` IN (")
val _inputSize: Int = __mapKeySet.size
appendPlaceholders(_stringBuilder, _inputSize)
_stringBuilder.append(")")
val _sql: String = _stringBuilder.toString()
val _argCount: Int = 0 + _inputSize
val _stmt: RoomSQLiteQuery = acquire(_sql, _argCount)
var _argIndex: Int = 1
for (_item: Long in __mapKeySet) {
_stmt.bindLong(_argIndex, _item)
_argIndex++
}
val _cursor: Cursor = query(__db, _stmt, false, null)
try {
val _itemKeyIndex: Int = getColumnIndex(_cursor, "artistKey")
if (_itemKeyIndex == -1) {
return
}
val _cursorIndexOfSongId: Int = 0
val _cursorIndexOfArtistKey: Int = 1
while (_cursor.moveToNext()) {
val _tmpKey: Long?
if (_cursor.isNull(_itemKeyIndex)) {
_tmpKey = null
} else {
_tmpKey = _cursor.getLong(_itemKeyIndex)
}
if (_tmpKey != null) {
val _tmpRelation: ArrayList<Song>? = _map.get(_tmpKey)
if (_tmpRelation != null) {
val _item_1: Song
val _tmpSongId: Long
_tmpSongId = _cursor.getLong(_cursorIndexOfSongId)
val _tmpArtistKey: Long?
if (_cursor.isNull(_cursorIndexOfArtistKey)) {
_tmpArtistKey = null
} else {
_tmpArtistKey = _cursor.getLong(_cursorIndexOfArtistKey)
}
_item_1 = Song(_tmpSongId,_tmpArtistKey)
_tmpRelation.add(_item_1)
}
}
}
} finally {
_cursor.close()
}
}
private fun __fetchRelationshipSongAsSong_1(_map: HashMap<Long, ArrayList<Song>>): Unit {
val __mapKeySet: Set<Long> = _map.keys
if (__mapKeySet.isEmpty()) {
return
}
if (_map.size > RoomDatabase.MAX_BIND_PARAMETER_CNT) {
recursiveFetchHashMap(_map, true) {
__fetchRelationshipSongAsSong_1(it)
}
return
}
val _stringBuilder: StringBuilder = newStringBuilder()
_stringBuilder.append("SELECT `Song`.`songId` AS `songId`,`Song`.`artistKey` AS `artistKey`,_junction.`playlistKey` FROM `PlaylistSongXRef` AS _junction INNER JOIN `Song` ON (_junction.`songKey` = `Song`.`songId`) WHERE _junction.`playlistKey` IN (")
val _inputSize: Int = __mapKeySet.size
appendPlaceholders(_stringBuilder, _inputSize)
_stringBuilder.append(")")
val _sql: String = _stringBuilder.toString()
val _argCount: Int = 0 + _inputSize
val _stmt: RoomSQLiteQuery = acquire(_sql, _argCount)
var _argIndex: Int = 1
for (_item: Long in __mapKeySet) {
_stmt.bindLong(_argIndex, _item)
_argIndex++
}
val _cursor: Cursor = query(__db, _stmt, false, null)
try {
// _junction.playlistKey
val _itemKeyIndex: Int = 2
if (_itemKeyIndex == -1) {
return
}
val _cursorIndexOfSongId: Int = 0
val _cursorIndexOfArtistKey: Int = 1
while (_cursor.moveToNext()) {
val _tmpKey: Long
_tmpKey = _cursor.getLong(_itemKeyIndex)
val _tmpRelation: ArrayList<Song>? = _map.get(_tmpKey)
if (_tmpRelation != null) {
val _item_1: Song
val _tmpSongId: Long
_tmpSongId = _cursor.getLong(_cursorIndexOfSongId)
val _tmpArtistKey: Long?
if (_cursor.isNull(_cursorIndexOfArtistKey)) {
_tmpArtistKey = null
} else {
_tmpArtistKey = _cursor.getLong(_cursorIndexOfArtistKey)
}
_item_1 = Song(_tmpSongId,_tmpArtistKey)
_tmpRelation.add(_item_1)
}
}
} finally {
_cursor.close()
}
}
public companion object {
@JvmStatic
public fun getRequiredConverters(): List<Class<*>> = emptyList()
}
} | apache-2.0 | be03f7513a525b924b5ef0391de21219 | 39.72619 | 258 | 0.536578 | 4.687564 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/resolve/scope/ImportScope.kt | 1 | 8163 | package org.elm.lang.core.resolve.scope
import com.intellij.openapi.util.Key
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.ParameterizedCachedValue
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.ElmNamedElement
import org.elm.lang.core.psi.elements.ElmImportClause
import org.elm.lang.core.psi.elements.ElmTypeAliasDeclaration
import org.elm.lang.core.psi.elements.ElmTypeDeclaration
import org.elm.lang.core.psi.globalModificationTracker
import org.elm.lang.core.stubs.index.ElmModulesIndex
private val EXPOSED_VALUES_KEY: Key<ParameterizedCachedValue<ExposedNames, ElmFile>> = Key.create("EXPOSED_VALUES_KEY")
private val EXPOSED_TYPES_KEY: Key<ParameterizedCachedValue<ExposedNames, ElmFile>> = Key.create("EXPOSED_TYPES_KEY")
private val EXPOSED_CONSTRUCTORS_KEY: Key<ParameterizedCachedValue<ExposedNames, ElmFile>> = Key.create("EXPOSED_CONSTRUCTORS_KEY")
class ExposedNames(val elements: Array<ElmNamedElement>) {
constructor(elements: List<ElmNamedElement>) : this(elements.toTypedArray())
private val byName = elements.associateByTo(mutableMapOf()) { it.name }.apply { remove(null) }
operator fun get(key: String?) = byName[key]
}
/**
* A scope of exposed names for the module named by [qualifierPrefix] reachable
* via [clientFile]. By default, the import scopes will be found by crawling the
* explicit import declarations in [clientFile] and automatically adding the
* implicit imports from Elm's Core standard library.
*
* @param qualifierPrefix The name of a module or an alias
* @param clientFile The Elm file from which the search should be performed
* @param importsOnly If true, include only modules reachable via imports (implicit and explicit).
* Otherwise, include all modules which could be reached by the file's [ElmProject]
*/
class QualifiedImportScope(
private val qualifierPrefix: String,
private val clientFile: ElmFile,
private val importsOnly: Boolean = true
) {
fun getExposedValue(name: String): ElmNamedElement? {
return scopes().mapNotNull { it.getExposedValues()[name] }.firstOrNull()
}
fun getExposedValues(): Sequence<ElmNamedElement> {
return scopes().flatMap { it.getExposedValues().elements.asSequence() }
}
fun getExposedType(name: String): ElmNamedElement? {
return scopes().mapNotNull { it.getExposedTypes()[name] }.firstOrNull()
}
fun getExposedTypes(): Sequence<ElmNamedElement> {
return scopes().flatMap { it.getExposedTypes().elements.asSequence() }
}
fun getExposedConstructor(name: String): ElmNamedElement? {
return scopes().mapNotNull { it.getExposedConstructors()[name] }.firstOrNull()
}
fun getExposedConstructors(): Sequence<ElmNamedElement> {
return scopes().flatMap { it.getExposedConstructors().elements.asSequence() }
}
/** Lazily yield all individual scopes that can contain exposed names with this prefix */
private fun scopes(): Sequence<ImportScope> = sequence {
if (importsOnly) {
yieldAll(explicitScopes())
yieldAll(implicitScopes())
} else {
val projectWideScopes = ElmModulesIndex.getAll(listOf(qualifierPrefix), clientFile)
.asSequence().map { ImportScope(it.elmFile) }
val allScopes = explicitScopes() + implicitScopes() + projectWideScopes
yieldAll(allScopes.distinctBy { it.elmFile.virtualFile.path })
}
}
private fun implicitScopes() = GlobalScope.implicitModulesMatching(qualifierPrefix, clientFile)
.asSequence().map { ImportScope(it.elmFile) }
private fun explicitScopes() = ModuleScope.importDeclsForQualifierPrefix(clientFile, qualifierPrefix)
.asSequence().mapNotNull { ImportScope.fromImportDecl(it) }
}
/**
* A scope that allows exposed values and types from the module named [elmFile]
* to be imported. You can think of it as the view of the module from the outside.
*
* @see ModuleScope for the view of the module from inside
*/
class ImportScope(val elmFile: ElmFile) {
companion object {
/**
* Returns an [ImportScope] for the module which is being imported by [importDecl].
*/
fun fromImportDecl(importDecl: ElmImportClause): ImportScope? {
val moduleName = importDecl.referenceName
return ElmModulesIndex.get(moduleName, importDecl.elmFile)
?.let { ImportScope(it.elmFile) }
}
}
/**
* Returns all value declarations exposed by this module.
*/
fun getExposedValues(): ExposedNames {
return CachedValuesManager.getManager(elmFile.project).getParameterizedCachedValue(elmFile, EXPOSED_VALUES_KEY, {
CachedValueProvider.Result.create(ExposedNames(produceExposedValues()), it.globalModificationTracker)
}, /*trackValue*/ false, /*parameter*/ elmFile)
}
private fun produceExposedValues(): List<ElmNamedElement> {
val moduleDecl = elmFile.getModuleDecl()
?: return emptyList()
if (moduleDecl.exposesAll)
return ModuleScope.getDeclaredValues(elmFile).list
val exposingList = moduleDecl.exposingList
?: return emptyList()
val declaredValues = ModuleScope.getDeclaredValues(elmFile).array
val exposedNames = mutableSetOf<String>()
exposingList.exposedValueList.mapTo(exposedNames) { it.referenceName }
exposingList.exposedOperatorList.mapTo(exposedNames) { it.referenceName }
return declaredValues.filter { it.name in exposedNames }
}
/**
* Returns all union type and type alias declarations exposed by this module.
*/
fun getExposedTypes(): ExposedNames {
return CachedValuesManager.getManager(elmFile.project).getParameterizedCachedValue(elmFile, EXPOSED_TYPES_KEY, {
CachedValueProvider.Result.create(ExposedNames(produceExposedTypes()), it.globalModificationTracker)
}, false, elmFile)
}
private fun produceExposedTypes(): List<ElmNamedElement> {
val moduleDecl = elmFile.getModuleDecl()
?: return emptyList()
if (moduleDecl.exposesAll)
return ModuleScope.getDeclaredTypes(elmFile).list
val exposedTypeList = moduleDecl.exposingList?.exposedTypeList
?: return emptyList()
val exposedNames = exposedTypeList.mapTo(mutableSetOf()) { it.referenceName }
return ModuleScope.getDeclaredTypes(elmFile).array.filter { it.name in exposedNames }
}
/**
* Returns all union and record constructors exposed by this module.
*/
fun getExposedConstructors(): ExposedNames {
return CachedValuesManager.getManager(elmFile.project).getParameterizedCachedValue(elmFile, EXPOSED_CONSTRUCTORS_KEY, {
CachedValueProvider.Result.create(ExposedNames(produceExposedConstructors()), it.globalModificationTracker)
}, false, elmFile)
}
private fun produceExposedConstructors(): List<ElmNamedElement> {
val moduleDecl = elmFile.getModuleDecl()
?: return emptyList()
if (moduleDecl.exposesAll)
return ModuleScope.getDeclaredConstructors(elmFile).list
val exposedTypeList = moduleDecl.exposingList?.exposedTypeList
?: return emptyList()
val types = ModuleScope.getDeclaredTypes(elmFile)
return exposedTypeList.flatMap { exposedType ->
val type = types[exposedType.referenceName]
when {
exposedType.exposesAll -> {
// It's a union type that exposes all of its constructors
(type as? ElmTypeDeclaration)?.unionVariantList
}
else -> {
// It's either a record type or a union type without any exposed constructors
if (type is ElmTypeAliasDeclaration && type.isRecordAlias) listOf(type)
else null
}
} ?: emptyList()
}
}
}
| mit | 633489edf4a8a582aa17f702a73e8a79 | 41.73822 | 131 | 0.691535 | 4.765324 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/webtoons/WebtoonsGenerator.kt | 1 | 795 | package eu.kanade.tachiyomi.multisrc.webtoons
import generator.ThemeSourceData.SingleLang
import generator.ThemeSourceData.MultiLang
import generator.ThemeSourceGenerator
class WebtoonsGenerator : ThemeSourceGenerator {
override val themePkg = "webtoons"
override val themeClass = "Webtoons"
override val baseVersionCode: Int = 2
override val sources = listOf(
MultiLang("Webtoons.com", "https://www.webtoons.com", listOf("en", "fr", "es", "id", "th", "zh"), className = "WebtoonsFactory", pkgName = "webtoons", overrideVersionCode = 29),
SingleLang("Dongman Manhua", "https://www.dongmanmanhua.cn", "zh")
)
companion object {
@JvmStatic
fun main(args: Array<String>) {
WebtoonsGenerator().createAll()
}
}
}
| apache-2.0 | 43a339db8eb8751bcc7807cb285b024a | 29.576923 | 185 | 0.683019 | 4.184211 | false | false | false | false |
JavaEden/Orchid | languageExtensions/OrchidSyntaxHighlighter/src/main/kotlin/com/eden/orchid/languages/highlighter/components/PrismComponent.kt | 2 | 3406 | package com.eden.orchid.languages.highlighter.components
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.theme.assets.AssetManagerDelegate
import com.eden.orchid.api.theme.components.OrchidComponent
import com.eden.orchid.utilities.OrchidUtils
@Description("Automatically find and highlight code snippets with Prism.js. Markdown code snippets are immediately " +
"compatible with Prism.js and requires no further configuration. This component simply attached the " +
"necessary scripts and styles to the page, but needs no UI template of its own.",
name = "Prism.js"
)
class PrismComponent : OrchidComponent("prism", true) {
@Option
@StringDefault("https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1")
@Description("The base URL to load Prism CSS and JS files from.")
lateinit var prismSource: String
@Option
@Description("The Prism language definitions to be included.")
lateinit var languages: Array<String>
@Option
@Description("The Prism plugins to be included.")
lateinit var plugins: Array<String>
@Option
@Description("The official Prism theme to be used. Alternatively, you may use a `githubTheme` to use one of the " +
"themes provided from the 'PrismJS/prism-themes' github repo."
)
lateinit var theme: String
@Option
@Description("The unofficial Prism theme to be used, from the 'PrismJS/prism-themes' github repo.")
lateinit var githubTheme: String
@Option
@Description("If true, only include the Prism Javascript files, opting to build the styles yourself.")
var scriptsOnly: Boolean = false
override fun loadAssets(delegate: AssetManagerDelegate): Unit = with(delegate) {
addJs(OrchidUtils.normalizePath(prismSource) + "/prism.min.js")
if (!scriptsOnly) {
if (!EdenUtils.isEmpty(theme)) {
addCss("${OrchidUtils.normalizePath(prismSource)}/themes/prism-$theme.min.css")
}
else if (!EdenUtils.isEmpty(githubTheme)) {
addCss("https://rawgit.com/PrismJS/prism-themes/master/themes/prism-$githubTheme.css")
}
else {
addCss("${OrchidUtils.normalizePath(prismSource)}/themes/prism.min.css")
}
}
if (!EdenUtils.isEmpty(languages)) {
for (lang in languages) {
addJs("${OrchidUtils.normalizePath(prismSource)}/components/prism-$lang.min.js")
}
}
if (!EdenUtils.isEmpty(plugins)) {
for (plugin in plugins) {
if (plugin == "copy-to-clipboard") {
addJs("https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.7.1/clipboard.min.js")
}
addJs("${OrchidUtils.normalizePath(prismSource)}/plugins/$plugin/prism-$plugin.min.js")
if (!scriptsOnly) {
when (plugin) {
"line-numbers", "line-highlight", "toolbar" -> addCss("${OrchidUtils.normalizePath(prismSource)}/plugins/$plugin/prism-$plugin.min.css")
}
}
}
}
}
override fun isHidden(): Boolean {
return true
}
}
| lgpl-3.0 | b472459f7544465c976313bef90bcf0e | 39.070588 | 160 | 0.647093 | 4.383526 | false | false | false | false |
ilya-g/kotlinx.collections.experimental | kotlinx-collections-experimental/src/main/kotlin/kotlinx.collections.experimental/scan/scan.kt | 1 | 1295 | package kotlinx.collections.experimental.scan
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each element.
*/
public inline fun <T, R> Iterable<T>.scan(initial: R, operation: (R, T) -> R): List<R> {
val result = mutableListOf<R>()
var accumulator = initial
for (element in this) {
accumulator = operation(accumulator, element)
result.add(accumulator)
}
return result
}
public fun <T, R> Sequence<T>.scan(initial: R, operation: (R, T) -> R): Sequence<R> = Sequence {
object : AbstractIterator<R>() {
var accumulator = initial
val iterator = [email protected]()
override fun computeNext() {
if (!iterator.hasNext())
done()
else {
val element = iterator.next()
accumulator = operation(accumulator, element)
setNext(accumulator)
}
}
}
}
fun main(args: Array<String>) {
val values = listOf("apple", "fooz", "bisquit", "abc", "far", "bar", "foo")
val scanResult = values.scan("") { acc, e -> acc + "/" + e }
println(scanResult)
assert(scanResult == values.asSequence().scan("") { acc, e -> acc + "/" + e }.toList())
} | apache-2.0 | a6b23ed9562d44f97faf736a5f9e3796 | 32.230769 | 141 | 0.586873 | 4.046875 | false | false | false | false |
wix/react-native-navigation | lib/android/app/src/reactNative63/java/com/reactnativenavigation/react/modal/ModalContentLayout.kt | 8 | 2958 | package com.reactnativenavigation.react.modal
import android.content.Context
import android.view.MotionEvent
import android.view.View
import com.facebook.react.bridge.*
import com.facebook.react.uimanager.*
import com.facebook.react.uimanager.events.EventDispatcher
import com.facebook.react.views.view.ReactViewGroup
class ModalContentLayout(context: Context?) : ReactViewGroup(context), RootView{
private var hasAdjustedSize = false
private var viewWidth = 0
private var viewHeight = 0
private val mJSTouchDispatcher = JSTouchDispatcher(this)
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
viewWidth = w
viewHeight = h
this.updateFirstChildView()
}
private fun updateFirstChildView() {
if (this.childCount > 0) {
hasAdjustedSize = false
val viewTag = getChildAt(0).id
val reactContext: ReactContext = this.getReactContext()
reactContext.runOnNativeModulesQueueThread(object : GuardedRunnable(reactContext) {
override fun runGuarded() {
val uiManager = [email protected]().getNativeModule(
UIManagerModule::class.java
) as UIManagerModule
uiManager.updateNodeSize(
viewTag,
[email protected],
[email protected]
)
}
})
} else {
hasAdjustedSize = true
}
}
override fun addView(child: View?, index: Int, params: LayoutParams?) {
super.addView(child, index, params)
if (hasAdjustedSize) {
updateFirstChildView()
}
}
override fun onChildStartedNativeGesture(androidEvent: MotionEvent?) {
mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, this.getEventDispatcher())
}
override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
private fun getEventDispatcher(): EventDispatcher? {
val reactContext: ReactContext = this.getReactContext()
return reactContext.getNativeModule(UIManagerModule::class.java)!!.eventDispatcher
}
override fun handleException(t: Throwable?) {
getReactContext().handleException(RuntimeException(t))
}
private fun getReactContext(): ReactContext {
return this.context as ReactContext
}
override fun onInterceptTouchEvent(event: MotionEvent?): Boolean {
mJSTouchDispatcher.handleTouchEvent(event, getEventDispatcher())
return super.onInterceptTouchEvent(event)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
mJSTouchDispatcher.handleTouchEvent(event, getEventDispatcher())
super.onTouchEvent(event)
return true
}
} | mit | 820a3f9769f92854c63eb1abb275e90c | 35.530864 | 95 | 0.660243 | 5.180385 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/commit/CommitFilesPresenter.kt | 1 | 3136 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.commit
import giuliolodi.gitnav.data.DataManager
import giuliolodi.gitnav.ui.base.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.eclipse.egit.github.core.CommitFile
import org.eclipse.egit.github.core.RepositoryCommit
import timber.log.Timber
import javax.inject.Inject
/**
* Created by giulio on 29/12/2017.
*/
class CommitFilesPresenter<V: CommitFilesContract.View> : BasePresenter<V>, CommitFilesContract.Presenter<V> {
private val TAG = "CommitFilesPresenter"
private var mCommitFileList: List<CommitFile> = mutableListOf()
private var mOwner: String? = null
private var mName: String? = null
private var mSha: String? = null
private var LOADING: Boolean = false
@Inject
constructor(mCompositeDisposable: CompositeDisposable, mDataManager: DataManager) : super(mCompositeDisposable, mDataManager)
override fun subscribe(isNetworkAvailable: Boolean, owner: String?, name: String?, sha: String?) {
mOwner = owner
mName = name
mSha = sha
if (!mCommitFileList.isEmpty()) getView().showFiles(mCommitFileList)
else if (LOADING) getView().showLoading()
else {
if (isNetworkAvailable) {
LOADING = true
getView().showLoading()
if (mOwner != null && mName != null && mSha != null) loadFiles()
}
else {
getView().showNoConnectionError()
getView().hideLoading()
LOADING = false
}
}
}
private fun loadFiles() {
getCompositeDisposable().add(getDataManager().getCommit(mOwner!!, mName!!, mSha!!)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ commit ->
mCommitFileList = commit.files
getView().showFiles(mCommitFileList)
getView().hideLoading()
LOADING = false
},
{ throwable ->
throwable?.localizedMessage?.let { getView().showError(it) }
getView().hideLoading()
Timber.e(throwable)
LOADING = false
}
))
}
} | apache-2.0 | fccb3e09902d2e75cc79ac2cee77c10b | 35.905882 | 129 | 0.610651 | 5.166392 | false | false | false | false |
Heiner1/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistory.kt | 1 | 13248 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.dana.comm.RecordTypes
import info.nightscout.androidaps.dana.database.DanaHistoryRecord
import info.nightscout.androidaps.dana.database.DanaHistoryRecordDao
import info.nightscout.androidaps.events.EventDanaRSyncStatus
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.utils.T
import org.joda.time.DateTime
import java.util.*
import javax.inject.Inject
abstract class DanaRSPacketHistory(
injector: HasAndroidInjector,
protected val from: Long
) : DanaRSPacket(injector) {
@Inject lateinit var rxBus: RxBus
@Inject lateinit var danaHistoryRecordDao: DanaHistoryRecordDao
@Inject lateinit var pumpSync: PumpSync
@Inject lateinit var danaPump: DanaPump
protected var year = 0
protected var month = 0
protected var day = 0
protected var hour = 0
protected var min = 0
protected var sec = 0
var done = false
var totalCount = 0
val danaRHistoryRecord = DanaHistoryRecord(0)
init {
val cal = GregorianCalendar()
if (from != 0L) cal.timeInMillis = from
else cal[2000, 0, 1, 0, 0] = 0
year = cal[Calendar.YEAR] - 1900 - 100
month = cal[Calendar.MONTH] + 1
day = cal[Calendar.DAY_OF_MONTH]
hour = cal[Calendar.HOUR_OF_DAY]
min = cal[Calendar.MINUTE]
sec = cal[Calendar.SECOND]
aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(cal.timeInMillis))
}
override fun getRequestParams(): ByteArray {
val request = ByteArray(6)
request[0] = (year and 0xff).toByte()
request[1] = (month and 0xff).toByte()
request[2] = (day and 0xff).toByte()
request[3] = (hour and 0xff).toByte()
request[4] = (min and 0xff).toByte()
request[5] = (sec and 0xff).toByte()
return request
}
override fun handleMessage(data: ByteArray) {
val error: Int
totalCount = 0
if (data.size == 3) {
val dataIndex = DATA_START
val dataSize = 1
error = byteArrayToInt(getBytes(data, dataIndex, dataSize))
done = true
aapsLogger.debug(LTag.PUMPCOMM, "History end. Code: " + error + " Success: " + (error == 0x00))
} else if (data.size == 5) {
var dataIndex = DATA_START
var dataSize = 1
error = byteArrayToInt(getBytes(data, dataIndex, dataSize))
done = true
dataIndex += dataSize
dataSize = 2
totalCount = byteArrayToInt(getBytes(data, dataIndex, dataSize))
aapsLogger.debug(LTag.PUMPCOMM, "History end. Code: " + error + " Success: " + (error == 0x00) + " Total count: " + totalCount)
} else {
val recordCode = byteArrayToInt(getBytes(data, DATA_START, 1))
val historyYear = byteArrayToInt(getBytes(data, DATA_START + 1, 1))
val historyMonth = byteArrayToInt(getBytes(data, DATA_START + 2, 1))
val historyDay = byteArrayToInt(getBytes(data, DATA_START + 3, 1))
val historyHour = byteArrayToInt(getBytes(data, DATA_START + 4, 1))
val dailyBasal: Double = ((data[DATA_START + 4].toInt() and 0xFF shl 8) + (data[DATA_START + 5].toInt() and 0xFF)) * 0.01
val historyMinute = byteArrayToInt(getBytes(data, DATA_START + 5, 1))
val historySecond = byteArrayToInt(getBytes(data, DATA_START + 6, 1))
val paramByte7 = historySecond.toByte()
val dailyBolus: Double = ((data[DATA_START + 6].toInt() and 0xFF shl 8) + (data[DATA_START + 7].toInt() and 0xFF)) * 0.01
val historyCode = byteArrayToInt(getBytes(data, DATA_START + 7, 1))
val paramByte8 = historyCode.toByte()
val value: Int = (data[DATA_START + 8].toInt() and 0xFF shl 8) + (data[DATA_START + 9].toInt() and 0xFF)
// danaRHistoryRecord.code is different from DanaR codes
// set in switch for every type
var messageType = ""
when (recordCode) {
0x02 -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS
val datetime = DateTime(2000 + historyYear, historyMonth, historyDay, historyHour, historyMinute)
danaRHistoryRecord.timestamp = datetime.millis
when (0xF0 and paramByte8.toInt()) {
0xA0 -> {
danaRHistoryRecord.bolusType = "DS"
messageType += "DS bolus"
}
0xC0 -> {
danaRHistoryRecord.bolusType = "E"
messageType += "E bolus"
}
0x80 -> {
danaRHistoryRecord.bolusType = "S"
messageType += "S bolus"
}
0x90 -> {
danaRHistoryRecord.bolusType = "DE"
messageType += "DE bolus"
}
else -> danaRHistoryRecord.bolusType = "None"
}
danaRHistoryRecord.duration = T.mins((paramByte8.toInt() and 0x0F) * 60 + paramByte7.toLong()).msecs()
danaRHistoryRecord.value = value * 0.01
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetime.millis) + " Code: " + historyCode + " Value: " + value)
}
0x03 -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_DAILY
messageType += "dailyinsulin"
val date = DateTime(2000 + historyYear, historyMonth, historyDay, 0, 0)
danaRHistoryRecord.timestamp = date.millis
danaRHistoryRecord.dailyBasal = dailyBasal
danaRHistoryRecord.dailyBolus = dailyBolus
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(date.millis) + " Code: " + historyCode + " Value: " + value)
}
0x04 -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_PRIME
messageType += "prime"
val datetimewihtsec = DateTime(2000 + historyYear, historyMonth, historyDay, historyHour, historyMinute, historySecond)
danaRHistoryRecord.timestamp = datetimewihtsec.millis
danaRHistoryRecord.value = value * 0.01
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetimewihtsec.millis) + " Code: " + historyCode + " Value: " + value)
}
0x05 -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_REFILL
messageType += "refill"
val datetimewihtsec = DateTime(2000 + historyYear, historyMonth, historyDay, historyHour, historyMinute, historySecond)
danaRHistoryRecord.timestamp = datetimewihtsec.millis
danaRHistoryRecord.value = value * 0.01
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetimewihtsec.millis) + " Code: " + historyCode + " Value: " + value)
}
0x0b -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_BASALHOUR
messageType += "basal hour"
val datetimewihtsec = DateTime(2000 + historyYear, historyMonth, historyDay, historyHour, historyMinute, historySecond)
danaRHistoryRecord.timestamp = datetimewihtsec.millis
danaRHistoryRecord.value = value * 0.01
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetimewihtsec.millis) + " Code: " + historyCode + " Value: " + value)
}
0x99 -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_TEMP_BASAL
messageType += "tb"
val datetimewihtsec = DateTime(2000 + historyYear, historyMonth, historyDay, historyHour, historyMinute, historySecond)
danaRHistoryRecord.timestamp = datetimewihtsec.millis
danaRHistoryRecord.value = value * 0.01
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetimewihtsec.millis) + " Code: " + historyCode + " Value: " + value)
}
0x06 -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_GLUCOSE
messageType += "glucose"
val datetimewihtsec = DateTime(2000 + historyYear, historyMonth, historyDay, historyHour, historyMinute, historySecond)
danaRHistoryRecord.timestamp = datetimewihtsec.millis
danaRHistoryRecord.value = value.toDouble()
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetimewihtsec.millis) + " Code: " + historyCode + " Value: " + value)
}
0x07 -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_CARBO
messageType += "carbo"
val datetimewihtsec = DateTime(2000 + historyYear, historyMonth, historyDay, historyHour, historyMinute, historySecond)
danaRHistoryRecord.timestamp = datetimewihtsec.millis
danaRHistoryRecord.value = value.toDouble()
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetimewihtsec.millis) + " Code: " + historyCode + " Value: " + value)
}
0x0a -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_ALARM
messageType += "alarm"
val datetimewihtsec = DateTime(2000 + historyYear, historyMonth, historyDay, historyHour, historyMinute, historySecond)
danaRHistoryRecord.timestamp = datetimewihtsec.millis
var strAlarm = "None"
when (paramByte8) {
'P'.code.toByte() -> strAlarm = "Basal Compare"
'R'.code.toByte() -> strAlarm = "Empty Reservoir"
'C'.code.toByte() -> strAlarm = "Check"
'O'.code.toByte() -> strAlarm = "Occlusion"
'M'.code.toByte() -> strAlarm = "Basal max"
'D'.code.toByte() -> strAlarm = "Daily max"
'B'.code.toByte() -> strAlarm = "Low Battery"
'S'.code.toByte() -> strAlarm = "Shutdown"
}
danaRHistoryRecord.alarm = strAlarm
danaRHistoryRecord.value = value * 0.01
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetimewihtsec.millis) + " Code: " + historyCode + " Value: " + value)
}
0x09 -> {
danaRHistoryRecord.code = RecordTypes.RECORD_TYPE_SUSPEND
messageType += "suspend"
val datetimewihtsec = DateTime(2000 + historyYear, historyMonth, historyDay, historyHour, historyMinute, historySecond)
danaRHistoryRecord.timestamp = datetimewihtsec.millis
var strRecordValue = "Off"
if (paramByte8.toInt() == 79) strRecordValue = "On"
danaRHistoryRecord.stringValue = strRecordValue
aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetimewihtsec.millis) + " Code: " + historyCode + " Value: " + value)
}
}
danaHistoryRecordDao.createOrUpdate(danaRHistoryRecord)
//If it is a TDD, store it for stats also.
if (danaRHistoryRecord.code == RecordTypes.RECORD_TYPE_DAILY) {
pumpSync.createOrUpdateTotalDailyDose(
timestamp = danaRHistoryRecord.timestamp,
bolusAmount = danaRHistoryRecord.dailyBolus,
basalAmount = danaRHistoryRecord.dailyBasal,
totalAmount = 0.0,
pumpId = null,
pumpType = danaPump.pumpType(),
danaPump.serialNumber
)
}
rxBus.send(EventDanaRSyncStatus(dateUtil.dateAndTimeString(danaRHistoryRecord.timestamp) + " " + messageType))
}
}
} | agpl-3.0 | 7d609b03b9e61a4e7647041e89359c80 | 53.522634 | 196 | 0.57337 | 4.561983 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt | 1 | 5848 | package info.nightscout.androidaps.plugins.constraints.objectives.activities
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.ObjectivesExamFragmentBinding
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.Option
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.interfaces.ResourceHelper
import javax.inject.Inject
class ObjectivesExamDialog : DaggerDialogFragment() {
@Inject lateinit var rxBus: RxBus
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var dateUtil: DateUtil
companion object {
var objective: Objective? = null
}
private var currentTask = 0
private var _binding: ObjectivesExamFragmentBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
// load data from bundle
(savedInstanceState ?: arguments)?.let { bundle ->
currentTask = bundle.getInt("currentTask", 0)
}
_binding = ObjectivesExamFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onStart() {
super.onStart()
dialog?.setCanceledOnTouchOutside(false)
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
override fun onResume() {
super.onResume()
updateGui()
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
bundle.putInt("currentTask", currentTask)
}
@Synchronized
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
@Synchronized
fun updateGui() {
if (_binding == null) return
objective?.let { objective ->
val task: ExamTask = objective.tasks[currentTask] as ExamTask
binding.examName.setText(task.task)
binding.examQuestion.setText(task.question)
// Options
binding.examOptions.removeAllViews()
task.options.forEach {
context?.let { context ->
val cb = it.generate(context)
if (task.answered) {
cb.isEnabled = false
if (it.isCorrect)
cb.isChecked = true
}
binding.examOptions.addView(cb)
}
}
// Hints
binding.examHints.removeAllViews()
for (h in task.hints) {
context?.let { binding.examHints.addView(h.generate(it)) }
}
// Disabled to
binding.examDisabledto.text = rh.gs(R.string.answerdisabledto, dateUtil.timeString(task.disabledTo))
binding.examDisabledto.visibility = if (task.isEnabledAnswer()) View.GONE else View.VISIBLE
// Buttons
binding.examVerify.isEnabled = !task.answered && task.isEnabledAnswer()
binding.examVerify.setOnClickListener {
var result = true
for (o in task.options) {
val option: Option = o
result = result && option.evaluate()
}
task.answered = result
if (!result) {
task.disabledTo = dateUtil.now() + T.hours(1).msecs()
context?.let { it1 -> ToastUtils.showToastInUiThread(it1, R.string.wronganswer) }
} else task.disabledTo = 0
updateGui()
rxBus.send(EventObjectivesUpdateGui())
}
binding.close.setOnClickListener { dismiss() }
binding.examReset.setOnClickListener {
task.answered = false
//task.disabledTo = 0
updateGui()
rxBus.send(EventObjectivesUpdateGui())
}
binding.backButton.isEnabled = currentTask != 0
binding.backButton.setOnClickListener {
currentTask--
updateGui()
}
binding.nextButton.isEnabled = currentTask != objective.tasks.size - 1
binding.nextButton.setOnClickListener {
currentTask++
updateGui()
}
binding.nextUnansweredButton.isEnabled = !objective.isCompleted
binding.nextUnansweredButton.setOnClickListener {
for (i in (currentTask + 1) until objective.tasks.size) {
if (!objective.tasks[i].isCompleted()) {
currentTask = i
updateGui()
return@setOnClickListener
}
}
for (i in 0..currentTask) {
if (!objective.tasks[i].isCompleted()) {
currentTask = i
updateGui()
return@setOnClickListener
}
}
}
}
}
}
| agpl-3.0 | 731da6303d598d5a26266b0cabd51025 | 36.974026 | 112 | 0.597298 | 5.340639 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/EffectiveProfileSwitchDataPoint.kt | 1 | 998 | package info.nightscout.androidaps.plugins.general.overview.graphExtensions
import android.content.Context
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch
import info.nightscout.androidaps.interfaces.ResourceHelper
class EffectiveProfileSwitchDataPoint(
val data: EffectiveProfileSwitch,
private val rh: ResourceHelper,
private val scale: Scale
) : DataPointWithLabelInterface {
override fun getX(): Double = data.timestamp.toDouble()
override fun getY(): Double = scale.transform(data.originalPercentage.toDouble())
override fun setY(y: Double) {}
override val label get() = if (data.originalPercentage != 100) data.originalPercentage.toString() + "%" else ""
override val duration = 0L
override val shape = PointsWithLabelGraphSeries.Shape.PROFILE
override val size = 2f
override fun color(context: Context?): Int {
return rh.gac(context, R.attr.profileSwitchColor)
}
} | agpl-3.0 | f51f62c3c2315df454446ed44641be0a | 40.625 | 115 | 0.766533 | 4.577982 | false | false | false | false |
ok2c/httpcomponents-release-tools | release-lib/src/main/kotlin/com/github/ok2c/hc/release/git/GetTagsCommand.kt | 1 | 2333 | /*
* Copyright 2020, OK2 Consulting Ltd
*
* 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.github.ok2c.hc.release.git
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.GitCommand
import org.eclipse.jgit.api.errors.RefNotFoundException
import org.eclipse.jgit.internal.JGitText
import org.eclipse.jgit.lib.Constants
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevWalk
import java.text.MessageFormat
class GetTagsCommand(repo: Repository) : GitCommand<List<String>>(repo) {
private var target: String? = null
private var startingWith: String? = null
fun setTarget(target: String?): GetTagsCommand {
this.target = target
return this
}
fun setStartingWith(startingWith: String?): GetTagsCommand {
this.startingWith = startingWith
return this
}
override fun call(): List<String> {
checkCallable()
val id = repo.resolve(target ?: Constants.HEAD)
?: throw RefNotFoundException(MessageFormat.format(JGitText.get().refNotResolved, target))
val tags = mutableListOf<String>()
RevWalk(repo).use { walker ->
val commitRef = walker.parseCommit(id)
for (ref in repo.refDatabase.getRefs(Constants.R_TAGS).values) {
val peeledRef = repo.peel(ref)
if (peeledRef.peeledObjectId == commitRef) {
val name = peeledRef.name.removePrefix("refs/tags/")
val pattern = startingWith
if (pattern == null || name.startsWith(pattern)) {
tags.add(name)
}
}
}
}
setCallable(false)
return tags
}
}
fun Git.getAllTags(): GetTagsCommand {
return GetTagsCommand(repository)
}
| apache-2.0 | e8156036d35b3ea552a6ff3745755c13 | 33.308824 | 106 | 0.659666 | 4.166071 | false | false | false | false |
google/identity-credential | appverifier/src/main/java/com/android/mdl/appreader/viewModel/RequestCustomViewModel.kt | 1 | 1332 | package com.android.mdl.appreader.viewModel
import androidx.lifecycle.ViewModel
import com.android.mdl.appreader.document.RequestDocument
class RequestCustomViewModel : ViewModel() {
private var selectedDataItems = mutableListOf<String>()
private lateinit var requestDocument: RequestDocument
private var isInitiated = false
fun init(requestDocument: RequestDocument) {
if (!isInitiated) {
this.requestDocument = requestDocument
requestDocument.dataItems.forEach { dataItem ->
selectedDataItems.add(dataItem.identifier)
}
isInitiated = true
}
}
fun isSelectedDataItem(identifier: String) = selectedDataItems.any { it == identifier }
fun dataItemSelected(identifier: String) {
if (isSelectedDataItem(identifier)) {
selectedDataItems.remove(identifier)
} else {
selectedDataItems.add(identifier)
}
}
fun getSelectedDataItems(intentToRetain: Boolean): Map<String, Boolean> {
if (!isInitiated) {
throw IllegalStateException("Needed to be initiated with a request document")
}
val map = mutableMapOf<String, Boolean>()
selectedDataItems.forEach {
map[it] = intentToRetain
}
return map
}
} | apache-2.0 | 1f310e6f5ae5bcbd7014b5ec2c74f6e6 | 29.295455 | 91 | 0.656907 | 5.045455 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/PostSettingsTagsFragment.kt | 1 | 1483 | package org.wordpress.android.ui.posts
import android.content.Context
import android.os.Bundle
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.fluxc.model.SiteModel
class PostSettingsTagsFragment : TagsFragment() {
override fun getContentLayout() = R.layout.fragment_post_settings_tags
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(requireActivity().application as WordPress).component().inject(this)
}
override fun onAttach(context: Context) {
super.onAttach(context)
mTagsSelectedListener = if (context is PostSettingsTagsActivity) {
context
} else {
throw RuntimeException("$context must implement TagsSelectedListener")
}
}
override fun onDetach() {
super.onDetach()
mTagsSelectedListener = null
}
override fun getTagsFromEditPostRepositoryOrArguments() = arguments?.getString(PostSettingsTagsActivity.KEY_TAGS)
companion object {
const val TAG = "post_settings_tags_fragment_tag"
@JvmStatic fun newInstance(site: SiteModel, tags: String?): PostSettingsTagsFragment {
val bundle = Bundle().apply {
putSerializable(WordPress.SITE, site)
putString(PostSettingsTagsActivity.KEY_TAGS, tags)
}
return PostSettingsTagsFragment().apply { arguments = bundle }
}
}
}
| gpl-2.0 | a0f48271a7c9f07e9a52a7d3ea025a7d | 33.488372 | 117 | 0.688469 | 4.894389 | false | false | false | false |
edwardharks/Aircraft-Recognition | androidcommon/src/main/kotlin/com/edwardharker/aircraftrecognition/ui/ExtendedFrameLayout.kt | 1 | 1281 | package com.edwardharker.aircraftrecognition.ui
import android.content.Context
import android.util.AttributeSet
import android.view.View.MeasureSpec.getMode
import android.view.View.MeasureSpec.getSize
import android.view.View.MeasureSpec.makeMeasureSpec
import android.widget.FrameLayout
import com.edwardharker.aircraftrecognition.androidcommon.R
import java.lang.Integer.MAX_VALUE
import java.lang.Math.min
class ExtendedFrameLayout : FrameLayout {
var maxWidth: Int = MAX_VALUE
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
attrs?.let {
val a = context.obtainStyledAttributes(attrs, R.styleable.ExtendedFrameLayout)
maxWidth = a.getDimensionPixelSize(R.styleable.ExtendedFrameLayout_maxWidth, MAX_VALUE)
a.recycle()
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val measureMode = getMode(widthMeasureSpec)
val boundedWidth = makeMeasureSpec(min(getSize(widthMeasureSpec), maxWidth), measureMode)
super.onMeasure(boundedWidth, heightMeasureSpec)
}
}
| gpl-3.0 | af4a988e77f6c76a3e4affb9676637f6 | 36.676471 | 106 | 0.752537 | 4.607914 | false | false | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/ide/lightEdit/project/LightEditProjectImpl.kt | 1 | 3726 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.lightEdit.project
import com.intellij.ide.impl.runUnderModalProgressIfIsEdt
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.projectInitListeners
import com.intellij.openapi.roots.FileIndexFacade
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.impl.DirectoryIndex
import kotlinx.coroutines.coroutineScope
import java.io.File
import java.nio.file.Path
internal class LightEditProjectImpl private constructor(projectPath: Path) : ProjectImpl(projectPath, NAME), LightEditCompatible {
companion object {
private val LOG = logger<LightEditProjectImpl>()
private const val NAME = "LightEditProject"
private val projectPath: Path
get() = Path.of(PathManager.getConfigPath() + File.separator + "light-edit")
}
constructor() : this(projectPath)
init {
registerComponents()
customizeRegisteredComponents()
componentStore.setPath(projectPath, false, null)
runUnderModalProgressIfIsEdt {
coroutineScope {
preloadServicesAndCreateComponents(project = this@LightEditProjectImpl, preloadServices = true)
projectInitListeners {
it.containerConfigured(this@LightEditProjectImpl)
}
}
}
}
private fun customizeRegisteredComponents() {
val pluginDescriptor = PluginManagerCore.getPlugin(PluginManagerCore.CORE_ID)
if (pluginDescriptor == null) {
LOG.error("Could not find plugin by id: ${PluginManagerCore.CORE_ID}")
return
}
registerService(serviceInterface = DirectoryIndex::class.java,
implementation = LightEditDirectoryIndex::class.java,
pluginDescriptor = pluginDescriptor,
override = true,
preloadMode = ServiceDescriptor.PreloadMode.FALSE)
registerService(serviceInterface = ProjectFileIndex::class.java,
implementation = LightEditProjectFileIndex::class.java,
pluginDescriptor = pluginDescriptor,
override = true,
preloadMode = ServiceDescriptor.PreloadMode.FALSE)
registerService(serviceInterface = FileIndexFacade::class.java,
implementation = LightEditFileIndexFacade::class.java,
pluginDescriptor = pluginDescriptor,
override = true,
preloadMode = ServiceDescriptor.PreloadMode.FALSE)
registerService(serviceInterface = DumbService::class.java,
implementation = LightEditDumbService::class.java,
pluginDescriptor = pluginDescriptor,
override = true,
preloadMode = ServiceDescriptor.PreloadMode.FALSE)
registerComponent(key = FileEditorManager::class.java,
implementation = LightEditFileEditorManagerImpl::class.java,
pluginDescriptor = pluginDescriptor,
override = true)
}
override fun setProjectName(value: String) {
throw IllegalStateException()
}
override fun getName() = NAME
override fun getLocationHash() = name
override fun isOpen() = true
override fun isInitialized() = true
} | apache-2.0 | c91dd6a6c1c8cfa44efae12a9a8816c2 | 40.411111 | 130 | 0.711218 | 5.487482 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/test/java/org/thoughtcrime/securesms/conversation/ConversationUpdateTickTest.kt | 4 | 2565 | package org.thoughtcrime.securesms.conversation
import android.app.Application
import androidx.lifecycle.LifecycleOwner
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowLooper
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE, application = Application::class)
class ConversationUpdateTickTest {
private val lifecycleOwner = mock(LifecycleOwner::class.java)
private val listener = mock(ConversationUpdateTick.OnTickListener::class.java)
private val testSubject = ConversationUpdateTick(listener)
private val timeoutMillis = ConversationUpdateTick.TIMEOUT
@Test
fun `Given onResume not invoked, then I expect zero invocations of onTick`() {
// THEN
verify(listener, never()).onTick()
}
@Test
fun `Given no time has passed after onResume is invoked, then I expect one invocations of onTick`() {
// GIVEN
ShadowLooper.pauseMainLooper()
testSubject.onResume(lifecycleOwner)
// THEN
verify(listener, times(1)).onTick()
}
@Test
fun `Given onResume is invoked, when half timeout passes, then I expect one invocations of onTick`() {
// GIVEN
testSubject.onResume(lifecycleOwner)
ShadowLooper.idleMainLooper(timeoutMillis / 2, TimeUnit.MILLISECONDS)
// THEN
verify(listener, times(1)).onTick()
}
@Test
fun `Given onResume is invoked, when timeout passes, then I expect two invocations of onTick`() {
// GIVEN
testSubject.onResume(lifecycleOwner)
// WHEN
ShadowLooper.idleMainLooper(timeoutMillis, TimeUnit.MILLISECONDS)
// THEN
verify(listener, times(2)).onTick()
}
@Test
fun `Given onResume is invoked, when timeout passes five times, then I expect six invocations of onTick`() {
// GIVEN
testSubject.onResume(lifecycleOwner)
// WHEN
ShadowLooper.idleMainLooper(timeoutMillis * 5, TimeUnit.MILLISECONDS)
// THEN
verify(listener, times(6)).onTick()
}
@Test
fun `Given onResume then onPause is invoked, when timeout passes, then I expect one invocation of onTick`() {
// GIVEN
testSubject.onResume(lifecycleOwner)
testSubject.onPause(lifecycleOwner)
// WHEN
ShadowLooper.idleMainLooper(timeoutMillis, TimeUnit.MILLISECONDS)
// THEN
verify(listener, times(1)).onTick()
}
}
| gpl-3.0 | 14cb50d5c69246b5cf21b475922190f2 | 28.147727 | 111 | 0.745029 | 4.468641 | false | true | false | false |
GunoH/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/ResumeIndexingAction.kt | 5 | 3938 | // 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.vcs.log.ui.actions
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.data.index.VcsLogBigRepositoriesList
import com.intellij.vcs.log.data.index.VcsLogIndex
import com.intellij.vcs.log.data.index.VcsLogModifiableIndex
import com.intellij.vcs.log.data.index.VcsLogPersistentIndex
import com.intellij.vcs.log.impl.VcsLogSharedSettings
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
import com.intellij.vcs.log.util.VcsLogUtil
class ResumeIndexingAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val data = e.getData(VcsLogInternalDataKeys.LOG_DATA)
val project = e.project
if (data == null || project == null || !VcsLogSharedSettings.isIndexSwitchedOn(project)) {
e.presentation.isEnabledAndVisible = false
return
}
val rootsForIndexing = VcsLogPersistentIndex.getRootsForIndexing(data.logProviders)
if (rootsForIndexing.isEmpty()) {
e.presentation.isEnabledAndVisible = false
return
}
val scheduledForIndexing = rootsForIndexing.filter { it.isScheduledForIndexing(data.index) }
val bigRepositories = rootsForIndexing.filter { it.isBig() }
e.presentation.isEnabledAndVisible = (bigRepositories.isNotEmpty() || scheduledForIndexing.isNotEmpty())
val vcsDisplayName = VcsLogUtil.getVcsDisplayName(project, rootsForIndexing.map { data.getLogProvider(it) })
if (scheduledForIndexing.isNotEmpty()) {
e.presentation.text = VcsLogBundle.message("action.title.pause.indexing", vcsDisplayName)
e.presentation.description = VcsLogBundle.message("action.description.is.scheduled", getText(scheduledForIndexing))
e.presentation.icon = AllIcons.Process.ProgressPauseSmall
}
else {
e.presentation.text = VcsLogBundle.message("action.title.resume.indexing", vcsDisplayName)
e.presentation.description = VcsLogBundle.message("action.description.was.paused", getText(bigRepositories))
e.presentation.icon = AllIcons.Process.ProgressResumeSmall
}
}
private fun getText(repositories: List<VirtualFile>): String {
val repositoriesLimit = 3
val result = repositories.map { it.name }.sorted().take(repositoriesLimit).joinToString(", ") { "'$it'" }
if (repositories.size > repositoriesLimit) {
return "$result, ..."
}
return result
}
override fun actionPerformed(e: AnActionEvent) {
VcsLogUsageTriggerCollector.triggerUsage(e, this)
val data = e.getRequiredData(VcsLogInternalDataKeys.LOG_DATA)
val rootsForIndexing = VcsLogPersistentIndex.getRootsForIndexing(data.logProviders)
if (rootsForIndexing.isEmpty()) return
if (rootsForIndexing.any { it.isScheduledForIndexing(data.index) }) {
rootsForIndexing.filter { !it.isBig() }.forEach { VcsLogBigRepositoriesList.getInstance().addRepository(it) }
}
else {
var resumed = false
for (root in rootsForIndexing.filter { it.isBig() }) {
resumed = resumed or VcsLogBigRepositoriesList.getInstance().removeRepository(root)
}
if (resumed) (data.index as? VcsLogModifiableIndex)?.scheduleIndex(false)
}
}
private fun VirtualFile.isBig(): Boolean = VcsLogBigRepositoriesList.getInstance().isBig(this)
private fun VirtualFile.isScheduledForIndexing(index: VcsLogIndex): Boolean = index.isIndexingEnabled(this) &&
!index.isIndexed(this)
override fun getActionUpdateThread() = ActionUpdateThread.BGT
} | apache-2.0 | 0b9c0c85007791bfa98d813cac08618d | 46.457831 | 121 | 0.748857 | 4.510882 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/JavaToKotlinConverterServices.kt | 4 | 1622 | // 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.j2k
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.idea.j2k.DocCommentConverter
import org.jetbrains.kotlin.idea.j2k.EmptyDocCommentConverter
interface JavaToKotlinConverterServices {
val referenceSearcher: ReferenceSearcher
val superMethodsSearcher: SuperMethodsSearcher
val resolverForConverter: ResolverForConverter
val docCommentConverter: DocCommentConverter
val javaDataFlowAnalyzerFacade: JavaDataFlowAnalyzerFacade
}
object EmptyJavaToKotlinServices: JavaToKotlinConverterServices {
override val referenceSearcher: ReferenceSearcher
get() = EmptyReferenceSearcher
override val superMethodsSearcher: SuperMethodsSearcher
get() = SuperMethodsSearcher.Default
override val resolverForConverter: ResolverForConverter
get() = EmptyResolverForConverter
override val docCommentConverter: DocCommentConverter
get() = EmptyDocCommentConverter
override val javaDataFlowAnalyzerFacade: JavaDataFlowAnalyzerFacade
get() = JavaDataFlowAnalyzerFacade.Default
}
interface SuperMethodsSearcher {
fun findDeepestSuperMethods(method: PsiMethod): Collection<PsiMethod>
object Default : SuperMethodsSearcher {
// use simple findSuperMethods by default because findDeepestSuperMethods requires some service from IDEA
override fun findDeepestSuperMethods(method: PsiMethod) = method.findSuperMethods().asList()
}
}
| apache-2.0 | 55673adf7fc9844dced819c611adce4b | 38.560976 | 158 | 0.79963 | 5.517007 | false | false | false | false |
GunoH/intellij-community | java/compiler/impl/src/com/intellij/packaging/impl/elements/ProductionModuleSourcePackagingElement.kt | 2 | 2999 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.packaging.impl.elements
import com.intellij.openapi.module.ModulePointer
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.packaging.elements.PackagingElementOutputKind
import com.intellij.packaging.elements.PackagingElementResolvingContext
import com.intellij.packaging.impl.artifacts.workspacemodel.mutableElements
import com.intellij.packaging.impl.ui.DelegatedPackagingElementPresentation
import com.intellij.packaging.impl.ui.ModuleElementPresentation
import com.intellij.packaging.ui.ArtifactEditorContext
import com.intellij.packaging.ui.PackagingElementPresentation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId
import com.intellij.workspaceModel.storage.bridgeEntities.addModuleSourcePackagingElementEntity
import org.jetbrains.annotations.NonNls
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
class ProductionModuleSourcePackagingElement : ModulePackagingElementBase {
constructor(project: Project) : super(ProductionModuleSourceElementType.ELEMENT_TYPE, project) {}
constructor(project: Project, modulePointer: ModulePointer) : super(ProductionModuleSourceElementType.ELEMENT_TYPE,
project,
modulePointer)
override fun getSourceRoots(context: PackagingElementResolvingContext): Collection<VirtualFile> {
val module = findModule(context) ?: return emptyList()
val rootModel = context.modulesProvider.getRootModel(module)
return rootModel.getSourceRoots(JavaModuleSourceRootTypes.PRODUCTION)
}
override fun createPresentation(context: ArtifactEditorContext): PackagingElementPresentation {
return DelegatedPackagingElementPresentation(
ModuleElementPresentation(myModulePointer, context, ProductionModuleSourceElementType.ELEMENT_TYPE))
}
override fun getFilesKind(context: PackagingElementResolvingContext) = PackagingElementOutputKind.OTHER
override fun getOrAddEntity(diff: MutableEntityStorage, source: EntitySource, project: Project): WorkspaceEntity {
val existingEntity = getExistingEntity(diff)
if (existingEntity != null) return existingEntity
val moduleName = this.moduleName
val addedEntity = if (moduleName != null) {
diff.addModuleSourcePackagingElementEntity(ModuleId(moduleName), source)
}
else {
diff.addModuleSourcePackagingElementEntity(null, source)
}
diff.mutableElements.addMapping(addedEntity, this)
return addedEntity
}
@NonNls
override fun toString() = "module sources:" + moduleName!!
}
| apache-2.0 | 0433e597b19467cd44d443f3f084ef4b | 48.163934 | 140 | 0.791931 | 5.298587 | false | false | false | false |
brianwernick/PlaylistCore | demo/src/main/java/com/devbrackets/android/playlistcoredemo/data/MediaItem.kt | 1 | 1134 | package com.devbrackets.android.playlistcoredemo.data
import com.devbrackets.android.playlistcore.annotation.SupportedMediaType
import com.devbrackets.android.playlistcore.api.PlaylistItem
import com.devbrackets.android.playlistcore.manager.BasePlaylistManager
/**
* A custom [PlaylistItem]
* to hold the information pertaining to the audio and video items
*/
class MediaItem(
private val sample: Samples.Sample,
internal var isAudio: Boolean
) : PlaylistItem {
override val id: Long
get() = 0
override val downloaded: Boolean
get() = false
@SupportedMediaType
override val mediaType: Int
get() = if (isAudio) BasePlaylistManager.AUDIO else BasePlaylistManager.VIDEO
override val mediaUrl: String
get() = sample.mediaUrl
override val downloadedMediaUri: String?
get() = null
override val thumbnailUrl: String?
get() = sample.artworkUrl
override val artworkUrl: String?
get() = sample.artworkUrl
override val title: String
get() = sample.title
override val album: String
get() = "PlaylistCore Demo"
override val artist: String
get() = "Unknown Artist"
} | apache-2.0 | 00339212d584e701d18358e1f99a3d40 | 23.148936 | 81 | 0.742504 | 4.517928 | false | false | false | false |
jk1/intellij-community | community-guitests/testSrc/com/intellij/ide/projectWizard/kotlin/installKotlinPlugin/InstallPluginGuiTest.kt | 2 | 1837 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.projectWizard.kotlin.installKotlinPlugin
import com.intellij.ide.projectWizard.kotlin.model.KotlinGuiTestCase
import com.intellij.ide.projectWizard.kotlin.model.KOTLIN_PLUGIN_NAME
import com.intellij.ide.projectWizard.kotlin.model.KotlinTestProperties
import com.intellij.testGuiFramework.util.scenarios.*
import org.junit.Ignore
import kotlin.test.assertTrue
import kotlin.test.assertFalse
import org.junit.Test
class InstallPluginGuiTest : KotlinGuiTestCase() {
@Test
fun installKotlinPlugin() {
//TODO: uncomment when new design of Plugins dialog is finished
// if (!pluginsDialogScenarios
// .isPluginRequiredVersionInstalled(KOTLIN_PLUGIN_NAME, KotlinTestProperties.kotlin_plugin_version_full)) {
pluginsDialogScenarios.actionAndRestart {
pluginsDialogScenarios.installPluginFromDisk(KotlinTestProperties.kotlin_plugin_install_path)
}
// assertTrue(
// actual = pluginsDialogScenarios
// .isPluginRequiredVersionInstalled(KOTLIN_PLUGIN_NAME, KotlinTestProperties.kotlin_plugin_version_full),
// message = "Kotlin plugin `${KotlinTestProperties.kotlin_plugin_version_full}` is not installed")
// }
}
@Test
@Ignore
fun uninstallKotlinPlugin() {
pluginsDialogScenarios.actionAndRestart {
pluginsDialogScenarios.uninstallPlugin(KOTLIN_PLUGIN_NAME)
}
assertFalse(
actual = pluginsDialogScenarios
.isPluginRequiredVersionInstalled(KOTLIN_PLUGIN_NAME, KotlinTestProperties.kotlin_plugin_version_full),
message = "Kotlin plugin `${KotlinTestProperties.kotlin_plugin_version_full}` is not uninstalled")
}
override fun isIdeFrameRun(): Boolean = false
} | apache-2.0 | 7c0c3e4538be5c7c778e07cbcc5d6423 | 42.761905 | 140 | 0.773544 | 4.524631 | false | true | false | false |
ktorio/ktor | ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/Frame.kt | 1 | 6261 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.websocket
import io.ktor.util.*
import io.ktor.utils.io.core.*
import kotlinx.coroutines.*
import java.nio.*
/**
* A frame received or ready to be sent. It is not reusable and not thread-safe
* @property fin is it final fragment, should be always `true` for control frames and if no fragmentation is used
* @property frameType enum value
* @property data - a frame content or fragment content
* @property disposableHandle could be invoked when the frame is processed
*/
public actual sealed class Frame actual constructor(
public actual val fin: Boolean,
public actual val frameType: FrameType,
public actual val data: ByteArray,
public actual val disposableHandle: DisposableHandle,
public actual val rsv1: Boolean,
public actual val rsv2: Boolean,
public actual val rsv3: Boolean
) {
/**
* Frame content
*/
public val buffer: ByteBuffer = ByteBuffer.wrap(data)
/**
* Represents an application level binary frame.
* In a RAW web socket session a big text frame could be fragmented
* (separated into several text frames so they have [fin] = false except the last one).
* Note that usually there is no need to handle fragments unless you have a RAW web socket session.
*/
public actual class Binary actual constructor(
fin: Boolean,
data: ByteArray,
rsv1: Boolean,
rsv2: Boolean,
rsv3: Boolean
) : Frame(fin, FrameType.BINARY, data, NonDisposableHandle, rsv1, rsv2, rsv3) {
public constructor(fin: Boolean, buffer: ByteBuffer) : this(fin, buffer.moveToByteArray())
public actual constructor(fin: Boolean, data: ByteArray) : this(fin, data, false, false, false)
public actual constructor(fin: Boolean, packet: ByteReadPacket) : this(fin, packet.readBytes())
}
/**
* Represents an application level text frame.
* In a RAW web socket session a big text frame could be fragmented
* (separated into several text frames so they have [fin] = false except the last one).
* Please note that a boundary between fragments could be in the middle of multi-byte (unicode) character
* so don't apply String constructor to every fragment but use decoder loop instead of concatenate fragments first.
* Note that usually there is no need to handle fragments unless you have a RAW web socket session.
*/
public actual class Text actual constructor(
fin: Boolean,
data: ByteArray,
rsv1: Boolean,
rsv2: Boolean,
rsv3: Boolean
) : Frame(fin, FrameType.TEXT, data, NonDisposableHandle, rsv1, rsv2, rsv3) {
public actual constructor(fin: Boolean, data: ByteArray) : this(fin, data, false, false, false)
public actual constructor(text: String) : this(true, text.toByteArray())
public actual constructor(fin: Boolean, packet: ByteReadPacket) : this(fin, packet.readBytes())
public constructor(fin: Boolean, buffer: ByteBuffer) : this(fin, buffer.moveToByteArray())
}
/**
* Represents a low-level level close frame. It could be sent to indicate web socket session end.
* Usually there is no need to send/handle it unless you have a RAW web socket session.
*/
public actual class Close actual constructor(
data: ByteArray
) : Frame(true, FrameType.CLOSE, data, NonDisposableHandle, false, false, false) {
public actual constructor(reason: CloseReason) : this(
buildPacket {
writeShort(reason.code)
writeText(reason.message)
}
)
public actual constructor(packet: ByteReadPacket) : this(packet.readBytes())
public actual constructor() : this(Empty)
public constructor(buffer: ByteBuffer) : this(buffer.moveToByteArray())
}
/**
* Represents a low-level ping frame. Could be sent to test connection (peer should reply with [Pong]).
* Usually there is no need to send/handle it unless you have a RAW web socket session.
*/
public actual class Ping actual constructor(
data: ByteArray
) : Frame(true, FrameType.PING, data, NonDisposableHandle, false, false, false) {
public actual constructor(packet: ByteReadPacket) : this(packet.readBytes())
public constructor(buffer: ByteBuffer) : this(buffer.moveToByteArray())
}
/**
* Represents a low-level pong frame. Should be sent in reply to a [Ping] frame.
* Usually there is no need to send/handle it unless you have a RAW web socket session.
*/
public actual class Pong actual constructor(
data: ByteArray,
disposableHandle: DisposableHandle
) : Frame(true, FrameType.PONG, data, disposableHandle, false, false, false) {
public actual constructor(packet: ByteReadPacket) : this(packet.readBytes(), NonDisposableHandle)
public constructor(
buffer: ByteBuffer,
disposableHandle: DisposableHandle = NonDisposableHandle
) : this(buffer.moveToByteArray(), disposableHandle)
public constructor(buffer: ByteBuffer) : this(buffer.moveToByteArray(), NonDisposableHandle)
}
override fun toString(): String = "Frame $frameType (fin=$fin, buffer len = ${data.size})"
/**
* Creates a frame copy.
*/
public actual fun copy(): Frame = byType(fin, frameType, data.copyOf(), rsv1, rsv2, rsv3)
public actual companion object {
private val Empty: ByteArray = ByteArray(0)
/**
* Create a particular [Frame] instance by frame type.
*/
public actual fun byType(
fin: Boolean,
frameType: FrameType,
data: ByteArray,
rsv1: Boolean,
rsv2: Boolean,
rsv3: Boolean
): Frame = when (frameType) {
FrameType.BINARY -> Binary(fin, data, rsv1, rsv2, rsv3)
FrameType.TEXT -> Text(fin, data, rsv1, rsv2, rsv3)
FrameType.CLOSE -> Close(data)
FrameType.PING -> Ping(data)
FrameType.PONG -> Pong(data, NonDisposableHandle)
}
}
}
| apache-2.0 | dd071b201395cee32710ffcd816e8f9a | 39.393548 | 119 | 0.665069 | 4.517316 | false | false | false | false |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/data/repository/ShotDataRepository.kt | 1 | 2303 | package io.armcha.ribble.data.repository
import io.armcha.ribble.data.cache.MemoryCache
import io.armcha.ribble.data.mapper.Mapper
import io.armcha.ribble.data.network.ApiConstants
import io.armcha.ribble.data.network.ShotApiService
import io.armcha.ribble.di.scope.PerActivity
import io.armcha.ribble.domain.entity.Comment
import io.armcha.ribble.domain.entity.Like
import io.armcha.ribble.domain.entity.Shot
import io.armcha.ribble.domain.fetcher.result_listener.RequestType
import io.armcha.ribble.domain.repository.ShotRepository
import io.reactivex.Flowable
import io.reactivex.Single
import javax.inject.Inject
/**
* Created by Chatikyan on 02.08.2017.
*/
class ShotDataRepository(private var shotApiService: ShotApiService,
private val memoryCache: MemoryCache,
private val mapper: Mapper) : ShotRepository {
override fun getShotList(shotType: String, count: Int): Flowable<List<Shot>> {
val requestType = if (shotType == ApiConstants.TYPE_POPULAR)
RequestType.POPULAR_SHOTS
else
RequestType.RECENT_SHOTS
return if (memoryCache.hasCacheFor(requestType)) {
Flowable.fromCallable<List<Shot>> { memoryCache.getCacheForType(requestType) }
} else {
shotApiService.getShots(shotType, count)
.map { mapper.translate(it) }
.doOnNext { memoryCache.put(requestType, it) }
}
}
override fun getShotLikes(shotId: String): Flowable<List<Like>> {
return shotApiService.getShotLikes(shotId)
.map { mapper.translate(it) }
}
override fun getShotComments(shotId: String): Single<List<Comment>> =
if (memoryCache.hasCacheFor(RequestType.COMMENTS)) {
Single.fromCallable<List<Comment>> { memoryCache.getCacheForType(RequestType.COMMENTS) }
} else {
shotApiService.getShotComments(shotId)
.map { mapper.translate(it) }
.doOnSuccess { memoryCache.put(RequestType.COMMENTS, it) }
}
override fun likeShot(shotId: String) = shotApiService.likeShot(shotId)
override fun deleteCacheFor(requestType: RequestType) {
memoryCache.clearCacheFor(requestType)
}
} | apache-2.0 | f4a4ee9fb2d351be6f9c62f25faefd7b | 38.724138 | 104 | 0.680417 | 4.353497 | false | false | false | false |
ClearVolume/scenery | src/test/kotlin/graphics/scenery/tests/examples/volumes/VolumeSamplingExample.kt | 1 | 10770 | package graphics.scenery.tests.examples.volumes
import org.joml.Vector3f
import graphics.scenery.*
import graphics.scenery.backends.Renderer
import graphics.scenery.numerics.Random
import graphics.scenery.primitives.Cylinder
import graphics.scenery.primitives.Line
import graphics.scenery.attribute.material.Material
import graphics.scenery.utils.MaybeIntersects
import graphics.scenery.utils.RingBuffer
import graphics.scenery.utils.extensions.minus
import graphics.scenery.utils.extensions.plus
import graphics.scenery.utils.extensions.times
import graphics.scenery.volumes.Colormap
import graphics.scenery.volumes.Volume
import net.imglib2.type.numeric.integer.UnsignedByteType
import org.lwjgl.system.MemoryUtil.memAlloc
import org.scijava.Context
import org.scijava.ui.UIService
import org.scijava.ui.behaviour.ClickBehaviour
import org.scijava.widget.FileWidget
import java.io.File
import java.nio.ByteBuffer
import kotlin.concurrent.thread
/**
* Example that renders procedurally generated volumes and samples from it.
* [bitsPerVoxel] can be set to 8 or 16, to generate Byte or UnsignedShort volumes.
*
* @author Ulrik Günther <[email protected]>
*/
class VolumeSamplingExample: SceneryBase("Volume Sampling example", 1280, 720) {
val bitsPerVoxel = 8
val volumeSize = 128
enum class VolumeType { File, Procedural }
var volumeType = VolumeType.Procedural
lateinit var volumes: List<String>
var playing = true
var skipToNext = false
var skipToPrevious = false
var currentVolume = 0
override fun init() {
val files = ArrayList<String>()
val fileFromProperty = System.getProperty("dataset")
volumeType = if(fileFromProperty != null) {
files.add(fileFromProperty)
VolumeType.File
} else {
val c = Context()
val ui = c.getService(UIService::class.java)
val file = ui.chooseFile(null, FileWidget.DIRECTORY_STYLE)
if(file != null) {
files.add(file.absolutePath)
VolumeType.File
} else {
VolumeType.Procedural
}
}
if(volumeType == VolumeType.File) {
val folder = File(files.first())
val stackfiles = folder.listFiles()
volumes = stackfiles.filter { it.isFile && it.name.lowercase().endsWith("raw") || it.name.substringAfterLast(".").lowercase().startsWith("tif") }.map { it.absolutePath }.sorted()
}
renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight))
val cam: Camera = DetachedHeadCamera()
with(cam) {
spatial {
position = Vector3f(0.0f, 0.5f, 5.0f)
}
perspectiveCamera(50.0f, windowWidth, windowHeight)
scene.addChild(this)
}
val shell = Box(Vector3f(10.0f, 10.0f, 10.0f), insideNormals = true)
shell.material {
cullingMode = Material.CullingMode.None
diffuse = Vector3f(0.2f, 0.2f, 0.2f)
specular = Vector3f(0.0f)
ambient = Vector3f(0.0f)
}
shell.spatial {
position = Vector3f(0.0f, 4.0f, 0.0f)
}
scene.addChild(shell)
val p1 = Icosphere(0.2f, 2)
p1.spatial().position = Vector3f(-0.5f, 0.0f, -2.0f)
p1.material().diffuse = Vector3f(0.3f, 0.3f, 0.8f)
scene.addChild(p1)
val p2 = Icosphere(0.2f, 2)
p2.spatial().position = Vector3f(0.0f, 0.5f, 2.0f)
p2.material().diffuse = Vector3f(0.3f, 0.8f, 0.3f)
scene.addChild(p2)
val connector = Cylinder.betweenPoints(p1.spatial().position, p2.spatial().position)
connector.material().diffuse = Vector3f(1.0f, 1.0f, 1.0f)
scene.addChild(connector)
p1.update.add {
connector.spatial().orientBetweenPoints(p1.spatial().position, p2.spatial().position, true, true)
}
p2.update.add {
connector.spatial().orientBetweenPoints(p1.spatial().position, p2.spatial().position, true, true)
}
val volume = Volume.fromBuffer(emptyList(), volumeSize, volumeSize, volumeSize, UnsignedByteType(), hub)
volume.name = "volume"
volume.spatial {
position = Vector3f(0.0f, 0.0f, 0.0f)
scale = Vector3f(10.0f, 10.0f, 10.0f)
}
volume.colormap = Colormap.get("viridis")
// volume.voxelSizeZ = 0.5f
with(volume.transferFunction) {
addControlPoint(0.0f, 0.0f)
addControlPoint(0.2f, 0.0f)
addControlPoint(0.4f, 0.5f)
addControlPoint(0.8f, 0.5f)
addControlPoint(1.0f, 0.0f)
}
volume.metadata["animating"] = true
scene.addChild(volume)
val bb = BoundingGrid()
bb.node = volume
val lights = (0 until 3).map {
PointLight(radius = 15.0f)
}
lights.mapIndexed { i, light ->
light.spatial().position = Vector3f(2.0f * i - 4.0f, i - 1.0f, 0.0f)
light.emissionColor = Vector3f(1.0f, 1.0f, 1.0f)
light.intensity = 0.5f
scene.addChild(light)
}
thread {
while(!scene.initialized) { Thread.sleep(200) }
val volumeSize = 128L
val volumeBuffer = RingBuffer<ByteBuffer>(2) { memAlloc((volumeSize*volumeSize*volumeSize*bitsPerVoxel/8).toInt()) }
val seed = Random.randomFromRange(0.0f, 133333337.0f).toLong()
var shift = Vector3f(0.0f)
val shiftDelta = Random.random3DVectorFromRange(-1.5f, 1.5f)
while(running) {
when(volumeType) {
VolumeType.File -> if (playing || skipToNext || skipToPrevious) {
val newVolume = if (skipToNext || playing) {
skipToNext = false
nextVolume()
} else {
skipToPrevious = false
previousVolume()
}
logger.debug("Loading volume $newVolume")
if (newVolume.lowercase().endsWith("raw")) {
TODO("Implement reading volumes from raw files")
} else {
TODO("Implemented reading volumes from image files")
}
}
VolumeType.Procedural ->
if (volume.metadata["animating"] == true) {
val currentBuffer = volumeBuffer.get()
Volume.generateProceduralVolume(volumeSize, 0.05f, seed = seed,
intoBuffer = currentBuffer, shift = shift, use16bit = bitsPerVoxel > 8)
volume.addTimepoint(
"procedural-cloud-${shift.hashCode()}", currentBuffer)
shift = shift + shiftDelta
}
}
val intersection = volume.spatial().intersectAABB(p1.spatial().position, (p2.spatial().position - p1.spatial().position).normalize())
if(intersection is MaybeIntersects.Intersection) {
val scale = volume.localScale()
val localEntry = (intersection.relativeEntry + Vector3f(1.0f)) * (1.0f/2.0f)
val localExit = (intersection.relativeExit + Vector3f(1.0f)) * (1.0f/2.0f)
logger.info("Ray intersects volume at ${intersection.entry}/${intersection.exit} rel=${localEntry}/${localExit} localScale=$scale")
val (samples, _) = volume.sampleRay(localEntry, localExit) ?: null to null
logger.info("Samples: ${samples?.joinToString(",") ?: "(no samples returned)"}")
if(samples == null) {
continue
}
val diagram = if(connector.getChildrenByName("diagram").isNotEmpty()) {
connector.getChildrenByName("diagram").first() as Line
} else {
TODO("Implement volume size queries or refactor")
// val sizeX = 128
// val sizeY = 128
// val sizeZ = 128
// val l = Line(capacity = maxOf(sizeX, sizeY, sizeZ) * 2)
// connector.addChild(l)
// l
}
diagram.clearPoints()
diagram.name = "diagram"
diagram.edgeWidth = 0.005f
diagram.material().diffuse = Vector3f(0.05f, 0.05f, 0.05f)
diagram.spatial().position = Vector3f(0.0f, 0.0f, -0.5f)
diagram.addPoint(Vector3f(0.0f, 0.0f, 0.0f))
var point = Vector3f(0.0f)
samples.filterNotNull().forEachIndexed { i, sample ->
point = Vector3f(0.0f, i.toFloat()/samples.size, -sample)
diagram.addPoint(point)
}
diagram.addPoint(point)
}
Thread.sleep(20)
}
}
}
fun nextVolume(): String {
val v = volumes[currentVolume % volumes.size]
currentVolume++
return v
}
fun previousVolume(): String {
val v = volumes[currentVolume % volumes.size]
currentVolume--
return v
}
override fun inputSetup() {
setupCameraModeSwitching()
val toggleRenderingMode = object : ClickBehaviour {
var modes = Volume.RenderingMethod.values()
var currentMode = (scene.find("volume") as? Volume)!!.renderingMethod
override fun click(x: Int, y: Int) {
currentMode = modes.getOrElse(modes.indexOf(currentMode) + 1 % modes.size) { Volume.RenderingMethod.AlphaBlending }
(scene.find("volume") as? Volume)?.renderingMethod = currentMode
logger.info("Switched volume rendering mode to $currentMode")
}
}
val togglePlaying = ClickBehaviour { _, _ ->
playing = !playing
}
inputHandler?.addBehaviour("toggle_rendering_mode", toggleRenderingMode)
inputHandler?.addKeyBinding("toggle_rendering_mode", "M")
inputHandler?.addBehaviour("toggle_playing", togglePlaying)
inputHandler?.addKeyBinding("toggle_playing", "G")
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
VolumeSamplingExample().main()
}
}
}
| lgpl-3.0 | 716d91325a7613b2fb9527d5f9f4b131 | 36.785965 | 190 | 0.561241 | 4.238095 | false | false | false | false |
kunny/RxBinding | buildSrc/src/main/kotlin/com/jakewharton/rxbinding/project/KotlinGenTask.kt | 1 | 11375 | package com.jakewharton.rxbinding.project
import com.github.javaparser.JavaParser
import com.github.javaparser.ast.ImportDeclaration
import com.github.javaparser.ast.PackageDeclaration
import com.github.javaparser.ast.TypeParameter
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
import com.github.javaparser.ast.body.MethodDeclaration
import com.github.javaparser.ast.body.ModifierSet
import com.github.javaparser.ast.type.ClassOrInterfaceType
import com.github.javaparser.ast.type.PrimitiveType
import com.github.javaparser.ast.type.ReferenceType
import com.github.javaparser.ast.type.Type
import com.github.javaparser.ast.type.VoidType
import com.github.javaparser.ast.type.WildcardType
import com.github.javaparser.ast.visitor.VoidVisitorAdapter
import org.gradle.api.tasks.SourceTask
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.incremental.IncrementalTaskInputs
import sun.reflect.generics.reflectiveObjects.NotImplementedException
import java.io.File
import java.nio.file.Files
import kotlin.properties.Delegates
open class KotlinGenTask : SourceTask() {
companion object {
/** Regex used for finding references in javadoc links */
private val DOC_LINK_REGEX = "[0-9A-Za-z._]*"
private val SLASH = File.separator
/**
* These are imports of classes that Kotlin advises against using and are replaced in
* {@link #resolveKotlinTypeByName}
*/
private val IGNORED_IMPORTS = listOf(
"java.util.List",
"android.annotation.TargetApi",
"android.support.annotation.CheckResult",
"android.support.annotation.NonNull"
)
fun resolveKotlinTypeByName(input: String): String {
when (input) {
"Object" ->
return "Any"
"Void" ->
return "Unit"
"Integer" ->
return "Int"
"int", "char", "boolean", "long", "float", "short", "byte" ->
return input.capitalize()
"List" ->
return "MutableList"
else ->
return input
}
}
/** Recursive function for resolving a Type into a Kotlin-friendly String representation */
fun resolveKotlinType(inputType: Type): String {
if (inputType is ReferenceType) {
return resolveKotlinType(inputType.type)
} else if (inputType is ClassOrInterfaceType) {
val baseType = resolveKotlinTypeByName(inputType.name)
if (inputType.typeArgs == null || inputType.typeArgs.isEmpty()) {
return baseType
}
return "$baseType<${inputType.typeArgs.map { type: Type -> resolveKotlinType(type) }.joinToString()}>"
} else if (inputType is PrimitiveType || inputType is VoidType) {
return resolveKotlinTypeByName(inputType.toString())
} else if (inputType is WildcardType) {
if (inputType.`super` != null) {
return "in ${resolveKotlinType(inputType.`super`)}"
} else if (inputType.extends != null) {
return "out ${resolveKotlinType(inputType.extends)}"
} else {
throw IllegalStateException("Wildcard with no super or extends")
}
} else {
throw NotImplementedException()
}
}
}
@TaskAction
@Suppress("unused")
fun generate(inputs: IncrementalTaskInputs) {
// Clear things out first to make sure no stragglers are left
val outputDir = File("${project.projectDir}-kotlin${SLASH}src${SLASH}main${SLASH}kotlin")
outputDir.deleteDir()
// Let's get going
getSource().forEach { generateKotlin(it) }
}
fun generateKotlin(file: File) {
val outputPath = file.parent.replace("java", "kotlin")
.replace("${SLASH}src", "-kotlin${SLASH}src")
.substringBefore("com${SLASH}jakewharton")
val outputDir = File(outputPath)
// Start parsing the java files
val cu = JavaParser.parse(file)
val kClass = KFile()
kClass.fileName = file.name.replace(".java", ".kt")
// Visit the appropriate nodes and extract information
cu.accept(object : VoidVisitorAdapter<KFile>() {
override fun visit(n: PackageDeclaration, arg: KFile) {
arg.packageName = n.name.toString()
super.visit(n, arg)
}
override fun visit(n: ClassOrInterfaceDeclaration, arg: KFile) {
arg.bindingClass = n.name
arg.extendedClass = n.name.replace("Rx", "")
super.visit(n, arg)
}
override fun visit(n: MethodDeclaration, arg: KFile) {
arg.methods.add(KMethod(n))
// Explicitly avoid going deeper, we only care about top level methods. Otherwise
// we'd hit anonymous inner classes and whatnot
}
override fun visit(n: ImportDeclaration, arg: KFile) {
if (!n.isStatic) {
arg.imports.add(n.name.toString())
}
super.visit(n, arg)
}
}, kClass)
kClass.generate(outputDir)
}
/**
* Represents a kotlin file that corresponds to a Java file/class in an RxBinding module
*/
class KFile {
var fileName: String by Delegates.notNull<String>()
var packageName: String by Delegates.notNull<String>()
var bindingClass: String by Delegates.notNull<String>()
var extendedClass: String by Delegates.notNull<String>()
val methods = mutableListOf<KMethod>()
val imports = mutableListOf<String>()
/** Generates the code and writes it to the desired directory */
fun generate(directory: File) {
var directoryPath = directory.absolutePath
var finalDir: File? = null
if (!packageName.isEmpty()) {
packageName.split('.').forEach {
directoryPath += File.separator + it
}
finalDir = File(directoryPath)
Files.createDirectories(finalDir.toPath())
}
File(finalDir, fileName).bufferedWriter().use { writer ->
// Package
writer.append("package $packageName\n\n")
// imports
imports.forEach { im ->
if (!IGNORED_IMPORTS.contains(im)) {
writer.append("import $im\n")
}
}
// fun!
methods.forEach { m ->
writer.append("\n${m.generate(bindingClass)}\n")
}
}
}
}
/**
* Represents a method implementation that needs to be wired up in Kotlin
*/
class KMethod(val n: MethodDeclaration) {
private val name = n.name
private val comment = if (n.comment != null) cleanUpDoc(n.comment.toString()) else null
private val accessModifier = ModifierSet.getAccessSpecifier(n.modifiers).codeRepresenation
private val extendedClass = n.parameters[0].type.toString()
private val parameters = n.parameters.subList(1, n.parameters.size)
private val returnType = n.type
private val typeParameters = typeParams(n.typeParameters)
/** Cleans up the generated doc and translates some html to equivalent markdown for Kotlin docs */
private fun cleanUpDoc(doc: String): String {
return doc.replace("<em>", "*")
.replace("</em>", "*")
.replace("<p>", "")
// JavaParser adds a couple spaces to the beginning of these for some reason
.replace(" *", " *")
// {@code view} -> `view`
.replace("\\{@code ($DOC_LINK_REGEX)\\}".toRegex()) { result: MatchResult ->
val codeName = result.destructured
"`${codeName.component1()}`"
}
// {@link Foo} -> [Foo]
.replace("\\{@link ($DOC_LINK_REGEX)\\}".toRegex()) { result: MatchResult ->
val foo = result.destructured
"[${foo.component1()}]"
}
// {@link Foo#bar} -> [Foo.bar]
.replace("\\{@link ($DOC_LINK_REGEX)#($DOC_LINK_REGEX)\\}".toRegex()) { result: MatchResult ->
val (foo, bar) = result.destructured
"[$foo.$bar]"
}
// {@linkplain Foo baz} -> [baz][Foo]
.replace("\\{@linkplain ($DOC_LINK_REGEX) ($DOC_LINK_REGEX)\\}".toRegex()) { result: MatchResult ->
val (foo, baz) = result.destructured
"[$baz][$foo]"
}
//{@linkplain Foo#bar baz} -> [baz][Foo.bar]
.replace("\\{@linkplain ($DOC_LINK_REGEX)#($DOC_LINK_REGEX) ($DOC_LINK_REGEX)\\}".toRegex()) { result: MatchResult ->
val (foo, bar, baz) = result.destructured
"[$baz][$foo.$bar]"
}
// Remove any trailing whitespace
.replace("(?m)\\s+$".toRegex(), "")
.trim()
}
/** Generates method level type parameters */
private fun typeParams(params: List<TypeParameter>?): String? {
if (params == null || params.isEmpty()) {
return null
}
val builder = StringBuilder()
builder.append("<")
params.forEach { p -> builder.append("${p.name} : ${resolveKotlinType(p.typeBound[0])}") }
builder.append(">")
return builder.toString()
}
/**
* Generates parameters in a kotlin-style format
*
* @param specifyType boolean indicating whether or not to specify the type (i.e. we don't
* need the type when we're passing params into the underlying Java implementation)
*/
private fun kParams(specifyType: Boolean): String {
val builder = StringBuilder()
parameters.forEach { p -> builder.append("${p.id.name}${if (specifyType) ": " + resolveKotlinType(p.type) else ""}") }
return builder.toString()
}
/**
* Generates the kotlin code for this method
*
* @param bindingClass name of the RxBinding class this is tied to
*/
fun generate(bindingClass: String): String {
///////////////
// STRUCTURE //
///////////////
// Javadoc
// public inline fun DrawerLayout.drawerOpen(): Observable<Boolean> = RxDrawerLayout.drawerOpen(this)
// <access specifier> inline fun <extendedClass>.<name>(params): <type> = <bindingClass>.name(this, params)
val fParams = kParams(true)
val jParams = kParams(false)
val builder = StringBuilder();
// doc
builder.append("${comment ?: ""}\n")
// access modifier and other signature boilerplate
builder.append("$accessModifier inline fun ")
// type params
builder.append(if (typeParameters != null) typeParameters + " " else "")
// return type
val kotlinType = resolveKotlinType(returnType)
builder.append("$extendedClass.$name($fParams): $kotlinType")
builder.append(" = ")
// target method call
builder.append("$bindingClass.$name(${if (jParams.isNotEmpty()) "this, $jParams" else "this"})")
// Void --> Unit mapping
if (kotlinType.equals("Observable<Unit>")) {
builder.append(".map { Unit }")
}
return builder.toString()
}
}
/**
* Copied over from the Groovy implementation
*/
fun File.deleteDir(): Boolean {
if (!exists()) {
return true
} else if (!isDirectory) {
return false
} else {
val files = listFiles()
if (files == null) {
return false
} else {
var result = true
for (file in files) {
if (file.isDirectory) {
if (!file.deleteDir()) {
result = false
}
} else if (!file.delete()) {
result = false
}
}
if (!delete()) {
result = false
}
return result
}
}
}
}
| apache-2.0 | e086c128477c3ed8a4816130c13bee21 | 32.854167 | 127 | 0.614945 | 4.364927 | false | false | false | false |
iSoron/uhabits | uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/screens/habits/show/views/FrequencyCard.kt | 1 | 1741 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.core.ui.screens.habits.show.views
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.PaletteColor
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.core.ui.views.Theme
import java.util.HashMap
data class FrequencyCardState(
val color: PaletteColor,
val firstWeekday: Int,
val frequency: HashMap<Timestamp, Array<Int>>,
val theme: Theme,
val isNumerical: Boolean
)
class FrequencyCardPresenter {
companion object {
fun buildState(
habit: Habit,
firstWeekday: Int,
theme: Theme
) = FrequencyCardState(
color = habit.color,
isNumerical = habit.isNumerical,
frequency = habit.originalEntries.computeWeekdayFrequency(
isNumerical = habit.isNumerical
),
firstWeekday = firstWeekday,
theme = theme,
)
}
}
| gpl-3.0 | 51bf6ea483eed2e6e40c6c037375d9a6 | 32.461538 | 78 | 0.694253 | 4.264706 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/settings/internal/AnalyticsTeiSettingHandlerShould.kt | 1 | 4232 | /*
* 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.settings.internal
import com.nhaarman.mockitokotlin2.*
import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore
import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction
import org.hisp.dhis.android.core.arch.handlers.internal.Handler
import org.hisp.dhis.android.core.arch.handlers.internal.LinkHandler
import org.hisp.dhis.android.core.settings.*
import org.junit.Before
import org.junit.Test
class AnalyticsTeiSettingHandlerShould {
private val analyticsTeiSettingStore: ObjectWithoutUidStore<AnalyticsTeiSetting> = mock()
private val analyticsTeiSetting: AnalyticsTeiSetting = mock()
private lateinit var analyticsTeiSettingHandler: Handler<AnalyticsTeiSetting>
private val teiDataElementHandler: LinkHandler<AnalyticsTeiDataElement, AnalyticsTeiDataElement> = mock()
private val teiIndicatorHandler: LinkHandler<AnalyticsTeiIndicator, AnalyticsTeiIndicator> = mock()
private val teiAttributeHandler: LinkHandler<AnalyticsTeiAttribute, AnalyticsTeiAttribute> = mock()
private val whoDataHandler: LinkHandler<AnalyticsTeiWHONutritionData, AnalyticsTeiWHONutritionData> = mock()
private val analyticsTeiSettingList: List<AnalyticsTeiSetting> = listOf(analyticsTeiSetting)
@Before
@Throws(Exception::class)
fun setUp() {
whenever(analyticsTeiSettingStore.updateOrInsertWhere(any())) doReturn HandleAction.Insert
whenever(analyticsTeiSetting.uid()) doReturn "tei_setting_uid"
analyticsTeiSettingHandler = AnalyticsTeiSettingHandler(
analyticsTeiSettingStore, teiDataElementHandler,
teiIndicatorHandler, teiAttributeHandler, whoDataHandler
)
}
@Test
fun clean_database_before_insert_collection() {
analyticsTeiSettingHandler.handleMany(analyticsTeiSettingList)
verify(analyticsTeiSettingStore).delete()
verify(analyticsTeiSettingStore).updateOrInsertWhere(analyticsTeiSetting)
}
@Test
fun clean_database_if_empty_collection() {
analyticsTeiSettingHandler.handleMany(emptyList())
verify(analyticsTeiSettingStore).delete()
verify(analyticsTeiSettingStore, never()).updateOrInsertWhere(analyticsTeiSetting)
}
@Test
fun call_data_handlers() {
analyticsTeiSettingHandler.handleMany(analyticsTeiSettingList)
verify(teiDataElementHandler).handleMany(any(), any(), any())
verify(teiIndicatorHandler).handleMany(any(), any(), any())
verify(teiAttributeHandler).handleMany(any(), any(), any())
verify(whoDataHandler).handleMany(any(), any(), any())
}
}
| bsd-3-clause | 4702dc2b6d9f79a6d8b2d6bdb2b26faf | 46.550562 | 112 | 0.767486 | 4.590022 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/util/DimenUtil.kt | 1 | 3833 | package org.wikipedia.util
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.Window
import androidx.annotation.DimenRes
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import kotlin.math.roundToInt
object DimenUtil {
@JvmStatic
fun dpToPx(dp: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, displayMetrics)
}
@JvmStatic
fun roundedDpToPx(dp: Float): Int {
return dpToPx(dp).roundToInt()
}
private fun pxToDp(px: Float): Float {
return px / densityScalar
}
@JvmStatic
fun roundedPxToDp(px: Float): Int {
return pxToDp(px).roundToInt()
}
@JvmStatic
val densityScalar: Float
get() = displayMetrics.density
@JvmStatic
fun getFloat(@DimenRes id: Int): Float {
return getValue(id).float
}
@JvmStatic
fun getDimension(@DimenRes id: Int): Float {
return TypedValue.complexToFloat(getValue(id).data)
}
@JvmStatic
fun getFontSizeFromSp(window: Window, fontSp: Float): Float {
val metrics = DisplayMetrics()
window.windowManager.defaultDisplay.getMetrics(metrics)
return fontSp / metrics.scaledDensity
}
// TODO: use getResources().getDimensionPixelSize()? Define leadImageWidth with px, not dp?
@JvmStatic
fun calculateLeadImageWidth(): Int {
val res = WikipediaApp.getInstance().resources
return (res.getDimension(R.dimen.leadImageWidth) / densityScalar).toInt()
}
@JvmStatic
val displayWidthPx: Int
get() = displayMetrics.widthPixels
@JvmStatic
val displayHeightPx: Int
get() = displayMetrics.heightPixels
@JvmStatic
fun getContentTopOffsetPx(context: Context): Int {
return roundedDpToPx(getContentTopOffset(context))
}
private fun getContentTopOffset(context: Context): Float {
return getToolbarHeight(context)
}
private fun getValue(@DimenRes id: Int): TypedValue {
val typedValue = TypedValue()
resources.getValue(id, typedValue, true)
return typedValue
}
private val displayMetrics: DisplayMetrics
get() = resources.displayMetrics
private val resources: Resources
get() = WikipediaApp.getInstance().resources
@JvmStatic
fun getNavigationBarHeight(context: Context): Float {
val id = getNavigationBarId(context)
return if (id > 0) getDimension(id) else 0f
}
private fun getToolbarHeight(context: Context): Float {
return roundedPxToDp(getToolbarHeightPx(context).toFloat()).toFloat()
}
@JvmStatic
fun getToolbarHeightPx(context: Context): Int {
val styledAttributes = context.theme.obtainStyledAttributes(intArrayOf(
androidx.appcompat.R.attr.actionBarSize
))
val size = styledAttributes.getDimensionPixelSize(0, 0)
styledAttributes.recycle()
return size
}
@DimenRes
private fun getNavigationBarId(context: Context): Int {
return context.resources.getIdentifier("navigation_bar_height", "dimen", "android")
}
@JvmStatic
fun isLandscape(context: Context): Boolean {
return context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
}
@JvmStatic
fun leadImageHeightForDevice(context: Context): Int {
return if (isLandscape(context)) (displayWidthPx * articleHeaderViewScreenHeightRatio()).toInt() else (displayHeightPx * articleHeaderViewScreenHeightRatio()).toInt()
}
private fun articleHeaderViewScreenHeightRatio(): Float {
return getFloat(R.dimen.articleHeaderViewScreenHeightRatio)
}
}
| apache-2.0 | 4a5e67aa2e874ead556f840454f6f1cc | 28.945313 | 174 | 0.693973 | 4.901535 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/tracing/TracingConfig.kt | 1 | 744 | package com.spotify.heroic.tracing
data class TracingConfig(
val probability: Double = 0.01,
val zpagesPort: Int = 0,
val requestHeadersToTags: List<String> = listOf(),
val tags: Map<String, String> = mapOf(),
val lightstep: Lightstep = Lightstep(),
val squash: Squash = Squash()
) {
data class Lightstep(
val collectorHost: String = "",
val collectorPort: Int = 80,
val accessToken: String = "",
val componentName: String = "heroic",
val reportingIntervalMs: Int = 1000,
val maxBufferedSpans: Int = 5000,
val resetClient: Boolean = false
)
data class Squash(
val whitelist: List<String>? = listOf(),
val threshold: Int = 100
)
}
| apache-2.0 | e98d30ec3e8ee8dd2d1759f141c6c478 | 28.76 | 54 | 0.61828 | 4.087912 | false | false | false | false |
elpassion/el-space-android | el-space-app/src/main/java/pl/elpassion/elspace/hub/report/list/service/ReportListService.kt | 1 | 2498 | package pl.elpassion.elspace.hub.report.list.service
import pl.elpassion.elspace.hub.project.Project
import pl.elpassion.elspace.hub.report.*
import pl.elpassion.elspace.hub.report.list.ReportList
import pl.elpassion.elspace.hub.report.list.YearMonth
import pl.elpassion.elspace.hub.report.list.toMonthDateRange
import io.reactivex.Observable
class ReportListService(private val reportApi: ReportList.ReportApi,
private val projectApi: ProjectListService) : ReportList.Service {
override fun getReports(yearMonth: YearMonth): Observable<List<Report>> = projectApi.getProjects()
.flatMap { projects ->
val (startOfMonth, endOfMonth) = yearMonth.toMonthDateRange()
reportApi.getReports(startOfMonth, endOfMonth).map { reportList ->
reportList.map { reportFromApi -> reportFromApi.toReport(projects) }
}
}
fun ReportFromApi.toReport(projects: List<Project>) = when (reportType) {
0 -> toRegularHourlyReport(projects)
1 -> toPaidVacationHourlyReport()
else -> toDayReport()
}
private fun ReportFromApi.toPaidVacationHourlyReport(): Report {
val date = performedAt.split("-")
return PaidVacationHourlyReport(
id = id,
year = date[0].toInt(),
month = date[1].toInt(),
day = date[2].toInt(),
reportedHours = value ?: 0.0)
}
private fun ReportFromApi.toRegularHourlyReport(projects: List<Project>): HourlyReport {
val date = performedAt.split("-")
return RegularHourlyReport(
id = id,
year = date[0].toInt(),
month = date[1].toInt(),
day = date[2].toInt(),
reportedHours = value ?: 0.0,
project = projects.first { it.id == projectId },
description = comment ?: "")
}
private fun ReportFromApi.toDayReport(): DailyReport {
val date = performedAt.split("-")
return DailyReport(
id = id,
year = date[0].toInt(),
month = date[1].toInt(),
day = date[2].toInt(),
reportType = reportType.toDailyReportType())
}
private fun Int.toDailyReportType() = when (this) {
3 -> DailyReportType.SICK_LEAVE
4 -> DailyReportType.PAID_CONFERENCE
else -> DailyReportType.UNPAID_VACATIONS
}
}
| gpl-3.0 | d259d482ede1ecb3732b90dc096b2778 | 38.03125 | 102 | 0.60008 | 4.566728 | false | false | false | false |
RockinRoel/FrameworkBenchmarks | frameworks/Kotlin/hexagon/src/main/kotlin/Settings.kt | 2 | 972 | package com.hexagonkt
import com.hexagonkt.helpers.Jvm.systemSetting
data class Settings(
val bindPort: Int = systemSetting("bindPort") ?: 9090,
val bindAddress: String = "0.0.0.0",
val database: String = "hello_world",
val worldCollection: String = "world",
val fortuneCollection: String = "fortune",
val databaseUsername: String = "benchmarkdbuser",
val databasePassword: String = "benchmarkdbpass",
val maximumPoolSize: Int = systemSetting("maximumPoolSize") ?: 96,
val webEngine: String = systemSetting("WEBENGINE") ?: "jetty",
val worldName: String = systemSetting("worldCollection") ?: "world",
val fortuneName: String = systemSetting("fortuneCollection") ?: "fortune",
val databaseName: String = systemSetting("database") ?: "hello_world",
val worldRows: Int = 10_000,
val textMessage: String = "Hello, World!",
val queriesParam: String = "queries",
val cachedQueriesParam: String = "count",
) | bsd-3-clause | 1e9ec4f07df9b1a2e9524f944e16ad7a | 33.75 | 78 | 0.694444 | 4.101266 | false | false | false | false |
pistatium/ssmemo | app/src/main/kotlin/com/appspot/pistatium/ssmemo/MainActivity.kt | 1 | 2895 | package com.appspot.pistatium.ssmemo
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.ListView
import android.widget.TextView
import com.appspot.pistatium.ssmemo.interfaces.MemoCellInterface
import com.appspot.pistatium.ssmemo.adapters.MemoListAdapter
import com.appspot.pistatium.ssmemo.models.Memo
import com.appspot.pistatium.ssmemo.models.MemoModel
import com.appspot.pistatium.ssmemo.models.MemoNotificationManager
import com.appspot.pistatium.ssmemo.models.Priority
import com.google.android.gms.analytics.HitBuilders
import jp.maru.mrd.IconLoader
import kotlinx.android.synthetic.activity_main.*
import kotlin.properties.Delegates
class MainActivity : AppCompatActivity(), MemoCellInterface {
private var memoModel: MemoModel by Delegates.notNull()
private var iconLoader: IconLoader<Int>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val application = applicationContext as SSMemoApplication
application.setAppFont(button_input_text)
memo_list.divider = null
memoModel = MemoModel(applicationContext)
initAds()
reloadList()
trackActivity()
}
override fun onResume() {
super.onResume()
iconLoader?.startLoading()
reloadList()
}
override fun onPause() {
iconLoader?.stopLoading()
super.onPause()
}
fun onClickEdit(view: View) {
val i = EditActivity.createIntent(applicationContext)
startActivity(i)
}
override fun onDestroy() {
super.onDestroy()
memoModel.close()
}
override fun onClickFav(memo: Memo) {
memoModel.toggleFav(memo)
if (memo.priority == Priority.HIGH.value) {
val manager = MemoNotificationManager(applicationContext)
manager.notify(memo)
}
reloadList()
}
override fun onClickDelete(memo: Memo) {
memoModel.tmpDelete(memo)
reloadList()
}
private fun reloadList(): Unit {
val memos = memoModel.list
memo_list.adapter = MemoListAdapter(this, R.id.memo_text, memos, this)
}
private fun initAds(): Unit {
iconLoader = IconLoader<Int>(BuildConfig.ASUTA_ICON_AD, this)
iconLoader?.let {
asuta_icon_cell.addToIconLoader(iconLoader)
asuta_icon_cell.titleColor = ContextCompat.getColor(applicationContext,R.color.baseBackground)
}
}
private fun trackActivity() {
val tracker = (application as SSMemoApplication).getDefaultTracker()
tracker?.setScreenName(this.localClassName)
tracker?.send(HitBuilders.ScreenViewBuilder().build())
}
}
| apache-2.0 | 0478774e6149194a5660925610eee8a0 | 28.845361 | 106 | 0.701209 | 4.269912 | false | false | false | false |
paplorinc/intellij-community | platform/projectModel-api/src/com/intellij/openapi/project/ProjectUtilCore.kt | 2 | 2550 | // 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.
@file:JvmName("ProjectUtilCore")
package com.intellij.openapi.project
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileProvider
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtil
import com.intellij.util.PlatformUtils
fun displayUrlRelativeToProject(file: VirtualFile, url: String, project: Project, isIncludeFilePath: Boolean, moduleOnTheLeft: Boolean): String {
var result = url
if (isIncludeFilePath) {
val projectHomeUrl = PathUtil.toSystemDependentName(project.basePath)
result = when {
projectHomeUrl != null && result.startsWith(projectHomeUrl) -> "...${result.substring(projectHomeUrl.length)}"
else -> FileUtil.getLocationRelativeToUserHome(file.presentableUrl)
}
}
if (file.fileSystem is LocalFileProvider) {
@Suppress("DEPRECATION") val localFile = (file.fileSystem as LocalFileProvider).getLocalVirtualFileFor(file)
if (localFile != null) {
val libraryEntry = LibraryUtil.findLibraryEntry(file, project)
when {
libraryEntry is JdkOrderEntry -> return "$result [${libraryEntry.jdkName}]"
libraryEntry != null -> return "$result [${libraryEntry.presentableName}]"
}
}
}
// see PredefinedSearchScopeProviderImpl.getPredefinedScopes for the other place to fix.
if (PlatformUtils.isCidr() || PlatformUtils.isRider()) {
return result
}
val module = ModuleUtilCore.findModuleForFile(file, project)
return when {
module == null || ModuleManager.getInstance(project).modules.size == 1 -> result
moduleOnTheLeft -> "[${module.name}] $result"
else -> "$result [${module.name}]"
}
}
val Project.isExternalStorageEnabled: Boolean
get() {
if (projectFilePath?.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION) == true) {
return false
}
val manager = ServiceManager.getService(this, ExternalStorageConfigurationManager::class.java) ?: return false
return manager.isEnabled || (ApplicationManager.getApplication()?.isUnitTestMode ?: false)
} | apache-2.0 | f6e4ce8b04f82082df34da539f0d017e | 40.819672 | 145 | 0.757647 | 4.6875 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/bungeecord/BungeeCordTemplate.kt | 1 | 2367 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bungeecord
import com.demonwav.mcdev.buildsystem.BuildSystem
import com.demonwav.mcdev.platform.BaseTemplate
import com.demonwav.mcdev.platform.bukkit.BukkitTemplate
import com.demonwav.mcdev.util.MinecraftFileTemplateGroupFactory
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import java.util.Properties
object BungeeCordTemplate {
fun applyMainClassTemplate(
project: Project,
file: VirtualFile,
packageName: String,
className: String
) {
val properties = Properties()
properties.setProperty("PACKAGE", packageName)
properties.setProperty("CLASS_NAME", className)
BaseTemplate.applyTemplate(
project,
file,
MinecraftFileTemplateGroupFactory.BUNGEECORD_MAIN_CLASS_TEMPLATE,
properties
)
}
fun applyPomTemplate(project: Project): String {
val properties = Properties()
val manager = FileTemplateManager.getInstance(project)
val fileTemplate = manager.getJ2eeTemplate(MinecraftFileTemplateGroupFactory.BUNGEECORD_POM_TEMPLATE)
return fileTemplate.getText(properties)
}
fun applyPluginDescriptionFileTemplate(
project: Project,
file: VirtualFile,
config: BungeeCordProjectConfiguration,
buildSystem: BuildSystem
) {
val base = config.base ?: return
val properties = BukkitTemplate.bukkitMain(buildSystem, base)
BukkitTemplate.bukkitDeps(properties, config)
if (config.hasAuthors()) {
// BungeeCord only supports one author
properties.setProperty("AUTHOR", base.authors[0])
properties.setProperty("HAS_AUTHOR", "true")
}
if (config.hasDescription()) {
properties.setProperty("DESCRIPTION", base.description)
properties.setProperty("HAS_DESCRIPTION", "true")
}
BaseTemplate.applyTemplate(
project,
file,
MinecraftFileTemplateGroupFactory.BUKKIT_PLUGIN_YML_TEMPLATE,
properties,
true
)
}
}
| mit | e4fc7cc19ac828ed598a5920e993ad4f | 28.222222 | 109 | 0.673426 | 5.014831 | false | true | false | false |
marcplouhinec/trust-service-reputation | src/main/kotlin/fr/marcsworld/model/entity/Document.kt | 1 | 1168 | package fr.marcsworld.model.entity
import fr.marcsworld.enums.DocumentType
import javax.persistence.*
/**
* Entity containing information about documents that can be downloaded from internet.
*
* @author Marc Plouhinec
*/
@Entity
@Table(name = "DOCUMENT")
class Document (
@Id @GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "DOCUMENT_ID", nullable = false)
var id: Long? = null,
@Column(name = "DOCUMENT_URL", nullable = false, length = 2000)
var url: String,
@Enumerated(EnumType.STRING)
@Column(name = "DOCUMENT_TYPE", nullable = false)
var type: DocumentType,
@Column(name = "LANGUAGE_CODE", nullable = false, length = 20)
var languageCode: String,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PROVIDED_BY_AGENCY_ID", nullable = false)
var providedByAgency: Agency,
@Column(name = "REFERENCED_BY_DOCUMENT_TYPE", nullable = true)
var referencedByDocumentType: DocumentType? = null,
@Column(name = "IS_STILL_PROVIDED_BY_AGENCY", nullable = false)
var isStillProvidedByAgency: Boolean = true
) | mit | 9bcd10a8b99435c5764340db4a5ee1e8 | 29.763158 | 86 | 0.65839 | 3.919463 | false | false | false | false |
google/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/oldGenerateUtil.kt | 2 | 1770 | // 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.core
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
fun <T : KtDeclaration> insertMembersAfterAndReformat(
editor: Editor?,
classOrObject: KtClassOrObject,
members: Collection<T>,
anchor: PsiElement? = null,
getAnchor: (KtDeclaration) -> PsiElement? = { null },
): List<T> {
val codeStyleManager = CodeStyleManager.getInstance(classOrObject.project)
return runWriteAction {
val insertedMembersElementPointers = insertMembersAfter(editor, classOrObject, members, anchor, getAnchor)
val firstElement = insertedMembersElementPointers.firstOrNull() ?: return@runWriteAction emptyList()
fun insertedMembersElements() = insertedMembersElementPointers.mapNotNull { it.element }
ShortenReferences.DEFAULT.process(insertedMembersElements())
if (editor != null) {
firstElement.element?.let { moveCaretIntoGeneratedElement(editor, it) }
}
insertedMembersElementPointers.onEach { it.element?.let { element -> codeStyleManager.reformat(element) } }
insertedMembersElements()
}
}
fun <T : KtDeclaration> insertMembersAfterAndReformat(editor: Editor?, classOrObject: KtClassOrObject, declaration: T, anchor: PsiElement? = null): T {
return insertMembersAfterAndReformat(editor, classOrObject, listOf(declaration), anchor).single()
}
| apache-2.0 | ea7c7ec0cfd1c9030eb66f9aadad0927 | 45.578947 | 158 | 0.759887 | 4.72 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/VorbisFloor.kt | 1 | 2278 | package org.runestar.client.updater.mapper.std.classes
import org.objectweb.asm.Opcodes.PUTFIELD
import org.objectweb.asm.Type.INT_TYPE
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
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 VorbisFloor : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.instanceFields.count { it.type == INT_TYPE } == 1 }
.and { it.instanceFields.count { it.type == IntArray::class.type } == 5 }
class multiplier : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == INT_TYPE }
}
class subclassBooks : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == INT_TYPE.withDimensions(2) }
}
class partitionClassList : OrderMapper.InConstructor.Field(VorbisFloor::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
class classDimensions : OrderMapper.InConstructor.Field(VorbisFloor::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
class classSubClasses : OrderMapper.InConstructor.Field(VorbisFloor::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
class classMasterbooks : OrderMapper.InConstructor.Field(VorbisFloor::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
class xList : OrderMapper.InConstructor.Field(VorbisFloor::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
} | mit | ec0408feda9f2b5cd72c2d93fb7eedb3 | 46.479167 | 124 | 0.729587 | 4.089767 | false | false | false | false |
sdeleuze/mixit | src/main/kotlin/mixit/web/handler/UserHandler.kt | 1 | 2714 | package mixit.web.handler
import mixit.model.*
import mixit.repository.UserRepository
import mixit.util.*
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.server.*
import org.springframework.web.reactive.function.server.ServerResponse.*
import reactor.core.publisher.toMono
import java.net.URI.*
import java.net.URLDecoder
@Component
class UserHandler(val repository: UserRepository) {
fun findOneView(req: ServerRequest) =
try {
val idLegacy = req.pathVariable("login").toLong()
repository.findByLegacyId(idLegacy).flatMap {
ok().render("user", mapOf(Pair("user", it.toDto(req.language()))))
}
} catch (e:NumberFormatException) {
repository.findOne(URLDecoder.decode(req.pathVariable("login"), "UTF-8")).flatMap {
ok().render("user", mapOf(Pair("user", it.toDto(req.language()))))
}
}
fun findOne(req: ServerRequest) = ok().json().body(repository.findOne(req.pathVariable("login")))
fun findAll(req: ServerRequest) = ok().json().body(repository.findAll())
fun findStaff(req: ServerRequest) = ok().json().body(repository.findByRole(Role.STAFF))
fun findOneStaff(req: ServerRequest) = ok().json().body(repository.findOneByRole(req.pathVariable("login"), Role.STAFF))
fun create(req: ServerRequest) = repository.save(req.bodyToMono<User>()).flatMap {
created(create("/api/user/${it.login}")).json().body(it.toMono())
}
}
class UserDto(
val login: String,
val firstname: String,
val lastname: String,
var email: String,
var company: String? = null,
var description: String,
var emailHash: String? = null,
var photoUrl: String? = null,
val role: Role,
var links: List<Link>,
val logoType: String?,
val logoWebpUrl: String? = null
)
fun User.toDto(language: Language) =
UserDto(login, firstname, lastname, email ?: "", company, description[language] ?: "",
emailHash, photoUrl, role, links, logoType(photoUrl), logoWebpUrl(photoUrl))
private fun logoWebpUrl(url: String?) =
when {
url == null -> null
url.endsWith("png") -> url.replace("png", "webp")
url.endsWith("jpg") -> url.replace("jpg", "webp")
else -> null
}
private fun logoType(url: String?) =
when {
url == null -> null
url.endsWith("svg") -> "image/svg+xml"
url.endsWith("png") -> "image/png"
url.endsWith("jpg") -> "image/jpeg"
else -> null
}
| apache-2.0 | 4f825c014b5d7140d3e1fa8c42b2c93d | 34.246753 | 124 | 0.609433 | 4.175385 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/settings/language/SingleLanguageInlayHintsSettingsPanel.kt | 1 | 10805 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.settings.language
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.hint.EditorFragmentComponent
import com.intellij.codeInsight.hints.ChangeListener
import com.intellij.codeInsight.hints.InlayHintsSettings
import com.intellij.codeInsight.hints.settings.InlayHintsConfigurable
import com.intellij.codeInsight.hints.settings.InlayProviderSettingsModel
import com.intellij.ide.CopyProvider
import com.intellij.ide.DataManager
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypes
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.options.ex.Settings
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.panel.ComponentPanelBuilder
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.EditorTextField
import com.intellij.ui.JBColor
import com.intellij.ui.JBSplitter
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.layout.*
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import java.awt.GridLayout
import java.awt.datatransfer.StringSelection
import javax.swing.*
import javax.swing.border.LineBorder
private const val TOP_PANEL_PROPORTION = 0.35f
class SingleLanguageInlayHintsSettingsPanel(
private val myModels: Array<InlayProviderSettingsModel>,
private val myLanguage: Language,
private val myProject: Project
) : JPanel(), CopyProvider {
private val config = InlayHintsSettings.instance()
private val myProviderList = createList()
private var myCurrentProvider = selectLastViewedProvider()
private val myEditorTextField = createEditor()
private val myCurrentProviderCustomSettingsPane = JBScrollPane().also {
it.border = null
}
private val myCurrentProviderCasesPane = JBScrollPane().also {
it.border = null
it.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
it.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
}
private val myBottomPanel = createBottomPanel()
private var myCasesPanel: CasesPanel? = null
private val myRightPanel: JPanel = JPanel()
private val myWarningContainer = JPanel().also {
it.layout = BoxLayout(it, BoxLayout.Y_AXIS)
}
init {
layout = GridLayout(1, 1)
val splitter = JBSplitter(true)
splitter.firstComponent = createTopPanel()
splitter.secondComponent = myBottomPanel
for (model in myModels) {
model.onChangeListener = object : ChangeListener {
override fun settingsChanged() {
updateHints()
}
}
}
myProviderList.addListSelectionListener {
val newProviderModel = myProviderList.selectedValue
update(newProviderModel)
config.saveLastViewedProviderId(newProviderModel.id)
}
myProviderList.selectedIndex = findIndexToSelect()
add(splitter)
updateWithNewProvider()
}
private fun selectLastViewedProvider(): InlayProviderSettingsModel {
return myModels[findIndexToSelect()]
}
private fun findIndexToSelect(): Int {
val id = config.getLastViewedProviderId() ?: return 0
return when (val index = myModels.indexOfFirst { it.id == id }) {
-1 -> 0
else -> index
}
}
private fun createList(): JBList<InlayProviderSettingsModel> {
return JBList(*myModels).also {
it.cellRenderer = object : ColoredListCellRenderer<InlayProviderSettingsModel>(), ListCellRenderer<InlayProviderSettingsModel> {
override fun customizeCellRenderer(list: JList<out InlayProviderSettingsModel>,
value: InlayProviderSettingsModel,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
append(value.name)
}
}
}
}
private fun createTopPanel(): JPanel {
val panel = JPanel()
panel.layout = GridLayout(1, 1)
val horizontalSplitter = JBSplitter(false, TOP_PANEL_PROPORTION)
horizontalSplitter.firstComponent = createLeftPanel()
horizontalSplitter.secondComponent = fillRightPanel()
panel.add(horizontalSplitter)
return panel
}
private fun createLeftPanel() = JBScrollPane(myProviderList)
private fun fillRightPanel(): JPanel {
return withInset(panel {
row {
myWarningContainer(growY)
}
row {
withInset(myCurrentProviderCasesPane)()
}
row {
withInset(myCurrentProviderCustomSettingsPane)()
}
})
}
private fun createBottomPanel(): JPanel {
val panel = JPanel()
panel.layout = BorderLayout()
panel.add(createPreviewPanel(), BorderLayout.CENTER)
return panel
}
private fun createPreviewPanel(): JPanel {
val previewPanel = JPanel()
previewPanel.layout = BorderLayout()
previewPanel.add(myEditorTextField, BorderLayout.CENTER)
return previewPanel
}
private fun createEditor(): EditorTextField {
val fileType: FileType = myLanguage.associatedFileType ?: FileTypes.PLAIN_TEXT
val editorField = object : EditorTextField(null, myProject, fileType, false, false) {
override fun addNotify() {
super.addNotify()
// only here the editor is finally initialized
updateHints()
}
}
val scheme = EditorColorsManager.getInstance().globalScheme
editorField.font = scheme.getFont(EditorFontType.PLAIN)
editorField.border = LineBorder(JBColor.border())
editorField.addSettingsProvider { editor ->
editor.setVerticalScrollbarVisible(true)
editor.setHorizontalScrollbarVisible(true)
editor.setBorder(JBUI.Borders.empty(4))
with(editor.settings) {
additionalLinesCount = 2
isAutoCodeFoldingEnabled = false
isLineNumbersShown = true
}
// Sadly, but we can't use daemon here, because we need specific kind of settings instance here.
editor.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
updateHints()
}
})
editor.backgroundColor = EditorFragmentComponent.getBackgroundColor(editor, false)
editor.setBorder(JBUI.Borders.empty())
// If editor is created as not viewer, daemon is enabled automatically. But we want to collect hints manually with another settings.
val psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.document)
if (psiFile != null) {
DaemonCodeAnalyzer.getInstance(myProject).setHighlightingEnabled(psiFile, false)
}
}
editorField.setCaretPosition(0)
return editorField
}
private fun withInset(component: JComponent): JPanel {
val panel = JPanel(GridLayout())
panel.add(component)
panel.border = JBUI.Borders.empty(2)
return panel
}
private fun update(newProvider: InlayProviderSettingsModel) {
if (myCurrentProvider == newProvider) return
myCurrentProvider = newProvider
updateWithNewProvider()
}
private fun updateWithNewProvider() {
myCurrentProviderCasesPane.setViewportView(createCasesPanel())
myCurrentProviderCustomSettingsPane.setViewportView(myCurrentProvider.component)
myRightPanel.validate()
updateWarningPanel()
val previewText = myCurrentProvider.previewText
if (previewText == null) {
myBottomPanel.isVisible = false
}
else {
myBottomPanel.isVisible = true
myEditorTextField.text = previewText
updateHints()
}
}
private fun updateWarningPanel() {
myWarningContainer.removeAll()
if (!config.hintsEnabled(myLanguage)) {
myWarningContainer.add(JLabel("Inlay hints for ${myLanguage.displayName} are disabled."))
myWarningContainer.add(LinkLabel.create("Configure settings.") {
val settings = Settings.KEY.getData(DataManager.getInstance().getDataContext(this))
if (settings != null) {
val mainConfigurable = settings.find(InlayHintsConfigurable::class.java)
if (mainConfigurable != null) {
settings.select(mainConfigurable)
}
}
})
}
myWarningContainer.revalidate()
myWarningContainer.repaint()
}
private fun createCasesPanel(): JPanel {
val model = myCurrentProvider
val casesPanel = CasesPanel(
cases = model.cases,
mainCheckBoxName = model.mainCheckBoxLabel,
loadMainCheckBoxValue = { model.isEnabled },
onUserChangedMainCheckBox = {
model.isEnabled = it
model.onChangeListener?.settingsChanged()
},
listener = model.onChangeListener!!, // must be installed at this point
disabledExternally = { !(config.hintsEnabled(myLanguage) && config.hintsEnabledGlobally()) }
)
myCasesPanel = casesPanel
return casesPanel
}
private fun updateHints() {
if (myBottomPanel.isVisible) {
val document = myEditorTextField.document
ApplicationManager.getApplication().runWriteAction {
PsiDocumentManager.getInstance(myProject).commitDocument(document)
val psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document)
val editor = myEditorTextField.editor
if (editor != null && psiFile != null) {
myCurrentProvider.collectAndApply(editor, psiFile)
}
}
}
}
fun isModified(): Boolean {
return myModels.any { it.isModified() }
}
fun apply() {
for (model in myModels) {
model.apply()
}
}
fun reset() {
for (model in myModels) {
model.reset()
}
myCasesPanel?.updateFromSettings()
updateWarningPanel()
updateHints()
}
override fun performCopy(dataContext: DataContext) {
val selectedIndex = myProviderList.selectedIndex
if (selectedIndex < 0) return
val selection = myProviderList.model.getElementAt(selectedIndex)
CopyPasteManager.getInstance().setContents(StringSelection(selection.name))
}
override fun isCopyEnabled(dataContext: DataContext): Boolean = !myProviderList.isSelectionEmpty
override fun isCopyVisible(dataContext: DataContext): Boolean = false
} | apache-2.0 | 3792ea890a593a0af5c44670467d6a2f | 34.198697 | 140 | 0.722258 | 4.787328 | 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.