repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jrvermeer/Psalter
|
app/src/main/java/com/jrvermeer/psalter/ui/adaptors/PsalterSearchAdapter.kt
|
1
|
5934
|
package com.jrvermeer.psalter.ui.adaptors
import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.jrvermeer.psalter.models.Psalter
import com.jrvermeer.psalter.R
import com.jrvermeer.psalter.allIndexesOf
import com.jrvermeer.psalter.helpers.StorageHelper
import com.jrvermeer.psalter.infrastructure.PsalterDb
import java.util.ArrayList
import kotlinx.android.synthetic.main.search_results_layout.view.*
/**
* Created by Jonathan on 4/4/2017.
*/
//uses data from PsalterDb class to fill search "screen" with items
class PsalterSearchAdapter(private val appContext: Context,
private val psalterDb: PsalterDb,
private val storage: StorageHelper) : ArrayAdapter<Psalter>(appContext, R.layout.search_results_layout) {
private var query: String? = null
private val inflater: LayoutInflater = LayoutInflater.from(appContext)
fun queryPsalter(searchQuery: String) {
query = getFilteredQuery(searchQuery.toLowerCase())
showResults(psalterDb.searchPsalter(query!!))
}
fun getAllFromPsalm(psalm: Int) {
query = null
showResults(psalterDb.getPsalm(psalm))
}
fun showFavorites() {
query = null
showResults(psalterDb.getFavorites())
}
private fun showResults(results: Array<Psalter>) {
clear()
addAll(*results)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
try {
val holder: ViewHolder
if (convertView == null) {
convertView = inflater.inflate(R.layout.search_results_layout, parent, false)
holder = ViewHolder(convertView)
convertView!!.tag = holder
}
else holder = convertView.tag as ViewHolder
holder.tvLyrics.textSize = 16 * storage.textScale
holder.tvNumber.textSize = 20 * storage.textScale
val psalter = getItem(position)
holder.tvNumber!!.text = psalter!!.number.toString()
holder.tvId!!.text = psalter!!.id.toString()
if (query == null) {
holder.tvLyrics!!.text = psalter.lyrics.substring(0, getVerseEndIndex(psalter.lyrics, 0))
} else { //lyric search
val filterLyrics = psalter.lyrics.toLowerCase()
// build SpannableStringBuilder of only the verses that contain query
val viewText = SpannableStringBuilder()
val verseHitIndices = ArrayList<Int>() // could be verse number, could be chorus, so build a list of indexes
var first = true
for (i in filterLyrics.allIndexesOf(query!!)) {
val iStart = getVerseStartIndex(filterLyrics, i)
if (!verseHitIndices.contains(iStart)) { // if 1st occurrence of query in this verse, add verse to display
verseHitIndices.add(iStart)
val iEnd = getVerseEndIndex(filterLyrics, i)
if (!first) viewText.append("\n\n")
first = false
viewText.append(psalter.lyrics.substring(iStart, iEnd))
}
}
// highlight all instances of query
val filterText = viewText.toString().toLowerCase()
var iHighlightStart = filterText.indexOf(query!!)
while (iHighlightStart >= 0) {
val iHighlightEnd = iHighlightStart + query!!.length
viewText.setSpan(StyleSpan(Typeface.BOLD), iHighlightStart, iHighlightEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
// viewText.setSpan(AbsoluteSizeSpan((holder.tvLyrics!!.textSize * 1.5).toInt()), iHighlightStart, iHighlightEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
viewText.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorAccent)), iHighlightStart, iHighlightEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
iHighlightStart = filterText.indexOf(query!!, iHighlightStart + 1)
}
holder.tvLyrics!!.text = viewText
}
return convertView
} catch (ex: Exception) {
return convertView!!
}
}
//filter out characters
private fun getFilteredQuery(rawQuery: String): String {
var filteredQuery = rawQuery
for (ignore in appContext.resources.getStringArray(R.array.search_ignore_strings)) {
filteredQuery = filteredQuery.replace(ignore, "")
}
return filteredQuery
}
//given random index in lyrics string, return index of the beginning of that verse
private fun getVerseStartIndex(lyrics: String, queryStartIndex: Int): Int {
val startIndex = lyrics.lastIndexOf("\n\n", queryStartIndex)
return if (startIndex < 0) 0
else startIndex + 2 // don't need to display the 2 newline chars
}
//given random index in lyrics string, return index of the end of that verse
private fun getVerseEndIndex(lyrics: String, queryStartIndex: Int): Int {
val i = lyrics.indexOf("\n\n", queryStartIndex)
return if (i > 0) i
else lyrics.length
}
class ViewHolder(view: View) {
var tvId: TextView = view.tvSearchId
var tvNumber: TextView = view.tvSearchNumber
var tvLyrics: TextView = view.tvSearchLyrics
}
}
|
mit
|
8d2a7b311a74546d8a80db7136d98b2e
| 39.924138 | 177 | 0.646781 | 4.900083 | false | false | false | false |
androidx/androidx
|
glance/glance-wear-tiles-preview/src/androidMain/kotlin/androidx/glance/wear/tiles/preview/GlanceTileServiceViewAdapter.kt
|
3
|
3886
|
/*
* 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 android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.widget.FrameLayout
import androidx.compose.runtime.Composable
import androidx.compose.runtime.currentComposer
import androidx.compose.ui.unit.DpSize
import androidx.core.content.ContextCompat
import androidx.glance.wear.tiles.ExperimentalGlanceWearTilesApi
import androidx.glance.wear.tiles.compose
import androidx.glance.wear.tiles.preview.ComposableInvoker.invokeComposable
import androidx.wear.tiles.LayoutElementBuilders
import androidx.wear.tiles.TileBuilders
import androidx.wear.tiles.TimelineBuilders
import kotlinx.coroutines.runBlocking
import androidx.wear.tiles.renderer.TileRenderer
private const val TOOLS_NS_URI = "http://schemas.android.com/tools"
/**
* View adapter that renders a glance `@Composable`. The `@Composable` is found by reading the
* `tools:composableName` attribute that contains the FQN of the function.
*/
internal class GlanceTileServiceViewAdapter : FrameLayout {
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
init(attrs)
}
@OptIn(ExperimentalGlanceWearTilesApi::class)
internal fun init(
className: String,
methodName: String,
) {
val content = @Composable {
val composer = currentComposer
invokeComposable(
className,
methodName,
composer)
}
val wearTilesComposition = runBlocking {
compose(
context = context,
size = DpSize.Unspecified,
content = content)
}
// As far as GlanceWearTiles.compose accepts no timeleine argument, assume we only support
// [TimelineMode.SingleEntry]
val timelineBuilders = TimelineBuilders.Timeline.Builder()
timelineBuilders.addTimelineEntry(
TimelineBuilders.TimelineEntry.Builder()
.setLayout(
LayoutElementBuilders.Layout.Builder()
.setRoot(wearTilesComposition.layout)
.build()
).build()
)
val tile = TileBuilders.Tile.Builder()
.setTimeline(timelineBuilders.build())
.build()
val layout = tile.timeline?.timelineEntries?.get(0)?.layout
if (layout != null) {
val renderer = TileRenderer(
context,
layout,
wearTilesComposition.resources,
ContextCompat.getMainExecutor(context)
) { }
renderer.inflate(this)?.apply {
(layoutParams as LayoutParams).gravity = Gravity.CENTER
}
}
}
private fun init(attrs: AttributeSet) {
val composableName = attrs.getAttributeValue(TOOLS_NS_URI, "composableName") ?: return
val className = composableName.substringBeforeLast('.')
val methodName = composableName.substringAfterLast('.')
init(className, methodName)
}
}
|
apache-2.0
|
f47f48206cbe1becb03fae9f879fc1e9
| 34.336364 | 98 | 0.664951 | 4.988447 | false | false | false | false |
zhiayang/pew
|
core/src/main/kotlin/Entities/Mobs/Dwarf.kt
|
1
|
1305
|
// Copyright (c) 2014 Orion Industries, [email protected]
// Licensed under the Apache License version 2.0
package Entities.Mobs
import Entities.CharacterEntity
import PewGame
import com.badlogic.gdx.graphics.Camera
import Utilities.CharacterSpriteSheet
import Entities.MobAI.ChaseAndMeleeAI
import Entities.MobAI.CharacterAI
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import Items.Inventory
import Items.Weapons.Sword
import Items.Weapons.Fists
import Utilities.DelayComponent
public class Dwarf(game: PewGame, spriteSheet: String) : CharacterEntity(game, spriteSheet)
{
override var health: Int = 100
override val maxHealth: Int = 100
override val moveSpeed: Float = 8.0f
override val sprite: CharacterSpriteSheet
override val ai: CharacterAI = ChaseAndMeleeAI(this)
override val inventory: Inventory = Inventory(2)
init
{
this.sprite = CharacterSpriteSheet(Utilities.createTextureFromFile(spriteSheet), this.game.getSpriteBatch(), 0.25f)
this.inventory.store(Sword(), 1)
this.inventory.store(Fists(), 1)
}
override fun Update(deltaTime: Float)
{
this.input = this.ai.Update()
super<CharacterEntity>.Update(deltaTime)
}
override fun RenderSprite(spriteBatch: SpriteBatch, deltaTime: Float, camera: Camera)
{
super.RenderSprite(spriteBatch, deltaTime, camera)
}
}
|
apache-2.0
|
143249b07de2a08a0058d8c6620ad1ba
| 28.659091 | 117 | 0.792337 | 3.555858 | false | false | false | false |
GunoH/intellij-community
|
platform/ide-core/src/com/intellij/ide/RecentProjectsManager.kt
|
4
|
2358
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.PathUtil
import com.intellij.util.messages.Topic
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.SystemIndependent
import java.nio.file.Path
interface RecentProjectsManager {
companion object {
@Topic.AppLevel
val RECENT_PROJECTS_CHANGE_TOPIC = Topic("Change of recent projects", RecentProjectsChange::class.java, Topic.BroadcastDirection.NONE)
@JvmStatic
fun getInstance(): RecentProjectsManager = ApplicationManager.getApplication().getService(RecentProjectsManager::class.java)
fun fireChangeEvent() {
ApplicationManager.getApplication().messageBus.syncPublisher(RECENT_PROJECTS_CHANGE_TOPIC).change()
}
}
// a path pointing to a directory where the last project was created or null if not available
var lastProjectCreationLocation: @SystemIndependent String?
fun setLastProjectCreationLocation(value: Path?) {
lastProjectCreationLocation = if (value == null) {
null
}
else {
PathUtil.toSystemIndependentName(value.toString())
}
}
fun updateLastProjectPath()
fun removePath(path: @SystemIndependent String)
@Deprecated("Use {@link RecentProjectListActionProvider#getActions}")
fun getRecentProjectsActions(addClearListItem: Boolean): Array<AnAction>
@Deprecated("Use {@link RecentProjectListActionProvider#getActions}")
fun getRecentProjectsActions(addClearListItem: Boolean, useGroups: Boolean): Array<AnAction> {
return getRecentProjectsActions(addClearListItem)
}
val groups: List<ProjectGroup>
get() = emptyList()
fun addGroup(group: ProjectGroup) {}
fun removeGroup(group: ProjectGroup) {}
fun moveProjectToGroup(projectPath: String, to: ProjectGroup) {}
fun removeProjectFromGroup(projectPath: String, from: ProjectGroup) {}
fun hasPath(path: @SystemIndependent String?): Boolean {
return false
}
fun willReopenProjectOnStart(): Boolean
@ApiStatus.Internal
suspend fun reopenLastProjectsOnStart(): Boolean
fun suggestNewProjectLocation(): String
interface RecentProjectsChange {
fun change()
}
}
|
apache-2.0
|
1b330e005ee20aaaf25ebb15115a57a9
| 30.878378 | 138 | 0.772265 | 4.892116 | false | false | false | false |
OnyxDevTools/onyx-database-parent
|
onyx-database-tests/src/main/kotlin/entities/AllAttributeEntityWithRelationship.kt
|
1
|
1413
|
package entities
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.annotations.Attribute
import com.onyx.persistence.annotations.Entity
import com.onyx.persistence.annotations.Identifier
import com.onyx.persistence.annotations.Relationship
import com.onyx.persistence.annotations.values.CascadePolicy
import com.onyx.persistence.annotations.values.RelationshipType
import java.util.Date
/**
* Created by timothy.osborn on 11/3/14.
*/
@Entity(fileName = "allAttribute.dat")
open class AllAttributeEntityWithRelationship : AbstractEntity(), IManagedEntity {
@Identifier
@Attribute(size = 64)
open var id: String? = null
@Attribute(nullable = true)
var longValue: Long? = null
@Attribute
var longPrimitive: Long = 0
@Attribute
var intValue: Int? = null
@Attribute
var intPrimitive: Int = 0
@Attribute
var stringValue: String? = null
@Attribute
var otherString: String? = null
@Attribute
var dateValue: Date? = null
@Attribute
var doubleValue: Double? = null
@Attribute
var doublePrimitive: Double = 0.toDouble()
@Attribute
var booleanValue: Boolean? = null
@Attribute
var booleanPrimitive: Boolean = false
@Relationship(type = RelationshipType.ONE_TO_ONE, inverseClass = AllAttributeEntity::class, cascadePolicy = CascadePolicy.SAVE)
var relationship:AllAttributeEntity? = null
}
|
agpl-3.0
|
0d2010a27cf211f750f635d38ff05a2c
| 29.06383 | 131 | 0.739561 | 4.374613 | false | false | false | false |
GunoH/intellij-community
|
platform/lang-impl/src/com/intellij/util/indexing/roots/builders/SdkIndexableIteratorHandler.kt
|
5
|
3251
|
// 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.util.indexing.roots.builders
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.indexing.roots.IndexableEntityProvider
import com.intellij.util.indexing.roots.IndexableEntityProviderMethods
import com.intellij.util.indexing.roots.IndexableFilesIterator
import com.intellij.util.indexing.roots.SdkIndexableFilesIteratorImpl
import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge.Companion.findSdk
import com.intellij.workspaceModel.storage.EntityStorage
class SdkIndexableIteratorHandler : IndexableIteratorBuilderHandler {
override fun accepts(builder: IndexableEntityProvider.IndexableIteratorBuilder): Boolean =
builder is SdkIteratorBuilder || builder is InheritedSdkIteratorBuilder
override fun instantiate(builders: Collection<IndexableEntityProvider.IndexableIteratorBuilder>,
project: Project,
entityStorage: EntityStorage): List<IndexableFilesIterator> {
val unifiedBuilders = mutableMapOf<Pair<String, String>, Roots>()
var projectSdkRoots: Roots? = null
for (builder in builders) {
if (builder is SdkIteratorBuilder) {
val key = Pair(builder.sdkName, builder.sdkType)
val newRoot = builderToRoot(builder)
unifiedBuilders[key] = unifiedBuilders[key]?.merge(newRoot) ?: newRoot
}
else {
if (projectSdkRoots == null) {
projectSdkRoots = AllRoots
}
}
}
if (projectSdkRoots != null) {
val sdk = ProjectRootManager.getInstance(project).projectSdk
if (sdk != null) {
val key = Pair(sdk.name, sdk.sdkType.name)
unifiedBuilders[key] = unifiedBuilders[key]?.merge(projectSdkRoots) ?: projectSdkRoots
}
}
val result = mutableListOf<IndexableFilesIterator>()
for (entry in unifiedBuilders.entries) {
findSdk(entry.key.first, entry.key.second)?.apply {
result.addAll(entry.value.createIterator(this))
}
}
return result
}
private fun builderToRoot(builder: SdkIteratorBuilder) =
builder.root?.let { ListOfRoots(it) } ?: AllRoots
private sealed interface Roots {
fun merge(newRoot: Roots): Roots
fun createIterator(sdk: Sdk): Collection<IndexableFilesIterator>
}
private object AllRoots : Roots {
override fun merge(newRoot: Roots): Roots = this
override fun createIterator(sdk: Sdk): Collection<IndexableFilesIterator> = IndexableEntityProviderMethods.createIterators(sdk)
}
private class ListOfRoots() : ArrayList<VirtualFile>(), Roots {
constructor(file: VirtualFile) : this() {
add(file)
}
override fun merge(newRoot: Roots): Roots {
when (newRoot) {
AllRoots -> return newRoot
is ListOfRoots -> {
addAll(newRoot)
return this
}
}
}
override fun createIterator(sdk: Sdk): Collection<IndexableFilesIterator> = SdkIndexableFilesIteratorImpl.createIterators(sdk, this)
}
}
|
apache-2.0
|
e8a18357fa7a5907f1dd2972f295660c
| 37.714286 | 136 | 0.721932 | 4.896084 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/structuralsearch/binaryExpression/binaryEquality.kt
|
4
|
417
|
var a: String? = "Hello world"
var b: String? = "Hello world"
var c: String? = "Hello other world"
val d = <warning descr="SSR">a == b</warning>
val e = <warning descr="SSR">a?.equals(b) ?: (b === null)</warning>
val f = a == c
val g = c == b
val h = a?.equals(c) ?: (b === null)
val i = c?.equals(b) ?: (b === null)
val j = a?.equals(b) ?: (c === null)
val k = a?.equals(b)
val l = a === b
val m = a != b
|
apache-2.0
|
cf0b4af54b77e0d192ed44b79e2c31da
| 15.72 | 67 | 0.52518 | 2.438596 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/intentions/ReformatTableIntention.kt
|
4
|
1531
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor.tables.intentions
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.command.executeCommand
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.editor.tables.TableFormattingUtils
import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.isCorrectlyFormatted
import org.intellij.plugins.markdown.editor.tables.TableUtils
internal class ReformatTableIntention: PsiElementBaseIntentionAction() {
override fun getFamilyName(): String = text
override fun getText(): String {
return MarkdownBundle.message("markdown.reformat.table.intention.text")
}
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean {
val table = TableUtils.findTable(element)
if (editor == null || table == null) {
return false
}
return !table.isCorrectlyFormatted()
}
override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
requireNotNull(editor)
val table = TableUtils.findTable(element)!!
executeCommand(project) {
TableFormattingUtils.reformatAllColumns(table, editor.document, trimToMaxContent = true)
}
}
}
|
apache-2.0
|
e7347c42b230805b312275ae9fc223df
| 41.527778 | 158 | 0.788374 | 4.583832 | false | false | false | false |
guiseco/Tower
|
Android/src/org/droidplanner/android/droneshare/data/DroneShareDB.kt
|
3
|
3402
|
package org.droidplanner.android.droneshare.data
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.net.Uri
import android.support.v4.util.Pair
import org.droidplanner.android.droneshare.data.DroneShareContract.UploadData
import org.droidplanner.android.droneshare.data.SessionContract.SessionData
import timber.log.Timber
import java.util.*
/**
* @author ne0fhyk (Fredia Huya-Kouadio)
*/
class DroneShareDB(context: Context) :
SQLiteOpenHelper(context, DroneShareContract.DB_NAME, null, DroneShareContract.DB_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
Timber.i("Creating ${DroneShareContract.DB_NAME} database.")
val sqlCreateEntries = DroneShareContract.getSQLCreateEntries()
for(sqlCreateEntry in sqlCreateEntries) {
db.execSQL(sqlCreateEntry)
}
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
Timber.i("Upgrading ${DroneShareContract.DB_NAME} database from version $oldVersion to version $newVersion")
val sqlDelEntries = DroneShareContract.getSQLDeleteEntries()
for(sqlDelEntry in sqlDelEntries) {
db.execSQL(sqlDelEntry)
}
onCreate(db)
}
fun queueDataUploadEntry(username: String, sessionId: Long){
val db = getWritableDatabase()
val values = ContentValues().apply{
put(UploadData.COL_DSHARE_USER, username)
put(UploadData.COL_SESSION_ID, sessionId)
}
db.insert(UploadData.TABLE_NAME, null, values)
}
/**
* Returns the list of data for the given user that have yet to be uploaded to droneshare
*/
fun getDataToUpload(username: String): List<Pair<Long, Uri>> {
val db = getReadableDatabase()
val query = "SELECT ${UploadData._ID}, ${SessionData.COLUMN_NAME_TLOG_LOGGING_URI} " +
"FROM ${UploadData.TABLE_NAME} JOIN ${SessionData.TABLE_NAME} " +
"ON ${UploadData.COL_SESSION_ID} = ${SessionData._ID} " +
"WHERE ${UploadData.COL_DATA_UPLOAD_TIME} IS NULL " +
"AND ${SessionData.COLUMN_NAME_END_TIME} IS NOT NULL " +
"AND ${UploadData.COL_DSHARE_USER} LIKE ? " +
"ORDER BY ${UploadData._ID} ASC"
val selectionArgs = arrayOf(username)
val cursor = db.rawQuery(query, selectionArgs)
val result = ArrayList<Pair<Long, Uri>>(cursor.count)
if(cursor.moveToFirst()){
do {
val uploadId = cursor.getLong(cursor.getColumnIndex(UploadData._ID))
val dataUri = Uri.parse(cursor.getString(cursor.getColumnIndex(SessionData.COLUMN_NAME_TLOG_LOGGING_URI)))
result.add(Pair(uploadId, dataUri))
} while(cursor.moveToNext())
}
cursor.close()
return result
}
fun commitUploadedData(uploadId: Long, uploadTimeInMillis: Long){
val db = getWritableDatabase()
val values = ContentValues().apply {
put(UploadData.COL_DATA_UPLOAD_TIME, uploadTimeInMillis)
}
val selection = "${UploadData._ID} LIKE ?"
val selectionArgs = arrayOf(uploadId.toString())
db.update(UploadData.TABLE_NAME, values, selection, selectionArgs)
}
}
|
gpl-3.0
|
2b880e7f1ea09630e70ace1378084700
| 36.811111 | 122 | 0.661082 | 4.295455 | false | false | false | false |
Webtrekk/webtrekk-android-sdk
|
sdk_test/src/main/java/com/webtrekk/SDKTest/ProductList/ProductListActivity.kt
|
1
|
4525
|
package com.webtrekk.SDKTest.ProductList
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.webtrekk.SDKTest.R
import com.webtrekk.webtrekksdk.ProductParameterBuilder
import com.webtrekk.webtrekksdk.Webtrekk
import kotlinx.android.synthetic.main.product_list_layout.*
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Webtrekk GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Created by vartbaronov on 13.11.17.
*/
class ProductListActivity : AppCompatActivity(){
private lateinit var adapter: ProductListAdapter
private lateinit var model: ProductListModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.product_list_layout)
model = ViewModelProviders.of(this).get(ProductListModel::class.java)
model.getList().observe(this, Observer { list ->
if (list != null) {adapter.setItems(list)}
})
productListRecyclerView.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
adapter = ProductListAdapter(mutableListOf(), View.OnClickListener { view ->
val intent = Intent(this@ProductListActivity, ProductDetailActivity::class.java)
intent.putExtra(PRODUCT_ITEM, (view.tag as ProductItem).saveToBundle())
startActivity(intent)
})
productListRecyclerView.adapter = adapter
productListRecyclerView.addItemDecoration(DividerItemDecoration(this, (productListRecyclerView.layoutManager as LinearLayoutManager).orientation))
if (savedInstanceState == null) {
testBasket.value = mutableListOf<ProductItem>()
}
}
override fun onStop() {
super.onStop()
unregisterTracking();
}
override fun onStart() {
super.onStart()
val webtrekk = Webtrekk.getInstance()
webtrekk.productListTracker.registerView(productListRecyclerView, 4000){ position ->
val item = model.getList().value!!.get(position)
val builder = ProductParameterBuilder(item.id, ProductParameterBuilder.ActionType.list)
builder.setPosition(position).setCost(item.cost).
setEcommerce(1, item.ecomParameters[0]).
setEcommerce(2, item.ecomParameters[1]).
setProductCategory(1, item.categories[0]).
setProductCategory(2, item.categories[1]).
setPaymentMethod(item.paymentMethod).
setShippingService(item.shippingService).
setShippingSpeed(item.shippingSpeed).
setShippingCost(item.shippingCost).
setGrossMargin(item.grossMargin).
setProductVariant(item.productVariant).
setIsProductSoldOut(item.productSoldOut).result!!
}
}
fun unregisterTracking(){
val webtrekk = Webtrekk.getInstance()
if (webtrekk.isInitialized) {
webtrekk.productListTracker.unregisterView(productListRecyclerView)
}
}
fun getRecyclerView() : RecyclerView {
return productListRecyclerView
}
}
|
mit
|
8d15bf5f358b2443ddefd6c76ddcd69d
| 42.095238 | 160 | 0.707845 | 4.977998 | false | false | false | false |
kvnxiao/meirei
|
meirei-jda/src/main/kotlin/com/github/kvnxiao/discord/meirei/jda/command/CommandJDA.kt
|
1
|
2296
|
/*
* Copyright (C) 2017-2018 Ze Hao Xiao
*
* 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.kvnxiao.discord.meirei.jda.command
import com.github.kvnxiao.discord.meirei.command.CommandDefaults
import com.github.kvnxiao.discord.meirei.command.DiscordCommand
import com.github.kvnxiao.discord.meirei.permission.PermissionData
import com.github.kvnxiao.discord.meirei.ratelimit.DiscordRateLimiter
import com.github.kvnxiao.discord.meirei.ratelimit.RateLimitManager
import com.github.kvnxiao.discord.meirei.utility.GuildId
import com.github.kvnxiao.discord.meirei.utility.UserId
abstract class CommandJDA(
final override val id: String,
final override val registryAware: Boolean = CommandDefaults.IS_REGISTRY_AWARE
) : DiscordCommand(id, registryAware), CommandExecutable {
private val rateLimitManager: DiscordRateLimiter = RateLimitManager(id)
fun isNotUserLimited(userId: UserId, permissionData: PermissionData): Boolean {
return rateLimitManager.isNotRateLimitedByUser(userId, permissionData)
}
fun isNotRateLimited(guildId: GuildId, userId: UserId, permissionData: PermissionData): Boolean {
return rateLimitManager.isNotRateLimited(guildId, userId, permissionData)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is CommandJDA) return false
if (id != other.id) return false
if (registryAware != other.registryAware) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + registryAware.hashCode()
return result
}
override fun toString(): String {
return "(id='$id', registryAware=$registryAware)"
}
}
|
apache-2.0
|
5ccc66d83164c508d0a487e5027cd6c6
| 37.266667 | 101 | 0.733449 | 4.348485 | false | false | false | false |
spinnaker/kork
|
kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/plugins/sdk/httpclient/Ok3ResponseTest.kt
|
3
|
2470
|
/*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.plugins.sdk.httpclient
import com.fasterxml.jackson.databind.ObjectMapper
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import io.mockk.mockk
import java.io.IOException
import okhttp3.MediaType
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody
import strikt.api.expectThat
import strikt.assertions.isFalse
import strikt.assertions.isTrue
internal class Ok3ResponseTest : JUnit5Minutests {
fun tests() = rootContext<Fixture> {
fixture {
Fixture()
}
test("should flag the response as success") {
expectThat(status200Subject.isError).isFalse()
}
test("should flag the response as error if exception received") {
expectThat(exceptionSubject.isError).isTrue()
}
test("should flag the response as error if response received with status > 4xx or 5xx") {
expectThat(status404Subject.isError).isTrue()
expectThat(status500Subject.isError).isTrue()
}
}
private inner class Fixture {
val objectMapper: ObjectMapper = mockk(relaxed = true)
val response404: Response = buildResponse(404)
val response500: Response = buildResponse(500)
val response200: Response = buildResponse(200)
val exceptionSubject = Ok3Response(objectMapper, null, IOException("error"))
val status404Subject = Ok3Response(objectMapper, response404, null)
val status500Subject = Ok3Response(objectMapper, response500, null)
val status200Subject = Ok3Response(objectMapper, response200, null)
}
private fun buildResponse(code: Int): Response {
return Response.Builder().code(code)
.request(mockk(relaxed = true))
.message("OK")
.protocol(Protocol.HTTP_1_1)
.header("Content-Type", "plain/text")
.body(ResponseBody.create(MediaType.parse("plain/text"), "test"))
.build()
}
}
|
apache-2.0
|
a122f0c887696398e7ef1d1425d69c91
| 32.835616 | 93 | 0.736437 | 4.215017 | false | true | false | false |
seventhroot/elysium
|
bukkit/rpk-trade-bukkit/src/main/kotlin/com/rpkit/trade/bukkit/listener/SignChangeListener.kt
|
1
|
2577
|
/*
* Copyright 2016 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.trade.bukkit.listener
import com.rpkit.economy.bukkit.currency.RPKCurrencyProvider
import com.rpkit.trade.bukkit.RPKTradeBukkit
import org.bukkit.ChatColor.GREEN
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.block.SignChangeEvent
/**
* Sign change listener for trader signs.
*/
class SignChangeListener(private val plugin: RPKTradeBukkit): Listener {
@EventHandler
fun onSignChange(event: SignChangeEvent) {
if (event.getLine(0) == "[trader]") {
if (event.player.hasPermission("rpkit.trade.sign.trader.create")) {
if ((Material.matchMaterial(event.getLine(1) ?: "") == null
&& (event.getLine(1)?.matches(Regex("\\d+\\s+.*")) != true))
|| Material.matchMaterial(event.getLine(1)?.replace(Regex("\\d+\\s+"), "") ?: "") == null) {
event.block.breakNaturally()
event.player.sendMessage(plugin.messages["trader-sign-invalid-material"])
return
}
if (event.getLine(2)?.matches(Regex("\\d+ \\| \\d+")) != true) {
event.block.breakNaturally()
event.player.sendMessage(plugin.messages["trader-sign-invalid-price"])
return
}
if (plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class).getCurrency(event.getLine(3) ?: "") == null) {
event.block.breakNaturally()
event.player.sendMessage(plugin.messages["trader-sign-invalid-currency"])
return
}
event.setLine(0, "$GREEN[trader]")
event.player.sendMessage(plugin.messages["trader-sign-valid"])
} else {
event.player.sendMessage(plugin.messages["no-permission-trader-create"])
}
}
}
}
|
apache-2.0
|
2434ccf8a14fe635a1fb63c8d9ca48f0
| 41.262295 | 140 | 0.617773 | 4.497382 | false | false | false | false |
rjhdby/motocitizen
|
Motocitizen/src/motocitizen/MyApp.kt
|
1
|
2096
|
package motocitizen
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.preference.PreferenceManager
import android.widget.Toast
import com.vk.api.sdk.VK
import com.vk.api.sdk.VKTokenExpiredHandler
import motocitizen.datasources.preferences.Preferences
import motocitizen.migration.Migration
import motocitizen.notifications.Messaging
import motocitizen.ui.activity.AuthActivity
class MyApp : Application() {
/**
* AccessToken invalidated. Слушатель токена
*/
private var vkAccessTokenHandler = object : VKTokenExpiredHandler {
override fun onTokenExpired() {
Toast.makeText(applicationContext, "Авторизация слетела, авторизируйтесь снова", Toast.LENGTH_LONG).show()
val intent = Intent(applicationContext, AuthActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
}
}
override fun onCreate() {
super.onCreate()
context = applicationContext
oldVersion = PreferenceManager.getDefaultSharedPreferences(this).getInt("mc.app.version", 0)
val currentVersion = packageManager.getPackageInfo(packageName, 0).versionCode
if (oldVersion < currentVersion) Migration.makeMigration(this)
Messaging.subscribe()
if (Preferences.isTester) Messaging.subscribeToTest()
VK.initialize(this)
VK.addTokenExpiredHandler(vkAccessTokenHandler)
}
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
var firstStart = false
var oldVersion = 0
fun isOnline(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val netInfo = cm.activeNetworkInfo
return netInfo != null && netInfo.isConnectedOrConnecting
}
}
}
|
mit
|
5bb80c4751805646ecc1c98d09dd574b
| 34.224138 | 118 | 0.722467 | 4.88756 | false | false | false | false |
luks91/Team-Bucket
|
app/src/main/java/com/github/luks91/teambucket/main/statistics/StatisticsStorage.kt
|
2
|
4967
|
/**
* Copyright (c) 2017-present, Team Bucket Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package com.github.luks91.teambucket.main.statistics
import com.github.luks91.teambucket.model.EMPTY_STRING
import com.github.luks91.teambucket.model.PullRequest
import com.github.luks91.teambucket.model.PullRequestActivity
import com.github.luks91.teambucket.persistence.*
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.realm.RealmList
import io.realm.RealmModel
import io.realm.annotations.PrimaryKey
import io.realm.annotations.RealmClass
import org.apache.commons.lang3.StringUtils
import javax.inject.Inject
class StatisticsStorage @Inject constructor(){
private val scheduler by RealmSchedulerHolder
companion object {
const val STATISTICS_REALM = "statistics.realm"
}
fun subscribePersistingStatistics(detailedPullRequests: Observable<Observable<DetailedPullRequest>>): Disposable {
return detailedPullRequests
.concatMap { window ->
usingRealm(STATISTICS_REALM, scheduler) { realm ->
window.observeOn(scheduler)
.map { RealmDetailedPullRequest.from(it) }
.toList()
.map { realmList -> realm.executeTransaction { realm.copyToRealmOrUpdate(realmList) } }
.toObservable()
}
}.subscribe()
}
}
//this class needed to have copied code from RealmPullRequest, due to https://github.com/realm/realm-java/issues/761
@RealmClass
internal open class RealmDetailedPullRequest(open var id: Long = 0,
open var title: String = EMPTY_STRING,
open var createdDate: Long = 0L,
open var updatedDate: Long = 0L,
open var author: RealmPullRequestMember = RealmPullRequestMember(),
open var reviewers: RealmList<RealmPullRequestMember> = RealmList(),
open var state: String = EMPTY_STRING,
open var sourceBranch: RealmGitReference = RealmGitReference(),
open var targetBranch: RealmGitReference = RealmGitReference(),
open var activities: RealmList<RealmPullRequestActivity> = RealmList()): RealmModel {
@PrimaryKey open var realmId: String = "${id}_${sourceBranch?.repository?.slug}_${sourceBranch?.repository?.project?.key}"
companion object {
fun from(detailedPr: DetailedPullRequest) = RealmDetailedPullRequest(
detailedPr.pullRequest.id, detailedPr.pullRequest.title, detailedPr.pullRequest.createdDate,
detailedPr.pullRequest.updatedDate, RealmPullRequestMember.from(detailedPr.pullRequest.author),
detailedPr.pullRequest.reviewers.map { RealmPullRequestMember.from(it) }.toRealmList(),
detailedPr.pullRequest.state, RealmGitReference.from(detailedPr.pullRequest.sourceBranch),
RealmGitReference.from(detailedPr.pullRequest.targetBranch),
detailedPr.activities.map { RealmPullRequestActivity.from(it) }.toRealmList())
}
fun toDetailedPullRequest() = DetailedPullRequest(
PullRequest(id, title, createdDate, updatedDate, author.toPullRequestMember(),
reviewers.map(RealmPullRequestMember::toPullRequestMember).toList(),
state, sourceBranch.toGitReference(), targetBranch.toGitReference()),
activities.map { it.toPullRequestActivity() })
}
@RealmClass
internal open class RealmPullRequestActivity(@PrimaryKey open var id: Long = 0,
open var createdDate: Long = 0,
open var user: RealmUser = RealmUser(),
open var action: String = StringUtils.EMPTY): RealmModel {
companion object {
fun from(activity: PullRequestActivity) = RealmPullRequestActivity(activity.id,
activity.createdDate, RealmUser.from(activity.user), activity.action)
}
fun toPullRequestActivity() = PullRequestActivity(id, createdDate, user.toUser(), action)
}
|
apache-2.0
|
97f336a0ce534da34fb4e9c1e557eeae
| 51.840426 | 129 | 0.644051 | 5.470264 | false | false | false | false |
google/private-compute-libraries
|
java/com/google/android/libraries/pcc/chronicle/api/operation/DefaultOperationLibrary.kt
|
1
|
2265
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.api.operation
/**
* Default implementation of [OperationLibrary] for use in constructing cantrips.
*
* The [operations] provided are grouped by [Operation.name], there can be more than one [Operation]
* for a given name, as long as the [Operation.inputType] / [Operation.outputType] values are
* unique.
*/
class DefaultOperationLibrary(operations: Set<Operation<*, *>>) : OperationLibrary {
private val operationsByName: Map<String, List<Operation<*, *>>> = operations.groupBy { it.name }
@Synchronized
@Suppress("UNCHECKED_CAST") // It is checked, using inClass/outClass.
override fun <Input, Output> findOperation(
name: String,
inputType: Class<in Input>,
outputType: Class<out Output>,
): Operation<in Input, out Output>? {
val byName = operationsByName[name] ?: return null
// First look for an exact match with the classes.
byName
.find { it.inputType == inputType && it.outputType == outputType }
?.let {
return it as Operation<in Input, out Output>
}
// Next look for an exact match with the input class and for output assignability.
byName
.find {
it.inputType == inputType &&
(it.outputType == Void::class.java || outputType.isAssignableFrom(it.outputType))
}
?.let {
return it as Operation<in Input, out Output>
}
// Next, look for input/output assignability.
return byName.find {
it.inputType.isAssignableFrom(inputType) &&
(it.outputType == Void::class.java || outputType.isAssignableFrom(it.outputType))
} as? Operation<in Input, out Output>
}
}
|
apache-2.0
|
d2437cc4d61d1ee58df6705a7dddab63
| 36.131148 | 100 | 0.692715 | 4.210037 | false | false | false | false |
summerlly/Quiet
|
app/src/main/java/tech/summerly/quiet/data/local/LocalEntityMapper.kt
|
1
|
3301
|
package tech.summerly.quiet.data.local
import tech.summerly.quiet.bean.Playlist
import tech.summerly.quiet.data.local.entity.Tag
import tech.summerly.quiet.extensions.delete
import tech.summerly.quiet.module.common.bean.Album
import tech.summerly.quiet.module.common.bean.Artist
import tech.summerly.quiet.module.common.bean.Music
import tech.summerly.quiet.module.common.bean.MusicType
import tech.summerly.quiet.data.local.entity.Album as AlbumEntity
import tech.summerly.quiet.data.local.entity.Artist as ArtistEntity
import tech.summerly.quiet.data.local.entity.Music as MusicEntity
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/28
* desc :
*/
class LocalEntityMapper {
fun convertMusicBeanToEntity(music: Music): MusicEntity {
return MusicEntity(
music.id,
music.url,
music.title,
music.artistString(),
music.album.name,
System.currentTimeMillis(),
music.duration,
music.picUrl
)
}
fun convertMusicEntityToBean(entity: MusicEntity, artist: List<Artist>? = null, album: Album? = null): Music {
return Music(
id = entity.id,
title = entity.title,
url = entity.path,
artist = artist ?: Artist.fromString(artists = entity.artist, from = MusicType.LOCAL),
album = album ?: Album(
id = 0,
name = entity.album,
picUrl = null,
type = MusicType.LOCAL
),
picUrl = entity.artwork,
type = MusicType.LOCAL,
bitrate = 0,
mvId = 0L,
duration = entity.duration
).also {
it.deleteAction = it::delete
}
}
fun convertPlaylistBeanToEntity(playlist: Playlist): Tag {
return Tag(
playlist.id,
playlist.name,
System.currentTimeMillis(),
playlist.coverImageUrl
)
}
fun convertPlaylistEntityToBean(tag: Tag): Playlist {
return Playlist(
id = tag.id,
name = tag.name,
coverImageUrl = tag.coverPath,
musics = emptyList(),
type = MusicType.LOCAL
)
}
fun convertArtistEntityToBean(artist: ArtistEntity): Artist {
return Artist(
id = 0,
name = artist.name,
picUrl = artist.picturePath,
type = MusicType.LOCAL
)
}
fun convertArtistBeanToEntity(artist: Artist): ArtistEntity {
return ArtistEntity(
artist.name,
null,
artist.picUrl
)
}
fun convertAlbumBeanToEntity(album: Album): AlbumEntity {
return AlbumEntity(
album.name,
"",
album.picUrl
)
}
fun convertAlbumEntityToBean(album: AlbumEntity): Album {
return Album(
id = 0L,
name = album.name,
picUrl = album.artworkPath,
type = MusicType.LOCAL
)
}
}
|
gpl-2.0
|
39a973a3459ba5ec2dcb7d5bbe1ed844
| 29.293578 | 114 | 0.538322 | 4.833089 | false | false | false | false |
YiiGuxing/TranslationPlugin
|
src/main/kotlin/cn/yiiguxing/plugin/translate/documentation/TranslatedDocComments.kt
|
1
|
1855
|
package cn.yiiguxing.plugin.translate.documentation
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocCommentBase
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.containers.ContainerUtil
@Service
internal class TranslatedDocComments: Disposable {
//use SmartPsiElementPointer to survive reparse
private val translatedDocs: MutableSet<SmartPsiElementPointer<PsiDocCommentBase>> = ContainerUtil.newConcurrentSet()
override fun dispose() {
translatedDocs.clear()
}
companion object {
fun isTranslated(docComment: PsiDocCommentBase): Boolean {
val translatedDocs = translatedDocs(docComment.project)
return translatedDocs.contains(SmartPointerManager.createPointer(docComment))
}
fun setTranslated(docComment: PsiDocCommentBase, value: Boolean) {
val translatedDocs = translatedDocs(docComment.project)
val pointer = SmartPointerManager.createPointer(docComment)
if (value) translatedDocs.add(pointer)
else translatedDocs.remove(pointer)
translatedDocs.scheduleCleanup()
}
private fun service(project: Project) = project.getService(TranslatedDocComments::class.java)
private fun translatedDocs(project: Project) = service(project).translatedDocs
private fun MutableSet<SmartPsiElementPointer<PsiDocCommentBase>>.scheduleCleanup() {
ReadAction.nonBlocking {
removeIf { it.element == null }
}.submit(AppExecutorUtil.getAppExecutorService())
}
}
}
|
mit
|
160f0fa65a95ce7edf081f8ed5baaad9
| 35.392157 | 120 | 0.740701 | 5.439883 | false | false | false | false |
FWDekker/intellij-randomness
|
src/test/kotlin/com/fwdekker/randomness/word/DefaultWordListTest.kt
|
1
|
2849
|
package com.fwdekker.randomness.word
import com.fwdekker.randomness.Bundle
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.io.IOException
import kotlin.system.measureNanoTime
/**
* Unit tests for [DefaultWordList].
*/
object DefaultWordListTest : Spek({
describe("words") {
it("throws an exception if the file does not exist") {
val list = DefaultWordList("throw", "word-lists/does-not-exist.txt")
assertThatThrownBy { list.words }
.isInstanceOf(IOException::class.java)
.hasMessage(Bundle("word_list.error.file_not_found"))
}
it("returns an empty list of words if the file is empty") {
val list = DefaultWordList("tailor", "word-lists/empty-list.txt")
assertThat(list.words).isEmpty()
}
it("returns the list of words from the file") {
val list = DefaultWordList("off", "word-lists/non-empty-list.txt")
assertThat(list.words).containsExactly("lorem", "ipsum", "dolor")
}
it("does not return blank lines") {
val list = DefaultWordList("wander", "word-lists/with-blank-lines.txt")
assertThat(list.words).containsExactly("afraid", "dive", "snow", "enemy")
}
describe("caching") {
it("throws an exception again if the words are read again") {
val list = DefaultWordList("bound", "word-lists/does-not-exist.txt")
assertThatThrownBy { list.words }.isInstanceOf(IOException::class.java)
.hasMessage(Bundle("word_list.error.file_not_found"))
assertThatThrownBy { list.words }.isInstanceOf(IOException::class.java)
.hasMessage(Bundle("word_list.error.file_not_found"))
}
it("returns words quicker if read again from the same instance") {
val list = DefaultWordList("height", "word-lists/timing-test-instance.txt")
val firstTime = measureNanoTime { list.words }
val secondTime = measureNanoTime { list.words }
assertThat(secondTime).isLessThan(firstTime / 2)
}
it("returns words quicker if read again from another instance") {
val firstList = DefaultWordList("charge", "word-lists/timing-test-global.txt")
val firstTime = measureNanoTime { firstList.words }
val secondList = DefaultWordList("charge", "word-lists/timing-test-global.txt")
val secondTime = measureNanoTime { secondList.words }
assertThat(secondTime).isLessThan(firstTime / 2)
}
}
}
})
|
mit
|
d7cc3b8cf21dac9d677583b5ad0b9c31
| 37.5 | 95 | 0.622324 | 4.580386 | false | true | false | false |
chrsep/Kingfish
|
app/src/main/java/com/directdev/portal/features/journal/JournalFragment.kt
|
1
|
3301
|
package com.directdev.portal.features.journal
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar
import com.directdev.portal.R
import com.directdev.portal.features.SettingsActivity
import com.directdev.portal.models.JournalModel
import com.directdev.portal.utils.action
import com.directdev.portal.utils.snack
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.analytics.FirebaseAnalytics
import dagger.android.AndroidInjection
import io.realm.RealmResults
import kotlinx.android.synthetic.main.fragment_journal.*
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.startActivity
import javax.inject.Inject
class JournalFragment : Fragment(), JournalContract.View {
@Inject override lateinit var fbAnalytics: FirebaseAnalytics
@Inject override lateinit var presenter: JournalContract.Presenter
@Inject lateinit var adapter: JournalRecyclerAdapter
override fun onAttach(context: Context?) {
if (android.os.Build.VERSION.SDK_INT >= 23) AndroidInjection.inject(this)
super.onAttach(context)
}
override fun onAttach(activity: Activity?) {
if (android.os.Build.VERSION.SDK_INT < 23) AndroidInjection.inject(this)
super.onAttach(activity)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_journal, container, false)
val toolbar = view.findViewById<Toolbar>(R.id.journalToolbar)
val recyclerView = view.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.recyclerContent)
toolbar.inflateMenu(R.menu.menu_journal)
toolbar.setOnMenuItemClickListener { presenter.onMenuItemClick(it.itemId) }
recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(activity)
recyclerView.adapter = adapter
presenter.onCreateView(toolbar)
return view
}
override fun onStart() {
super.onStart()
presenter.onStart()
}
override fun onStop() {
super.onStop()
presenter.onStop()
}
override fun setTitle(toolbar: Toolbar, date: String) {
toolbar.title = "Today - " + date
}
override fun logAnalytics() {
val bundle = Bundle()
bundle.putString("content", "journal")
fbAnalytics.logEvent("content_opened", bundle)
}
override fun showSuccess(message: String) {
view?.snack(message, Snackbar.LENGTH_SHORT)
}
override fun showFailed(message: String) {
view?.snack(message, Snackbar.LENGTH_INDEFINITE) {
action("RETRY", Color.YELLOW, { presenter.sync(true) })
}
}
override fun updateAdapterData(data: RealmResults<JournalModel>) = adapter.updateData(data)
override fun navigateToSettings() = startActivity<SettingsActivity>()
override fun showLoading() = runOnUiThread { journalSyncProgress.visibility = View.VISIBLE }
override fun hideLoading() = runOnUiThread { journalSyncProgress.visibility = View.INVISIBLE }
}
|
gpl-3.0
|
a912305fbaecfe4f26b4d6df39eff32d
| 35.677778 | 115 | 0.738564 | 4.610335 | false | false | false | false |
cketti/okhttp
|
mockwebserver/src/main/kotlin/okhttp3/mockwebserver/RecordedRequest.kt
|
1
|
4263
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.mockwebserver
import java.io.IOException
import java.net.Inet6Address
import java.net.Socket
import javax.net.ssl.SSLSocket
import okhttp3.Handshake
import okhttp3.Handshake.Companion.handshake
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.TlsVersion
import okio.Buffer
/** An HTTP request that came into the mock web server. */
class RecordedRequest @JvmOverloads constructor(
val requestLine: String,
/** All headers. */
val headers: Headers,
/**
* The sizes of the chunks of this request's body, or an empty list if the request's body
* was empty or unchunked.
*/
val chunkSizes: List<Int>,
/** The total size of the body of this POST request (before truncation).*/
val bodySize: Long,
/** The body of this POST request. This may be truncated. */
val body: Buffer,
/**
* The index of this request on its HTTP connection. Since a single HTTP connection may serve
* multiple requests, each request is assigned its own sequence number.
*/
val sequenceNumber: Int,
socket: Socket,
/**
* The failure MockWebServer recorded when attempting to decode this request. If, for example,
* the inbound request was truncated, this exception will be non-null.
*/
val failure: IOException? = null
) {
val method: String?
val path: String?
/**
* The TLS handshake of the connection that carried this request, or null if the request was
* received without TLS.
*/
val handshake: Handshake?
val requestUrl: HttpUrl?
@get:JvmName("-deprecated_utf8Body")
@Deprecated(
message = "Use body.readUtf8()",
replaceWith = ReplaceWith("body.readUtf8()"),
level = DeprecationLevel.ERROR)
val utf8Body: String
get() = body.readUtf8()
/** Returns the connection's TLS version or null if the connection doesn't use SSL. */
val tlsVersion: TlsVersion?
get() = handshake?.tlsVersion
init {
if (socket is SSLSocket) {
try {
this.handshake = socket.session.handshake()
} catch (e: IOException) {
throw IllegalArgumentException(e)
}
} else {
this.handshake = null
}
if (requestLine.isNotEmpty()) {
val methodEnd = requestLine.indexOf(' ')
val pathEnd = requestLine.indexOf(' ', methodEnd + 1)
this.method = requestLine.substring(0, methodEnd)
var path = requestLine.substring(methodEnd + 1, pathEnd)
if (!path.startsWith("/")) {
path = "/"
}
this.path = path
val scheme = if (socket is SSLSocket) "https" else "http"
val inetAddress = socket.localAddress
var hostname = inetAddress.hostName
if (inetAddress is Inet6Address && hostname.contains(':')) {
// hostname is likely some form representing the IPv6 bytes
// 2001:0db8:85a3:0000:0000:8a2e:0370:7334
// 2001:db8:85a3::8a2e:370:7334
// ::1
hostname = "[$hostname]"
}
val localPort = socket.localPort
// Allow null in failure case to allow for testing bad requests
this.requestUrl = "$scheme://$hostname:$localPort$path".toHttpUrlOrNull()
} else {
this.requestUrl = null
this.method = null
this.path = null
}
}
@Deprecated(
message = "Use body.readUtf8()",
replaceWith = ReplaceWith("body.readUtf8()"),
level = DeprecationLevel.WARNING)
fun getUtf8Body(): String = body.readUtf8()
/** Returns the first header named [name], or null if no such header exists. */
fun getHeader(name: String): String? = headers.values(name).firstOrNull()
override fun toString(): String = requestLine
}
|
apache-2.0
|
dfd6a3f7400cb613c88f4b27902853bd
| 29.891304 | 96 | 0.680507 | 4.212451 | false | false | false | false |
Yalantis/Context-Menu.Android
|
lib/src/main/java/com/yalantis/contextmenu/lib/MenuParams.kt
|
1
|
2346
|
package com.yalantis.contextmenu.lib
import android.os.Parcel
import android.os.Parcelable
/**
* @property [animationDelay]
* Delay after opening and before closing.
* @see ContextMenuDialogFragment
*
* @property [isClosableOutside]
* If option menu can be closed on touch to non-button area.
*
* @property [gravity]
* You can change the side. By default - MenuGravity.END
* @see MenuGravity
*/
data class MenuParams(
var actionBarSize: Int = 0,
var menuObjects: List<MenuObject> = listOf(),
var animationDelay: Long = 0L,
var animationDuration: Long = ANIMATION_DURATION,
var backgroundColorAnimationDuration: Long = BACKGROUND_COLOR_ANIMATION_DURATION,
var isFitsSystemWindow: Boolean = false,
var isClipToPadding: Boolean = true,
var isClosableOutside: Boolean = false,
var gravity: MenuGravity = MenuGravity.END
) : Parcelable {
private constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.createTypedArrayList(MenuObject.CREATOR) ?: listOf(),
parcel.readLong(),
parcel.readLong(),
parcel.readLong(),
parcel.readByte() != 0.toByte(),
parcel.readByte() != 0.toByte(),
parcel.readByte() != 0.toByte(),
parcel.readSerializable() as? MenuGravity ?: MenuGravity.END
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.apply {
writeInt(actionBarSize)
writeTypedList(menuObjects)
writeLong(animationDelay)
writeLong(animationDuration)
writeLong(backgroundColorAnimationDuration)
writeByte(if (isFitsSystemWindow) 1 else 0)
writeByte(if (isClipToPadding) 1 else 0)
writeByte(if (isClosableOutside) 1 else 0)
writeSerializable(gravity)
}
}
override fun describeContents(): Int = 0
companion object {
const val ANIMATION_DURATION = 100L
const val BACKGROUND_COLOR_ANIMATION_DURATION = 200L
@JvmField
val CREATOR = object : Parcelable.Creator<MenuParams> {
override fun createFromParcel(parcel: Parcel): MenuParams = MenuParams(parcel)
override fun newArray(size: Int): Array<MenuParams?> = arrayOfNulls(size)
}
}
}
|
apache-2.0
|
af96f162811cd0bcc5958d77f329ea3e
| 32.528571 | 90 | 0.64237 | 4.768293 | false | false | false | false |
eugeis/ee
|
ee-lang/src/main/kotlin/ee/lang/gen/proto/LangProtoGeneratorFactory.kt
|
1
|
1738
|
package ee.lang.gen.proto
import ee.lang.*
open class LangProtoGeneratorFactory(private val targetAsSingleModule: Boolean = false) {
open fun pojoProto(fileNamePrefix: String = ""): GeneratorContexts<StructureUnitI<*>> {
val templates = buildProtoTemplates()
val contextFactory = buildProtoContextFactory()
val contextBuilder = contextFactory.buildForImplOnly()
val enums: StructureUnitI<*>.() -> List<EnumTypeI<*>> = { findDownByType(EnumTypeI::class.java) }
val compilationUnits: StructureUnitI<*>.() -> List<CompilationUnitI<*>> = {
findDownByType(CompilationUnitI::class.java).filter { it !is EnumTypeI<*> && !it.isIfc() }
}
val generator = GeneratorGroup("pojoProto", listOf(
GeneratorSimple("base", contextBuilder = contextBuilder,
template = FragmentsTemplate(name = "${fileNamePrefix}base",
nameBuilder = itemAndTemplateNameAsProtoFileName, fragments = {
listOf(
ItemsFragment(items = enums, fragments = {
listOf(templates.enum())
}),
ItemsFragment(items = compilationUnits, fragments = {
listOf(templates.pojo(itemNameAsProtoFileName))
}))
}))))
return GeneratorContexts(generator, contextBuilder)
}
protected open fun buildProtoContextFactory() = LangProtoContextFactory(targetAsSingleModule)
protected open fun buildProtoTemplates() = LangProtoTemplates(itemNameAsProtoFileName)
}
|
apache-2.0
|
894e042a1fa64e01fcfc1c176a96195e
| 48.685714 | 105 | 0.58458 | 5.735974 | false | false | false | false |
jiangkang/KTools
|
vpn/src/main/java/com/jiangkang/vpn/ToyVpnClientActivity.kt
|
1
|
1282
|
package com.jiangkang.vpn
import android.app.Activity
import android.content.Intent
import android.net.VpnService
import android.os.Bundle
import com.jiangkang.vpn.databinding.LayoutToyVpnClientActivityBinding
class ToyVpnClientActivity : Activity(){
private val binding by lazy { LayoutToyVpnClientActivityBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.btnConnect.setOnClickListener {
val intent = VpnService.prepare(this@ToyVpnClientActivity)
if (intent != null) {
startActivityForResult(intent, 0)
} else {
onActivityResult(0, RESULT_OK, null)
}
}
binding.btnDisconnect.setOnClickListener {
startService(getServiceIntent().setAction(ToyVpnService.ACTION_DISCONNECT))
}
}
override fun onActivityResult(request: Int, result: Int, data: Intent?) {
if (result == RESULT_OK && request == 0) {
startService(getServiceIntent().setAction(ToyVpnService.ACTION_CONNECT))
}
}
private fun getServiceIntent(): Intent {
return Intent(this, ToyVpnService::class.java)
}
}
|
mit
|
088ed8dfcdc572b25a898aa16ea0263e
| 31.897436 | 93 | 0.677847 | 4.930769 | false | false | false | false |
ngageoint/mage-android
|
mage/src/main/java/mil/nga/giat/mage/map/MapViewModel.kt
|
1
|
13094
|
package mil.nga.giat.mage.map
import android.app.Application
import androidx.lifecycle.*
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.launch
import mil.nga.giat.mage.data.feed.Feed
import mil.nga.giat.mage.data.feed.FeedItemDao
import mil.nga.giat.mage.data.feed.FeedWithItems
import mil.nga.giat.mage.data.feed.ItemWithFeed
import mil.nga.giat.mage.data.layer.LayerRepository
import mil.nga.giat.mage.data.location.LocationRepository
import mil.nga.giat.mage.data.observation.ObservationRepository
import mil.nga.giat.mage.form.Form
import mil.nga.giat.mage.glide.model.Avatar
import mil.nga.giat.mage.map.annotation.MapAnnotation
import mil.nga.giat.mage.map.preference.MapLayerPreferences
import mil.nga.giat.mage.network.Server
import mil.nga.giat.mage.network.gson.asStringOrNull
import mil.nga.giat.mage.observation.ObservationImportantState
import mil.nga.giat.mage.sdk.datastore.location.Location
import mil.nga.giat.mage.sdk.datastore.location.LocationHelper
import mil.nga.giat.mage.sdk.datastore.observation.Observation
import mil.nga.giat.mage.sdk.datastore.observation.ObservationHelper
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeature
import mil.nga.giat.mage.sdk.datastore.user.EventHelper
import mil.nga.giat.mage.sdk.datastore.user.User
import mil.nga.giat.mage.sdk.datastore.user.UserHelper
import mil.nga.giat.mage.sdk.exceptions.ObservationException
import mil.nga.giat.mage.sdk.exceptions.UserException
import mil.nga.giat.mage.sdk.utils.ISO8601DateFormatFactory
import mil.nga.giat.mage.utils.DateFormatFactory
import java.text.DateFormat
import java.util.*
import javax.inject.Inject
import kotlin.collections.set
data class FeedItemId(val feedId: String, val itemId: String)
data class StaticFeatureId(val layerId: Long, val featureId: Long)
@HiltViewModel
class MapViewModel @Inject constructor(
private val application: Application,
private val mapLayerPreferences: MapLayerPreferences,
private val feedItemDao: FeedItemDao,
private val geocoder: Geocoder,
private val layerRepository: LayerRepository,
locationRepository: LocationRepository,
observationRepository: ObservationRepository,
): ViewModel() {
var dateFormat: DateFormat =
DateFormatFactory.format("yyyy-MM-dd HH:mm zz", Locale.getDefault(), application)
private val eventHelper: EventHelper = EventHelper.getInstance(application)
private val eventId = MutableLiveData<Long>()
val observations = observationRepository.getObservations().transform { observations ->
val states = observations.map { observation ->
MapAnnotation.fromObservation(observation, application)
}
emit(states)
}.flowOn(Dispatchers.IO).asLiveData()
val locations = locationRepository.getLocations().transform { locations ->
val states = locations.map { location ->
MapAnnotation.fromUser(location.user, location)
}
emit(states)
}.flowOn(Dispatchers.IO).asLiveData()
val featureLayers = eventId.switchMap { eventId ->
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
val layers = layerRepository.getStaticFeatureLayers(eventId)
val annotations = layers.associateBy({ it.id }, { layer ->
val features = layerRepository.getStaticFeatures(layer.id)
val annotations = features.map { feature ->
MapAnnotation.fromStaticFeature(feature, application)
}
annotations
})
emit(annotations)
}
}
private val _feeds = MutableLiveData<MutableMap<String, LiveData<FeedState>>>()
val feeds: LiveData<MutableMap<String, LiveData<FeedState>>> = _feeds
private val feedIds = MutableLiveData<Set<String>>()
fun setEvent(id: Long) {
eventId.value = id
feedIds.value = mapLayerPreferences.getEnabledFeeds(id)
}
val items: LiveData<MutableMap<String, LiveData<FeedState>>> =
Transformations.switchMap(feedIds) { feedIds ->
val items = mutableMapOf<String, LiveData<FeedState>>()
feedIds.forEach { feedId ->
var liveData = _feeds.value?.get(feedId)
if (liveData == null) {
liveData = feedItemDao.feedWithItems(feedId).map {
toFeedItemState(it)
}
}
items[feedId] = liveData
}
_feeds.value = items
feeds
}
data class FeedState(val feed: Feed, val items: List<MapAnnotation<String>>)
private fun toFeedItemState(feedWithItems: FeedWithItems): FeedState {
val mapFeatures = feedWithItems.items.mapNotNull {
MapAnnotation.fromFeedItem(ItemWithFeed(feedWithItems.feed, it), application)
}
return FeedState(feedWithItems.feed, mapFeatures)
}
private val searchText = MutableLiveData<String>()
val searchResult = Transformations.switchMap(searchText) {
liveData {
emit(geocoder.search(it))
}
}
fun search(text: String) {
searchText.value = text
}
private val observationId = MutableLiveData<Long?>()
val observationMap: LiveData<ObservationMapState?> = observationId.switchMap { id ->
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
if (id != null) {
val observation = ObservationHelper.getInstance(application).read(id)
emit(toObservationItemState(observation))
} else {
emit(null)
}
}
}
fun selectObservation(id: Long?) {
observationId.value = id
}
private fun toObservationItemState(observation: Observation): ObservationMapState {
val currentUser = UserHelper.getInstance(application).readCurrentUser()
val isFavorite = if (currentUser != null) {
val favorite = observation.favoritesMap[currentUser.remoteId]
favorite != null && favorite.isFavorite
} else false
val importantState = if (observation.important?.isImportant == true) {
val importantUser: User? = try {
UserHelper.getInstance(application).read(observation.important?.userId)
} catch (ue: UserException) {
null
}
ObservationImportantState(
description = observation.important?.description,
user = importantUser?.displayName
)
} else null
var primary: String? = null
var secondary: String? = null
if (observation.forms.isNotEmpty()) {
val observationForm = observation.forms.first()
val formJson = eventHelper.getForm(observationForm.formId).json
val formDefinition = Form.fromJson(formJson)
primary = observationForm?.properties?.find { it.key == formDefinition?.primaryMapField }?.value as? String
secondary = observationForm?.properties?.find { it.key == formDefinition?.secondaryMapField }?.value as? String
}
val iconFeature = MapAnnotation.fromObservation(observation, application)
val user = UserHelper.getInstance(application).read(observation.userId)
val title = "${user.displayName} \u2022 ${dateFormat.format(observation.timestamp)}"
return ObservationMapState(
observation.id,
title,
observation.geometry,
primary,
secondary,
iconFeature,
isFavorite,
importantState
)
}
fun toggleFavorite(observationMapState: ObservationMapState) {
viewModelScope.launch(Dispatchers.IO) {
val observationHelper = ObservationHelper.getInstance(application)
val observation = observationHelper.read(observationMapState.id)
try {
val user: User? = try {
UserHelper.getInstance(application).readCurrentUser()
} catch (e: Exception) {
null
}
if (observationMapState.favorite) {
observationHelper.unfavoriteObservation(observation, user)
} else {
observationHelper.favoriteObservation(observation, user)
}
observationId.value = observation.id
} catch (ignore: ObservationException) {}
}
}
private val locationId = MutableLiveData<Long?>()
val location = locationId.switchMap { id ->
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
if (id != null) {
val location = LocationHelper.getInstance(application).read(id)
emit(toUserState(location.user, location))
} else {
emit(null)
}
}
}
fun selectUser(id: Long?) {
locationId.value = id
}
private fun toUserState(user: User, location: Location): UserMapState {
return UserMapState(
id = user.id,
title = dateFormat.format(location.timestamp),
primary = user.displayName,
geometry = location.geometry,
image = Avatar.forUser(user),
email = user.email,
phone = user.primaryPhone
)
}
private val feedItemId = MutableLiveData<FeedItemId?>()
val feedItem: LiveData<FeatureMapState<FeedItemId>?> = feedItemId.switchMap { id ->
liveData {
if (id != null) {
val liveData = feedItemDao.item(id.feedId, id.itemId).map {
feedItemToState(it)
}.asLiveData()
emitSource(liveData)
} else {
emit(null)
}
}
}
fun selectFeedItem(id: FeedItemId?) {
feedItemId.value = id
}
private fun feedItemToState(itemWithFeed: ItemWithFeed): FeatureMapState<FeedItemId>? {
val feed = itemWithFeed.feed
val item = itemWithFeed.item
val geometry = item.geometry ?: return null
val title = item.timestamp?.let {
dateFormat.format(it)
}
val primary = item.properties?.asJsonObject?.get(feed.itemPrimaryProperty)?.asStringOrNull()
val secondary = item.properties?.asJsonObject?.get(feed.itemSecondaryProperty)?.asStringOrNull()
return FeatureMapState(
id = FeedItemId(feed.id, item.id),
title = title,
primary = primary,
secondary = secondary,
geometry = geometry,
image = "${Server(application).baseUrl}/api/icons/${feed.mapStyle?.iconStyle?.id}/content"
)
}
private val _userPhone = MutableLiveData<User?>()
val userPhone: LiveData<User?> = _userPhone
fun selectUserPhone(userState: UserMapState?) {
val user: User? = userState?.let {
LocationHelper.getInstance(application).read(it.id)?.user
}
_userPhone.value = user
}
private val _staticFeatureId = MutableLiveData<StaticFeatureId?>()
val staticFeature: LiveData<StaticFeatureMapState?> = _staticFeatureId.switchMap { id ->
liveData {
if (id != null) {
layerRepository.getStaticFeature(id.layerId, id.featureId)?.let { feature ->
emit(staticFeatureToState(feature))
}
} else {
emit(null)
}
}
}
fun selectStaticFeature(feature: StaticFeatureId) {
_staticFeatureId.value = feature
}
private fun staticFeatureToState(feature: StaticFeature): StaticFeatureMapState {
val properties = feature.propertiesMap
val timestamp = properties["timestamp"]?.value?.let { timestamp ->
try {
ISO8601DateFormatFactory.ISO8601().parse(timestamp)?.let { date ->
dateFormat.format(date)
}
} catch (e: Exception) { null }
}
return StaticFeatureMapState(
id = feature.id,
title = timestamp,
primary = properties["name"]?.value,
secondary = feature.layer.name,
geometry = feature.geometry,
content = properties["description"]?.value
)
}
private val _geoPackageFeature = MutableLiveData<GeoPackageFeatureMapState?>()
val geoPackageFeature:LiveData<GeoPackageFeatureMapState?> = _geoPackageFeature
fun selectGeoPackageFeature(mapState: GeoPackageFeatureMapState?) {
_geoPackageFeature.value = mapState
}
fun deselectFeature() {
observationId.value = null
locationId.value = null
feedItemId.value = null
_geoPackageFeature.value = null
_staticFeatureId.value = null
}
}
|
apache-2.0
|
531d643170cfd46741837e0040b7acf6
| 35.991525 | 123 | 0.642355 | 4.858627 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer
|
settings/src/main/kotlin/voice/settings/views/resumeOnReplug.kt
|
1
|
1150
|
package voice.settings.views
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.ListItem
import androidx.compose.material.Switch
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import voice.settings.R
@Composable
internal fun ResumeOnReplugRow(
resumeOnReplug: Boolean,
toggle: () -> Unit
) {
ListItem(
modifier = Modifier
.clickable {
toggle()
}
.fillMaxWidth(),
singleLineSecondaryText = false,
text = {
Text(
text = stringResource(R.string.pref_resume_on_replug),
style = MaterialTheme.typography.bodyLarge
)
},
secondaryText = {
Text(
text = stringResource(R.string.pref_resume_on_replug_hint),
style = MaterialTheme.typography.bodyMedium
)
},
trailing = {
Switch(
checked = resumeOnReplug,
onCheckedChange = {
toggle()
}
)
}
)
}
|
lgpl-3.0
|
9cb1b35137525e3c1fd92212ddc8ebdc
| 23.468085 | 67 | 0.683478 | 4.423077 | false | false | false | false |
spark/photon-tinker-android
|
meshui/src/main/java/io/particle/mesh/ui/controlpanel/ControlPanelMeshInspectNetworkFragment.kt
|
1
|
4899
|
package io.particle.mesh.ui.controlpanel
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import io.particle.android.sdk.cloud.ParticleCloudSDK
import io.particle.android.sdk.cloud.ParticleNetwork
import io.particle.firmwareprotos.ctrl.mesh.Mesh
import io.particle.mesh.common.android.livedata.nonNull
import io.particle.mesh.common.android.livedata.runBlockOnUiThreadAndAwaitUpdate
import io.particle.mesh.setup.flow.DialogResult.NEGATIVE
import io.particle.mesh.setup.flow.DialogResult.POSITIVE
import io.particle.mesh.setup.flow.DialogSpec.StringDialogSpec
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.ui.R
import io.particle.mesh.ui.TitleBarOptions
import kotlinx.android.synthetic.main.fragment_controlpanel_mesh_network_info.*
import mu.KotlinLogging
class ControlPanelMeshInspectNetworkFragment : BaseControlPanelFragment() {
override val titleBarOptions = TitleBarOptions(
R.string.p_controlpanel_mesh_inspect_title,
showBackButton = true
)
private val log = KotlinLogging.logger {}
private val cloud = ParticleCloudSDK.getCloud()
private var cachedMeshNetworkDataFromDevice: Mesh.NetworkInfo? = null
private var cachedMeshNetworkDataFromCloud: ParticleNetwork? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_controlpanel_mesh_network_info, container, false)
}
override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
super.onFragmentReady(activity, flowUiListener)
log.info { "onFragmentReady()" }
p_controlpanel_action_leave_network.setOnClickListener { leaveNetwork() }
updateLocalNetworkInfoCaches(flowUiListener)
onNetworkInfoUpdated(cachedMeshNetworkDataFromDevice!!)
}
private fun updateLocalNetworkInfoCaches(flowUiListener: FlowRunnerUiListener) {
cachedMeshNetworkDataFromDevice = flowUiListener.mesh.currentlyJoinedNetwork!!
cachedMeshNetworkDataFromCloud = flowUiListener.cloud.meshNetworksFromAPI!!
.firstOrNull { cachedMeshNetworkDataFromDevice?.networkId == it.id }
}
override fun onResume() {
super.onResume()
onNetworkInfoUpdated(cachedMeshNetworkDataFromDevice!!)
}
private fun onNetworkInfoUpdated(networkInfo: Mesh.NetworkInfo) {
log.info { "onNetworkInfoUpdated(): $networkInfo" }
p_controlpanel_mesh_inspect_network_name.text = networkInfo.name
p_controlpanel_mesh_inspect_network_pan_id.text = networkInfo.panId.toString()
p_controlpanel_mesh_inspect_network_xpan_id.text = networkInfo.extPanId.toString()
p_controlpanel_mesh_inspect_network_channel.text = networkInfo.channel.toString()
p_controlpanel_mesh_inspect_network_network_id.text = networkInfo.networkId
flowScopes.onMain {
flowSystemInterface.showGlobalProgressSpinner(true)
val (isGateway, count) = flowScopes.withWorker {
val meshMemberships = cloud.getNetworkDevices(networkInfo.networkId)
val isGw = meshMemberships.firstOrNull { it.deviceId == device.id }
?.membership
?.roleData
?.isGateway
return@withWorker Pair(isGw, meshMemberships.size)
}
val roleLabel = if (isGateway == true) "Gateway" else "Node"
p_controlpanel_mesh_inspect_network_device_role.text = roleLabel
p_controlpanel_mesh_inspect_network_device_count.text = count.toString()
flowSystemInterface.showGlobalProgressSpinner(false)
}
}
private fun leaveNetwork() {
val meshName = cachedMeshNetworkDataFromDevice?.name
flowScopes.onMain {
val result = flowSystemInterface.dialogHack.dialogResultLD
.nonNull(flowScopes)
.runBlockOnUiThreadAndAwaitUpdate(flowScopes) {
flowSystemInterface.dialogHack.newDialogRequest(
StringDialogSpec(
"Remove this device from the current mesh network, '$meshName'?",
"Leave network",
"Cancel",
"Leave current network?"
)
)
}
when (result) {
NEGATIVE -> { /* no-op */
}
POSITIVE -> {
startFlowWithBarcode(
flowRunner::startControlPanelMeshLeaveCurrentMeshNetworkFlow
)
}
}
}
}
}
|
apache-2.0
|
c3996312026dd4b40cc9a0840902ed71
| 38.508065 | 100 | 0.673811 | 5.167722 | false | false | false | false |
ScreamingHawk/phone-saver
|
app/src/main/java/link/standen/michael/phonesaver/adapter/DeletableLocationArrayAdapter.kt
|
1
|
1562
|
package link.standen.michael.phonesaver.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import link.standen.michael.phonesaver.R
import link.standen.michael.phonesaver.util.LocationHelper
import link.standen.michael.phonesaver.data.LocationWithData
import java.io.File
/**
* Manages a list of deletable strings.
*/
class DeletableLocationArrayAdapter(context: Context, private val resourceId: Int, private val items: MutableList<LocationWithData>) :
ArrayAdapter<LocationWithData>(context, resourceId, items) {
private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getItem(index: Int): LocationWithData? = items[index]
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView?: inflater.inflate(resourceId, null)
// Delete button
val item = getItem(position)
if (item == null || item.deletable) {
view.findViewById<View>(R.id.delete).setOnClickListener {
items.removeAt(position)
LocationHelper.saveFolderList(context, items.filter { it.deletable }.map { it.location }.toMutableList())
notifyDataSetChanged()
}
} else {
view.findViewById<View>(R.id.delete).visibility = View.GONE
}
// Description
val s = item?.location
view.findViewById<TextView>(R.id.description).text = if (s.isNullOrBlank()) File.separator else s
return view
}
}
|
mit
|
b84f28ce4de5dba622201027ff792bd3
| 32.956522 | 134 | 0.773367 | 3.984694 | false | false | false | false |
moezbhatti/qksms
|
presentation/src/main/java/com/moez/QKSMS/feature/notificationprefs/NotificationPrefsViewModel.kt
|
3
|
6519
|
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.notificationprefs
import android.content.Context
import android.media.RingtoneManager
import android.net.Uri
import com.moez.QKSMS.R
import com.moez.QKSMS.common.Navigator
import com.moez.QKSMS.common.base.QkViewModel
import com.moez.QKSMS.extensions.mapNotNull
import com.moez.QKSMS.repository.ConversationRepository
import com.moez.QKSMS.util.Preferences
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import io.reactivex.Flowable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
import javax.inject.Named
class NotificationPrefsViewModel @Inject constructor(
@Named("threadId") private val threadId: Long,
private val context: Context,
private val conversationRepo: ConversationRepository,
private val navigator: Navigator,
private val prefs: Preferences
) : QkViewModel<NotificationPrefsView, NotificationPrefsState>(NotificationPrefsState(threadId = threadId)) {
private val notifications = prefs.notifications(threadId)
private val previews = prefs.notificationPreviews(threadId)
private val wake = prefs.wakeScreen(threadId)
private val vibration = prefs.vibration(threadId)
private val ringtone = prefs.ringtone(threadId)
init {
disposables += Flowable.just(threadId)
.mapNotNull { threadId -> conversationRepo.getConversation(threadId) }
.map { conversation -> conversation.getTitle() }
.subscribeOn(Schedulers.io())
.subscribe { title -> newState { copy(conversationTitle = title) } }
disposables += notifications.asObservable()
.subscribe { enabled -> newState { copy(notificationsEnabled = enabled) } }
val previewLabels = context.resources.getStringArray(R.array.notification_preview_options)
disposables += previews.asObservable()
.subscribe { previewId ->
newState { copy(previewSummary = previewLabels[previewId], previewId = previewId) }
}
val actionLabels = context.resources.getStringArray(R.array.notification_actions)
disposables += prefs.notifAction1.asObservable()
.subscribe { previewId -> newState { copy(action1Summary = actionLabels[previewId]) } }
disposables += prefs.notifAction2.asObservable()
.subscribe { previewId -> newState { copy(action2Summary = actionLabels[previewId]) } }
disposables += prefs.notifAction3.asObservable()
.subscribe { previewId -> newState { copy(action3Summary = actionLabels[previewId]) } }
disposables += wake.asObservable()
.subscribe { enabled -> newState { copy(wakeEnabled = enabled) } }
disposables += vibration.asObservable()
.subscribe { enabled -> newState { copy(vibrationEnabled = enabled) } }
disposables += ringtone.asObservable()
.map { uriString ->
uriString.takeIf { it.isNotEmpty() }
?.let(Uri::parse)
?.let { uri -> RingtoneManager.getRingtone(context, uri) }?.getTitle(context)
?: context.getString(R.string.settings_ringtone_none)
}
.subscribe { title -> newState { copy(ringtoneName = title) } }
disposables += prefs.qkreply.asObservable()
.subscribe { enabled -> newState { copy(qkReplyEnabled = enabled) } }
disposables += prefs.qkreplyTapDismiss.asObservable()
.subscribe { enabled -> newState { copy(qkReplyTapDismiss = enabled) } }
}
override fun bindView(view: NotificationPrefsView) {
super.bindView(view)
view.preferenceClickIntent
.autoDisposable(view.scope())
.subscribe {
when (it.id) {
R.id.notificationsO -> navigator.showNotificationChannel(threadId)
R.id.notifications -> notifications.set(!notifications.get())
R.id.previews -> view.showPreviewModeDialog()
R.id.wake -> wake.set(!wake.get())
R.id.vibration -> vibration.set(!vibration.get())
R.id.ringtone -> view.showRingtonePicker(ringtone.get().takeIf { it.isNotEmpty() }?.let(Uri::parse))
R.id.action1 -> view.showActionDialog(prefs.notifAction1.get())
R.id.action2 -> view.showActionDialog(prefs.notifAction2.get())
R.id.action3 -> view.showActionDialog(prefs.notifAction3.get())
R.id.qkreply -> prefs.qkreply.set(!prefs.qkreply.get())
R.id.qkreplyTapDismiss -> prefs.qkreplyTapDismiss.set(!prefs.qkreplyTapDismiss.get())
}
}
view.previewModeSelectedIntent
.autoDisposable(view.scope())
.subscribe { previews.set(it) }
view.ringtoneSelectedIntent
.autoDisposable(view.scope())
.subscribe { ringtone -> this.ringtone.set(ringtone) }
view.actionsSelectedIntent
.withLatestFrom(view.preferenceClickIntent) { action, preference ->
when (preference.id) {
R.id.action1 -> prefs.notifAction1.set(action)
R.id.action2 -> prefs.notifAction2.set(action)
R.id.action3 -> prefs.notifAction3.set(action)
}
}
.autoDisposable(view.scope())
.subscribe()
}
}
|
gpl-3.0
|
eeac50614a87adac46913a2019fd127c
| 42.178808 | 124 | 0.633686 | 4.908886 | false | false | false | false |
Zhuinden/simple-stack
|
samples/advanced-samples/mvvm-sample/src/main/java/com/zhuinden/simplestackexamplemvvm/application/CustomApplication.kt
|
1
|
1337
|
package com.zhuinden.simplestackexamplemvvm.application
import android.app.Application
import com.zhuinden.simplestack.GlobalServices
import com.zhuinden.simplestackexamplemvvm.core.database.DatabaseManager
import com.zhuinden.simplestackexamplemvvm.core.scheduler.BackgroundScheduler
import com.zhuinden.simplestackexamplemvvm.data.tasks.TaskDao
import com.zhuinden.simplestackexamplemvvm.data.tasks.TaskTable
import com.zhuinden.simplestackexamplemvvm.data.tasks.TasksDataSource
import com.zhuinden.simplestackextensions.servicesktx.add
class CustomApplication : Application() {
lateinit var globalServices: GlobalServices
private set
override fun onCreate() {
super.onCreate()
val snackbarTextEmitter = SnackbarTextEmitter()
val backgroundScheduler = BackgroundScheduler()
val taskTable = TaskTable()
val databaseManager = DatabaseManager(this, listOf(taskTable), backgroundScheduler)
val taskDao = TaskDao(databaseManager, taskTable)
val tasksDataSource = TasksDataSource(backgroundScheduler, taskDao)
globalServices = GlobalServices.builder()
.add(snackbarTextEmitter)
.add(backgroundScheduler)
.add(databaseManager)
.add(taskDao)
.add(tasksDataSource)
.build()
}
}
|
apache-2.0
|
e3c9b4afd40557149ade121f15a74ddf
| 32.45 | 91 | 0.749439 | 5.391129 | false | false | false | false |
SUPERCILEX/Robot-Scouter
|
library/shared-scouting/src/main/java/com/supercilex/robotscouter/shared/scouting/MetricListFragment.kt
|
1
|
2419
|
package com.supercilex.robotscouter.shared.scouting
import android.os.Bundle
import android.view.View
import androidx.annotation.LayoutRes
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.firestore.CollectionReference
import com.supercilex.robotscouter.core.ui.FragmentBase
import com.supercilex.robotscouter.core.ui.LifecycleAwareLazy
import com.supercilex.robotscouter.core.ui.SavedStateAdapter
abstract class MetricListFragment(@LayoutRes contentLayoutId: Int) : FragmentBase(contentLayoutId) {
protected val holder by viewModels<MetricListHolder>()
abstract val metricsRef: CollectionReference
abstract val dataId: String
protected val metricsView: RecyclerView by LifecycleAwareLazy {
requireView().findViewById(R.id.metricsView)
}
protected var adapter: SavedStateAdapter<*, *> by LifecycleAwareLazy()
private set
/**
* Hack to ensure the recycler adapter state is saved.
*
* We have to clear our pager adapter of data when the database listeners a killed to prevent
* adapter inconsistencies. Sadly, this means onSaveInstanceState methods are going to be called
* twice which creates invalid saved states. This property serves as a temporary place to store
* the original saved state.
*/
private var tmpSavedAdapterState: Bundle? = null
init {
setHasOptionsMenu(true)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
holder.init(metricsRef)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
metricsView.layoutManager = LinearLayoutManager(context)
metricsView.setHasFixedSize(true)
adapter = onCreateRecyclerAdapter(savedInstanceState)
metricsView.adapter = adapter
tmpSavedAdapterState = null
}
abstract fun onCreateRecyclerAdapter(savedInstanceState: Bundle?): SavedStateAdapter<*, *>
override fun onSaveInstanceState(outState: Bundle) {
outState.putAll(tmpSavedAdapterState ?: run {
if (view != null) adapter.onSaveInstanceState(outState)
tmpSavedAdapterState = outState
outState
})
}
override fun onStop() {
super.onStop()
metricsView.clearFocus()
}
}
|
gpl-3.0
|
fa5663a3bd993eca9752f3ebff8d7a80
| 35.104478 | 100 | 0.737081 | 5.270153 | false | false | false | false |
InnoFang/Android-Code-Demos
|
JetPackDemo/app/src/main/java/io/github/innofang/jetpackdemo/WordRoomDatabase.kt
|
1
|
1792
|
package io.github.innofang.jetpackdemo
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.content.Context
import android.arch.persistence.db.SupportSQLiteDatabase
import android.os.AsyncTask
import android.support.annotation.NonNull
@Database(entities = [Word::class], version = 1)
abstract class WordRoomDatabase : RoomDatabase() {
abstract fun wordDao(): WordDao
companion object {
@Volatile
private var INSTANCE: WordRoomDatabase? = null
fun getDatabase(context: Context): WordRoomDatabase {
if (INSTANCE == null) {
synchronized(WordRoomDatabase::class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.applicationContext,
WordRoomDatabase::class.java,
"word_database")
.addCallback(rootDatabaseCallback)
.build()
}
}
}
return INSTANCE!!
}
private val rootDatabaseCallback = object : RoomDatabase.Callback() {
override fun onOpen(db: SupportSQLiteDatabase) {
super.onOpen(db)
INSTANCE?.let { PopulateDbAsync(it).execute() }
}
}
}
private class PopulateDbAsync(db: WordRoomDatabase): AsyncTask<Unit, Unit, Unit>() {
val wordDao = db.wordDao()
override fun doInBackground(vararg params: Unit?) {
wordDao.deleteAll()
var word = Word("Hello")
wordDao.insert(word)
word = Word("World")
wordDao.insert(word)
}
}
}
|
apache-2.0
|
1eb3609a29fc188f576ac60e1126b462
| 31 | 88 | 0.583705 | 5.301775 | false | false | false | false |
bachhuberdesign/deck-builder-gwent
|
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/deckdetail/DeckDetailPresenter.kt
|
1
|
2367
|
package com.bachhuberdesign.deckbuildergwent.features.deckdetail
import android.util.Log
import com.bachhuberdesign.deckbuildergwent.features.cardviewer.CardRepository
import com.bachhuberdesign.deckbuildergwent.features.deckbuild.DeckRepository
import com.bachhuberdesign.deckbuildergwent.features.shared.base.BasePresenter
import com.bachhuberdesign.deckbuildergwent.features.shared.exception.CardException
import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card
import com.bachhuberdesign.deckbuildergwent.features.shared.model.CardType
import com.bachhuberdesign.deckbuildergwent.inject.annotation.PersistedScope
import javax.inject.Inject
/**
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
@PersistedScope
class DeckDetailPresenter
@Inject constructor(private val deckRepository: DeckRepository,
private val cardRepository: CardRepository) : BasePresenter<DeckDetailMvpContract>() {
companion object {
@JvmStatic val TAG: String = DeckDetailPresenter::class.java.name
}
/**
*
*/
fun loadDeck(deckId: Int) {
val deck = deckRepository.getDeckById(deckId)
if (deck != null) {
getViewOrThrow().onDeckLoaded(deck)
} else {
view!!.showErrorMessage("Unable to load deck $deckId.")
}
}
/**
*
*/
fun removeCardFromDeck(card: Card?, deckId: Int) {
Log.d(TAG, "Removing card ${card?.cardId} from deck with selectedLane: ${card?.selectedLane}")
if (card != null) {
deckRepository.removeCardFromDeck(card, deckId)
getViewOrThrow().cardRemovedFromLane(card)
}
}
/**
*
*/
fun getLeadersForFaction(factionId: Int) {
val leaders: List<Card> = deckRepository.getLeadersForFaction(factionId)
getViewOrThrow().onLeadersLoaded(leaders)
}
/**
*
*/
fun updateLeaderForDeck(deckId: Int, leaderId: Int) {
if (cardRepository.getCardById(leaderId).cardType != CardType.LEADER) {
throw CardException("Tried to add card ID $leaderId but is not a leader. ")
}
deckRepository.updateLeaderForDeck(deckId, leaderId)
val deck = deckRepository.getDeckById(deckId)
getViewOrThrow().onDeckLoaded(deck!!)
getViewOrThrow().showDeckNameChangeDialog()
}
}
|
apache-2.0
|
f3bed8354226d65e78e4160bd9aed3a7
| 30.573333 | 106 | 0.694128 | 4.596117 | false | false | false | false |
mistraltechnologies/smogen
|
src/main/kotlin/com/mistraltech/smogen/codegenerator/matchergenerator/MatcherClassCodeWriter.kt
|
1
|
23064
|
package com.mistraltech.smogen.codegenerator.matchergenerator
import com.mistraltech.smogen.codegenerator.javabuilder.AnnotationBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.BlockStatementBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.CastBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.ClassBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.ExpressionBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.ExpressionStatementBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.ExpressionTextBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.FieldTermBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.JavaDocumentBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.MethodBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.MethodCallBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.NestedClassBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.NewInstanceBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.ParameterBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.ReturnStatementBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.StaticMethodCallBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.TypeBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.TypeParameterBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.TypeParameterDeclBuilder
import com.mistraltech.smogen.codegenerator.javabuilder.VariableBuilder
import com.mistraltech.smogen.property.Property
import com.mistraltech.smogen.property.PropertyLocator.locatePropertiesFromGetters
import com.mistraltech.smogen.utils.NameUtils.createFQN
@Suppress("DuplicatedCode")
internal class MatcherClassCodeWriter(matcherGeneratorProperties: MatcherGeneratorProperties) :
AbstractMatcherCodeWriter(matcherGeneratorProperties) {
override fun generateDocumentContent(document: JavaDocumentBuilder) {
document.addClass(generateMatcherClass())
}
private fun generateMatcherClass(): ClassBuilder {
val generatedClassFQN = createFQN(targetPackage.qualifiedName, generatorProperties.className!!)
val clazz = generateClassOutline()
val matchedType = TypeBuilder.aType()
.withName(sourceClassFQName)
.withTypeBindings(typeParameters())
val returnType: TypeBuilder
val matchedTypeParam: TypeBuilder
val matcherType: TypeBuilder
if (generatorProperties.isExtensible) {
val returnTypeDecl = TypeParameterDeclBuilder.aTypeParameterDecl()
.withName("R")
.withExtends(
TypeBuilder.aType()
.withName(generatedClassFQN)
.withTypeBindings(typeParameters())
.withTypeBinding(
TypeParameterBuilder.aTypeParameter()
.withName("R")
)
.withTypeBinding(
TypeParameterBuilder.aTypeParameter()
.withName("T")
)
)
returnType = returnTypeDecl.type
val matchedTypeDecl = TypeParameterDeclBuilder.aTypeParameterDecl().withName("T")
.withExtends(matchedType)
matchedTypeParam = matchedTypeDecl.type
matcherType = TypeBuilder.aType()
.withName(nestedClassName())
.withTypeBindings(typeParameters())
clazz.withTypeParameter(returnTypeDecl)
.withTypeParameter(matchedTypeDecl)
} else {
clazz.withFinalFlag(true)
returnType = TypeBuilder.aType()
.withName(generatedClassFQN)
.withTypeBindings(typeParameters())
matchedTypeParam = matchedType
matcherType = returnType
}
applySuperClass(clazz, returnType, matchedTypeParam)
applyClassBody(clazz, returnType, matchedType, matchedTypeParam, matcherType)
return clazz
}
private fun generateClassOutline() = ClassBuilder.aJavaClass()
.withAccessModifier("public")
.withName(generatorProperties.className)
.withTypeParameters(typeParameterDecls())
.withAnnotation(
AnnotationBuilder.anAnnotation()
.withType(
TypeBuilder.aType()
.withName("com.mistraltech.smog.core.annotation.Matches")
)
.withParameter(
FieldTermBuilder.aField()
.withType(sourceClassFQName)
.withField("class")
)
)
private fun applySuperClass(clazz: ClassBuilder, returnType: TypeBuilder, matchedTypeParam: TypeBuilder) {
val superType: TypeBuilder = if (generatorProperties.matcherSuperClassName != null) {
TypeBuilder.aType()
.withName(generatorProperties.matcherSuperClassName)
.withTypeBindings(sourceSuperClassParameterBuilders)
.withTypeBinding(returnType)
.withTypeBinding(matchedTypeParam)
} else {
TypeBuilder.aType()
.withName(generatorProperties.baseClassName)
.withTypeBinding(matchedTypeParam)
}
clazz.withSuperclass(superType)
}
private fun applyClassBody(
clazz: ClassBuilder,
returnType: TypeBuilder,
matchedType: TypeBuilder,
matchedTypeParam: TypeBuilder,
matcherType: TypeBuilder
) {
val includeSuperClassProperties = generatorProperties.matcherSuperClassName == null
val sourceClassProperties = locatePropertiesFromGetters(sourceClass!!, includeSuperClassProperties)
val objectDescription = if (generatorProperties.factoryMethodPrefix.isNullOrBlank()) {
sourceClassName
} else {
generatorProperties.factoryMethodPrefix + " " + sourceClassName
}
clazz.withVariable(
VariableBuilder.aVariable()
.withAccessModifier("private")
.withFinalFlag(true)
.withStaticFlag(true)
.withType(TypeBuilder.aType().withName("java.lang.String"))
.withName("MATCHED_OBJECT_DESCRIPTION")
.withInitialiser(
ExpressionBuilder.anExpression()
.withText("\"" + objectDescription + "\"")
)
)
clazz.withVariables(generateMatcherVariables(sourceClassProperties))
.withMethod(generateConstructor(sourceClassProperties, matchedTypeParam))
.withMethod(generateStaticFactoryMethod(matcherType))
if (generatorProperties.isGenerateTemplateFactoryMethod) {
clazz.withMethod(generateLikeStaticFactoryMethod(matcherType, matchedType))
}
if (generatorProperties.isExtensible) {
clazz.withMethod(generateSelfMethod(returnType))
}
sourceClassProperties.forEach { p: Property -> clazz.withMethods(generateMatcherSetters(p, returnType)) }
if (generatorProperties.isExtensible) {
clazz.withNestedClass(generateNestedClass(matcherType, matchedType, sourceClassProperties))
} else {
clazz.withMethod(generateMatchesSafely(matchedType, sourceClassProperties))
}
}
private fun generateMatchesSafely(matchedType: TypeBuilder, properties: List<Property>): MethodBuilder {
val matchesSafelyMethod = MethodBuilder.aMethod()
.withAnnotation(
AnnotationBuilder.anAnnotation()
.withType(
TypeBuilder.aType()
.withName("java.lang.Override")
)
)
.withAccessModifier("protected")
.withReturnType(TypeBuilder.VOID)
.withName("matchesSafely")
.withParameter(
ParameterBuilder.aParameter()
.withFinalFlag(generatorProperties.isMakeMethodParametersFinal)
.withType(matchedType)
.withName("item")
)
.withParameter(
ParameterBuilder.aParameter()
.withFinalFlag(generatorProperties.isMakeMethodParametersFinal)
.withType(
TypeBuilder.aType()
.withName("com.mistraltech.smog.core.MatchAccumulator")
)
.withName("matchAccumulator")
)
.withStatement(
ExpressionStatementBuilder.anExpressionStatement()
.withExpression(
ExpressionBuilder.anExpression()
.withText("super.matchesSafely(item, matchAccumulator)")
)
)
if (!generatorProperties.isUseReflectingPropertyMatcher) {
properties.forEach { p: Property ->
matchesSafelyMethod
.withStatement(
ExpressionStatementBuilder.anExpressionStatement()
.withExpression(
MethodCallBuilder.aMethodCall()
.withObject("matchAccumulator")
.withName("matches")
.withParameter(matcherAttributeName(p))
.withParameter(
MethodCallBuilder.aMethodCall()
.withObject("item")
.withName(p.accessorName)
)
)
)
}
}
return matchesSafelyMethod
}
private fun generateMatcherVariables(properties: List<Property>): List<VariableBuilder> {
return properties.map { generateMatcherVariable(it) }
}
private fun generateMatcherVariable(property: Property): VariableBuilder {
val concretePropertyMatcher = if (generatorProperties.isUseReflectingPropertyMatcher) {
"com.mistraltech.smog.core.ReflectingPropertyMatcher"
} else {
"com.mistraltech.smog.core.PropertyMatcher"
}
val accessModifier =
if (generatorProperties.isUseReflectingPropertyMatcher || !generatorProperties.isExtensible) {
"private"
} else {
"protected"
}
return VariableBuilder.aVariable()
.withAccessModifier(accessModifier)
.withFinalFlag(true)
.withType(
TypeBuilder.aType()
.withName("com.mistraltech.smog.core.PropertyMatcher")
.withTypeBinding(getPropertyTypeBuilder(property, true))
)
.withName(matcherAttributeName(property))
.withInitialiser(
NewInstanceBuilder.aNewInstance()
.withType(
TypeBuilder.aType()
.withName(concretePropertyMatcher)
.withTypeBinding("")
)
.withParameter("\"" + property.name + "\"")
.withParameter("this")
)
}
private fun generateConstructor(sourceClassProperties: List<Property>, matchedType: TypeBuilder): MethodBuilder {
val superMethodCall = MethodCallBuilder.aMethodCall()
.withName("super")
.withParameter("matchedObjectDescription")
if (generatorProperties.matcherSuperClassName != null && generatorProperties.isGenerateTemplateFactoryMethod) {
superMethodCall.withParameter("template")
}
val constructor = MethodBuilder.aMethod()
.withAccessModifier(if (generatorProperties.isExtensible) "protected" else "private")
.withName(generatorProperties.className)
.withParameter(
ParameterBuilder.aParameter()
.withFinalFlag(generatorProperties.isMakeMethodParametersFinal)
.withType(
TypeBuilder.aType()
.withName("java.lang.String")
)
.withName("matchedObjectDescription")
)
.withStatement(
ExpressionStatementBuilder.anExpressionStatement()
.withExpression(superMethodCall)
)
if (generatorProperties.isGenerateTemplateFactoryMethod) {
constructor.withParameter(
ParameterBuilder.aParameter()
.withFinalFlag(generatorProperties.isMakeMethodParametersFinal)
.withType(matchedType)
.withName("template")
)
if (sourceClassProperties.isNotEmpty()) {
val setFromTemplate = BlockStatementBuilder.aBlockStatement()
.withHeader("if (template != null)")
sourceClassProperties.forEach { property: Property ->
setFromTemplate.withStatement(
MethodCallBuilder.aMethodCall()
.withName(setterMethodName(property))
.withParameter(
MethodCallBuilder.aMethodCall()
.withObject("template")
.withName(property.accessorName)
)
)
}
constructor.withStatement(setFromTemplate)
}
}
return constructor
}
private fun generateNestedClass(
matcherType: TypeBuilder,
matchedType: TypeBuilder,
properties: List<Property>
): NestedClassBuilder {
val superCall = MethodCallBuilder.aMethodCall()
.withName("super")
.withParameter("matchedObjectDescription")
if (generatorProperties.isGenerateTemplateFactoryMethod) {
superCall.withParameter("template")
}
val constructor = MethodBuilder.aMethod()
.withAccessModifier("protected")
.withName(nestedClassName())
.withParameter(
ParameterBuilder.aParameter()
.withFinalFlag(generatorProperties.isMakeMethodParametersFinal)
.withType(
TypeBuilder.aType()
.withName("java.lang.String")
)
.withName("matchedObjectDescription")
)
.withStatement(ExpressionStatementBuilder.anExpressionStatement().withExpression(superCall))
if (generatorProperties.isGenerateTemplateFactoryMethod) {
constructor.withParameter(
ParameterBuilder.aParameter()
.withFinalFlag(generatorProperties.isMakeMethodParametersFinal)
.withType(matchedType)
.withName("template")
)
}
return NestedClassBuilder.aNestedClass()
.withAccessModifier("public")
.withStaticFlag(true)
.withName(nestedClassName())
.withTypeParameters(typeParameterDecls())
.withSuperclass(
TypeBuilder.aType()
.withName(generatorProperties.className)
.withTypeBindings(typeParameters())
.withTypeBinding(matcherType)
.withTypeBinding(matchedType)
)
.withMethod(constructor)
.withMethod(generateMatchesSafely(matchedType, properties))
}
private fun generateStaticFactoryMethod(matcherType: TypeBuilder): MethodBuilder {
val newInstance = NewInstanceBuilder.aNewInstance()
.withType(matcherType)
.withParameter("MATCHED_OBJECT_DESCRIPTION")
if (generatorProperties.isGenerateTemplateFactoryMethod) {
newInstance.withParameter("null")
}
return MethodBuilder.aMethod()
.withAccessModifier("public")
.withStaticFlag(true)
.withReturnType(matcherType)
.withTypeParameters(typeParameterDecls())
.withName(
generatorProperties.factoryMethodPrefix + sourceClassName +
generatorProperties.factoryMethodSuffix
)
.withStatement(
ReturnStatementBuilder.aReturnStatement()
.withExpression(newInstance)
)
}
private fun generateLikeStaticFactoryMethod(matcherType: TypeBuilder, matchedType: TypeBuilder): MethodBuilder {
return MethodBuilder.aMethod()
.withAccessModifier("public")
.withStaticFlag(true)
.withReturnType(matcherType)
.withTypeParameters(typeParameterDecls())
.withName(
generatorProperties.factoryMethodPrefix + sourceClassName +
generatorProperties.templateFactoryMethodSuffix
)
.withParameter(
ParameterBuilder.aParameter()
.withFinalFlag(generatorProperties.isMakeMethodParametersFinal)
.withType(matchedType)
.withName("template")
)
.withStatement(
ReturnStatementBuilder.aReturnStatement()
.withExpression(
NewInstanceBuilder.aNewInstance()
.withType(matcherType)
.withParameter("MATCHED_OBJECT_DESCRIPTION")
.withParameter("template")
)
)
}
private fun generateSelfMethod(typeParameterR: TypeBuilder): MethodBuilder {
return MethodBuilder.aMethod()
.withAnnotation(
AnnotationBuilder.anAnnotation()
.withType(
TypeBuilder.aType()
.withName("java.lang.SuppressWarnings")
)
.withParameter(ExpressionTextBuilder.expressionText("\"unchecked\""))
)
.withAccessModifier("private")
.withReturnType(typeParameterR)
.withName("self")
.withStatement(
ReturnStatementBuilder.aReturnStatement()
.withExpression(
ExpressionBuilder.anExpression()
.withTerm(CastBuilder.aCast().withType(typeParameterR))
.withText("this")
)
)
}
private fun generateMatcherSetters(property: Property, returnType: TypeBuilder): List<MethodBuilder> {
val methods: MutableList<MethodBuilder> = ArrayList()
val boxedPropertyType = getPropertyTypeBuilder(property, true)
methods.add(generateSetterTakingValue(returnType, property, boxedPropertyType))
methods.add(generateSetterTakingMatcher(returnType, property, boxedPropertyType))
return methods
}
private fun generateSetterTakingValue(
returnType: TypeBuilder,
property: Property,
boxedPropertyType: TypeBuilder
): MethodBuilder {
val equalToCall = StaticMethodCallBuilder.aStaticMethodCall()
.withType(
TypeBuilder.aType()
.withName("org.hamcrest.CoreMatchers")
)
.withName("equalTo")
.withParameter(property.fieldName)
if (boxedPropertyType.containsWildcard()) {
equalToCall.withTypeBinding(boxedPropertyType)
}
return MethodBuilder.aMethod()
.withAccessModifier("public")
.withReturnType(returnType)
.withName(setterMethodName(property))
.withParameter(
ParameterBuilder.aParameter()
.withFinalFlag(generatorProperties.isMakeMethodParametersFinal)
.withType(getPropertyTypeBuilder(property, false))
.withName(property.fieldName)
)
.withStatement(
ReturnStatementBuilder.aReturnStatement()
.withExpression(
MethodCallBuilder.aMethodCall()
.withName(setterMethodName(property))
.withParameter(equalToCall)
)
)
}
private fun generateSetterTakingMatcher(
returnType: TypeBuilder,
property: Property,
boxedPropertyType: TypeBuilder
): MethodBuilder {
val returnExpression = if (generatorProperties.isExtensible) {
ExpressionBuilder.anExpression()
.withTerm(
MethodCallBuilder.aMethodCall()
.withName("self")
)
} else {
ExpressionBuilder.anExpression()
.withText("this")
}
return MethodBuilder.aMethod()
.withAccessModifier("public")
.withReturnType(returnType)
.withName(setterMethodName(property))
.withParameter(
ParameterBuilder.aParameter()
.withFinalFlag(generatorProperties.isMakeMethodParametersFinal)
.withType(
TypeBuilder.aType()
.withName("org.hamcrest.Matcher")
.withTypeBinding(
TypeParameterBuilder.aTypeParameter()
.withType(boxedPropertyType)
.withSuperTypes(true)
)
)
.withName(matcherAttributeName(property))
)
.withStatement(
ExpressionStatementBuilder.anExpressionStatement()
.withExpression(
MethodCallBuilder.aMethodCall()
.withObject("this." + matcherAttributeName(property))
.withName("setMatcher")
.withParameter(
ExpressionBuilder.anExpression().withText(matcherAttributeName(property))
)
)
)
.withStatement(
ReturnStatementBuilder.aReturnStatement()
.withExpression(returnExpression)
)
}
private fun nestedClassName(): String {
return generatorProperties.className.toString() + "Type"
}
}
|
bsd-3-clause
|
9b1e6ed7cc85f9de24eb4c78c982653b
| 40.039146 | 119 | 0.584417 | 6.890947 | false | false | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/settings/MdParserSettings.kt
|
1
|
15516
|
// 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.settings
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.vladsch.md.nav.editor.util.HtmlPanelProvider
import com.vladsch.md.nav.parser.Extensions
import com.vladsch.md.nav.parser.MdLexParser
import com.vladsch.md.nav.settings.api.MdExtendableSettings
import com.vladsch.md.nav.settings.api.MdExtendableSettingsImpl
import com.vladsch.md.nav.settings.api.MdSettings
class MdParserSettings @JvmOverloads constructor(extensionFlags: Int,
optionFlags: Long,
wasShownGitHubSyntaxChange: Boolean,
emojiShortcuts: Int,
emojiImages: Int,
private val mySettingsExtensions: MdExtendableSettingsImpl = MdExtendableSettingsImpl()
) : StateHolderImpl({ MdParserSettings() }), MdExtendableSettings by mySettingsExtensions, MdSettings {
init {
initializeExtensions(this)
}
constructor() : this(DEFAULT._pegdownFlags, DEFAULT._parserFlags, false, DEFAULT.emojiShortcuts, DEFAULT.emojiImages)
constructor(pegdownExtensions: Collection<PegdownExtensions>, parserOptions: Collection<ParserOptions>, wasShownGitHubSyntaxChange: Boolean, emojiShortcuts: EmojiShortcutsType, emojiImages: EmojiImagesType)
: this(PegdownExtensions.asFlags(pegdownExtensions), ParserOptions.asFlags(parserOptions), wasShownGitHubSyntaxChange, emojiShortcuts.intValue, emojiImages.intValue)
constructor(other: MdParserSettings) : this(other._pegdownFlags, other._parserFlags, other.gitHubSyntaxChange, other.emojiShortcuts, other.emojiImages) {
mySettingsExtensions.copyFrom(other)
}
override fun resetToDefaults() {
LOG.debug { "MdParserSettings:resetToDefaults:$hashCodeId" }
copyFrom(DEFAULT, withExtensions = false, validateReset = false)
}
val hashCodeId: String get() = "@" + super.hashCode().toString(16)
private var correctedInvalidSettings = false
private fun validateReset(_pegdownFlags: Int) {
if (LOG_TOC_RESET.isDebugEnabled) {
if (_pegdownFlags and Extensions.TOC == 0) {
// log stack trace
try {
throw IllegalStateException("TOC reset")
} catch (e: IllegalStateException) {
LOG_TOC_RESET.info(e)
}
}
}
}
fun copyFrom(other: MdParserSettings, withExtensions: Boolean = true) {
copyFrom(other, withExtensions, validateReset = true)
}
private fun copyFrom(other: MdParserSettings, withExtensions: Boolean, validateReset: Boolean) {
if (other._pegdownFlags == 0 && other._parserFlags == 0L) {
LOG.error("Copying cleared Parser settings from $other to $this")
}
if (validateReset) validateReset(other._pegdownFlags)
this._pegdownFlags = other._pegdownFlags
this._parserFlags = other._parserFlags
this.gitHubSyntaxChange = other.gitHubSyntaxChange
this.emojiShortcuts = other.emojiShortcuts
this.emojiImages = other.emojiImages
// this.correctedInvalidSettings = other.correctedInvalidSettings
if (withExtensions) mySettingsExtensions.copyFrom(other)
if (validateReset) validateReset(this._pegdownFlags)
}
private var _pegdownFlags = extensionFlags
var pegdownFlags: Int
get() = _pegdownFlags
set(value) {
_pegdownFlags = value
validateReset(this._pegdownFlags)
}
private val pegdownExtensions: Set<PegdownExtensions>
get() = PegdownExtensions.asSet(_pegdownFlags)
fun anyExtensions(flags: Int): Boolean {
return (_pegdownFlags and flags) != 0
}
override fun validateLoadedSettings() {
mySettingsExtensions.validateLoadedSettings()
validateReset(this._pegdownFlags)
// NOTE: if settings are cleared then this will reset them to defaults
if (_pegdownFlags == 0 && _parserFlags == 0L) {
LOG.info("Resetting Parser settings on load: $this")
correctedInvalidSettings = true
_pegdownFlags = DEFAULT._pegdownFlags
_parserFlags = DEFAULT._parserFlags
emojiShortcuts = DEFAULT.emojiShortcuts
emojiImages = DEFAULT.emojiImages
} else {
correctedInvalidSettings = false
}
validateReset(this._pegdownFlags)
}
fun anyExtensions(vararg flags: PegdownExtensions): Boolean {
return flags.any { anyExtensions(it.flags) }
}
fun allExtensions(flags: Int): Boolean {
return (_pegdownFlags and flags) == flags
}
fun allExtensions(vararg flags: PegdownExtensions): Boolean {
return flags.all { anyExtensions(it.flags) }
}
private var _parserFlags: Long = optionFlags
var optionsFlags: Long
get() = _parserFlags
set(value) {
_parserFlags = value
}
fun anyOptions(flags: Long): Boolean {
return (_parserFlags and flags) != 0L
}
fun anyOptions(vararg flags: ParserOptions): Boolean {
return flags.any { anyOptions(it.flags) }
}
fun allOptions(flags: Long): Boolean {
return (_parserFlags and flags) != 0L
}
fun allOptions(vararg flags: ParserOptions): Boolean {
return flags.all { anyOptions(it.flags) }
}
private var parserOptions: Set<ParserOptions>
get() = ParserOptions.asSet(_parserFlags)
private set(value) {
_parserFlags = ParserOptions.asFlags(value)
}
val parserListIndentationType: ListIndentationType
get() {
return listIndentationType(optionsFlags)
}
var gitHubSyntaxChange: Boolean = wasShownGitHubSyntaxChange
var emojiShortcuts: Int = emojiShortcuts
private set
var emojiShortcutsType: EmojiShortcutsType
get() = EmojiShortcutsType.ADAPTER.findEnum(emojiShortcuts)
set(value) {
emojiShortcuts = value.intValue
}
var emojiImages: Int = emojiImages
protected set
var emojiImagesType: EmojiImagesType
get() = EmojiImagesType.ADAPTER.findEnum(emojiImages)
set(value) {
emojiImages = value.intValue
}
override fun getStateHolder(): StateHolder {
return mySettingsExtensions.addItems(TagItemHolder("ParserSettings").addItems(
MapItem("PegdownExtensions",
// NOTE: turning off code only flags to prevent saved settings toggling their state from version to version
{
val map = PegdownExtensions.asMap((_pegdownFlags and EXCLUDED_PEGDOWN_EXTENSIONS.inv()) or PegdownExtensions.INTELLIJ_DUMMY_IDENTIFIER.flags)
val filtered = map.filter { it.value }.toMap()
filtered
},
{
_pegdownFlags = PegdownExtensions.asFlags(it)
validateReset(this._pegdownFlags)
},
{ key, value -> Pair(key.name, value.toString()) },
{ key, value ->
val enumConstant = PegdownExtensions.enumConstant(key)
if (enumConstant == null) null else Pair(enumConstant, value?.toBoolean() ?: false)
}),
MapItem("ParserOptions",
{
val map = ParserOptions.asMap((_parserFlags and EXCLUDED_PARSER_OPTIONS.inv()) or MdLexParser.PRODUCTION_SPEC_PARSER)
val filtered = map.filter { it.value }.toMap()
filtered
},
{ _parserFlags = ParserOptions.asFlags(it) },
{ key, value -> Pair(key.name, value.toString()) },
{ key, value ->
val enumConstant = ParserOptions.enumConstant(key)
if (enumConstant == null) null else Pair(enumConstant, value?.toBoolean() ?: false)
}),
BooleanAttribute("gitHubSyntaxChange", { gitHubSyntaxChange }, { gitHubSyntaxChange = it }),
BooleanAttribute("correctedInvalidSettings", { correctedInvalidSettings }, { correctedInvalidSettings = it }),
IntAttribute("emojiShortcuts", { emojiShortcuts }, { emojiShortcuts = it }),
IntAttribute("emojiImages", { emojiImages }, { emojiImages = it })
))
}
interface Holder {
var parserSettings: MdParserSettings
}
fun isDefault(htmlPanelProvider: HtmlPanelProvider.Info?): Boolean {
return !correctedInvalidSettings && this == getDefaultSettings(htmlPanelProvider)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as MdParserSettings
if ((_pegdownFlags and EXCLUDED_PEGDOWN_EXTENSIONS.inv()) != (other._pegdownFlags and EXCLUDED_PEGDOWN_EXTENSIONS.inv())) return false
if ((_parserFlags and EXCLUDED_PARSER_OPTIONS.inv()) != (other._parserFlags and EXCLUDED_PARSER_OPTIONS.inv())) return false
if (gitHubSyntaxChange != other.gitHubSyntaxChange) return false
if (emojiShortcuts != other.emojiShortcuts) return false
if (emojiImages != other.emojiImages) return false
// if (correctedInvalidSettings != other.correctedInvalidSettings) return false
return mySettingsExtensions == other
}
override fun hashCode(): Int {
var result = mySettingsExtensions.hashCode()
result += 31 * result + (_pegdownFlags and EXCLUDED_PEGDOWN_EXTENSIONS.inv()).hashCode()
result += 31 * result + (_parserFlags and EXCLUDED_PARSER_OPTIONS.inv()).hashCode()
result += 31 * result + gitHubSyntaxChange.hashCode()
result += 31 * result + emojiShortcuts.hashCode()
result += 31 * result + emojiImages.hashCode()
// result += 31 * result + correctedInvalidSettings.hashCode()
return result
}
@Suppress("UNUSED_PARAMETER")
fun changeToProvider(fromPanelProviderInfo: HtmlPanelProvider.Info?, toPanelProviderInfo: HtmlPanelProvider.Info) {
}
companion object {
private val LOG = Logger.getInstance("com.vladsch.md.nav.settings.parser")
private val LOG_TOC_RESET = Logger.getInstance("com.vladsch.md.nav.settings.parser.tocReset")
const val EXCLUDED_PEGDOWN_EXTENSIONS: Int =
Extensions.INTELLIJ_DUMMY_IDENTIFIER or
Extensions.MULTI_LINE_IMAGE_URLS
const val EXCLUDED_PARSER_OPTIONS: Long = MdLexParser.PRODUCTION_SPEC_PARSER
const val GITHUB_DOCUMENT_COMPATIBLE: Long = MdLexParser.EMOJI_SHORTCUTS or
MdLexParser.GFM_TABLE_RENDERING or
MdLexParser.COMMONMARK_LISTS
const val GITBOOK_DOCUMENT_COMPATIBLE: Long = MdLexParser.EMOJI_SHORTCUTS or
MdLexParser.GFM_TABLE_RENDERING or
MdLexParser.GITHUB_LISTS or
MdLexParser.GFM_LOOSE_BLANK_LINE_AFTER_ITEM_PARA or
MdLexParser.GITBOOK_URL_ENCODING or
MdLexParser.ATTRIBUTES_EXT or
MdLexParser.HEADER_ID_NO_DUPED_DASHES or
MdLexParser.HEADER_ID_NON_ASCII_TO_LOWERCASE
const val GITHUB_WIKI_COMPATIBLE: Long = GITHUB_DOCUMENT_COMPATIBLE or MdLexParser.GITHUB_WIKI_LINKS
const val COMMONMARK: Long = MdLexParser.COMMONMARK_LISTS or
MdLexParser.HEADER_ID_NON_ASCII_TO_LOWERCASE
const val COMMONMARK_EXTENSIONS: Int = Extensions.FENCED_CODE_BLOCKS or
Extensions.RELAXEDHRULES or
Extensions.ATXHEADERSPACE
const val GITHUB_COMMENT_COMPATIBLE: Long = MdLexParser.COMMONMARK_LISTS or
MdLexParser.EMOJI_SHORTCUTS or
MdLexParser.GFM_TABLE_RENDERING
const val GITLAB_DOCUMENT_COMPATIBLE: Long = MdLexParser.COMMONMARK_LISTS or
MdLexParser.EMOJI_SHORTCUTS or
MdLexParser.GFM_TABLE_RENDERING or
MdLexParser.GITLAB_EXT or
MdLexParser.GITLAB_MATH_EXT or
MdLexParser.GITLAB_MERMAID_EXT or
MdLexParser.HEADER_ID_NO_DUPED_DASHES or
MdLexParser.HEADER_ID_NON_ASCII_TO_LOWERCASE
@JvmStatic
val DEFAULT: MdParserSettings by lazy { MdParserSettings(Extensions.GITHUB_DOCUMENT_COMPATIBLE and Extensions.AUTOLINKS.inv(), GITHUB_DOCUMENT_COMPATIBLE or MdLexParser.SIM_TOC_BLANK_LINE_SPACER, false, EmojiShortcutsType.GITHUB.intValue, EmojiImagesType.IMAGE_ONLY.intValue) }
@JvmStatic
val GITBOOK: MdParserSettings by lazy { MdParserSettings(Extensions.GITHUB_DOCUMENT_COMPATIBLE, GITBOOK_DOCUMENT_COMPATIBLE or MdLexParser.SIM_TOC_BLANK_LINE_SPACER, false, EmojiShortcutsType.GITHUB.intValue, EmojiImagesType.IMAGE_ONLY.intValue) }
@JvmStatic
val GITLAB: MdParserSettings by lazy { MdParserSettings(Extensions.GITHUB_DOCUMENT_COMPATIBLE, GITLAB_DOCUMENT_COMPATIBLE or MdLexParser.SIM_TOC_BLANK_LINE_SPACER, false, EmojiShortcutsType.GITHUB.intValue, EmojiImagesType.IMAGE_ONLY.intValue) }
@JvmStatic
val GITHUB: MdParserSettings by lazy { MdParserSettings(Extensions.GITHUB_DOCUMENT_COMPATIBLE, GITHUB_DOCUMENT_COMPATIBLE or MdLexParser.SIM_TOC_BLANK_LINE_SPACER, false, EmojiShortcutsType.GITHUB.intValue, EmojiImagesType.IMAGE_ONLY.intValue) }
@JvmStatic
val FOR_SAMPLE_DOC: MdParserSettings by lazy {
val pegdownExtensionFlags = (
Extensions.GITHUB_DOCUMENT_COMPATIBLE or
Extensions.ALL or
Extensions.AUTOLINKS or
Extensions.RELAXEDHRULES or
Extensions.TOC or
Extensions.TASKLISTITEMS or
Extensions.FOOTNOTES or
// Extensions.ASIDE or // this one conflicts with table
Extensions.DEFINITIONS or
Extensions.SUBSCRIPT or
Extensions.SUPERSCRIPT or
Extensions.INSERTED
) and (Extensions.ATXHEADERSPACE).inv()
val parserOptionsFlags = (
MdLexParser.ATTRIBUTES_EXT or
MdLexParser.COMMONMARK_LISTS or
MdLexParser.EMOJI_SHORTCUTS or
MdLexParser.ENUMERATED_REFERENCES_EXT or
MdLexParser.GITHUB_WIKI_LINKS or
MdLexParser.GITLAB_EXT or
MdLexParser.JEKYLL_FRONT_MATTER or
MdLexParser.MACROS_EXT or
MdLexParser.SIM_TOC_BLANK_LINE_SPACER
) and (MdLexParser.GITHUB_LISTS).inv()
MdParserSettings(pegdownExtensionFlags, parserOptionsFlags, true, EmojiShortcutsType.ANY_GITHUB_PREFERRED.intValue, EmojiImagesType.IMAGE_ONLY.intValue)
}
@Suppress("UNUSED_PARAMETER")
fun getDefaultSettings(htmlPanelProvider: HtmlPanelProvider.Info?): MdParserSettings = DEFAULT
@JvmStatic
fun listIndentationType(parserOptionsFlags: Long): ListIndentationType {
if (parserOptionsFlags and MdLexParser.COMMONMARK_LISTS != 0L) {
return ListIndentationType.COMMONMARK
}
if (parserOptionsFlags and MdLexParser.GITHUB_LISTS != 0L) {
return ListIndentationType.GITHUB
}
return ListIndentationType.FIXED
}
}
}
|
apache-2.0
|
bbcc896dc85afa4546b47dec548be56c
| 42.220056 | 285 | 0.657773 | 5.273963 | false | false | false | false |
fnberta/PopularMovies
|
app/src/main/java/ch/berta/fabio/popularmovies/Extentions.kt
|
1
|
2169
|
/*
* Copyright (c) 2017 Fabio Berta
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.berta.fabio.popularmovies
import android.animation.ObjectAnimator
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleRegistry
import android.view.View
import android.widget.TextView
import io.reactivex.Observable
import java.text.DateFormat
import java.util.*
fun <T> Observable<T>.log(tag: String): Observable<T> = doOnNext { timber.log.Timber.d("$tag: $it") }
fun <T> Observable<T>.bindTo(lifecycleRegistry: LifecycleRegistry): Observable<T> = compose {
it
.takeWhile { lifecycleRegistry.currentState != Lifecycle.State.DESTROYED }
.filter { lifecycleRegistry.currentState.isAtLeast(Lifecycle.State.STARTED) }
}
private const val COLLAPSE_EXPAND_ANIM_TIME: Long = 300
private const val MAX_LINES_EXPANDED = 500
/**
* Expands or collapses a [TextView] by increasing or decreasing its maxLines setting.
*
* @param maxLinesCollapsed the number of lines in the collapsed state
*/
fun TextView.expandOrCollapse(maxLinesCollapsed: Int) {
val value = if (maxLines == maxLinesCollapsed) MAX_LINES_EXPANDED else maxLinesCollapsed
val anim = ObjectAnimator.ofInt(this, "maxLines", value)
anim.duration = COLLAPSE_EXPAND_ANIM_TIME
anim.start()
}
fun View.setHeight(height: Int) {
val params = layoutParams
params.height = height
layoutParams = params
}
fun Date.formatLong(): String = DateFormat.getDateInstance(DateFormat.LONG, Locale.getDefault()).format(this)
fun Date.formatShort(): String = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).format(this)
|
apache-2.0
|
8c7d4e5c5daaf2919b6058bf2b10ab99
| 35.762712 | 111 | 0.754265 | 4.147228 | false | false | false | false |
jpmoreto/play-with-robots
|
android/lib/src/main/java/jpm/lib/graph/graphbuilder/GraphBuilder.kt
|
1
|
5163
|
package jpm.lib.graph.graphbuilder
import it.unimi.dsi.fastutil.objects.ObjectAVLTreeSet
import jpm.lib.graph.graphs.WeightedSpaceGraph
import jpm.lib.maps.KDTreeD
import jpm.lib.math.DoubleVector2D
import jpm.lib.math.RectangleContext
import jpm.lib.math.Side
/**
* Created by jm on 25/03/17.
*
*/
object GraphBuilder {
fun build(startPoint: DoubleVector2D, endPoint: DoubleVector2D, rectangles: Collection<RectangleContext>): WeightedSpaceGraph.Graph {
val graph = WeightedSpaceGraph.Graph()
val startNode = WeightedSpaceGraph.Node(startPoint,startPoint,startPoint)
graph.add(startNode)
graph.startAdd(startNode)
val endNode = WeightedSpaceGraph.Node(endPoint,endPoint,endPoint)
graph.add(endNode)
graph.endAdd(endNode)
fun addHorizontal(nodesToAdd: ObjectAVLTreeSet<WeightedSpaceGraph.Node>, r: RectangleContext, other: RectangleContext, y: Double) {
val xMin = Math.max(other.p1.x,r.p1.x)
val xMax = Math.min(other.p2.x,r.p2.x)
val middlePoint = DoubleVector2D((xMin + xMax) / 2.0, y)
var node = graph.nodes[middlePoint]
if(node === null) {
node = WeightedSpaceGraph.Node(DoubleVector2D(xMin,y),DoubleVector2D(xMax,y),middlePoint)
graph.add(node)
}
nodesToAdd.add(node)
}
fun addVertical(nodesToAdd: ObjectAVLTreeSet<WeightedSpaceGraph.Node>, r: RectangleContext, other: RectangleContext, x: Double) {
val yMin = Math.max(other.p1.y,r.p1.y)
val yMax = Math.min(other.p2.y,r.p2.y)
val middlePoint = DoubleVector2D(x, (yMin + yMax) / 2.0)
var node1 = graph.nodes[middlePoint]
if(node1 === null) {
node1 = WeightedSpaceGraph.Node(DoubleVector2D(x,yMin),DoubleVector2D(x,yMax),middlePoint)
graph.add(node1)
}
nodesToAdd.add(node1)
}
var startFound = false
var endFound = false
val nodesToAdd = ObjectAVLTreeSet<WeightedSpaceGraph.Node>(WeightedSpaceGraph.NodeComparator)
for(r in rectangles) {
for (bottom in r[Side.BOTTOM]) addHorizontal(nodesToAdd,r,bottom,bottom.p2.y)
for (top in r[Side.TOP]) addHorizontal(nodesToAdd,r,top,top.p1.y)
for (left in r[Side.LEFT]) addVertical(nodesToAdd,r,left,left.p2.x)
for (right in r[Side.RIGHT]) addVertical(nodesToAdd,r,right,right.p1.x)
for(nodeA in nodesToAdd)
for(nodeB in nodesToAdd)
if(nodeA !== nodeB)
WeightedSpaceGraph.Arc(nodeA,nodeB,(nodeA.middlePoint - nodeB.middlePoint).length())
if(!startFound && r.contains(startPoint)) {
for(nodeA in nodesToAdd)
WeightedSpaceGraph.Arc(startNode,nodeA,(startNode.middlePoint - nodeA.middlePoint).length())
startFound = true
}
if(!endFound && r.contains(endPoint)) {
for(nodeA in nodesToAdd)
WeightedSpaceGraph.Arc(nodeA,endNode,(endNode.middlePoint - nodeA.middlePoint).length())
endFound = true
}
nodesToAdd.clear()
}
return graph
}
fun getPath(graph: WeightedSpaceGraph.Graph): List<WeightedSpaceGraph.Node> {
val path = mutableListOf<WeightedSpaceGraph.Node>()
var node = graph.endNode
val startNode = graph.startNode
if(node !== null && startNode !== null) {
while (node !== null) {
path.add(node)
node = node.from()
}
}
return path.asReversed()
}
fun optimizePath(originalPath: List<WeightedSpaceGraph.Node>, tree: KDTreeD.Node, occupiedThreshold: Double): List<WeightedSpaceGraph.Node> {
fun havePathFromTo(start: WeightedSpaceGraph.Node, end: WeightedSpaceGraph.Node): Boolean {
var occupied = false
fun visit(tree: KDTreeD.Node, p: DoubleVector2D, v: DoubleVector2D, t: Double): Boolean {
if (tree.isLeaf && tree.occupied() > occupiedThreshold) occupied = true
return !occupied
}
tree.intersectRay(start.middlePoint,end.middlePoint - start.middlePoint, 1.0, ::visit)
return !occupied
}
if(originalPath.isEmpty()) return originalPath
val path = mutableListOf<WeightedSpaceGraph.Node>()
var firstNode: WeightedSpaceGraph.Node? = null
var lastNode: WeightedSpaceGraph.Node? = null
for (node in originalPath) {
if (firstNode === null) {
firstNode = node
path.add(firstNode)
} else {
if (lastNode !== null && !havePathFromTo(firstNode, node)) {
path.add(lastNode)
firstNode = lastNode
}
lastNode = node
}
}
if (firstNode !== originalPath.last()) {
path.add(lastNode!!)
}
return path
}
}
|
mit
|
9bfe2c68e5a5d26ab5211f5a90468133
| 32.973684 | 145 | 0.594809 | 4.360642 | false | false | false | false |
laurencegw/jenjin
|
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/specs/render/RenderNodeSpec.kt
|
1
|
6838
|
package com.binarymonks.jj.core.specs.render
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.ParticleEffect
import com.badlogic.gdx.graphics.g2d.PolygonSprite
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.utils.Array
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.assets.AssetReference
import com.binarymonks.jj.core.extensions.copy
import com.binarymonks.jj.core.pools.recycleItems
import com.binarymonks.jj.core.properties.PropOverride
import com.binarymonks.jj.core.render.ShaderSpec
import com.binarymonks.jj.core.render.nodes.*
import com.binarymonks.jj.core.workshop.ParamStack
import kotlin.reflect.KClass
abstract class RenderNodeSpec {
var id = JJ.B.nextID()
var priority: Int = 0
var color: PropOverride<Color> = PropOverride(Color.WHITE)
var renderGraphType: RenderGraphType = RenderGraphType.DEFAULT
var name: String? = null
var shaderSpec: ShaderSpec? = null
abstract fun getAssets(): Array<AssetReference>
abstract fun makeNode(paramsStack: ParamStack): RenderNode
}
abstract class SpatialRenderNodeSpec : RenderNodeSpec() {
var offsetX = 0f
var offsetY = 0f
var rotationD = 0f
}
class PolygonRenderNodeSpec : SpatialRenderNodeSpec() {
var vertices: Array<Vector2> = Array()
override fun makeNode(paramsStack: ParamStack): RenderNode {
var sprite: PolygonSprite?
if (PolygonRenderNode.haveBuilt(this)) {
sprite = PolygonRenderNode.getSprite(this)
} else {
val vertCopy: Array<Vector2> = Array()
vertices.forEach { vertCopy.add(it.copy()) }
sprite = PolygonRenderNode.polygonSprite(vertices)
recycleItems(vertCopy)
}
return PolygonRenderNode(
priority,
color.clone(),
renderGraphType,
name,
shaderSpec,
checkNotNull(sprite),
paramsStack.scaleX,
paramsStack.scaleY,
offsetX * paramsStack.scaleX,
offsetY * paramsStack.scaleY,
rotationD
)
}
override fun getAssets(): Array<AssetReference> {
return Array()
}
}
class LineChainRenderNodeSpec : SpatialRenderNodeSpec() {
var vertices: Array<Vector2> = Array()
var fill: Boolean = false
override fun makeNode(paramsStack: ParamStack): RenderNode {
val vertCopy: Array<Vector2> = Array()
vertices.forEach { vertCopy.add(it.copy()) }
return LineChainRenderNode(
priority,
color.clone(),
renderGraphType,
name,
shaderSpec,
fill,
paramsStack.scaleX,
paramsStack.scaleY,
offsetX,
offsetY,
rotationD,
vertCopy
)
}
override fun getAssets(): Array<AssetReference> {
return Array()
}
}
class CircleRenderNodeSpec : SpatialRenderNodeSpec() {
var radius: Float = 1f
var fill: Boolean = true
override fun makeNode(paramsStack: ParamStack): RenderNode {
return CircleRenderNode(
this.priority,
this.color.clone(),
renderGraphType,
name,
shaderSpec,
fill = fill,
offsetX = offsetX * paramsStack.scaleX,
offsetY = offsetY * paramsStack.scaleY,
radius = radius * paramsStack.scaleX
)
}
override fun getAssets(): Array<AssetReference> {
return Array()
}
}
abstract class ImageNodeSpec<out K : KClass<*>> : SpatialRenderNodeSpec() {
var width: Float = 1f
var height: Float = 1f
var assetPath: String? = null
override fun getAssets(): Array<AssetReference> {
val assets: Array<AssetReference> = Array()
if (assetPath != null) {
assets.add(AssetReference(assetClass(), assetPath!!))
} else {
throw Exception("Trying to fetch an asset that has no path set")
}
return assets
}
abstract fun assetClass(): K
}
class ParticleNodeSpec : SpatialRenderNodeSpec() {
var effectPath: String? = null
var imageDir: String? = null
var atlatPath: String? = null
var scale = 1f
override fun getAssets(): Array<AssetReference> {
if (imageDir == null && atlatPath == null) {
throw Exception("Need to set one of imageDir or atlasPath")
}
//TODO: Make the spec point at an optional atlas to allow preloading particle images
val assets: Array<AssetReference> = Array()
return assets
}
override fun makeNode(paramsStack: ParamStack): RenderNode {
val particleEffect = ParticleEffect()
particleEffect.load(Gdx.files.internal(effectPath), Gdx.files.internal(imageDir))
return ParticleRenderNode(
priority = priority,
color = color.clone(),
renderGraphType = renderGraphType,
name = name,
shaderSpec = shaderSpec,
particleEffect = particleEffect,
offsetX = offsetX,
offsetY = offsetY,
rotationD = rotationD,
scale = scale * paramsStack.scaleX
)
}
}
class TextureNodeSpec : ImageNodeSpec<KClass<Texture>>() {
override fun assetClass() = Texture::class
override fun makeNode(paramsStack: ParamStack): RenderNode {
val frameProvider: FrameProvider = if (assetPath == null) {
throw Exception("No Path set in backing image")
} else {
TextureFrameProvider(JJ.B.assets.getAsset(assetPath!!, Texture::class))
}
return FrameRenderNode(
priority = priority,
color = color.clone(),
renderGraphType = renderGraphType,
name = name,
shaderSpec = shaderSpec,
provider = frameProvider,
offsetX = offsetX,
offsetY = offsetY,
rotationD = rotationD,
width = width,
height = height,
scaleX = paramsStack.scaleX,
scaleY = paramsStack.scaleY
)
}
}
class TextNodeSpec: RenderNodeSpec() {
override fun getAssets(): Array<AssetReference> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun makeNode(paramsStack: ParamStack): RenderNode {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
|
apache-2.0
|
da59b9c6bff02f0cb1f9601860935a38
| 30.804651 | 107 | 0.607926 | 5.009524 | false | false | false | false |
Samourai-Wallet/samourai-wallet-android
|
app/src/main/java/com/samourai/wallet/onboard/RestoreOptionActivity.kt
|
1
|
9035
|
package com.samourai.wallet.onboard
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.samourai.wallet.R
import com.samourai.wallet.RestoreSeedWalletActivity
import com.samourai.wallet.access.AccessFactory
import com.samourai.wallet.crypto.AESUtil
import com.samourai.wallet.hd.HD_WalletFactory
import com.samourai.wallet.payload.ExternalBackupManager
import com.samourai.wallet.network.dojo.DojoUtil
import com.samourai.wallet.payload.PayloadUtil
import com.samourai.wallet.util.AppUtil
import com.samourai.wallet.util.CharSequenceX
import com.samourai.wallet.util.PrefsUtil
import kotlinx.android.synthetic.main.activity_restore_option.*
import kotlinx.coroutines.*
import org.json.JSONObject
import java.io.*
class RestoreOptionActivity : AppCompatActivity() {
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_restore_option)
window.statusBarColor = ContextCompat.getColor(this, R.color.window)
setSupportActionBar(restoreOptionToolBar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
title = ""
samouraiMnemonicRestore.setOnClickListener {
val intent = Intent(this@RestoreOptionActivity, RestoreSeedWalletActivity::class.java)
intent.putExtra("mode", "mnemonic")
intent.putExtra("type", "samourai")
startActivity(intent)
}
samouraiBackupFileRestore.setOnClickListener {
val intent = Intent(this@RestoreOptionActivity, RestoreSeedWalletActivity::class.java)
intent.putExtra("mode", "backup")
startActivity(intent)
}
externalWalletRestore.setOnClickListener {
val intent = Intent(this@RestoreOptionActivity, RestoreSeedWalletActivity::class.java)
intent.putExtra("mode", "mnemonic")
startActivity(intent)
}
restoreBtn.setOnClickListener { restoreWalletFromBackup() }
ExternalBackupManager.getPermissionStateLiveData().observe(this, Observer {
if (ExternalBackupManager.backupAvailable()) {
restoreFromBackupSnackbar.visibility = View.VISIBLE
} else {
restoreFromBackupSnackbar.visibility = View.GONE
}
})
if (ExternalBackupManager.backupAvailable()) {
restoreFromBackupSnackbar.visibility = View.VISIBLE
} else {
restoreFromBackupSnackbar.visibility = View.GONE
}
restoreOptionToolBar.setNavigationOnClickListener {
this.onBackPressed()
}
}
override fun onDestroy() {
scope.cancel()
super.onDestroy()
}
private fun showLoading(show: Boolean) {
if (show) {
loaderRestore.visibility = View.VISIBLE
restoreBtn.visibility = View.GONE
} else {
loaderRestore.visibility = View.GONE
restoreBtn.visibility = View.VISIBLE
}
}
private fun restoreWalletFromBackup() {
fun initializeRestore(decrypted: String,skipDojo:Boolean){
showLoading(true)
scope.launch(Dispatchers.IO) {
val json = JSONObject(decrypted)
val hdw = PayloadUtil.getInstance(applicationContext)
.restoreWalletfromJSON(json, skipDojo)
HD_WalletFactory.getInstance(applicationContext).set(hdw)
val guid = AccessFactory.getInstance(applicationContext).createGUID()
val hash = AccessFactory.getInstance(applicationContext).getHash(
guid,
CharSequenceX(AccessFactory.getInstance(applicationContext).pin),
AESUtil.DefaultPBKDF2Iterations
)
PrefsUtil.getInstance(applicationContext).setValue(PrefsUtil.ACCESS_HASH, hash)
PrefsUtil.getInstance(applicationContext).setValue(PrefsUtil.ACCESS_HASH2, hash)
PayloadUtil.getInstance(applicationContext)
.saveWalletToJSON(CharSequenceX(guid + AccessFactory.getInstance().pin))
}.invokeOnCompletion {
it?.printStackTrace()
scope.launch(Dispatchers.Main) {
showLoading(false)
}
if (it != null) {
scope.launch(Dispatchers.Main) {
Toast.makeText(this@RestoreOptionActivity, R.string.decryption_error, Toast.LENGTH_SHORT).show()
}
} else {
AppUtil.getInstance(this@RestoreOptionActivity).restartApp()
}
}
}
fun checkRestoreOptions(decrypted: String) {
val json = JSONObject(decrypted)
var existDojo = false
if (json.has("meta") && json.getJSONObject("meta").has("dojo")) {
if (json.getJSONObject("meta").getJSONObject("dojo").has("pairing")) {
existDojo = true
}
}
if (existDojo && DojoUtil.getInstance(application).dojoParams != null) {
MaterialAlertDialogBuilder(this@RestoreOptionActivity)
.setTitle(getString(R.string.dojo_config_detected))
.setMessage(getString(R.string.dojo_config_override))
.setPositiveButton(R.string.yes) { dialog: DialogInterface?, which: Int ->
initializeRestore(decrypted, true)
}
.setNegativeButton(R.string.no) { _: DialogInterface?, _: Int ->
initializeRestore(decrypted, false)
}
.show()
} else {
initializeRestore(decrypted, false)
}
}
suspend fun readBackUp(password: String) = withContext(Dispatchers.IO) {
try {
val backupData = ExternalBackupManager.read()
if (backupData != null) {
val decrypted = PayloadUtil.getInstance(applicationContext).getDecryptedBackupPayload(backupData, CharSequenceX(password))
if (decrypted != null && decrypted.isNotEmpty()) {
withContext(Dispatchers.Main){
checkRestoreOptions(decrypted)
}
}
return@withContext
}
return@withContext
} catch (e: Exception) {
scope.launch(Dispatchers.Main) {
Toast.makeText(this@RestoreOptionActivity, R.string.decryption_error, Toast.LENGTH_SHORT).show()
}
}
}
val builder = MaterialAlertDialogBuilder(this)
builder.setTitle(R.string.restore_backup)
val inflater = layoutInflater
val view = inflater.inflate(R.layout.password_input_dialog_layout, null)
view.findViewById<TextView>(R.id.dialogMessage).setText(R.string.enter_your_wallet_passphrase)
val password = view.findViewById<EditText>(R.id.restore_dialog_password_edittext)
builder.setView(view)
builder.setPositiveButton(R.string.restore) { dialog, which ->
dialog.dismiss()
scope.launch {
readBackUp(password.text.toString())
}.invokeOnCompletion {
}
}
builder.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.cancel() }
builder.create().show()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.get_help_menu_create -> {
doSupportCreate()
false
}
R.id.get_help_menu_restore -> {
doSupportRestore()
false
}
else -> {
false
}
}
}
private fun doSupportCreate() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://docs.samourai.io/wallet/start#create-new-wallet"))
startActivity(intent)
}
private fun doSupportRestore() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://docs.samourai.io/wallet/restore-recovery"))
startActivity(intent)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.landing_activity_menu, menu)
return true
}
}
|
unlicense
|
45522434ef4630a4836b77e8b463e620
| 38.112554 | 142 | 0.617598 | 5.174685 | false | false | false | false |
huhanpan/smart
|
app/src/main/java/com/etong/smart/Main/LeftDrawer/Message/NoticeFragment.kt
|
1
|
7115
|
package com.etong.smart.Main.LeftDrawer.Message
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupMenu
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONException
import com.alibaba.fastjson.JSONObject
import com.etong.smart.Data.Notice
import com.etong.smart.Other.Service
import com.etong.smart.Other.Storage
import com.etong.smart.Other.toDate
import com.etong.smart.R
import io.realm.RealmResults
import org.greenrobot.eventbus.EventBus
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class NoticeFragment : Fragment() {
private var mRecyclerView: RecyclerView? = null
private var mRefreshLayout: SwipeRefreshLayout? = null
private var mNullView: View? = null
private var mResult: RealmResults<Notice>? = null
private var canLoadMore = true
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.fragment_notice, container, false)
mRecyclerView = view.findViewById(R.id.recyclerView) as RecyclerView
mRefreshLayout = view.findViewById(R.id.refreshLayout) as SwipeRefreshLayout
mNullView = view.findViewById(R.id.nullView)
mRefreshLayout?.setColorSchemeColors(0xff4dd0c8.toInt())
mRefreshLayout?.setOnRefreshListener {
loadDataFromWeb()
EventBus.getDefault().post("refresh")
}
loadDataFromDB()
loadDataFromWeb()
return view
}
public fun loadDataFromDB() {
mResult = Storage.mRealm.where(Notice::class.java).findAll()
mResult!!.addChangeListener {
mRecyclerView?.adapter?.notifyDataSetChanged()
mNullView?.visibility = if (it.size == 0) View.VISIBLE else View.GONE
mRecyclerView?.visibility = if (it.size != 0) View.VISIBLE else View.GONE
}
mNullView?.visibility = if (mResult!!.size == 0) View.VISIBLE else View.GONE
mRecyclerView?.visibility = if (mResult!!.size != 0) View.VISIBLE else View.GONE
mRecyclerView?.layoutManager = LinearLayoutManager(context)
mRecyclerView?.adapter = Adapter(mResult!!)
}
private fun loadDataFromWeb(date: String = "") {
Service.getNotice(date).enqueue(object : Callback<String> {
override fun onFailure(call: Call<String>?, t: Throwable?) {
if (mRefreshLayout!!.isRefreshing) mRefreshLayout?.isRefreshing = false
Snackbar.make(mRecyclerView!!, t?.message.toString(), Snackbar.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<String>?, response: Response<String>?) {
if (mRefreshLayout!!.isRefreshing) mRefreshLayout?.isRefreshing = false
if (response != null && response.isSuccessful) {
try {
val json = JSON.parseObject(response.body())
if (json.getInteger("status") == 1) {
val dataStr = json.getString("data")
Storage.mRealm.beginTransaction()
if (date == "")
Storage.mRealm.delete(Notice::class.java)
Storage.mRealm.createOrUpdateAllFromJson(Notice::class.java, dataStr)
Storage.mRealm.commitTransaction()
canLoadMore = JSONObject.parseArray(dataStr).size == 10
}
} catch (e: JSONException) {
}
}
}
})
}
///////////////////////////////////////////////////////////////////////////
// Adpater
///////////////////////////////////////////////////////////////////////////
inner class Adapter(val data: RealmResults<Notice>) : RecyclerView.Adapter<Holder>() {
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): Holder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_notice, parent, false)
return Holder(view)
}
override fun onBindViewHolder(holder: Holder?, position: Int) {
holder?.setView(data[position])
val size = mResult!!.size
if (position == size - 1 && canLoadMore) {
loadDataFromWeb(data[position].create_date.toString())
}
}
override fun getItemCount(): Int {
return data.count()
}
}
///////////////////////////////////////////////////////////////////////////
// Viewholder
///////////////////////////////////////////////////////////////////////////
inner class Holder(val item: View) : RecyclerView.ViewHolder(item) {
private val tv_time: TextView = item.findViewById(R.id.textView11) as TextView
private val notice_title: TextView = item.findViewById(R.id.textView13) as TextView
private val notice_content: TextView = item.findViewById(R.id.textView14) as TextView
private val mbubbleLayout: LinearLayout = item.findViewById(R.id.bubbleLayout) as LinearLayout
fun setView(notice: Notice) {
tv_time.text = notice.create_date?.toDate()
notice_title.text = notice.title
notice_content.text = notice.content
mbubbleLayout.setBackgroundResource(if (notice.is_read == "0") R.drawable.ic_message_bg else R.drawable.ic_message_black_bg)
val menu = PopupMenu(context, mbubbleLayout)
menu.menuInflater.inflate(R.menu.notice_menu, menu.menu)
menu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.set_read -> {
Service.setNoticeRead(notice.id!!).enqueue(object : Callback<String> {
override fun onFailure(call: Call<String>?, t: Throwable?) {
println(t?.message)
}
override fun onResponse(call: Call<String>?, response: Response<String>?) {
println(response?.body())
}
})
EventBus.getDefault().post("-1")
Storage.mRealm.beginTransaction()
notice.is_read = "1"
Storage.mRealm.commitTransaction()
true
}
else -> false
}
}
mbubbleLayout.setOnClickListener {
if (notice.is_read == "0")
menu.show()
}
}
}
}
|
gpl-2.0
|
8f73a86dbb9dabc448def5aa9d5e6c8f
| 42.650307 | 136 | 0.574982 | 5.178311 | false | false | false | false |
youkai-app/Youkai
|
app/src/main/kotlin/app/youkai/ui/feature/login/LoginActivity.kt
|
1
|
3643
|
package app.youkai.ui.feature.login
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.text.method.LinkMovementMethod
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import app.youkai.MainActivity
import app.youkai.R
import app.youkai.util.ext.inputString
import app.youkai.util.ext.snackbar
import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateActivity
import com.hannesdorfmann.mosby.mvp.viewstate.ViewState
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent
import com.jakewharton.rxbinding2.widget.afterTextChangeEvents
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : MvpViewStateActivity<LoginView, LoginPresenter>(), LoginView {
override fun createPresenter(): LoginPresenter = LoginPresenter()
override fun createViewState(): ViewState<LoginView> = LoginState()
override fun onNewViewStateInstance() {
/* do nothing */
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
password.setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_GO && go.isEnabled) {
doLogin()
}
false
}
go.setOnClickListener { doLogin() }
// Allows for HTML-formatted links in the text to be clickable.
bottomLinks.movementMethod = LinkMovementMethod()
val inputConsumer: Consumer<TextViewAfterTextChangeEvent> = Consumer({
enableButton(
presenter.isUsernameSufficient(username.inputString())
&& presenter.isPasswordSufficient(password.inputString())
)
})
username.afterTextChangeEvents().subscribe(inputConsumer)
password.afterTextChangeEvents().subscribe(inputConsumer)
}
override fun onSaveInstanceState(outState: Bundle?) {
getState().usernameEnabled = username.isEnabled
getState().passwordEnabled = password.isEnabled
getState().buttonEnabled = go.isEnabled
getState().progressVisible = progress.visibility == VISIBLE
super.onSaveInstanceState(outState)
}
override fun enableUsername(enable: Boolean) {
username.isEnabled = enable
}
override fun enablePassword(enable: Boolean) {
password.isEnabled = enable
}
override fun enableButton(enable: Boolean) {
go.isEnabled = enable
}
override fun showProgress(show: Boolean) {
progress.visibility = if (show) VISIBLE else GONE
}
override fun showError(message: String) {
val snackbar = root.snackbar(message) {}
snackbar.addCallback(object : Snackbar.Callback() {
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
getState().error = null
}
})
getState().error = message
}
override fun setLoading(isLoading: Boolean) {
getState().isLoading = isLoading
}
override fun doLogin() {
presenter.doLogin(username.inputString(), password.inputString())
}
override fun completeLogin() {
finish()
startActivity(MainActivity.getLaunchIntent(this))
}
private fun getState(): LoginState = viewState as LoginState
companion object {
fun getLaunchIntent(context: Context) = Intent(context, LoginActivity::class.java)
}
}
|
gpl-3.0
|
8ddbdb0e74c8093e948bed5095f8e930
| 30.95614 | 90 | 0.694757 | 5.116573 | false | false | false | false |
ziggy42/Blum
|
app/src/main/java/com/andreapivetta/blu/ui/tweetdetails/TweetDetailsPresenter.kt
|
1
|
3813
|
package com.andreapivetta.blu.ui.tweetdetails
import com.andreapivetta.blu.R
import com.andreapivetta.blu.data.model.Tweet
import com.andreapivetta.blu.data.twitter.TwitterAPI
import com.andreapivetta.blu.ui.base.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import twitter4j.User
/**
* Created by andrea on 25/05/16.
*/
class TweetDetailsPresenter : BasePresenter<TweetDetailsMvpView>() {
private var isLoading = false
private val disposables = CompositeDisposable()
override fun detachView() {
super.detachView()
disposables.clear()
}
fun getConversation(statusId: Long) {
checkViewAttached()
mvpView?.showLoading()
isLoading = true
disposables.add(TwitterAPI.getConversation(statusId)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
mvpView?.hideLoading()
if (it == null)
mvpView?.showError()
else {
val (list, index) = it
if (list.isEmpty())
mvpView?.showError()
else
mvpView?.showTweets(index, list.map(::Tweet).toMutableList())
}
isLoading = false
}, { Timber.e(it) }))
}
fun favorite(tweet: Tweet) {
checkViewAttached()
disposables.add(TwitterAPI.favorite(tweet.id)
.map(::Tweet)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
tweet.favorited = true
tweet.favoriteCount++
mvpView?.updateRecyclerViewView()
}, { Timber.e(it) }))
}
fun retweet(tweet: Tweet) {
checkViewAttached()
disposables.add(TwitterAPI.retweet(tweet.id)
.map(::Tweet)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
tweet.retweeted = true
tweet.retweetCount++
mvpView?.updateRecyclerViewView()
}, { Timber.e(it) }))
}
fun unfavorite(tweet: Tweet) {
checkViewAttached()
disposables.add(TwitterAPI.unfavorite(tweet.id)
.map(::Tweet)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
tweet.favorited = false
tweet.favoriteCount--
mvpView?.updateRecyclerViewView()
}, { Timber.e(it) }))
}
fun unretweet(tweet: Tweet) {
checkViewAttached()
disposables.add(TwitterAPI.unretweet(tweet.status.currentUserRetweetId)
.map(::Tweet)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
if (it != null) {
tweet.retweeted = false
tweet.retweetCount--
mvpView?.updateRecyclerViewView()
} else {
mvpView?.showSnackBar(R.string.error_unretweet)
}
}, {
Timber.e(it)
mvpView?.showSnackBar(R.string.error_unretweet)
}))
}
fun reply(tweet: Tweet, user: User) {
mvpView?.showNewTweet(tweet, user)
}
}
|
apache-2.0
|
36f49182a784f4a2918cff9c41a7ffc5
| 31.598291 | 89 | 0.525833 | 5.447143 | false | false | false | false |
debop/debop4k
|
debop4k-web/src/main/kotlin/debop4k/web/interceptors/Slf4jInterceptor.kt
|
1
|
1859
|
/*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.web.interceptors
import debop4k.core.loggerOf
import org.aspectj.lang.annotation.Aspect
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* Slf4jInterceptor
* @author [email protected]
*/
@Aspect
class Slf4jInterceptor : HandlerInterceptorAdapter() {
private val log = loggerOf(javaClass)
override fun preHandle(request: HttpServletRequest,
response: HttpServletResponse,
handler: Any?): Boolean {
log.trace("pre handle. request method={}, query={}", request.method, request.requestURL)
return super.preHandle(request, response, handler)
}
override fun postHandle(request: HttpServletRequest,
response: HttpServletResponse,
handler: Any?,
modelAndView: ModelAndView?) {
log.trace("post handle. response status={}, request method={}, query={}",
response.status, request.method, request.requestURL)
super.postHandle(request, response, handler, modelAndView)
}
}
|
apache-2.0
|
b4d3269279021ce5b03bd3e8c8732231
| 35.470588 | 92 | 0.70737 | 4.567568 | false | false | false | false |
Mauin/detekt
|
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/SwallowedException.kt
|
1
|
2483
|
package io.gitlab.arturbosch.detekt.rules.exceptions
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.collectByType
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtThrowExpression
/**
* Exceptions should not be swallowed. This rule reports all instances where exceptions are `caught` and not correctly
* passed into a newly thrown exception.
*
* <noncompliant>
* fun foo() {
* try {
* // ...
* } catch(e: IOException) {
* throw MyException(e.message) // e is swallowed
* }
* }
* </noncompliant>
*
* <compliant>
* fun foo() {
* try {
* // ...
* } catch(e: IOException) {
* throw MyException(e)
* }
* }
* </compliant>
*
* @author schalkms
* @author Marvin Ramin
*/
class SwallowedException(config: Config = Config.empty) : Rule(config) {
override val issue = Issue("SwallowedException", Severity.CodeSmell,
"The caught exception is swallowed. The original exception could be lost.",
Debt.TWENTY_MINS)
override fun visitCatchSection(catchClause: KtCatchClause) {
if (isExceptionSwallowed(catchClause) == true) {
report(CodeSmell(issue, Entity.from(catchClause), issue.description))
}
}
private fun isExceptionSwallowed(catchClause: KtCatchClause): Boolean? {
val parameterName = catchClause.catchParameter?.name
val throwExpressions = catchClause.catchBody?.collectByType<KtThrowExpression>()
throwExpressions?.forEach { throwExpr ->
val parameterNameReferences = throwExpr.thrownExpression?.collectByType<KtNameReferenceExpression>()?.filter {
it.text == parameterName
}
return hasParameterReferences(parameterNameReferences)
}
return false
}
private fun hasParameterReferences(parameterNameReferences: List<KtNameReferenceExpression>?): Boolean {
return parameterNameReferences != null &&
parameterNameReferences.isNotEmpty() &&
parameterNameReferences.all { callsMemberOfCaughtException(it) }
}
private fun callsMemberOfCaughtException(expression: KtNameReferenceExpression): Boolean {
return expression.nextSibling?.text == "."
}
}
|
apache-2.0
|
4055dda5edcbbe6ec3c1dd781b2b540e
| 32.106667 | 118 | 0.743858 | 4.173109 | false | true | false | false |
hartwigmedical/hmftools
|
teal/src/main/kotlin/com/hartwig/hmftools/teal/telbam/TelbamReader.kt
|
1
|
3700
|
package com.hartwig.hmftools.teal.telbam
import com.hartwig.hmftools.common.genome.chromosome.ContigComparator
import com.hartwig.hmftools.common.genome.region.GenomeRegion
import com.hartwig.hmftools.teal.ReadGroup
import htsjdk.samtools.SAMRecord
import htsjdk.samtools.SamReaderFactory
import org.apache.logging.log4j.LogManager
// read the telbam file and gives the read groups
class TelbamReader(
telbamFile: java.io.File,
excludedRegions: List<GenomeRegion> = emptyList(),
includedRegions: List<GenomeRegion>? = null)
{
private val mLogger = LogManager.getLogger(TelbamReader::class.java)
private val mTelbamFile = telbamFile
private val mExcludedGenomeRegions = excludedRegions
private val mIncludedGenomeRegions = includedRegions
// the distance which we deem the same breakpoint
private val mReadGroups: MutableMap<String, ReadGroup> = HashMap()
val readGroups: Map<String, ReadGroup> get() { return mReadGroups }
// create into read groups
fun read()
{
mLogger.info("processing telbam: {}", mTelbamFile)
val factory = SamReaderFactory.makeDefault()
val samReader = factory.open(mTelbamFile)
samReader.iterator().use({ iterator ->
while (iterator.hasNext())
{
val record = iterator.next()
processReadRecord(record)
}
})
}
private fun processReadRecord(record: SAMRecord)
{
var readGroup: ReadGroup? = mReadGroups[record.readName]
if (readGroup == null)
{
// cache if new
readGroup = ReadGroup(record.readName)
mReadGroups[record.readName] = readGroup
}
readGroup.acceptRead(record)
if (readGroup.isComplete())
{
// now we see if all the reads are in the excluded region, if so just remove it
if (shouldExcludeReadGroup(readGroup))
{
mReadGroups.remove(readGroup.name)
}
}
assert(readGroup.invariant())
}
fun shouldExcludeReadGroup(readGroup: ReadGroup): Boolean
{
if (mIncludedGenomeRegions != null)
{
// if none is included then we exclude read group
return readGroup.allReads.none({ r ->
var isIncluded = false
// check if this read should be included
for (includedRegion in mIncludedGenomeRegions)
{
if (r.alignmentStart <= includedRegion.end() &&
r.alignmentEnd >= includedRegion.start() &&
ContigComparator.INSTANCE.compare(r.referenceName, includedRegion.chromosome()) == 0)
{
isIncluded = true
break
}
}
// if not explicitly included then it is excluded
isIncluded
})
}
else
{
// if all reads are excluded then we exclude read group
return readGroup.allReads.all({ r ->
var isExcluded = false
for (excludedRegion in mExcludedGenomeRegions)
{
if (r.alignmentStart <= excludedRegion.end() &&
r.alignmentEnd >= excludedRegion.start() &&
ContigComparator.INSTANCE.compare(r.referenceName, excludedRegion.chromosome()) == 0
)
{
isExcluded = true
break
}
}
isExcluded
})
}
}
}
|
gpl-3.0
|
c5741e5b777647531bdaacf950aaf3bf
| 33.90566 | 109 | 0.567568 | 5.203938 | false | false | false | false |
light-and-salt/kotloid
|
src/main/kotlin/kr/or/lightsalt/kotloid/webkit/BaseWebViewClient.kt
|
1
|
2012
|
@file:Suppress("DEPRECATION", "OverridingDeprecatedMember")
package kr.or.lightsalt.kotloid.webkit
import android.content.Intent
import android.net.Uri
import android.net.UrlQuerySanitizer
import android.os.Build
import android.provider.Browser
import android.webkit.*
import kr.or.lightsalt.kotloid.installPackage
import kr.or.lightsalt.kotloid.startActivity
open class BaseWebViewClient : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean = try {
val context = view.context
val uri = Uri.parse(url)
when (uri.scheme) {
"file" -> false
"http", "https" -> {
if (url.startsWith(
"https://m.facebook.com/v2.0/dialog/oauth?redirect")) {
view.loadUrl(UrlQuerySanitizer(url).getValue("redirect"))
true
}else false
}
"intent" -> context.run {
val intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
if(uri.host == "scan"){
startActivity(intent)
return@run true
}
val pkg = intent.`package`!!
if (packageManager.getLaunchIntentForPackage(pkg) != null) {
startActivity(intent)
} else {
installPackage(pkg, intent.getStringExtra("referrer") ?: "")
}
true
}
"mailto", "sms" -> {
context.startActivity(Intent.ACTION_SENDTO, url)
true
}
"market" -> {
Intent.parseUri(url, Intent.URI_INTENT_SCHEME).apply {
context.startActivity(this)
}
true
}
"tel" -> {
context.startActivity(Intent.ACTION_DIAL, url)
true
}
else -> {
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.addCategory(Intent.CATEGORY_BROWSABLE)
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.packageName)
context.startActivity(intent)
true
}
}
} catch (e: Exception) {
e.printStackTrace()
false
}
override fun onPageFinished(view: WebView, url: String) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.getInstance().sync()
} else {
CookieManager.getInstance().flush()
}
}
}
|
apache-2.0
|
be8e7380391c8d6068799a38b895327c
| 25.486842 | 83 | 0.682406 | 3.421769 | false | false | false | false |
sandjelkovic/dispatchd
|
content-service/src/main/kotlin/com/sandjelkovic/dispatchd/content/trakt/dto/SeasonTrakt.kt
|
1
|
542
|
package com.sandjelkovic.dispatchd.content.trakt.dto
import com.fasterxml.jackson.annotation.JsonProperty
import java.time.ZonedDateTime
/**
* @author sandjelkovic
* @date 28.1.18.
*/
data class SeasonTrakt(
val number: String? = null,
val ids: Map<String, String> = mapOf(),
val overview: String? = null,
@JsonProperty("first_aired")
val firstAired: ZonedDateTime? = null,
@JsonProperty("episode_count")
val episodeCount: Int? = null,
@JsonProperty("aired_episodes")
val airedEpisodes: Int? = null
)
|
apache-2.0
|
2cb5123455942331fa9938a0d9a5ddd4
| 26.1 | 52 | 0.699262 | 3.816901 | false | false | false | false |
jereksel/LibreSubstratum
|
app/src/main/kotlin/com/jereksel/libresubstratum/activities/detailed/DetailedReducer.kt
|
1
|
13208
|
package com.jereksel.libresubstratum.activities.detailed
import arrow.optics.PLens
import arrow.optics.POptional
import arrow.optics.PTraversal
import arrow.optics.modify
import com.jereksel.libresubstratum.extensions.getLogger
import io.reactivex.functions.BiFunction
object DetailedReducer: BiFunction<DetailedViewState, DetailedResult, Pair<DetailedViewState, List<DetailedAction>>> {
val log = getLogger()
override fun apply(t1: DetailedViewState, t2: DetailedResult): Pair<DetailedViewState, List<DetailedAction>> {
// return t1 to emptyList()
return when(t2) {
is DetailedResult.ListLoaded -> {
t1.copy(
// themeAppId = t2.themeAppId,
themePack = DetailedViewState.ThemePack(
appId = t2.themeAppId,
themeName = t2.themeName,
themes = t2.themes.map {
DetailedViewState.Theme(
it.appId,
it.name,
"",
it.type1a?.let { DetailedViewState.Type1(it.data, 0) },
it.type1b?.let { DetailedViewState.Type1(it.data, 0) },
it.type1c?.let { DetailedViewState.Type1(it.data, 0) },
it.type2?.let { DetailedViewState.Type2(it.data, 0) },
null,
DetailedViewState.CompilationState.DEFAULT,
DetailedViewState.EnabledState.UNKNOWN,
DetailedViewState.InstalledState.Unknown,
checked = false
)
},
type3 = t2.type3?.let { DetailedViewState.Type3(it.data, 0) }
)
) to emptyList()
}
is DetailedResult.ChangeSpinnerSelection -> {
val errorOptional = detailedViewStateThemePackOptional() +
themePackThemes() +
listElementOptional(t2.listPosition) +
themeCompilationError()
val state = when(t2) {
is DetailedResult.ChangeSpinnerSelection.ChangeType1aSpinnerSelection -> {
val optional = detailedViewStateThemePackOptional() +
themePackThemes() +
listElementOptional(t2.listPosition) +
themeType1aOptional() +
type1Position()
optional.modify(t1, { t2.position })
}
is DetailedResult.ChangeSpinnerSelection.ChangeType1bSpinnerSelection -> {
val optional = detailedViewStateThemePackOptional() +
themePackThemes() +
listElementOptional(t2.listPosition) +
themeType1bOptional() +
type1Position()
optional.modify(t1, { t2.position })
}
is DetailedResult.ChangeSpinnerSelection.ChangeType1cSpinnerSelection -> {
val optional = detailedViewStateThemePackOptional() +
themePackThemes() +
listElementOptional(t2.listPosition) +
themeType1cOptional() +
type1Position()
optional.modify(t1, { t2.position })
}
is DetailedResult.ChangeSpinnerSelection.ChangeType2SpinnerSelection -> {
val optional = detailedViewStateThemePackOptional() +
themePackThemes() +
listElementOptional(t2.listPosition) +
themeType2Optional() +
type2Position()
optional.modify(t1, { t2.position })
}
}.modify(errorOptional, { null })
state to listOf(DetailedAction.GetInfoBasicAction(t2.listPosition))
}
is DetailedResult.InstalledStateResult.Result -> {
val targetApp = t2.targetApp
val themePack = t1.themePack
val position = themePack?.themes?.indexOfFirst { it.appId == targetApp } ?: -1
val option = detailedViewStateThemePackOptional() +
themePackThemes() +
listElementOptional(position)
t1.modify(option, {
it.copy(
installedState = t2.installedResult,
enabledState = t2.enabledState,
overlayId = t2.targetOverlayId
)
}) to emptyList()
}
is DetailedResult.ChangeType3SpinnerSelection -> {
val position = t2.position
val optional = detailedViewStateThemePackOptional() +
themePackType3Optional() +
type3Position()
if (optional.getOption(t1).orNull() == position) {
//Another spinner f**kup
t1 to emptyList()
} else {
val errorsOptional = detailedViewStateThemePackOptional() +
themePackThemes()
val a = t1
.modify(errorsOptional, { it.map { it.copy(compilationError = null) } })
.modify(optional, { position })
val b = (t1.themePack?.themes
?: listOf()).indices.map { DetailedAction.GetInfoBasicAction(it) }
a to b
}
}
is DetailedResult.ToggleCheckbox -> {
val optional = detailedViewStateThemePackOptional() +
themePackThemes() +
listElementOptional(t2.position) +
themeChecked()
optional.modify(t1, { t2.state }) to emptyList()
}
is DetailedResult.InstalledStateResult.PositionResult -> {
val theme = t1.themePack?.themes?.get(t2.position) ?: return t1 to emptyList()
val action = DetailedAction.GetInfoAction(
appId = t1.themePack.appId,
targetAppId = theme.appId,
type1a = theme.type1a?.get(),
type1b = theme.type1b?.get(),
type1c = theme.type1c?.get(),
type2 = theme.type2?.get(),
type3 = t1.themePack.type3?.get()
)
return t1 to listOf(action)
}
is DetailedResult.InstalledStateResult.AppIdResult -> {
val themeLocation = t1.themePack?.themes?.indexOfFirst { it.appId == t2.appId } ?: -1
if (themeLocation == -1) {
log.error("Cannot find app: {}", t2.appId)
t1 to emptyList()
} else {
t1 to listOf(DetailedAction.GetInfoBasicAction(themeLocation))
}
}
is DetailedResult.LongClickBasicResult -> {
val theme = t1.themePack?.themes?.get(t2.position) ?: return t1 to emptyList()
val action = DetailedAction.CompilationAction(
appId = t1.themePack.appId,
targetAppId = theme.appId,
type1a = theme.type1a?.get(),
type1b = theme.type1b?.get(),
type1c = theme.type1c?.get(),
type2 = theme.type2?.get(),
type3 = t1.themePack.type3?.get(),
compileMode = t2.compileMode
)
return t1 to listOf(action)
}
is DetailedResult.CompilationStatusResult -> {
val appId = t2.appId
val themeLocation = t1.themePack?.themes?.indexOfFirst { it.appId == appId } ?: -1
val compilationStateOptional = detailedViewStateThemePackOptional() +
themePackThemes() +
listElementOptional(themeLocation) +
themeCompilationState()
val compilationErrorOptional = detailedViewStateThemePackOptional() +
themePackThemes() +
listElementOptional(themeLocation) +
themeCompilationError()
val allCompilationsOptional = detailedViewStateNumberOfAllCompilations()
val finishedCompilationsOptional = detailedViewStateNumberOfFinishedCompilations()
when(t2) {
is DetailedResult.CompilationStatusResult.StartFlow -> {
t1
.modify(allCompilationsOptional, {it + 1})
}
is DetailedResult.CompilationStatusResult.StartCompilation -> {
t1
.modify(compilationStateOptional, {DetailedViewState.CompilationState.COMPILING})
}
is DetailedResult.CompilationStatusResult.StartInstallation -> {
t1
.modify(compilationStateOptional, {DetailedViewState.CompilationState.INSTALLING})
}
is DetailedResult.CompilationStatusResult.FailedCompilation -> {
t1
.modify(compilationErrorOptional, { t2.error })
.copy(toast = oneTimeFunction("Compilation failed for ${t2.appId}"))
}
is DetailedResult.CompilationStatusResult.CleanError -> {
t1
.copy(compilationError = null)
}
is DetailedResult.CompilationStatusResult.EndFlow -> {
val t = t1
.modify(compilationStateOptional, {DetailedViewState.CompilationState.DEFAULT})
.modify(finishedCompilationsOptional, {it + 1})
if (t.numberOfAllCompilations == t.numberOfFinishedCompilations) {
t.copy(numberOfAllCompilations = 0, numberOfFinishedCompilations = 0)
} else {
t
}
}
} to emptyList()
}
is DetailedResult.CompileSelectedResult -> {
val themeOptions = detailedViewStateThemePackOptional() + themePackThemes()
t1.modify(themeOptions, {it.map { it.copy(checked = false) }}) to
(t1.themePack?.themes ?: listOf()).mapIndexedNotNull { index: Int, theme: DetailedViewState.Theme ->
if (theme.checked) {
DetailedAction.CompilationLocationAction(index, t2.compileMode)
} else {
null
}
}
}
is DetailedResult.SelectAllResult -> {
val themesOptional = detailedViewStateThemePackOptional() + themePackThemes()
themesOptional.modify(t1, {it.map { it.copy(checked = true) }}) to emptyList()
}
is DetailedResult.DeselectAllResult -> {
val themesOptional = detailedViewStateThemePackOptional() + themePackThemes()
themesOptional.modify(t1, {it.map { it.copy(checked = false) }}) to emptyList()
}
is DetailedResult.ShowErrorResult -> {
t1.copy(toast = oneTimeFunction(t2.message)) to emptyList()
}
}
}
private inline fun <S, T, A, B> S.modify(optional: POptional<S, T, A, B>, crossinline f: (A) -> B) = optional.modify(this, f)
private inline fun <S, T, A, B> S.modify(optional: PLens<S, T, A, B>, crossinline f: (A) -> B) = optional.modify(this, f)
private inline fun <S, T, A, B> S.modify(optional: PTraversal<S, T, A, B>, crossinline f: (A) -> B) = optional.modify(this, f)
fun <T> oneTimeFunction(a: T): () -> T? {
var invoked = false
return {
if (invoked) {
null
} else {
invoked = true
a
}
}
}
}
|
mit
|
a7c68d626ecd6cbaae922ac30d0d66f4
| 41.336538 | 130 | 0.475091 | 6.131848 | false | false | false | false |
rcgroot/open-gpstracker-ng
|
studio/wear-shared/src/main/java/nl/sogeti/android/gpstracker/v2/sharedwear/datasync/DataSender.kt
|
1
|
2065
|
package nl.sogeti.android.gpstracker.v2.sharedwear.datasync
import android.content.Context
import com.google.android.gms.wearable.*
import nl.sogeti.android.gpstracker.v2.sharedwear.model.StatisticsMessage
import nl.sogeti.android.gpstracker.v2.sharedwear.model.StatusMessage
import nl.sogeti.android.gpstracker.v2.sharedwear.model.WearMessage
class DataSender(
private val context: Context) :
DataClient.OnDataChangedListener {
private var updateListener: DataUpdateListener? = null
fun updateMessage(message: WearMessage, urgent: Boolean = false) {
val putDataMapReq = PutDataMapRequest.create(message.path)
putDataMapReq.dataMap.putAll(message.toDataMap())
if (urgent) {
putDataMapReq.setUrgent()
}
val putDataReq = putDataMapReq.asPutDataRequest()
Wearable.getDataClient(context).putDataItem(putDataReq)
}
fun start(updateListener: DataUpdateListener) {
this.updateListener = updateListener
startDataListener()
}
fun stop() {
stopDataListener()
}
override fun onDataChanged(dataEvents: DataEventBuffer) {
dataEvents.forEach {
when (it.dataItem.uri.path) {
StatusMessage.PATH_STATUS -> {
val status = StatusMessage(DataMapItem.fromDataItem(it.dataItem).dataMap)
updateListener?.onStatusUpdate(status)
}
StatisticsMessage.PATH_STATISTICS -> {
val status = StatisticsMessage(DataMapItem.fromDataItem(it.dataItem).dataMap)
updateListener?.onStatisticsUpdate(status)
}
}
}
}
private fun startDataListener() {
Wearable.getDataClient(context).addListener(this)
}
private fun stopDataListener() {
Wearable.getDataClient(context).removeListener(this)
}
interface DataUpdateListener {
fun onStatusUpdate(status: StatusMessage)
fun onStatisticsUpdate(status: StatisticsMessage)
}
}
|
gpl-3.0
|
931cc8bb74f3867f0e41cb0d4eea687f
| 30.769231 | 97 | 0.668281 | 4.714612 | false | false | false | false |
DankBots/Mega-Gnar
|
src/main/kotlin/com/jagrosh/jdautilities/menu/PaginatorBuilder.kt
|
1
|
1305
|
package com.jagrosh.jdautilities.menu
import com.google.common.collect.Lists
import com.jagrosh.jdautilities.waiter.EventWaiter
class PaginatorBuilder(waiter: EventWaiter) : MenuBuilder<PaginatorBuilder>(waiter) {
private val items: MutableList<String> = mutableListOf()
private var emptyMessage: String? = null
private var itemsPerPage = 10
inline fun entry(lazy: () -> String): PaginatorBuilder {
return addEntry(lazy())
}
fun addEntry(item: String): PaginatorBuilder {
this.items.add(item)
return this
}
inline fun empty(lazy: () -> String): PaginatorBuilder {
return setEmptyMessage(lazy())
}
fun setEmptyMessage(emptyMessage: String?): PaginatorBuilder {
this.emptyMessage = emptyMessage
return this
}
fun addAll(items: Collection<String>): PaginatorBuilder {
this.items.addAll(items)
return this
}
fun setItemsPerPage(itemsPerPage: Int): PaginatorBuilder {
this.itemsPerPage = itemsPerPage
return this
}
override fun build(): Paginator {
return Paginator(waiter, user, title, description, color, fields, emptyMessage,
if (items.isEmpty()) emptyList() else Lists.partition(items, itemsPerPage), timeout, unit, finally)
}
}
|
mit
|
dc8347d81b7d7bbf13d60dd4b3fceae5
| 28.681818 | 111 | 0.679693 | 4.78022 | false | false | false | false |
soywiz/korge
|
korge/src/commonMain/kotlin/com/soywiz/korge/component/docking/SortedChildrenByComponent.kt
|
1
|
2588
|
package com.soywiz.korge.component.docking
import com.soywiz.klock.TimeSpan
import com.soywiz.korge.component.*
import com.soywiz.korge.view.*
class SortedChildrenByComponent(override val view: Container, var comparator: Comparator<View>) : UpdateComponent {
override fun update(dt: TimeSpan) {
view.sortChildrenBy(comparator)
}
}
fun <T, T2 : Comparable<T2>> ((T) -> T2).toComparator() = Comparator { a: T, b: T -> this(a).compareTo(this(b)) }
fun <T2 : Comparable<T2>> Container.sortChildrenBy(selector: (View) -> T2) = sortChildrenBy(selector.toComparator())
fun Container.sortChildrenByY() = sortChildrenBy(View::y)
// @TODO: kotlin-native: kotlin.Comparator { }
// korge/korge/common/src/com/soywiz/korge/component/docking/SortedChildrenByComponent.kt:25:127: error: unresolved reference: Comparator
// @TODO: kotlin-native: recursive problem!
//korge/korge/common/src/com/soywiz/korge/component/docking/SortedChildrenByComponent.kt:18:140: error: cannot infer a type for this parameter. Please specify it explicitly.
// fun <T : Container, T2 : Comparable<T2>> T.keepChildrenSortedBy(selector: (View) -> T2): T = this.keepChildrenSortedBy(kotlin.Comparator { a, b -> selector(a).compareTo(selector(b)) })
//fun <T : Container> T.keepChildrenSortedBy(comparator: Comparator<View>) = this.apply { SortedChildrenByComponent(this, comparator).attach() }
//fun <T : Container, T2 : Comparable<T2>> T.keepChildrenSortedBy(selector: (View) -> T2) = this.keepChildrenSortedBy(kotlin.Comparator { a, b -> selector(a).compareTo(selector(b)) })
//fun <T : Container> T.keepChildrenSortedBy(comparator: Comparator<View>): T = this.apply { SortedChildrenByComponent(this, comparator).attach() }
//fun <T : Container, T2 : Comparable<T2>> T.keepChildrenSortedBy(selector: (View) -> T2): T = this.keepChildrenSortedBy(kotlin.Comparator { a, b -> selector(a).compareTo(selector(b)) })
//fun <T : Container> T.keepChildrenSortedByY(): T = this.keepChildrenSortedBy(View::y)
//fun <T : Container, T2 : Comparable<T2>> T.keepChildrenSortedBy(selector: (View) -> T2): T = this.keepChildrenSortedBy(kotlin.Comparator { a: View, b: View -> selector(a).compareTo(selector(b)) })
fun <T : Container> T.keepChildrenSortedBy(comparator: Comparator<View>): T {
SortedChildrenByComponent(this, comparator).attach()
return this
}
fun <T : Container, T2 : Comparable<T2>> T.keepChildrenSortedBy(selector: (View) -> T2): T =
this.keepChildrenSortedBy(selector.toComparator())
fun <T : Container> T.keepChildrenSortedByY(): T = this.keepChildrenSortedBy(View::y)
|
apache-2.0
|
90168ca4dc3457b0d787b3c7ac31b74f
| 65.358974 | 198 | 0.73493 | 3.691869 | false | false | false | false |
bozaro/git-as-svn
|
src/main/kotlin/svnserver/repository/locks/TreeMapLockDepthVisitor.kt
|
1
|
2940
|
/*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.locks
import svnserver.StringHelper
import svnserver.repository.DepthVisitor
import java.util.*
/**
* Depth visitor for lock iteration.
* *
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class TreeMapLockDepthVisitor internal constructor(private val locks: SortedMap<String, LockDesc>, private val pathKey: String) : DepthVisitor<Iterator<LockDesc>> {
override fun visitEmpty(): Iterator<LockDesc> {
val desc: LockDesc? = locks[pathKey]
return if (desc == null) Collections.emptyIterator() else arrayOf(desc).iterator()
}
override fun visitFiles(): Iterator<LockDesc> {
return object : LockDescIterator(locks, pathKey) {
override fun filter(item: Map.Entry<String, LockDesc>): Boolean {
return pathKey == item.key || pathKey == StringHelper.parentDir(item.key)
}
}
}
override fun visitImmediates(): Iterator<LockDesc> {
return visitFiles()
}
override fun visitInfinity(): Iterator<LockDesc> {
return object : LockDescIterator(locks, pathKey) {
override fun filter(item: Map.Entry<String, LockDesc>): Boolean {
return true
}
}
}
override fun visitUnknown(): Iterator<LockDesc> {
return Collections.emptyIterator()
}
private abstract class LockDescIterator(locks: SortedMap<String, LockDesc>, pathKey: String) : Iterator<LockDesc> {
private val iterator: Iterator<Map.Entry<String, LockDesc>>
private val pathKey: String
private var nextItem: LockDesc?
private fun findNext(): LockDesc? {
while (iterator.hasNext()) {
val item: Map.Entry<String, LockDesc> = iterator.next()
if (StringHelper.isParentPath(pathKey, item.key)) {
if (filter(item)) {
return item.value
}
}
}
return null
}
protected abstract fun filter(item: Map.Entry<String, LockDesc>): Boolean
override fun hasNext(): Boolean {
return nextItem != null
}
override fun next(): LockDesc {
val result: LockDesc? = nextItem
if (result != null) {
nextItem = findNext()
}
return result!!
}
init {
iterator = locks.tailMap(pathKey).entries.iterator()
this.pathKey = pathKey
nextItem = findNext()
}
}
}
|
gpl-2.0
|
f91712f6bfa939bf19372f4e56da45d9
| 33.588235 | 164 | 0.610544 | 4.741935 | false | false | false | false |
vondear/RxTools
|
RxKit/src/main/java/com/tamsiree/rxkit/RxPictureTool.kt
|
1
|
7811
|
package com.tamsiree.rxkit
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import com.tamsiree.rxkit.RxDataTool.Companion.isNullString
import com.tamsiree.rxkit.RxImageTool.save
import java.io.File
import java.io.IOException
/**
*
* @author tamsiree
* @date 2016/1/24
* 相机相关工具类
*/
object RxPictureTool {
/**
* 获取打开照程序界面的Intent
*/
val openCameraIntent: Intent get() = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
/**
* 获取跳转至相册选择界面的Intent
*/
val imagePickerIntent: Intent
get() {
val intent = Intent(Intent.ACTION_PICK, null)
return intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
}
/**
* 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent
*/
@JvmStatic
fun getImagePickerIntent(outputX: Int, outputY: Int, fromFileURI: Uri?,
saveFileURI: Uri?): Intent {
return getImagePickerIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI)
}
/**
* 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent
*/
@JvmStatic
fun getImagePickerIntent(aspectX: Int, aspectY: Int, outputX: Int, outputY: Int, fromFileURI: Uri?,
saveFileURI: Uri?): Intent {
return getImagePickerIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI)
}
/**
* 获取[跳转至相册选择界面,并跳转至裁剪界面,可以指定是否缩放裁剪区域]的Intent
*
* @param aspectX 裁剪框尺寸比例X
* @param aspectY 裁剪框尺寸比例Y
* @param outputX 输出尺寸宽度
* @param outputY 输出尺寸高度
* @param canScale 是否可缩放
* @param fromFileURI 文件来源路径URI
* @param saveFileURI 输出文件路径URI
*/
@JvmStatic
fun getImagePickerIntent(aspectX: Int, aspectY: Int, outputX: Int, outputY: Int, canScale: Boolean,
fromFileURI: Uri?, saveFileURI: Uri?): Intent {
val intent = Intent(Intent.ACTION_PICK)
intent.setDataAndType(fromFileURI, "image/*")
intent.putExtra("crop", "true")
intent.putExtra("aspectX", if (aspectX <= 0) 1 else aspectX)
intent.putExtra("aspectY", if (aspectY <= 0) 1 else aspectY)
intent.putExtra("outputX", outputX)
intent.putExtra("outputY", outputY)
intent.putExtra("scale", canScale)
// 图片剪裁不足黑边解决
intent.putExtra("scaleUpIfNeeded", true)
intent.putExtra("return-data", false)
intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI)
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
// 去除人脸识别
return intent.putExtra("noFaceDetection", true)
}
/**
* 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent
*/
@JvmStatic
fun getCameraIntent(saveFileURI: Uri?): Intent {
val mIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
return mIntent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI)
}
/**
* 获取[跳转至裁剪界面,默认可缩放]的Intent
*/
@JvmStatic
fun getCropImageIntent(outputX: Int, outputY: Int, fromFileURI: Uri?,
saveFileURI: Uri?): Intent {
return getCropImageIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI)
}
/**
* 获取[跳转至裁剪界面,默认可缩放]的Intent
*/
@JvmStatic
fun getCropImageIntent(aspectX: Int, aspectY: Int, outputX: Int, outputY: Int, fromFileURI: Uri?,
saveFileURI: Uri?): Intent {
return getCropImageIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI)
}
/**
* 获取[跳转至裁剪界面]的Intent
*/
@JvmStatic
fun getCropImageIntent(aspectX: Int, aspectY: Int, outputX: Int, outputY: Int, canScale: Boolean,
fromFileURI: Uri?, saveFileURI: Uri?): Intent {
val intent = Intent("com.android.camera.action.CROP")
intent.setDataAndType(fromFileURI, "image/*")
intent.putExtra("crop", "true")
// X方向上的比例
intent.putExtra("aspectX", if (aspectX <= 0) 1 else aspectX)
// Y方向上的比例
intent.putExtra("aspectY", if (aspectY <= 0) 1 else aspectY)
intent.putExtra("outputX", outputX)
intent.putExtra("outputY", outputY)
intent.putExtra("scale", canScale)
// 图片剪裁不足黑边解决
intent.putExtra("scaleUpIfNeeded", true)
intent.putExtra("return-data", false)
// 需要将读取的文件路径和裁剪写入的路径区分,否则会造成文件0byte
intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI)
// true-->返回数据类型可以设置为Bitmap,但是不能传输太大,截大图用URI,小图用Bitmap或者全部使用URI
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
// 取消人脸识别功能
intent.putExtra("noFaceDetection", true)
return intent
}
/**
* 获得选中相册的图片
*
* @param context 上下文
* @param data onActivityResult返回的Intent
* @return bitmap
*/
@JvmStatic
fun getChoosedImage(context: Activity, data: Intent?): Bitmap? {
if (data == null) return null
var bm: Bitmap? = null
val cr = context.contentResolver
val originalUri = data.data
try {
bm = MediaStore.Images.Media.getBitmap(cr, originalUri)
} catch (e: IOException) {
e.printStackTrace()
}
return bm
}
/**
* 获得选中相册的图片路径
*
* @param context 上下文
* @param data onActivityResult返回的Intent
* @return
*/
@JvmStatic
fun getChoosedImagePath(context: Activity, data: Intent?): String? {
if (data == null) return null
var path = ""
val resolver = context.contentResolver
val originalUri = data.data ?: return null
val projection = arrayOf(MediaStore.Images.Media.DATA)
val cursor = resolver.query(originalUri, projection, null, null, null)
if (null != cursor) {
try {
val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
path = cursor.getString(column_index)
} catch (e: IllegalArgumentException) {
e.printStackTrace()
} finally {
try {
if (!cursor.isClosed) {
cursor.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
return if (isNullString(path)) originalUri.path else null
}
/**
* 获取拍照之后的照片文件(JPG格式)
*
* @param data onActivityResult回调返回的数据
* @param filePath 文件路径
* @return 文件
*/
@JvmStatic
fun getTakePictureFile(data: Intent?, filePath: String?): File? {
if (data == null) return null
val extras = data.extras ?: return null
val photo = extras.getParcelable<Bitmap>("data")
val file = File(filePath)
return if (save(photo!!, file, Bitmap.CompressFormat.JPEG)) file else null
}
}
|
apache-2.0
|
abfb91689f06c2a39957859943a04339
| 32.511962 | 103 | 0.605455 | 4.314849 | false | false | false | false |
ethauvin/TESRemoteProgrammer
|
app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/StepsActivity.kt
|
1
|
1884
|
/*
* StepsActivity.kt
*
* Copyright 2016-2019 Erik C. Thauvin ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.thauvin.erik.android.tesremoteprogrammer
import android.app.Fragment
import android.app.FragmentManager
import android.os.Bundle
import androidx.legacy.app.FragmentStatePagerAdapter
import androidx.fragment.app.FragmentActivity
import kotlinx.android.synthetic.main.activity_steps.indicator
import kotlinx.android.synthetic.main.activity_steps.pager
import java.util.ArrayList
class StepsActivity : FragmentActivity() {
companion object {
const val EXTRA_STEPS = "steps"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_steps)
val steps = intent?.extras?.getStringArrayList(EXTRA_STEPS) ?: arrayListOf()
pager.adapter = StepsAdapter(fragmentManager, steps)
indicator.setViewPager(pager, pager.currentItem - 1)
indicator.fades = false
}
private inner class StepsAdapter(
fm: FragmentManager,
steps: ArrayList<String>
) : FragmentStatePagerAdapter(fm) {
private val steps = ArrayList(steps)
override fun getItem(position: Int): Fragment = StepsFragment.create(position, steps)
override fun getCount(): Int = steps.size
}
}
|
apache-2.0
|
02ba397a9025d5c76eaa22f6aa880dcc
| 33.888889 | 93 | 0.733546 | 4.443396 | false | false | false | false |
andimage/PCBridge
|
src/main/kotlin/com/projectcitybuild/core/infrastructure/network/clients/MojangClient.kt
|
1
|
1134
|
package com.projectcitybuild.core.infrastructure.network.clients
import com.projectcitybuild.entities.requests.mojang.MojangAPIRequest
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MojangClient(private val withLogging: Boolean) {
private val instance: Retrofit = build()
private val client: OkHttpClient
get() {
var clientBuilder = OkHttpClient().newBuilder()
if (withLogging) {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
clientBuilder = clientBuilder.addInterceptor(loggingInterceptor)
}
return clientBuilder.build()
}
val mojangApi = instance.create(MojangAPIRequest::class.java)
private fun build(): Retrofit {
return Retrofit.Builder()
.client(client)
.baseUrl("https://api.mojang.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
|
mit
|
1431fcda2702bc822ec59a98bc0f9487
| 31.4 | 80 | 0.685185 | 5.349057 | false | false | false | false |
vimeo/vimeo-networking-java
|
models/src/main/java/com/vimeo/networking2/StreamPrivacy.kt
|
1
|
1139
|
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.enums.EmbedPrivacyType
import com.vimeo.networking2.enums.ViewPrivacyType
import com.vimeo.networking2.enums.asEnum
/**
* Stream privacy data.
*
* @param embedPrivacy The event's embed permission setting.
* @param unlistedHash The hash for unlisted recurring live events.
* @param viewPrivacy The general privacy setting for generated videos and the embed privacy of the entire collection.
*/
@JsonClass(generateAdapter = true)
data class StreamPrivacy(
@Json(name = "embed")
val embedPrivacy: String? = null,
@Json(name = "unlisted_hash")
val unlistedHash: String? = null,
@Json(name = "view")
val viewPrivacy: String? = null,
)
/**
* @see StreamPrivacy.embedPrivacy
* @see EmbedPrivacyType
*/
val StreamPrivacy.embedPrivacyType: EmbedPrivacyType
get() = embedPrivacy.asEnum(EmbedPrivacyType.UNKNOWN)
/**
* @see Privacy.viewPrivacy
* @see ViewPrivacyType
*/
val StreamPrivacy.viewPrivacyType: ViewPrivacyType
get() = viewPrivacy.asEnum(ViewPrivacyType.UNKNOWN)
|
mit
|
2488c8ec661f7aed62fed13d3d690931
| 26.780488 | 118 | 0.755926 | 3.887372 | false | false | false | false |
ANPez/TextImageView
|
textimageview/src/main/java/com/antonionicolaspina/textimageview/TextImageView.kt
|
1
|
11821
|
package com.antonionicolaspina.textimageview
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.animation.LinearInterpolator
import androidx.annotation.ColorInt
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.content.ContextCompat
import androidx.core.graphics.contains
import androidx.core.graphics.toPoint
import androidx.core.graphics.toRectF
import androidx.core.graphics.withMatrix
import com.mapbox.android.gestures.*
import kotlin.math.*
class TextImageView
@JvmOverloads constructor(
context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0
): AppCompatImageView(context, attributeSet, defStyleAttr) {
interface Listener {
fun textsChanged(texts: List<Text>)
fun textTapped(text: Text)
}
var panEnabled = false
var scaleEnabled = false
var rotationEnabled = false
val deleteEnabled: Boolean
var listener: Listener? = null
var initialTextSize = 0f
var minTextSize = 0f
var maxTextSize = 0f
private val texts = mutableListOf<TextProperties>()
private var selectedText: TextProperties? = null
private var deleteAreaVisible = false
private val deleteAreaHeight = context.resources.getDimensionPixelSize(R.dimen.tiv_delete_area_height)
private val deleteButtonHeight = context.resources.getDimensionPixelSize(R.dimen.tiv_delete_button_height)
private val deleteDrawable = ContextCompat.getDrawable(context, R.drawable.ic_trash)!!
private var deleteButtonScale = 1f
init {
context.theme.obtainStyledAttributes(attributeSet, R.styleable.TextImageView, 0, 0).apply {
try {
panEnabled = getBoolean(R.styleable.TextImageView_tiv_panEnabled, false)
scaleEnabled = getBoolean(R.styleable.TextImageView_tiv_scaleEnabled, false)
rotationEnabled = getBoolean(R.styleable.TextImageView_tiv_rotationEnabled, false)
deleteEnabled = getBoolean(R.styleable.TextImageView_tiv_deleteEnabled, false)
initialTextSize = getDimensionPixelSize(R.styleable.TextImageView_tiv_initialTextSize, resources.getDimensionPixelSize(
R.dimen.tiv_default_text_size
)).toFloat()
minTextSize = getDimensionPixelSize(R.styleable.TextImageView_tiv_minTextSize, resources.getDimensionPixelSize(
R.dimen.tiv_default_min_text_size
)).toFloat()
maxTextSize = getDimensionPixelSize(R.styleable.TextImageView_tiv_maxTextSize, resources.getDimensionPixelSize(R.dimen.tiv_default_max_text_size)).toFloat()
} finally {
recycle()
}
}
if (deleteEnabled) {
setPadding(
paddingLeft,
paddingTop,
paddingRight,
paddingBottom+deleteAreaHeight
)
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (isInEditMode) {
if (texts.isEmpty()) {
setText("sample text")
}
deleteAreaVisible = deleteEnabled
}
if (deleteEnabled && deleteAreaVisible) {
val w = measuredWidth
val h = measuredHeight
val buttonSize = getDeleteButtonSize()
deleteDrawable.setBounds(
(w-buttonSize)/2,
h-deleteAreaHeight+(deleteAreaHeight-buttonSize)/2,
(w+buttonSize)/2,
h-(deleteAreaHeight-buttonSize)/2
)
deleteDrawable.draw(canvas)
}
texts.forEach { tp ->
canvas.withMatrix(tp.matrix) {
canvas.drawText(tp.text, 0f, 0f, tp.paint)
}
}
}
/**
* Set text to be drawn over the image.
* @param text The text.
*/
fun setText(text: String) {
texts.clear()
addText(text)
}
/**
* Change selected text.
* @param text The text.
*/
fun changeText(text: String) {
selectedText?.let {
it.text = text
textChanged(it)
}
}
/**
* Set the typeface to use for the text.
* @param typeface The typeface to be used.
*/
fun setTypeface(typeface: Typeface?) {
selectedText?.let {
it.paint.typeface = typeface
textChanged(it)
}
}
fun setPosition(position: PointF) {
selectedText?.let {
it.position.x = position.x*measuredWidth
it.position.y = position.y*measuredHeight
textChanged(it)
}
}
fun setScaleFactor(scale: Float) {
selectedText?.let {
it.scaleFactor = scale
textChanged(it)
}
}
fun setRotationDegrees(rotation: Float) {
selectedText?.let {
it.rotationDegress = rotation
textChanged(it)
}
}
fun getSelected() = selectedText?.toText(measuredWidth, measuredHeight)
/**
* Set the text color.
* @param color Color in the format of <a href="http://developer.android.com/reference/android/graphics/Color.html">android.graphics.Color</a>.
*
* @see <a href="http://developer.android.com/reference/android/graphics/Color.html">android.graphics.Color</a>
*/
fun setTextColor(@ColorInt color: Int) {
selectedText?.let {
it.paint.color = color
textChanged(it)
}
}
/**
* Adds a text to be drawn over the image, above existing texts.
* @param text The text.
*/
fun addText(text: String) {
val tp = TextProperties(text)
tp.paint.textSize = initialTextSize
tp.paint.getTextBounds(tp.text, 0, tp.text.length, tp.boundingRect)
tp.position.x = measuredWidth/2f-tp.boundingRect.exactCenterX()
tp.position.y = measuredHeight/2f-tp.boundingRect.exactCenterY()
texts.add(tp)
selectedText = tp
textChanged(tp)
}
/**
* Adds a drop shadow
*/
fun addDropShadow(
angle: Float = 45f, distance: Float = 0.02f, @ColorInt color: Int = Color.argb(
0x80,
0,
0,
0
)
) {
selectedText?.let {
val textSize = it.paint.textSize
it.paint.setShadowLayer(
1f,
textSize * cos(angle) * distance,
textSize * sin(angle) * distance,
color
)
}
}
/**
* Returns all texts' data
*/
fun getTexts(): List<Text> {
val w = measuredWidth
val h = measuredHeight
return texts.map { it.toText(w, h) }
}
private var valueAnimator: ValueAnimator? = null
//region Gestures
private val androidGesturesManager = AndroidGesturesManager(context).apply {
setMoveGestureListener(object : MoveGestureDetector.SimpleOnMoveGestureListener() {
override fun onMove(
detector: MoveGestureDetector,
distanceX: Float,
distanceY: Float
): Boolean {
if (panEnabled) {
selectedText?.let { tp ->
tp.position.x -= distanceX
tp.position.y -= distanceY
textChanged(tp)
if (deleteEnabled && deleteAreaVisible) {
if (inDeleteArea(tp)) {
ValueAnimator.ofFloat(deleteButtonScale, 1.5f)
.setDuration(200)
.apply {
interpolator = LinearInterpolator()
addUpdateListener {
deleteButtonScale = it.animatedValue as Float
invalidate()
}
start()
valueAnimator = this
}
} else {
ValueAnimator.ofFloat(deleteButtonScale, 1f)
.setDuration(200)
.apply {
interpolator = LinearInterpolator()
addUpdateListener {
deleteButtonScale = it.animatedValue as Float
invalidate()
}
start()
valueAnimator = this
}
}
}
}
}
return true
}
override fun onMoveBegin(detector: MoveGestureDetector): Boolean {
if (deleteEnabled) {
if (null != selectedText) {
deleteButtonScale = 1f
deleteAreaVisible = true
invalidate()
}
}
return true
}
override fun onMoveEnd(detector: MoveGestureDetector, velocityX: Float, velocityY: Float) {
if (deleteEnabled && deleteAreaVisible) {
deleteAreaVisible = false
if (true == valueAnimator?.isRunning) {
valueAnimator?.cancel()
valueAnimator = null
}
deleteButtonScale = 1f
selectedText?.let {
checkDeleted(it)
}
invalidate()
}
}
})
setStandardScaleGestureListener(object :
StandardScaleGestureDetector.SimpleStandardOnScaleGestureListener() {
override fun onScale(detector: StandardScaleGestureDetector): Boolean {
if (scaleEnabled) {
selectedText?.let {
val s = it.scaleFactor * detector.scaleFactor
val textSize = s * it.paint.textSize
it.scaleFactor = max(minTextSize, min(textSize, maxTextSize)) / it.paint.textSize
textChanged(it)
}
}
return true
}
})
setRotateGestureListener(object : RotateGestureDetector.SimpleOnRotateGestureListener() {
override fun onRotate(
detector: RotateGestureDetector,
rotationDegreesSinceLast: Float,
rotationDegreesSinceFirst: Float
): Boolean {
if (rotationEnabled) {
selectedText?.let {
it.rotationDegress -= rotationDegreesSinceLast
textChanged(it)
}
}
return true
}
})
setStandardGestureListener(object : StandardGestureDetector.SimpleStandardOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
texts.forEach { tp ->
val p = tp.inverseMap(e.x, e.y)
if (tp.boundingRect.contains(p.toPoint())) {
selectedText = tp
}
}
invalidate()
return true
}
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
val listener = listener
val selectedText = selectedText
if ( (null!=selectedText) && (null != listener) ) {
val p = selectedText.inverseMap(e.x, e.y)
if (selectedText.boundingRect.contains(p.toPoint())) {
listener.textTapped(selectedText.toText(measuredWidth, measuredHeight))
}
}
return true
}
})
}
private fun getDeleteButtonSize() = (deleteButtonHeight*deleteButtonScale).roundToInt()
private fun inDeleteArea(tp: TextProperties): Boolean {
val w = measuredWidth
val h = measuredHeight
val buttonSize = getDeleteButtonSize()
val r = RectF(
(w-buttonSize)/2f,
h-deleteAreaHeight+(deleteAreaHeight-buttonSize)/2f,
(w+buttonSize)/2f,
h-(deleteAreaHeight-buttonSize)/2f
)
val boundingRect = tp.boundingRect.toRectF()
tp.matrix.mapRect(boundingRect)
return r.intersect(boundingRect)
}
private fun checkDeleted(tp: TextProperties) {
if (inDeleteArea(tp)) {
texts.remove(tp)
invalidate()
listener?.textsChanged(getTexts())
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
androidGesturesManager.onTouchEvent(event)
return true
}
//endregion
private fun textChanged(tp: TextProperties) {
invalidate()
tp.paint.getTextBounds(tp.text, 0, tp.text.length, tp.boundingRect)
with(tp.matrix) {
reset()
setScale(tp.scaleFactor, tp.scaleFactor)
preTranslate(tp.position.x / tp.scaleFactor, tp.position.y / tp.scaleFactor)
preRotate(
tp.rotationDegress,
tp.boundingRect.exactCenterX() / tp.scaleFactor,
tp.boundingRect.exactCenterY() / tp.scaleFactor
)
}
listener?.textsChanged(getTexts())
}
}
|
apache-2.0
|
d1b5f339455dd4e34f72655247089318
| 28.115764 | 164 | 0.631842 | 4.685295 | false | false | false | false |
mickele/DBFlow
|
dbflow-processor/src/test/java/com/raizlabs/android/dbflow/processor/test/ForeignKeyAccessCombinerTests.kt
|
1
|
8168
|
package com.raizlabs.android.dbflow.processor.test
import com.raizlabs.android.dbflow.processor.definition.column.*
import com.raizlabs.android.dbflow.processor.definition.column.PrimaryReferenceAccessCombiner
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.TypeName
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
/**
* Description:
*
* @author Andrew Grosner (fuzz)
*/
class ForeignKeyAccessCombinerTest {
@Test
fun test_canCombineSimpleCase() {
val foreignKeyAccessCombiner = ForeignKeyAccessCombiner(VisibleScopeColumnAccessor("name"))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("test",
ContentValuesCombiner(Combiner(VisibleScopeColumnAccessor("test"), TypeName.get(String::class.java))))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("test2",
ContentValuesCombiner(Combiner(PrivateScopeColumnAccessor("test2"), TypeName.get(Int::class.java))))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(4))
assertEquals("if (model.name != null) {" +
"\n values.put(\"test\", model.name.test);" +
"\n values.put(\"test2\", model.name.getTest2());" +
"\n} else {" +
"\n values.putNull(\"test\");" +
"\n values.putNull(\"test2\");" +
"\n}",
builder.build().toString().trim())
}
@Test
fun test_canCombineSimplePrivateCase() {
val foreignKeyAccessCombiner = ForeignKeyAccessCombiner(PrivateScopeColumnAccessor("name"))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("start",
SqliteStatementAccessCombiner(Combiner(VisibleScopeColumnAccessor("test"), TypeName.get(String::class.java))))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(4))
assertEquals("if (model.getName() != null) {" +
"\n statement.bindString(4 + start, model.getName().test);" +
"\n} else {" +
"\n statement.bindNull(4 + start);" +
"\n}",
builder.build().toString().trim())
}
@Test
fun test_canCombinePackagePrivateCase() {
val foreignKeyAccessCombiner = ForeignKeyAccessCombiner(PackagePrivateScopeColumnAccessor("name",
"com.fuzz.android", "_", "TestHelper"))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("test",
PrimaryReferenceAccessCombiner(Combiner(PackagePrivateScopeColumnAccessor("test",
"com.fuzz.android", "_", "TestHelper2"),
TypeName.get(String::class.java))))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(4))
assertEquals("if (com.fuzz.android.TestHelper_Helper.getName(model) != null) {" +
"\n clause.and(test.eq(com.fuzz.android.TestHelper2_Helper.getTest(com.fuzz.android.TestHelper_Helper.getName(model))));" +
"\n} else {" +
"\n clause.and(test.eq((com.raizlabs.android.dbflow.sql.language.IConditional) null));" +
"\n}",
builder.build().toString().trim())
}
@Test
fun test_canDoComplexCase() {
val foreignKeyAccessCombiner = ForeignKeyAccessCombiner(VisibleScopeColumnAccessor("modem"))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("number",
ContentValuesCombiner(Combiner(PackagePrivateScopeColumnAccessor("number",
"com.fuzz", "\$", "AnotherHelper"),
TypeName.INT)))
foreignKeyAccessCombiner.fieldAccesses += ForeignKeyAccessField("date",
ContentValuesCombiner(Combiner(TypeConverterScopeColumnAccessor("global_converter", "date"),
TypeName.get(Date::class.java))))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(1))
assertEquals("if (model.modem != null) {" +
"\n values.put(\"number\", com.fuzz.AnotherHelper\$Helper.getNumber(model.modem));" +
"\n values.put(\"date\", global_converter.getDBValue(model.modem.date));" +
"\n} else {" +
"\n values.putNull(\"number\");" +
"\n values.putNull(\"date\");" +
"\n}",
builder.build().toString().trim())
}
@Test
fun test_canLoadFromCursor() {
val foreignKeyAccessCombiner = ForeignKeyLoadFromCursorCombiner(VisibleScopeColumnAccessor("testModel1"),
ClassName.get("com.raizlabs.android.dbflow.test.container", "ParentModel"),
ClassName.get("com.raizlabs.android.dbflow.test.container", "ParentModel_Table"), false)
foreignKeyAccessCombiner.fieldAccesses += PartialLoadFromCursorAccessCombiner("testmodel_id",
"name", TypeName.get(String::class.java), false, null)
foreignKeyAccessCombiner.fieldAccesses += PartialLoadFromCursorAccessCombiner("testmodel_type",
"type", TypeName.get(String::class.java), false, null)
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(0))
assertEquals("int index_testmodel_id = cursor.getColumnIndex(\"testmodel_id\");" +
"\nint index_testmodel_type = cursor.getColumnIndex(\"testmodel_type\");" +
"\nif (index_testmodel_id != -1 && !cursor.isNull(index_testmodel_id) && index_testmodel_type != -1 && !cursor.isNull(index_testmodel_type)) {" +
"\n model.testModel1 = com.raizlabs.android.dbflow.sql.language.SQLite.select().from(com.raizlabs.android.dbflow.test.container.ParentModel.class).where()" +
"\n .and(com.raizlabs.android.dbflow.test.container.ParentModel_Table.name.eq(cursor.getString(index_testmodel_id)))" +
"\n .and(com.raizlabs.android.dbflow.test.container.ParentModel_Table.type.eq(cursor.getString(index_testmodel_type)))" +
"\n .querySingle();" +
"\n} else {" +
"\n model.testModel1 = null;" +
"\n}", builder.build().toString().trim())
}
@Test
fun test_canLoadFromCursorStubbed() {
val foreignKeyAccessCombiner = ForeignKeyLoadFromCursorCombiner(VisibleScopeColumnAccessor("testModel1"),
ClassName.get("com.raizlabs.android.dbflow.test.container", "ParentModel"),
ClassName.get("com.raizlabs.android.dbflow.test.container", "ParentModel_Table"), true)
foreignKeyAccessCombiner.fieldAccesses += PartialLoadFromCursorAccessCombiner("testmodel_id",
"name", TypeName.get(String::class.java), false, VisibleScopeColumnAccessor("name"))
foreignKeyAccessCombiner.fieldAccesses += PartialLoadFromCursorAccessCombiner("testmodel_type",
"type", TypeName.get(String::class.java), false, VisibleScopeColumnAccessor("type"))
val builder = CodeBlock.builder()
foreignKeyAccessCombiner.addCode(builder, AtomicInteger(0))
assertEquals("int index_testmodel_id = cursor.getColumnIndex(\"testmodel_id\");" +
"\nint index_testmodel_type = cursor.getColumnIndex(\"testmodel_type\");" +
"\nif (index_testmodel_id != -1 && !cursor.isNull(index_testmodel_id) && index_testmodel_type != -1 && !cursor.isNull(index_testmodel_type)) {" +
"\n model.testModel1 = new com.raizlabs.android.dbflow.test.container.ParentModel();" +
"\n model.testModel1.name = cursor.getString(index_testmodel_id);" +
"\n model.testModel1.type = cursor.getString(index_testmodel_type);" +
"\n} else {" +
"\n model.testModel1 = null;" +
"\n}", builder.build().toString().trim())
}
}
|
mit
|
2a7f6caefb01befe38f288e4b92f1137
| 52.743421 | 174 | 0.63761 | 4.902761 | false | true | false | false |
pyamsoft/power-manager
|
powermanager-base/src/main/java/com/pyamsoft/powermanager/base/states/WearStateObserver.kt
|
1
|
3316
|
/*
* Copyright 2017 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.powermanager.base.states
import android.content.Context
import android.support.annotation.CheckResult
import android.support.annotation.WorkerThread
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.wearable.Node
import com.google.android.gms.wearable.Wearable
import com.pyamsoft.powermanager.base.preference.WearablePreferences
import com.pyamsoft.powermanager.model.StateObserver
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
internal class WearStateObserver @Inject internal constructor(context: Context,
private val preferences: WearablePreferences) : StateObserver {
private val googleApiClient: GoogleApiClient = GoogleApiClient.Builder(
context.applicationContext).addApiIfAvailable(Wearable.API).build()
private val isWearableNodeConnected: Boolean
@WorkerThread @CheckResult get() {
val waitTime = preferences.wearableDelay
Timber.d("Wait for nodes for %d seconds", waitTime)
val nodesResult = Wearable.NodeApi.getConnectedNodes(googleApiClient).await(waitTime,
TimeUnit.SECONDS)
var wearableNode: Node? = null
val nodes = nodesResult.nodes
Timber.d("Search node list of size : %d", nodes.size)
for (node in nodes) {
if (node.isNearby) {
Timber.d("Wearable node: %s %s", node.displayName, node.id)
wearableNode = node
break
}
}
val result: Boolean
if (wearableNode == null) {
Timber.w("No wearable node was found")
result = false
} else {
Timber.d("Found a wearable node")
result = true
}
disconnectGoogleApiClient()
return result
}
/**
* Return if a wearable is connected
*/
private val isConnected: Boolean
@WorkerThread @CheckResult get() {
Timber.d("Check if wearable is connected")
val waitTime = preferences.wearableDelay
Timber.d("Wait for connection for %d seconds", waitTime)
val connectionResult = googleApiClient.blockingConnect(waitTime, TimeUnit.SECONDS)
val result: Boolean
if (connectionResult.isSuccess) {
Timber.d("Connect Google APIs")
result = isWearableNodeConnected
} else {
Timber.e("Could not connect to Google APIs")
result = false
}
return result
}
private fun disconnectGoogleApiClient() {
if (googleApiClient.isConnected) {
Timber.d("Disconnect Google Api Client")
googleApiClient.disconnect()
}
}
override fun enabled(): Boolean {
return isConnected
}
override fun unknown(): Boolean {
return !googleApiClient.isConnected
}
}
|
apache-2.0
|
9a2083333fb6852d2d0308dcbc1251d5
| 32.494949 | 91 | 0.707177 | 4.605556 | false | false | false | false |
mauriciocoelho/upcomingmovies
|
infrastructure/src/test/kotlin/com/mauscoelho/upcomingmovies/infrastructure/GenreRepositoryTest.kt
|
1
|
3756
|
package com.mauscoelho.upcomingmovies.infrastructure
import br.ufs.github.rxassertions.RxAssertions
import com.fasterxml.jackson.databind.ObjectMapper
import com.mauscoelho.upcomingmovies.infrastructure.interactor.GenreRepositoryImpl
import com.mauscoelho.upcomingmovies.infrastructure.network.TmdbNetwork
import com.mauscoelho.upcomingmovies.model.Genre
import com.mauscoelho.upcomingmovies.model.Genres
import com.snappydb.DB
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.Mockito.mock
import rx.Observable
@RunWith(JUnitPlatform::class)
class GenreRepositoryTest : Spek({
val genresCollection = "genres"
val snappyDb = mock(DB::class.java)
val mapper = mock(ObjectMapper::class.java)
val tmdbNetwork = mock(TmdbNetwork::class.java)
val genreRepository = GenreRepositoryImpl(tmdbNetwork, genresCollection , snappyDb, mapper)
val apiKey = "1f54bd990f1cdfb230adb312546d765d"
val language = "en-US"
val genreJson = "[{\"id\":28,\"name\":\"Action\"},{\"id\":12,\"name\":\"Adventure\"},{\"id\":16,\"name\":\"Animation\"},{\"id\":35,\"name\":\"Comedy\"},{\"id\":80,\"name\":\"Crime\"},{\"id\":99,\"name\":\"Documentary\"},{\"id\":18,\"name\":\"Drama\"},{\"id\":10751,\"name\":\"Family\"},{\"id\":14,\"name\":\"Fantasy\"},{\"id\":36,\"name\":\"History\"},{\"id\":27,\"name\":\"Horror\"},{\"id\":10402,\"name\":\"Music\"},{\"id\":9648,\"name\":\"Mystery\"},{\"id\":10749,\"name\":\"Romance\"},{\"id\":878,\"name\":\"Science Fiction\"},{\"id\":10770,\"name\":\"TV Movie\"},{\"id\":53,\"name\":\"Thriller\"},{\"id\":10752,\"name\":\"War\"},{\"id\":37,\"name\":\"Western\"}]"
describe("GenreRepositoryTest") {
context("Get genre") {
it("should return 1 genres from repository by id") {
val expected = listOf(Genre(1,"Horror"))
val searchIds = listOf(1)
Mockito.`when`(snappyDb.get(genresCollection)).thenReturn(genreJson)
Mockito.`when`(mapper.readValue(genreJson, Array<Genre>::class.java)).thenReturn(arrayOf(Genre(1, "Horror")))
RxAssertions.assertThat(genreRepository.getGenres(searchIds))
.completes()
.withoutErrors()
.emissionsCount(1)
.expectedSingleValue(expected)
}
it("should return 2 genres from repository by ids") {
val expected = listOf(Genre(1,"Horror"), Genre(2,"Terror"))
Mockito.`when`(snappyDb.get(genresCollection)).thenReturn(genreJson)
Mockito.`when`(mapper.readValue(genreJson, Array<Genre>::class.java)).thenReturn(arrayOf(Genre(1, "Horror"), Genre(2, "Terror")))
RxAssertions.assertThat(genreRepository.getGenres(listOf(1, 2)))
.completes()
.withoutErrors()
.emissionsCount(1)
.expectedSingleValue(expected)
}
}
context("Load genre") {
it("should load genres") {
val expected = Genres(listOf(Genre(1,"Horror")))
Mockito.`when`(tmdbNetwork.getGenres(apiKey,language)).thenReturn(Observable.just(expected))
RxAssertions.assertThat(genreRepository.loadGenres(apiKey, language))
.completes()
.withoutErrors()
.emissionsCount(1)
.expectedSingleValue(expected)
}
}
}
})
|
apache-2.0
|
1d2dd91641e2942d890156b11b53f859
| 45.95 | 672 | 0.608094 | 4.450237 | false | false | false | false |
dkrivoruchko/SwitchMovie
|
app/src/main/kotlin/info/dvkr/switchmovie/ui/fragment/MovieGridFragment.kt
|
1
|
5620
|
package info.dvkr.switchmovie.ui.fragment
import android.content.res.ColorStateList
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.navigation.findNavController
import androidx.recyclerview.widget.*
import coil.load
import com.elvishew.xlog.XLog
import info.dvkr.switchmovie.R
import info.dvkr.switchmovie.databinding.FragmentMovieGridBinding
import info.dvkr.switchmovie.databinding.ItemMovieBinding
import info.dvkr.switchmovie.domain.model.Movie
import info.dvkr.switchmovie.domain.utils.getLog
import info.dvkr.switchmovie.helpers.viewBinding
import info.dvkr.switchmovie.viewmodel.moviegrid.MovieGridViewEvent
import info.dvkr.switchmovie.viewmodel.moviegrid.MovieGridViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class MovieGridFragment : BaseFragment(R.layout.fragment_movie_grid) {
data class MovieGridViewItem(val id: Long, val posterPath: String, val isStar: Boolean) {
companion object {
fun fromMovie(movie: Movie) = MovieGridViewItem(movie.id, movie.posterPath, movie.isStar)
}
override fun toString() = "Movie(id=$id)"
}
private val viewModel by viewModel<MovieGridViewModel>()
private var movieAdapter: MovieAdapter? = null
private var error: Throwable? = null
private val binding by viewBinding { fragment -> FragmentMovieGridBinding.bind(fragment.requireView()) }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
requireActivity().title = getString(R.string.movie_grid_activity_name)
movieAdapter = MovieAdapter { movieGridViewItem ->
if (movieGridViewItem.isStar) viewModel.onEvent(MovieGridViewEvent.UnsetMovieStar(movieGridViewItem.id))
else viewModel.onEvent(MovieGridViewEvent.SetMovieStar(movieGridViewItem.id))
}
.apply { setHasStableIds(true) }
binding.rvFragmentMovieGrid.apply {
layoutManager = StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL)
itemAnimator = DefaultItemAnimator()
adapter = movieAdapter
setHasFixedSize(true)
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (canScrollVertically(1).not()) viewModel.onEvent(MovieGridViewEvent.LoadMore)
}
})
}
viewModel.getStateLiveData().observe(viewLifecycleOwner, { movieGridState ->
XLog.d(getLog("stateLiveData", movieGridState.toString()))
movieAdapter?.submitList(movieGridState.movies.map { MovieGridViewItem.fromMovie(it) })
binding.srFragmentMovieGrid.isRefreshing = movieGridState.workInProgressCounter > 0
if (error != movieGridState.error) {
error = movieGridState.error
movieGridState.error?.run {
Toast.makeText(requireActivity(), message, Toast.LENGTH_LONG).show()
}
}
})
binding.srFragmentMovieGrid.setOnRefreshListener { viewModel.onEvent(MovieGridViewEvent.Refresh) }
viewModel.onEvent(MovieGridViewEvent.Update)
}
override fun onDestroyView() {
super.onDestroyView()
movieAdapter = null
error = null
}
private class MovieAdapter(
private val onItemStartClick: (MovieGridViewItem) -> Unit
) : ListAdapter<MovieGridViewItem, MovieViewItemHolder>(
object : DiffUtil.ItemCallback<MovieGridViewItem>() {
override fun areItemsTheSame(oldItem: MovieGridViewItem, newItem: MovieGridViewItem) =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: MovieGridViewItem, newItem: MovieGridViewItem) =
oldItem == newItem
}
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = MovieViewItemHolder(
ItemMovieBinding.inflate(LayoutInflater.from(parent.context), parent, false),
onItemStartClick
)
override fun onBindViewHolder(holder: MovieViewItemHolder, position: Int) = holder.bind(getItem(position))
override fun getItemId(position: Int): Long = getItem(position).id
}
private class MovieViewItemHolder(
private val binding: ItemMovieBinding,
private val onItemStartClick: (MovieGridViewItem) -> Unit
) : RecyclerView.ViewHolder(binding.root) {
private val colorWhite by lazy(LazyThreadSafetyMode.NONE) {
ContextCompat.getColor(binding.root.context, R.color.colorWhite)
}
private val colorAccent by lazy(LazyThreadSafetyMode.NONE) {
ContextCompat.getColor(binding.root.context, R.color.colorAccent)
}
fun bind(item: MovieGridViewItem) {
binding.ibItemMovie.load(item.posterPath)
// TODO Add shared element transition
binding.ibItemMovie.setOnClickListener {
it.findNavController().navigate(
MovieGridFragmentDirections.actionMovieGridFragmentToMovieDetailFragment(item.id)
)
}
binding.ivItemMoviewStar.imageTintList =
ColorStateList.valueOf(if (item.isStar) colorAccent else colorWhite)
binding.ivItemMoviewStar.setOnClickListener { onItemStartClick.invoke(item) }
}
}
}
|
mit
|
a7d1617c264f02cad89ce38af660790d
| 40.330882 | 116 | 0.697153 | 5.194085 | false | false | false | false |
handstandsam/ShoppingApp
|
app/src/main/java/com/handstandsam/shoppingapp/features/home/HomeActivity.kt
|
1
|
1828
|
package com.handstandsam.shoppingapp.features.home
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.handstandsam.shoppingapp.LoggedInActivity
import com.handstandsam.shoppingapp.compose.HomeScreen
import com.handstandsam.shoppingapp.features.category.CategoryActivity
import com.handstandsam.shoppingapp.features.login.LoginActivity
import com.handstandsam.shoppingapp.utils.exhaustive
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class HomeActivity : LoggedInActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.hide()
val homeViewModel = ViewModelProvider(this, graph.viewModelFactory)
.get(HomeViewModel::class.java)
lifecycleScope.launchWhenCreated {
homeViewModel.sideEffects
.onEach {
when (it) {
is HomeViewModel.SideEffect.LaunchCategoryActivity -> {
CategoryActivity.launch(this@HomeActivity, it.category)
}
HomeViewModel.SideEffect.Logout -> {
LoginActivity.launch(this@HomeActivity)
}
}.exhaustive
}
.launchIn(this)
}
setContent {
HomeScreen(
itemsInCart = graph
.sessionGraph
.shoppingCart
.itemsInCart,
homeViewModel = homeViewModel,
showCartClicked = { startCheckoutActivity() },
logoutClicked = { logout() }
)
}
}
}
|
apache-2.0
|
330345e6feb82cd66a3adfc72e4a9ca6
| 34.843137 | 83 | 0.615974 | 5.993443 | false | false | false | false |
kenrube/Fantlab-client
|
app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/EditionsViewHolder.kt
|
2
|
2326
|
package ru.fantlab.android.ui.adapter.viewholder
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.edition_row_item.view.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.EditionsBlocks
import ru.fantlab.android.provider.scheme.LinkParserHelper.HOST_DATA
import ru.fantlab.android.provider.scheme.LinkParserHelper.PROTOCOL_HTTPS
import ru.fantlab.android.provider.storage.WorkTypesProvider
import ru.fantlab.android.ui.widgets.Dot
import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter
import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder
class EditionsViewHolder(itemView: View, adapter: BaseRecyclerAdapter<EditionsBlocks.Edition, EditionsViewHolder>)
: BaseViewHolder<EditionsBlocks.Edition>(itemView, adapter) {
override fun bind(edition: EditionsBlocks.Edition) {
itemView.coverLayout.setUrl(Uri.Builder().scheme(PROTOCOL_HTTPS)
.authority(HOST_DATA)
.appendPath("images")
.appendPath("editions")
.appendPath("big")
.appendPath(edition.editionId.toString())
.toString(), WorkTypesProvider.getCoverByTypeId(25))
itemView.coverLayout.setDotColor(
when {
edition.planDate != null -> Dot.Color.GREY
edition.correctLevel == 0f -> Dot.Color.RED
edition.correctLevel == 0.5f -> Dot.Color.ORANGE
edition.correctLevel == 1f -> Dot.Color.GREEN
else -> throw IllegalStateException("Received invalid edition->correct_level from API")
}
)
if (edition.authors.isNotEmpty()) {
itemView.authors.text = edition.authors.replace(ANY_CHARACTERS_IN_BRACKETS_REGEX, "")
itemView.authors.visibility = View.VISIBLE
} else {
itemView.authors.visibility = View.GONE
}
itemView.title.text = edition.name.replace(ANY_CHARACTERS_IN_BRACKETS_REGEX, "")
if (edition.year.toString().isNotEmpty() && edition.year != 0) {
itemView.year.text = edition.year.toString()
} else {
itemView.year.visibility = View.GONE
}
}
companion object {
private val ANY_CHARACTERS_IN_BRACKETS_REGEX = "\\[.*?]".toRegex()
fun newInstance(
viewGroup: ViewGroup,
adapter: BaseRecyclerAdapter<EditionsBlocks.Edition, EditionsViewHolder>
): EditionsViewHolder =
EditionsViewHolder(getView(viewGroup, R.layout.edition_row_item), adapter)
}
}
|
gpl-3.0
|
e7bfe59eead5e0edfe50b75e39067efc
| 35.936508 | 114 | 0.759673 | 3.794454 | false | false | false | false |
Etik-Tak/backend
|
src/main/kotlin/dk/etiktak/backend/service/product/ProductCategoryService.kt
|
1
|
6713
|
// Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package dk.etiktak.backend.service.product
import dk.etiktak.backend.model.contribution.Contribution
import dk.etiktak.backend.model.contribution.TextContribution
import dk.etiktak.backend.model.contribution.TrustVote
import dk.etiktak.backend.model.product.ProductCategory
import dk.etiktak.backend.model.user.Client
import dk.etiktak.backend.repository.product.ProductCategoryRepository
import dk.etiktak.backend.service.security.ClientVerified
import dk.etiktak.backend.service.trust.ContributionService
import dk.etiktak.backend.util.CryptoUtil
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
open class ProductCategoryService @Autowired constructor(
private val productCategoryRepository: ProductCategoryRepository,
private val contributionService: ContributionService) {
private val logger = LoggerFactory.getLogger(ProductCategoryService::class.java)
/**
* Finds a product category from the given UUID.
*
* @param uuid UUID
* @return Product category with given UUID
*/
open fun getProductCategoryByUuid(uuid: String): ProductCategory? {
return productCategoryRepository.findByUuid(uuid)
}
/**
* Creates a product category.
*
* @param inClient Client
* @param name Name
* @param modifyValues Function called with modified client
* @return Product category
*/
@ClientVerified
open fun createProductCategory(inClient: Client, name: String, modifyValues: (Client) -> Unit = {}): ProductCategory {
var client = inClient
// Create product category
var productCategory = ProductCategory()
productCategory.uuid = CryptoUtil().uuid()
productCategory.name = name
productCategory = productCategoryRepository.save(productCategory)
// Create name contribution
editProductCategoryName(client, productCategory, name, modifyValues = {modifiedClient, modifiedProductCategory -> client = modifiedClient; productCategory = modifiedProductCategory})
modifyValues(client)
return productCategory
}
/**
* Edits a product category name.
*
* @param inClient Client
* @param inProductCategory Product category
* @param name Name of product category
* @param modifyValues Function called with modified client and product category
* @return Product category name contribution
*/
@ClientVerified
open fun editProductCategoryName(inClient: Client, inProductCategory: ProductCategory, name: String, modifyValues: (Client, ProductCategory) -> Unit = {client, productCategory -> Unit}): Contribution {
var client = inClient
var productCategory = inProductCategory
// Create contribution
val contribution = contributionService.createTextContribution(Contribution.ContributionType.EditProductCategoryName, client, productCategory.uuid, name, modifyValues = { modifiedClient -> client = modifiedClient})
// Edit name
productCategory.name = name
productCategory = productCategoryRepository.save(productCategory)
modifyValues(client, productCategory)
return contribution
}
/**
* Returns whether the given client can edit the name of the product category.
*
* @param client Client
* @param productCategory Product category
* @return Yes, if the given client can edit the name of the product category, or else false
*/
open fun canEditProductCategoryName(client: Client, productCategory: ProductCategory): Boolean {
return client.verified && contributionService.hasSufficientTrustToEditContribution(client, productCategoryNameContribution(productCategory))
}
/**
* Returns the product category name contribution which is currently active.
*
* @param productCategory Product category
* @return Product category name contribution
*/
open fun productCategoryNameContribution(productCategory: ProductCategory): TextContribution? {
return contributionService.currentTextContribution(Contribution.ContributionType.EditProductCategoryName, productCategory.uuid)
}
/**
* Trust votes product category name.
*
* @param client Client
* @param productCategory Product category
* @param vote Vote
* @param modifyValues Function called with modified client
* @return Trust vote
*/
open fun trustVoteProductCategoryName(client: Client, productCategory: ProductCategory, vote: TrustVote.TrustVoteType, modifyValues: (Client) -> Unit = {}): TrustVote {
val contribution = productCategoryNameContribution(productCategory)!!
return contributionService.trustVoteItem(client, contribution, vote, modifyValues = {client, contribution -> modifyValues(client)})
}
}
|
bsd-3-clause
|
ec441e3907502e0c436ca49b6bc70368
| 44.358108 | 221 | 0.728437 | 5.38764 | false | false | false | false |
inorichi/tachiyomi-extensions
|
multisrc/overrides/madara/mangatk/src/MangaTK.kt
|
1
|
1343
|
package eu.kanade.tachiyomi.extension.en.mangatk
import eu.kanade.tachiyomi.multisrc.madara.Madara
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SManga
import java.util.Locale
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
class MangaTK : Madara("MangaTK", "https://mangatk.com", "en") {
override fun popularMangaSelector() = "div.manga-item"
override val popularMangaUrlSelector = "div > h3 > a"
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/manga/page/$page?orderby=trending")
}
override fun latestUpdatesRequest(page: Int): Request {
return GET("$baseUrl/manga/page/$page?orderby=latest")
}
override val pageListParseSelector = "div.read-content img"
override fun pageListParse(document: Document): List<Page> {
return document.select(pageListParseSelector).mapIndexed { index, element ->
Page(
index,
document.location(),
element?.let {
it.absUrl(if (it.hasAttr("data-src")) "data-src" else "src")
}
)
}
}
}
|
apache-2.0
|
ebc363939735b9e7ba2cb3800749d143
| 31.756098 | 84 | 0.679077 | 4.157895 | false | false | false | false |
ligee/kotlin-jupyter
|
jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/libraries/LibraryReference.kt
|
1
|
524
|
package org.jetbrains.kotlinx.jupyter.api.libraries
data class LibraryReference(
val info: LibraryResolutionInfo,
val name: String? = null,
) : LibraryCacheable by info {
val key: String
init {
val namePart = if (name.isNullOrEmpty()) "" else "${name}_"
key = namePart + info.key
}
override fun toString(): String {
val namePart = name ?: ""
val infoPart = info.toString()
return if (infoPart.isEmpty()) namePart
else "$namePart@$infoPart"
}
}
|
apache-2.0
|
5c71d067ff46e034419ad86d3d12dae0
| 23.952381 | 67 | 0.616412 | 4.260163 | false | false | false | false |
lydia-schiff/hella-renderscript
|
coolalgebralydiathanks/src/main/java/cat/the/lydia/coolalgebralydiathanks/implementation/KotlinCpuTrilinear.kt
|
1
|
9125
|
package cat.the.lydia.coolalgebralydiathanks.implementation
import cat.the.lydia.coolalgebralydiathanks.Bounded
import cat.the.lydia.coolalgebralydiathanks.Color
import cat.the.lydia.coolalgebralydiathanks.ColorCube
import cat.the.lydia.coolalgebralydiathanks.utils.Util
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Future
/**
* CPU reference implementation of ColorCube application to ColorData. This does 3D-lookup on a
* ColorCube's data and uses trilinear-interpolation.
*
* For any reasonably sized ColorData, this should be slower than equivalent versions implemented
* in C++, RenderScript, or OpenGL, although the parallel versions should be faster than sequential.
*/
object KotlinCpuTrilinear {
/**
* Apply a ColorCube to a Color.
*/
fun applyCubeToColor(
cube: ColorCube,
color: Color
): Color = trilinearInterpolateColor(cube, color)
/**
* Apply a ColorCube to a list of colors sequentially.
*/
fun applyCubeToColors(
cube: ColorCube,
colors: List<Color>
): List<Color> = colors.map { trilinearInterpolateColor(cube, it) }
/**
* Apply a ColorCube to a list of colors in parallel, for when you happen to have an
* ExecutorService lying around, and you're trying to try.
*/
fun applyCubeToColorsInParallel(
cube: ColorCube,
colors: List<Color>,
executor: ExecutorService,
batchSize: Int = DEFAULT_BATCH_SIZE
): List<Color> {
val size = batchSize.coerceIn(0, colors.size)
val tasks = mutableListOf<Future<List<Color>>>()
var remaining = colors.size
var n = 0
while (remaining > 0) {
val start = n
val end = (n + size).coerceAtMost(colors.size)
tasks += executor.submit(Callable {
applyCubeToColors(cube, colors.subList(start, end))
})
n += batchSize
remaining -= size
}
return mutableListOf<Color>().apply {
tasks.forEach {
addAll(it.get())
}
}
}
private const val DEFAULT_BATCH_SIZE = ColorCube.N_COLORS / 17
/**
* Use tri-linear interpolation to apply a ColorCube to a Color.
*
* We Use the color as a position in the ColorCube and find out local cube. Whatever
* fractional part of the distance from the ColorCube origin we had left is our local cube
* offset.
*
* Do our little zoom-in and we're just a Color in a unit cube again!
* The corners of our local cube are the 8 nearest colors in the lattice.
* That's everything we need. Calculate the result Color.
*/
private fun trilinearInterpolateColor(cube: ColorCube, color: Color): Color {
val position = LocalCubePosition(color)
val localCube = LocalColorCube(position.localOrigin, cube)
// Lerp is a great but also kind of bad word for linear interpolate. It's sometimes
// called mix. Everything in our algebra is lerp-able, and Color is no exception.
// We choose one channel to interpolate in first. We did red here but it doesn't matter
// because it's a cube! We now start with the two faces of the cube perpendicular to the
// red axis and do 4 interpolations to collapse the down to 4 Colors in a green-blue plane.
val c00x = Util.linearInterpolate(localCube.c000, localCube.c001, position.localOffset.b)
val c01x = Util.linearInterpolate(localCube.c010, localCube.c011, position.localOffset.b)
val c10x = Util.linearInterpolate(localCube.c100, localCube.c101, position.localOffset.b)
val c11x = Util.linearInterpolate(localCube.c110, localCube.c111, position.localOffset.b)
// Interpolate twice more in the green direction to collapse the plane down to a line
// parallel to the blue axis.
val c0xx = Util.linearInterpolate(c00x, c01x, position.localOffset.g)
val c1xx = Util.linearInterpolate(c10x, c11x, position.localOffset.g)
// Interpolate once more in the blue direction to collapse the line to a point,
// our Color!
return Util.linearInterpolate(c0xx, c1xx, position.localOffset.r)
}
/**
* Use a Color as the location in our ColorCube. The point will map to a point inside a local
* cube in the lattice with the 8 nearest colors at the corners. We need to figure out the
* coordinates of the lattice points so we can get the nearby colors, and we need the local
* position in the cube so we can interpolate.
*/
private class LocalCubePosition(color: Color) {
val localOrigin: Int3
val localOffset: Color
/**
* Convert the color from a position in the unit cube to a position in our N*N*N cube.
* Values will be real numbers in [0,N-1].
*
* Floor this value to get the integer part of the position. This will be the indices of the
* origin for our local cube. From now on our local cube is the origin + [0,1] in each
* direction.
*
* If the Color has the value 1f in any of the channels, then the cube index will be
* CoolAlgebra.N-1, which is the last index in 3D (the edge of our lattice).
*
* What we actually want is an index that is at most CoolAlgebra.N-2. This is because we
* always want to have a lattice point on each side of us for interpolating.
*
* If we need to coerce the point to the interior of the lattice, then rather than being 0f
* of the way from the edge, we will be 1f of the way from the previous point (which is the
* same thing! It makes our math nicer.
*
* Next, subtract the base index from the position the get the fractional part of the
* position. This is the offset from our local origin, and is a color again! Just as if
* the local cube is our unit cube.
*/
init {
val realPositionInIndexSpace = Float3(color) * (ColorCube.N - 1)
val intPositionInIndexSpace: Int3 = realPositionInIndexSpace.floor()
var rOrigin = intPositionInIndexSpace.x
var rOffset = realPositionInIndexSpace.x - rOrigin
if (rOrigin == ColorCube.N - 1) {
rOrigin--
rOffset = 1f
}
var gOrigin = intPositionInIndexSpace.y
var gOffset = realPositionInIndexSpace.y - gOrigin
if (gOrigin == ColorCube.N - 1) {
gOrigin--
gOffset = 1f
}
var bOrigin = intPositionInIndexSpace.z
var bOffset = realPositionInIndexSpace.z - bOrigin
if (bOrigin == ColorCube.N - 1) {
bOrigin--
bOffset = 1f
}
localOrigin = Int3(rOrigin, gOrigin, bOrigin)
localOffset = Color(Bounded(rOffset), Bounded(gOffset), Bounded(bOffset))
}
}
/**
* 8 nearest Colors in a ColorCube based on indices of localOrigin.
*/
private class LocalColorCube(localOrigin: Int3, cube: ColorCube) {
val c000: Color = cube.colors[index1d(localOrigin + p000)]
val c001: Color = cube.colors[index1d(localOrigin + p001)]
val c010: Color = cube.colors[index1d(localOrigin + p010)]
val c011: Color = cube.colors[index1d(localOrigin + p011)]
val c100: Color = cube.colors[index1d(localOrigin + p100)]
val c101: Color = cube.colors[index1d(localOrigin + p101)]
val c110: Color = cube.colors[index1d(localOrigin + p110)]
val c111: Color = cube.colors[index1d(localOrigin + p111)]
companion object {
private fun index1d(p: Int3) = p.x + p.y * ColorCube.N + p.z * ColorCube.N2
// Unit index offsets
private val p000 = Int3(0, 0, 0)
private val p001 = Int3(0, 0, 1)
private val p010 = Int3(0, 1, 0)
private val p011 = Int3(0, 1, 1)
private val p100 = Int3(1, 0, 0)
private val p101 = Int3(1, 0, 1)
private val p110 = Int3(1, 1, 0)
private val p111 = Int3(1, 1, 1)
}
}
private data class Float3(val x: Float, val y: Float, val z: Float) {
constructor(c: Color) : this(c.r.value, c.g.value, c.b.value)
fun floor() = Int3(x.toInt(), y.toInt(), z.toInt())
infix operator fun minus(value: Float3) =
Float3(value.x * x, value.y * y, value.z * z)
infix operator fun minus(value: Int3) =
Float3(value.x * x, value.y * y, value.z * z)
infix operator fun times(value: Float) =
Float3(value * x, value * y, value * z)
infix operator fun times(value: Int) =
Float3(value * x, value * y, value * z)
}
private data class Int3(val x: Int, val y: Int, val z: Int) {
infix operator fun plus(o: Int3) = Int3(x + o.x, y + o.y, z + o.z)
}
}
|
mit
|
ec000dc34350ba477cccf26c9809c56e
| 41.840376 | 100 | 0.624329 | 4.132699 | false | false | false | false |
TCA-Team/TumCampusApp
|
app/src/main/java/de/tum/in/tumcampusapp/component/ui/cafeteria/fragment/CafeteriaFragment.kt
|
1
|
8769
|
package de.tum.`in`.tumcampusapp.component.ui.cafeteria.fragment
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProviders
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.generic.fragment.FragmentForDownloadingExternal
import de.tum.`in`.tumcampusapp.component.other.locations.LocationManager
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.CafeteriaMenuFormatter
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.activity.CafeteriaNotificationSettingsActivity
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.controller.CafeteriaManager
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.details.CafeteriaDetailsSectionsPagerAdapter
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.details.CafeteriaViewModel
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.Cafeteria
import de.tum.`in`.tumcampusapp.di.ViewModelFactory
import de.tum.`in`.tumcampusapp.di.injector
import de.tum.`in`.tumcampusapp.service.DownloadWorker
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Utils
import de.tum.`in`.tumcampusapp.utils.observeNonNull
import kotlinx.android.synthetic.main.fragment_cafeteria.pager
import kotlinx.android.synthetic.main.fragment_cafeteria.spinnerToolbar
import org.joda.time.DateTime
import javax.inject.Inject
import javax.inject.Provider
class CafeteriaFragment : FragmentForDownloadingExternal(
R.layout.fragment_cafeteria,
R.string.cafeteria
), AdapterView.OnItemSelectedListener {
@Inject
lateinit var viewModelProvider: Provider<CafeteriaViewModel>
@Inject
lateinit var locationManager: LocationManager
@Inject
lateinit var cafeteriaManager: CafeteriaManager
@Inject
lateinit var cafeteriaDownloadAction: DownloadWorker.Action
private var cafeterias = mutableListOf<Cafeteria>()
private val cafeteriaViewModel: CafeteriaViewModel by lazy {
val factory = ViewModelFactory(viewModelProvider)
ViewModelProviders.of(this, factory).get(CafeteriaViewModel::class.java)
}
private val adapter: ArrayAdapter<Cafeteria> by lazy { createArrayAdapter() }
private val sectionsPagerAdapter: CafeteriaDetailsSectionsPagerAdapter by lazy {
CafeteriaDetailsSectionsPagerAdapter(childFragmentManager)
}
override val method: DownloadWorker.Action?
get() = cafeteriaDownloadAction
override fun onAttach(context: Context) {
super.onAttach(context)
injector.cafeteriaComponent().inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pager.offscreenPageLimit = 50
spinnerToolbar.adapter = adapter
spinnerToolbar.onItemSelectedListener = this
cafeteriaViewModel.cafeterias.observeNonNull(this) { updateCafeterias(it) }
cafeteriaViewModel.selectedCafeteria.observeNonNull(this) { onNewCafeteriaSelected(it) }
cafeteriaViewModel.menuDates.observeNonNull(this) { updateSectionsPagerAdapter(it) }
cafeteriaViewModel.error.observeNonNull(this) { isError ->
if (isError) {
showError(R.string.error_something_wrong)
} else {
showContentLayout()
}
}
}
override fun onStart() {
super.onStart()
val location = locationManager.getCurrentOrNextLocation()
cafeteriaViewModel.fetchCafeterias(location)
}
private fun updateCafeterias(newCafeterias: List<Cafeteria>) {
cafeterias.clear()
cafeterias.addAll(newCafeterias)
adapter.clear()
adapter.addAll(newCafeterias)
adapter.notifyDataSetChanged()
initCafeteriaSpinner()
}
private fun onNewCafeteriaSelected(cafeteria: Cafeteria) {
sectionsPagerAdapter.setCafeteriaId(cafeteria.id)
cafeteriaViewModel.fetchMenuDates()
}
private fun initCafeteriaSpinner() {
val intent = requireActivity().intent
val cafeteriaId: Int
if (intent != null && intent.hasExtra(Const.MENSA_FOR_FAVORITEDISH)) {
cafeteriaId = intent.getIntExtra(Const.MENSA_FOR_FAVORITEDISH, NONE_SELECTED)
intent.removeExtra(Const.MENSA_FOR_FAVORITEDISH)
} else if (intent != null && intent.hasExtra(Const.CAFETERIA_ID)) {
cafeteriaId = intent.getIntExtra(Const.CAFETERIA_ID, 0)
} else {
// If we're not provided with a cafeteria ID, we choose the best matching cafeteria.
cafeteriaId = cafeteriaManager.bestMatchMensaId
}
updateCafeteriaSpinner(cafeteriaId)
}
private fun updateCafeteriaSpinner(cafeteriaId: Int) {
var selectedIndex = NONE_SELECTED
for (cafeteria in cafeterias) {
val index = cafeterias.indexOf(cafeteria)
if (cafeteriaId == NONE_SELECTED || cafeteriaId == cafeteria.id) {
selectedIndex = index
break
}
}
if (selectedIndex != NONE_SELECTED) {
spinnerToolbar.setSelection(selectedIndex)
}
}
private fun updateSectionsPagerAdapter(menuDates: List<DateTime>) {
pager.adapter = null
sectionsPagerAdapter.update(menuDates)
pager.adapter = sectionsPagerAdapter
}
private fun createArrayAdapter(): ArrayAdapter<Cafeteria> {
return object : ArrayAdapter<Cafeteria>(
requireContext(), R.layout.simple_spinner_item_actionbar) {
private val inflater = LayoutInflater.from(context)
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val v = inflater.inflate(
R.layout.simple_spinner_dropdown_item_actionbar_two_line, parent, false)
val cafeteria = getItem(position)
val name = v.findViewById<TextView>(android.R.id.text1)
val address = v.findViewById<TextView>(android.R.id.text2)
val distance = v.findViewById<TextView>(R.id.distance)
if (cafeteria != null) {
name.text = cafeteria.name
address.text = cafeteria.address
distance.text = Utils.formatDistance(cafeteria.distance)
}
return v
}
}
}
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val selected = cafeterias.get(position)
cafeteriaViewModel.updateSelectedCafeteria(selected)
}
override fun onNothingSelected(adapterView: AdapterView<*>?) = Unit
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater?.inflate(R.menu.menu_section_fragment_cafeteria_details, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_ingredients -> {
showIngredientsInfo()
true
}
R.id.action_settings -> {
openNotificationSettings()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun openNotificationSettings() {
val intent = Intent(requireContext(), CafeteriaNotificationSettingsActivity::class.java)
startActivity(intent)
}
private fun showIngredientsInfo() {
// Build a alert dialog containing the mapping of ingredients to the numbers
val formatter = CafeteriaMenuFormatter(requireContext())
val message = formatter.format(R.string.cafeteria_ingredients, true)
AlertDialog.Builder(requireContext())
.setTitle(R.string.action_ingredients)
.setMessage(message)
.setPositiveButton(R.string.ok, null)
.create()
.apply {
window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background)
}
.show()
}
companion object {
private const val NONE_SELECTED = -1
@JvmStatic
fun newInstance() = CafeteriaFragment()
}
}
|
gpl-3.0
|
a5f5e264cadab73be4b46161382d3baf
| 35.5375 | 102 | 0.688904 | 5.033869 | false | false | false | false |
jk1/pmd-kotlin
|
src/test/kotlin/org/jetbrains/pmdkotlin/CpdTest.kt
|
1
|
3285
|
package org.jetbrains.pmdkotlin
import net.sourceforge.pmd.cpd.*
import net.sourceforge.pmd.lang.ParserOptions
import org.jetbrains.kotlin.codegen.FrameMap
import org.jetbrains.pmdkotlin.cpd.KotlinLanguage
import org.jetbrains.pmdkotlin.lang.kotlin.KotlinParser
import org.testng.annotations.BeforeTest
import org.testng.annotations.Test
import java.io.File
import java.io.FileNotFoundException
import java.io.FileReader
import java.io.PrintWriter
import java.net.URISyntaxException
import java.util.*
import org.mockito.Mockito.mock
// todo: add detailed asserts for matches
public class CpdTest {
var config: CPDConfiguration = CPDConfiguration()
var cpd: CPD = CPD(config)
private var hm: MutableMap<String, String>? = null
BeforeTest fun setUp() {
config = CPDConfiguration()
with(config) {
setLanguage(KotlinLanguage())
setEncoding("UTF-8")
setMinimumTileSize(30)
setIgnoreIdentifiers(true)
setIgnoreLiterals(true)
}
cpd = CPD(config)
}
// Test fun parser() {
// val parser = KotlinParser(ParserOptions())
// //val file = getResource("deprecatedTest/TraitKeywordTest.kt")
// val file = getResource("trashTest.kt")
//
// parser.parse(file.getAbsolutePath(), FileReader(file))
// }
// Test fun duplicateFunction() {
// //cpd.add(getResource("DuplicateFunction.kt"))
// cpd.add(getResource())
// cpd.go()
// show(cpd.getMatches())
// }
//
// Test fun ignoreImports() {
// val parser = KotlinParser(ParserOptions())
// val file = getResource("ignoreImportsTest/IgnoreImports1.kt")
// parser.parse(file.getAbsolutePath(), FileReader(file))
// }
//
Test fun falsePositives(){
cpd.add(getResource("cpd/KotlinParserVisitor.kt"))
cpd.go()
show(cpd.getMatches())
}
// @Test
// public void testDuplicateFunction() throws IOException {
// cpd.add(getKotlinFile("DuplicateFunction.kt"));
// cpd.go();
//
// show(cpd.getMatches());
//
// }
// @Test
// public void testIgnoreImports() throws IOException {
// cpd.add(getKotlinFile("ignoreImportsTest/IgnoreImports1.kt"));
// cpd.add(getKotlinFile("ignoreImportsTest/IgnoreImports2.kt"));
//
// cpd.go();
//
// show(cpd.getMatches());
// }
//
// @Test
// public void testIgnoreIdentifiersAndLiterals() throws IOException {
// cpd.add(getKotlinFile("ignoreIdentifiersAndLiteralsTest/IgnoreIdentifiers.kt"));
// cpd.add(getKotlinFile("ignoreIdentifiersAndLiteralsTest/IgnoreIdentifiers2.kt"));
//
// cpd.go();
// show(cpd.getMatches());
// }
public fun show(matches: Iterator<Match>) {
val pw = PrintWriter("cpd_results.txt")
while (matches.hasNext()) {
val match = matches.next()
pw.println(match.toString())
for (m in match.getMarkSet()) {
pw.println(m.getBeginLine())
pw.println(m.getEndLine());
}
pw.println(match.getSourceCodeSlice())
}
pw.close()
}
}
|
apache-2.0
|
73f37ad8b7241daaf8574e97c0556903
| 29.416667 | 95 | 0.611872 | 4.174079 | false | true | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/settings/questselection/QuestSelectionAdapter.kt
|
1
|
8362
|
package de.westnordost.streetcomplete.settings.questselection
import android.content.SharedPreferences
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.ItemTouchHelper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import java.util.Collections
import java.util.Locale
import java.util.concurrent.FutureTask
import javax.inject.Inject
import de.westnordost.countryboundaries.CountryBoundaries
import de.westnordost.streetcomplete.Prefs
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.view.ListAdapter
import androidx.recyclerview.widget.ItemTouchHelper.ACTION_STATE_DRAG
import androidx.recyclerview.widget.ItemTouchHelper.ACTION_STATE_IDLE
import androidx.recyclerview.widget.ItemTouchHelper.DOWN
import androidx.recyclerview.widget.ItemTouchHelper.UP
import de.westnordost.streetcomplete.data.quest.QuestType
import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType
import de.westnordost.streetcomplete.data.quest.AllCountries
import de.westnordost.streetcomplete.data.quest.AllCountriesExcept
import de.westnordost.streetcomplete.data.quest.NoCountriesExcept
import de.westnordost.streetcomplete.ktx.containsAny
import de.westnordost.streetcomplete.settings.genericQuestTitle
import kotlinx.android.synthetic.main.row_quest_selection.view.*
/** Adapter for the list that in which the user can enable and disable quests as well as re-order
* them */
class QuestSelectionAdapter @Inject constructor(
countryBoundaries: FutureTask<CountryBoundaries>,
prefs: SharedPreferences
) : ListAdapter<QuestVisibility>() {
private val currentCountryCodes: List<String>
interface Listener {
fun onReorderedQuests(before: QuestType<*>, after: QuestType<*>)
fun onChangedQuestVisibility(questType: QuestType<*>, visible: Boolean)
}
var listener: Listener? = null
init {
val lat = Double.fromBits(prefs.getLong(Prefs.MAP_LATITUDE, 0.0.toBits()))
val lng = Double.fromBits(prefs.getLong(Prefs.MAP_LONGITUDE, 0.0.toBits()))
currentCountryCodes = countryBoundaries.get().getIds(lng, lat)
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
val ith = ItemTouchHelper(TouchHelperCallback())
ith.attachToRecyclerView(recyclerView)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<QuestVisibility> {
val layout = LayoutInflater.from(parent.context).inflate(R.layout.row_quest_selection, parent, false)
return QuestVisibilityViewHolder(layout)
}
private inner class TouchHelperCallback : ItemTouchHelper.Callback() {
private var draggedFrom = -1
private var draggedTo = -1
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
val qv = (viewHolder as QuestVisibilityViewHolder).item
return if (!qv.isInteractionEnabled) 0
else makeFlag(ACTION_STATE_IDLE, UP or DOWN) or makeFlag(ACTION_STATE_DRAG, UP or DOWN)
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
val from = viewHolder.adapterPosition
val to = target.adapterPosition
Collections.swap(list, from, to)
notifyItemMoved(from, to)
return true
}
override fun canDropOver(recyclerView: RecyclerView, current: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
val qv = (target as QuestVisibilityViewHolder).item
return qv.isInteractionEnabled
}
override fun onMoved(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, fromPos: Int, target: RecyclerView.ViewHolder, toPos: Int, x: Int, y: Int) {
super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y)
if (draggedFrom == -1) draggedFrom = fromPos
draggedTo = toPos
}
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
if (actionState == ACTION_STATE_IDLE && draggedTo != draggedFrom) {
var pos = draggedTo
if (draggedTo == 0) pos++
val before = list[pos - 1].questType
val after = list[pos].questType
listener?.onReorderedQuests(before, after)
draggedFrom = -1
draggedTo = draggedFrom
}
}
override fun isItemViewSwipeEnabled() = false
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}
}
private inner class QuestVisibilityViewHolder(itemView: View) :
ListAdapter.ViewHolder<QuestVisibility>(itemView), CompoundButton.OnCheckedChangeListener {
private val questIcon: ImageView = itemView.questIcon
private val questTitle: TextView = itemView.questTitle
private val visibilityCheckBox: CheckBox = itemView.visibilityCheckBox
private val countryDisabledText: TextView = itemView.countryDisabledText
lateinit var item: QuestVisibility
private val isEnabledInCurrentCountry: Boolean
get() {
(item.questType as? OsmElementQuestType<*>)?.let { questType ->
return when(val countries = questType.enabledInCountries) {
is AllCountries -> true
is AllCountriesExcept -> !countries.exceptions.containsAny(currentCountryCodes)
is NoCountriesExcept -> countries.exceptions.containsAny(currentCountryCodes)
}
}
return true
}
override fun onBind(with: QuestVisibility) {
this.item = with
val colorResId = if (item.isInteractionEnabled) R.color.background else R.color.greyed_out
itemView.setBackgroundResource(colorResId)
questIcon.setImageResource(item.questType.icon)
questTitle.text = genericQuestTitle(questTitle, item.questType)
visibilityCheckBox.setOnCheckedChangeListener(null)
visibilityCheckBox.isChecked = item.visible
visibilityCheckBox.isEnabled = item.isInteractionEnabled
visibilityCheckBox.setOnCheckedChangeListener(this)
countryDisabledText.isGone = isEnabledInCurrentCountry
if (!isEnabledInCurrentCountry) {
val cc = if (currentCountryCodes.isEmpty()) "Atlantis" else currentCountryCodes[0]
countryDisabledText.text = countryDisabledText.resources.getString(
R.string.questList_disabled_in_country, Locale("", cc).displayCountry
)
}
updateSelectionStatus()
}
private fun updateSelectionStatus() {
if (!item.visible) {
questIcon.setColorFilter(ContextCompat.getColor(itemView.context, R.color.greyed_out))
} else {
questIcon.clearColorFilter()
}
questTitle.isEnabled = item.visible
}
override fun onCheckedChanged(compoundButton: CompoundButton, b: Boolean) {
item.visible = b
updateSelectionStatus()
listener?.onChangedQuestVisibility(item.questType, item.visible)
if (b && item.questType.defaultDisabledMessage > 0) {
AlertDialog.Builder(compoundButton.context)
.setTitle(R.string.enable_quest_confirmation_title)
.setMessage(item.questType.defaultDisabledMessage)
.setPositiveButton(android.R.string.yes, null)
.setNegativeButton(android.R.string.no) { _, _ ->
compoundButton.isChecked = false
}
.show()
}
}
}
}
|
gpl-3.0
|
18c03c32b3d4d1aeba585e0d482f962d
| 42.780105 | 170 | 0.687993 | 5.319338 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/PreferencesFragment.kt
|
1
|
20075
|
package com.habitrpg.android.habitica.ui.fragments.preferences
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.preference.CheckBoxPreference
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceScreen
import com.habitrpg.android.habitica.BuildConfig
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.ContentRepository
import com.habitrpg.android.habitica.extensions.addCancelButton
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.helpers.SoundManager
import com.habitrpg.android.habitica.helpers.TaskAlarmManager
import com.habitrpg.android.habitica.helpers.notifications.PushNotificationManager
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.prefs.TimePreference
import com.habitrpg.android.habitica.ui.activities.ClassSelectionActivity
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.android.habitica.ui.activities.PrefsActivity
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar
import com.habitrpg.android.habitica.ui.views.SnackbarActivity
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.android.habitica.ui.views.insufficientCurrency.InsufficientGemsDialog
import com.habitrpg.common.habitica.helpers.AppTestingLevel
import com.habitrpg.common.habitica.helpers.LanguageHelper
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import java.util.Locale
import javax.inject.Inject
class PreferencesFragment : BasePreferencesFragment(), SharedPreferences.OnSharedPreferenceChangeListener {
@Inject
lateinit var contentRepository: ContentRepository
@Inject
lateinit var soundManager: SoundManager
@Inject
lateinit var pushNotificationManager: PushNotificationManager
@Inject
lateinit var configManager: AppConfigManager
@Inject
lateinit var apiClient: ApiClient
private var timePreference: TimePreference? = null
private var pushNotificationsPreference: PreferenceScreen? = null
private var emailNotificationsPreference: PreferenceScreen? = null
private var classSelectionPreference: Preference? = null
private var serverUrlPreference: ListPreference? = null
private var taskListPreference: ListPreference? = null
override fun onCreate(savedInstanceState: Bundle?) {
HabiticaBaseApplication.userComponent?.inject(this)
super.onCreate(savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
listView.itemAnimator = null
userRepository.retrieveTeamPlans().subscribe({}, ExceptionHandler.rx())
}
override fun setupPreferences() {
timePreference = findPreference("reminder_time") as? TimePreference
val useReminder = preferenceManager.sharedPreferences?.getBoolean("use_reminder", false)
timePreference?.isEnabled = useReminder ?: false
classSelectionPreference = findPreference("choose_class")
val weekdayPreference = findPreference("FirstDayOfTheWeek") as? ListPreference
weekdayPreference?.summary = weekdayPreference?.entry
serverUrlPreference = findPreference("server_url") as? ListPreference
serverUrlPreference?.isVisible = false
serverUrlPreference?.summary = preferenceManager.sharedPreferences?.getString("server_url", "")
val themePreference = findPreference("theme_name") as? ListPreference
themePreference?.summary = themePreference?.entry ?: "Default"
val themeModePreference = findPreference("theme_mode") as? ListPreference
themeModePreference?.summary = themeModePreference?.entry ?: "Follow System"
val launchScreenPreference = findPreference("launch_screen") as? ListPreference
launchScreenPreference?.summary = launchScreenPreference?.entry ?: "Habits"
val taskDisplayPreference = findPreference("task_display") as? ListPreference
if (configManager.enableTaskDisplayMode()) {
taskDisplayPreference?.isVisible = true
taskDisplayPreference?.summary = taskDisplayPreference?.entry
} else {
taskDisplayPreference?.isVisible = false
}
}
override fun onResume() {
super.onResume()
preferenceManager.sharedPreferences?.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
preferenceManager.sharedPreferences?.unregisterOnSharedPreferenceChangeListener(this)
super.onPause()
}
override fun onPreferenceTreeClick(preference: Preference): Boolean {
when (preference.key) {
"logout" -> {
logout()
}
"choose_class" -> {
val bundle = Bundle()
bundle.putBoolean("isInitialSelection", user?.flags?.classSelected == false)
val intent = Intent(activity, ClassSelectionActivity::class.java)
intent.putExtras(bundle)
if (user?.flags?.classSelected == true && user?.preferences?.disableClasses == false) {
if ((user?.gemCount ?: 0) >= 3) {
context?.let { context ->
val builder = AlertDialog.Builder(context)
.setMessage(getString(R.string.change_class_confirmation))
.setNegativeButton(getString(R.string.dialog_go_back)) { dialog, _ -> dialog.dismiss() }
.setPositiveButton(getString(R.string.change_class)) { _, _ ->
classSelectionResult.launch(
intent
)
}
val alert = builder.create()
alert.show()
}
} else {
val dialog = context?.let { InsufficientGemsDialog(it, 3) }
dialog?.show()
}
} else {
classSelectionResult.launch(intent)
}
return true
}
"reload_content" -> {
(activity as? SnackbarActivity)?.showSnackbar(
content = context?.getString(R.string.reloading_content)
)
reloadContent(true)
}
}
return super.onPreferenceTreeClick(preference)
}
private fun reloadContent(withConfirmation: Boolean) {
lifecycleScope.launch(ExceptionHandler.coroutine()) {
contentRepository.retrieveContent(true)
if (withConfirmation) {
(activity as? SnackbarActivity)?.showSnackbar(
content = context?.getString(R.string.reloaded_content),
displayType = HabiticaSnackbar.SnackbarDisplayType.SUCCESS
)
}
}
}
private fun logout() {
context?.let { context ->
val dialog = HabiticaAlertDialog(context)
dialog.setTitle(R.string.are_you_sure)
dialog.addButton(R.string.logout, true) { _, _ ->
HabiticaBaseApplication.logout(context)
activity?.finish()
}
dialog.addCancelButton()
dialog.show()
}
}
private val classSelectionResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
lifecycleScope.launch(ExceptionHandler.coroutine()) {
userRepository.retrieveUser(true, true)
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) {
when (key) {
"use_reminder" -> {
val useReminder = sharedPreferences.getBoolean(key, false)
timePreference?.isEnabled = useReminder
if (useReminder) {
TaskAlarmManager.scheduleDailyReminder(context)
} else {
TaskAlarmManager.removeDailyReminder(context)
}
}
"reminder_time" -> {
TaskAlarmManager.removeDailyReminder(context)
TaskAlarmManager.scheduleDailyReminder(context)
}
"usePushNotifications" -> {
val userPushNotifications = sharedPreferences.getBoolean(key, false)
pushNotificationsPreference?.isEnabled = userPushNotifications
userRepository.updateUser("preferences.pushNotifications.unsubscribeFromAll", userPushNotifications).subscribe()
if (userPushNotifications) {
pushNotificationManager.addPushDeviceUsingStoredToken()
} else {
pushNotificationManager.removePushDeviceUsingStoredToken()
}
}
"useEmails" -> {
val useEmailNotifications = sharedPreferences.getBoolean(key, false)
emailNotificationsPreference?.isEnabled = useEmailNotifications
userRepository.updateUser("preferences.emailNotifications.unsubscribeFromAll", useEmailNotifications).subscribe()
}
"cds_time" -> {
val timeval = sharedPreferences.getString("cds_time", "0") ?: "0"
val hour = Integer.parseInt(timeval)
userRepository.changeCustomDayStart(hour).subscribe({ }, ExceptionHandler.rx())
val preference = findPreference<ListPreference>(key)
preference?.summary = preference?.entry
}
"language" -> {
val languageHelper = LanguageHelper(sharedPreferences.getString(key, "en"))
Locale.setDefault(languageHelper.locale)
val configuration = Configuration()
configuration.setLocale(languageHelper.locale)
@Suppress("DEPRECATION")
activity?.resources?.updateConfiguration(configuration, activity?.resources?.displayMetrics)
if (user?.preferences?.language == languageHelper.languageCode) {
return
}
userRepository.updateLanguage(languageHelper.languageCode ?: "en")
.subscribe({ reloadContent(false) }, ExceptionHandler.rx())
val intent = Intent(activity, MainActivity::class.java)
this.startActivity(intent)
activity?.finishAffinity()
}
"audioTheme" -> {
val newAudioTheme = sharedPreferences.getString(key, "off")
if (newAudioTheme != null) {
compositeSubscription.add(
userRepository.updateUser("preferences.sound", newAudioTheme)
.subscribe({ }, ExceptionHandler.rx())
)
soundManager.soundTheme = newAudioTheme
soundManager.preloadAllFiles()
}
}
"theme_name" -> {
val activity = activity as? PrefsActivity ?: return
activity.reload()
}
"theme_mode" -> {
val activity = activity as? PrefsActivity ?: return
activity.reload()
}
"dailyDueDefaultView" -> userRepository.updateUser("preferences.dailyDueDefaultView", sharedPreferences.getBoolean(key, false))
.subscribe({ }, ExceptionHandler.rx())
"server_url" -> {
apiClient.updateServerUrl(sharedPreferences.getString(key, ""))
findPreference<Preference>(key)?.summary = sharedPreferences.getString(key, "")
}
"task_display" -> {
val preference = findPreference<ListPreference>(key)
preference?.summary = preference?.entry
}
"FirstDayOfTheWeek" -> {
val preference = findPreference<ListPreference>(key)
preference?.summary = preference?.entry
}
"disablePMs" -> {
val isDisabled = sharedPreferences.getBoolean("disablePMs", false)
if (user?.inbox?.optOut != isDisabled) {
compositeSubscription.add(
userRepository.updateUser("inbox.optOut", isDisabled)
.subscribe({ }, ExceptionHandler.rx())
)
}
}
"launch_screen" -> {
val preference = findPreference<ListPreference>(key)
preference?.summary = preference?.entry ?: "Habits"
}
}
}
override fun onDisplayPreferenceDialog(preference: Preference) {
if (preference is TimePreference) {
if (parentFragmentManager.findFragmentByTag(TimePreferenceDialogFragment.TAG) == null) {
TimePreferenceDialogFragment.newInstance(this, preference.getKey())
.show(parentFragmentManager, TimePreferenceDialogFragment.TAG)
}
} else {
super.onDisplayPreferenceDialog(preference)
}
}
override fun setUser(user: User?) {
super.setUser(user)
if (10 <= (user?.stats?.lvl ?: 0)) {
if (user?.flags?.classSelected == true) {
if (user.preferences?.disableClasses == true) {
classSelectionPreference?.title = getString(R.string.enable_class)
} else {
classSelectionPreference?.title = getString(R.string.change_class)
classSelectionPreference?.summary = getString(R.string.change_class_description)
}
} else {
classSelectionPreference?.title = getString(R.string.enable_class)
}
classSelectionPreference?.isVisible = true
} else {
classSelectionPreference?.isVisible = false
}
val cdsTimePreference = findPreference("cds_time") as? ListPreference
cdsTimePreference?.value = user?.preferences?.dayStart.toString()
cdsTimePreference?.summary = cdsTimePreference?.entry
val dailyDueDefault = findPreference<Preference>("dailyDueDefaultView") as? CheckBoxPreference
dailyDueDefault?.isChecked = user?.preferences?.dailyDueDefaultView == true
val languagePreference = findPreference("language") as? ListPreference
languagePreference?.value = user?.preferences?.language
languagePreference?.summary = languagePreference?.entry
val audioThemePreference = findPreference("audioTheme") as? ListPreference
audioThemePreference?.value = user?.preferences?.sound
audioThemePreference?.summary = audioThemePreference?.entry
val preference = findPreference<Preference>("authentication")
if (user?.flags?.verifiedUsername == true) {
preference?.layoutResource = R.layout.preference_child_summary
preference?.summary = context?.getString(R.string.authentication_summary)
} else {
preference?.layoutResource = R.layout.preference_child_summary_error
preference?.summary = context?.getString(R.string.username_not_confirmed)
}
if (user?.party?.id?.isNotBlank() != true) {
val launchScreenPreference = findPreference<ListPreference>("launch_screen")
launchScreenPreference?.entries = resources.getStringArray(R.array.launch_screen_types).dropLast(1).toTypedArray()
launchScreenPreference?.entryValues = resources.getStringArray(R.array.launch_screen_values).dropLast(1).toTypedArray()
}
val disablePMsPreference = findPreference("disablePMs") as? CheckBoxPreference
val inbox = user?.inbox
disablePMsPreference?.isChecked = inbox?.optOut ?: true
val usePushPreference = findPreference("usePushNotifications") as? CheckBoxPreference
pushNotificationsPreference = findPreference("pushNotifications") as? PreferenceScreen
val usePushNotifications = user?.preferences?.pushNotifications?.unsubscribeFromAll ?: false
pushNotificationsPreference?.isEnabled = usePushNotifications
usePushPreference?.isChecked = usePushNotifications
val useEmailPreference = findPreference("useEmails") as? CheckBoxPreference
emailNotificationsPreference = findPreference("emailNotifications") as? PreferenceScreen
val useEmailNotifications = user?.preferences?.emailNotifications?.unsubscribeFromAll ?: false
emailNotificationsPreference?.isEnabled = useEmailNotifications
useEmailPreference?.isChecked = useEmailNotifications
lifecycleScope.launch {
val teams = userRepository.getTeamPlans().firstOrNull() ?: return@launch
val context = context ?: return@launch
val groupCategory = findPreference<PreferenceCategory>("groups_category")
val footer = groupCategory?.findPreference<Preference>("groups_footer")
footer?.order = 9999
groupCategory?.removeAll()
if (teams.isEmpty()) {
groupCategory?.isVisible = false
} else {
groupCategory?.isVisible = true
for (team in teams) {
val newPreference = CheckBoxPreference(context)
newPreference.layoutResource = R.layout.preference_child_summary
newPreference.title = getString(R.string.copy_shared_tasks)
newPreference.summary = team.summary
newPreference.key = "copy_tasks-${team.id}"
newPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { preference, newValue ->
val currentIds = user?.preferences?.tasks?.mirrorGroupTasks?.toMutableList() ?: mutableListOf()
if (newValue == true && !currentIds.contains(team.id)) {
currentIds.add(team.id)
} else if (newValue == false && currentIds.contains(team.id)) {
currentIds.remove(team.id)
}
userRepository.updateUser("preferences.tasks.mirrorGroupTasks", currentIds).subscribe({}, ExceptionHandler.rx())
true
}
groupCategory?.addPreference(newPreference)
newPreference.isChecked = user?.preferences?.tasks?.mirrorGroupTasks?.contains(team.id) == true
}
}
if (footer != null) {
groupCategory.addPreference(footer)
}
}
if (configManager.testingLevel() == AppTestingLevel.STAFF || BuildConfig.DEBUG) {
serverUrlPreference?.isVisible = true
taskListPreference?.isVisible = true
}
}
}
|
gpl-3.0
|
226272a0fba3ee735fe586f5e0ce7497
| 46.963415 | 139 | 0.620274 | 6.001495 | false | false | false | false |
BloodWorkXGaming/ExNihiloCreatio
|
src/main/java/exnihilocreatio/registries/types/WitchWaterWorld.kt
|
1
|
1392
|
package exnihilocreatio.registries.types
import exnihilocreatio.util.BlockInfo
data class WitchWaterWorld(val results: MutableList<BlockInfo>, val weights: MutableList<Int>){
private var totalWeight: Int = weights.sum()
fun toMap(): Map<BlockInfo, Int> {
val mapping = HashMap<BlockInfo, Int>()
for(idx in 0 until results.size)
mapping[results[idx]] = weights[idx]
return mapping
}
constructor(results: MutableList<BlockInfo>): this(results, results.map { 1 }.toMutableList())
fun add(result: BlockInfo, weight: Int){
results.add(result)
weights.add(weight)
totalWeight += weight
}
fun getResult(chance: Int): BlockInfo {
if(chance > totalWeight || chance < 1)
return results.last()
var remainer = chance
var idx = -1
while(remainer > 0){
idx++
remainer -= weights[idx]
}
return results[idx]
}
fun getResult(chance: Float): BlockInfo {
return getResult((chance * this.totalWeight).toInt() + 1)
}
companion object {
@JvmStatic
fun fromMap(mapping: Map<BlockInfo, Int>): WitchWaterWorld {
val keys = mapping.keys.toMutableList()
val vals = keys.map { mapping[it] ?: 0 }.toMutableList()
return WitchWaterWorld(keys, vals)
}
}
}
|
mit
|
30b6ae5b7300db207cbdb37976bd2326
| 28.638298 | 98 | 0.604885 | 4.419048 | false | false | false | false |
GLodi/GitNav
|
app/src/main/java/giuliolodi/gitnav/ui/login/LoginActivity.kt
|
1
|
5115
|
/*
* 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.login
import android.app.ProgressDialog
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.customtabs.CustomTabsIntent
import android.support.v4.content.ContextCompat
import android.view.KeyEvent
import android.widget.Toast
import es.dmoral.toasty.Toasty
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.base.BaseActivity
import giuliolodi.gitnav.ui.events.EventActivity
import kotlinx.android.synthetic.main.login_activity.*
import javax.inject.Inject
/**
* Created by giulio on 12/05/2017.
*/
class LoginActivity : BaseActivity(), LoginContract.View {
@Inject lateinit var mPresenter: LoginContract.Presenter<LoginContract.View>
lateinit var progDialog: ProgressDialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_activity)
initLayout()
getActivityComponent().inject(this)
mPresenter.onAttach(this)
mPresenter.subscribe()
}
private fun initLayout() {
login_activity_loginbtn.setOnClickListener {
if (login_activity_user.text.isEmpty() || login_activity_pass.text.isEmpty())
Toasty.warning(applicationContext, getString(R.string.insert_credentials), Toast.LENGTH_LONG).show()
else {
if (isNetworkAvailable())
mPresenter.onLoginClick(login_activity_user.text.toString(), login_activity_pass.text.toString())
else
Toasty.warning(applicationContext, getString(R.string.network_error), Toast.LENGTH_LONG).show()
}
}
login_activity_pass.setOnKeyListener { v, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
if (login_activity_user.text.isEmpty() || login_activity_pass.text.isEmpty())
Toasty.warning(applicationContext, getString(R.string.insert_credentials), Toast.LENGTH_LONG).show()
else {
if (isNetworkAvailable())
mPresenter.onLoginClick(login_activity_user.text.toString(), login_activity_pass.text.toString())
else
Toasty.warning(applicationContext, getString(R.string.network_error), Toast.LENGTH_LONG).show()
}
return@setOnKeyListener true
}
return@setOnKeyListener false
}
login_activity_signup.setOnClickListener {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/"))
startActivity(browserIntent)
}
login_activity_web.setOnClickListener {
val intent = CustomTabsIntent.Builder()
.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setShowTitle(true)
.build()
try {
intent.launchUrl(this, mPresenter.getFirstStepUri())
} catch (ignored: ActivityNotFoundException) {
}
}
}
override fun showLoading() {
progDialog = ProgressDialog(this)
progDialog.setMessage("Signing in")
progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER)
progDialog.setCancelable(false)
progDialog.show()
}
override fun hideLoading() {
if (progDialog.isShowing) progDialog.dismiss()
}
override fun showSuccess() {
Toasty.success(applicationContext, getString(R.string.logged_in), Toast.LENGTH_LONG).show()
}
override fun showError(error: String) {
Toasty.error(applicationContext, error, Toast.LENGTH_LONG).show()
}
override fun intentToEventActivity() {
startActivity(EventActivity.getIntent(applicationContext))
finish()
overridePendingTransition(0,0)
}
override fun onResume() {
super.onResume()
mPresenter.onHandleAuthIntent(intent)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
mPresenter.onHandleAuthIntent(intent)
}
override fun onDestroy() {
mPresenter.onDetach()
super.onDestroy()
}
companion object {
fun getIntent(context: Context): Intent {
return Intent(context, LoginActivity::class.java)
}
}
}
|
apache-2.0
|
40502bf37ff9d071a350ccdcaf4abf77
| 33.802721 | 121 | 0.660997 | 4.84375 | false | false | false | false |
dhleong/ideavim
|
src/com/maddyhome/idea/vim/helper/CommandStateExtensions.kt
|
1
|
1360
|
@file:JvmName("CommandStateHelper")
package com.maddyhome.idea.vim.helper
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.command.CommandState
/**
* @author Alex Plate
*/
private val modesWithEndAllowed = setOf(CommandState.Mode.INSERT, CommandState.Mode.REPEAT, CommandState.Mode.VISUAL, CommandState.Mode.SELECT)
val CommandState.Mode.isEndAllowed
get() = this in modesWithEndAllowed
val Editor.mode
get() = CommandState.getInstance(this).mode
var Editor.subMode
get() = CommandState.getInstance(this).subMode
set(value) {
CommandState.getInstance(this).subMode = value
}
@get:JvmName("inInsertMode")
val Editor.inInsertMode
get() = this.mode == CommandState.Mode.INSERT || this.mode == CommandState.Mode.REPLACE
@get:JvmName("inRepeatMode")
val Editor.inRepeatMode
get() = this.mode == CommandState.Mode.REPEAT
@get:JvmName("inVisualMode")
val Editor.inVisualMode
get() = this.mode == CommandState.Mode.VISUAL
@get:JvmName("inSelectMode")
val Editor.inSelectMode
get() = this.mode == CommandState.Mode.SELECT
@get:JvmName("inBlockSubMode")
val Editor.inBlockSubMode
get() = this.subMode == CommandState.SubMode.VISUAL_BLOCK
@get:JvmName("inSingleCommandMode")
val Editor.inSingleCommandMode
get() = this.subMode == CommandState.SubMode.SINGLE_COMMAND && this.mode == CommandState.Mode.COMMAND
|
gpl-2.0
|
3ad90807d98967cf298c0c790340105b
| 27.93617 | 143 | 0.767647 | 3.820225 | false | false | false | false |
LegNeato/buck
|
tools/datascience/src/com/facebook/buck/datascience/traces/CountApRounds.kt
|
5
|
1975
|
package com.facebook.buck.datascience.traces
class CountApRounds : TraceAnalysisVisitor<CountApRounds.Summary> {
private val roundCounts = mutableMapOf<Int, Int>()
private val distribution = mutableMapOf<Int, Int>()
private val maxByRule = mutableMapOf<String, Int>()
class Summary(
val distribution: Map<Int, Int>,
val maxByRule: Map<String, Int>)
override fun traceComplete() = Summary(distribution, maxByRule)
override fun finishAnalysis(args: List<String>, intermediates: List<Summary>) {
for (partial in intermediates) {
for ((rounds, samples) in partial.distribution) {
distribution[rounds] = samples + distribution.getOrDefault(rounds, 0)
}
for ((rule, max) in partial.maxByRule) {
maxByRule[rule] = Math.max(max, maxByRule.getOrDefault(rule, 0))
}
}
maxByRule.entries.sortedWith(compareBy({it.value}, {it.key})).forEach {
println("%s %d".format(it.key, it.value))
}
println()
distribution.toSortedMap().forEach { (count, samples) ->
println("%s %d".format(count, samples))
}
}
override fun eventBegin(event: TraceEvent, state: TraceState) {
when (event.name) {
"annotation processing round" -> {
roundCounts[event.tid] = 1 + roundCounts.getOrDefault(event.tid, 0)
}
}
}
override fun eventEnd(event: TraceEvent, state: TraceState) {
when (event.name) {
"javac_jar" -> {
val count = roundCounts.getOrDefault(event.tid, 0)
roundCounts.remove(event.tid)
distribution[count] = 1 + distribution.getOrDefault(event.tid, 0)
val ruleName = state.threadStacks[event.tid]!![0].name
maxByRule[ruleName] = Math.max(count, maxByRule.getOrDefault(ruleName, 0))
}
}
}
}
|
apache-2.0
|
5ec834925e5b0110137120338e40938c
| 35.574074 | 90 | 0.592405 | 4.438202 | false | false | false | false |
da1z/intellij-community
|
platform/projectModel-api/src/com/intellij/util/jdom.kt
|
4
|
4525
|
// Copyright 2000-2017 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.util
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.reference.SoftReference
import com.intellij.util.io.inputStream
import com.intellij.util.io.outputStream
import com.intellij.util.text.CharSequenceReader
import org.jdom.Document
import org.jdom.Element
import org.jdom.JDOMException
import org.jdom.Parent
import org.jdom.filter.ElementFilter
import org.jdom.input.SAXBuilder
import org.jdom.input.SAXHandler
import org.xml.sax.EntityResolver
import org.xml.sax.InputSource
import org.xml.sax.XMLReader
import java.io.*
import java.nio.file.Path
import javax.xml.XMLConstants
private val cachedSaxBuilder = ThreadLocal<SoftReference<SAXBuilder>>()
private fun getSaxBuilder(): SAXBuilder {
val reference = cachedSaxBuilder.get()
var saxBuilder = SoftReference.dereference<SAXBuilder>(reference)
if (saxBuilder == null) {
saxBuilder = object : SAXBuilder() {
override fun configureParser(parser: XMLReader, contentHandler: SAXHandler?) {
super.configureParser(parser, contentHandler)
try {
parser.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true)
}
catch (ignore: Exception) {
}
}
}
saxBuilder.ignoringBoundaryWhitespace = true
saxBuilder.ignoringElementContentWhitespace = true
saxBuilder.entityResolver = EntityResolver { publicId, systemId -> InputSource(CharArrayReader(ArrayUtil.EMPTY_CHAR_ARRAY)) }
cachedSaxBuilder.set(SoftReference<SAXBuilder>(saxBuilder))
}
return saxBuilder
}
@JvmOverloads
@Throws(IOException::class)
fun Parent.write(file: Path, lineSeparator: String = "\n", filter: JDOMUtil.ElementOutputFilter? = null) {
write(file.outputStream(), lineSeparator, filter)
}
@JvmOverloads
fun Parent.write(output: OutputStream, lineSeparator: String = "\n", filter: JDOMUtil.ElementOutputFilter? = null) {
output.bufferedWriter().use { writer ->
if (this is Document) {
JDOMUtil.writeDocument(this, writer, lineSeparator)
}
else {
JDOMUtil.writeElement(this as Element, writer, JDOMUtil.createOutputter(lineSeparator, filter))
}
}
}
@Throws(IOException::class, JDOMException::class)
fun loadElement(chars: CharSequence) = loadElement(CharSequenceReader(chars))
@Throws(IOException::class, JDOMException::class)
fun loadElement(reader: Reader): Element = loadDocument(reader).detachRootElement()
@Throws(IOException::class, JDOMException::class)
fun loadElement(stream: InputStream): Element = loadDocument(stream.reader()).detachRootElement()
@Throws(IOException::class, JDOMException::class)
fun loadElement(path: Path): Element = loadDocument(path.inputStream().bufferedReader()).detachRootElement()
fun loadDocument(reader: Reader): Document = reader.use { getSaxBuilder().build(it) }
fun Element?.isEmpty() = this == null || JDOMUtil.isEmpty(this)
fun Element.getOrCreate(name: String): Element {
var element = getChild(name)
if (element == null) {
element = Element(name)
addContent(element)
}
return element
}
fun Element.get(name: String): Element? = getChild(name)
fun Element.element(name: String): Element {
val element = Element(name)
addContent(element)
return element
}
fun Element.attribute(name: String, value: String?): Element = setAttribute(name, value)
fun <T> Element.remove(name: String, transform: (child: Element) -> T): List<T> {
val result = SmartList<T>()
val groupIterator = getContent(ElementFilter(name)).iterator()
while (groupIterator.hasNext()) {
val child = groupIterator.next()
result.add(transform(child))
groupIterator.remove()
}
return result
}
fun Element.toByteArray(): ByteArray {
val out = BufferExposingByteArrayOutputStream(512)
JDOMUtil.write(this, out, "\n")
return out.toByteArray()
}
fun Element.addOptionTag(name: String, value: String) {
val element = Element("option")
element.setAttribute("name", name)
element.setAttribute("value", value)
addContent(element)
}
fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream {
val out = BufferExposingByteArrayOutputStream(512)
JDOMUtil.write(this, out, lineSeparator)
return out
}
fun Element.getAttributeBooleanValue(name: String): Boolean = java.lang.Boolean.parseBoolean(getAttributeValue(name))
|
apache-2.0
|
2e0352058a7419afe1d8041822c38c95
| 33.549618 | 140 | 0.756464 | 4.236891 | false | false | false | false |
exponentjs/exponent
|
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/sensors/modules/AccelerometerModule.kt
|
2
|
1899
|
// Copyright 2015-present 650 Industries. All rights reserved.
package abi44_0_0.expo.modules.sensors.modules
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorManager
import android.os.Bundle
import abi44_0_0.expo.modules.interfaces.sensors.SensorServiceInterface
import abi44_0_0.expo.modules.interfaces.sensors.services.AccelerometerServiceInterface
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.interfaces.ExpoMethod
class AccelerometerModule(reactContext: Context?) : BaseSensorModule(reactContext) {
override val eventName: String = "accelerometerDidUpdate"
override fun getName(): String = "ExponentAccelerometer"
override fun getSensorService(): SensorServiceInterface {
return moduleRegistry.getModule(AccelerometerServiceInterface::class.java)
}
override fun eventToMap(sensorEvent: SensorEvent): Bundle {
return Bundle().apply {
putDouble("x", (sensorEvent.values[0] / SensorManager.GRAVITY_EARTH).toDouble())
putDouble("y", (sensorEvent.values[1] / SensorManager.GRAVITY_EARTH).toDouble())
putDouble("z", (sensorEvent.values[2] / SensorManager.GRAVITY_EARTH).toDouble())
}
}
@ExpoMethod
fun startObserving(promise: Promise) {
super.startObserving()
promise.resolve(null)
}
@ExpoMethod
fun stopObserving(promise: Promise) {
super.stopObserving()
promise.resolve(null)
}
@ExpoMethod
fun setUpdateInterval(updateInterval: Int, promise: Promise) {
super.setUpdateInterval(updateInterval)
promise.resolve(null)
}
@ExpoMethod
fun isAvailableAsync(promise: Promise) {
val mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val isAvailable = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null
promise.resolve(isAvailable)
}
}
|
bsd-3-clause
|
863bed907e4ef5be9b6d0a8fe07050a1
| 33.527273 | 90 | 0.771985 | 4.32574 | false | false | false | false |
square/wire
|
wire-library/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/internal/JvmLanguages.kt
|
1
|
7104
|
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("JvmLanguages")
package com.squareup.wire.schema.internal
import com.squareup.wire.ProtoAdapter
import com.squareup.wire.internal.camelCase
import com.squareup.wire.schema.EnumType
import com.squareup.wire.schema.Extend
import com.squareup.wire.schema.Field
import com.squareup.wire.schema.Options
import com.squareup.wire.schema.ProtoFile
import com.squareup.wire.schema.ProtoType
import com.squareup.wire.schema.Schema
import com.squareup.wire.schema.Type
import java.lang.NullPointerException
import java.lang.annotation.ElementType
import java.math.BigInteger
import java.util.Locale
/*
* This file contains logic common to code generators targeting the JVM: Kotlin and Java. It's
* useful to keep these consistent because sometimes a schema will be generated with some parts in
* one language and other parts in another language.
*/
fun builtInAdapterString(type: ProtoType): String? {
if (type.isScalar) {
return "${ProtoAdapter::class.java.name}#${type.toString().uppercase(Locale.US)}"
}
return when (type) {
ProtoType.DURATION -> ProtoAdapter::class.java.name + "#DURATION"
ProtoType.TIMESTAMP -> ProtoAdapter::class.java.name + "#INSTANT"
ProtoType.EMPTY -> ProtoAdapter::class.java.name + "#EMPTY"
ProtoType.STRUCT_MAP -> ProtoAdapter::class.java.name + "#STRUCT_MAP"
ProtoType.STRUCT_VALUE -> ProtoAdapter::class.java.name + "#STRUCT_VALUE"
ProtoType.STRUCT_NULL -> ProtoAdapter::class.java.name + "#STRUCT_NULL"
ProtoType.STRUCT_LIST -> ProtoAdapter::class.java.name + "#STRUCT_LIST"
ProtoType.DOUBLE_VALUE -> ProtoAdapter::class.java.name + "#DOUBLE_VALUE"
ProtoType.FLOAT_VALUE -> ProtoAdapter::class.java.name + "#FLOAT_VALUE"
ProtoType.INT64_VALUE -> ProtoAdapter::class.java.name + "#INT64_VALUE"
ProtoType.UINT64_VALUE -> ProtoAdapter::class.java.name + "#UINT64_VALUE"
ProtoType.INT32_VALUE -> ProtoAdapter::class.java.name + "#INT32_VALUE"
ProtoType.UINT32_VALUE -> ProtoAdapter::class.java.name + "#UINT32_VALUE"
ProtoType.BOOL_VALUE -> ProtoAdapter::class.java.name + "#BOOL_VALUE"
ProtoType.STRING_VALUE -> ProtoAdapter::class.java.name + "#STRING_VALUE"
ProtoType.BYTES_VALUE -> ProtoAdapter::class.java.name + "#BYTES_VALUE"
else -> null
}
}
fun eligibleAsAnnotationMember(schema: Schema, field: Field): Boolean {
val type = field.type!!
if (type == ProtoType.BYTES) {
return false
}
if (!type.isScalar && schema.getType(type) !is EnumType) {
return false
}
val qualifiedName = field.qualifiedName
if (qualifiedName.startsWith("google.protobuf.")
|| qualifiedName.startsWith("wire.")) {
return false // Don't emit annotations for packed, since, etc.
}
if (field.name == "redacted") {
return false // Redacted is built-in.
}
return true
}
fun annotationTargetType(extend: Extend): ElementType? {
return when (extend.type!!) {
Options.MESSAGE_OPTIONS, Options.ENUM_OPTIONS, Options.SERVICE_OPTIONS -> ElementType.TYPE
Options.FIELD_OPTIONS, Options.ENUM_VALUE_OPTIONS -> ElementType.FIELD
Options.METHOD_OPTIONS -> ElementType.METHOD
else -> null
}
}
fun optionValueToInt(value: Any?): Int {
if (value == null) return 0
val string = value.toString()
return when {
// Hexadecimal.
string.startsWith("0x") || string.startsWith("0X") -> string.substring("0x".length).toInt(16)
// Octal.
string.startsWith("0") && string != "0" -> error("Octal literal unsupported: $value")
// Decimal.
else -> BigInteger(string).toInt()
}
}
fun optionValueToLong(value: Any?): Long {
if (value == null) return 0L
val string = value.toString()
return when {
// Hexadecimal.
string.startsWith("0x") || string.startsWith("0X") -> string.substring("0x".length).toLong(16)
// Octal.
string.startsWith("0") && string != "0" -> error("Octal literal unsupported: $value")
// Decimal.
else -> BigInteger(string).toLong()
}
}
fun javaPackage(protoFile: ProtoFile): String {
val wirePackage = protoFile.wirePackage()
if (wirePackage != null) return wirePackage
val javaPackage = protoFile.javaPackage()
if (javaPackage != null) return javaPackage
return protoFile.packageName ?: ""
}
fun hasEponymousType(schema: Schema, field: Field): Boolean {
// See if the package in which the field is defined already has a
// type by the same name. If so, the field and type name may collide.
return schema.getType(legacyQualifiedFieldName(field)) != null
// TODO: This is likely incomplete. Ideally, we could search for
// symbols in the generated Java/Kotlin code to find conflicts based
// on the actual lexical scope in which the field is defined. And
// even then, instead of mangling the field name, we could instead
// use fully-qualified references to the types.
}
fun legacyQualifiedFieldName(field: Field): String {
// for backwards compatibility with older generated code, we use
// package name + field name instead of the fully-qualified name.
return when {
field.packageName.isBlank() -> field.name
else -> "${field.packageName}.${field.name}"
}
// TODO: If a qualified name is really appropriate, it should
// be the fully-qualified name, not this weird hybrid.
}
fun <T> annotationName(protoFile: ProtoFile, extension: Field, factory: NameFactory<T>): T {
val simpleName = camelCase(extension.name, true) + "Option"
// collect class names: all enclosing message names plus simpleName
var names = when (extension.namespaces.size) {
// 0 means no package and no enclosing messages
// 1 means a package, but no enclosing messages
0, 1 -> listOf(simpleName)
// 2 or more: first is a package name, the rest are enclosing messages
else -> extension.namespaces.subList(1, extension.namespaces.size).plus(simpleName)
}
// we know that names has at least one element (simpleName), so the loop
// below will produce a non-null type
var type: T? = null
for (n in names) {
type = if (type == null) {
factory.newName(javaPackage(protoFile), n)
} else {
factory.nestedName(type, n)
}
}
if (type == null) {
// should not be possible; keeping compiler happy
throw NullPointerException()
}
return type
}
/** NameFactory is an abstraction for creating language-specific (Java vs Kotlin) type names. */
interface NameFactory<T> {
fun newName(packageName: String, simpleName: String): T
fun nestedName(enclosing: T, simpleName: String): T
}
|
apache-2.0
|
0674b3f07791c13282121f4efd438c32
| 35.430769 | 98 | 0.711571 | 3.975378 | false | false | false | false |
PolymerLabs/arcs
|
java/arcs/core/data/Schema.kt
|
1
|
4349
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data
import arcs.core.crdt.CrdtEntity
import arcs.core.data.Schema.Companion.hashCode
import arcs.core.data.expression.Expression
import arcs.core.data.expression.asExpr
import arcs.core.data.expression.asScope
import arcs.core.data.expression.evalExpression
import arcs.core.type.Type
/** Returns true if the RawEntity data matches the refinement predicate */
typealias Refinement = (data: RawEntity) -> Boolean
/** Returns true if the RawEntity data matches the query predicate (given a query argument) */
typealias Query = (data: RawEntity, queryArgs: Any) -> Boolean
data class Schema(
val names: Set<SchemaName>,
val fields: SchemaFields,
/**
* The hash code for the schema (note that this is not the same as this object's [hashCode]
* method.
*/
val hash: String,
val refinementExpression: Expression<Boolean> = true.asExpr(),
val queryExpression: Expression<Boolean> = true.asExpr()
) {
private val hashCode by lazy {
var result = names.hashCode()
result = 31 * result + fields.hashCode()
result = 31 * result + hash.hashCode()
result = 31 * result + refinementExpression.hashCode()
result = 31 * result + queryExpression.hashCode()
result
}
/** Ensure instance is registered on construction. */
init {
SchemaRegistry.register(this)
}
val name: SchemaName?
get() = names.firstOrNull()
private val emptyRawEntity: RawEntity
get() = RawEntity(
singletonFields = fields.singletons.keys,
collectionFields = fields.collections.keys
)
val refinement: Refinement = { rawEntity ->
evalExpression(refinementExpression, rawEntity.asScope())
}
val query: Query? = { data, args ->
evalExpression(queryExpression, data.asScope(), "queryArgument" to args)
}
fun toLiteral(): Literal = Literal(names, fields, hash, refinementExpression, queryExpression)
fun createCrdtEntityModel(): CrdtEntity = CrdtEntity.newWithEmptyEntity(emptyRawEntity)
override fun toString() = toString(Type.ToStringOptions())
/**
* @param options granular options, e.g. whether to list Schema fields.
*/
fun toString(options: Type.ToStringOptions) =
names.map { it.name }.plusElement(fields.toString(options)).joinToString(" ")
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Schema) return false
if (names != other.names) return false
if (fields != other.fields) return false
if (hash != other.hash) return false
if (refinementExpression != other.refinementExpression) return false
if (queryExpression != other.queryExpression) return false
return true
}
override fun hashCode(): Int = hashCode
data class Literal(
val names: Set<SchemaName>,
val fields: SchemaFields,
val hash: String,
val refinementExpression: Expression<Boolean>,
val queryExpression: Expression<Boolean>
) : arcs.core.common.Literal {
fun toJson(): String {
// TODO: Actually use a json serializer when we're ready for it.
return "{\"names\":[\"${names.joinToString { "\"$it\"" }}\"]}"
}
}
companion object {
/** Hydrates a [Schema] instance from a [Literal]. */
fun fromLiteral(literal: arcs.core.common.Literal): Schema {
val schemaLiteral = requireNotNull(literal as? Literal) {
"Cannot interpret Schema from a non-Schema Literal"
}
return Schema(
schemaLiteral.names,
schemaLiteral.fields,
schemaLiteral.hash,
schemaLiteral.refinementExpression,
schemaLiteral.queryExpression
)
}
val EMPTY = Schema(
setOf(),
SchemaFields(emptyMap(), emptyMap()),
// Calculated from TypeScript's Schema.hash() function for an empty schema.
"42099b4af021e53fd8fd4e056c2568d7c2e3ffa8"
)
}
}
/** Defines a [Type] that's capable of providing a schema for its entities. */
interface EntitySchemaProviderType : Type {
/** [Schema] for the entity/entities managed by this [Type]. */
val entitySchema: Schema?
}
|
bsd-3-clause
|
d8d11c9acd5bc90c61633bbb1942257f
| 30.28777 | 96 | 0.697862 | 4.218235 | false | false | false | false |
yyYank/Kebab
|
src/main/kotlin/Factories.kt
|
1
|
3562
|
package kebab
import kebab.core.Browser
import kebab.core.PageContentTemplate
import kebab.locator.DefaultLocator
import kebab.locator.EmptyLocator
import kebab.locator.Locator
import kebab.locator.SearchContextBasedBasicLocator
import kebab.navigator.EmptyNavigator
import kebab.navigator.Navigate
import kebab.navigator.Navigator
import kebab.navigator.NonEmptyNavigator
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import java.util.*
/**
* Created by yy_yank on 2015/12/19.
*/
interface NavigatorFactory {
val innerNavigatorFactory: InnerNavigatorFactory
fun getBase(): Navigator?
fun getLocator(): Locator
fun createFromWebElements(elements: Iterable<WebElement>): Navigator?
fun createFromNavigators(navigators: Iterable<Navigate>): Navigator
fun relativeTo(newBase: Navigator): NavigatorFactory
}
class BrowserBackedNavigatorFactory(browser: Browser, innerNavigatorFactory: InnerNavigatorFactory) : AbstractNavigatorFactory(browser, innerNavigatorFactory) {
val locator = DefaultLocator(SearchContextBasedBasicLocator(browser.config.driver, this))
val baseTagName = "html"
override fun createFromNavigators(navigators: Iterable<Navigate>): Navigator {
throw UnsupportedOperationException()
}
override fun getLocator(): Locator = locator
fun createBase(): Navigator? =
createFromWebElements(Collections.singletonList(browser.config.driver.findElement(By.tagName(baseTagName))))
override fun getBase(): Navigator? = createBase()
}
abstract class AbstractNavigatorFactory(val browser: Browser, override val innerNavigatorFactory: InnerNavigatorFactory) : NavigatorFactory {
override fun createFromWebElements(elements: Iterable<WebElement>): Navigator? {
val filtered = ArrayList<WebElement>()
elements.asSequence().forEach { filtered.add(it) }
return innerNavigatorFactory.createNavigator(browser, filtered)
}
override fun relativeTo(newBase: Navigator): NavigatorFactory = NavigatorBackedNavigatorFactory(newBase, innerNavigatorFactory)
}
class NavigatorBackedNavigatorFactory(newBase: Navigator, innerNavigatorFactory: InnerNavigatorFactory) : NavigatorFactory {
// TODO UnsupportedOperationExceptionの山
override val innerNavigatorFactory: InnerNavigatorFactory
get() = throw UnsupportedOperationException()
override fun getBase(): Navigator? {
throw UnsupportedOperationException()
}
override fun getLocator(): Locator {
throw UnsupportedOperationException()
}
override fun createFromWebElements(elements: Iterable<WebElement>): Navigator? {
throw UnsupportedOperationException()
}
override fun createFromNavigators(navigators: Iterable<Navigate>): Navigator {
throw UnsupportedOperationException()
}
override fun relativeTo(newBase: Navigator): NavigatorFactory {
throw UnsupportedOperationException()
}
}
interface InnerNavigatorFactory {
fun createNavigator(browser: Browser, filtered: ArrayList<WebElement>): Navigator?
}
class DefaultInnerNavigatorFactory : InnerNavigatorFactory {
override fun createNavigator(browser: Browser, elements: ArrayList<WebElement>): Navigator? {
return if (elements != null) {
NonEmptyNavigator(browser, elements, EmptyLocator())
} else {
EmptyNavigator(browser, elements, EmptyLocator())
}
}
}
class PageContentTemplateFactoryDelegate(pageContentTemplate: PageContentTemplate, args: Array<Any>) {
}
|
apache-2.0
|
17757413ea21c0bffff747fc15d0b9af
| 32.261682 | 160 | 0.765599 | 5.490741 | false | false | false | false |
JetBrains/ideavim
|
src/main/java/com/maddyhome/idea/vim/listener/VimListenerManager.kt
|
1
|
22821
|
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.listener
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.trace
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.actionSystem.TypedAction
import com.intellij.openapi.editor.event.CaretEvent
import com.intellij.openapi.editor.event.CaretListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.event.EditorMouseEvent
import com.intellij.openapi.editor.event.EditorMouseEventArea
import com.intellij.openapi.editor.event.EditorMouseListener
import com.intellij.openapi.editor.event.EditorMouseMotionListener
import com.intellij.openapi.editor.event.SelectionEvent
import com.intellij.openapi.editor.event.SelectionListener
import com.intellij.openapi.editor.ex.DocumentEx
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.rd.createLifetime
import com.intellij.openapi.rd.createNestedDisposable
import com.intellij.openapi.util.Disposer
import com.intellij.util.ExceptionUtil
import com.jetbrains.rd.util.lifetime.intersect
import com.maddyhome.idea.vim.EventFacade
import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimKeyListener
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.VimTypedActionHandler
import com.maddyhome.idea.vim.api.getLineEndForOffset
import com.maddyhome.idea.vim.api.getLineStartForOffset
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.ex.ExOutputModel
import com.maddyhome.idea.vim.group.EditorGroup
import com.maddyhome.idea.vim.group.FileGroup
import com.maddyhome.idea.vim.group.MotionGroup
import com.maddyhome.idea.vim.group.SearchGroup
import com.maddyhome.idea.vim.group.visual.IdeaSelectionControl
import com.maddyhome.idea.vim.group.visual.VimVisualTimer
import com.maddyhome.idea.vim.group.visual.moveCaretOneCharLeftFromSelectionEnd
import com.maddyhome.idea.vim.group.visual.vimSetSystemSelectionSilently
import com.maddyhome.idea.vim.helper.GuicursorChangeListener
import com.maddyhome.idea.vim.helper.UpdatesChecker
import com.maddyhome.idea.vim.helper.exitSelectMode
import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.helper.forceBarCursor
import com.maddyhome.idea.vim.helper.inSelectMode
import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.helper.isEndAllowed
import com.maddyhome.idea.vim.helper.isIdeaVimDisabledHere
import com.maddyhome.idea.vim.helper.localEditors
import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset
import com.maddyhome.idea.vim.helper.subMode
import com.maddyhome.idea.vim.helper.updateCaretsVisualAttributes
import com.maddyhome.idea.vim.helper.vimDisabled
import com.maddyhome.idea.vim.listener.MouseEventsDataHolder.skipEvents
import com.maddyhome.idea.vim.listener.MouseEventsDataHolder.skipNDragEvents
import com.maddyhome.idea.vim.listener.VimListenerManager.EditorListeners.add
import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.helpers.KeywordOptionChangeListener
import com.maddyhome.idea.vim.options.helpers.StrictMode
import com.maddyhome.idea.vim.ui.ShowCmdOptionChangeListener
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.SwingUtilities
/**
* @author Alex Plate
*/
object VimListenerManager {
private val logger = Logger.getInstance(VimListenerManager::class.java)
fun turnOn() {
GlobalListeners.enable()
EditorListeners.addAll()
}
fun turnOff() {
GlobalListeners.disable()
EditorListeners.removeAll()
}
object GlobalListeners {
fun enable() {
val typedAction = TypedAction.getInstance()
if (typedAction.rawHandler !is VimTypedActionHandler) {
// Actually this if should always be true, but just as protection
EventFacade.getInstance().setupTypedActionHandler(VimTypedActionHandler(typedAction.rawHandler))
} else {
StrictMode.fail("typeAction expected to be non-vim.")
}
VimPlugin.getOptionService().addListener(OptionConstants.numberName, EditorGroup.NumberChangeListener.INSTANCE)
VimPlugin.getOptionService().addListener(OptionConstants.relativenumberName, EditorGroup.NumberChangeListener.INSTANCE)
VimPlugin.getOptionService().addListener(OptionConstants.scrolloffName, MotionGroup.ScrollOptionsChangeListener.INSTANCE)
VimPlugin.getOptionService().addListener(OptionConstants.showcmdName, ShowCmdOptionChangeListener)
VimPlugin.getOptionService().addListener(OptionConstants.guicursorName, GuicursorChangeListener)
VimPlugin.getOptionService().addListener(OptionConstants.iskeywordName, KeywordOptionChangeListener, true)
EventFacade.getInstance().addEditorFactoryListener(VimEditorFactoryListener, VimPlugin.getInstance().onOffDisposable)
EditorFactory.getInstance().eventMulticaster.addCaretListener(VimCaretListener, VimPlugin.getInstance().onOffDisposable)
}
fun disable() {
EventFacade.getInstance().restoreTypedActionHandler()
VimPlugin.getOptionService().removeListener(OptionConstants.numberName, EditorGroup.NumberChangeListener.INSTANCE)
VimPlugin.getOptionService().removeListener(OptionConstants.relativenumberName, EditorGroup.NumberChangeListener.INSTANCE)
VimPlugin.getOptionService().removeListener(OptionConstants.scrolloffName, MotionGroup.ScrollOptionsChangeListener.INSTANCE)
VimPlugin.getOptionService().removeListener(OptionConstants.showcmdName, ShowCmdOptionChangeListener)
VimPlugin.getOptionService().removeListener(OptionConstants.guicursorName, GuicursorChangeListener)
VimPlugin.getOptionService().removeListener(OptionConstants.iskeywordName, KeywordOptionChangeListener)
}
}
object EditorListeners {
fun addAll() {
localEditors().forEach { editor ->
this.add(editor)
}
}
fun removeAll() {
localEditors().forEach { editor ->
this.remove(editor, false)
}
}
fun add(editor: Editor) {
val pluginLifetime = VimPlugin.getInstance().createLifetime()
val editorLifetime = (editor as EditorImpl).disposable.createLifetime()
val disposable = editorLifetime.intersect(pluginLifetime).createNestedDisposable("MyLifetimedDisposable")
editor.contentComponent.addKeyListener(VimKeyListener)
Disposer.register(disposable) { editor.contentComponent.removeKeyListener(VimKeyListener) }
val eventFacade = EventFacade.getInstance()
eventFacade.addEditorMouseListener(editor, EditorMouseHandler, disposable)
eventFacade.addEditorMouseMotionListener(editor, EditorMouseHandler, disposable)
eventFacade.addEditorSelectionListener(editor, EditorSelectionHandler, disposable)
eventFacade.addComponentMouseListener(editor.contentComponent, ComponentMouseListener, disposable)
VimPlugin.getEditor().editorCreated(editor)
VimPlugin.getChange().editorCreated(editor, disposable)
Disposer.register(disposable) {
VimPlugin.getEditorIfCreated()?.editorDeinit(editor, true)
}
}
fun remove(editor: Editor, isReleased: Boolean) {
editor.contentComponent.removeKeyListener(VimKeyListener)
val eventFacade = EventFacade.getInstance()
eventFacade.removeEditorMouseListener(editor, EditorMouseHandler)
eventFacade.removeEditorMouseMotionListener(editor, EditorMouseHandler)
eventFacade.removeEditorSelectionListener(editor, EditorSelectionHandler)
eventFacade.removeComponentMouseListener(editor.contentComponent, ComponentMouseListener)
VimPlugin.getEditorIfCreated()?.editorDeinit(editor, isReleased)
VimPlugin.getChange().editorReleased(editor)
}
}
object VimCaretListener : CaretListener {
override fun caretAdded(event: CaretEvent) {
if (vimDisabled(event.editor)) return
event.editor.updateCaretsVisualAttributes()
}
override fun caretRemoved(event: CaretEvent) {
if (vimDisabled(event.editor)) return
event.editor.updateCaretsVisualAttributes()
}
}
class VimFileEditorManagerListener : FileEditorManagerListener {
override fun selectionChanged(event: FileEditorManagerEvent) {
if (!VimPlugin.isEnabled()) return
MotionGroup.fileEditorManagerSelectionChangedCallback(event)
FileGroup.fileEditorManagerSelectionChangedCallback(event)
SearchGroup.fileEditorManagerSelectionChangedCallback(event)
}
}
private object VimEditorFactoryListener : EditorFactoryListener {
override fun editorCreated(event: EditorFactoryEvent) {
add(event.editor)
UpdatesChecker.check()
}
override fun editorReleased(event: EditorFactoryEvent) {
VimPlugin.getMark().editorReleased(event)
}
}
private object EditorSelectionHandler : SelectionListener {
private var myMakingChanges = false
/**
* This event is executed for each caret using [com.intellij.openapi.editor.CaretModel.runForEachCaret]
*/
override fun selectionChanged(selectionEvent: SelectionEvent) {
if (selectionEvent.editor.isIdeaVimDisabledHere) return
val editor = selectionEvent.editor
val document = editor.document
logger.trace { "Selection changed" }
logger.trace { ExceptionUtil.currentStackTrace() }
//region Not selected last character protection
// Here is currently a bug in IJ for IdeaVim. If you start selection right from the line end, then
// move to the left, the last character remains unselected.
// It's not clear why this happens, but this code fixes it.
val caret = editor.caretModel.currentCaret
val lineEnd = IjVimEditor(editor).getLineEndForOffset(caret.offset)
val lineStart = IjVimEditor(editor).getLineStartForOffset(caret.offset)
if (skipNDragEvents < skipEvents &&
lineEnd != lineStart &&
selectionEvent.newRange.startOffset == selectionEvent.newRange.endOffset &&
selectionEvent.newRange.startOffset == lineEnd - 1 &&
selectionEvent.newRange.startOffset == caret.offset
) {
caret.setSelection(lineEnd, lineEnd - 1)
}
//endregion
if (SelectionVimListenerSuppressor.isNotLocked) {
logger.debug("Adjust non vim selection change")
IdeaSelectionControl.controlNonVimSelectionChange(editor)
}
if (myMakingChanges || document is DocumentEx && document.isInEventsHandling) {
return
}
myMakingChanges = true
try {
// Synchronize selections between editors
val newRange = selectionEvent.newRange
for (e in localEditors(document)) {
if (e != editor) {
e.selectionModel.vimSetSystemSelectionSilently(newRange.startOffset, newRange.endOffset)
}
}
} finally {
myMakingChanges = false
}
}
}
private object EditorMouseHandler : EditorMouseListener, EditorMouseMotionListener {
private var mouseDragging = false
private var cutOffFixed = false
override fun mouseDragged(e: EditorMouseEvent) {
if (e.editor.isIdeaVimDisabledHere) return
val caret = e.editor.caretModel.primaryCaret
clearFirstSelectionEvents(e)
if (mouseDragging && caret.hasSelection()) {
/**
* We force the bar caret while dragging because it matches IntelliJ's selection model better.
* * Vim's drag selection is based on character bounding boxes. When 'selection' is set to "inclusive" (the
* default), Vim selects a character when the mouse cursor drags the text caret into its bounding box (LTR).
* The character at the text caret is selected and the block caret is drawn to cover the character (the bar
* caret would be between the selection and the last character of the selection, which is weird). See "v" in
* 'guicursor'. When 'selection' is "exclusive", Vim will select a character when the mouse cursor drags the
* text caret out of its bounding box. The character at the text caret is not selected and the bar caret is
* drawn at the start of this character to make it more obvious that it is unselected. See "ve" in
* 'guicursor'.
* * IntelliJ's selection is based on character mid-points. E.g. the caret is moved to the start of offset 2
* when the second half of offset 1 is clicked, and a character is selected when the mouse is moved from the
* first half to the second half. This means:
* 1) While dragging, the selection is always exclusive - the character at the text caret is not selected. We
* convert to an inclusive selection when the mouse is released, by moving back one character. It makes
* sense to match Vim's bar caret here.
* 2) An exclusive selection should trail behind the mouse cursor, but IntelliJ doesn't, because the selection
* boundaries are mid-points - the text caret can be in front of/to the right of the mouse cursor (LTR).
* Using a block caret would push the block further out passed the selection and the mouse cursor, and
* feels wrong. The bar caret is a better user experience.
* RTL probably introduces other fun issues
* We can implement inclusive/exclusive 'selection' with normal text movement, but unless we can change the way
* selection works while dragging, I don't think we can match Vim's selection behaviour exactly.
*/
caret.forceBarCursor()
if (!cutOffFixed && ComponentMouseListener.cutOffEnd) {
cutOffFixed = true
SelectionVimListenerSuppressor.lock().use {
if (caret.selectionEnd == e.editor.document.getLineEndOffset(caret.logicalPosition.line) - 1 &&
caret.leadSelectionOffset == caret.selectionEnd
) {
// A small but important customization. Because IdeaVim doesn't allow to put the caret on the line end,
// the selection can omit the last character if the selection was started in the middle on the
// last character in line and has a negative direction.
caret.setSelection(caret.selectionStart, caret.selectionEnd + 1)
}
// This is the same correction, but for the newer versions of the IDE: 213+
if (caret.selectionEnd == e.editor.document.getLineEndOffset(caret.logicalPosition.line) &&
caret.selectionEnd == caret.selectionStart + 1
) {
caret.setSelection(caret.selectionEnd, caret.selectionEnd)
}
}
}
}
skipNDragEvents -= 1
}
/**
* When user places the caret, sometimes they perform a small drag. This doesn't affect clear IJ, but with IdeaVim
* it may introduce unwanted selection. Here we remove any selection if "dragging" happens for less than 3 events.
* This is because the first click moves the caret passed the end of the line, is then received in
* [ComponentMouseListener] and the caret is moved back to the start of the last character of the line. If there is
* a drag, this translates to a selection of the last character. In this case, remove the selection.
* We force the bar caret simply because it looks better - the block caret is dragged to the end, becomes a less
* intrusive bar caret and snaps back to the last character (and block caret) when the mouse is released.
* TODO: Vim supports selection of the character after the end of line
* (Both with mouse and with v$. IdeaVim treats v$ as an exclusive selection)
*/
private fun clearFirstSelectionEvents(e: EditorMouseEvent) {
if (skipNDragEvents > 0) {
logger.debug("Mouse dragging")
VimVisualTimer.swingTimer?.stop()
if (!mouseDragging) {
SelectionVimListenerSuppressor.lock()
}
mouseDragging = true
val caret = e.editor.caretModel.primaryCaret
if (onLineEnd(caret)) {
SelectionVimListenerSuppressor.lock().use {
caret.removeSelection()
caret.forceBarCursor()
}
}
}
}
private fun onLineEnd(caret: Caret): Boolean {
val editor = caret.editor
val lineEnd = IjVimEditor(editor).getLineEndForOffset(caret.offset)
val lineStart = IjVimEditor(editor).getLineStartForOffset(caret.offset)
return caret.offset == lineEnd && lineEnd != lineStart && caret.offset - 1 == caret.selectionStart && caret.offset == caret.selectionEnd
}
override fun mousePressed(event: EditorMouseEvent) {
if (event.editor.isIdeaVimDisabledHere) return
skipNDragEvents = skipEvents
SelectionVimListenerSuppressor.reset()
}
/**
* This method may not be called
* Known cases:
* - Click-hold and close editor (ctrl-w)
* - Click-hold and switch editor (ctrl-tab)
*/
override fun mouseReleased(event: EditorMouseEvent) {
if (event.editor.isIdeaVimDisabledHere) return
SelectionVimListenerSuppressor.unlock()
clearFirstSelectionEvents(event)
skipNDragEvents = skipEvents
if (mouseDragging) {
logger.debug("Release mouse after dragging")
val editor = event.editor
val caret = editor.caretModel.primaryCaret
SelectionVimListenerSuppressor.lock().use {
val predictedMode = IdeaSelectionControl.predictMode(editor, SelectionSource.MOUSE)
IdeaSelectionControl.controlNonVimSelectionChange(editor, SelectionSource.MOUSE)
// TODO: This should only be for 'selection'=inclusive
moveCaretOneCharLeftFromSelectionEnd(editor, predictedMode)
// Reset caret after forceBarShape while dragging
editor.updateCaretsVisualAttributes()
}
mouseDragging = false
cutOffFixed = false
}
}
override fun mouseClicked(event: EditorMouseEvent) {
if (event.editor.isIdeaVimDisabledHere) return
logger.debug("Mouse clicked")
if (event.area == EditorMouseEventArea.EDITING_AREA) {
VimPlugin.getMotion()
val editor = event.editor
if (ExEntryPanel.getInstance().isActive) {
VimPlugin.getProcess().cancelExEntry(editor.vim, false)
}
ExOutputModel.getInstance(editor).clear()
val caretModel = editor.caretModel
if (editor.subMode != VimStateMachine.SubMode.NONE) {
caretModel.removeSecondaryCarets()
}
// Removing selection on just clicking.
//
// Actually, this event should not be fired on right click (when the menu appears), but since 202 it happens
// sometimes. To prevent unwanted selection removing, an assertion for isRightClick was added.
// See:
// https://youtrack.jetbrains.com/issue/IDEA-277716
// https://youtrack.jetbrains.com/issue/VIM-2368
if (event.mouseEvent.clickCount == 1 && !SwingUtilities.isRightMouseButton(event.mouseEvent)) {
if (editor.inVisualMode) {
editor.vim.exitVisualMode()
} else if (editor.inSelectMode) {
editor.exitSelectMode(false)
KeyHandler.getInstance().reset(editor.vim)
}
}
} else if (event.area != EditorMouseEventArea.ANNOTATIONS_AREA &&
event.area != EditorMouseEventArea.FOLDING_OUTLINE_AREA &&
event.mouseEvent.button != MouseEvent.BUTTON3
) {
VimPlugin.getMotion()
if (ExEntryPanel.getInstance().isActive) {
VimPlugin.getProcess().cancelExEntry(event.editor.vim, false)
}
ExOutputModel.getInstance(event.editor).clear()
}
}
}
private object ComponentMouseListener : MouseAdapter() {
var cutOffEnd = false
override fun mousePressed(e: MouseEvent?) {
val editor = (e?.component as? EditorComponentImpl)?.editor ?: return
if (editor.isIdeaVimDisabledHere) return
val predictedMode = IdeaSelectionControl.predictMode(editor, SelectionSource.MOUSE)
when (e.clickCount) {
1 -> {
// If you click after the line, the caret is placed by IJ after the last symbol.
// This is not allowed in some vim modes, so we move the caret over the last symbol.
if (!predictedMode.isEndAllowed) {
@Suppress("ideavimRunForEachCaret")
editor.caretModel.runForEachCaret { caret ->
val lineEnd = IjVimEditor(editor).getLineEndForOffset(caret.offset)
val lineStart = IjVimEditor(editor).getLineStartForOffset(caret.offset)
cutOffEnd = if (caret.offset == lineEnd && lineEnd != lineStart) {
caret.moveToInlayAwareOffset(caret.offset - 1)
true
} else {
false
}
}
} else cutOffEnd = false
}
// Double-clicking a word in IntelliJ will select the word and locate the caret at the end of the selection,
// on the following character. When using a bar caret, this is drawn as between the end of selection and the
// following char. With a block caret, this draws the caret "over" the following character.
// In Vim, when 'selection' is "inclusive" (default), double clicking a word will select the last character of
// the word and leave the caret on the last character, drawn as a block caret. We move one character left to
// match this behaviour.
// When 'selection' is exclusive, the caret is placed *after* the end of the word, and is drawn using the 've'
// option of 'guicursor' - as a bar, so it appears to be in between the end of the word and the start of the
// following character.
// TODO: Modify this to support 'selection' set to "exclusive"
2 -> moveCaretOneCharLeftFromSelectionEnd(editor, predictedMode)
}
}
}
enum class SelectionSource {
MOUSE,
OTHER
}
}
private object MouseEventsDataHolder {
const val skipEvents = 3
var skipNDragEvents = skipEvents
}
|
mit
|
b7b232978e98756ce38ae413646af5de
| 44.100791 | 142 | 0.724377 | 4.903524 | false | false | false | false |
KotlinNLP/SimpleDNN
|
src/test/kotlin/core/layers/merge/biaffine/BiaffineLayerStructureSpec.kt
|
1
|
4169
|
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain contexte at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.layers.merge.biaffine
import com.kotlinnlp.simplednn.core.optimizer.getErrorsOf
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertTrue
/**
*
*/
class BiaffineLayerStructureSpec : Spek({
describe("a BiaffineLayer") {
context("forward") {
val layer = BiaffineLayerUtils.buildLayer()
layer.forward()
it("should match the expected outputArray") {
assertTrue {
layer.outputArray.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.714345, -0.161572)),
tolerance = 1.0e-06)
}
}
}
context("backward") {
val layer = BiaffineLayerUtils.buildLayer()
layer.forward()
layer.outputArray.assignErrors(layer.outputArray.values.sub(BiaffineLayerUtils.getOutputGold()))
val paramsErrors = layer.backward(propagateToInput = true)
val params = layer.params
it("should match the expected errors of the outputArray") {
assertTrue {
layer.outputArray.errors.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.398794, 0.134815)),
tolerance = 1.0e-06)
}
}
it("should match the expected errors of the biases") {
assertTrue {
paramsErrors.getErrorsOf(params.b)!!.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.398794, 0.134815)),
tolerance = 1.0e-06)
}
}
it("should match the expected errors of w1") {
assertTrue {
(paramsErrors.getErrorsOf(params.w1)!!.values as DenseNDArray).equals(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.319035, 0.358915),
doubleArrayOf(-0.107852, -0.121333)
)),
tolerance = 1.0e-06)
}
}
it("should match the expected errors of w2") {
assertTrue {
(paramsErrors.getErrorsOf(params.w2)!!.values as DenseNDArray).equals(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.199397, 0.079759, -0.239276),
doubleArrayOf(0.067407, -0.026963, 0.080889)
)),
tolerance = 1.0e-06)
}
}
it("should match the expected errors of the first w array") {
assertTrue {
(paramsErrors.getErrorsOf(params.w[0])!!.values as DenseNDArray).equals(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.159518, 0.179457),
doubleArrayOf(-0.063807, -0.071783),
doubleArrayOf(0.191421, 0.215349)
)),
tolerance = 1.0e-06)
}
}
it("should match the expected errors of the second w array") {
assertTrue {
(paramsErrors.getErrorsOf(params.w[1])!!.values as DenseNDArray).equals(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.053926, -0.060667),
doubleArrayOf(0.021570, 0.024267),
doubleArrayOf(-0.064711, -0.072800)
)),
tolerance = 1.0e-06)
}
}
it("should match the expected errors of the inputArray1") {
assertTrue {
layer.inputArray1.errors.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.048872, -0.488442)),
tolerance = 1.0e-06)
}
}
it("should match the expected errors of the inputArray2") {
assertTrue {
layer.inputArray2.errors.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.342293, -0.086394, 0.601735)),
tolerance = 1.0e-06)
}
}
}
}
})
|
mpl-2.0
|
340e1a917f5c7895b067bc7cec5a8bbc
| 31.570313 | 102 | 0.603742 | 4.33368 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/BindingTraceForBodyResolve.kt
|
5
|
907
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.resolve
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTraceFilter
import org.jetbrains.kotlin.resolve.DelegatingBindingTrace
import org.jetbrains.kotlin.util.slicedMap.WritableSlice
class BindingTraceForBodyResolve(
parentContext: BindingContext,
debugName: String,
filter: BindingTraceFilter = BindingTraceFilter.ACCEPT_ALL
) : DelegatingBindingTrace(parentContext, debugName, filter = filter, allowSliceRewrite = true) {
override fun <K, V> getKeys(slice: WritableSlice<K, V>): Collection<K> {
if (slice == BindingContext.DEFERRED_TYPE) {
return map.getKeys(slice)
}
return super.getKeys(slice)
}
}
|
apache-2.0
|
9cd526e3935887b1ef1e41052216373f
| 42.238095 | 158 | 0.761852 | 4.319048 | false | false | false | false |
android/play-billing-samples
|
PlayBillingCodelab/start/src/main/java/com/sample/subscriptionscodelab/ui/theme/Type.kt
|
2
|
1407
|
/*
* Copyright 2022 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sample.subscriptionscodelab.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
)
|
apache-2.0
|
9f7676bc7c38a72e3b01b6ee9787f3a5
| 30.977273 | 75 | 0.711443 | 4.302752 | false | false | false | false |
ACRA/acra
|
acra-core/src/main/java/org/acra/file/Directory.kt
|
1
|
3671
|
/*
* Copyright (c) 2016
*
* 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.acra.file
import android.content.Context
import android.os.Build
import android.os.Environment
import java.io.File
/**
* @author F43nd1r
* @since 4.9.1
*/
enum class Directory {
/**
* Legacy behaviour:
* If the string starts with a path separator, this behaves like [ROOT].
* Otherwise it behaves like [FILES].
*/
FILES_LEGACY {
override fun getFile(context: Context, fileName: String): File {
return (if (fileName.startsWith("/")) ROOT else FILES).getFile(context, fileName)
}
},
/**
* Directory returned by [Context.getFilesDir]
*/
FILES {
override fun getFile(context: Context, fileName: String): File {
return File(context.filesDir, fileName)
}
},
/**
* Directory returned by [Context.getExternalFilesDir]
* Note: Additional permissions may be required.
*/
EXTERNAL_FILES {
override fun getFile(context: Context, fileName: String): File {
return File(context.getExternalFilesDir(null), fileName)
}
},
/**
* Directory returned by [Context.getCacheDir]
*/
CACHE {
override fun getFile(context: Context, fileName: String): File {
return File(context.cacheDir, fileName)
}
},
/**
* Directory returned by [Context.getExternalCacheDir]
* Note: Additional permissions may be required.
*/
EXTERNAL_CACHE {
override fun getFile(context: Context, fileName: String): File {
return File(context.externalCacheDir, fileName)
}
},
/**
* Directory returned by [Context.getNoBackupFilesDir].
* Will fall back to [Context.getFilesDir] on API < 21
*/
NO_BACKUP_FILES {
override fun getFile(context: Context, fileName: String): File {
val dir: File = if (Build.VERSION.SDK_INT >= 21) {
context.noBackupFilesDir
} else {
File(context.applicationInfo.dataDir, "no_backup")
}
return File(dir, fileName)
}
},
/**
* Directory returned by [Environment.getExternalStorageDirectory]
* Note: Additional permissions may be required.
*/
EXTERNAL_STORAGE {
override fun getFile(context: Context, fileName: String): File {
return File(Environment.getExternalStorageDirectory(), fileName)
}
},
/**
* Root Directory, paths in this directory are absolute paths
*/
ROOT {
override fun getFile(context: Context, fileName: String): File {
val parts = fileName.split(File.separator, limit = 2)
if (parts.size == 1) return File(fileName)
val roots = File.listRoots()
for (root in roots) {
if (parts[0] == root.path.replace(File.separator, "")) {
return File(root, parts[1])
}
}
return File(roots[0], fileName)
}
};
abstract fun getFile(context: Context, fileName: String): File
}
|
apache-2.0
|
7e6f24854684bd326e39c8ab381edf3a
| 29.6 | 93 | 0.61264 | 4.532099 | false | false | false | false |
jimandreas/BottomNavigationView-plus-LeakCanary
|
app/src/main/java/com/jimandreas/android/designlibdemo/CheeseListFragment.kt
|
2
|
4149
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jimandreas.android.designlibdemo
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.jimandreas.android.goodies.Cheeses
import java.util.ArrayList
import java.util.Random
class CheeseListFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rv = inflater.inflate(
R.layout.fragment_cheese_list, container, false) as RecyclerView
setupRecyclerView(rv)
return rv
}
private fun setupRecyclerView(recyclerView: RecyclerView) {
with(recyclerView) {
layoutManager = LinearLayoutManager(context)
adapter = SimpleStringRecyclerViewAdapter(this.context,
getRandomSublist(Cheeses.cheeseStrings, 30))
}
}
private fun getRandomSublist(array: Array<String>, amount: Int): List<String> {
val list = ArrayList<String>(amount)
val random = Random()
while (list.size < amount) {
list.add(array[random.nextInt(array.size)])
}
return list
}
class SimpleStringRecyclerViewAdapter(context: Context, private val mValues: List<String>) : RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder>() {
private val mTypedValue = TypedValue()
private val mBackground: Int
class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) {
lateinit var mBoundString: String
val mImageView: ImageView = mView.findViewById(R.id.avatar)
val mTextView: TextView = mView.findViewById(android.R.id.text1)
override fun toString(): String {
return super.toString() + " '" + mTextView.text
}
}
fun getValueAt(position: Int): String {
return mValues[position]
}
init {
context.theme.resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true)
mBackground = mTypedValue.resourceId
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item, parent, false)
view.setBackgroundResource(mBackground)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.mBoundString = mValues[position]
holder.mTextView.text = mValues[position]
holder.mView.setOnClickListener { v ->
val context = v.context
val intent = Intent(context, CheeseDetailActivity::class.java)
intent.putExtra(CheeseDetailActivity.EXTRA_NAME, holder.mBoundString)
context.startActivity(intent)
}
Glide.with(holder.mImageView.context)
.load(Cheeses.randomCheeseDrawable)
.fitCenter()
.into(holder.mImageView)
}
override fun getItemCount(): Int {
return mValues.size
}
}
}
|
apache-2.0
|
24ee7f1d95dc42bdd46be6fc65274397
| 34.461538 | 165 | 0.667149 | 4.818815 | false | false | false | false |
milosmns/Timecrypt
|
Android/app/src/main/java/co/timecrypt/android/pages/SwipeAdapter.kt
|
1
|
3569
|
package co.timecrypt.android.pages
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import co.timecrypt.android.activities.CreateMessageActivity
import co.timecrypt.android.helpers.OnMessageChangedEmitter
import co.timecrypt.android.helpers.OnMessageChangedListener
import co.timecrypt.android.v2.api.TimecryptMessage
import kotlin.reflect.full.primaryConstructor
/**
* The pager adapter being used in the [CreateMessageActivity]. Does caching internally but also uses the cache from [FragmentManager].
*/
class SwipeAdapter(
listener: OnMessageChangedListener,
message: TimecryptMessage,
private val manager: FragmentManager,
override var listeners: MutableList<OnMessageChangedListener> = mutableListOf()
) : FragmentPagerAdapter(manager), OnMessageChangedListener, OnMessageChangedEmitter {
companion object {
val PAGES = listOf(
TextFragment::class,
ViewsFragment::class,
DestructDateFragment::class,
DeliveryFragment::class
)
}
private val fragmentCache: MutableMap<String, TimecryptFragment> = mutableMapOf()
private var messageListener: OnMessageChangedListener?
private var _message: TimecryptMessage = TimecryptMessage("")
override var message: TimecryptMessage
get() = _message
set(value) {
_message = value
// notify only if listeners are attached (no reason to update otherwise)
if (listeners.size > 0) {
onMessageUpdated()
}
}
init {
_message = message
messageListener = listener
addMessageListener(listener)
}
/**
* Makes sure that a fragment exists at the given [position]. Uses the [fragmentCache] to store them afterwards.
* @param position Which position to look at - refer to [PAGES]
*/
private fun ensureFragment(position: Int): TimecryptFragment {
val name = PAGES[position].simpleName!!
val found = manager.findFragmentByTag(name) ?: fragmentCache[name]
if (found == null) {
val fragment = PAGES[position].primaryConstructor?.call() ?: throw IllegalStateException()
fragment.message = this.message
fragmentCache[name] = fragment
fragment.addMessageListener(this)
return fragment
}
return found as TimecryptFragment
}
override fun getItem(position: Int): TimecryptFragment {
return ensureFragment(position)
}
override fun getCount(): Int {
return PAGES.size
}
/**
* Clears the internal cache.
*/
fun cleanup() {
for ((_, fragment) in fragmentCache) {
fragment.removeMessageListener(this)
}
try {
val transaction = manager.beginTransaction()
PAGES.forEach {
val fragment = manager.findFragmentByTag(it.simpleName)
fragment?.let { transaction.remove(it) }
}
transaction.commitAllowingStateLoss()
} catch (ignored: Throwable) {
}
fragmentCache.clear()
messageListener?.let { removeMessageListener(it) }
}
/* Message emitter and listener */
override fun onTextInvalidated(empty: Boolean) {
notifyListener { it.onTextInvalidated(empty) }
}
override fun onMessageUpdated() {
for ((_, fragment) in fragmentCache) {
fragment.message = message
}
}
}
|
apache-2.0
|
8b96eb8eacf8ab4e797c2836f781cbde
| 31.454545 | 135 | 0.648641 | 5.264012 | false | false | false | false |
asedunov/intellij-community
|
platform/configuration-store-impl/src/FileBasedStorage.kt
|
1
|
10670
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.util.LineSeparator
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import com.intellij.util.io.readChars
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.loadElement
import com.intellij.util.toBufferExposingByteArray
import org.jdom.Element
import org.jdom.JDOMException
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
open class FileBasedStorage(file: Path,
fileSpec: String,
rootElementName: String?,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
roamingType: RoamingType? = null,
provider: StreamProvider? = null) : XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider) {
private @Volatile var cachedVirtualFile: VirtualFile? = null
protected var lineSeparator: LineSeparator? = null
protected var blockSavingTheContent = false
@Volatile var file = file
private set
init {
if (ApplicationManager.getApplication().isUnitTestMode && file.toString().startsWith('$')) {
throw AssertionError("It seems like some macros were not expanded for path: $file")
}
}
protected open val isUseXmlProlog: Boolean = false
// we never set io file to null
fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: Path?) {
cachedVirtualFile = virtualFile
if (ioFileIfChanged != null) {
file = ioFileIfChanged
}
}
override fun createSaveSession(states: StateMap) = FileSaveSession(states, this)
protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) : XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) {
override fun save() {
if (!storage.blockSavingTheContent) {
super.save()
}
}
override fun saveLocally(element: Element?) {
if (storage.lineSeparator == null) {
storage.lineSeparator = if (storage.isUseXmlProlog) LineSeparator.LF else LineSeparator.getSystemLineSeparator()
}
val virtualFile = storage.virtualFile
if (element == null) {
deleteFile(storage.file, this, virtualFile)
storage.cachedVirtualFile = null
}
else {
storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, element, if (storage.isUseXmlProlog) storage.lineSeparator!! else LineSeparator.LF, storage.isUseXmlProlog)
}
}
}
val virtualFile: VirtualFile?
get() {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(file.systemIndependentPath)
cachedVirtualFile = result
}
return cachedVirtualFile
}
protected inline fun <T> runAndHandleExceptions(task: () -> T): T? {
try {
return task()
}
catch (e: JDOMException) {
processReadException(e)
}
catch (e: IOException) {
processReadException(e)
}
return null
}
fun preloadStorageData(isEmpty: Boolean) {
if (isEmpty) {
storageDataRef.set(StateMap.EMPTY)
}
else {
getStorageData()
}
}
override fun loadLocalData(): Element? {
blockSavingTheContent = false
return runAndHandleExceptions { loadLocalDataUsingIo() }
}
private fun loadLocalDataUsingIo(): Element? {
val attributes: BasicFileAttributes?
try {
attributes = Files.readAttributes(file, BasicFileAttributes::class.java)
}
catch (e: NoSuchFileException) {
LOG.debug { "Document was not loaded for $fileSpec, doesn't exist" }
return null
}
if (!attributes.isRegularFile) {
LOG.debug { "Document was not loaded for $fileSpec, not a file" }
}
else if (attributes.size() == 0L) {
processReadException(null)
}
else {
val data = file.readChars()
lineSeparator = detectLineSeparators(data, if (isUseXmlProlog) null else LineSeparator.LF)
return loadElement(data)
}
return null
}
protected fun processReadException(e: Exception?) {
val contentTruncated = e == null
blockSavingTheContent = !contentTruncated && (PROJECT_FILE == fileSpec || fileSpec.startsWith(PROJECT_CONFIG_DIR) || fileSpec == StoragePathMacros.MODULE_FILE || fileSpec == StoragePathMacros.WORKSPACE_FILE)
if (!ApplicationManager.getApplication().isUnitTestMode && !ApplicationManager.getApplication().isHeadlessEnvironment) {
if (e != null) {
LOG.info(e)
}
Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID,
"Load Settings",
"Cannot load settings from file '$file': ${if (contentTruncated) "content truncated" else e!!.message}\n${if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"}",
NotificationType.WARNING)
.notify(null)
}
}
override fun toString() = file.systemIndependentPath
}
fun writeFile(file: Path?, requestor: Any, virtualFile: VirtualFile?, element: Element, lineSeparator: LineSeparator, prependXmlProlog: Boolean): VirtualFile {
val result = if (file != null && (virtualFile == null || !virtualFile.isValid)) {
getOrCreateVirtualFile(requestor, file)
}
else {
virtualFile!!
}
if ((LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) && !FileUtilRt.isTooLarge(result.length)) {
val content = element.toBufferExposingByteArray(lineSeparator.separatorString)
if (isEqualContent(result, lineSeparator, content, prependXmlProlog)) {
throw IllegalStateException("Content equals, but it must be handled not on this level: file ${result.name}, content\n${content.toByteArray().toString(StandardCharsets.UTF_8)}")
}
else if (DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) {
DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}"
}
}
doWrite(requestor, result, element, lineSeparator, prependXmlProlog)
return result
}
private val XML_PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".toByteArray()
private fun isEqualContent(result: VirtualFile, lineSeparator: LineSeparator, content: BufferExposingByteArrayOutputStream, prependXmlProlog: Boolean): Boolean {
val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size + lineSeparator.separatorBytes.size
if (result.length.toInt() != (headerLength + content.size())) {
return false
}
val oldContent = result.contentsToByteArray()
if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) || !ArrayUtil.startsWith(oldContent, XML_PROLOG.size, lineSeparator.separatorBytes))) {
return false
}
return (headerLength..oldContent.size - 1).all { oldContent[it] == content.internalBuffer[it - headerLength] }
}
private fun doWrite(requestor: Any, file: VirtualFile, content: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) {
LOG.debug { "Save ${file.presentableUrl}" }
if (!file.isWritable) {
// may be element is not long-lived, so, we must write it to byte array
val byteArray = (content as? Element)?.toBufferExposingByteArray(lineSeparator.separatorString) ?: content as BufferExposingByteArrayOutputStream
throw ReadOnlyModificationException(file, StateStorage.SaveSession { doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog) })
}
runUndoTransparentWriteAction {
file.getOutputStream(requestor).use { out ->
if (prependXmlProlog) {
out.write(XML_PROLOG)
out.write(lineSeparator.separatorBytes)
}
if (content is Element) {
JDOMUtil.write(content, out, lineSeparator.separatorString)
}
else {
(content as BufferExposingByteArrayOutputStream).writeTo(out)
}
}
}
}
internal fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator?): LineSeparator {
for (c in chars) {
if (c == '\r') {
return LineSeparator.CRLF
}
else if (c == '\n') {
// if we are here, there was no \r before
return LineSeparator.LF
}
}
return defaultSeparator ?: LineSeparator.getSystemLineSeparator()
}
private fun deleteFile(file: Path, requestor: Any, virtualFile: VirtualFile?) {
if (virtualFile == null) {
LOG.warn("Cannot find virtual file $file")
}
if (virtualFile == null) {
if (file.exists()) {
file.delete()
}
}
else if (virtualFile.exists()) {
if (virtualFile.isWritable) {
deleteFile(requestor, virtualFile)
}
else {
throw ReadOnlyModificationException(virtualFile, StateStorage.SaveSession { deleteFile(requestor, virtualFile) })
}
}
}
internal fun deleteFile(requestor: Any, virtualFile: VirtualFile) {
runUndoTransparentWriteAction { virtualFile.delete(requestor) }
}
internal class ReadOnlyModificationException(val file: VirtualFile, val session: StateStorage.SaveSession?) : RuntimeException("File is read-only: "+file)
|
apache-2.0
|
1ea0bee668eb4fdda61abf56b331d746
| 36.442105 | 215 | 0.720431 | 4.791199 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadHeaderHolder.kt
|
2
|
1234
|
package eu.kanade.tachiyomi.ui.download
import android.annotation.SuppressLint
import android.view.View
import androidx.recyclerview.widget.ItemTouchHelper
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.viewholders.ExpandableViewHolder
import eu.kanade.tachiyomi.databinding.DownloadHeaderBinding
class DownloadHeaderHolder(view: View, adapter: FlexibleAdapter<*>) : ExpandableViewHolder(view, adapter) {
private val binding = DownloadHeaderBinding.bind(view)
@SuppressLint("SetTextI18n")
fun bind(item: DownloadHeaderItem) {
setDragHandleView(binding.reorder)
binding.title.text = "${item.name} (${item.size})"
}
override fun onActionStateChanged(position: Int, actionState: Int) {
super.onActionStateChanged(position, actionState)
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
binding.container.isDragged = true
mAdapter.collapseAll()
}
}
override fun onItemReleased(position: Int) {
super.onItemReleased(position)
binding.container.isDragged = false
mAdapter as DownloadAdapter
mAdapter.expandAll()
mAdapter.downloadItemListener.onItemReleased(position)
}
}
|
apache-2.0
|
13f8599896521e28c8cb3183bfbdf03b
| 34.257143 | 107 | 0.734198 | 4.801556 | false | false | false | false |
ClearVolume/scenery
|
src/test/kotlin/graphics/scenery/tests/examples/advanced/DFTMDExample.kt
|
2
|
2245
|
package graphics.scenery.tests.examples.advanced
import org.joml.Vector3f
import graphics.scenery.*
import graphics.scenery.atomicsimulations.AtomicSimulation
import graphics.scenery.backends.Renderer
import kotlin.concurrent.thread
/**
* Visualizes a DFT-MD trajectory with volumetric data (electronic density).
*
* @author Lenz Fiedler <[email protected]>
*/
class DFTMDExample : SceneryBase("DFTMDExample") {
override fun init() {
renderer = hub.add(SceneryElement.Renderer,
Renderer.createRenderer(hub, applicationName, scene, 512, 512))
// Create an object for the DFT (-MD) simulation.
val atomicSimulation = AtomicSimulation.fromCube("Fe_snapshot0_dens.cube",
hub,0.5f, 0.5f, rootFolder = getDemoFilesPath() + "/dft_data/")
scene.addChild(atomicSimulation)
// One light in every corner.
val lights = (0 until 8).map {
PointLight(radius = 15.0f)
}
lights.mapIndexed { i, light ->
val permutation = String.format("%3s", Integer.toBinaryString(i)).replace(' ', '0')
light.spatial().position = Vector3f(atomicSimulation.simulationData.unitCellDimensions[0] *
(permutation[0].code-48),
atomicSimulation.simulationData.unitCellDimensions[1] * (permutation[1].code-48),
atomicSimulation.simulationData.unitCellDimensions[2] * (permutation[2].code-48))
scene.addChild(light)
}
val cam: Camera = DetachedHeadCamera()
with(cam) {
spatial {
position = Vector3f(0.0f, 0.0f, 5.0f)
}
perspectiveCamera(50.0f, 512, 512)
scene.addChild(this)
}
var currentSnapshot = 0
val maxSnapshot = 10
var count = 0
thread {
while (running) {
atomicSimulation.updateFromCube("Fe_snapshot${currentSnapshot}_dens.cube")
Thread.sleep(500)
currentSnapshot = (currentSnapshot + 1) % maxSnapshot
count++
}
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
DFTMDExample().main()
}
}
}
|
lgpl-3.0
|
48c5807bc2a574698907981ad5783b5c
| 33.015152 | 103 | 0.603118 | 4.227872 | false | false | false | false |
ogarcia/ultrasonic
|
core/subsonic-api/src/integrationTest/kotlin/org/moire/ultrasonic/api/subsonic/SubsonicApiScrobbleTest.kt
|
2
|
1617
|
package org.moire.ultrasonic.api.subsonic
import java.util.Calendar
import org.junit.Test
/**
* Integration test for [SubsonicAPIClient] for scrobble call.
*/
class SubsonicApiScrobbleTest : SubsonicAPIClientTest() {
@Test
fun `Should handle error response`() {
checkErrorCallParsed(mockWebServerRule) {
client.api.scrobble("id").execute()
}
}
@Test
fun `Should handle ok response`() {
mockWebServerRule.enqueueResponse("ping_ok.json")
val response = client.api.scrobble("id").execute()
assertResponseSuccessful(response)
}
@Test
fun `Should pass id param in request`() {
val id = "some-id"
mockWebServerRule.assertRequestParam(
responseResourceName = "ping_ok.json",
expectedParam = "id=$id"
) {
client.api.scrobble(id = id).execute()
}
}
@Test
fun `Should pass time param in request`() {
val time = Calendar.getInstance().timeInMillis
mockWebServerRule.assertRequestParam(
responseResourceName = "ping_ok.json",
expectedParam = "time=$time"
) {
client.api.scrobble(id = "some-id", time = time).execute()
}
}
@Test
fun `Should pass submission param in request`() {
val submission = false
mockWebServerRule.assertRequestParam(
responseResourceName = "ping_ok.json",
expectedParam = "submission=$submission"
) {
client.api.scrobble(id = "some-id", submission = submission).execute()
}
}
}
|
gpl-3.0
|
d6298e119c0da02ca62f5f21edd40a6c
| 25.508197 | 82 | 0.601113 | 4.714286 | false | true | false | false |
JiaweiWu/GiphyApp
|
app/src/main/java/com/jwu5/giphyapp/network/model/GiphyModel.kt
|
1
|
560
|
package com.jwu5.giphyapp.network.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import java.io.Serializable
/**
* Created by Jiawei on 8/17/2017.
*/
class GiphyModel {
@SerializedName("type")
@Expose
var type: String? = null
@SerializedName("id")
@Expose
var id: String? = null
@SerializedName("url")
@Expose
var url: String? = null
get() = PREVIEW_URL + id + "/200w.gif"
companion object {
val PREVIEW_URL = "https://i.giphy.com/media/"
}
}
|
mit
|
766f89584954961b19ef96b4b660fd79
| 20.538462 | 54 | 0.648214 | 3.522013 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/platform-api/src/com/intellij/ui/tabs/impl/SingleHeightTabs.kt
|
13
|
1208
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.tabs.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.tabs.TabInfo
import com.intellij.util.ui.JBUI
import java.awt.Dimension
open class SingleHeightTabs(project: Project?, focusManager: IdeFocusManager?, parent: Disposable) : JBEditorTabs(project, focusManager, parent) {
companion object {
const val UNSCALED_PREF_HEIGHT = 28
}
constructor(project: Project?, parent: Disposable) : this(project, if (project == null) null else IdeFocusManager.getInstance(project), parent)
override fun createTabLabel(info: TabInfo): TabLabel = SingleHeightLabel(this, info)
open inner class SingleHeightLabel(tabs: JBTabsImpl, info: TabInfo) : TabLabel(tabs, info) {
override fun getPreferredSize(): Dimension {
val size = super.getPreferredSize()
return Dimension(size.width, getPreferredHeight())
}
protected open fun getPreferredHeight(): Int {
return JBUI.scale(UNSCALED_PREF_HEIGHT)
}
}
}
|
apache-2.0
|
b44ef3b70d03b69125482afe7cee1e51
| 39.3 | 146 | 0.760762 | 4.223776 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/LibraryInfo.kt
|
1
|
5375
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.serviceContainer.AlreadyDisposedException
import com.intellij.util.PathUtil
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.idea.base.projectStructure.*
import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices
import org.jetbrains.kotlin.idea.base.projectStructure.libraryToSourceAnalysis.ResolutionAnchorCacheService
import org.jetbrains.kotlin.idea.base.projectStructure.libraryToSourceAnalysis.useLibraryToSourceAnalysis
import org.jetbrains.kotlin.idea.base.projectStructure.scope.PoweredLibraryScopeBase
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.*
import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices
abstract class LibraryInfo(
override val project: Project,
val library: Library
) : IdeaModuleInfo, LibraryModuleInfo, BinaryModuleInfo, TrackableModuleInfo {
private val libraryWrapper = LibraryWrapper(library as LibraryEx)
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.LIBRARY
override val name: Name = Name.special("<library ${library.name}>")
override val displayedName: String
get() = KotlinBaseProjectStructureBundle.message("library.0", library.name.toString())
override val contentScope: GlobalSearchScope
get() = LibraryWithoutSourceScope(project, library)
override fun dependencies(): List<IdeaModuleInfo> {
val dependencies = LibraryDependenciesCache.getInstance(project).getLibraryDependencies(this)
return LinkedHashSet<IdeaModuleInfo>(dependencies.libraries.size + dependencies.sdk.size + 1).apply {
add(this@LibraryInfo)
addAll(dependencies.sdk)
addAll(dependencies.libraries)
}.toList()
}
abstract override val platform: TargetPlatform // must override
override val analyzerServices: PlatformDependentAnalyzerServices
get() = platform.findAnalyzerServices(project)
private val _sourcesModuleInfo: SourceForBinaryModuleInfo by lazy { LibrarySourceInfo(project, library, this) }
override val sourcesModuleInfo: SourceForBinaryModuleInfo
get() = _sourcesModuleInfo
override fun getLibraryRoots(): Collection<String> =
library.getFiles(OrderRootType.CLASSES).mapNotNull(PathUtil::getLocalPath)
override fun createModificationTracker(): ModificationTracker =
if (!project.useLibraryToSourceAnalysis) {
ModificationTracker.NEVER_CHANGED
} else {
ResolutionAnchorAwareLibraryModificationTracker(this)
}
internal val isDisposed
get() = if (library is LibraryEx) library.isDisposed else false
override fun checkValidity() {
if (isDisposed) {
throw AlreadyDisposedException("Library '${name}' is already disposed")
}
}
override fun toString() =
"${this::class.simpleName}(libraryName=${library.name}${if (isDisposed) ", libraryRoots=${getLibraryRoots()})" else ""}"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is LibraryInfo) return false
return libraryWrapper == other.libraryWrapper
}
override fun hashCode() = libraryWrapper.hashCode()
}
private class ResolutionAnchorAwareLibraryModificationTracker(libraryInfo: LibraryInfo) : ModificationTracker {
private val dependencyModules: List<Module> = if (!libraryInfo.isDisposed) {
ResolutionAnchorCacheService.getInstance(libraryInfo.project)
.getDependencyResolutionAnchors(libraryInfo)
.map { it.module }
} else {
emptyList()
}
override fun getModificationCount(): Long {
if (dependencyModules.isEmpty()) {
return ModificationTracker.NEVER_CHANGED.modificationCount
}
val project = dependencyModules.first().project
val modificationTrackerProvider = KotlinModificationTrackerProvider.getInstance(project)
return dependencyModules
.maxOfOrNull(modificationTrackerProvider::getModuleSelfModificationCount)
?: ModificationTracker.NEVER_CHANGED.modificationCount
}
}
@Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide calcHashCode()
private class LibraryWithoutSourceScope(
project: Project,
private val library: Library
) : PoweredLibraryScopeBase(project, library.getFiles(OrderRootType.CLASSES), arrayOf()) {
override fun getFileRoot(file: VirtualFile): VirtualFile? = myIndex.getClassRootForFile(file)
override fun equals(other: Any?) = other is LibraryWithoutSourceScope && library == other.library
override fun calcHashCode(): Int = library.hashCode()
override fun toString() = "LibraryWithoutSourceScope($library)"
}
|
apache-2.0
|
c27ffecc5546d6bd37b25e02c29e400d
| 41 | 128 | 0.754419 | 5.183221 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ui/KotlinExtractInterfaceDialog.kt
|
6
|
5712
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce.extractClass.ui
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.refactoring.HelpID
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.classMembers.MemberInfoModel
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.idea.refactoring.introduce.extractClass.ExtractSuperInfo
import org.jetbrains.kotlin.idea.refactoring.introduce.extractClass.KotlinExtractInterfaceHandler
import org.jetbrains.kotlin.idea.refactoring.isConstructorDeclaredProperty
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.extractClassMembers
import org.jetbrains.kotlin.idea.refactoring.memberInfo.lightElementForMemberInfo
import org.jetbrains.kotlin.idea.refactoring.pullUp.getInterfaceContainmentVerifier
import org.jetbrains.kotlin.idea.refactoring.pullUp.isAbstractInInterface
import org.jetbrains.kotlin.idea.refactoring.pullUp.mustBeAbstractInInterface
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
class KotlinExtractInterfaceDialog(
originalClass: KtClassOrObject,
targetParent: PsiElement,
conflictChecker: (KotlinExtractSuperDialogBase) -> Boolean,
refactoring: (ExtractSuperInfo) -> Unit
) : KotlinExtractSuperDialogBase(
originalClass,
targetParent,
conflictChecker,
true,
KotlinExtractInterfaceHandler.REFACTORING_NAME,
refactoring
) {
companion object {
private const val DESTINATION_PACKAGE_RECENT_KEY = "KotlinExtractInterfaceDialog.RECENT_KEYS"
}
init {
init()
}
override fun createMemberInfoModel(): MemberInfoModelBase {
val extractableMemberInfos = extractClassMembers(originalClass).filterNot {
val member = it.member
member is KtClass && member.hasModifier(KtTokens.INNER_KEYWORD) ||
member is KtParameter && member.hasModifier(KtTokens.PRIVATE_KEYWORD)
}
extractableMemberInfos.forEach { it.isToAbstract = true }
return object : MemberInfoModelBase(
originalClass,
extractableMemberInfos,
getInterfaceContainmentVerifier { selectedMembers }
) {
override fun isMemberEnabled(member: KotlinMemberInfo): Boolean {
if (!super.isMemberEnabled(member)) return false
val declaration = member.member
return !(declaration.hasModifier(KtTokens.INLINE_KEYWORD) ||
declaration.hasModifier(KtTokens.EXTERNAL_KEYWORD) ||
declaration.hasModifier(KtTokens.LATEINIT_KEYWORD))
}
override fun isAbstractEnabled(memberInfo: KotlinMemberInfo): Boolean {
if (!super.isAbstractEnabled(memberInfo)) return false
val member = memberInfo.member
if (member.isAbstractInInterface(originalClass)) return false
if (member.isConstructorDeclaredProperty()) return false
return member is KtNamedFunction || (member is KtProperty && !member.mustBeAbstractInInterface()) || member is KtParameter
}
override fun isAbstractWhenDisabled(memberInfo: KotlinMemberInfo): Boolean {
val member = memberInfo.member
return member is KtProperty || member.isAbstractInInterface(originalClass) || member.isConstructorDeclaredProperty()
}
override fun checkForProblems(memberInfo: KotlinMemberInfo): Int {
val result = super.checkForProblems(memberInfo)
if (result != MemberInfoModel.OK) return result
if (!memberInfo.isSuperClass || memberInfo.overrides != false || memberInfo.isChecked) return result
val psiSuperInterface = lightElementForMemberInfo(memberInfo.member) as? PsiClass ?: return result
for (info in memberInfos) {
if (!info.isChecked || info.isToAbstract) continue
val member = info.member ?: continue
val psiMethodToCheck = lightElementForMemberInfo(member) as? PsiMethod ?: continue
if (psiSuperInterface.findMethodBySignature(psiMethodToCheck, true) != null) return MemberInfoModel.ERROR
}
return result
}
}
}
override fun getDestinationPackageRecentKey() = DESTINATION_PACKAGE_RECENT_KEY
override fun getClassNameLabelText() = RefactoringBundle.message("interface.name.prompt")!!
override fun getPackageNameLabelText() = RefactoringBundle.message("package.for.new.interface")!!
override fun getEntityName() = RefactoringBundle.message("extractSuperInterface.interface")!!
override fun getTopLabelText() = RefactoringBundle.message("extract.interface.from")!!
override fun getDocCommentPolicySetting() = KotlinRefactoringSettings.instance.EXTRACT_INTERFACE_JAVADOC
override fun setDocCommentPolicySetting(policy: Int) {
KotlinRefactoringSettings.instance.EXTRACT_INTERFACE_JAVADOC = policy
}
override fun getExtractedSuperNameNotSpecifiedMessage() = RefactoringBundle.message("no.interface.name.specified")!!
override fun getHelpId() = HelpID.EXTRACT_INTERFACE
override fun createExtractedSuperNameField() = super.createExtractedSuperNameField().apply { text = "I${originalClass.name}" }
}
|
apache-2.0
|
35c2972fb2184eea793509d7821a0eee
| 46.608333 | 158 | 0.722689 | 5.55642 | false | false | false | false |
android/location-samples
|
LocationAddress/app/src/main/java/com/google/android/gms/location/sample/locationaddress/MainViewModel.kt
|
1
|
3092
|
/*
* Copyright (C) 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.location.sample.locationaddress
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.gms.location.sample.locationaddress.UiState.Initializing
import com.google.android.gms.location.sample.locationaddress.UiState.PlayServicesAvailable
import com.google.android.gms.location.sample.locationaddress.UiState.PlayServicesUnavailable
import com.google.android.gms.location.sample.locationaddress.data.FormattedAddress
import com.google.android.gms.location.sample.locationaddress.data.GeocodingApi
import com.google.android.gms.location.sample.locationaddress.data.LocationApi
import com.google.android.gms.location.sample.locationaddress.data.PlayServicesAvailabilityChecker
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(
availabilityChecker: PlayServicesAvailabilityChecker,
private val locationApi: LocationApi,
private val geocodingApi: GeocodingApi
) : ViewModel() {
val uiState = flow {
emit(
if (availabilityChecker.isGooglePlayServicesAvailable()) {
PlayServicesAvailable
} else {
PlayServicesUnavailable
}
)
}.stateIn(viewModelScope, SharingStarted.Eagerly, Initializing)
var addressList by mutableStateOf(emptyList<FormattedAddress>())
private set
var showProgress by mutableStateOf(false)
private set
val maxResultsRange = 1..7
var maxResults by mutableStateOf(1)
private set
fun updateMaxResults(max: Int) {
maxResults = max.coerceIn(maxResultsRange)
}
fun getCurrentAddress() {
viewModelScope.launch {
showProgress = true
val location = locationApi.getCurrentLocation()
val addresses = if (location != null) {
geocodingApi.getFromLocation(location, maxResults)
} else {
emptyList()
}
addressList = addresses
showProgress = false
}
}
}
enum class UiState {
Initializing, PlayServicesUnavailable, PlayServicesAvailable
}
|
apache-2.0
|
ed7a8ebb6a90c65c425493065b06b3e4
| 34.953488 | 98 | 0.739327 | 4.892405 | false | false | false | false |
DreierF/MyTargets
|
app/src/main/java/de/dreier/mytargets/utils/multiselector/SingleSelector.kt
|
1
|
1735
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.utils.multiselector
import android.os.Bundle
/**
*
* A Selector that only allows for one position at a time to be selected.
*
* Any time [SelectorBase.setSelected] is called, all other selected positions are set to false.
*/
class SingleSelector : SelectorBase() {
private var selectedId = -1L
override fun setSelected(id: Long, isSelected: Boolean) {
val oldId = selectedId
selectedId = if (isSelected) {
id
} else {
-1
}
refreshHolder(tracker.getHolder(oldId))
refreshHolder(tracker.getHolder(selectedId))
}
public override fun isSelected(id: Long): Boolean {
return id == selectedId && selectedId != -1L
}
override fun saveSelectionStates(bundle: Bundle) {
bundle.putLong(SELECTION_ID, selectedId)
}
override fun restoreSelectionStates(savedStates: Bundle) {
super.restoreSelectionStates(savedStates)
selectedId = savedStates.getLong(SELECTION_ID)
}
fun getSelectedId(): Long? {
return if (selectedId == -1L) null else selectedId
}
companion object {
private const val SELECTION_ID = "selection_id"
}
}
|
gpl-2.0
|
c27a471ffa4ae2264499d5227fbfdc40
| 27.916667 | 96 | 0.680115 | 4.403553 | false | false | false | false |
nibarius/opera-park-android
|
app/src/main/java/se/barsk/park/mainui/ParkedCarListEntry.kt
|
1
|
1796
|
package se.barsk.park.mainui
import android.content.Context
import android.text.SpannableString
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import se.barsk.park.R
import se.barsk.park.datatypes.Car
import se.barsk.park.datatypes.ParkedCar
import se.barsk.park.utils.Utils.fixRegnoForDisplay
/**
* One entry in the list of parked cars
*/
class ParkedCarListEntry(context: Context?) : RelativeLayout(context), CarListEntry {
private val parkTextView: TextView by lazy { findViewById<TextView>(R.id.parked_entry_text) }
private val avatarTextView: TextView by lazy { findViewById<TextView>(R.id.avatar_text_view) }
init {
LayoutInflater.from(context).inflate(R.layout.parked_car_entry, this, true)
}
override fun showItem(car: Car, selected: Boolean, garageFull: Boolean) {
car as ParkedCar
val firstLine = "${fixRegnoForDisplay(car.regNo)} - ${car.owner}"
val secondLine = if (car.startTime.length >= 19) {
car.startTime.substring(11, 19) // Skip the date part
} else {
car.startTime
}
val spannable = SpannableString("$firstLine\n$secondLine")
spannable.setSpan(AbsoluteSizeSpan(resources.getDimensionPixelSize(R.dimen.parked_cars_text_size)), 0, firstLine.length, 0)
spannable.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.highEmphasisText)), 0, firstLine.length, 0)
parkTextView.text = spannable
setAvatarColor(car, context, avatarTextView)
avatarTextView.text = if (car.regNo.isNotEmpty()) car.regNo.substring(0, 1) else "?"
}
}
|
mit
|
ade99f2164f628b99a663dc02c8fea83
| 38.933333 | 131 | 0.732183 | 4.026906 | false | false | false | false |
apache/isis
|
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/FR_OBJECT.kt
|
2
|
11373
|
/*
* 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.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
object FR_OBJECT : Response() {
override val url = "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4="
override val str = """{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "domain-app-demo/persist-all/item-5:"
},
{
"rel": "describedby",
"href": "http://localhost:8080/restful/domain-types/causewayApplib.FixtureResult",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/domain-type\""
},
{
"rel": "urn:org.apache.causeway.restfulobjects:rels/object-layout",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=/object-layout",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "domain-app-demo/persist-all/item-5:"
},
{
"rel": "urn:org.restfulobjects:rels/update",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=",
"method": "PUT",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"arguments": {}
}
],
"extensions": {
"oid": "*causewayApplib.FixtureResult:PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=",
"isService": false,
"isPersistent": true
},
"title": "domain-app-demo/persist-all/item-5:",
"domainType": "causewayApplib.FixtureResult",
"instanceId": "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=",
"members": {
"fixtureScriptClassName": {
"id": "fixtureScriptClassName",
"memberType": "property",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsproperty=\"fixtureScriptClassName\"",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=/properties/fixtureScriptClassName",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\""
}
],
"value": null,
"extensions": {
"x-causeway-format": "string"
},
"disabledReason": "Immutable Non-cloneable view models are read-only"
},
"key": {
"id": "key",
"memberType": "property",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsproperty=\"key\"",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=/properties/key",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\""
}
],
"value": "domain-app-demo/persist-all/item-5",
"extensions": {
"x-causeway-format": "string"
},
"disabledReason": "Non-cloneable view models are read-only Immutable"
},
"object": {
"id": "object",
"memberType": "property",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsproperty=\"object\"",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=/properties/object",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\""
}
],
"value": null,
"disabledReason": "Non-cloneable view models are read-only Immutable"
},
"className": {
"id": "className",
"memberType": "property",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsproperty=\"className\"",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=/properties/className",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\""
}
],
"value": null,
"extensions": {
"x-causeway-format": "string"
},
"disabledReason": "Non-cloneable view models are read-only Immutable"
},
"rebuildMetamodel": {
"id": "rebuildMetamodel",
"memberType": "action",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsaction=\"rebuildMetamodel\"",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=/actions/rebuildMetamodel",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\""
}
]
},
"openRestApi": {
"id": "openRestApi",
"memberType": "action",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsaction=\"openRestApi\"",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=/actions/openRestApi",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\""
}
]
},
"downloadLayoutXml": {
"id": "downloadLayoutXml",
"memberType": "action",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsaction=\"downloadLayoutXml\"",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=/actions/downloadLayoutXml",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\""
}
]
},
"clearHints": {
"id": "clearHints",
"memberType": "action",
"links": [
{
"rel": "urn:org.restfulobjects:rels/detailsaction=\"clearHints\"",
"href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS01PC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjExNDwvb2JqZWN0LmJvb2ttYXJrPjwvbWVtZW50bz4=/actions/clearHints",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\""
}
]
}
}
}"""
}
|
apache-2.0
|
46f55ebf591c9f8f5f1a2de47f3de1b3
| 62.536313 | 352 | 0.628858 | 4.527468 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/common/InferenceFacade.kt
|
1
|
2700
|
// 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.j2k.post.processing.inference.common
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.idea.j2k.post.processing.runUndoTransparentActionInEdt
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtPsiFactory
class InferenceFacade(
private val typeVariablesCollector: ContextCollector,
private val constraintsCollectorAggregator: ConstraintsCollectorAggregator,
private val boundTypeCalculator: BoundTypeCalculator,
private val stateUpdater: StateUpdater,
private val defaultStateProvider: DefaultStateProvider,
private val renderDebugTypes: Boolean = false,
private val printDebugConstraints: Boolean = false
) {
fun runOn(elements: List<KtElement>) {
val inferenceContext = runReadAction { typeVariablesCollector.collectTypeVariables(elements) }
val constraints = runReadAction {
constraintsCollectorAggregator.collectConstraints(boundTypeCalculator, inferenceContext, elements)
}
val initialConstraints = if (renderDebugTypes) constraints.map { it.copy() } else null
runReadAction {
Solver(inferenceContext, printDebugConstraints, defaultStateProvider).solveConstraints(constraints)
}
if (renderDebugTypes) {
with(DebugPrinter(inferenceContext)) {
runUndoTransparentActionInEdt(inWriteAction = true) {
for ((expression, boundType) in boundTypeCalculator.expressionsWithBoundType()) {
val comment = KtPsiFactory(expression.project).createComment("/*${boundType.asString()}*/")
expression.parent.addAfter(comment, expression)
}
for (element in elements) {
element.addTypeVariablesNames()
}
for (element in elements) {
val psiFactory = KtPsiFactory(element.project)
element.add(psiFactory.createNewLine(lineBreaks = 2))
for (constraint in initialConstraints!!) {
element.add(psiFactory.createComment("//${constraint.asString()}"))
element.add(psiFactory.createNewLine(lineBreaks = 1))
}
}
}
}
}
runUndoTransparentActionInEdt(inWriteAction = true) {
stateUpdater.updateStates(inferenceContext)
}
}
}
|
apache-2.0
|
ccfbb25e37a3cccffbc85c0fe9fea7dc
| 48.109091 | 158 | 0.655185 | 5.806452 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.